cluster

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pkg/cluster

Multi-node ZedSearch: membership, index ownership, fenced handoff, request routing and scatter-gather search. Coordination state lives in etcd, index data does not.

Model

Every index hashes to one of zed_cluster_partitions (256 by default) partitions, and every partition is owned by exactly one node:

index name --fnv1a--> partition --etcd--> owner node

The owner is the only node that writes the index. Reads go to the owner too, so a read always sees the owner's WAL.

The ownership map lives in etcd under <zed_etcd_prefix>/cluster/<zed_cluster_name>/:

key meaning
nodes/<id> member record, written under a lease, disappears when the node dies
leader leader lock, created with a lease, whoever creates it rebalances
assign/<partition> {"owner": "<node id>"}, its etcd mod revision is the epoch
replicas {"<partition>": ["<node id>", ...]}, replicas, a separate key so a replica change never bumps an epoch
insync {"<index>": ["<node id>", ...]}, replicas holding every acknowledged write (OpenSearch in-sync allocation ids)

The epoch is never written by us: it is the store revision of the assignment key, so it grows on every handoff and can be used as a fencing token.

Fenced handoff

The hole in a plain "ownership map in etcd" design is the transfer window: the new owner starts serving while the old owner is still finishing requests it admitted before the move.

Every request that lands on the owner records the epoch it was admitted with (ClusterEpochKey in the gin context). After a mutating handler returns, the middleware checks the epoch again:

  • unchanged: the buffered response is sent as is
  • changed (or we are no longer the owner): 409 {"error":"partition moved","owner":"<id>"}

Clients retry on 409; the retry is routed to the new owner.

This closes the window in which a stale owner could report success for a write the cluster no longer counts as its own. It does not roll back a WAL append that already happened - a write accepted before the handoff stays in the old owner's WAL. Keep that in mind when a partition moves while a bulk load is running.

Request routing

routes.ClusterRoute() is installed before the API routes, so it covers every :target route:

case behaviour
clustering disabled nothing happens, single node build
partition unassigned served locally
another node owns it httputil.ReverseProxy to its advertise address, Authorization copied, X-Zed-Forwarded-By: <node> set
already forwarded, still not ours 508 Loop Detected
we own it, read served locally
we own it, write served locally, then the epoch is re-checked (see above)
we are a replica, read of a cold index served locally, no hop
owner not resolvable, read of a cold index proxied to the first live replica
a,b, logs-*, _all on /es/.../_search split per owner, POST /api/_internal/search in parallel (at most 8 in flight), responses merged

/api/:target/_search speaks the v1 query format and is never scattered.

Scatter-gather asks every owner, including this node, over HTTP. That costs one loopback request but keeps one code path, and the internal endpoint never scatters again, so there is no recursion.

Merging (MergeSearch):

  • hits: re-sorted by score, or by the single sort field when the query has one, then cut to from/size
  • total summed, max_score maximum, took the slowest node
  • count/sum/value_count summed, max/min reduced, avg weighted by the _partial {count, sum} counters each node attaches
  • bucket aggregations unioned by key, doc_count summed, sub-aggregations merged recursively
  • everything else (cardinality, percentiles, stats, top_hits, pipelines) keeps the first node's value and logs a warning - those are approximations across nodes

Replication (full HA)

pkg/cluster/replication follows the three OpenSearch replication paths. Every write is acknowledged only after it is durable on more than one node (or in the bucket):

path indexes how OpenSearch counterpart
document (default) disk the owner records every WAL entry with a sequence number and ships it to each replica before answering; replicas append it to their own WAL and index it document replication, ReplicationOperation
segment disk entries are shipped the same way but replicas only keep them; every zed_cluster_replication_interval they copy the owner's segments (a checkpoint) and drop the entries it covers; on promotion they replay what they kept segment replication, FULL_REPLICATION translog + SegmentReplicationTarget
remote s3/gcs/oss, writable entries are uploaded to <index>/_translog/ before answering; segments already live in the bucket; a new owner replays the translog, a periodic flush persists the segments and trims it remote-backed storage, RemoteFsTranslog

zed_cluster_replication picks document, segment or none for disk indexes; object-storage indexes always use the remote translog when replication is on. Cold indexes take no writes and need none of this.

