leader

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 19 Imported by: ? 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.

README

grpcproc/leader

Leader election for grpcproc, and a singleton that runs on the leader only, carrying its state from one leader to the next. A package of grpcproc's, built on its public API alone.

go get github.com/floatdrop/grpcproc/leader
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
    },
})

// on any node that takes part: the singleton, wherever it runs
resp, err := leader.Call[*schedpb.Scheduled](ctx, node, "scheduler", "scheduler", &schedpb.Schedule{…})
info, err := leader.Status(ctx, node, "scheduler") // Role, Term, Leader, View, Singleton, Cordoned

Leadership is the singleton's lifetime

A node that wins an election starts the singleton, an actor.ChildSpec like any other, and a node that stops leading tells it to exit with reason demoted. Its Init is "became leader", its context ending is "stopped being leader", and no handler asks whether it still leads. Its name is registered on the leader's node only, so a call to it on a node that does not lead fails with grpcproc.ErrNoProc; Status says where it runs.

A singleton that exits by itself, or cannot start, ends its node's leadership: the node steps down and campaigns again only after a backoff that doubles with each failure in a row, while the others elect one of themselves. So a failing singleton moves across the cluster rather than restart in place; for restarts in place, make it an actor.ChildSupervisor.

Spec.Confirm runs after a win and before the singleton starts: an error withholds leadership, with the same backoff. It is where leadership waits for an external lock.

The election

One elector process per node, registered as leader/<cluster>, under a supervisor that leader.Start returns (or leader.Child puts in a tree of yours). It is Raft's election without the log:

  • Terms order leaderships. A candidate starts a term and asks for votes; a node votes once per term; a majority makes a leader, which asserts itself with heartbeats every HeartbeatInterval (50ms). A follower that hears none for an ElectionTimeout (150ms, randomized up to twice that) campaigns.
  • Pre-votes come first: a node asks whether it would win before it starts a term, so one cut off from the others does not raise its term alone and depose the leader when it is back.
  • A leader steps down once it has not heard from a majority for two election timeouts; a leader cut off from the others stops acting as one.
  • Followers stick to a leader they heard from within an election timeout, ignoring vote requests, unless the leader handed over (Resign).
  • Sends go through a relay process per peer, which also monitors the peer's elector: a send or monitor that waits for a dial to a node that does not answer holds that relay, never the elector and its heartbeats.
Who votes

With Voters, the view is that fixed set of nodes and a majority of it elects, whether the others are up or not. Two majorities of one set share a node, so a partition never elects two leaders. That is the default to reach for.

Without Voters, the view is dynamic: this node, Peers, and the nodes Membership reports up (with Membership, only those; without it, also any node that talks to this one). Left unset, Membership is the node's own Config.Membership, if it has one. No leader is elected in a view smaller than MinClusterSize (3). The relays' monitors keep it current:

The peer's elector The peer
exits (shutdown, a crash) or never ran (noproc) leaves the view at once
cannot be reached (noconnection) stays, as a ghost, until Membership reports it gone, or for GhostTTL (5s) without Membership
is heard from again is back

A dynamic view trades safety for availability: nodes whose views differ can each count a majority of their own.

A leader's elector that exits (its node stops gracefully) is seen by every follower's monitor at once, and they campaign without waiting out a timeout.

State from one leader to the next

The singleton checkpoints its state through its Lease:

err := lease.Checkpoint(ctx, state) // returns once a majority holds it
lease.Save(state)                   // the same, without the wait

The leader sends it to the followers with its heartbeats, and a follower votes only for a candidate whose state is at least as recent as its own: whichever node leads next starts its singleton from every checkpoint that returned, or a later one. Once the lease's term is over, Checkpoint fails with ErrNotLeader, and nothing a deposed singleton saves reaches anyone.

leader.Resign(ctx, node, cluster) hands over on purpose: the leader stops its singleton (whose Terminate can still checkpoint), waits for the follower with the latest state to hold the leader's, and has it campaign at once. Call it before stopping a leader's node, and the next leader starts from the singleton's last word rather than its last checkpoint.

