membership

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0 modules, 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.

Documentation

Overview

Package membership changes the voter set of the cluster (ADR 0005 point 7, ADR 0012 A3–A5, FA-CLU-03/04/08/10): joining nodes enter as nonvoters and are promoted once they caught up, changes are serialized, nodes are only removed by a platform admin and are revoked with it.

Index

Constants

View Source
const (
	// MaxLag is how far a nonvoter may be behind the leader's log to be promoted.
	MaxLag = 100
	// PromoteTimeout is how long the leader tries to promote a nonvoter.
	PromoteTimeout = 10 * time.Minute
)

Timings of the promotion (FA-CLU-03).

Variables

View Source
var (
	ErrNotLeader    = errors.New("membership changes run on the leader")
	ErrUnknownNode  = errors.New("node is not a member of the cluster")
	ErrRemoveLeader = errors.New("the leader cannot remove itself; transfer leadership first")
	ErrLastVoter    = errors.New("the last voter cannot be removed")

	// ErrLeaderUnavailable is a transport failure while a follower forwards a
	// request to the leader; the caller may retry.
	ErrLeaderUnavailable = errors.New("no leader available, retry")
)

Errors of membership changes.

Access levels of the ClusterService and ReplicationService methods (clusternet.Authorize). Apply accepts forwarded commands from voters only: a voter is a full member and could propose any command itself, probes never write (FA-CLU-05). RemoveNode carries a platform admin's request that the forwarding voter has authorized; any voter could change the configuration itself, so it needs no more than a voter certificate. Replication runs between voters only; probe heartbeats reach the cluster through the probe gateway (P5).

View Source
var (
	ErrJoinRejected = errors.New("join rejected")
)

Permanent join errors: retrying with the same token cannot succeed.

Functions

func RenewViaLeader

func RenewViaLeader(leader func() string, dial func(address string) (pb.ClusterServiceClient, func(), error)) clusterpki.IssueFunc

RenewViaLeader returns an IssueFunc that renews this node's certificate through RenewCertificate on the leader (followers, FA-PKI-03).

Types

type AddressInUseError

type AddressInUseError struct{ NodeID string }

AddressInUseError rejects a join of a new node under an address another node already has (FA-CLU-08, ADR 0012 A5).

func (*AddressInUseError) Error

func (e *AddressInUseError) Error() string

type Forwarder

type Forwarder struct {
	// Client returns a client for the leader at address (mTLS as voter). The
	// client is reused across calls; the caller owns its connection.
	Client func(address string) (pb.ClusterServiceClient, error)
}

Forwarder sends commands of a follower to the leader over the cluster port and implements cluster.Forwarder.

func (*Forwarder) Forward

func (f *Forwarder) Forward(ctx context.Context, leaderAddress string, cmd *pb.Command) (cluster.ApplyResult, error)

Forward calls Apply on the leader. The error contract of cluster.Forwarder: FAILED_PRECONDITION (the callee is not the leader) is ErrNotApplied; any other transport or server failure is ErrUnknownOutcome, because the leader may have appended the command before the failure.

type HealthTracker

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

HealthTracker turns the heartbeat observations of the leader into health decisions (ADR 0017). It does no I/O: the caller feeds it, asks Decide and proposes the changes it returns. It is safe for concurrent use. The zero value is ready to use.

func (*HealthTracker) BecameLeader

func (t *HealthTracker) BecameLeader(at time.Time)

BecameLeader records when this node became leader. Until healthThreshold has passed no peer is decided healthy, because the heartbeats of the previous leader tell nothing about the new one.

func (*HealthTracker) Decide

func (t *HealthTracker) Decide(now time.Time, peers []string, registry map[string]bool) map[string]bool

Decide returns the health changes to propose at now. Only peers that are in peers and in registry are decided; registry maps node IDs to their current health. A change is returned only if the decided value differs from the registry. Without leadership nothing is decided.

A peer is unhealthy once its heartbeats failed for healthThreshold. It is healthy again once it has been without failure for healthThreshold, and the node has been leader for that long too; a peer that never failed counts as healthy after the leader grace. Failures shorter than the threshold change nothing, which keeps brief interruptions from making a node flap.

func (*HealthTracker) Failed

func (t *HealthTracker) Failed(peer string, at time.Time)

Failed records a failed heartbeat to peer at the given time.

func (*HealthTracker) Reset

func (t *HealthTracker) Reset()

Reset forgets the leadership and all observations. The caller resets when this node stops being leader and before it becomes leader again.

func (*HealthTracker) Resumed

func (t *HealthTracker) Resumed(peer string, at time.Time)

