Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions leader/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 56 additions & 0 deletions otel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
1 change: 1 addition & 0 deletions otel/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions otel/go.sum
Original file line number Diff line number Diff line change
@@ -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=
Expand Down
122 changes: 122 additions & 0 deletions otel/leader.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading