Help us shape the future of Go! Take the 2026 Go Developer Survey

esapi

package
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package esapi implements Elasticsearch administration over CA-pinned HTTPS. Requests use endpoints in order. Only connection-establishment failures permit failover; mutations with an uncertain outcome are never replayed.

Index

Constants

This section is empty.

Variables

View Source
var ErrRestoreFailed = errors.New("snapshot restore failed")

ErrRestoreFailed identifies an explicit unsuccessful native completion.

Functions

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err represents HTTP 409.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err represents HTTP 404.

Types

type APIKey

type APIKey struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	APIKey     string `json:"api_key"`
	Encoded    string `json:"encoded"`
	Expiration int64  `json:"expiration"`
}

APIKey contains the key's one-time secret and expiration in Unix milliseconds.

type APIKeyInfo

type APIKeyInfo struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Creation    int64          `json:"creation"`
	Expiration  int64          `json:"expiration"`
	Invalidated bool           `json:"invalidated"`
	Username    string         `json:"username"`
	Realm       string         `json:"realm"`
	Metadata    map[string]any `json:"metadata"`
}

APIKeyInfo is non-secret API-key inventory, with timestamps in Unix milliseconds.

type APIKeyRequest

type APIKeyRequest struct {
	Name            string          `json:"name"`
	Expiration      string          `json:"expiration,omitempty"`
	RoleDescriptors map[string]Role `json:"role_descriptors"`
	Metadata        map[string]any  `json:"metadata,omitempty"`
}

APIKeyRequest specifies a new API key with explicit scoped permissions.

type ApplicationPrivileges

type ApplicationPrivileges struct {
	Application string   `json:"application"`
	Privileges  []string `json:"privileges"`
	Resources   []string `json:"resources"`
}

ApplicationPrivileges grants application-defined privileges.

type Authentication

type Authentication struct {
	Username           string `json:"username"`
	AuthenticationType string `json:"authentication_type"`
}

Authentication identifies the current credential's principal and mechanism.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is safe for concurrent use. Authentication and trust are immutable.

func New

func New(cfg Config) (*Client, error)

New constructs a client trusting only CAPEM, with hostname verification enabled.

func (*Client) AddVotingExclusion

func (c *Client) AddVotingExclusion(ctx context.Context, nodeNames []string, timeout time.Duration) error

AddVotingExclusion excludes named master-eligible nodes and waits for voting reconfiguration.

func (*Client) AllocationExcludeNames

func (c *Client) AllocationExcludeNames(ctx context.Context) ([]string, error)

AllocationExcludeNames merges both explicit layers so migration preserves operator exclusions hidden by a transient override.

func (*Client) AnalyzeRepository

func (c *Client) AnalyzeRepository(ctx context.Context, name string, params map[string]string) (map[string]any, error)

AnalyzeRepository runs a repository analysis with caller-selected query parameters.

func (*Client) Authenticate

func (c *Client) Authenticate(ctx context.Context) (Authentication, error)

Authenticate validates the configured basic or bearer credential.

func (*Client) ChangePassword

func (c *Client) ChangePassword(ctx context.Context, user, password string) error

ChangePassword changes a native or built-in user's password.

func (*Client) ClearVotingExclusions

func (c *Client) ClearVotingExclusions(ctx context.Context, waitForRemoval bool) error

ClearVotingExclusions clears exclusions, optionally waiting for excluded nodes to leave.

func (*Client) Close

func (c *Client) Close()

Close releases idle transport connections; it does not interrupt requests.

func (*Client) CloseIndices

func (c *Client) CloseIndices(ctx context.Context, names []string) error

CloseIndices closes explicit indices in bounded-length URL batches.

func (*Client) ClusterSettings

func (c *Client) ClusterSettings(ctx context.Context) (ClusterSettings, error)

ClusterSettings retrieves settings without implicit defaults.

func (*Client) CommittedVoters

func (c *Client) CommittedVoters(ctx context.Context) ([]string, error)

CommittedVoters returns node IDs in the last committed voting configuration.

func (*Client) Count

func (c *Client) Count(ctx context.Context, index string) (int64, error)

Count returns the number of documents in selected indices.

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, req APIKeyRequest) (APIKey, error)

CreateAPIKey creates a key, returning its secret only in this response.

func (*Client) CreateServiceToken

func (c *Client) CreateServiceToken(ctx context.Context, namespace, service, name string) (string, error)

CreateServiceToken creates a cluster-wide service account bearer token.

func (*Client) CreateSnapshot

func (c *Client) CreateSnapshot(ctx context.Context, repo, name string, req SnapshotRequest, wait bool) error