Resumed records that heartbeats to peer succeed again.

type HealthWatcher

type HealthWatcher struct {
	Node  *cluster.Node
	State store.State
	Log   *slog.Logger
	// Now is the wall clock of this node; nil means time.Now. It must be the
	// clock the heartbeat observations are stamped with (ADR 0020).
	Now func() time.Time
	// contains filtered or unexported fields
}

HealthWatcher runs the health decisions of the leader (ADR 0017): it feeds the heartbeat observations of Raft into a HealthTracker and proposes the changes to the node registry. Only the leader proposes.

func (*HealthWatcher) Observe

func (w *HealthWatcher) Observe(peerID string, ok bool, at time.Time)

Observe records one heartbeat observation of the leader. It is the callback of cluster.Node.OnHeartbeat.

func (*HealthWatcher) Run

func (w *HealthWatcher) Run(ctx context.Context)

Run decides on health changes every healthInterval until ctx ends.

type JoinOptions

type JoinOptions struct {
	Seeds   []string
	Token   string
	NodeID  string
	Name    string
	Address string
	Version string
	// MaxCommandVersion is announced to the cluster at join (ADR 0018). Zero
	// means cluster.CommandVersion; tests override it.
	MaxCommandVersion uint32
	Cert              *clusterpki.NodeCert
	Log               *slog.Logger
	// Clock is the wall clock of the joining node; nil means time.Now (ADR 0020).
	Clock func() time.Time
}

JoinOptions describe a node joining an existing cluster.

type Joined

type Joined struct {
	ClusterID string
	// KEK is the cluster's generated master key, if it uses one (ADR 0011
	// option B); empty if the cluster uses an external key.
	KEK            []byte
	KEKFingerprint string
}

Joined is the result of a successful join.

func Join

func Join(ctx context.Context, opts JoinOptions) (Joined, error)

Join enrolls this node as voter through one of the seeds (FA-CLU-03). It trusts only a server whose CA matches the fingerprint in the token and retries with backoff and jitter until ctx ends; a rejected token or an address conflict ends it at once.

type KEK

type KEK interface {
	Transferable() ([]byte, bool)
}

KEK hands the generated master key to joining voters (ADR 0011 option B).

type LevelNode

type LevelNode interface {
	IsLeader() bool
	Members() ([]cluster.Member, uint64, error)
	CommandLevel(ctx context.Context) (uint32, error)
	Apply(ctx context.Context, cmd *pb.Command) (cluster.ApplyResult, error)
}

LevelNode is the part of cluster.Node the LevelWatcher uses.

type LevelWatcher

type LevelWatcher struct {
	Node  LevelNode
	State store.State
	Log   *slog.Logger
}

LevelWatcher raises the cluster command level once all voters support a higher one (ADR 0018). Only the leader proposes. It never lowers the level.

func (*LevelWatcher) Run

func (w *LevelWatcher) Run(ctx context.Context)

Run checks the level every levelInterval until ctx ends.

type Manager

type Manager struct {
	Raft   Raft
	Status StatusFunc
	// DialLeader returns a client for the leader at address (mTLS as voter).
	// The caller closes the connection with the returned func.
	DialLeader func(address string) (pb.ClusterServiceClient, func(), error)
	Log        *slog.Logger
	// contains filtered or unexported fields
}

Manager serializes membership changes on the leader. The mutex covers multi-step changes (nonvoter → voter, remove → add); after a leader change the new leader continues them idempotently (ADR 0012 A4).

func (*Manager) AddVoter

func (m *Manager) AddVoter(_ context.Context, nodeID, address string) error

AddVoter enrolls a voter: as nonvoter first (or with a new address if it is a member already, FA-CLU-10), then promoted in the background once it caught up.

func (*Manager) CheckAddress

func (m *Manager) CheckAddress(nodeID, address string) error

CheckAddress reports whether nodeID may use address: it is free or already belongs to nodeID. It runs before a join token is spent.

func (*Manager) Remove

func (m *Manager) Remove(ctx context.Context, nodeID, requestedBy string) (Removal, error)

Remove takes a node out of the cluster and revokes its certificates. Nodes are never removed automatically (FA-CLU-08); the caller is a platform admin. Any voter accepts the request: a follower forwards it to the leader, which does the work (RemoveNode). requestedBy is the admin's user ID, for the log only.

func (*Manager) Resume

func (m *Manager) Resume()

Resume continues the promotion of all nonvoters on a new leader.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context, interval time.Duration)

Run calls Resume whenever this node becomes leader.

type Node