Write path on the owner (serveFenced):

  1. replication.Prepare - the first write after a promotion replays the kept entries (segment) or the remote translog (remote)
  2. the handler runs, core.WALHook records each entry in WAL order
  3. replication.Commit ships everything recorded to every replica (or uploads it). A replica that fails is removed from the in-sync set before the write is acknowledged (OpenSearch failShardIfNeeded); if that removal cannot be written the write fails with 503
  4. the epoch is checked as before, then the response is sent

_bulk without an index in the path commits every index it touched.

The term is unique per owner incarnation (epoch + start time). A replica on another term, or one missing entries the owner no longer retains (100k entries), is asked to recover: it downloads a tar of the owner's segments (riot point-in-time backup after the WAL was applied), replaces its copy and continues from the snapshot's sequence number. Entries are rewritten to idempotent updates, so an entry already in the snapshot is harmless when replayed. A replica whose entries are retained is caught up from the log without copying files.

Promotion. The leader only hands a replicated partition to a node in the in-sync set of all its indexes. When the owner dies with no live in-sync replica the partition stays on the dead owner (unavailable, like a red shard) instead of going to a stale node. A rebalance never moves a replicated partition off a live owner to a node that has not caught up.

Reads. Replicas serve reads of their copy once installed (near real time, like OpenSearch replicas) and are the fallback when the owner is gone.

