Merge pull request #629 from seaweedfs/feat/standalone-failover-cli

feat(sw-block): ops failover for standalone; the alpha stack deploys the manual failover
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-25 22:12:26 -08:00
commit c83b5ffc62
23 files changed
+858 -28

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const opsFailoverName = "sw-block ops failover"
// failoverRuntime is blockmaster's admin-only FailbackService, the one call
// the operator's failover makes.
type failoverRuntime interface {
ExecuteFailback(context.Context, ops.FailbackRuntimeRequest) (ops.FailbackRuntimeResult, error)
}
// opsFailoverRuntimeFactory dials blockmaster with the mutual-TLS client
// identity from SW_BLOCK_TLS_CERT / SW_BLOCK_TLS_KEY / SW_BLOCK_TLS_CA.
var opsFailoverRuntimeFactory = func(master string) failoverRuntime {
return ops.NewGRPCFailbackRuntime(master)
}
const failoverUsage = `usage: sw-block ops failover --master ADDR --volume V --target R
--target-data A --target-ctrl A --expect-current R@E --confirm-old-node-off V
The operator's failover of volume V's primary to replica R, for a standalone
(systemd) deployment. blockmaster decides: when the current primary is
unreachable it runs the fencing round (every other replica fenced at E+1) and
moves the line only to a ready replica holding the highest fenced end; a
reachable primary's move is a planned move under its guard. --target-data
and --target-ctrl must be blockmaster's record of the replica (its heartbeat);
other addresses are refused before any round. A refusal publishes no line,
but a refused fencing round may already have fenced the survivors above the
line (blockmaster continues the old primary when it answers again).
The fencing round stops the old primary's writes, not its reads: power the
old node off or cut it from its clients first, then confirm with
--confirm-old-node-off V. --expect-current is the line you saw (sw-block ops
volumes); a line that moved since is refused.
Needs an admin client certificate: SW_BLOCK_TLS_CERT, SW_BLOCK_TLS_KEY and
SW_BLOCK_TLS_CA, all three; without them the command refuses before dialing.
Exit: 0 moved; 1 refused by blockmaster, or the line did not move; 2 bad
arguments or identity (no call made); 3 outcome unknown (the connection or the
deadline failed: the line may have moved; read it with sw-block ops volumes
before retrying).
`
func runOpsFailover(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet(opsFailoverName, flag.ContinueOnError)
fs.SetOutput(stderr)
fs.Usage = func() { fmt.Fprint(stderr, failoverUsage) }
var master, volume, target, data, ctrl, expect, confirm string
var timeout time.Duration
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
fs.StringVar(&volume, "volume", "", "volume id")
fs.StringVar(&target, "target", "", "replica id to promote")
fs.StringVar(&data, "target-data", "", "the target replica's data address host:port")
fs.StringVar(&ctrl, "target-ctrl", "", "the target replica's control address host:port")
fs.StringVar(&expect, "expect-current", "", "the current line, exactly <replica>@<epoch>")
fs.StringVar(&confirm, "confirm-old-node-off", "", "exactly the volume id: the old primary's node is off or cut from its clients")
fs.DurationVar(&timeout, "timeout", 30*time.Second, "bound for the call (the fencing round runs inside it)")
if err := fs.Parse(args); err != nil {
return 2
}
if fs.NArg() != 0 || master == "" || volume == "" || target == "" || data == "" || ctrl == "" || timeout <= 0 {
fmt.Fprint(stderr, failoverUsage)
return 2
}
curReplica, curEpoch, ok := parseReplicaAtEpoch(expect)
if !ok {
fmt.Fprintf(stderr, "%s: --expect-current %q is not <replica>@<epoch>\n", opsFailoverName, expect)
return 2
}
if curReplica == target {
fmt.Fprintf(stderr, "%s: the target %s is the current primary\n", opsFailoverName, target)
return 2
}
if confirm != volume {
fmt.Fprintf(stderr, "%s: --confirm-old-node-off must be exactly %q (the old node is off or cut from its clients)\n", opsFailoverName, volume)
return 2
}
// An admin command never falls back to a plaintext link.
if tls, err := link.MasterTLSFromEnv(); err != nil {
fmt.Fprintf(stderr, "%s: client identity: %v\n", opsFailoverName, err)
return 2
} else if tls == nil {
fmt.Fprintf(stderr, "%s: needs an admin client certificate: set %s, %s and %s\n", opsFailoverName, link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)
return 2
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
res, err := opsFailoverRuntimeFactory(master).ExecuteFailback(ctx, ops.FailbackRuntimeRequest{
VolumeID: volume,
ReplicaID: target,
TargetDataAddr: data,
TargetCtrlAddr: ctrl,
ExpectedCurrentReplicaID: curReplica,
ExpectedCurrentEpoch: curEpoch,
// Required by the runtime but decide nothing (they are not evidence):
// blockmaster's gate (the fencing round for an unreachable primary)
// decides the move, and the target is published at blockmaster's own
// record of its addresses (a request naming others is refused).
AckEligible: true,
FrontendFencedBeforeFailback: true, // --confirm-old-node-off
DurableFrontierCovered: true,
NoCrossVolumeIdentityChange: true,
EvidenceRefs: []string{"sw-block ops failover", "operator_confirmed_old_node_off=" + volume},
})
if err != nil {
if failoverOutcomeUnknown(err) {
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=unknown\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: outcome unknown (%v): the line may have moved; read it with sw-block ops volumes before retrying\n", opsFailoverName, err)
return 3
}
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch)
fmt.Fprintf(stderr, "%s: refused: %v (no line published; a refused fencing round may have fenced the survivors)\n", opsFailoverName, err)
return 1
}
moved := res.FailbackStarted && res.AuthorityEpochAdvanced && res.SinglePrimaryAfterFailback
fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=%s epoch_advanced=%t single_primary=%t publish_target_swapped=%t\n",
volume, target, curReplica, curEpoch, map[bool]string{true: "moved", false: "not_moved"}[moved],
res.AuthorityEpochAdvanced, res.SinglePrimaryAfterFailback, res.PublishTargetSwappedAfterFailback)
if !moved {
return 1
}
return 0
}
// parseReplicaAtEpoch parses "<replica>@<epoch>" with a nonzero epoch.
func parseReplicaAtEpoch(s string) (string, uint64, bool) {
i := strings.LastIndexByte(s, '@')
if i <= 0 || i == len(s)-1 {
return "", 0, false
}
e, err := strconv.ParseUint(s[i+1:], 10, 64)
if err != nil || e == 0 {
return "", 0, false
}
return s[:i], e, true
}
// failoverOutcomeUnknown: the call did not get blockmaster's decision back
// (connection, deadline, cancellation or an internal failure), so the line
// may or may not have moved. A decided refusal is any other status.
func failoverOutcomeUnknown(err error) bool {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return true
}
s, ok := status.FromError(err)
if !ok {
return true
}
switch s.Code() {
case codes.Unavailable, codes.DeadlineExceeded, codes.Canceled, codes.Unknown, codes.Internal, codes.DataLoss, codes.ResourceExhausted:
return true
}
return false
}
+290
View File
@@ -0,0 +1,290 @@
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"math/big"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type fakeFailoverRuntime struct {
calls []ops.FailbackRuntimeRequest
res ops.FailbackRuntimeResult
err error
}
func (f *fakeFailoverRuntime) ExecuteFailback(_ context.Context, req ops.FailbackRuntimeRequest) (ops.FailbackRuntimeResult, error) {
f.calls = append(f.calls, req)
return f.res, f.err
}
func withFailoverRuntime(t *testing.T, f *fakeFailoverRuntime) *string {
t.Helper()
withClientIdentity(t)
var dialed string
prev := opsFailoverRuntimeFactory
opsFailoverRuntimeFactory = func(master string) failoverRuntime { dialed = master; return f }
t.Cleanup(func() { opsFailoverRuntimeFactory = prev })
return &dialed
}
func failoverArgs(extra ...string) []string {
args := []string{"ops", "failover", "--master", "m:9333", "--volume", "v1", "--target", "r2",
"--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4", "--confirm-old-node-off", "v1"}
return append(args, extra...)
}
// The operator's failover sends one FailbackService call carrying the
// expected current line it was given; a move is reported and exits 0.
func TestOpsFailoverSendsTheExpectedLineAndReportsTheMove(t *testing.T) {
f := &fakeFailoverRuntime{res: ops.FailbackRuntimeResult{FailbackStarted: true, AuthorityEpochAdvanced: true, SinglePrimaryAfterFailback: true, PublishTargetSwappedAfterFailback: true}}
dialed := withFailoverRuntime(t, f)
var out, errb bytes.Buffer
if rc := run(failoverArgs(), &out, &errb); rc != 0 {
t.Fatalf("rc=%d stderr=%s", rc, errb.String())
}
if *dialed != "m:9333" || len(f.calls) != 1 {
t.Fatalf("dialed %q calls %d; want one call to m:9333", *dialed, len(f.calls))
}
r := f.calls[0]
if r.VolumeID != "v1" || r.ReplicaID != "r2" || r.TargetDataAddr != "d2:1" || r.TargetCtrlAddr != "c2:1" ||
r.ExpectedCurrentReplicaID != "r1" || r.ExpectedCurrentEpoch != 4 || !r.FrontendFencedBeforeFailback {
t.Fatalf("request %+v", r)
}
if !strings.Contains(out.String(), "result=moved") {
t.Fatalf("stdout %q; want result=moved", out.String())
}
}
// A refusal by blockmaster (for example a fencing round that does not allow
// the target) is reported and exits 1; a call that returns without moving
// the line is not a move either.
func TestOpsFailoverReportsARefusal(t *testing.T) {
for _, f := range []*fakeFailoverRuntime{
{err: status.Error(codes.FailedPrecondition, "execute failback: fenced move: the fencing round at epoch 5 does not allow r2")},
{res: ops.FailbackRuntimeResult{FailbackStarted: true}},
} {
withFailoverRuntime(t, f)
var out, errb bytes.Buffer
if rc := run(failoverArgs(), &out, &errb); rc != 1 {
t.Fatalf("rc=%d; want 1 (stdout %q stderr %q)", rc, out.String(), errb.String())
}
if strings.Contains(out.String(), "result=moved") {
t.Fatalf("stdout %q reports a move", out.String())
}
}
}
// Every argument guard refuses locally, before any call: the old node must
// be confirmed off for exactly this volume, the expected line must be
// <replica>@<epoch> with a nonzero epoch, and the target must not be the
// current primary.
func TestOpsFailoverRefusesBadArgumentsWithoutACall(t *testing.T) {
for name, args := range map[string][]string{
"no confirmation": {"ops", "failover", "--master", "m:9333", "--volume", "v1", "--target", "r2", "--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4"},
"confirmation for another": failoverArgs("--confirm-old-node-off", "v2"),
"expected line without epoch": failoverArgs("--expect-current", "r1"),
"expected epoch zero": failoverArgs("--expect-current", "r1@0"),
"expected epoch not a number": failoverArgs("--expect-current", "r1@x"),
"target is current": failoverArgs("--expect-current", "r2@4"),
"no master": {"ops", "failover", "--volume", "v1", "--target", "r2", "--target-data", "d2:1", "--target-ctrl", "c2:1", "--expect-current", "r1@4", "--confirm-old-node-off", "v1"},
"stray argument": append(failoverArgs(), "extra"),
} {
t.Run(name, func(t *testing.T) {
f := &fakeFailoverRuntime{}
withFailoverRuntime(t, f)
var out, errb bytes.Buffer
if rc := run(args, &out, &errb); rc != 2 || len(f.calls) != 0 {
t.Fatalf("rc=%d calls=%d; want 2 and no call (stderr %q)", rc, len(f.calls), errb.String())
}
})
}
}
// The alpha stack deploys the manual failover its notes describe: blockmaster
// serves the admin failback RPC, the executor runs with the admin client
// Secret and execution on, the CRD is applied, and uninstall removes both.
func TestAlphaStackDeploysTheManualFailover(t *testing.T) {
read := func(p string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join("..", "..", p))
if err != nil {
t.Fatal(err)
}
return string(b)
}
const crd = "charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml"
read(crd)
for file, wants := range map[string][]string{
"deploy/k8s/alpha/block-stack.yaml": {`"--failback-runtime-rpc"`},
"deploy/k8s/alpha/failback-executor.yaml": {"secretName: sw-block-failback-executor-tls", `"--enable-execution"`, `"--execution-policy"`, `"--failback-runtime-grpc-addr=blockmaster.kube-system.svc.cluster.local:9333"`},
"scripts/install-k8s-alpha.sh": {crd, `render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml"`, `kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml"`},
"scripts/run-alpha-app-demo.sh": {crd, `render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml"`, `kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml"`},
"scripts/uninstall-k8s-alpha.sh": {crd, "deploy/k8s/alpha/failback-executor.yaml"},
"scripts/k8s-alpha-certs.sh": {"failback-executor:admin"},
} {
s := read(file)
for _, w := range wants {
if !strings.Contains(s, w) {
t.Errorf("%s: missing %s", file, w)
}
}
}
}
// A call that does not get blockmaster's decision back (the connection or
// the deadline failed) is reported as unknown, exit 3, never as a refusal:
// the line may have moved.
func TestOpsFailoverReportsAnUnknownOutcome(t *testing.T) {
for name, err := range map[string]error{
"unavailable": status.Error(codes.Unavailable, "connection reset"),
"deadline status": status.Error(codes.DeadlineExceeded, "deadline"),
"context deadline": context.DeadlineExceeded,
"not a status": errors.New("dial tcp: i/o timeout"),
} {
t.Run(name, func(t *testing.T) {
withFailoverRuntime(t, &fakeFailoverRuntime{err: err})
var out, errb bytes.Buffer
if rc := run(failoverArgs(), &out, &errb); rc != 3 || !strings.Contains(out.String(), "result=unknown") {
t.Fatalf("rc=%d stdout=%q; want 3 and result=unknown", rc, out.String())
}
})
}
}
// The admin command never dials without a complete, valid client identity:
// unset, partial or unreadable TLS settings are refused locally (exit 2, no
// call); a valid identity makes the call.
func TestOpsFailoverRequiresAClientIdentity(t *testing.T) {
dir := t.TempDir()
cert, key, ca := writeClientIdentity(t, dir)
junk := filepath.Join(dir, "junk.pem")
if err := os.WriteFile(junk, []byte("not a certificate"), 0o600); err != nil {
t.Fatal(err)
}
for name, c := range map[string]struct {
cert, key, ca string
calls int
}{
"unset": {"", "", "", 0},
"cert only": {cert, "", "", 0},
"no CA": {cert, key, "", 0},
"unreadable": {junk, junk, junk, 0},
"valid": {cert, key, ca, 1},
} {
t.Run(name, func(t *testing.T) {
f := &fakeFailoverRuntime{res: ops.FailbackRuntimeResult{FailbackStarted: true, AuthorityEpochAdvanced: true, SinglePrimaryAfterFailback: true}}
prev := opsFailoverRuntimeFactory
opsFailoverRuntimeFactory = func(string) failoverRuntime { return f }
t.Cleanup(func() { opsFailoverRuntimeFactory = prev })
t.Setenv(link.EnvTLSCert, c.cert)
t.Setenv(link.EnvTLSKey, c.key)
t.Setenv(link.EnvTLSCA, c.ca)
var out, errb bytes.Buffer
rc := run(failoverArgs(), &out, &errb)
if len(f.calls) != c.calls {
t.Fatalf("calls=%d; want %d (rc=%d stderr %q)", len(f.calls), c.calls, rc, errb.String())
}
if c.calls == 0 && rc != 2 {
t.Fatalf("rc=%d; want 2", rc)
}
if c.calls == 1 && rc != 0 {
t.Fatalf("rc=%d stderr %q; want 0", rc, errb.String())
}
})
}
}
// withClientIdentity sets a valid admin client identity for the test.
func withClientIdentity(t *testing.T) {
t.Helper()
cert, key, ca := writeClientIdentity(t, t.TempDir())
t.Setenv(link.EnvTLSCert, cert)
t.Setenv(link.EnvTLSKey, key)
t.Setenv(link.EnvTLSCA, ca)
}
// writeClientIdentity writes a CA and a client certificate it signed.
func writeClientIdentity(t *testing.T, dir string) (certPath, keyPath, caPath string) {
t.Helper()
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-ca"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
cliKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
cliTmpl := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "sw-block-admin"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}
caCert, err := x509.ParseCertificate(caDER)
if err != nil {
t.Fatal(err)
}
cliDER, err := x509.CreateCertificate(rand.Reader, cliTmpl, caCert, &cliKey.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalECPrivateKey(cliKey)
if err != nil {
t.Fatal(err)
}
write := func(name, typ string, der []byte) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}), 0o600); err != nil {
t.Fatal(err)
}
return p
}
return write("client.crt", "CERTIFICATE", cliDER), write("client.key", "EC PRIVATE KEY", keyDER), write("ca.crt", "CERTIFICATE", caDER)
}
// The executor runs the image the install selected, like the rest of the
// stack: rendering it with a registry image replaces the local image and its
// never-pull policy.
func TestAlphaFailbackExecutorRendersTheSelectedImage(t *testing.T) {
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("no bash")
}
root := filepath.Join("..", "..")
out := filepath.Join(t.TempDir(), "rendered.yaml")
const image = "registry.example.com/seaweedfs/seaweed-block:v9.9"
cmd := exec.Command(bash, filepath.Join(root, "scripts", "render-k8s-alpha-image.sh"), image, filepath.Join(root, "deploy", "k8s", "alpha", "failback-executor.yaml"), out)
if b, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("render: %v: %s", err, b)
}
b, err := os.ReadFile(out)
if err != nil {
t.Fatal(err)
}
r := string(b)
if !strings.Contains(r, "image: "+image) || !strings.Contains(r, "imagePullPolicy: IfNotPresent") || strings.Contains(r, "sw-block:local") || strings.Contains(r, "imagePullPolicy: Never") {
t.Fatalf("rendered executor does not run the selected image: %s", r)
}
}
+4 -1
View File
@@ -82,7 +82,7 @@ func run(args []string, stdout, stderr io.Writer) int {
return ops.VolumeStatusExitInvalid
}
if len(args) < 2 {
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume|volume-unheld|workspace")
fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk|volume|volume-unheld|workspace|failover")
usage(stderr)
return ops.VolumeStatusExitInvalid
}
@@ -131,6 +131,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return runOpsVolumeUnheld(args[2:], stdout, stderr)
case "workspace":
return runOpsWorkspace(args[2:], stdout, stderr)
case "failover":
return runOpsFailover(args[2:], stdout, stderr)
default:
fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1])
usage(stderr)
@@ -2300,6 +2302,7 @@ func usage(w io.Writer) {
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
fmt.Fprintln(w, " sw-block ops volume resolve --master <addr> [--timeout 10s] <name> (prints the master layout id)")
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
fmt.Fprintln(w, " sw-block ops failover --master <addr> --volume <id> --target <replica> --target-data <addr> --target-ctrl <addr> --expect-current <replica>@<epoch> --confirm-old-node-off <volume>")
fmt.Fprintln(w, " sw-block ops workspace force-move --master <addr> --volume <id> --target-host <server-id> --target-data <addr> --target-ctrl <addr> --request-id <id> --confirm-forced <volume>@<epoch> [--dry-run]")
fmt.Fprintln(w, " sw-block ops workspace lost-range --master <addr> --volume <id> [--request-id <id>] (authority only; no bypass: see `sw-block ops workspace help`)")
}
@@ -623,6 +623,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
p.mu.Unlock()
return ErrReassignNotBound
}
if exp := ask.ExpectCurrent; exp != nil {
if cur, ok := p.volumeLineLocked(ask.VolumeID); !ok || cur.ReplicaID != exp.ReplicaID || cur.Epoch != exp.Epoch {
p.mu.Unlock()
return fmt.Errorf("%w: volume %s expected %s@%d, the line is %s@%d", ErrExpectedLineMoved, ask.VolumeID, exp.ReplicaID, exp.Epoch, cur.ReplicaID, cur.Epoch)
}
}
next = adapter.AssignmentInfo{
VolumeID: ask.VolumeID,
ReplicaID: ask.ReplicaID,
+15
View File
@@ -79,8 +79,23 @@ type AssignmentAsk struct {
// differs from the line's is a restarted primary: a new endpoint version
// even at the same addresses.
Incarnation string
// ExpectCurrent, when set, makes a reassign conditional on the volume's
// line being exactly this replica at this epoch when the publisher mints
// (under its lock): an operator's move never lands on a line it did not
// see.
ExpectCurrent *ExpectedLine
}
// ExpectedLine is the line a conditional reassign was decided against.
type ExpectedLine struct {
ReplicaID string
Epoch uint64
}
// ErrExpectedLineMoved: a conditional reassign found the volume's line no
// longer the one it was decided against; the publisher mints nothing.
var ErrExpectedLineMoved = errors.New("authority: the volume's line moved since the move was decided")
// ErrReassignWithoutKind: a primary change was asked without a kind (no
// promotion-gate evidence, not a forced move); the publisher mints no line.
var ErrReassignWithoutKind = errors.New("authority: a reassign needs a primary kind (promotion evidence or a forced move)")
@@ -2,6 +2,7 @@ package authority
import (
"context"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/adapter"
@@ -39,9 +40,20 @@ type FailbackAuthorityRuntime struct {
// Gate is the promotion gate's decision for this planned move: the
// target's probed evidence, or why the move is refused. A failback is a
// primary change: without a gate it publishes nothing.
Gate func(volumeID, targetReplicaID string) (adapter.PrimaryEvidence, error)
// It decides on current, the line the request was checked against (the
// expected line), never on a line read later.
Gate func(volumeID, targetReplicaID string, current AuthorityBasis) (adapter.PrimaryEvidence, error)
// TargetEndpoint is the master's own record of the target replica's data
// and control addresses (its heartbeat, else its placement). The line is
// published at the addresses the master knows, never the caller's: a
// request naming other addresses, or a target with no record, is refused.
TargetEndpoint func(volumeID, targetReplicaID string) (dataAddr, ctrlAddr string, ok bool)
}
// ErrFailbackTargetEndpoint: the request's target addresses are not the
// master's record of that replica (or it has none).
var ErrFailbackTargetEndpoint = errors.New("authority failback runtime: target addresses are not the master's record of the replica")
func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req FailbackRuntimeRequest) (FailbackRuntimeResult, error) {
if err := validateFailbackRuntimeRequest(req); err != nil {
return FailbackRuntimeResult{}, err
@@ -68,7 +80,16 @@ func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req Failb
if r.Gate == nil {
return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w (no promotion gate)", ErrReassignWithoutKind)
}
evidence, err := r.Gate(req.VolumeID, req.ReplicaID)
if r.TargetEndpoint == nil {
return FailbackRuntimeResult{}, fmt.Errorf("%w: no endpoint record is configured", ErrFailbackTargetEndpoint)
}
if data, ctrl, ok := r.TargetEndpoint(req.VolumeID, req.ReplicaID); !ok {
return FailbackRuntimeResult{}, fmt.Errorf("%w: no record of %s", ErrFailbackTargetEndpoint, req.ReplicaID)
} else if data != req.TargetDataAddr || ctrl != req.TargetCtrlAddr {
return FailbackRuntimeResult{}, fmt.Errorf("%w: %s is at data=%s ctrl=%s, the request names data=%s ctrl=%s",
ErrFailbackTargetEndpoint, req.ReplicaID, data, ctrl, req.TargetDataAddr, req.TargetCtrlAddr)
}
evidence, err := r.Gate(req.VolumeID, req.ReplicaID, before)
if err != nil {
return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w", err)
}
@@ -79,6 +100,9 @@ func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req Failb
CtrlAddr: req.TargetCtrlAddr,
Intent: IntentReassign,
Evidence: evidence,
// Conditional on the expected line at the mint, not only at the
// check above: a move that landed in between refuses this one.
ExpectCurrent: &ExpectedLine{ReplicaID: req.ExpectedCurrentReplicaID, Epoch: req.ExpectedCurrentEpoch},
}); err != nil {
return FailbackRuntimeResult{}, err
}
@@ -20,7 +20,7 @@ func TestFailbackAuthorityRuntime_ReassignsThroughPublisher(t *testing.T) {
}); err != nil {
t.Fatalf("bind current: %v", err)
}
result, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), validAuthorityFailbackRequest())
result, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate, TargetEndpoint: r1Endpoint}).ExecuteFailback(context.Background(), validAuthorityFailbackRequest())
if err != nil {
t.Fatalf("execute failback: %v", err)
}
@@ -49,7 +49,7 @@ func TestFailbackAuthorityRuntime_RejectsStaleExpectedCurrent(t *testing.T) {
}
req := validAuthorityFailbackRequest()
req.ExpectedCurrentEpoch = 99
_, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), req)
_, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate, TargetEndpoint: r1Endpoint}).ExecuteFailback(context.Background(), req)
if err == nil || !strings.Contains(err.Error(), "stale expected current line") {
t.Fatalf("err=%v", err)
}
@@ -63,7 +63,7 @@ func TestFailbackAuthorityRuntime_RequiresTerminalPreconditions(t *testing.T) {
pub := NewPublisher(NewStaticDirective(nil))
req := validAuthorityFailbackRequest()
req.AckEligible = false
_, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate}).ExecuteFailback(context.Background(), req)
_, err := (FailbackAuthorityRuntime{Publisher: pub, Gate: allowGate, TargetEndpoint: r1Endpoint}).ExecuteFailback(context.Background(), req)
if err == nil || !strings.Contains(err.Error(), "terminal failback preconditions") {
t.Fatalf("err=%v", err)
}
@@ -90,7 +90,7 @@ func validAuthorityFailbackRequest() FailbackRuntimeRequest {
// allowGate stands in for the master's planned-move decision: the target is
// allowed with the probe round's evidence.
func allowGate(volumeID, target string) (adapter.PrimaryEvidence, error) {
func allowGate(volumeID, target string, _ AuthorityBasis) (adapter.PrimaryEvidence, error) {
return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 1, Basis: adapter.BasisPlanned}, nil
}
@@ -101,7 +101,7 @@ func TestFailbackAuthorityRuntime_PublishesNothingWithoutTheGatesEvidence(t *tes
for name, rt := range map[string]func(*Publisher) FailbackAuthorityRuntime{
"no gate": func(p *Publisher) FailbackAuthorityRuntime { return FailbackAuthorityRuntime{Publisher: p} },
"gate refuses": func(p *Publisher) FailbackAuthorityRuntime {
return FailbackAuthorityRuntime{Publisher: p, Gate: func(string, string) (adapter.PrimaryEvidence, error) {
return FailbackAuthorityRuntime{Publisher: p, TargetEndpoint: r1Endpoint, Gate: func(string, string, AuthorityBasis) (adapter.PrimaryEvidence, error) {
return adapter.PrimaryEvidence{}, errors.New("not caught up")
}}
},
@@ -121,3 +121,84 @@ func TestFailbackAuthorityRuntime_PublishesNothingWithoutTheGatesEvidence(t *tes
})
}
}
// r1Endpoint is the master's record of r1's addresses, as the valid request
// names them.
func r1Endpoint(_, replica string) (string, string, bool) {
if replica == "r1" {
return "data-r1", "ctrl-r1", true
}
return "", "", false
}
// The line is published at the master's record of the target's addresses:
// a request naming other addresses, a target with no record, or a runtime
// without the record is refused with ErrFailbackTargetEndpoint, and nothing
// is published.
func TestFailbackAuthorityRuntime_RefusesAddressesThatAreNotTheMastersRecord(t *testing.T) {
for name, c := range map[string]struct {
endpoint func(string, string) (string, string, bool)
data string
ctrl string
}{
"wrong data address": {r1Endpoint, "data-elsewhere", "ctrl-r1"},
"wrong control address": {r1Endpoint, "data-r1", "ctrl-elsewhere"},
"no record of the target": {func(string, string) (string, string, bool) { return "", "", false }, "data-r1", "ctrl-r1"},
"no endpoint record configured": {nil, "data-r1", "ctrl-r1"},
} {
t.Run(name, func(t *testing.T) {
pub := NewPublisher(NewStaticDirective(nil))
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r2", DataAddr: "data-r2", CtrlAddr: "ctrl-r2", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
before, _ := pub.VolumeAuthorityLine("v1")
req := validAuthorityFailbackRequest()
req.TargetDataAddr, req.TargetCtrlAddr = c.data, c.ctrl
gated := false
rt := FailbackAuthorityRuntime{Publisher: pub, TargetEndpoint: c.endpoint, Gate: func(v, r string, cur AuthorityBasis) (adapter.PrimaryEvidence, error) {
gated = true
return allowGate(v, r, cur)
}}
if _, err := rt.ExecuteFailback(context.Background(), req); !errors.Is(err, ErrFailbackTargetEndpoint) {
t.Fatalf("err=%v; want ErrFailbackTargetEndpoint", err)
}
if gated {
t.Fatal("the gate ran (a fencing round may have fenced survivors) for a request refused on its addresses")
}
if after, _ := pub.VolumeAuthorityLine("v1"); after != before {
t.Fatalf("line=%+v; want %+v unchanged", after, before)
}
})
}
}
// The operator's expected line binds the move through publication, not only
// at the first check: a move that lands after the check and before the mint
// (here: inside the gate) makes the stale request publish nothing, and the
// line is the intervening one. The gate decides on the expected line.
func TestFailbackAuthorityRuntime_AnInterveningMoveRefusesTheStaleRequest(t *testing.T) {
pub := NewPublisher(NewStaticDirective(nil))
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r2", DataAddr: "data-r2", CtrlAddr: "ctrl-r2", Intent: IntentBind}); err != nil {
t.Fatal(err)
}
var decidedOn AuthorityBasis
rt := FailbackAuthorityRuntime{Publisher: pub, TargetEndpoint: r1Endpoint, Gate: func(v, r string, cur AuthorityBasis) (adapter.PrimaryEvidence, error) {
decidedOn = cur
// Another move lands now: r3 at epoch 2.
if err := pub.apply(AssignmentAsk{VolumeID: "v1", ReplicaID: "r3", DataAddr: "data-r3", CtrlAddr: "ctrl-r3", Intent: IntentReassign,
Evidence: adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 1, Basis: adapter.BasisPlanned}}); err != nil {
t.Fatalf("intervening move: %v", err)
}
return allowGate(v, r, cur)
}}
_, err := rt.ExecuteFailback(context.Background(), validAuthorityFailbackRequest())
if !errors.Is(err, ErrExpectedLineMoved) {
t.Fatalf("err=%v; want ErrExpectedLineMoved", err)
}
if decidedOn.ReplicaID != "r2" || decidedOn.Epoch != 1 {
t.Fatalf("the gate decided on %+v; want the expected line r2@1", decidedOn)
}
if line, _ := pub.VolumeAuthorityLine("v1"); line.ReplicaID != "r3" || line.Epoch != 2 {
t.Fatalf("line=%+v; want the intervening r3@2, not the stale request's r1", line)
}
}
+5
View File
@@ -92,6 +92,11 @@ func (p *Publisher) LastAuthorityBasis(volumeID, replicaID string) (AuthorityBas
func (p *Publisher) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) {
p.mu.Lock()
defer p.mu.Unlock()
return p.volumeLineLocked(volumeID)
}
// volumeLineLocked is VolumeAuthorityLine with p.mu held.
func (p *Publisher) volumeLineLocked(volumeID string) (AuthorityBasis, bool) {
var best AuthorityBasis
any := false
for k, st := range p.state {
@@ -26,7 +26,7 @@ func TestPromotionBasisCensus(t *testing.T) {
want := []string{
"core/authority/controller.go plannedEvidence BasisPlanned",
"core/authority/workspace.go MoveWorkspace BasisPlanned",
"core/host/master/planned_move.go plannedMoveEvidence BasisPlanned",
"core/host/master/planned_move.go plannedMoveEvidenceAt BasisPlanned",
"core/host/master/product_loop.go healAfterFailedFence BasisHeal",
"core/host/master/product_loop.go promotionEvidenceFor BasisFenced",
}
@@ -0,0 +1,53 @@
package master
import (
"context"
"testing"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// The operator's failover publishes the new primary at the addresses the
// master knows for that replica (its heartbeat), never at the caller's: a
// request naming other addresses is refused and the line does not move; the
// same request at the recorded addresses moves it.
func TestFailbackPublishesOnlyTheMastersRecordedTargetAddresses(t *testing.T) {
h := newTestMasterWithControllerConfig(t, t.TempDir(), authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 2})
defer closeTestMaster(t, h)
h.SetPromotionEvidenceProvider(staticPromotionProbe{result: PromotionProbeResult{
AckProfile: "sync_all",
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 1}},
}})
seedRF2Placement(t, h)
ingestRF2Observation(t, h, true, true) // r2 heartbeats at 127.0.0.1:19201 / :19202
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatalf("product tick: %v", err)
}
line := waitAuthorityLine(t, h.Publisher(), "vol-rf2")
if line.ReplicaID != "r1" {
t.Fatalf("initial line=%+v want r1", line)
}
req := func(data, ctrl string) authority.FailbackRuntimeRequest {
return authority.FailbackRuntimeRequest{VolumeID: "vol-rf2", ReplicaID: "r2", TargetDataAddr: data, TargetCtrlAddr: ctrl,
ExpectedCurrentReplicaID: line.ReplicaID, ExpectedCurrentEpoch: line.Epoch,
AckEligible: true, FrontendFencedBeforeFailback: true, DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true}
}
for name, r := range map[string]authority.FailbackRuntimeRequest{
"wrong data address": req("127.0.0.1:29201", "127.0.0.1:19202"),
"wrong control address": req("127.0.0.1:19201", "127.0.0.1:29202"),
} {
if _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), r); err == nil {
t.Fatalf("%s: the failover published the caller's addresses", name)
}
if after, _ := h.Publisher().VolumeAuthorityLine("vol-rf2"); after != line {
t.Fatalf("%s: line=%+v; want %+v unchanged", name, after, line)
}
}
if _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), req("127.0.0.1:19201", "127.0.0.1:19202")); err != nil {
t.Fatalf("at the recorded addresses: %v", err)
}
after, _ := h.Publisher().VolumeAuthorityLine("vol-rf2")
if after.ReplicaID != "r2" || after.DataAddr != "127.0.0.1:19201" || after.CtrlAddr != "127.0.0.1:19202" {
t.Fatalf("line=%+v; want r2 at its recorded addresses", after)
}
}
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/ops"
@@ -25,6 +26,7 @@ func TestHostFailbackAuthorityRuntimeUsesLivePublisher(t *testing.T) {
t.Fatalf("product tick: %v", err)
}
current := waitAuthorityLine(t, h.Publisher(), "vol-a")
recordFailbackTargetR1(t, h) // the master knows the target replica's addresses
if current.ReplicaID != "r2" {
t.Fatalf("current line=%+v want r2", current)
}
@@ -73,6 +75,7 @@ func TestHostFrontendPublicationRuntimeHTTPConfirmsPostFailbackAuthorityLine(t *
t.Fatalf("product tick: %v", err)
}
current := waitAuthorityLine(t, h.Publisher(), "vol-a")
recordFailbackTargetR1(t, h) // the master knows the target replica's addresses
if _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), authority.FailbackRuntimeRequest{
VolumeID: "vol-a",
ReplicaID: "r1",
@@ -204,6 +207,7 @@ func TestFailbackServiceEnabledUsesHostRuntime(t *testing.T) {
t.Fatalf("product tick: %v", err)
}
current := waitAuthorityLine(t, h.Publisher(), "vol-a")
recordFailbackTargetR1(t, h) // the master knows the target replica's addresses
resp, err := newServices(h).ExecuteFailback(context.Background(), &control.FailbackRequest{
VolumeId: "vol-a",
@@ -247,6 +251,7 @@ func TestFailbackExecutorGRPCRuntimeUsesRealMasterService(t *testing.T) {
t.Fatalf("product tick: %v", err)
}
current := waitAuthorityLine(t, h.Publisher(), "vol-a")
recordFailbackTargetR1(t, h) // the master knows the target replica's addresses
if current.ReplicaID != "r2" {
t.Fatalf("current line=%+v want r2", current)
}
@@ -381,3 +386,21 @@ func installPlannedMoveGate(h *Host) {
Candidates: []PromotionCandidateEvidence{{ReplicaID: "r1", Ready: true, DurableLSN: 1}},
}})
}
// recordFailbackTargetR1 gives the master its own record of the failback
// target r1 (a heartbeat at the addresses the requests name): a failback is
// published at the master's record of the target, never the caller's.
func recordFailbackTargetR1(t *testing.T, h *Host) {
t.Helper()
if err := h.ObservationHost().Ingest(authority.Observation{
ServerID: "node-b",
ObservedAt: time.Now().UTC(),
Server: authority.ServerFact{Reachable: true, Eligible: true},
Slots: []authority.SlotFact{{
VolumeID: "vol-a", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101",
Reachable: true, ReadyForPrimary: true, Eligible: true,
}},
}); err != nil {
t.Fatalf("ingest r1: %v", err)
}
}
+20 -1
View File
@@ -462,7 +462,26 @@ func (h *Host) Publisher() *authority.Publisher {
// the live Publisher. Callers still need an explicit policy gate before using
// it; constructing the runtime does not execute failback.
func (h *Host) FailbackAuthorityRuntime() authority.FailbackAuthorityRuntime {
return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidence}
return authority.FailbackAuthorityRuntime{Publisher: h.Publisher(), Gate: h.plannedMoveEvidenceAt, TargetEndpoint: h.replicaEndpoint}
}
// replicaEndpoint is the master's own record of a replica's addresses: its
// fresh heartbeat slot (what the automatic path publishes), else its
// placement slot when that names both.
func (h *Host) replicaEndpoint(volumeID, replicaID string) (string, string, bool) {
if s, ok := h.freshCurrentSlot(volumeID, replicaID); ok && s.DataAddr != "" && s.CtrlAddr != "" {
return s.DataAddr, s.CtrlAddr, true
}
if h.lifecycle != nil {
if p, ok := h.lifecycle.Placements.GetPlacement(volumeID); ok {
for _, s := range p.Slots {
if s.ReplicaID == replicaID && s.DataAddr != "" && s.CtrlAddr != "" {
return s.DataAddr, s.CtrlAddr, true
}
}
}
}
return "", "", false
}
// Controller exposes the controller for tests.
+14 -12
View File
@@ -48,10 +48,14 @@ type ackProfiled interface{ AckProfile() string }
func (p *roundEvidenceProvider) AckProfile() string { return p.ackProfile }
// plannedMoveEvidence is the promotion gate's decision for an operator's
// planned move to target: the guard, then a probe round of the target, which
// must answer ready; its evidence goes on the line (kind PROMOTION).
func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvidence, error) {
// plannedMoveEvidenceAt is the promotion gate's decision for an operator's
// move to target: the guard, then a probe round of the target, which must
// answer ready (or, for an unreachable primary, the fencing round); its
// evidence goes on the line (kind PROMOTION). It decides the move against current, the line the
// operator's request was checked against (its expected line): the
// reachability judged and the fencing round opened are that line's, never a
// line read later. The publisher then mints only while the line is still it.
func (h *Host) plannedMoveEvidenceAt(volumeID, target string, current authority.AuthorityBasis) (adapter.PrimaryEvidence, error) {
h.promotionMu.RLock()
prober := h.promotionProber
h.promotionMu.RUnlock()
@@ -80,8 +84,8 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid
// move stays a planned move under its guard.
if err := plannedMoveAllowed(profile, len(placement.Slots)); err != nil && !errors.Is(err, ErrPlannedMoveNeedsSeal) {
return adapter.PrimaryEvidence{}, err
} else if h.primaryUnreachable(volumeID) {
return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots)
} else if h.primaryUnreachable(volumeID, current) {
return h.fencedMoveEvidence(volumeID, target, profile, placement.Slots, current)
} else if err != nil {
return adapter.PrimaryEvidence{}, err
}
@@ -101,9 +105,8 @@ func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvid
// primaryUnreachable: the line's primary has no fresh, reachable heartbeat
// slot. A volume without a line has no primary to lose.
func (h *Host) primaryUnreachable(volumeID string) bool {
current, ok := h.Publisher().VolumeAuthorityLine(volumeID)
if !ok {
func (h *Host) primaryUnreachable(volumeID string, current authority.AuthorityBasis) bool {
if !current.Assigned {
return false
}
slot, fresh := h.freshCurrentSlot(volumeID, current.ReplicaID)
@@ -118,9 +121,8 @@ func (h *Host) primaryUnreachable(volumeID string) bool {
// fenced end and is ready). A round that does not allow the target publishes
// nothing and leaves the fence pending, so a primary that answers again is
// continued at e+1 (healAfterFailedFence) by the product loop.
func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []lifecycle.PlacementSlotIntent) (adapter.PrimaryEvidence, error) {
current, ok := h.Publisher().VolumeAuthorityLine(volumeID)
if !ok {
func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []lifecycle.PlacementSlotIntent, current authority.AuthorityBasis) (adapter.PrimaryEvidence, error) {
if !current.Assigned {
return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: volume %s has no authority line", volumeID)
}
h.promotionMu.RLock()
@@ -4,6 +4,7 @@ import (
"fmt"
"testing"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/authority"
)
@@ -74,3 +75,11 @@ func TestPlannedMoveOneGuardForFailbackAndRebalance(t *testing.T) {
}
}
}
// plannedMoveEvidence is plannedMoveEvidenceAt against the volume's line as
// it is now (the tests' shorthand; the failback runtime passes the line its
// request was checked against).
func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvidence, error) {
current, _ := h.Publisher().VolumeAuthorityLine(volumeID)
return h.plannedMoveEvidenceAt(volumeID, target, current)
}
@@ -117,6 +117,7 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) {
// existing tests; this is not a VM-stop or physical fencing qualification.
// The planned move decides on the promotion gate (its fixture, too).
installPlannedMoveGate(m)
recordFailbackTargetR1(t, m)
if _, err := m.FailbackAuthorityRuntime().ExecuteFailback(ctx, authority.FailbackRuntimeRequest{
VolumeID: "vol-a", ReplicaID: "r1", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101",
ExpectedCurrentReplicaID: oldLine.ReplicaID, ExpectedCurrentEpoch: oldLine.Epoch,
@@ -15,10 +15,11 @@ type AuthorityFailbackRuntime struct {
}
// NewAuthorityFailbackRuntime adapts the authority failback runtime; gate is
// the promotion gate's planned-move decision (nil: every failback refuses).
func NewAuthorityFailbackRuntime(publisher *authority.Publisher, gate func(volumeID, targetReplicaID string) (adapter.PrimaryEvidence, error)) *AuthorityFailbackRuntime {
// the promotion gate's planned-move decision and endpoint the master's record
// of the target's addresses (nil either: every failback refuses).
func NewAuthorityFailbackRuntime(publisher *authority.Publisher, gate func(volumeID, targetReplicaID string, current authority.AuthorityBasis) (adapter.PrimaryEvidence, error), endpoint func(volumeID, targetReplicaID string) (string, string, bool)) *AuthorityFailbackRuntime {
return &AuthorityFailbackRuntime{
Runtime: authority.FailbackAuthorityRuntime{Publisher: publisher, Gate: gate},
Runtime: authority.FailbackAuthorityRuntime{Publisher: publisher, Gate: gate, TargetEndpoint: endpoint},
}
}
@@ -20,7 +20,7 @@ func TestFailbackExecutorUsesAuthorityRuntimeAdapter(t *testing.T) {
result, err := (FailbackExecutorReconciler{
Namespace: "kube-system",
Client: client,
Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate),
Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate, opsR1Endpoint),
ExecutionRequested: true,
ExecutionPolicyEnabled: true,
Now: func() time.Time { return time.Date(2026, 6, 26, 15, 0, 0, 0, time.UTC) },
@@ -70,7 +70,7 @@ func TestFailbackAuthorityRuntimeAdapterRejectsStaleExpectedCurrent(t *testing.T
result, err := (FailbackExecutorReconciler{
Namespace: "kube-system",
Client: client,
Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate),
Runtime: NewAuthorityFailbackRuntime(publisher, opsAllowGate, opsR1Endpoint),
ExecutionRequested: true,
ExecutionPolicyEnabled: true,
}).Reconcile(context.Background())
@@ -147,6 +147,15 @@ func seededFailbackPublisher(t *testing.T) *authority.Publisher {
}
// opsAllowGate stands in for the master's planned-move decision (allowed).
func opsAllowGate(string, string) (adapter.PrimaryEvidence, error) {
func opsAllowGate(string, string, authority.AuthorityBasis) (adapter.PrimaryEvidence, error) {
return adapter.PrimaryEvidence{Kind: adapter.PrimaryKindPromotion, DurableLSN: 1, Basis: adapter.BasisPlanned}, nil
}
// opsR1Endpoint stands in for the master's record of r1's addresses (as the
// executable target fixture names them).
func opsR1Endpoint(_, replica string) (string, string, bool) {
if replica == "r1" {
return "data-r1", "ctrl-r1", true
}
return "", "", false
}
@@ -53,6 +53,7 @@ spec:
- "--audit-log=/var/lib/sw-block/audit.log"
- "--launcher-master-tls-secret-prefix=sw-block-node-tls"
- "--expected-slots-per-volume=__EXPECTED_SLOTS_PER_VOLUME__"
- "--failback-runtime-rpc"
ports:
- name: grpc
containerPort: 9333
@@ -0,0 +1,99 @@
# The admin's manual failover in the alpha stack: the failback executor reads
# SwBlockReplicaFailback objects in kube-system and calls blockmaster's
# admin-only ExecuteFailback over mutual TLS (client Secret
# sw-block-failback-executor-tls from scripts/k8s-alpha-certs.sh). The CRD is
# charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml.
#
# Who may fail over: the executor holds a full admin client certificate and
# executes what a SwBlockReplicaFailback object says, so the right to create or
# change those objects in kube-system IS the right to fail over any volume.
# Grant it only to the cluster administrators who would run
# `sw-block ops failover` by hand. blockmaster still decides every move (the
# fencing round for an unreachable primary) and publishes the target at its
# own record of the replica's addresses, never the object's.
#
# The object field that asserts the old primary's frontend is fenced
# (frontendFencedBeforeFailback) is the operator's confirmation that the old
# node is off or cut from its clients (the fencing round stops its writes,
# not its reads). Automation must never set it.
#
# Limit, dated 2026-11-26: the certificate carries the admin role although the
# executor makes one call (ExecuteFailback); a role limited to that call is
# not in this release.
apiVersion: v1
kind: ServiceAccount
metadata:
name: sw-block-failback-executor
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: sw-block-failback-executor
rules:
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockreplicafailbacks"]
verbs: ["get", "list", "watch"]
- apiGroups: ["block.seaweedfs.com"]
resources: ["swblockreplicafailbacks/status"]
verbs: ["get", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sw-block-failback-executor
subjects:
- kind: ServiceAccount
name: sw-block-failback-executor
namespace: kube-system
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: sw-block-failback-executor
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: sw-block-failback-executor
namespace: kube-system
labels:
app: sw-block-failback-executor
spec:
replicas: 1
selector:
matchLabels:
app: sw-block-failback-executor
template:
metadata:
labels:
app: sw-block-failback-executor
spec:
serviceAccountName: sw-block-failback-executor
containers:
- name: failback-executor
image: sw-block:local
imagePullPolicy: Never
command: ["/usr/local/bin/sw-block"]
args:
- "ops"
- "failback-executor"
- "--namespace=kube-system"
- "--enable-execution"
- "--execution-policy"
- "--failback-runtime-grpc-addr=blockmaster.kube-system.svc.cluster.local:9333"
- "--interval=5s"
env:
- name: SW_BLOCK_TLS_CERT
value: /etc/sw-block/master-tls/tls.crt
- name: SW_BLOCK_TLS_KEY
value: /etc/sw-block/master-tls/tls.key
- name: SW_BLOCK_TLS_CA
value: /etc/sw-block/master-tls/ca.crt
volumeMounts:
- name: master-tls
mountPath: /etc/sw-block/master-tls
readOnly: true
volumes:
- name: master-tls
secret:
secretName: sw-block-failback-executor-tls
@@ -268,6 +268,9 @@ kubectl apply -f "$STACK_RENDERED" | tee "$ARTIFACT_DIR/apply-block-stack.log"
kubectl -n kube-system wait --for=condition=available deploy/sw-blockmaster --timeout=120s
log "apply CSI components"
kubectl apply -f "$ROOT/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" | tee "$ARTIFACT_DIR/apply-failback-crd.log"
bash "$ROOT/scripts/render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml" "$ARTIFACT_DIR/failback-executor.rendered.yaml"
kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml" | tee "$ARTIFACT_DIR/apply-failback-executor.log"
kubectl apply -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" | tee "$ARTIFACT_DIR/apply-csidriver.log"
kubectl apply -f "$CSI_CONTROLLER_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-controller.log"
kubectl apply -f "$CSI_NODE_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-node.log"
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Renders an alpha manifest written for the local image (sw-block:local,
# imagePullPolicy: Never) with the selected image, the way the stack itself is
# rendered: usage: render-k8s-alpha-image.sh IMAGE IN OUT
set -euo pipefail
[[ $# -eq 3 ]] || { echo "usage: $0 IMAGE IN OUT" >&2; exit 2; }
image_sed="$(printf '%s' "$1" | sed 's/[\/&]/\\&/g')"
sed -e "s/sw-block:local/${image_sed}/g" \
-e "s/imagePullPolicy: Never/imagePullPolicy: IfNotPresent/g" \
"$2" >"$3"
grep -q "image: $1\$" "$3" || { echo "render-k8s-alpha-image: $3 does not name image $1" >&2; exit 1; }
@@ -1545,6 +1545,9 @@ kubectl apply -f "$STACK_RENDERED" | tee "$ARTIFACT_DIR/apply-block-stack.log"
kubectl -n kube-system wait --for=condition=available deploy/sw-blockmaster --timeout=120s
log "apply CSI manifests"
kubectl apply -f "$ROOT/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" | tee "$ARTIFACT_DIR/apply-failback-crd.log"
bash "$ROOT/scripts/render-k8s-alpha-image.sh" "$IMAGE" "$ROOT/deploy/k8s/alpha/failback-executor.yaml" "$ARTIFACT_DIR/failback-executor.rendered.yaml"
kubectl apply -f "$ARTIFACT_DIR/failback-executor.rendered.yaml" | tee "$ARTIFACT_DIR/apply-failback-executor.log"
kubectl apply -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" | tee "$ARTIFACT_DIR/apply-csidriver.log"
kubectl apply -f "$CSI_CONTROLLER_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-controller.log"
kubectl apply -f "$CSI_NODE_RENDERED" | tee "$ARTIFACT_DIR/apply-csi-node.log"
@@ -65,6 +65,8 @@ log "delete CSI components"
kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-node.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csi-node.log"
kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-controller.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csi-controller.log"
kubectl delete -f "$ROOT/deploy/k8s/alpha/csi-driver.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-csidriver.log"
kubectl delete -f "$ROOT/deploy/k8s/alpha/failback-executor.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-failback-executor.log"
kubectl delete -f "$ROOT/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-failback-crd.log"
kubectl delete -f "$ROOT/deploy/k8s/alpha/rbac.yaml" --ignore-not-found=true --wait=true --timeout=120s | tee "$ARTIFACT_DIR/delete-rbac.log"
log "delete alpha StorageClass"