Documentation
¶
Overview ¶
Package leader elects one node of a cluster to run a singleton: a child spec that runs on the leader only, started when its node wins an election and told to exit when it loses. Leadership is the singleton's lifetime: its Init runs on becoming leader, its context ends on losing it, and no handler has to ask whether it still leads.
leader.Start(node, leader.Spec[*schedpb.State]{
Cluster: "scheduler",
Voters: []string{"a", "b", "c"},
Singleton: func(l *leader.Lease[*schedpb.State], last *schedpb.State) (actor.ChildSpec, error) {
return actor.Child("scheduler", func() *Scheduler { return &Scheduler{lease: l, state: last} }), nil
},
})
The election is Raft's without the log: terms, votes and heartbeats between one elector process per node, registered as ElectorName(cluster). A node leads with the votes of a majority, and steps down once it has not heard from a majority for two election timeouts.
The singleton can carry state across leaders. Lease.Checkpoint replicates its state to the followers and returns once a majority holds it; a follower votes only for a candidate whose state is at least as recent as its own, so whichever node leads next starts its singleton from every checkpoint that returned. Resign hands over on purpose: it stops the singleton, brings a follower up to date and has it campaign at once.
Terms, votes and state live in memory, and a cluster that loses a majority of its nodes at once loses them, unless Spec.Store keeps them: then each node saves its own before it tells anyone of them, as Raft does, and a cluster that restarts whole carries on from where it was (File keeps them in a file). Two nodes may briefly both believe they lead (one cut off from the others that has not noticed yet); Lease.Term is the fencing token that lets an external resource tell their writes apart, and Spec.Confirm can make leadership wait for an external lock.
Index ¶
- Constants
- Variables
- func Call[R, M proto.Message](ctx context.Context, from grpcproc.Caller, cluster, name string, req M) (R, error)
- func Child[S proto.Message](name string, spec Spec[S], opts ...grpcproc.SpawnOption) (actor.ChildSpec, error)
- func Cordon(ctx context.Context, n *grpcproc.Node, cluster, node string) error
- func ElectorName(cluster string) string
- func Resign(ctx context.Context, n *grpcproc.Node, cluster string) error
- func Start[S proto.Message](n *grpcproc.Node, spec Spec[S], opts ...grpcproc.SpawnOption) (grpcproc.PID, error)
- func Transfer(ctx context.Context, n *grpcproc.Node, cluster, to string) error
- func Uncordon(ctx context.Context, n *grpcproc.Node, cluster, node string) error
- type Info
- type Lease
- type Role
- type Spec
- type Store
Constants ¶
const ReasonDemoted = "demoted"
ReasonDemoted is the exit reason a singleton is told to exit with when its node stops leading.
Variables ¶
var ( // ErrNotLeader is the answer to Checkpoint once the Lease's term is // over, and to Resign on a node that does not lead. ErrNotLeader = errors.New("leader: not the leader") // ErrNoSuccessor is Resign's answer on a leader with no follower to // hand over to (Transfer's, when its follower did not catch up): it // stepped down, and campaigns again after a backoff. ErrNoSuccessor = errors.New("leader: no follower to hand over to") // ErrNoLeader is the answer of Transfer, Cordon and Uncordon while the // node asked knows of no leader. ErrNoLeader = errors.New("leader: no leader is known") )
An elector's answers cross nodes as text: they come back as a *grpcproc.RemoteError, which is the sentinel to errors.Is.
Functions ¶
func Call ¶
func Call[R, M proto.Message](ctx context.Context, from grpcproc.Caller, cluster, name string, req M) (R, error)
Call calls the process registered as name on whichever node leads cluster, the singleton, with req, and returns its answer, typed as R:
scheduled, err := leader.Call[*schedpb.Scheduled](ctx, p, "scheduler", "scheduler", &schedpb.Schedule{…})
from is who calls, a *grpcproc.Node or a *grpcproc.Process from inside its handler, as for grpcproc.Addr.Call; its node's elector for cluster says who leads, and must run.
Leadership moves, and Call follows it, asking again for as long as ctx allows, but only when the call cannot have reached the singleton: while no leader is known, when the node named has no process called name (it no longer leads, or has not started its singleton yet), or when the call never left this node (a *grpcproc.LinkError whose Unsent is set). A call that did leave may have been handled, and delivery is at most once: if its link breaks, or ctx ends while it waits, Call returns that error rather than call again, and the caller decides whether the request is safe to repeat. An answer that is an error is returned as it is.
func Child ¶
func Child[S proto.Message](name string, spec Spec[S], opts ...grpcproc.SpawnOption) (actor.ChildSpec, error)
Child is Start for a supervisor: a child, registered as name unless name is empty, that runs its node's part in spec's election.
func Cordon ¶
Cordon keeps node from leading cluster, until Uncordon: it campaigns no more, voters refuse it, and if it leads, it hands over. The leader, which n's elector names, records it in the state it replicates, and Cordon returns once a majority holds it: node stays cordoned across its own restarts, and across leaders. It is for taking a host out of the running, to work on it. A cordon that would leave no node of the view to lead is refused.
func ElectorName ¶
ElectorName is the name a cluster's elector is registered under on every node that takes part in it.
func Resign ¶
Resign has the leader of cluster, on n, hand over: it stops its singleton, whose Terminate may still checkpoint, brings the follower with the latest state up to date, and has it campaign at once. It returns once the follower has been told to, with ErrNotLeader if n does not lead. Call it before stopping a leader's node, for the next leader to start from the singleton's last state.
func Start ¶
func Start[S proto.Message](n *grpcproc.Node, spec Spec[S], opts ...grpcproc.SpawnOption) (grpcproc.PID, error)
Start runs n's part in spec's election: a supervisor, whose opts these are, of the elector and, while n leads, the singleton. It returns the supervisor.
Types ¶
type Info ¶
type Info struct {
Role Role
Term uint64
// Leader is the leader's node, or empty while none is known.
Leader string
// View is the nodes whose majority elects a leader, this one included,
// sorted.
View []string
Quorum int
// Singleton is the singleton, on the leader, once it runs.
Singleton grpcproc.PID
// Cordoned is the nodes that may not lead, sorted.
Cordoned []string
}
Info is what a node's elector believes.
type Lease ¶
Lease is a leader's hold on its term, as its singleton sees it.
func (*Lease[S]) Checkpoint ¶
Checkpoint replicates state to the cluster's other electors, and returns once a majority of the cluster holds it: from then on whichever node leads next starts its singleton from it, or from a later one. It fails with ErrNotLeader once the term is over.
type Spec ¶
type Spec[S proto.Message] struct { // Cluster names the election: every node that runs one of that name // takes part in it. Required. Cluster string // Voters, if set, is the fixed set of nodes whose majority elects a // leader, this node among them. A voter that is down still counts: // two majorities of one set always share a node, so no partition can // elect two leaders. Voters []string // Peers, with Voters empty, are nodes taken to take part, from the // start. They and the nodes Membership reports make the view: a // majority of the view elects a leader. A node that runs no elector // for Cluster leaves the view as soon as that is known, and so does // one whose elector exits; one that cannot be reached stays in it for // GhostTTL, or until Membership reports it gone. Without Membership, // a node that talks to this one joins it. Peers []string // Membership, with Voters empty, reports the nodes of the grpcproc // cluster: each one it reports up joins the view, and each one it // reports down leaves it. Only those it reports up, and Peers, take // part. Unset, it is the node's own Config.Membership, if the node has // one, so the cluster the node follows is the one given once. Membership grpcproc.Membership // MinClusterSize is the smallest view, this node included, that may // elect a leader, with Voters empty. Default 3. MinClusterSize int // ElectionTimeout is how long a follower goes without hearing from a // leader before it campaigns: a random time between it and twice it. // Default 150ms. ElectionTimeout time.Duration // HeartbeatInterval is how often a leader asserts itself. It must be // shorter than ElectionTimeout. Default 50ms. HeartbeatInterval time.Duration // GhostTTL is how long a node of the view that cannot be reached still // counts, with Voters empty and no Membership. Default 5s. GhostTTL time.Duration // Store, if set, keeps this node's term, vote and state across restarts // of its elector and of the node (File keeps them in a file): with one // on every node, a cluster that restarts whole starts again from its // last checkpoint, and its terms go on growing. Without it they live in // memory. A Save that fails ends the elector, and its supervisor starts // it again from what the Store holds. Saves hold up the elector's // heartbeats: on a disk that may stall for longer than // ElectionTimeout, raise it. Store Store // Confirm, if set, runs when this node wins an election, before its // singleton starts: an error withholds leadership, and the node steps // down and campaigns again only after a backoff, longer after each // failure in a row. It is where leadership waits for an external lock // (an etcd lease, a Kubernetes Lease). Confirm func(ctx context.Context, term uint64) error // Singleton builds what runs on the leader, given the state the last // leader checkpointed (the zero S before any has). Required. Its // Restart is Temporary whatever it says: a singleton that exits ends // its node's leadership, and runs again wherever the next election // says, after the same backoff as Confirm's. For restarts in place, // make it an actor.ChildSupervisor. Singleton func(l *Lease[S], state S) (actor.ChildSpec, error) }
Spec describes a node's part in a cluster's election, and what runs on the leader. S is the singleton's state: proto.Message for any, or emptypb.Empty for none.
type Store ¶
type Store interface {
// Load returns what Save saved last, or nothing if it never did.
Load() ([]byte, error)
// Save replaces what is saved with b, and returns once that would
// outlast a crash of the machine.
Save(b []byte) error
}
A Store keeps a node's part in an election across restarts of its elector, and of the node: the term, its vote in it, and the singleton's state. An elector saves to it before anything that tells of them leaves it, as Raft does, so with a Store on every node a cluster that loses a majority of its nodes at once, or all of them, carries on from where it was. Each node needs its own, on its own disk: a Store that nodes share breaks the election, and so does one restored from a backup.