diff --git a/leader/README.md b/leader/README.md index 75368e0..19e3cd4 100644 --- a/leader/README.md +++ b/leader/README.md @@ -400,6 +400,10 @@ shows: `role`, `term`, `leader`, `voted_for`, `view`, `quorum`, membership watch are its children, labelled `leader relay`, `leader starter` and `leader membership`. +[grpcproc/otel](../otel/README.md#leader-elections)'s `ObserveLeader` turns +it into gauges on every node, to alert on: no leader or two, a singleton that +runs nowhere, a view one node short of losing its majority. + ## A job that runs once in a cluster [grpcproc/cron](../cron/README.md) as the singleton: the cron process runs on diff --git a/otel/README.md b/otel/README.md index 0db0eec..9da143e 100644 --- a/otel/README.md +++ b/otel/README.md @@ -14,6 +14,8 @@ h, err := grpcprocotel.New() // global meter/tracer providers and propagator; se node, err := grpcproc.NewNode(grpcproc.Config{…, Hooks: grpcproc.JoinHooks(h, myHooks)}) reg, err := h.Observe(node) // gauges read from node snapshots at each collection defer reg.Unregister() +lreg, err := h.ObserveLeader(node) // gauges of the node's grpcproc/leader elections +defer lreg.Unregister() ``` ## Traces @@ -71,3 +73,57 @@ mailbox was full: `WithMailboxLimit`), `too_large` (the message, or the reply, was over `Config.MaxMessageSize`), `busy` (the link to the peer was full: `Config.MaxQueued`), `noconnection`, `timeout`, `canceled`, `remote` (the handler returned an error), `other`. + +## Leader elections + +`ObserveLeader` reads each [grpcproc/leader](../leader/README.md) elector on +the node, the processes named `leader.ElectorName(cluster)` with its label, +at each collection, from its inspect map, and reports one set of gauges per +election, by `grpcproc.leader.cluster`. The electors are asked at once. One +that the node's snapshot shows on one message for a second (busy in a slow +`Store`, say), or that does not answer within a second of a collection that +lasts that long, is reported as stalled, with no other gauge. + +| Name | What it says | +| --- | --- | +| `grpcproc.leader.electors` | 1, with `grpcproc.leader.role`: `leader`, `candidate`, `follower` or `unclustered` | +| `grpcproc.leader.stalled` | 1 while the elector is on one message for a second or more, or does not answer within one; 0 while it answers | +| `grpcproc.leader.term` | the elector's term | +| `grpcproc.leader.view`, `grpcproc.leader.quorum` | the nodes whose majority elects, and how many that majority is | +| `grpcproc.leader.reachable` | the nodes of the view it hears from, itself included | +| `grpcproc.leader.singleton` | 1 while the singleton runs on this node | +| `grpcproc.leader.checkpoints.waiting` | `Checkpoint` calls waiting for a majority to hold their state | + +Alerts per cluster, in PromQL, with the names as the Prometheus exporter +writes them: dots turned to underscores, and a unit suffix where there is one: + +```promql +# No leader: the leaders, with a 0 for every elector, so that none adds up to 0. +# A cluster below MinClusterSize has none by design: its electors are unclustered. +sum by (grpcproc_leader_cluster) (grpcproc_leader_electors{grpcproc_leader_role="leader"} or grpcproc_leader_electors * 0) < 1 +# No node of a cluster reporting at all: one rule per cluster. +absent(grpcproc_leader_electors{grpcproc_leader_cluster="scheduler"}) +# Two leaders: a leader cut off from the others has not noticed. +sum by (grpcproc_leader_cluster) (grpcproc_leader_electors{grpcproc_leader_role="leader"}) > 1 +# The singleton runs nowhere, or twice. +sum by (grpcproc_leader_cluster) (grpcproc_leader_singleton) != 1 +# One more node lost and this side has no majority; below it, none can be elected. +# A view of one or two never has a node to spare. +grpcproc_leader_reachable <= grpcproc_leader_quorum and grpcproc_leader_view >= 3 +# Elections keep happening. +changes(max by (grpcproc_leader_cluster) (grpcproc_leader_term)[15m:]) > 3 +# A majority is not taking the leader's state. +grpcproc_leader_checkpoints_waiting > 0 +# An elector held up for a second or more, which sends no heartbeat or vote meanwhile. +grpcproc_leader_stalled > 0 +``` + +Give each a `for:` of a few scrape intervals, a minute say: an election, and +a hand-over (`Resign` stops the old singleton before the next leader starts +its own), leave no leader or no singleton for a moment, and a leader cut off +from the others leads for up to two election timeouts after they elect +another. A stalled elector is in none of the sums: when the leader is the one +held up, the other nodes' gauges show no leader, and with no other node +reporting the sums are empty, which only "stalled" alerts on. A second is +fixed: with an `ElectionTimeout` above it, a `Store` slow enough to be stalled +can still be within it, so give "stalled" a `for:` longer than the timeout. diff --git a/otel/go.mod b/otel/go.mod index 2051b5c..f76aa78 100644 --- a/otel/go.mod +++ b/otel/go.mod @@ -20,6 +20,7 @@ require ( require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/floatdrop/fsm v0.8.0 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/google/uuid v1.6.0 // indirect diff --git a/otel/go.sum b/otel/go.sum index 73333c3..7e1ce01 100644 --- a/otel/go.sum +++ b/otel/go.sum @@ -1,5 +1,7 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/floatdrop/fsm v0.8.0 h1:jzK/vv5BYLrlT2/UJ7Hr8SsCxEtOOvVv/CzOoCwclUE= +github.com/floatdrop/fsm v0.8.0/go.mod h1:omx7JkDDk097D1d1WkBuafEi8sDEJq+15cR++gnuyS4= github.com/floatdrop/grpcproc v0.13.0 h1:3tgmY5q41s5y+JA0Yi/FM77Rw03UuDoS5H78ioshWKw= github.com/floatdrop/grpcproc v0.13.0/go.mod h1:BERDv3Ikxz+R+UB1x+1Yiu52u3WIcigwhNensEufiuQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= diff --git a/otel/leader.go b/otel/leader.go new file mode 100644 index 0000000..aef1c22 --- /dev/null +++ b/otel/leader.go @@ -0,0 +1,122 @@ +package grpcprocotel + +import ( + "context" + "errors" + "strconv" + "strings" + "sync" + "time" + + "go.opentelemetry.io/otel/metric" + + "github.com/floatdrop/grpcproc" + "github.com/floatdrop/grpcproc/leader" +) + +// The inspect map's keys, the label and the PID's form are leader's, not +// its API: TestObserveLeader, against the core this module requires, is what +// notices a change to them. +const ( + // inspectTimeout bounds how long a collection waits for the electors. + inspectTimeout = time.Second + // electorLabel is the label grpcproc/leader gives its electors. + electorLabel = "leader" +) + +// errStalled ends the wait for electors that do not answer in time. +var errStalled = errors.New("grpcprocotel: the elector did not answer in time") + +// ObserveLeader registers gauges read at each collection from the electors +// of grpcproc/leader on node, by grpcproc.leader.cluster: one set for each +// election the node takes part in when the collection runs. They come from +// what each elector publishes through its inspect map: its role (1, with +// grpcproc.leader.role), its term, the nodes of its view, the quorum, how many +// of the view it hears from, itself included, whether the singleton runs on +// this node, and how many Checkpoint calls wait for a majority. The electors +// are asked at once. One that the node's snapshot shows on one message for a +// second, busy in a slow Store say, or that does not answer within a second +// of a collection that lasts that long, is reported as stalled, with no other +// gauge. Unregister the returned registration when the node stops. +func (h *Hooks) ObserveLeader(node *grpcproc.Node) (metric.Registration, error) { + var errs []error + electors := h.gauge(&errs, "grpcproc.leader.electors", "1 for this node's elector, by cluster and role.", "{elector}") + stalled := h.gauge(&errs, "grpcproc.leader.stalled", "1 while the elector is on one message for a second or more, or does not answer within one, by cluster.", "{elector}") + term := h.gauge(&errs, "grpcproc.leader.term", "The elector's term, by cluster.", "{term}") + view := h.gauge(&errs, "grpcproc.leader.view", "Nodes whose majority elects, by cluster.", "{node}") + quorum := h.gauge(&errs, "grpcproc.leader.quorum", "Nodes that make a majority of the view, by cluster.", "{node}") + reachable := h.gauge(&errs, "grpcproc.leader.reachable", "Nodes of the view the elector hears from, itself included, by cluster.", "{node}") + singleton := h.gauge(&errs, "grpcproc.leader.singleton", "1 while the singleton runs on this node, by cluster.", "{process}") + waiting := h.gauge(&errs, "grpcproc.leader.checkpoints.waiting", "Checkpoint calls waiting for a majority to hold their state, by cluster.", "{checkpoint}") + if err := errors.Join(errs...); err != nil { + return nil, err + } + + type answer struct { + cluster string + stalled bool + m map[string]string + err error + } + prefix := leader.ElectorName("") + return h.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error { + ictx, cancel := context.WithTimeoutCause(ctx, inspectTimeout, errStalled) + defer cancel() + var answers []*answer + var wg sync.WaitGroup + for _, p := range node.Processes() { + cluster, ok := strings.CutPrefix(p.Name, prefix) + if !ok || p.Label != electorLabel || p.State == grpcproc.StateExiting { + continue + } + a := &answer{cluster: cluster, stalled: p.BusyFor >= inspectTimeout} + answers = append(answers, a) + if !a.stalled { + wg.Go(func() { + a.m, a.err = node.Inspect(ictx, p.PID) + a.stalled = a.err != nil && errors.Is(context.Cause(ictx), errStalled) // not ended by the collection + }) + } + } + wg.Wait() + for _, a := range answers { + attrs := metric.WithAttributes(AttrCluster.String(a.cluster)) + switch { + case a.stalled: + o.ObserveInt64(stalled, 1, attrs) + continue + case a.err != nil: + continue // exited since the snapshot, or the collection ended first + case a.m["role"] == "": + continue // a process of that name and label that is no elector + } + o.ObserveInt64(electors, 1, metric.WithAttributes(AttrCluster.String(a.cluster), AttrRole.String(a.m["role"]))) + o.ObserveInt64(stalled, 0, attrs) + o.ObserveInt64(term, number(a.m["term"]), attrs) + o.ObserveInt64(view, count(a.m["view"]), attrs) + o.ObserveInt64(quorum, number(a.m["quorum"]), attrs) + o.ObserveInt64(reachable, count(a.m["view"])-count(a.m["unreachable"]), attrs) + running := int64(0) + if strings.HasPrefix(a.m["singleton"], "<") { // its PID; a phase otherwise + running = 1 + } + o.ObserveInt64(singleton, running, attrs) + o.ObserveInt64(waiting, number(a.m["checkpoints_waiting"]), attrs) + } + return nil + }, electors, stalled, term, view, quorum, reachable, singleton, waiting) +} + +// number is an inspect value as a number, 0 if absent. +func number(s string) int64 { + n, _ := strconv.ParseInt(s, 10, 64) + return n +} + +// count is how many nodes an inspect list names. +func count(list string) int64 { + if list == "" { + return 0 + } + return int64(strings.Count(list, ",") + 1) +} diff --git a/otel/leader_test.go b/otel/leader_test.go new file mode 100644 index 0000000..4901564 --- /dev/null +++ b/otel/leader_test.go @@ -0,0 +1,222 @@ +package grpcprocotel_test + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/sdk/metric/metricdata" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/emptypb" + + "github.com/floatdrop/grpcproc" + "github.com/floatdrop/grpcproc/actor" + "github.com/floatdrop/grpcproc/grpcproctest" + "github.com/floatdrop/grpcproc/leader" + grpcprocotel "github.com/floatdrop/grpcproc/otel" +) + +func idle(*leader.Lease[*emptypb.Empty], *emptypb.Empty) (actor.ChildSpec, error) { + return actor.ChildFunc("singleton", func(p *grpcproc.Process[proto.Message]) error { + for { + if _, err := p.Receive(); err != nil { + return err + } + } + }), nil +} + +// Each node's gauges say what its elector believes: one leader among them, +// running the singleton, in the term they all agree on, and a view that +// shrinks to what the leader hears from once a node is gone. +func TestObserveLeader(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + c := grpcproctest.New(t, "a", "b", "c") + envs := map[string]env{} + for _, name := range []string{"a", "b", "c"} { + e := setup(t) + reg, err := e.hooks.ObserveLeader(c.Node(name)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = reg.Unregister() }) + if _, err := leader.Start(c.Node(name), leader.Spec[*emptypb.Empty]{Cluster: "test", Voters: []string{"a", "b", "c"}, Singleton: idle}); err != nil { + t.Fatal(err) + } + envs[name] = e + } + // None is an elector: one is not labelled as one, one publishes + // nothing, and one exits when asked. + for _, opts := range [][]grpcproc.SpawnOption{ + {grpcproc.WithName(leader.ElectorName("unlabelled"))}, + {grpcproc.WithName(leader.ElectorName("silent")), grpcproc.WithLabel("leader")}, + {grpcproc.WithName(leader.ElectorName("exits")), grpcproc.WithLabel("leader"), grpcproc.WithInspect(func() map[string]string { panic("asked") })}, + } { + if _, err := c.Node("a").Spawn(func(p *grpcproc.Process[proto.Message]) error { + _, err := p.Receive() + return err + }, opts...); err != nil { + t.Fatal(err) + } + } + time.Sleep(5 * time.Second) + synctest.Wait() + for _, other := range []string{"unlabelled", "silent", "exits"} { + rm := collect(t, envs["a"].reader) + if got := intValue(rm, "grpcproc.leader.electors", grpcprocotel.AttrCluster.String(other)) + intValue(rm, "grpcproc.leader.stalled", grpcprocotel.AttrCluster.String(other)); got != 0 { + t.Errorf("%s observed as an elector: %d", other, got) + } + } + + cluster := grpcprocotel.AttrCluster.String("test") + gauge := func(node, name string, attrs ...attribute.KeyValue) int64 { + return intValue(collect(t, envs[node].reader), name, append(attrs, cluster)...) + } + info, err := leader.Status(t.Context(), c.Node("a"), "test") + if err != nil || info.Leader == "" { + t.Fatalf("status %+v, %v", info, err) + } + for _, node := range []string{"a", "b", "c"} { + role := leader.Follower + if node == info.Leader { + role = leader.Leader + } + running := int64(0) + if role == leader.Leader { + running = 1 + } + checks := []struct { + name string + attrs []attribute.KeyValue + want int64 + }{ + {"grpcproc.leader.electors", []attribute.KeyValue{grpcprocotel.AttrRole.String(role.String())}, 1}, + {"grpcproc.leader.electors", nil, 1}, // one role at a time + {"grpcproc.leader.stalled", nil, 0}, + {"grpcproc.leader.term", nil, int64(info.Term)}, + {"grpcproc.leader.view", nil, 3}, + {"grpcproc.leader.quorum", nil, 2}, + {"grpcproc.leader.reachable", nil, 3}, + {"grpcproc.leader.singleton", nil, running}, + {"grpcproc.leader.checkpoints.waiting", nil, 0}, + } + for _, ch := range checks { + if got := gauge(node, ch.name, ch.attrs...); got != ch.want { + t.Errorf("%s: %s%v = %d, want %d", node, ch.name, ch.attrs, got, ch.want) + } + } + } + + gone := "a" + if info.Leader == "a" { + gone = "b" + } + c.Kill(gone) + time.Sleep(5 * time.Second) + synctest.Wait() + if got := gauge(info.Leader, "grpcproc.leader.reachable"); got != 2 { + t.Errorf("reachable with %s gone = %d, want 2", gone, got) + } + if got := gauge(info.Leader, "grpcproc.leader.view"); got != 3 { + t.Errorf("view with %s gone = %d, want 3", gone, got) + } + }) +} + +// stalled is a Store whose Save waits while it is held. +type stalled struct { + held atomic.Bool + release chan struct{} +} + +func (*stalled) Load() ([]byte, error) { return nil, nil } + +func (s *stalled) Save([]byte) error { + if s.held.Load() { + <-s.release + } + return nil +} + +// An elector held up by its Store is reported as stalled, with no other +// gauge, rather than holding the collection up: the first time after the +// second it is given to answer, then at once, as the node's snapshot says +// how long it has been on one message. A collection that ends sooner +// reports nothing of it. +func TestObserveLeaderStalled(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := setup(t) + c := grpcproctest.New(t, "a") + reg, err := e.hooks.ObserveLeader(c.Node("a")) + if err != nil { + t.Fatal(err) + } + defer func() { _ = reg.Unregister() }() + store := &stalled{release: make(chan struct{})} + if _, err := leader.Start(c.Node("a"), leader.Spec[*emptypb.Empty]{Cluster: "test", Voters: []string{"a"}, Store: store, Singleton: idle}); err != nil { + t.Fatal(err) + } + time.Sleep(time.Second) + synctest.Wait() + gauges := func(when string, electors, stall int64, wait time.Duration) { + t.Helper() + start := time.Now() + rm := collect(t, e.reader) + if got := intValue(rm, "grpcproc.leader.electors"); got != electors { + t.Errorf("%s: electors = %d, want %d", when, got, electors) + } + if got := intValue(rm, "grpcproc.leader.stalled"); got != stall { + t.Errorf("%s: stalled = %d, want %d", when, got, stall) + } + if waited := time.Since(start); waited != wait { + t.Errorf("%s: the collection waited %v, want %v", when, waited, wait) + } + } + gauges("answering", 1, 0, 0) + + // It steps down, campaigns again after a backoff, and stalls saving + // its vote. + store.held.Store(true) + if err := leader.Resign(t.Context(), c.Node("a"), "test"); !errors.Is(err, leader.ErrNoSuccessor) { + t.Fatalf("resign: %v", err) + } + for i := 0; ; i++ { + if p, ok := c.Node("a").Process(pidOf(t, c.Node("a"))); ok && p.BusyFor > 0 && p.State == grpcproc.StateRunning { + break + } + if i == 1000 { + t.Fatal("the elector did not stall") + } + time.Sleep(10 * time.Millisecond) + } + // A collection that ends first reports it as nothing. + short, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) + var rm metricdata.ResourceMetrics + _ = e.reader.Collect(short, &rm) + cancel() + if got := intValue(rm, "grpcproc.leader.stalled") + intValue(rm, "grpcproc.leader.electors"); got != 0 { + t.Errorf("a collection that ended first: %d", got) + } + gauges("stalled, asked", 0, 1, time.Second) + gauges("stalled, from the snapshot", 0, 1, 0) + + store.held.Store(false) + close(store.release) + time.Sleep(time.Second) + synctest.Wait() + gauges("answering again", 1, 0, 0) + }) +} + +func pidOf(t *testing.T, n *grpcproc.Node) grpcproc.PID { + t.Helper() + pid, ok := n.Whereis(leader.ElectorName("test")) + if !ok { + t.Fatal("no elector") + } + return pid +} diff --git a/otel/observe.go b/otel/observe.go index fde5516..d6bd5ab 100644 --- a/otel/observe.go +++ b/otel/observe.go @@ -22,13 +22,8 @@ import ( // returned registration when the node stops. func (h *Hooks) Observe(node *grpcproc.Node) (metric.Registration, error) { var errs []error - gauge := func(name, desc, unit string) metric.Int64ObservableGauge { - g, err := h.meter.Int64ObservableGauge(name, metric.WithDescription(desc), metric.WithUnit(unit)) - errs = append(errs, err) - return g - } - processes := gauge("grpcproc.processes", "Live processes, by label.", "{process}") - depth := gauge("grpcproc.mailbox.depth", "Messages waiting in mailboxes, summed by label.", "{message}") + processes := h.gauge(&errs, "grpcproc.processes", "Live processes, by label.", "{process}") + depth := h.gauge(&errs, "grpcproc.mailbox.depth", "Messages waiting in mailboxes, summed by label.", "{message}") oldest, err := h.meter.Float64ObservableGauge("grpcproc.mailbox.oldest", metric.WithDescription("Age of the oldest waiting message, the maximum by label."), metric.WithUnit("s")) errs = append(errs, err) @@ -111,3 +106,10 @@ func (h *Hooks) Observe(node *grpcproc.Node) (metric.Registration, error) { return nil }, processes, depth, oldest, linkMessages, linkBytes) } + +// gauge makes an int64 gauge, adding its error to errs. +func (h *Hooks) gauge(errs *[]error, name, desc, unit string) metric.Int64ObservableGauge { + g, err := h.meter.Int64ObservableGauge(name, metric.WithDescription(desc), metric.WithUnit(unit)) + *errs = append(*errs, err) + return g +} diff --git a/otel/otel.go b/otel/otel.go index 253ce55..eb88183 100644 --- a/otel/otel.go +++ b/otel/otel.go @@ -6,6 +6,8 @@ // node, err := grpcproc.NewNode(grpcproc.Config{…, Hooks: h}) // reg, err := h.Observe(node) // gauges from snapshots // defer reg.Unregister() +// lreg, err := h.ObserveLeader(node) // grpcproc/leader elections, if any +// defer lreg.Unregister() // // Inside a handler, h.Extract(ctx, m.Metadata) is a context whose span is the // one handling m, for the handler's own spans (a database call, an HTTP @@ -44,7 +46,9 @@ const ( AttrMessageType = attribute.Key("grpcproc.message.type") AttrPeer = attribute.Key("grpcproc.peer") AttrDirection = attribute.Key("grpcproc.direction") - AttrPID = attribute.Key("grpcproc.pid") // spans only + AttrCluster = attribute.Key("grpcproc.leader.cluster") // ObserveLeader + AttrRole = attribute.Key("grpcproc.leader.role") // ObserveLeader's grpcproc.leader.electors + AttrPID = attribute.Key("grpcproc.pid") // spans only AttrErrorType = attribute.Key("error.type") ) diff --git a/otel/otel_test.go b/otel/otel_test.go index b2bfd9a..e21af39 100644 --- a/otel/otel_test.go +++ b/otel/otel_test.go @@ -465,6 +465,9 @@ func TestInstrumentErrors(t *testing.T) { if _, err := h.Observe(c.Node("a")); !errors.Is(err, errNoInstruments) { t.Fatalf("Observe: %v", err) } + if _, err := h.ObserveLeader(c.Node("a")); !errors.Is(err, errNoInstruments) { + t.Fatalf("ObserveLeader: %v", err) + } } type observeFailing struct{ noop.MeterProvider } diff --git a/site/src/content/guides-leader.tsx b/site/src/content/guides-leader.tsx index c2d144e..df6e81e 100644 --- a/site/src/content/guides-leader.tsx +++ b/site/src/content/guides-leader.tsx @@ -408,6 +408,11 @@ c follower 2 a a,b,c 2.3 b none`}leader relay; the process that starts the singleton, leader starter; and the watch of a Membership, leader membership.

+

+ grpcproc/otel's ObserveLeader turns what + every node's elector publishes into gauges, to alert on: no leader or two, a singleton + that runs nowhere, a view one node short of losing its majority. +

) } diff --git a/site/src/content/guides-observability.tsx b/site/src/content/guides-observability.tsx index 3e4a464..39c04ca 100644 --- a/site/src/content/guides-observability.tsx +++ b/site/src/content/guides-observability.tsx @@ -289,7 +289,9 @@ go tool pprof -tagfocus=grpcproc.label=ledger http://localhost:6060/debug/pprof/ {`h, err := grpcprocotel.New() // global meter and tracer providers and propagator; see Options node, err := grpcproc.NewNode(grpcproc.Config{…, Hooks: grpcproc.JoinHooks(h, myHooks)}) reg, err := h.Observe(node) // gauges read from node snapshots at each collection -defer reg.Unregister()`} +defer reg.Unregister() +lreg, err := h.ObserveLeader(node) // gauges of the node's grpcproc/leader elections +defer lreg.Unregister()`}