CreateSnapshot starts a snapshot, optionally waiting for its completion.

func (*Client) DeleteDataStreams

func (c *Client) DeleteDataStreams(ctx context.Context, pattern string) error

DeleteDataStreams deletes matching streams, including hidden streams.

func (*Client) DeleteIndices

func (c *Client) DeleteIndices(ctx context.Context, names []string) error

DeleteIndices deletes explicit indices in bounded-length URL batches. Empty input is a no-op, never an implicit delete-all request.

func (*Client) DeleteRepository

func (c *Client) DeleteRepository(ctx context.Context, name string) error

DeleteRepository unregisters a repository without deleting its snapshots.

func (*Client) DeleteRole

func (c *Client) DeleteRole(ctx context.Context, name string) error

DeleteRole deletes a native role.

func (*Client) DeleteServiceToken

func (c *Client) DeleteServiceToken(ctx context.Context, namespace, service, name string) error

DeleteServiceToken deletes an API-created service account token.

func (*Client) DeleteSnapshot

func (c *Client) DeleteSnapshot(ctx context.Context, repo, name string) error

DeleteSnapshot deletes snapshot contents from a writable repository.

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, name string) error

DeleteUser deletes a native user.

func (*Client) ExplainDrain

func (c *Client) ExplainDrain(ctx context.Context, node string) (DrainAllocation, error)

ExplainDrain diagnoses one deterministic started shard on the draining node.

func (*Client) Flush

func (c *Client) Flush(ctx context.Context) error

Flush flushes indices, returning conflicts for the caller to handle.

func (*Client) GetAPIKeys

func (c *Client) GetAPIKeys(ctx context.Context, owner bool, name string) ([]APIKeyInfo, error)

GetAPIKeys lists keys, optionally restricting to the owner and a name pattern.

func (*Client) GetRepository

func (c *Client) GetRepository(ctx context.Context, name string) (Repository, error)

GetRepository retrieves a repository definition.

func (*Client) GetRoles

func (c *Client) GetRoles(ctx context.Context, names ...string) (map[string]Role, error)

GetRoles returns named roles, or all roles when names is empty.

func (*Client) GetSnapshot

func (c *Client) GetSnapshot(ctx context.Context, repo, name string) (SnapshotInfo, error)

GetSnapshot retrieves one snapshot, including in-progress snapshots.

func (*Client) GetUsers

func (c *Client) GetUsers(ctx context.Context, names ...string) (map[string]User, error)

GetUsers returns named native and built-in users, or all users when names is empty.

func (*Client) Health

func (c *Client) Health(ctx context.Context, o HealthOptions) (Health, error)

Health retrieves shard health, optionally waiting for a minimum status.

func (*Client) Index

func (c *Client) Index(ctx context.Context, index, id string, doc any, refresh bool) error

Index writes a document by ID, optionally refreshing search visibility.

func (*Client) IndexWriteBlocks added in v0.2.0

func (c *Client) IndexWriteBlocks(ctx context.Context) ([]string, error)

IndexWriteBlocks observes native index write restrictions, including hidden system indices. It never removes a disk-pressure or operator-owned block.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (Info, error)

Info retrieves cluster identity.

func (*Client) InvalidateAPIKeys

func (c *Client) InvalidateAPIKeys(ctx context.Context, ids []string) error

InvalidateAPIKeys revokes the supplied key IDs and reports per-key failures.

func (*Client) ListIndices

func (c *Client) ListIndices(ctx context.Context, expandHidden bool) ([]string, error)

ListIndices lists concrete index names, optionally including hidden indices.

func (*Client) ListSnapshots

func (c *Client) ListSnapshots(ctx context.Context, repo string) ([]SnapshotInfo, error)

ListSnapshots retrieves all snapshots in a repository.

func (*Client) LocalNodes added in v0.2.0

func (c *Client) LocalNodes(ctx context.Context) ([]Node, error)

LocalNodes observes only this endpoint, so an unresponsive peer cannot hold up the node's own identity and version evidence.

func (*Client) MasterNode

func (c *Client) MasterNode(ctx context.Context) (string, error)

MasterNode returns the elected master's node name, or empty when none is elected.

func (*Client) MaxIndexReplicas

func (c *Client) MaxIndexReplicas(ctx context.Context, dataNodes int) (int, error)

MaxIndexReplicas returns the largest replica requirement for the projected data-node count after removal, including auto-expand bounds.

func (*Client) Nodes

func (c *Client) Nodes(ctx context.Context) ([]Node, error)

Nodes returns nodes ordered by name and ID.