type Node interface {
	Raft
	Leader() (address, id string)
	// ApplyLocal proposes a forwarded command on the leader without forwarding it again.
	ApplyLocal(ctx context.Context, cmd *pb.Command) (cluster.ApplyResult, error)
}

Node is the part of cluster.Node the service uses.

type OwnSignals

type OwnSignals struct {
	// Incarnation returns the incarnation of metrics.db.
	Incarnation func() string
	// DiskFreeRatio returns the free share of the data directory, or a
	// negative value if it cannot be measured.
	DiskFreeRatio func() float64
	// WALBytes returns the WAL sizes of state.db and metrics.db.
	WALBytes func() (state, metrics int64)
	// CertNotAfter returns the expiry of the node certificate; zero if there is none.
	CertNotAfter func() time.Time
	// ReplicationLagMs returns the largest lag to a connected peer in
	// milliseconds, -1 if a connected peer never caught up, 0 without peers.
	ReplicationLagMs func() int64
	// Checkpoint returns the index and fingerprint of the last FSM checkpoint.
	Checkpoint func() (index uint64, fingerprint string)
}

OwnSignals are the signals of this node that GetStatus reports (ADR 0025). Each function is optional; a nil one leaves its fields unset, which the leader reads as no signal.

type Raft

type Raft interface {
	IsLeader() bool
	ID() string
	Status() cluster.Status
	Members() ([]cluster.Member, uint64, error)
	AddNonvoter(id, address string, prevIndex uint64, timeout time.Duration) (uint64, error)
	AddVoter(id, address string, prevIndex uint64, timeout time.Duration) (uint64, error)
	RemoveServer(id string, prevIndex uint64, timeout time.Duration) (uint64, error)
	Apply(ctx context.Context, cmd *pb.Command) (cluster.ApplyResult, error)
	Leader() (address, id string)
}

Raft is the part of cluster.Node the manager uses.

type Removal

type Removal struct {
	VotersLeft int
	// Warning is set when the remaining voters tolerate no failure or are an
	// even number.
	Warning string
}

Removal describes the cluster after a removal, for the quorum warning (FA-CLU-08, FA-CLU-11).

type Service

type Service struct {
	pb.UnimplementedClusterServiceServer

	Node      Node
	State     store.State
	Authority *clusterpki.Authority
	Manager   *Manager
	KEK       KEK
	// KEKFingerprint is sent to joining voters, so a voter with an external
	// key can check it uses the same one.
	KEKFingerprint string
	// DialLeader returns a client for the leader at address (mTLS as voter).
	DialLeader func(address string) (pb.ClusterServiceClient, func(), error)
	Log        *slog.Logger
	// Clock is the wall clock of this node, reported in GetStatus; nil means
	// time.Now (ADR 0020).
	Clock func() time.Time
	// SelfCheck returns the latest result of the reference targets of this
	// node (ADR 0022). Nil means no targets are configured.
	SelfCheck func() selfcheck.Status
	// Own reports the signals of this node that the leader evaluates (ADR 0025).
	Own OwnSignals
	// SSRFProtection is whether SSRF protection is on for this node's checks
	// and notifications (ADR 0030); GetStatus reports it.
	SSRFProtection bool
}

Service implements ClusterService on the cluster port.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, req *pb.ApplyRequest) (*pb.ApplyResponse, error)

Apply runs a command forwarded by a follower (FA-CLU-05). Only the leader applies; a follower answers FAILED_PRECONDITION and never forwards again, so forwarding cannot loop.

func (*Service) GetStatus

GetStatus reports this node's Raft state (ADR 0012 A3/A9).

func (*Service) Join

func (s *Service) Join(ctx context.Context, req *pb.JoinRequest) (*pb.JoinResponse, error)

Join enrolls a node with a join token (FA-CLU-03, FA-PKI-02).

func (*Service) RemoveNode

func (s *Service) RemoveNode(ctx context.Context, req *pb.RemoveNodeRequest) (*pb.RemoveNodeResponse, error)

RemoveNode removes a member on the leader for a follower that forwards a platform admin's request (FA-CLU-08). The follower has authorized the admin; requested_by is for the log only. It only calls removeLocal: a follower answers FAILED_PRECONDITION and never forwards again.

func (*Service) RenewCertificate

RenewCertificate issues a new certificate with the caller's identity (FA-PKI-03). It runs on the leader only and re-checks membership and revocation against the state, because the TLS handshake used the cached revocation list.

type StatusFunc

type StatusFunc func(ctx context.Context, address string) (*pb.GetStatusResponse, error)

StatusFunc asks a node for its status over the cluster port (GetStatus).

Jump to

Keyboard shortcuts

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