Traces

noconnection, timeout, canceled, remote (the handler returned an error) or other. Errors and exit reasons says what each means.

+

Leader elections

+

+ ObserveLeader reads each grpcproc/leader elector on the + node, the processes named leader.ElectorName(cluster) with its label, at each + collection, from its inspect map, and reports one set + of gauges per election, by grpcproc.leader.cluster. The electors are asked at once. + One that the node's snapshot shows on one message for a second, busy in a slow{' '} + Store say, or that does not answer within a second of a collection that lasts that + long, is reported as stalled, with no other gauge. +

+
grpcproc.leader.electors, <> + 1, with grpcproc.leader.role: leader, candidate, follower or{' '} + unclustered + ], + [grpcproc.leader.stalled, <> + 1 while the elector is on one message for a second or more, or does not answer within + one; 0 while it answers. + ], + [grpcproc.leader.term, "The elector's term."], + [<> + grpcproc.leader.view, grpcproc.leader.quorum + , 'The nodes whose majority elects, and how many that majority is.'], + [grpcproc.leader.reachable, 'The nodes of the view it hears from, itself included.'], + [grpcproc.leader.singleton, '1 while the singleton runs on this node.'], + [grpcproc.leader.checkpoints.waiting, <> + Checkpoint calls waiting for a majority to hold their state. + ] + ]} + /> +

