Files
seaweedfs/test/multi_master/chaos_test.go
T
Chris LuandGitHub 35d53a20f6 master: let the leader admit a master that starts with no raft state (#10865)
* master: answer with the leader raft already knows

Topo.Leader() backs off for up to 20 seconds waiting for an election.
Callers that a health probe or a client is blocked on cannot afford that:
/cluster/status, /cluster/healthz and /readyz all sit past the probe
timeout of both the helm chart and the operator, so a master that is
still joining looks dead rather than joining, and the kubelet restarts
it. informNewLeader and SendHeartbeat hold the client on a master that
cannot serve it, exactly when it should move on to find the one that can.

Answer these from MaybeLeader instead, which reports what raft knows
right now. MaybeLeader takes over the "am I the leader myself" fallback
that Leader() used to apply on top of it, so one non-blocking call is
still correct; Leader() keeps the backoff for callers that must wait.

* master: let the leader admit a master that starts with no raft state

Neither raft implementation lets a server outside the configuration
campaign: goraft's promotable() requires a non-empty log, and hashicorp
rejects vote requests from a candidate that is not in its configuration.
A master that comes up with fresh state therefore cannot elect itself in
— the leader has to pull it in. Nothing did.

The peer list is static, rendered from the replica count, so scaling it
up leaves the sitting leader running the old list with no idea the new
masters exist. Under goraft they wait forever. Under hashicorp they are
worse off: each bootstraps a cluster of its own from the new list, and
two of them form a quorum next to the live leader, with their own
TopologyId. That is the split brain SetTopologyId kills a master over.

Admit the peer where it registers instead. Only the leader gets past the
IsLeader check in KeepConnected, and a joining master's client lands
there, so that is the moment it joins. The broadcast OnPeerUpdate rides
on is not enough on its own: it only reaches masters already connected,
which is why a leader that came up first missed both newcomers.

RaftAddServer grew a goraft branch on the way, so cluster.raft.add stops
silently doing nothing on the default raft, and RaftRemoveServer with it.
Bootstrapping is now one call for both implementations, made only after
the peers confirm nobody has a leader, and retried until this master is
in rather than checked once and dropped.

* master: do not evict a peer that is still in -peers

The hashicorp leader drops a master from the raft configuration as soon
as it stops answering pings. A master that is merely restarting answers
nothing, so an ordinary bounce shrinks the quorum behind the operator's
back — and then races its own return: the master comes back, registers,
gets re-admitted, and the eviction lands after it.

A randomized start/stop walk lands on it. Two of three masters running,
the leader evicts the one that just went down, the restart re-adds it,
the removal commits late and takes the leader's own leadership with it.
What is left is a two-server configuration whose other half is down, and
a running master that nobody will ask for a vote — no quorum, no way
back until the third master returns.

-peers is what declares membership. updatePeers already reconciles the
configuration against it on every leadership change, and an operator who
really means to drop a master can say so with cluster.raft.remove, so
keep the eviction for masters that are no longer listed at all.

* test: bounce masters at random and hold the election to it

Twelve rounds of stopping or starting a random master, on both raft
implementations, checking the two things an election must never get
wrong: two masters claiming leadership at once, and a quorum that comes
back without agreeing on one. The cluster's identity has to survive the
whole walk, since a master that re-mints a TopologyId is the split brain
SetTopologyId kills its peers over. The seed is random and logged, so a
failure names the walk that reproduces it.

Below a quorum the walk moves straight on. A master that has lost its
quorum cannot commit anything, and goraft only checks whether it still
has one on an election-timeout ticker, after its peers have been quiet
for a full timeout — measured taking over 30 seconds to step down. That
direction belongs to TestTwoMastersDownAndRestart, which was giving it
ten seconds and would have started failing on a slower machine; it now
waits on that behaviour explicitly rather than sleeping twice and hoping.

WaitForTopologyId returns the id it waited for. Reading it separately
raced the leader applying the raft entry that carries it, which shows up
as an empty id right after an election rather than as a wrong one.
2026-08-21 15:22:22 -07:00

187 lines
5.4 KiB
Go

package multi_master
import (
"fmt"
"math/rand/v2"
"os"
"strconv"
"testing"
"time"
)
// chaosRounds is one stop or start per round, enough to walk in and out of
// quorum several times without turning this into a soak test.
const chaosRounds = 12
// TestRandomStartStopElection bounces masters at random and holds the election
// to the two things it must never get wrong: two masters claiming leadership at
// once, and a quorum that comes back without agreeing on one. The cluster's
// identity has to survive the whole walk — a master that re-mints a TopologyId
// here is the split brain SetTopologyId kills its peers over.
func TestRandomStartStopElection(t *testing.T) {
for _, impl := range raftImplementations {
t.Run(impl.name, func(t *testing.T) {
seed := chaosSeed(t)
t.Logf("seed %d — replay this walk with MULTI_MASTER_IT_SEED=%d", seed, seed)
rng := rand.New(rand.NewPCG(seed, seed))
mc := NewMasterCluster(t, impl.raftHashicorp)
for i := range 3 {
mc.StartNode(i)
}
if err := mc.WaitForLeader(waitTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("cluster did not elect a leader: %v", err)
}
topologyId, err := mc.WaitForTopologyId(waitTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("no initial TopologyId: %v", err)
}
for round := 1; round <= chaosRounds; round++ {
target := rng.IntN(3)
if mc.IsNodeRunning(target) {
mc.StopNode(target)
t.Logf("round %d: stopped master %d, %d left running", round, target, runningMasters(mc))
} else {
mc.StartNode(target)
t.Logf("round %d: started master %d, %d now running", round, target, runningMasters(mc))
}
if err := waitForSettledElection(mc, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): %v", round, seed, err)
}
// /dir/status proxies to the leader, so this reads the value the
// cluster as a whole is carrying, not any one master's copy.
if runningMasters(mc) >= 2 {
id, err := mc.WaitForTopologyId(leaderElectionTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): %v", round, seed, err)
}
if id != topologyId {
mc.DumpLogs()
t.Fatalf("round %d (seed %d): TopologyId changed from %s to %s", round, seed, topologyId, id)
}
}
}
// Everything back up, so the walk ends on a full cluster.
for i := range 3 {
mc.StartNode(i)
}
if _, err := waitForCommonLeader(mc, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("cluster did not recover after the walk (seed %d): %v", seed, err)
}
for i := range 3 {
if err := waitForPeerCount(mc, i, 2, leaderElectionTimeout); err != nil {
mc.DumpLogs()
t.Fatalf("master %d does not see the full cluster (seed %d): %v", i, seed, err)
}
}
id, err := mc.WaitForTopologyId(leaderElectionTimeout)
if err != nil {
mc.DumpLogs()
t.Fatalf("no TopologyId after the walk (seed %d): %v", seed, err)
}
if id != topologyId {
mc.DumpLogs()
t.Fatalf("TopologyId changed from %s to %s over the walk (seed %d)", topologyId, id, seed)
}
})
}
}
// waitForSettledElection waits for a quorum to agree on one leader, and fails
// if two masters claim leadership across consecutive polls — anything shorter
// than that is a master on its way down.
//
// Below a quorum there is nothing to wait for: the walk moves on. A master that
// has lost its quorum can keep claiming leadership for tens of seconds under
// goraft, and it cannot commit anything in that window, so stepping down is a
// liveness question rather than a safety one. TestTwoMastersDownAndRestart
// holds that direction to account.
func waitForSettledElection(mc *MasterCluster, timeout time.Duration) error {
if runningMasters(mc) < 2 {
return nil
}
var lastErr error
splitPolls := 0
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
claims, err := leaderClaims(mc)
if err != nil {
lastErr = err
}
if len(claims) > 1 {
splitPolls++
if splitPolls > 1 {
return fmt.Errorf("masters %v all claim leadership", claims)
}
time.Sleep(waitTick)
continue
}
splitPolls = 0
if _, err := commonLeader(mc); err == nil {
return nil
} else {
lastErr = err
}
time.Sleep(waitTick)
}
if lastErr == nil {
lastErr = fmt.Errorf("cluster did not settle within %v", timeout)
}
return lastErr
}
// leaderClaims returns the running masters that call themselves leader. The
// error reports masters that did not answer at all, which is a reason to keep
// waiting rather than a verdict.
func leaderClaims(mc *MasterCluster) (claims []int, err error) {
for i := range 3 {
if !mc.IsNodeRunning(i) {
continue
}
cs, statusErr := mc.GetClusterStatus(i)
if statusErr != nil {
err = fmt.Errorf("master %d: %w", i, statusErr)
continue
}
if cs.IsLeader {
claims = append(claims, i)
}
}
return claims, err
}
func runningMasters(mc *MasterCluster) int {
count := 0
for i := range 3 {
if mc.IsNodeRunning(i) {
count++
}
}
return count
}
// chaosSeed picks the walk. It is random by default and always logged, so a
// failure names the seed that reproduces it.
func chaosSeed(t *testing.T) uint64 {
t.Helper()
if v := os.Getenv("MULTI_MASTER_IT_SEED"); v != "" {
seed, err := strconv.ParseUint(v, 10, 64)
if err != nil {
t.Fatalf("MULTI_MASTER_IT_SEED %q: %v", v, err)
}
return seed
}
return uint64(time.Now().UnixNano())
}