From a43c23fe1bf3fa14057c4ca82fc1012a3e044922 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:38:20 -0800 Subject: [PATCH 01/10] test(sw-block): the standalone operator failover command and the alpha failover wiring (red) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/failover_test.go | 137 ++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/failover_test.go diff --git a/seaweed-block/cmd/sw-block/failover_test.go b/seaweed-block/cmd/sw-block/failover_test.go new file mode 100644 index 0000000000..ad84fc1d8c --- /dev/null +++ b/seaweed-block/cmd/sw-block/failover_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +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() + 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: errors.New("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 +// @ 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, "deploy/k8s/alpha/failback-executor.yaml"}, + "scripts/run-alpha-app-demo.sh": {crd, "deploy/k8s/alpha/failback-executor.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) + } + } + } +} From 20a93fc09c98a13521c7b45995a37f956eb45a60 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:38:32 -0800 Subject: [PATCH 02/10] feat(sw-block): ops failover for standalone; the alpha stack deploys the manual failover sw-block ops failover is the operator's failover of a standalone deployment: one call to blockmaster's admin-only FailbackService over mutual TLS with the expected current line, after the operator confirms the old node is off or cut from its clients. blockmaster decides the move. The alpha stack now deploys what its notes describe: blockmaster serves the failback RPC, and the failback executor (admin client Secret, execution on) runs in kube-system; install applies the CRD and executor, uninstall removes both. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/failover.go | 125 ++++++++++++++++++ seaweed-block/cmd/sw-block/main.go | 5 +- .../deploy/k8s/alpha/block-stack.yaml | 1 + .../deploy/k8s/alpha/failback-executor.yaml | 82 ++++++++++++ seaweed-block/scripts/install-k8s-alpha.sh | 2 + seaweed-block/scripts/run-alpha-app-demo.sh | 2 + seaweed-block/scripts/uninstall-k8s-alpha.sh | 2 + 7 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/sw-block/failover.go create mode 100644 seaweed-block/deploy/k8s/alpha/failback-executor.yaml diff --git a/seaweed-block/cmd/sw-block/failover.go b/seaweed-block/cmd/sw-block/failover.go new file mode 100644 index 0000000000..453a344795 --- /dev/null +++ b/seaweed-block/cmd/sw-block/failover.go @@ -0,0 +1,125 @@ +package main + +import ( + "context" + "flag" + "fmt" + "io" + "strconv" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +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. A refusal changes +nothing. + +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. Exit: 0 moved; 1 refused or failed; 2 +bad arguments. +` + +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 @") + 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 @\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 + } + 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, + // The operator's assertions the runtime requires; blockmaster's gate + // (the fencing round for an unreachable primary) decides the move. + 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 { + fmt.Fprintf(stdout, "failover volume=%s target=%s expected=%s@%d result=refused\n", volume, target, curReplica, curEpoch) + fmt.Fprintf(stderr, "%s: %v\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 "@" 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 +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 81bfc7e5dd..8b4ca9f27f 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -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-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-unheld|workspace|failover") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -129,6 +129,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) @@ -2297,6 +2299,7 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops chunk verify --volume --chunk-filer [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout ]") 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-unheld --path (exit 0: no process on this host holds it; local filesystems only)") + fmt.Fprintln(w, " sw-block ops failover --master --volume --target --target-data --target-ctrl --expect-current @ --confirm-old-node-off ") fmt.Fprintln(w, " sw-block ops workspace force-move --master --volume --target-host --target-data --target-ctrl --request-id --confirm-forced @ [--dry-run]") fmt.Fprintln(w, " sw-block ops workspace lost-range --master --volume [--request-id ] (authority only; no bypass: see `sw-block ops workspace help`)") } diff --git a/seaweed-block/deploy/k8s/alpha/block-stack.yaml b/seaweed-block/deploy/k8s/alpha/block-stack.yaml index 1ea5da978e..dabcb62954 100644 --- a/seaweed-block/deploy/k8s/alpha/block-stack.yaml +++ b/seaweed-block/deploy/k8s/alpha/block-stack.yaml @@ -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 diff --git a/seaweed-block/deploy/k8s/alpha/failback-executor.yaml b/seaweed-block/deploy/k8s/alpha/failback-executor.yaml new file mode 100644 index 0000000000..ff5b9a7946 --- /dev/null +++ b/seaweed-block/deploy/k8s/alpha/failback-executor.yaml @@ -0,0 +1,82 @@ +# 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. +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 diff --git a/seaweed-block/scripts/install-k8s-alpha.sh b/seaweed-block/scripts/install-k8s-alpha.sh index 7e3bbaeba2..bb92c41e96 100755 --- a/seaweed-block/scripts/install-k8s-alpha.sh +++ b/seaweed-block/scripts/install-k8s-alpha.sh @@ -268,6 +268,8 @@ 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" +kubectl apply -f "$ROOT/deploy/k8s/alpha/failback-executor.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" diff --git a/seaweed-block/scripts/run-alpha-app-demo.sh b/seaweed-block/scripts/run-alpha-app-demo.sh index 082143dca9..967c8624c1 100755 --- a/seaweed-block/scripts/run-alpha-app-demo.sh +++ b/seaweed-block/scripts/run-alpha-app-demo.sh @@ -1545,6 +1545,8 @@ 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" +kubectl apply -f "$ROOT/deploy/k8s/alpha/failback-executor.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" diff --git a/seaweed-block/scripts/uninstall-k8s-alpha.sh b/seaweed-block/scripts/uninstall-k8s-alpha.sh index a30bfe2a4e..ec26e226a1 100755 --- a/seaweed-block/scripts/uninstall-k8s-alpha.sh +++ b/seaweed-block/scripts/uninstall-k8s-alpha.sh @@ -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" From b5ea0f22103974a958051d3dcff35ee95e0598c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:57:47 -0800 Subject: [PATCH 03/10] test(master): a failback publishes only the master's recorded target addresses (red) Co-Authored-By: Claude Opus 5.5 --- .../host/master/failback_endpoint_test.go | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 seaweed-block/core/host/master/failback_endpoint_test.go diff --git a/seaweed-block/core/host/master/failback_endpoint_test.go b/seaweed-block/core/host/master/failback_endpoint_test.go new file mode 100644 index 0000000000..264f2620e8 --- /dev/null +++ b/seaweed-block/core/host/master/failback_endpoint_test.go @@ -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) + } +} From 4a61a5ab2936c6ccb20d1b02489723cd24b37348 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 17:58:50 -0800 Subject: [PATCH 04/10] fix(authority): a failback publishes the master's record of the target's addresses, never the caller's The line was published at the data and control addresses the caller sent (CLI flags, or the Kubernetes object's fields): a typo or a writer of that object could make the fenced replica primary at an endpoint clients never reach. The runtime now requires the master's own record of the target (its fresh heartbeat slot, else its placement) and refuses a request whose addresses differ, or a target with no record, before the gate runs, so a refused request fences nothing. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/failback_runtime.go | 19 ++++++ .../core/authority/failback_runtime_test.go | 58 +++++++++++++++++-- seaweed-block/core/host/master/host.go | 21 ++++++- .../ops/failback_authority_runtime_adapter.go | 7 ++- ...failback_authority_runtime_adapter_test.go | 13 ++++- 5 files changed, 108 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/authority/failback_runtime.go b/seaweed-block/core/authority/failback_runtime.go index 675ff065ce..600a682d12 100644 --- a/seaweed-block/core/authority/failback_runtime.go +++ b/seaweed-block/core/authority/failback_runtime.go @@ -2,6 +2,7 @@ package authority import ( "context" + "errors" "fmt" "github.com/seaweedfs/seaweed-block/core/adapter" @@ -40,8 +41,17 @@ type FailbackAuthorityRuntime struct { // 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) + // 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,6 +78,15 @@ 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) } + 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) if err != nil { return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w", err) diff --git a/seaweed-block/core/authority/failback_runtime_test.go b/seaweed-block/core/authority/failback_runtime_test.go index 16fb15f376..fe492ccbd0 100644 --- a/seaweed-block/core/authority/failback_runtime_test.go +++ b/seaweed-block/core/authority/failback_runtime_test.go @@ -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) } @@ -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) (adapter.PrimaryEvidence, error) { return adapter.PrimaryEvidence{}, errors.New("not caught up") }} }, @@ -121,3 +121,53 @@ 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) (adapter.PrimaryEvidence, error) { + gated = true + return allowGate(v, r) + }} + 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) + } + }) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 59c5a0754f..ce0f8f4494 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -453,7 +453,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.plannedMoveEvidence, 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. diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter.go b/seaweed-block/core/ops/failback_authority_runtime_adapter.go index aaabfb83ba..fe20618cf1 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter.go @@ -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) (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}, } } diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go index 29eb23164b..54c45deaa7 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go @@ -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()) @@ -150,3 +150,12 @@ func seededFailbackPublisher(t *testing.T) *authority.Publisher { func opsAllowGate(string, string) (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 +} From 5663ab6751ae34d72fe9e565c6a1bfe6d0c65a85 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:04:04 -0800 Subject: [PATCH 05/10] test(master): failback fixtures give the master its record of the target replica Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/failback_runtime_test.go | 23 +++++++++++++++++++ .../host/master/workspace_restore_test.go | 1 + 2 files changed, 24 insertions(+) diff --git a/seaweed-block/core/host/master/failback_runtime_test.go b/seaweed-block/core/host/master/failback_runtime_test.go index 6197c4f3c6..72cbc03b67 100644 --- a/seaweed-block/core/host/master/failback_runtime_test.go +++ b/seaweed-block/core/host/master/failback_runtime_test.go @@ -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) + } +} diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index 09cacad702..b9c3c5e8ce 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -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, From 52f87933282776cc42e99d3fc05af07051e9c34a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:09:03 -0800 Subject: [PATCH 06/10] docs: who may fail over through the alpha executor, its admin certificate limit, and that the request flags are not evidence Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/failover.go | 11 +++++++---- .../deploy/k8s/alpha/failback-executor.yaml | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/sw-block/failover.go b/seaweed-block/cmd/sw-block/failover.go index 453a344795..9df0b2e0ea 100644 --- a/seaweed-block/cmd/sw-block/failover.go +++ b/seaweed-block/cmd/sw-block/failover.go @@ -33,8 +33,9 @@ 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. A refusal changes -nothing. +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. A refusal changes nothing. 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 @@ -88,8 +89,10 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int { TargetCtrlAddr: ctrl, ExpectedCurrentReplicaID: curReplica, ExpectedCurrentEpoch: curEpoch, - // The operator's assertions the runtime requires; blockmaster's gate - // (the fencing round for an unreachable primary) decides the move. + // 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, diff --git a/seaweed-block/deploy/k8s/alpha/failback-executor.yaml b/seaweed-block/deploy/k8s/alpha/failback-executor.yaml index ff5b9a7946..dcdd371124 100644 --- a/seaweed-block/deploy/k8s/alpha/failback-executor.yaml +++ b/seaweed-block/deploy/k8s/alpha/failback-executor.yaml @@ -3,6 +3,23 @@ # 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: From a0ad707ecb25caaef6957a4b3bfd5a47a03b2d74 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:21:00 -0800 Subject: [PATCH 07/10] fix(authority): the operator's expected line binds the failover through publication The runtime checked --expect-current once, then ran the gate and published without it: a move landing in between let the stale request move a line the operator never saw. The reassign now carries the expected line and the publisher mints only while the volume's line is exactly it (under its lock); the gate decides on that same line (reachability and the fencing round are the expected line's, never one read later). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 6 +++ seaweed-block/core/authority/directive.go | 15 +++++++ .../core/authority/failback_runtime.go | 9 ++++- .../core/authority/failback_runtime_test.go | 39 +++++++++++++++++-- seaweed-block/core/authority/policy.go | 5 +++ .../authority/promotion_basis_census_test.go | 2 +- seaweed-block/core/host/master/host.go | 2 +- .../core/host/master/planned_move.go | 26 +++++++------ .../host/master/planned_move_paths_test.go | 9 +++++ .../ops/failback_authority_runtime_adapter.go | 2 +- ...failback_authority_runtime_adapter_test.go | 2 +- 11 files changed, 95 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 6b56109a4e..d0104a8c49 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -586,6 +586,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, diff --git a/seaweed-block/core/authority/directive.go b/seaweed-block/core/authority/directive.go index d68f029ebd..8b15b4eb30 100644 --- a/seaweed-block/core/authority/directive.go +++ b/seaweed-block/core/authority/directive.go @@ -74,8 +74,23 @@ type AssignmentAsk struct { // target (a bind is always a bootstrap); see adapter.PrimaryEvidence. It // is a probe fact about the target, never an authority fact. Evidence adapter.PrimaryEvidence + // 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)") diff --git a/seaweed-block/core/authority/failback_runtime.go b/seaweed-block/core/authority/failback_runtime.go index 600a682d12..c55e868283 100644 --- a/seaweed-block/core/authority/failback_runtime.go +++ b/seaweed-block/core/authority/failback_runtime.go @@ -40,7 +40,9 @@ 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 @@ -87,7 +89,7 @@ func (r FailbackAuthorityRuntime) ExecuteFailback(ctx context.Context, req Failb 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) + evidence, err := r.Gate(req.VolumeID, req.ReplicaID, before) if err != nil { return FailbackRuntimeResult{}, fmt.Errorf("authority failback runtime: %w", err) } @@ -98,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 } diff --git a/seaweed-block/core/authority/failback_runtime_test.go b/seaweed-block/core/authority/failback_runtime_test.go index fe492ccbd0..5a3eaf8ebf 100644 --- a/seaweed-block/core/authority/failback_runtime_test.go +++ b/seaweed-block/core/authority/failback_runtime_test.go @@ -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, TargetEndpoint: r1Endpoint, 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") }} }, @@ -155,9 +155,9 @@ func TestFailbackAuthorityRuntime_RefusesAddressesThatAreNotTheMastersRecord(t * req := validAuthorityFailbackRequest() req.TargetDataAddr, req.TargetCtrlAddr = c.data, c.ctrl gated := false - rt := FailbackAuthorityRuntime{Publisher: pub, TargetEndpoint: c.endpoint, Gate: func(v, r string) (adapter.PrimaryEvidence, error) { + rt := FailbackAuthorityRuntime{Publisher: pub, TargetEndpoint: c.endpoint, Gate: func(v, r string, cur AuthorityBasis) (adapter.PrimaryEvidence, error) { gated = true - return allowGate(v, r) + return allowGate(v, r, cur) }} if _, err := rt.ExecuteFailback(context.Background(), req); !errors.Is(err, ErrFailbackTargetEndpoint) { t.Fatalf("err=%v; want ErrFailbackTargetEndpoint", err) @@ -171,3 +171,34 @@ func TestFailbackAuthorityRuntime_RefusesAddressesThatAreNotTheMastersRecord(t * }) } } + +// 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) + } +} diff --git a/seaweed-block/core/authority/policy.go b/seaweed-block/core/authority/policy.go index 12d19a465d..d64e3a29cd 100644 --- a/seaweed-block/core/authority/policy.go +++ b/seaweed-block/core/authority/policy.go @@ -88,6 +88,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 { diff --git a/seaweed-block/core/authority/promotion_basis_census_test.go b/seaweed-block/core/authority/promotion_basis_census_test.go index 7b8e1b4812..9dc4fd1134 100644 --- a/seaweed-block/core/authority/promotion_basis_census_test.go +++ b/seaweed-block/core/authority/promotion_basis_census_test.go @@ -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", } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ce0f8f4494..0d6fd3031b 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -453,7 +453,7 @@ 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, TargetEndpoint: h.replicaEndpoint} + 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 diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index 88469beda2..b10239640e 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -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() diff --git a/seaweed-block/core/host/master/planned_move_paths_test.go b/seaweed-block/core/host/master/planned_move_paths_test.go index 86bc59771a..4a26790840 100644 --- a/seaweed-block/core/host/master/planned_move_paths_test.go +++ b/seaweed-block/core/host/master/planned_move_paths_test.go @@ -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) +} diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter.go b/seaweed-block/core/ops/failback_authority_runtime_adapter.go index fe20618cf1..89bd7b53c2 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter.go @@ -17,7 +17,7 @@ type AuthorityFailbackRuntime struct { // NewAuthorityFailbackRuntime adapts the authority failback runtime; gate is // 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) (adapter.PrimaryEvidence, error), endpoint func(volumeID, targetReplicaID string) (string, string, bool)) *AuthorityFailbackRuntime { +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, TargetEndpoint: endpoint}, } diff --git a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go index 54c45deaa7..e7f928772a 100644 --- a/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go +++ b/seaweed-block/core/ops/failback_authority_runtime_adapter_test.go @@ -147,7 +147,7 @@ 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 } From b3e6cdd4b091e0a035820a37775731490a6620a5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:21:01 -0800 Subject: [PATCH 08/10] fix(sw-block): ops failover needs a client identity and tells an unknown outcome from a refusal Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/failover.go | 50 +++++- seaweed-block/cmd/sw-block/failover_test.go | 159 +++++++++++++++++++- 2 files changed, 202 insertions(+), 7 deletions(-) diff --git a/seaweed-block/cmd/sw-block/failover.go b/seaweed-block/cmd/sw-block/failover.go index 9df0b2e0ea..32bbd6ef76 100644 --- a/seaweed-block/cmd/sw-block/failover.go +++ b/seaweed-block/cmd/sw-block/failover.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "flag" "fmt" "io" @@ -10,6 +11,9 @@ import ( "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" @@ -35,15 +39,22 @@ 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. A refusal changes nothing. +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. Exit: 0 moved; 1 refused or failed; 2 -bad arguments. +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 { @@ -80,6 +91,14 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int { 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{ @@ -100,8 +119,13 @@ func runOpsFailover(args []string, stdout, stderr io.Writer) int { 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: %v\n", opsFailoverName, err) + 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 @@ -126,3 +150,21 @@ func parseReplicaAtEpoch(s string) (string, uint64, bool) { } 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 +} diff --git a/seaweed-block/cmd/sw-block/failover_test.go b/seaweed-block/cmd/sw-block/failover_test.go index ad84fc1d8c..216af4ff2a 100644 --- a/seaweed-block/cmd/sw-block/failover_test.go +++ b/seaweed-block/cmd/sw-block/failover_test.go @@ -3,13 +3,25 @@ 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 { @@ -25,6 +37,7 @@ func (f *fakeFailoverRuntime) ExecuteFailback(_ context.Context, req ops.Failbac 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 } @@ -65,7 +78,7 @@ func TestOpsFailoverSendsTheExpectedLineAndReportsTheMove(t *testing.T) { // the line is not a move either. func TestOpsFailoverReportsARefusal(t *testing.T) { for _, f := range []*fakeFailoverRuntime{ - {err: errors.New("fenced move: the fencing round at epoch 5 does not allow r2")}, + {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) @@ -122,8 +135,8 @@ func TestAlphaStackDeploysTheManualFailover(t *testing.T) { 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, "deploy/k8s/alpha/failback-executor.yaml"}, - "scripts/run-alpha-app-demo.sh": {crd, "deploy/k8s/alpha/failback-executor.yaml"}, + "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"}, } { @@ -135,3 +148,143 @@ func TestAlphaStackDeploysTheManualFailover(t *testing.T) { } } } + +// 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) + } +} From 3ff0a640fdbd5a935d0796910d9fd3a8925bed9a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:21:01 -0800 Subject: [PATCH 09/10] fix(k8s-alpha): render the failback executor with the selected image Co-Authored-By: Claude Opus 5.5 --- seaweed-block/scripts/install-k8s-alpha.sh | 3 ++- seaweed-block/scripts/render-k8s-alpha-image.sh | 11 +++++++++++ seaweed-block/scripts/run-alpha-app-demo.sh | 3 ++- 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/scripts/render-k8s-alpha-image.sh diff --git a/seaweed-block/scripts/install-k8s-alpha.sh b/seaweed-block/scripts/install-k8s-alpha.sh index bb92c41e96..038bf2ad34 100755 --- a/seaweed-block/scripts/install-k8s-alpha.sh +++ b/seaweed-block/scripts/install-k8s-alpha.sh @@ -269,7 +269,8 @@ kubectl -n kube-system wait --for=condition=available deploy/sw-blockmaster --ti log "apply CSI components" kubectl apply -f "$ROOT/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" | tee "$ARTIFACT_DIR/apply-failback-crd.log" -kubectl apply -f "$ROOT/deploy/k8s/alpha/failback-executor.yaml" | tee "$ARTIFACT_DIR/apply-failback-executor.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" diff --git a/seaweed-block/scripts/render-k8s-alpha-image.sh b/seaweed-block/scripts/render-k8s-alpha-image.sh new file mode 100644 index 0000000000..d5db336401 --- /dev/null +++ b/seaweed-block/scripts/render-k8s-alpha-image.sh @@ -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; } diff --git a/seaweed-block/scripts/run-alpha-app-demo.sh b/seaweed-block/scripts/run-alpha-app-demo.sh index 967c8624c1..70cfc7ae4f 100755 --- a/seaweed-block/scripts/run-alpha-app-demo.sh +++ b/seaweed-block/scripts/run-alpha-app-demo.sh @@ -1546,7 +1546,8 @@ kubectl -n kube-system wait --for=condition=available deploy/sw-blockmaster --ti log "apply CSI manifests" kubectl apply -f "$ROOT/charts/seaweed-block/crds/swblockreplicafailbacks.block.seaweedfs.com.yaml" | tee "$ARTIFACT_DIR/apply-failback-crd.log" -kubectl apply -f "$ROOT/deploy/k8s/alpha/failback-executor.yaml" | tee "$ARTIFACT_DIR/apply-failback-executor.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" From 9379f5c059d234cc27084a3ff84cbd2cb5a3d4ac Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 18:27:33 -0800 Subject: [PATCH 10/10] fix(k8s-alpha): escape the image for sed as the install scripts do Co-Authored-By: Claude Opus 5.5 --- seaweed-block/scripts/render-k8s-alpha-image.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/scripts/render-k8s-alpha-image.sh b/seaweed-block/scripts/render-k8s-alpha-image.sh index d5db336401..5ef42384c7 100644 --- a/seaweed-block/scripts/render-k8s-alpha-image.sh +++ b/seaweed-block/scripts/render-k8s-alpha-image.sh @@ -4,7 +4,7 @@ # 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')" +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"