Keep the state to what the next leader needs to carry on: the jobs a scheduler ran last, not a database. Every checkpoint carries all of it.

Keeping it on disk

Without a Store, terms, votes and state live in memory. A cluster that loses a majority of its nodes at once loses them, and so does a cluster of one at every restart: its singleton starts from nothing, and its terms from zero again. A restarted node, which may have voted before, votes only once it has had time to hear from a leader.

leader.Start(node, leader.Spec[*cronv1.State]{
    Cluster: "cron",
    Voters:  []string{"a", "b", "c"},
    Store:   leader.File("/var/lib/app/cron.election"), // this node's own
    Singleton: …,
})

With a Store, each node keeps its term, its vote and the state, as Raft does. It saves them before anything that tells of them leaves its elector: a vote, an acknowledgement of a checkpoint, a leader's own count of one, a lease. A cluster that restarts whole starts its singleton from the last checkpoint that returned, cordons included; its terms go on growing, so Lease.Term stays a fencing token; and a restarted node votes at once, having forgotten nothing. A Save that fails ends the elector, which its supervisor starts again from what the Store holds; one that cannot be loaded keeps it from starting.

leader.File(path) writes path.tmp, syncs it, renames it over path, and syncs the directory, so a crash leaves the old state or the new one. Each node needs a Store of its own, on its own disk. A shared one breaks the election, and so does a file restored from a backup: it has forgotten votes it cast since. Delete it instead, and the node starts afresh, as one without a Store does.

The elector saves in its own loop, so a save holds up its heartbeats. It saves at elections and checkpoints only, and a local SSD syncs in a millisecond or so, but a disk that stalls for longer than ElectionTimeout (150ms) has the followers campaign: leadership moves, safely, and for nothing. On a slower disk, a cloud volume say, raise ElectionTimeout, and HeartbeatInterval with it; etcd, which syncs the same way, defaults to 1s and 100ms.

The Store is a two-method interface, Load and Save of a few bytes, for anything else that stays on the node.

Calling the leader

scheduled, err := leader.Call[*schedpb.Scheduled](ctx, p, "scheduler", "scheduler", &schedpb.Schedule{…})

calls the process registered as scheduler on whichever node leads scheduler, from a node or from inside a process (p), and follows leadership as it moves. It asks again, for as long as ctx allows, only when the call cannot have reached the singleton:

The call Asked again?
no leader is known yet yes
the node named has no such process: it no longer leads, or has not started its singleton yet yes
never left this node: a *grpcproc.LinkError whose Unsent is set yes
left, and its link broke, or ctx ended, while it waited no: it may have been handled
was answered with an error no: that is the answer

Delivery is at most once, so the choice to repeat a call that may have been handled is the caller's: fine for a read, or for a request the singleton de-duplicates. examples/singleton has a singleton that hands out numbers that never repeat, across a leader crash: each is checkpointed before it is handed out, and callers on every node reach it through leader.Call.

Moving the leader, and taking a node out

leader.Transfer(ctx, node, "scheduler", "b") // b leads next; "" for the most up-to-date follower
leader.Cordon(ctx, node, "scheduler", "c")   // c may not lead: for work on its host
leader.Uncordon(ctx, node, "scheduler", "c")

All three go to whichever node leads, found through node's elector, from any node that takes part. Transfer hands over as Resign does, to the node named: the leader stops its singleton, waits for that follower to hold its state, and has it campaign. It is refused for a node that leads already, is not in the view, or is cordoned, and ends with ErrNoSuccessor if the follower cannot be reached.

Cordon keeps a node from leading until Uncordon: it campaigns no more, voters refuse it, and if it leads, it hands over. The cordoned nodes are part of the state the leader replicates, and Cordon returns once a majority holds it, so a cordon outlasts the cordoned node's restarts and the leader's too: cordon a node, stop it, work on the host, start it again, and it stays a follower until you uncordon it. A cordon that would leave no node of the view to lead is refused. A cordoned node still votes, so a cluster keeps its quorum while one is out.

A node that restarts holds no state, and voters refuse a candidate whose state is older than theirs. So a voter that refuses one sends its own state with the refusal, and the candidate campaigns again with it: a restarted node catches up even when no leader is left to send it anything, as when every other node is cordoned.

Status and the elector's inspect map list the cordoned nodes, and grpcprocctl leader shows the election as every node sees it, and moves the leader or cordons a node from a terminal.

Two leaders

Two nodes can briefly both believe they lead: a leader cut off from the others leads until it notices, two election timeouts at most, while they elect another. Lease.Term grows with every election: a resource that remembers the highest term it has seen can refuse a deposed leader's writes.

Observing it

The elector publishes through its inspect map what grpcprocctl inspect shows: role, term, leader, voted_for, view, quorum, unreachable, state (the version it holds), cordoned, checkpoints_waiting, singleton and backoff. Its relays, starter and membership watch are its children, labelled leader relay, leader starter and leader membership.

A job that runs once in a cluster

grpcproc/cron as the singleton: the cron process runs on the leader, reports each job's last run as its state, and the next leader resumes from it, catching up on what it missed within each job's StartingDeadline.

leader.Start(node, leader.Spec[*cronv1.State]{
    Cluster: "cron",
    Voters:  []string{"a", "b", "c"},
    Singleton: func(l *leader.Lease[*cronv1.State], last *cronv1.State) (actor.ChildSpec, error) {
        return cron.Child("cron", cron.Spec{Jobs: jobs, Resume: last, OnState: l.Save})
    },
})

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

View Source
const ReasonDemoted = "demoted"

ReasonDemoted is the exit reason a singleton is told to exit with when its node stops leading.

Variables

View Source
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

func Cordon(ctx context.Context, n *grpcproc.Node, cluster, node string) error

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

func ElectorName(cluster string) string

ElectorName is the name a cluster's elector is registered under on every node that takes part in it.

func Resign

func Resign(ctx context.Context, n *grpcproc.Node, cluster string) error

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.

func Transfer

func Transfer(ctx context.Context, n *grpcproc.Node, cluster, to string) error

Transfer moves the leadership of cluster to the node to: the leader, which n's elector names, hands over to it as Resign does, once to holds its state. to must be in the leader's view, and not cordoned.

func Uncordon

func Uncordon(ctx context.Context, n *grpcproc.Node, cluster, node string) error

Uncordon lets node lead cluster again.

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.

func Status

func Status(ctx context.Context, n *grpcproc.Node, cluster string) (Info, error)

Status asks n's elector for cluster what it believes.

type Lease

type Lease[S proto.Message] struct {
	// contains filtered or unexported fields
}

Lease is a leader's hold on its term, as its singleton sees it.

func (*Lease[S]) Checkpoint

func (l *Lease[S]) Checkpoint(ctx context.Context, state S) error

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.

func (*Lease[S]) Save

func (l *Lease[S]) Save(state S)

Save is Checkpoint without the wait, for a caller that must not block: state is replicated, and the next leader starts from it if a majority held it by then. Once the term is over it is dropped.

func (*Lease[S]) Term

func (l *Lease[S]) Term() uint64

Term is the term this node leads in. Terms grow with every election, so it is a fencing token: a resource that remembers the highest it has seen can refuse a deposed leader's writes.

type Role

type Role uint8

Role is what an elector is to its cluster.

const (
	// Unclustered: the view is smaller than MinClusterSize, and nobody
	// may be elected.
	Unclustered Role = iota
	// Follower: following a leader, or waiting to campaign.
	Follower
	// Candidate: campaigning.
	Candidate
	// Leader: elected, and running the singleton.
	Leader
)

func (Role) String

func (r Role) String() string

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.

func File

func File(path string) Store

File is a Store in the file at path. Save writes path+".tmp", syncs it to disk and renames it over path, so a crash leaves the old state or the new one, and at most the one temporary file beside it, which the next Save overwrites.

Directories

Path Synopsis
proto

Jump to

Keyboard shortcuts

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