func (*Client) PutClusterSettings

func (c *Client) PutClusterSettings(ctx context.Context, persistent, transient map[string]any) error

PutClusterSettings updates explicit settings; nil values reset a setting.

func (*Client) PutRepository

func (c *Client) PutRepository(ctx context.Context, name string, repo Repository, verify bool) error

PutRepository registers or updates a repository, optionally verifying access.

func (*Client) PutRole

func (c *Client) PutRole(ctx context.Context, name string, role Role) error

PutRole creates or updates a native role.

func (*Client) PutUser

func (c *Client) PutUser(ctx context.Context, name string, user User) error

PutUser creates or updates a native user.

func (*Client) RecoveryInProgress

func (c *Client) RecoveryInProgress(ctx context.Context) (bool, error)

RecoveryInProgress reports whether any active shard recovery remains.

func (*Client) ReloadSecureSettings

func (c *Client) ReloadSecureSettings(ctx context.Context) error

ReloadSecureSettings reloads node keystores and reports any node-level failure.

func (*Client) RestoreSnapshot

func (c *Client) RestoreSnapshot(ctx context.Context, repo, name string, req RestoreRequest) error

RestoreSnapshot waits for native completion and requires an explicit complete shard result. Submission acceptance or an empty recovery list is not evidence that a snapshot restored successfully.

func (*Client) Search

func (c *Client) Search(ctx context.Context, index string, query any) (int64, []json.RawMessage, error)

Search returns exact total hits and the source documents from the result page.

func (*Client) SetAllocationEnable

func (c *Client) SetAllocationEnable(ctx context.Context, value *string) error

SetAllocationEnable sets persistent allocation.enable; nil restores its default.

func (*Client) SetAllocationExcludeNames

func (c *Client) SetAllocationExcludeNames(ctx context.Context, names []string) error

SetAllocationExcludeNames replaces effective exclusions, clearing transient precedence.

func (*Client) ShardCounts

func (c *Client) ShardCounts(ctx context.Context) (map[string]int, error)

ShardCounts returns allocated shard counts by node name, excluding UNASSIGNED.

func (*Client) SnapshotSize

func (c *Client) SnapshotSize(ctx context.Context, repo, name string) (int64, error)

SnapshotSize reports total snapshot bytes when status information is available. Callers may treat an error as unavailable metadata, rather than a failed backup.

func (*Client) SystemIndices

func (c *Client) SystemIndices(ctx context.Context) (map[string]bool, error)

SystemIndices identifies system indices from metadata, not their names.

func (*Client) UnassignedReplicasUnplaceable

func (c *Client) UnassignedReplicasUnplaceable(ctx context.Context, dataNodes int) (bool, error)

UnassignedReplicasUnplaceable proves that every unassigned copy is a replica whose shard already has a started copy on every intended data node. A large replica count on a different index or shard is not evidence of safety.

func (*Client) VerifyRepository

func (c *Client) VerifyRepository(ctx context.Context, name string) ([]string, error)

VerifyRepository verifies node access, returning sorted participating node names.

type ClusterSettings

type ClusterSettings struct {
	Persistent map[string]any `json:"persistent,omitempty"`
	Transient  map[string]any `json:"transient,omitempty"`
}

ClusterSettings holds explicit persistent and transient settings in flat form.

type Config

type Config struct {
	Endpoints          []string
	CAPEM              []byte
	Username, Password string
	BearerToken        string
	DialContext        func(ctx context.Context, network, addr string) (net.Conn, error)
	Timeout            time.Duration
}

Config selects endpoints, authentication and the namespace transport.

type DrainAllocation

type DrainAllocation struct {
	Index          string
	NoEligibleNode bool
	Filter         bool
}

DrainAllocation identifies a remaining shard and its allocation constraints. Native explanation text is deliberately not retained in status or events.

type Error

type Error struct {
	Status       int
	Type, Reason string
}

Error is an Elasticsearch HTTP error. Reason contains no client credentials.

func (*Error) Error

func (e *Error) Error() string

Error describes the HTTP status and Elasticsearch error type and reason.

type FieldSecurity

type FieldSecurity struct {
	Grant  *[]string `json:"grant,omitempty"`
	Except *[]string `json:"except,omitempty"`
}

FieldSecurity preserves absent and explicitly empty field lists separately. An empty grant list must not become an omitted (unrestricted) grant.

type Health