Node to node calls (/api/_internal/replication/*) carry X-Zed-Cluster-Secret; set zed_cluster_secret to the same value on every node. Replication refuses to start without it.

Read replicas

zed_cluster_replicas (default 1) is the number of extra nodes the leader assigns to each partition next to its owner. The start node rotates with the partition, so one owner's replicas spread over all the other nodes.

Replicas serve reads of cold indexes (read-only on object storage, every node sees the same data) and, with replication on, of disk indexes once their copy is installed. Hot and warm object-storage indexes are read through the owner's writer.

  • a read of a cold index on one of its replicas is served locally
  • a read whose owner cannot be resolved (died, not yet reassigned) is sent to the first live replica instead of failing with 503
  • scatter-gather serves the indexes this node holds a ready replica of locally
  • when an owner dies the rebalance hands its partitions to a live replica first (within quota), so failover lands on a node already serving them

Node addresses are cached from a membership watch (resynced every heartbeat interval), so forwarding a request no longer reads etcd.

Configuration

zed_cluster_enable = true
zed_cluster_name = "prod"
zed_cluster_node_id = ""                 # defaults to the hostname
zed_cluster_advertise_addr = "http://10.0.0.1:4080"
zed_cluster_partitions = 256
zed_cluster_heartbeat_interval = 5000000000   # 5s, in ns
zed_cluster_heartbeat_ttl = 15000000000       # 15s, in ns
zed_cluster_replicas = 1                      # replicas per partition
zed_cluster_replication = "document"          # document | segment | none
zed_cluster_replication_interval = 10000000000 # 10s: checkpoints, flushes, catch-up
zed_cluster_secret = "change-me"              # same on every node

zed_etcd_endpoints = ["http://10.0.0.10:2379"]
zed_etcd_prefix = "/zed"

Every setting is also an environment variable in upper case (ZED_CLUSTER_ENABLE, ZED_ETCD_ENDPOINTS, ...).

Three nodes with a shared etcd
# etcd (single node is fine for a test, run three for production)
docker run -d --name etcd -p 2379:2379 \
  -e ALLOW_NONE_AUTHENTICATION=yes \
  -e ETCD_ADVERTISE_CLIENT_URLS=http://10.0.0.10:2379 \
  -e ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379 \
  bitnami/etcd:latest

# node 1..3, same on every host with its own id and address
export ZED_FIRST_ADMIN_USER=admin ZED_FIRST_ADMIN_PASSWORD=Complexpass#123
export ZED_CLUSTER_ENABLE=true
export ZED_CLUSTER_NAME=prod
export ZED_ETCD_ENDPOINTS=http://10.0.0.10:2379
export ZED_CLUSTER_NODE_ID=node-1
export ZED_CLUSTER_ADVERTISE_ADDR=http://10.0.0.1:4080
export ZED_CLUSTER_SECRET=***
./zedsearch

Check the cluster:

curl -u admin:Complexpass#123 http://10.0.0.1:4080/api/cluster/nodes
curl -u admin:Complexpass#123 'http://10.0.0.1:4080/api/cluster/partitions?index=logs-2024'
curl -u admin:Complexpass#123 http://10.0.0.1:4080/es/_cat/health?v

Guarantees

  • one writer per index at any time, enforced by the ownership map
  • handoffs are fenced by the partition epoch, a write admitted by the old owner cannot be reported as successful after the move
  • leadership is only used to compute the assignment; every assignment write is a compare-and-swap, so two leaders during a partition cannot corrupt the map
  • rebalancing is stable: adding or removing a node moves about partitions / nodes partitions, the rest stay where they are
  • a node that dies loses its lease, its partitions are reassigned within zed_cluster_heartbeat_ttl
  • indexes on object storage (s3, gcs, oss) are readable by whichever node takes over, so they survive node loss
  • with replication on, an acknowledged write is on every in-sync replica (document, segment) or in the bucket (remote), and only an in-sync replica is promoted, so losing the owner loses no acknowledged write

Limits

  • a replica records its position (term, last operation, installed files) in _replica.json beside the index data, on every replication tick, after each install and on shutdown; a restarted replica resumes from it and is caught up from the owner's retained log. Segment-mode kept entries are in memory and are fetched again. A restarted owner starts a new term, which makes its replicas recover
  • recovery and segment checkpoints send only the segments the replica does not already hold (matched by path, size and sha256); the owner still makes a full local snapshot of the index for each one, and checkpoints are skipped when nothing changed
  • replicas and owners must run the same version for incremental recovery: a newer replica asks with POST, an older owner only serves GET
  • with zed_cluster_replicas = 0, or zed_cluster_replication = "none", disk indexes are back to failover by reassignment
  • index metadata is shared through etcd: cluster mode always stores it there, whatever ZED_METADATA_STORAGE says, so every node sees every index
  • the remote flush closes the writers of the index briefly, writes wait for it
  • a 409 is not retried for the client, the caller has to repeat the request
  • cardinality, percentiles, stats and top_hits are approximated in a scatter-gather search, the first responding owner wins
  • an avg is weighted by the number of documents each node matched, which is exact only when the averaged field is present in every matched document

Tests

go test ./pkg/cluster/...                    # unit tests, in-memory store and replication
ZED_ETCD_ENDPOINTS=http://127.0.0.1:2379 \
  go test ./pkg/cluster/ -run TestEtcdStoreIntegration   # against a real etcd

Documentation

Index

Constants

View Source
const DefaultPartitions = 256

DefaultPartitions is used when the config leaves the count unset.

View Source
const PartialAggName = "_partial"

PartialAggName is the sub-aggregation a node attaches to an average so the coordinator can weight it: {"count": n, "sum": s}.

Variables

View Source
var (
	// ErrStoreClosed is returned by a store that has already been closed.
	ErrStoreClosed = errors.New("cluster: store closed")
	// ErrNotEnabled is returned by cluster calls made while clustering is off.
	ErrNotEnabled = errors.New("cluster: not enabled")
)
View Source
var ErrNoOwner = errors.New("cluster: index has no owner")

ErrNoOwner is returned when nothing owns the partition of an index yet, which happens before the first rebalance has been applied.

View Source
var ErrNotLive = errors.New("cluster: membership lease may have expired")

ErrNotLive is returned when the local membership lease may have expired, so the ownership map this node sees can be stale.

Functions

func Assignments

func Assignments() map[int]Assignment

Assignments returns the ownership map, empty when clustering is off.

func CheckEpoch

func CheckEpoch(indexName string, epoch int64) error

CheckEpoch fails when the partition of indexName moved since epoch was taken. Always nil with clustering disabled.

func ConstrainChanges

func ConstrainChanges(changes, owners map[int]string, nodes []string, eligible map[int][]string) map[int]string

ConstrainChanges drops rebalance moves that would hand a replicated partition to a node that is not in sync. A partition whose owner is dead goes to a live in-sync node instead, or nowhere when there is none.

func DecodeSearchResponse

func DecodeSearchResponse(data []byte) (*meta.SearchResponse, error)

DecodeSearchResponse decodes a response received from another node.

meta.AggregationResponse marshals its sub-aggregations inline but has no matching unmarshaller, so a plain decode silently drops them, including the "_partial" counters. This restores every object key that is not a field of AggregationResponse as a sub-aggregation.

func EligibleOwners

func EligibleOwners(insync map[string][]string, partitions int) map[int][]string

EligibleOwners maps every partition holding a replicated index to the nodes that are in sync for all of its indexes. Partitions without a replicated index are absent: any node may own them.

func Enabled

func Enabled() bool

Enabled reports whether this process participates in a cluster.

func InSync

func InSync(ctx context.Context) (map[string][]string, error)

InSync returns the in-sync map, empty with clustering disabled.

func IsLeader

func IsLeader() bool

IsLeader reports whether this node currently holds the leader lock.

func IsLocalOwner

func IsLocalOwner(indexName string) bool

IsLocalOwner reports whether this node may write indexName. A node whose membership lease may have expired owns nothing: its partitions may have been handed to another node it cannot hear from.

func IsLocalReplica

func IsLocalReplica(indexName string) bool

IsLocalReplica reports whether this node is a read replica of indexName. Only indexes every node can open read-only (cold, object storage) may be served from a replica; that check is left to the caller.

func KeyPrefix

func KeyPrefix() string

KeyPrefix is the etcd key prefix every cluster key of this deployment lives under.

func MergeSearch

func MergeSearch(responses []*meta.SearchResponse, query *meta.ZedQuery) *meta.SearchResponse

MergeSearch combines the per-owner responses of a scatter-gather search into the single response the client expects.

Hits are re-sorted globally and cut down to the requested window, counts are summed and aggregations are merged according to the aggregation type taken from the original query. Aggregations that cannot be merged exactly (cardinality, percentiles, stats) keep the first node's value and are logged, they are approximations across nodes.

func NodeAddr

func NodeAddr(id string) (string, bool)

NodeAddr returns the advertised address of a node id. It is answered from the member cache; a miss (a node that just joined) falls back to one read.

func Owner

func Owner(indexName string) (string, int64, bool)

Owner returns the node owning indexName and the epoch of that ownership. ok is false when clustering is off or the partition is unassigned.

func PartitionOf

func PartitionOf(indexName string) int

PartitionOf maps an index name to its partition using the configured partition count. The mapping is a pure function of the name, so every node computes the same partition without coordination.

func PartitionOfN

func PartitionOfN(indexName string, partitions int) int

PartitionOfN maps an index name onto `partitions` buckets.

func PlanReplicas

func PlanReplicas(owners map[int]string, nodes []string, n int) map[int][]string

PlanReplicas picks n read replicas for every owned partition among the live nodes, never the owner itself. The start node rotates with the partition number, so the replicas of one owner spread over all the others instead of piling onto its ring successor.

func Rebalance

func Rebalance(current map[int]string, nodes []string, partitions int) map[int]string

Rebalance spreads `partitions` buckets over `nodes` and returns only the partitions that must move.

Stability is the point: a partition already owned by a live node is left alone unless that node is over quota. Adding or removing a node therefore moves roughly partitions/nodes buckets instead of reshuffling everything.

func RebalanceWarm

func RebalanceWarm(current map[int]string, replicas map[int][]string, nodes []string, partitions int) map[int]string

RebalanceWarm is Rebalance that hands a partition that must move to one of its warm replicas first, as long as that replica is alive and under quota. The replica already serves the partition's reads, so failover lands on a node that is ready instead of a cold one.

func Replicas

func Replicas(indexName string) []string

Replicas returns the nodes keeping a warm read replica of indexName, empty when clustering is off or `zed_cluster_replicas` is 0.

func Start

func Start(ctx context.Context) error

Start joins the cluster. It is a no-op when clustering is disabled, so callers can call it unconditionally.

func StartWith

func StartWith(ctx context.Context, store Store) error

StartWith joins the cluster using a caller provided store. Tests use it with a MemoryStore, production goes through Start.

func Stop

func Stop()

Stop leaves the cluster: resign leadership, drop the membership record so peers stop routing here, then close the store.

func UpdateInSync

func UpdateInSync(ctx context.Context, index string, nodes []string) error

UpdateInSync records the in-sync replicas of an index this node owns, nil drops the entry. A no-op with clustering disabled.

Types

type Assigner

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

Assigner reads and writes the partition ownership map.

func NewAssigner

func NewAssigner(store Store, prefix string, partitions int) *Assigner

NewAssigner builds an assigner over `<prefix>assign/`.

func (*Assigner) Apply

func (a *Assigner) Apply(ctx context.Context, current map[int]Assignment, changes map[int]string) error

Apply writes a rebalance result. Partitions whose assignment changed under us are skipped, the next rebalance round picks them up again.

func (*Assigner) AssignPrefix

func (a *Assigner) AssignPrefix() string

AssignPrefix is the key prefix every assignment lives under.

func (*Assigner) InSyncKey

func (a *Assigner) InSyncKey() string

InSyncKey is the key holding the in-sync map.

func (*Assigner) List

func (a *Assigner) List(ctx context.Context) (map[int]Assignment, error)

List returns the current ownership map keyed by partition.

func (*Assigner) ListInSync

func (a *Assigner) ListInSync(ctx context.Context) (map[string][]string, int64, error)

ListInSync returns index -> in-sync replicas and the revision it was read at.

func (*Assigner) ListReplicas

func (a *Assigner) ListReplicas(ctx context.Context) (map[int][]string, int64, error)

ListReplicas returns the replica map and the revision it was read at, 0 when it was never written.

func (*Assigner) ReplicasKey

func (a *Assigner) ReplicasKey() string

ReplicasKey is the key holding the replica map.

func (*Assigner) Set

func (a *Assigner) Set(ctx context.Context, partition int, owner string, rev int64) (Assignment, bool, error)

Set installs owner for a partition. rev is the revision the caller last saw for that partition (0 when it was unassigned); the write is rejected when somebody else changed it meanwhile, which keeps epochs strictly ordered.

func (*Assigner) SetReplicas

func (a *Assigner) SetReplicas(ctx context.Context, replicas map[int][]string, rev int64) (bool, error)

SetReplicas writes the replica map when it is still at rev.

func (*Assigner) UpdateInSync

func (a *Assigner) UpdateInSync(ctx context.Context, index string, nodes []string) error

UpdateInSync sets the in-sync replicas of index, nil removes the entry.

type Assignment

type Assignment struct {
	Partition int      `json:"partition"`
	Owner     string   `json:"owner"`
	Epoch     int64    `json:"epoch"`
	Replicas  []string `json:"replicas,omitempty"`
}

Assignment names the single node that owns a partition.

Epoch is the store revision of the assignment key. It is never written by us, it is filled in from the revision the store reports, so it increases on every handoff and can be used as a fencing token.

type Coordinator

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

Coordinator keeps the partition map in shape. Only the leader writes, the others just watch membership so they can take over without delay.

func NewCoordinator

func NewCoordinator(election *Election, membership *Membership, assigner *Assigner, partitions, replicas int, interval time.Duration) *Coordinator

NewCoordinator wires the pieces the rebalance loop needs. replicas is the number of warm read replicas kept per partition.

func (*Coordinator) RebalanceOnce

func (c *Coordinator) RebalanceOnce(ctx context.Context) error

RebalanceOnce recomputes ownership from the live member list, writes the partitions that must move, then the replica map. Orphaned partitions go to a warm replica first. It is a no-op on non-leaders.

func (*Coordinator) Run

func (c *Coordinator) Run(ctx context.Context)

Run rebalances on every membership change and on a slow timer, which covers missed watch events after a reconnect.

type Election

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

Election is a lease based leader election on `<prefix>leader`. The winner is whoever manages to create the key; it stays leader as long as it keeps the lease alive. When the process dies the lease expires, the key is removed and the next campaign round elects somebody else.

The leader is only a convenience: it is the node that computes and writes the partition assignment. Correctness of ownership does not depend on there being exactly one leader, every assignment write is a compare-and-swap on the partition key.

func NewElection

func NewElection(store Store, prefix, nodeID string, ttl, interval time.Duration) *Election

NewElection builds an election for nodeID over `<prefix>leader`.

func (*Election) Campaign

func (e *Election) Campaign(ctx context.Context) (bool, error)

Campaign runs one election round: renew leadership when we hold it, else try to take the key. It reports whether the local node is leader after the round.

func (*Election) IsLeader

func (e *Election) IsLeader() bool

IsLeader reports whether the local node last won the election and its lease cannot have expired yet: when renewals keep failing, another node may already have taken the key.

func (*Election) Key

func (e *Election) Key() string

Key is the key the election is held on.

func (*Election) Leader

func (e *Election) Leader() string

Leader returns the node id currently believed to hold the leadership, empty when it is unknown.

func (*Election) Resign

func (e *Election) Resign(ctx context.Context) error

Resign gives up leadership so another node can take over immediately instead of waiting for the lease to expire. Revoking the lease removes the key only while it is still ours; deleting it by name could remove the key of a leader elected after our lease expired.

func (*Election) Run

func (e *Election) Run(ctx context.Context)

Run campaigns every interval until ctx is done.

type EpochError

type EpochError struct {
	Index string
	Owner string
	Have  int64
	Want  int64
}

EpochError says the partition of an index moved: the epoch presented by the caller is not the epoch currently recorded in the ownership map.

func (*EpochError) Error

func (e *EpochError) Error() string

type EtcdStore

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

EtcdStore is the production Store, it maps our small interface onto the etcd v3 client. Revisions are etcd mod revisions, which is what makes them usable as fencing tokens.

func NewEtcdStore

func NewEtcdStore() (*EtcdStore, error)

NewEtcdStore dials the etcd cluster configured in the [Etcd] section.

func (*EtcdStore) Close

func (s *EtcdStore) Close() error

func (*EtcdStore) CompareAndSwap

func (s *EtcdStore) CompareAndSwap(ctx context.Context, key string, value []byte, rev int64, lease LeaseID) (int64, bool, error)

func (*EtcdStore) Create

func (s *EtcdStore) Create(ctx context.Context, key string, value []byte, lease LeaseID) (int64, bool, error)

func (*EtcdStore) Delete

func (s *EtcdStore) Delete(ctx context.Context, key string) error

func (*EtcdStore) Get

func (s *EtcdStore) Get(ctx context.Context, key string) (KV, error)

func (*EtcdStore) Grant

func (s *EtcdStore) Grant(ctx context.Context, ttl time.Duration) (LeaseID, error)

func (*EtcdStore) KeepAlive

func (s *EtcdStore) KeepAlive(ctx context.Context, id LeaseID) error

func (*EtcdStore) List

func (s *EtcdStore) List(ctx context.Context, prefix string) ([]KV, error)

func (*EtcdStore) Put

func (s *EtcdStore) Put(ctx context.Context, key string, value []byte, lease LeaseID) (int64, error)

func (*EtcdStore) Revoke

func (s *EtcdStore) Revoke(ctx context.Context, id LeaseID) error

func (*EtcdStore) Watch

func (s *EtcdStore) Watch(ctx context.Context, prefix string) (<-chan Event, error)

type Event

type Event struct {
	Type EventType
	KV   KV
}

Event is a single change observed on a watched prefix.

type EventType

type EventType int

EventType tells apart a write from a removal in a Watch stream.

const (
	// EventPut is emitted when a key is created or updated.
	EventPut EventType = iota
	// EventDelete is emitted when a key is deleted or its lease expires.
	EventDelete
)

type Fence

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

Fence answers "who owns this index and with which epoch" from a local copy of the ownership map kept current by a watch.

The epoch is the store revision of the assignment key, so it grows on every handoff. A request that started while this node was the owner carries the epoch it saw; if the partition moved meanwhile the epoch no longer matches and the write is rejected with 409.

This closes the transfer window - the interval between the new owner taking the partition and the old owner noticing - it does not roll back an append that already reached the WAL. A write that was accepted before the handoff stays accepted; what is prevented is reporting success for a write whose partition is no longer ours.

func NewFence

func NewFence(assigner *Assigner, nodeID string, partitions int) *Fence

NewFence builds an empty fence, call Refresh or Run to fill it.

func (*Fence) Assignments

func (f *Fence) Assignments() map[int]Assignment

Assignments returns a copy of the ownership map, replicas included.

func (*Fence) CheckEpoch

func (f *Fence) CheckEpoch(indexName string, epoch int64) error

CheckEpoch fails when the ownership of indexName changed since epoch was taken, or when this node is no longer the owner.

func (*Fence) IsLocalOwner

func (f *Fence) IsLocalOwner(indexName string) bool

IsLocalOwner reports whether this node owns indexName. An unassigned partition counts as local: before the first rebalance every node serves its own requests, exactly like the single node build does.

func (*Fence) IsLocalReplica

func (f *Fence) IsLocalReplica(indexName string) bool

IsLocalReplica reports whether this node is a read replica of indexName.

func (*Fence) NodeID

func (f *Fence) NodeID() string

NodeID is the local node id the fence compares owners against.

func (*Fence) Owner

func (f *Fence) Owner(indexName string) (string, int64, bool)

Owner returns the node that owns indexName and the epoch of that ownership. ok is false while the partition is unassigned.

func (*Fence) PartitionCounts

func (f *Fence) PartitionCounts() map[string]int

PartitionCounts returns how many partitions each node owns.

func (*Fence) Refresh

func (f *Fence) Refresh(ctx context.Context) error

Refresh replaces the local copy with a full read of the ownership map.

func (*Fence) Replicas

func (f *Fence) Replicas(indexName string) []string

Replicas returns the nodes holding a warm read replica of indexName.

func (*Fence) Run

func (f *Fence) Run(ctx context.Context, resync time.Duration)

Run keeps the local copy current until ctx is done: the watch stream, one full read, with a periodic re-read so a dropped watch heals. The watches open before the read so no change falls between the two.

type KV

type KV struct {
	Key      string
	Value    []byte
	Revision int64
}

KV is a single key with the store revision of its last write. The revision is the fencing token: it only ever grows for a given key.

type LeaseID

type LeaseID int64

LeaseID identifies a lease held by a node. NoLease means the key is written without a lease and therefore never expires on its own.

const NoLease LeaseID = 0

NoLease is the zero lease, keys written with it are permanent.

type Membership

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

Membership keeps `<prefix>/nodes/<id>` alive under a lease. When the process dies the lease expires and the key disappears, which is how the rest of the cluster learns the node is gone.

func NewMembership

func NewMembership(store Store, prefix string, local Node, ttl, interval time.Duration) *Membership

NewMembership builds membership for local under prefix.

func (*Membership) Addr

func (m *Membership) Addr(id string) (string, bool)

Addr returns the cached advertise address of a member. Request routing resolves an owner on every forwarded call, the cache keeps that off etcd.

func (*Membership) Join

func (m *Membership) Join(ctx context.Context) error

Join grants a lease and registers the local node under it.

func (*Membership) KeepAlive

func (m *Membership) KeepAlive(ctx context.Context) error

KeepAlive refreshes the lease once. A lease that the store no longer knows about (expired during a network partition) is replaced by re-joining, so a node that comes back always reappears in the member list.

func (*Membership) Lease

func (m *Membership) Lease() LeaseID

Lease returns the lease currently backing the local node record.

func (*Membership) Leave

func (m *Membership) Leave(ctx context.Context) error

Leave revokes the lease, which removes the node record. The key is not deleted by name: a newer process with the same id may own it by now.

func (*Membership) ListNodes

func (m *Membership) ListNodes(ctx context.Context) ([]Node, error)

ListNodes returns every live node, sorted by id so every node computes the same rebalance result from the same input.

func (*Membership) Live

func (m *Membership) Live() bool

Live reports whether the local node record cannot have expired yet: once renewals keep failing past the ttl, the partitions may already be owned by another node.

func (*Membership) NodesPrefix

func (m *Membership) NodesPrefix() string

NodesPrefix is the key prefix every node record lives under.

func (*Membership) Refresh

func (m *Membership) Refresh(ctx context.Context) error

Refresh replaces the cached member list with a full read.

func (*Membership) Run

func (m *Membership) Run(ctx context.Context, resync time.Duration)

Run keeps the member cache current until ctx is done: one full read, then the watch stream, with a periodic re-read so a dropped watch heals.

func (*Membership) Watch

func (m *Membership) Watch(ctx context.Context) (<-chan Event, error)

Watch streams membership changes until ctx is done.

type MemoryStore

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

MemoryStore is an in-process Store used by tests. Lease expiry is driven by a pluggable clock so TTL behaviour can be exercised without sleeping.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty store using the wall clock.

func (*MemoryStore) Close

func (m *MemoryStore) Close() error

func (*MemoryStore) CompareAndSwap

func (m *MemoryStore) CompareAndSwap(_ context.Context, key string, value []byte, rev int64, lease LeaseID) (int64, bool, error)

func (*MemoryStore) Create

func (m *MemoryStore) Create(_ context.Context, key string, value []byte, lease LeaseID) (int64, bool, error)

func (*MemoryStore) Delete

func (m *MemoryStore) Delete(_ context.Context, key string) error

func (*MemoryStore) Get

func (m *MemoryStore) Get(_ context.Context, key string) (KV, error)

func (*MemoryStore) Grant

func (m *MemoryStore) Grant(_ context.Context, ttl time.Duration) (LeaseID, error)

func (*MemoryStore) KeepAlive

func (m *MemoryStore) KeepAlive(_ context.Context, id LeaseID) error

func (*MemoryStore) List

func (m *MemoryStore) List(_ context.Context, prefix string) ([]KV, error)

func (*MemoryStore) Put

func (m *MemoryStore) Put(_ context.Context, key string, value []byte, lease LeaseID) (int64, error)

func (*MemoryStore) Revoke

func (m *MemoryStore) Revoke(_ context.Context, id LeaseID) error

func (*MemoryStore) SetClock

func (m *MemoryStore) SetClock(now func() time.Time)

SetClock replaces the clock used for lease expiry, for deterministic tests.

func (*MemoryStore) Watch

func (m *MemoryStore) Watch(ctx context.Context, prefix string) (<-chan Event, error)

type Node

type Node struct {
	ID        string `json:"id"`
	Addr      string `json:"addr"`
	StartedAt int64  `json:"started_at"` // unix milliseconds
}

Node is one zedsearch process in the cluster.

func Local

func Local() *Node

Local returns the local node record, nil when clustering is disabled.

type NodeStatus

type NodeStatus struct {
	ID         string `json:"id"`
	Addr       string `json:"addr"`
	Alive      bool   `json:"alive"`
	Partitions int    `json:"partitions"`
	IsLeader   bool   `json:"is_leader"`
}

NodeStatus is one row of `GET /api/cluster/nodes`.

func Nodes

func Nodes() []NodeStatus

Nodes lists the cluster members. With clustering disabled it reports the single local process, so callers do not need a special case.

type Store

type Store interface {
	// Grant creates a lease that expires after ttl unless kept alive.
	Grant(ctx context.Context, ttl time.Duration) (LeaseID, error)
	// KeepAlive refreshes a lease once, it must be called more often than the ttl.
	KeepAlive(ctx context.Context, id LeaseID) error
	// Revoke drops a lease and every key attached to it.
	Revoke(ctx context.Context, id LeaseID) error

	// Put writes key unconditionally and returns the new revision.
	Put(ctx context.Context, key string, value []byte, lease LeaseID) (int64, error)
	// Get returns a single key, errors.ErrKeyNotFound when it is absent.
	Get(ctx context.Context, key string) (KV, error)
	// List returns every key under prefix, sorted by key.
	List(ctx context.Context, prefix string) ([]KV, error)
	// Delete removes a key, removing a missing key is not an error.
	Delete(ctx context.Context, key string) error

	// Create writes key only when it does not exist yet. It reports whether
	// the write happened; when it did not, the returned revision belongs to
	// the value that is already there.
	Create(ctx context.Context, key string, value []byte, lease LeaseID) (int64, bool, error)
	// CompareAndSwap writes key only when its current revision is rev. Use
	// rev == 0 to require that the key does not exist.
	CompareAndSwap(ctx context.Context, key string, value []byte, rev int64, lease LeaseID) (int64, bool, error)

	// Watch streams changes under prefix until ctx is done.
	Watch(ctx context.Context, prefix string) (<-chan Event, error)

	// Close releases the underlying connection.
	Close() error
}

Store is the small slice of a consistent key value store the cluster needs: leases for liveness, revisions for fencing, prefix watches for change notification. It is implemented by etcd in production and by an in-memory store in tests.

Directories

Path Synopsis
Package replication keeps the data of every index on more than one node, following the three OpenSearch replication paths:
Package replication keeps the data of every index on more than one node, following the three OpenSearch replication paths:

Jump to

Keyboard shortcuts

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