+ Alerts per cluster, in PromQL, with the names as the Prometheus exporter writes them: dots + turned to underscores, and a unit suffix where there is one: +

+ {`# No leader: the leaders, with a 0 for every elector, so that none adds up to 0. +# A cluster below MinClusterSize has none by design: its electors are unclustered. +sum by (grpcproc_leader_cluster) (grpcproc_leader_electors{grpcproc_leader_role="leader"} or grpcproc_leader_electors * 0) < 1 +# No node of a cluster reporting at all: one rule per cluster. +absent(grpcproc_leader_electors{grpcproc_leader_cluster="scheduler"}) +# Two leaders: a leader cut off from the others has not noticed. +sum by (grpcproc_leader_cluster) (grpcproc_leader_electors{grpcproc_leader_role="leader"}) > 1 +# The singleton runs nowhere, or twice. +sum by (grpcproc_leader_cluster) (grpcproc_leader_singleton) != 1 +# One more node lost and this side has no majority; below it, none can be elected. +# A view of one or two never has a node to spare. +grpcproc_leader_reachable <= grpcproc_leader_quorum and grpcproc_leader_view >= 3 +# Elections keep happening. +changes(max by (grpcproc_leader_cluster) (grpcproc_leader_term)[15m:]) > 3 +# A majority is not taking the leader's state. +grpcproc_leader_checkpoints_waiting > 0 +# An elector held up for a second or more, which sends no heartbeat or vote meanwhile. +grpcproc_leader_stalled > 0`} +

+ Give each a for: of a few scrape intervals, a minute say: an election, and a + hand-over, whose Resign stops the old singleton before the next leader starts its + own, leave no leader or no singleton for a moment, and a leader cut off from the others + leads for up to two election timeouts after they elect another. A stalled elector is in + none of the sums: when the leader is the one held up, the other nodes' gauges show no + leader, and with no other node reporting the sums are empty, which only "stalled" alerts + on. A second is fixed: with an ElectionTimeout above it, a Store slow enough + to be stalled can still be within it, so give "stalled" a for: longer than the + timeout. +

) } diff --git a/site/src/content/guides-operations.tsx b/site/src/content/guides-operations.tsx index fc86050..d78821a 100644 --- a/site/src/content/guides-operations.tsx +++ b/site/src/content/guides-operations.tsx @@ -369,7 +369,10 @@ srv.GracefulStop()`} 'Crashes, and a supervisor that gave up.' ], [ - <>A leader's term rising, from leader.Status: no metric carries it, + <> + grpcproc.leader.term rising, from{' '} + ObserveLeader + , <> Elections keep happening: ElectionTimeout too low for the network, or a node flapping. grpcprocctl leader shows each node's view.