type Health struct {
	Status              string `json:"status"`
	NumberOfNodes       int    `json:"number_of_nodes"`
	NumberOfDataNodes   int    `json:"number_of_data_nodes"`
	ActivePrimaryShards int    `json:"active_primary_shards"`
	ActiveShards        int    `json:"active_shards"`
	RelocatingShards    int    `json:"relocating_shards"`
	InitializingShards  int    `json:"initializing_shards"`
	UnassignedShards    int    `json:"unassigned_shards"`
	TimedOut            bool   `json:"timed_out"`
}

Health is the shard health and node count response.

type HealthOptions

type HealthOptions struct {
	WaitForStatus string
	Timeout       time.Duration
	Local         bool
}

HealthOptions controls an optional server-side health wait.

type IndexPrivileges

type IndexPrivileges struct {
	Names                  []string       `json:"names"`
	Privileges             []string       `json:"privileges"`
	AllowRestrictedIndices bool           `json:"allow_restricted_indices"`
	Query                  *string        `json:"query,omitempty"`
	FieldSecurity          *FieldSecurity `json:"field_security,omitempty"`
}

IndexPrivileges grants privileges to the selected index patterns.

func (*IndexPrivileges) UnmarshalJSON

func (p *IndexPrivileges) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts Elasticsearch's string and object forms of a DLS query. The public API carries both as opaque query JSON strings.

type Info

type Info struct {
	Name        string `json:"name"`
	ClusterName string `json:"cluster_name"`
	ClusterUUID string `json:"cluster_uuid"`
	Version     struct {
		Number string `json:"number"`
	} `json:"version"`
}

Info is the cluster identity and responding node version.

type Node

type Node struct {
	ID      string   `json:"-"`
	Name    string   `json:"name"`
	Version string   `json:"version"`
	Roles   []string `json:"roles"`
}

Node is the observed identity, version and roles of a cluster node.

type Repository

type Repository struct {
	Type     string         `json:"type"`
	Settings map[string]any `json:"settings"`
}

Repository configures a snapshot repository.

type RestoreRequest

type RestoreRequest struct {
	Indices            string   `json:"indices,omitempty"`
	IncludeGlobalState bool     `json:"include_global_state"`
	FeatureStates      []string `json:"feature_states,omitempty"`
	IncludeAliases     bool     `json:"include_aliases"`
	IgnoreUnavailable  bool     `json:"ignore_unavailable"`
}

RestoreRequest selects data and state for a restore.

type Role

type Role struct {
	Cluster      []string                `json:"cluster,omitempty"`
	Indices      []IndexPrivileges       `json:"indices,omitempty"`
	Metadata     map[string]any          `json:"metadata,omitempty"`
	Applications []ApplicationPrivileges `json:"applications,omitempty"`
}

Role is a native role or API-key role descriptor.

type SnapshotFailure

type SnapshotFailure struct {
	Index     string `json:"index"`
	IndexUUID string `json:"index_uuid"`
	ShardID   int    `json:"shard_id"`
	NodeID    string `json:"node_id"`
	Reason    string `json:"reason"`
	Status    string `json:"status"`
}

SnapshotFailure describes a failed snapshot shard.

type SnapshotInfo

type SnapshotInfo struct {
	Snapshot  string            `json:"snapshot"`
	UUID      string            `json:"uuid"`
	State     string            `json:"state"`
	Version   string            `json:"version"`
	Indices   []string          `json:"indices"`
	StartTime time.Time         `json:"start_time"`
	EndTime   time.Time         `json:"end_time"`
	Failures  []SnapshotFailure `json:"failures"`
	Shards    SnapshotShards    `json:"shards"`
	// Reason is the snapshot-level failure reason, if any.
	Reason string `json:"reason,omitempty"`
}

SnapshotInfo describes a snapshot and its shard outcomes.

type SnapshotRequest

type SnapshotRequest struct {
	Indices            string         `json:"indices,omitempty"`
	IncludeGlobalState bool           `json:"include_global_state"`
	FeatureStates      []string       `json:"feature_states,omitempty"`
	Metadata           map[string]any `json:"metadata,omitempty"`
}

SnapshotRequest selects data, feature states and metadata to snapshot. Omitted FeatureStates uses Elasticsearch's include_global_state-dependent default.

type SnapshotShards

type SnapshotShards struct {
	Total      int `json:"total"`
	Failed     int `json:"failed"`
	Successful int `json:"successful"`
}

SnapshotShards summarizes snapshot shard outcomes.

type User

type User struct {
	Password string         `json:"password,omitempty"`
	Roles    []string       `json:"roles"`
	FullName string         `json:"full_name,omitempty"`
	Email    string         `json:"email,omitempty"`
	Enabled  *bool          `json:"enabled,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

User is a native user definition. Password is write-only and omitted when empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL