From e9c7a5c4da4087108f1626eccec468a7bb82ffca Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 01:22:52 -0800 Subject: [PATCH] sw-block: finalize-format and a refused move answer with typed fields A script must not parse message text. finalize-format now exits 0 for finalized or already finalized, 2 for a refusal, 75 when the master cannot be reached, and 1 for any other failure (a failed write of the format record included); --json prints result, reason, hosts, format_level and message for every outcome. The master's refusal carries each refused host in its ErrorInfo metadata, and a failed attestation write is Internal, not Unavailable. A move onto a host whose binary reported a read level below the cluster's carries the typed reason BINARY_TOO_OLD; ops workspace move and force-move show it in --json. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/cluster_format.go | 95 ++++++++++++++++-- .../cmd/sw-block/cluster_format_json_test.go | 97 +++++++++++++++++++ .../cmd/sw-block/cluster_format_test.go | 10 +- seaweed-block/cmd/sw-block/workspace.go | 5 +- seaweed-block/cmd/sw-block/workspace_clean.go | 33 ++++++- .../cmd/sw-block/workspace_clean_test.go | 27 ++++++ seaweed-block/core/host/master/format_gate.go | 49 ++++++++-- .../core/host/master/format_gate_test.go | 16 ++- .../core/host/master/workspace_service.go | 33 ++++--- .../core/rpc/lifecycleclient/reason.go | 24 ++++- seaweed-block/core/rpc/wsclient/wsclient.go | 19 ++++ seaweed-block/docs/releases/v1.1.md | 7 ++ 12 files changed, 369 insertions(+), 46 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/cluster_format_json_test.go diff --git a/seaweed-block/cmd/sw-block/cluster_format.go b/seaweed-block/cmd/sw-block/cluster_format.go index 33cdaa8fb4..60fbe63c01 100644 --- a/seaweed-block/cmd/sw-block/cluster_format.go +++ b/seaweed-block/cmd/sw-block/cluster_format.go @@ -2,13 +2,17 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "io" + "sort" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/ops" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "github.com/seaweedfs/seaweed-block/core/rpc/link" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -41,6 +45,32 @@ func runCluster(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } +// finalize-format's exit codes, part of its contract: a script decides by +// them and by the --json answer, never by message text. +const ( + finalizeExitOK = 0 // finalized, or already finalized + finalizeExitFailed = 1 // any other failure, a failed durable write included + finalizeExitRefused = 2 // the master refused: hosts below the level + finalizeExitTempFail = 75 // transient: the master unreachable (EX_TEMPFAIL) +) + +// finalizeAnswer is finalize-format's --json answer, one shape for every +// outcome. Result is finalized, already, refused, unavailable or failed; +// Reason the master's typed reason (or the gRPC code, "" on success); Hosts +// the refused hosts, each with what it reported (empty otherwise). +type finalizeAnswer struct { + Result string `json:"result"` + Reason string `json:"reason"` + Hosts []finalizeHost `json:"hosts"` + FormatLevel uint32 `json:"format_level"` + Message string `json:"message"` +} + +type finalizeHost struct { + Server string `json:"server"` + Reported string `json:"reported"` +} + // runClusterFinalizeFormat raises the cluster's format level to 1. Going // back to v1.0.x works only before it: afterwards a v1.0.x master or holder // refuses the store (an expected refusal, not damage). The master refuses @@ -50,29 +80,74 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int { fs.SetOutput(stderr) master := fs.String("master", "", "blockmaster gRPC address (required)") timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer") + jsonOut := fs.Bool("json", false, "print the typed answer as JSON: result, reason, hosts, format_level, message") + answer := finalizeAnswer{Hosts: []finalizeHost{}} + defer func() { + if *jsonOut { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err) + } + } + }() + fail := func(result, reason, msg string, code int) int { + answer.Result, answer.Reason, answer.Message = result, reason, msg + fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", msg) + return code + } if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" { - fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s]") - return ops.VolumeStatusExitInvalid + fmt.Fprintln(stderr, "usage: sw-block cluster finalize-format --master host:port [--timeout 30s] [--json]") + answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master is required" + return finalizeExitFailed } c, closeFn, err := clusterLifecycleDial(*master) if err != nil { - fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", err) - return ops.VolumeStatusExitUnhealthy + return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail) } defer closeFn() ctx, cancel := context.WithTimeout(context.Background(), *timeout) defer cancel() resp, err := c.FinalizeFormat(ctx, &control.FinalizeFormatRequest{Level: 1}, grpc.WaitForReady(false)) if err != nil { - fmt.Fprintln(stderr, "sw-block: cluster finalize-format:", status.Convert(err).Message()) - return clusterExit(err) + msg := status.Convert(err).Message() + reason, md := lifecycleclient.ReasonDetail(err) + if reason == "" { + reason = status.Code(err).String() + } + switch status.Code(err) { + case codes.FailedPrecondition: + answer.Hosts = finalizeHosts(md) + return fail("refused", reason, msg, finalizeExitRefused) + case codes.Unavailable, codes.DeadlineExceeded: + return fail("unavailable", reason, msg, finalizeExitTempFail) + } + return fail("failed", reason, msg, finalizeExitFailed) } + answer.FormatLevel = resp.GetFormatLevel() if resp.GetAlready() { - fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel()) - return ops.VolumeStatusExitOK + answer.Result, answer.Message = "already", "already finalized; nothing written" + if !*jsonOut { + fmt.Fprintf(stdout, "format level %d (already finalized; nothing written)\n", resp.GetFormatLevel()) + } + return finalizeExitOK } - fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel()) - return ops.VolumeStatusExitOK + answer.Result, answer.Message = "finalized", "v1.0.x binaries now refuse this cluster's stores" + if !*jsonOut { + fmt.Fprintf(stdout, "format level %d finalized: v1.0.x binaries now refuse this cluster's stores\n", resp.GetFormatLevel()) + } + return finalizeExitOK +} + +// finalizeHosts reads the refused hosts from the refusal's typed metadata, +// sorted by server id. +func finalizeHosts(md map[string]string) []finalizeHost { + hosts := []finalizeHost{} + for k, v := range md { + if server, ok := strings.CutPrefix(k, lifecycleclient.HostMetadataPrefix); ok { + hosts = append(hosts, finalizeHost{Server: server, Reported: v}) + } + } + sort.Slice(hosts, func(i, j int) bool { return hosts[i].Server < hosts[j].Server }) + return hosts } // runClusterRetireHost removes a registered host from the node inventory. diff --git a/seaweed-block/cmd/sw-block/cluster_format_json_test.go b/seaweed-block/cmd/sw-block/cluster_format_json_test.go new file mode 100644 index 0000000000..da2fe75f04 --- /dev/null +++ b/seaweed-block/cmd/sw-block/cluster_format_json_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "reflect" + "sort" + "testing" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// finalize-format's answer is typed: exit 0 for finalized or already, 2 for +// a refusal, 75 for a transient failure (the master unreachable), 1 for any +// other failure (a failed durable write included); --json prints the same +// keys for every outcome, and a refusal lists each refused host from the +// master's typed metadata, never from its message text. +func TestClusterFinalizeFormatTypedAnswer(t *testing.T) { + refused := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"), + lifecycleclient.ReasonFormatHostsTooOld, map[string]string{ + lifecycleclient.HostMetadataPrefix + "node-c": "no report", + lifecycleclient.HostMetadataPrefix + "node-b": "process 10.0.0.2:1 of v1 (reads level 0)", + }).Err() + for _, tc := range []struct { + name string + resp *control.FinalizeFormatResponse + err error + dialErr error + exit int + result string + reason string + hosts []finalizeHost + levelOut uint32 + }{ + {name: "finalized", resp: &control.FinalizeFormatResponse{FormatLevel: 1}, exit: 0, result: "finalized", levelOut: 1}, + {name: "already", resp: &control.FinalizeFormatResponse{FormatLevel: 1, Already: true}, exit: 0, result: "already", levelOut: 1}, + {name: "refused", err: refused, exit: 2, result: "refused", reason: lifecycleclient.ReasonFormatHostsTooOld, + hosts: []finalizeHost{{"node-b", "process 10.0.0.2:1 of v1 (reads level 0)"}, {"node-c", "no report"}}}, + {name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"}, + {name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "write-failed", err: status.Error(codes.Internal, "format finalize: attestation write failed"), exit: 1, result: "failed", reason: "Internal"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeClusterMaster{finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + return tc.resp, tc.err + }} + withClusterMaster(t, f) + if tc.dialErr != nil { + clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr } + } + var out, errOut bytes.Buffer + code := run([]string{"cluster", "finalize-format", "--master", "m:1", "--json"}, &out, &errOut) + if code != tc.exit { + t.Fatalf("exit %d, want %d (stderr %q)", code, tc.exit, errOut.String()) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(out.Bytes(), &keys); err != nil { + t.Fatalf("--json output %q: %v", out.String(), err) + } + var names []string + for k := range keys { + names = append(names, k) + } + sort.Strings(names) + if want := []string{"format_level", "hosts", "message", "reason", "result"}; !reflect.DeepEqual(names, want) { + t.Fatalf("--json keys %v, want %v for every outcome", names, want) + } + var a finalizeAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil { + t.Fatal(err) + } + if a.Result != tc.result || a.Reason != tc.reason || a.FormatLevel != tc.levelOut { + t.Fatalf("answer %+v, want result %q reason %q level %d", a, tc.result, tc.reason, tc.levelOut) + } + if want := tc.hosts; want == nil && len(a.Hosts) != 0 || want != nil && !reflect.DeepEqual(a.Hosts, want) { + t.Fatalf("hosts %+v, want %+v", a.Hosts, want) + } + }) + } +} + +// A usage error is "any other failure": exit 1, with the same --json shape. +func TestClusterFinalizeFormatUsageIsAFailure(t *testing.T) { + var out, errOut bytes.Buffer + if code := run([]string{"cluster", "finalize-format", "--json"}, &out, &errOut); code != 1 { + t.Fatalf("finalize without --master: exit %d, want 1", code) + } + var a finalizeAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil || a.Result != "failed" || a.Reason != "usage" || a.Hosts == nil { + t.Fatalf("usage answer %q: %+v %v", out.String(), a, err) + } +} diff --git a/seaweed-block/cmd/sw-block/cluster_format_test.go b/seaweed-block/cmd/sw-block/cluster_format_test.go index 18ad1504df..8340998f76 100644 --- a/seaweed-block/cmd/sw-block/cluster_format_test.go +++ b/seaweed-block/cmd/sw-block/cluster_format_test.go @@ -35,8 +35,8 @@ func withClusterMaster(t *testing.T, f *fakeClusterMaster) { } } -// finalize-format asks level 1; a refusal names the old hosts and exits 1, -// a finalize and an already-finalized cluster exit 0, a malformed command 2. +// finalize-format asks level 1; a refusal names the old hosts and exits 2, +// a finalize and an already-finalized cluster exit 0, a malformed command 1. func TestClusterFinalizeFormat(t *testing.T) { refuse := true f := &fakeClusterMaster{finalize: func(r *control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { @@ -50,7 +50,7 @@ func TestClusterFinalizeFormat(t *testing.T) { }} withClusterMaster(t, f) var out, errOut bytes.Buffer - if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "node-b (no report)") { + if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "node-b (no report)") { t.Fatalf("refused finalize: exit %d, stderr %q", code, errOut.String()) } refuse = false @@ -65,8 +65,8 @@ func TestClusterFinalizeFormat(t *testing.T) { if code := run([]string{"cluster", "finalize-format", "--master", "m:1"}, &out, &errOut); code != 0 || !strings.Contains(out.String(), "already finalized") { t.Fatalf("already finalized: exit %d, stdout %q", code, out.String()) } - if code := run([]string{"cluster", "finalize-format"}, &out, &errOut); code != 2 { - t.Fatalf("finalize without --master: exit %d, want 2", code) + if code := run([]string{"cluster", "finalize-format"}, &out, &errOut); code != 1 { + t.Fatalf("finalize without --master: exit %d, want 1", code) } } diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index 14f748787c..c77e1e5968 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -127,6 +127,7 @@ type workspaceForceMoveAnswer struct { Admitted bool `json:"admitted"` Until string `json:"until"` Code string `json:"code"` + Reason string `json:"reason,omitempty"` // the master's typed reason, e.g. BINARY_TOO_OLD MoveID string `json:"move_id,omitempty"` NewEpoch *uint64 `json:"new_epoch,omitempty"` NewHost string `json:"new_host,omitempty"` @@ -210,7 +211,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { return workspacePreview(ctx, c, m, stdout, stderr, nil) } g, err := c.ForceMove(ctx, m) - answer.Code = wsclient.CodeOf(err) + answer.Code, answer.Reason = wsclient.CodeOf(err), wsclient.ReasonOf(err) switch o := wsclient.OutcomeOf(err); o { case wsclient.OutcomeOK: answer.issued(g, true) @@ -280,7 +281,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced p, err := c.PreviewForcedMove(ctx, m) if err != nil { if answer != nil { - answer.Code = wsclient.CodeOf(err) + answer.Code, answer.Reason = wsclient.CodeOf(err), wsclient.ReasonOf(err) } fmt.Fprintf(stderr, "%s --dry-run: %v\n", workspaceForceMoveName, err) if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { diff --git a/seaweed-block/cmd/sw-block/workspace_clean.go b/seaweed-block/cmd/sw-block/workspace_clean.go index 1b940489b3..65b0c599ae 100644 --- a/seaweed-block/cmd/sw-block/workspace_clean.go +++ b/seaweed-block/cmd/sw-block/workspace_clean.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "io" @@ -18,8 +19,16 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int { fs.SetOutput(stderr) var q control.WorkspaceMove var master string - var clean bool + var clean, jsonOutput bool var timeout time.Duration + answer := workspaceCleanMoveAnswer{Code: "InvalidArgument"} + defer func() { + if jsonOutput { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintf(stderr, "workspace move: JSON output: %v\n", err) + } + } + }() fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") fs.StringVar(&q.VolumeId, "volume", "", "volume id") fs.StringVar(&q.ExpectedReplicaId, "replica", "", "current logical replica id") @@ -30,6 +39,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int { fs.StringVar(&q.TargetCtrlAddr, "target-ctrl", "", "target control address host:port") fs.BoolVar(&clean, "clean", false, "required: move using the detached HEAD and matching recorded host ACK") fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC") + fs.BoolVar(&jsonOutput, "json", false, "print the typed answer: issued, refusal code and reason, issued move") if err := fs.Parse(args); err != nil { return wsExitRefusedLocally } @@ -47,6 +57,7 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() g, err := c.CleanMove(ctx, &q) + answer.Code, answer.Reason = wsclient.CodeOf(err), wsclient.ReasonOf(err) if err != nil { fmt.Fprintf(stderr, "workspace move: %v\n", err) if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { @@ -54,7 +65,27 @@ func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int { } return workspaceExit(wsclient.OutcomeOf(err)) } + answer.Issued, answer.MoveID, answer.NewHost, answer.NewReplica = true, g.GetRequestId(), g.GetNewHost(), g.GetNewReplicaId() + epoch := g.GetNewEpoch() + answer.NewEpoch = &epoch + if jsonOutput { + return wsExitOK + } fmt.Fprintf(stdout, "clean move issued: volume %s request %s: %s@%d -> %s@%d on %s (sealed HEAD gen %d, remote LSN %d)\n", g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn()) fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", g.GetVolumeId(), g.GetNewHost()) return wsExitOK } + +// workspaceCleanMoveAnswer is the move's --json answer, output only: Code is +// the RPC's code ("" when issued), Reason the master's typed refusal reason +// (for example BINARY_TOO_OLD when the target's binary does not read the +// cluster's format level). +type workspaceCleanMoveAnswer struct { + Issued bool `json:"issued"` + Code string `json:"code"` + Reason string `json:"reason,omitempty"` + MoveID string `json:"move_id,omitempty"` + NewEpoch *uint64 `json:"new_epoch,omitempty"` + NewHost string `json:"new_host,omitempty"` + NewReplica string `json:"new_replica,omitempty"` +} diff --git a/seaweed-block/cmd/sw-block/workspace_clean_test.go b/seaweed-block/cmd/sw-block/workspace_clean_test.go index 0892b69855..cad21e3f11 100644 --- a/seaweed-block/cmd/sw-block/workspace_clean_test.go +++ b/seaweed-block/cmd/sw-block/workspace_clean_test.go @@ -1,10 +1,12 @@ package main import ( + "encoding/json" "strings" "testing" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -98,3 +100,28 @@ func TestWorkspaceCleanMovePreservesRefusalAndUnknown(t *testing.T) { }) } } + +// A move refused because the target's binary does not read the cluster's +// format level shows the master's typed reason in --json (the refusal's +// ErrorInfo detail), and an issued move shows its grant. +func TestWorkspaceCleanMoveJSONCarriesTheTypedReason(t *testing.T) { + refuse := true + f := &fakeWorkspace{move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if refuse { + return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, "message text a script must not parse"), lifecycleclient.ReasonBinaryTooOld).Err() + } + return cleanGrant(q), nil + }} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(cleanMoveArgs(addr, "--json")) + var a workspaceCleanMoveAnswer + if code != wsExitRefused || json.Unmarshal([]byte(out), &a) != nil || a.Issued || a.Code != "FailedPrecondition" || a.Reason != lifecycleclient.ReasonBinaryTooOld { + t.Fatalf("refused move: exit=%d out=%q err=%q answer=%+v", code, out, errOut, a) + } + refuse = false + code, out, errOut = runCLI(cleanMoveArgs(addr, "--json")) + a = workspaceCleanMoveAnswer{} + if code != wsExitOK || json.Unmarshal([]byte(out), &a) != nil || !a.Issued || a.Reason != "" || a.MoveID != "clean-1" || a.NewEpoch == nil { + t.Fatalf("issued move: exit=%d out=%q err=%q answer=%+v", code, out, errOut, a) + } +} diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 492fba1b01..54cc43b1d4 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -161,31 +161,60 @@ func (h *Host) formatTooOld(server string) string { return fmt.Sprintf("node %q reads format level %d (the lowest of its processes); the cluster's format level is %d (binary_too_old)", server, reads, h.formatLevel()) } +// hostBelow is one server below a format level and what it reported. +type hostBelow struct{ server, detail string } + +// formatTooOldReason is the typed reason of formatTooOld: ReasonBinaryTooOld +// when server reported a read level below the cluster's, "" when it is +// eligible or has not reported one (its binary is then unknown). +func (h *Host) formatTooOldReason(server string) string { + if h.formatEligible(server) { + return "" + } + if _, ok := h.reads.of(server, h.servedBy(server)); !ok { + return "" + } + return lifecycleclient.ReasonBinaryTooOld +} + // belowLevel lists the given servers whose reported read level is below // level, or that have not reported, sorted, each with what it reported. -func (h *Host) belowLevel(servers []string, level uint32) []string { - var out []string +func (h *Host) belowLevel(servers []string, level uint32) []hostBelow { + var out []hostBelow for _, s := range servers { served := h.servedBy(s) reads, ok := h.reads.of(s, served) switch { case !ok: - out = append(out, fmt.Sprintf("%s (no report)", s)) + out = append(out, hostBelow{s, "no report"}) case reads < level: - out = append(out, fmt.Sprintf("%s (process %s)", s, strings.Join(h.reads.below(s, level, served), ", "))) + out = append(out, hostBelow{s, "process " + strings.Join(h.reads.below(s, level, served), ", ")}) } } - sort.Strings(out) + sort.Slice(out, func(i, j int) bool { return out[i].server < out[j].server }) return out } // errFormatHostsTooOld is a finalize refused for registered hosts that do // not read the new level; errHostHoldsWork a retire refused for a host that // holds work. Both name what refused them. -type errFormatHostsTooOld struct{ hosts []string } +type errFormatHostsTooOld struct{ hosts []hostBelow } func (e errFormatHostsTooOld) Error() string { - return fmt.Sprintf("format finalize refused: registered hosts do not read format level 1: %s; upgrade each one, or retire it (sw-block cluster retire-host)", strings.Join(e.hosts, ", ")) + named := make([]string, len(e.hosts)) + for i, b := range e.hosts { + named[i] = fmt.Sprintf("%s (%s)", b.server, b.detail) + } + return fmt.Sprintf("format finalize refused: registered hosts do not read format level 1: %s; upgrade each one, or retire it (sw-block cluster retire-host)", strings.Join(named, ", ")) +} + +// metadata keys each refused host for the refusal's typed detail. +func (e errFormatHostsTooOld) metadata() map[string]string { + md := make(map[string]string, len(e.hosts)) + for _, b := range e.hosts { + md[lifecycleclient.HostMetadataPrefix+b.server] = b.detail + } + return md } type errHostHoldsWork struct { @@ -268,11 +297,13 @@ func (s *services) FinalizeFormat(ctx context.Context, req *control.FinalizeForm var old errFormatHostsTooOld switch { case errors.As(err, &old): - return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonFormatHostsTooOld).Err() + return nil, lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonFormatHostsTooOld, old.metadata()).Err() case err != nil && req.GetLevel() != 1: return nil, status.Error(codes.InvalidArgument, err.Error()) case err != nil: - return nil, status.Error(codes.Unavailable, err.Error()) + // The attestation write failed: not a transient answer, the level + // is unchanged and the operator must look at the master's store. + return nil, status.Error(codes.Internal, err.Error()) } return &control.FinalizeFormatResponse{FormatLevel: s.host.formatLevel(), Already: already}, nil } diff --git a/seaweed-block/core/host/master/format_gate_test.go b/seaweed-block/core/host/master/format_gate_test.go index 4a9d57fc0f..bbc6500985 100644 --- a/seaweed-block/core/host/master/format_gate_test.go +++ b/seaweed-block/core/host/master/format_gate_test.go @@ -108,6 +108,11 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) { if status.Code(moveErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(moveErr).Message(), "move target node \"node-b\" "+why) { t.Fatalf("level 1: MoveWorkspace onto node-b: %v, want %q", moveErr, why) } + // The typed reason names an old binary only when node-b reported one. + wantReason := map[bool]string{true: lifecycleclient.ReasonBinaryTooOld, false: ""}[reported] + if got := reasonOf(moveErr); got != wantReason { + t.Fatalf("level 1: MoveWorkspace onto node-b: reason %q, want %q", got, wantReason) + } }) } } @@ -182,7 +187,8 @@ func TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable(t *testing.T) { for _, step := range []struct { reads *uint32 want string - }{{nil, "node-b (no report)"}, {ptr(uint32(0)), "node-b (process 127.0.0.1:19311 of hb-node-b (reads level 0))"}} { + md string + }{{nil, "node-b (no report)", "no report"}, {ptr(uint32(0)), "node-b (process 127.0.0.1:19311 of hb-node-b (reads level 0))", "process 127.0.0.1:19311 of hb-node-b (reads level 0)"}} { if step.reads != nil { if err := r.fgHeartbeat("node-b", *step.reads); err != nil { t.Fatal(err) @@ -192,6 +198,10 @@ func TestFinalizeFormatNeedsEveryRegisteredHostAndIsDurable(t *testing.T) { if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonFormatHostsTooOld || !strings.Contains(status.Convert(err).Message(), step.want) { t.Fatalf("finalize with %s: %v (reason %q)", step.want, err, reasonOf(err)) } + // The refused hosts are typed too: one metadata entry per host. + if _, md := lifecycleclient.ReasonDetail(err); len(md) != 1 || md[lifecycleclient.HostMetadataPrefix+"node-b"] != step.md { + t.Fatalf("finalize with %s: metadata %v, want node-b = %q", step.want, md, step.md) + } if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 { t.Fatal("a refused finalize changed the level") } @@ -280,8 +290,8 @@ func TestAFailedFinalizeWriteLeavesLevel0(t *testing.T) { saved := syncAttestationDir t.Cleanup(func() { syncAttestationDir = saved }) syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") } - if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); err == nil { - t.Fatal("a finalize whose envelope write failed succeeded") + if _, err := r.lc.FinalizeFormat(r.ctx, &control.FinalizeFormatRequest{Level: 1}); status.Code(err) != codes.Internal { + t.Fatalf("a finalize whose envelope write failed: %v, want Internal (a failure, not a transient answer)", err) } if r.m.formatLevel() != 0 || r.m.Publisher().FormatLevel() != 0 { t.Fatalf("a failed finalize switched the level: master %d, publisher %d", r.m.formatLevel(), r.m.Publisher().FormatLevel()) diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 401c570c2c..a82b667d25 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -11,6 +11,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -368,8 +369,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - if refusal = why; refusal != "" { - return nil, status.Error(codes.FailedPrecondition, refusal) + if refusal = why.text; refusal != "" { + st := status.New(codes.FailedPrecondition, refusal) + if why.reason != "" { + st = lifecycleclient.WithReason(st, why.reason) + } + return nil, st.Err() } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { return nil, workspaceError(err) @@ -419,12 +424,12 @@ func (s *services) issuedRecord(req authority.WorkspaceMoveRequest) *control.Wor // blockmaster's own refusal of it ("" when none): endpoints, source host, // target node and binding. It reads and writes nothing else; MoveWorkspace // and PreviewWorkspaceMove share it. Caller holds workspaceMu. -func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req authority.WorkspaceMoveRequest, target lifecycle.NodeRegistration, replay bool, refusal string, err error) { +func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req authority.WorkspaceMoveRequest, target lifecycle.NodeRegistration, replay bool, refusal moveRefusal, err error) { oldHost := s.host.workspaceSourceHost(q.GetVolumeId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()) target, ok := s.host.lifecycle.Nodes.GetNode(q.GetTargetServerId()) bindings, explicit, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) if err != nil { - return authority.WorkspaceMoveRequest{}, lifecycle.NodeRegistration{}, false, "", err + return authority.WorkspaceMoveRequest{}, lifecycle.NodeRegistration{}, false, moveRefusal{}, err } // A volume without per-volume bindings may move to any port on the // target node's registered hosts (a host runs several slots): the host @@ -446,23 +451,27 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho replay = ok && s.host.Publisher().IssuedWorkspaceMove(req) switch { case endpointErr != nil: - refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) + refusal.text = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) case oldHost == "": - refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) + refusal.text = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) case !ok: - refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) + refusal.text = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) // The authority still checks the clean seal/ACK or forced lease barrier // after these endpoint and binding checks, also for a same-host target. case !replay && s.host.colocatedTargetRefused(target.ServerID): - refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID) + refusal.text = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID) case !replay && s.host.formatTooOld(target.ServerID) != "": - refusal = "move target " + s.host.formatTooOld(target.ServerID) + refusal = moveRefusal{"move target " + s.host.formatTooOld(target.ServerID), s.host.formatTooOldReason(target.ServerID)} case !matched: - refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) + refusal.text = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) } return req, target, replay, refusal, nil } +// moveRefusal is blockmaster's own refusal of a move: its text and, when +// one applies, its typed reason (an ErrorInfo detail on the error). +type moveRefusal struct{ text, reason string } + // sameHost reports whether two host:port addresses name the same host: // canonical host parts (equivalent IP spellings equal), no name resolution. func sameHost(a, b string) bool { @@ -582,8 +591,8 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac pv := s.host.Publisher().PreviewWorkspaceForcedMove(req) out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS switch { - case why != "": - out.Admitted, out.Reason = false, why + case why.text != "": + out.Admitted, out.Reason = false, why.text case !pv.Admitted: out.Reason = pv.Reason case pv.Replay: diff --git a/seaweed-block/core/rpc/lifecycleclient/reason.go b/seaweed-block/core/rpc/lifecycleclient/reason.go index 6fa801ee9b..903458b8de 100644 --- a/seaweed-block/core/rpc/lifecycleclient/reason.go +++ b/seaweed-block/core/rpc/lifecycleclient/reason.go @@ -31,7 +31,13 @@ const ( // WithReason returns st with an ErrorInfo detail carrying reason in // ErrorDomain; st unchanged if the detail cannot be attached. func WithReason(st *status.Status, reason string) *status.Status { - if d, err := st.WithDetails(&errdetails.ErrorInfo{Reason: reason, Domain: ErrorDomain}); err == nil { + return WithReasonMetadata(st, reason, nil) +} + +// WithReasonMetadata is WithReason with typed fields in the detail's +// metadata (for example one entry per refused host). +func WithReasonMetadata(st *status.Status, reason string, md map[string]string) *status.Status { + if d, err := st.WithDetails(&errdetails.ErrorInfo{Reason: reason, Domain: ErrorDomain, Metadata: md}); err == nil { return d } return st @@ -40,14 +46,24 @@ func WithReason(st *status.Status, reason string) *status.Status { // Reason is the typed refusal reason in err's gRPC status (an ErrorInfo in // ErrorDomain), or "" when it carries none. err may be wrapped. func Reason(err error) string { + reason, _ := ReasonDetail(err) + return reason +} + +// ReasonDetail is Reason with the detail's metadata (nil when none). +func ReasonDetail(err error) (string, map[string]string) { var se interface{ GRPCStatus() *status.Status } if !errors.As(err, &se) { - return "" + return "", nil } for _, d := range se.GRPCStatus().Details() { if info, ok := d.(*errdetails.ErrorInfo); ok && info.GetDomain() == ErrorDomain { - return info.GetReason() + return info.GetReason(), info.GetMetadata() } } - return "" + return "", nil } + +// HostMetadataPrefix keys one refused host in a reason's metadata: +// "host." maps to what that host reported. +const HostMetadataPrefix = "host." diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index 94c9b262c7..dc092d2e77 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -18,6 +18,7 @@ import ( "time" control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" "github.com/seaweedfs/seaweed-block/core/rpc/link" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -56,6 +57,7 @@ var ErrConfirmation = errors.New("forced move confirmation") type Error struct { Outcome Outcome Code string // original gRPC status code, when a remote call supplied one + Reason string // the master's typed refusal reason (its ErrorInfo detail), when it sent one Op string Err error } @@ -104,6 +106,23 @@ func classify(op string, err error) error { if err == nil { return nil } + e := classifyCode(op, err) + if ce, ok := e.(*Error); ok { + ce.Reason = lifecycleclient.Reason(err) + } + return e +} + +// ReasonOf is the master's typed refusal reason carried by err, or "". +func ReasonOf(err error) string { + var e *Error + if errors.As(err, &e) { + return e.Reason + } + return "" +} + +func classifyCode(op string, err error) error { switch status.Code(err) { case codes.Unauthenticated, codes.PermissionDenied: return &Error{Outcome: OutcomeNotAuthorized, Code: status.Code(err).String(), Op: op, Err: fmt.Errorf("not authorized by blockmaster: %s (its role file must list this certificate's fingerprint with a role allowed to do this)", status.Convert(err).Message())} diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 8938c48b43..453b38287f 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -47,5 +47,12 @@ These notes collect v1.1's changes as they land; v1.1 is not released. superblock`; without one, `HEAD written by a newer version` (v1.0.0 and v1.0.1 report that HEAD as malformed). None of these means damage: do not rebuild the volume; start v1.1 again. - After the finalize, a host whose binary does not read v1.1 is refused (`binary_too_old`) and gets no volume. + A move onto such a host is refused with the typed reason `BINARY_TOO_OLD` (`reason` in + `sw-block ops workspace move --json` and `force-move --json`). + - `finalize-format` answers with exit codes a script can rely on, and `--json` prints the same keys for every + outcome (`result`, `reason`, `hosts`, `format_level`, `message`): **0** finalized or already finalized; + **2** refused (`FORMAT_HOSTS_TOO_OLD`, each refused host in `hosts` with what it reported); **75** the master + could not be reached, retry; **1** any other failure, a failed write of the format record included (the level + is unchanged) and a usage error. - v1.1 answers the reverse case, a store or HEAD written by a later version, with a final exit 78 (`store_format_newer`, `head_newer_version`), which the unit does not restart.