diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index afc06e0cc6..fec89981af 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "io" @@ -32,7 +33,7 @@ const workspaceUsage = `usage: sw-block ops workspace move --clean --master ADDR --volume V --replica R --epoch E --target-host H --target-data A --target-ctrl A --request-id ID [--timeout 30s] sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A - --request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s] + --request-id ID --confirm-forced V@EPOCH [--dry-run] [--json] [--timeout 30s] sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s] force-move FORCES an RF1 workspace volume's authority off a holder that is gone, @@ -120,13 +121,52 @@ func workspaceExit(o wsclient.Outcome) int { return wsExitUnknown } +// workspaceForceMoveAnswer is output only; admission and exit policy stay in +// the existing client/master paths. A preview never supplies a move id. +type workspaceForceMoveAnswer struct { + Admitted bool `json:"admitted"` + Until string `json:"until"` + Code string `json:"code"` + MoveID string `json:"move_id,omitempty"` + KeptGen *uint64 `json:"kept_gen,omitempty"` + KeptLSN *uint64 `json:"kept_lsn,omitempty"` + LostRange *workspaceForceMoveLoss `json:"lost_range,omitempty"` +} + +type workspaceForceMoveLoss struct { + Proven bool `json:"proven"` + AfterLSN *uint64 `json:"after_lsn,omitempty"` + Until string `json:"until,omitempty"` +} + +func (a *workspaceForceMoveAnswer) issued(g *control.WorkspaceGrant, rangeProven bool) { + a.Admitted, a.MoveID = true, g.GetRequestId() + gen, lsn := g.GetHeadGen(), g.GetRemoteLsn() + a.KeptGen, a.KeptLSN = &gen, &lsn + a.LostRange = &workspaceForceMoveLoss{Proven: rangeProven} + if rangeProven { + r := g.GetLostRange() + after := r.GetLostAfterLsn() + a.LostRange.AfterLSN = &after + a.LostRange.Until = wsclient.FormatTime(r.GetLostUntilNs()) + } +} + func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { fs := flag.NewFlagSet(workspaceForceMoveName, flag.ContinueOnError) fs.SetOutput(stderr) fs.Usage = func() { fmt.Fprint(stderr, workspaceUsage) } var m wsclient.ForcedMove var master string - var dryRun bool + var dryRun, jsonOutput bool + answer := workspaceForceMoveAnswer{Code: "InvalidArgument"} + defer func() { + if jsonOutput { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintf(stderr, "%s: JSON output: %v\n", workspaceForceMoveName, err) + } + } + }() var timeout time.Duration fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port") fs.StringVar(&m.VolumeID, "volume", "", "volume id") @@ -136,6 +176,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { fs.StringVar(&m.RequestID, "request-id", "", "this move's id; a rerun with the same id returns the stored grant") fs.StringVar(&m.Confirm, "confirm-forced", "", "exactly @") fs.BoolVar(&dryRun, "dry-run", false, "advisory preview only; writes nothing") + fs.BoolVar(&jsonOutput, "json", false, "print typed admission, barrier, refusal code and issued move id") fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPCs") if err := fs.Parse(args); err != nil { return wsExitRefusedLocally @@ -158,18 +199,29 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if dryRun { - return workspacePreview(ctx, c, m, stdout, stderr) + if jsonOutput { + return workspacePreview(ctx, c, m, stdout, stderr, &answer) + } + return workspacePreview(ctx, c, m, stdout, stderr, nil) } g, err := c.ForceMove(ctx, m) + answer.Code = wsclient.CodeOf(err) switch o := wsclient.OutcomeOf(err); o { case wsclient.OutcomeOK: + answer.issued(g, true) + if jsonOutput { + return wsExitOK + } printForcedGrant(stdout, g) fmt.Fprintln(stdout, wsclient.Readout(m.VolumeID, g.GetLostRange())) fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", m.VolumeID, g.GetNewHost()) return wsExitOK case wsclient.OutcomeReadoutUnproven: if g != nil { - printForcedGrant(stdout, g) + answer.issued(g, false) + if !jsonOutput { + printForcedGrant(stdout, g) + } } fmt.Fprintf(stderr, "%s: %v\n", workspaceForceMoveName, err) fmt.Fprintf(stderr, "%s: the move IS issued; do not assume no loss. Check the master's load errors, and read the range with:\n", workspaceForceMoveName) @@ -178,6 +230,7 @@ func runWorkspaceForceMove(args []string, stdout, stderr io.Writer) int { case wsclient.OutcomeRefused: fmt.Fprintf(stderr, "%s: refused by the master (nothing moved): %v\n", workspaceForceMoveName, err) if at, ok := c.AdmissibleAt(ctx, m); ok { + answer.Until = wsclient.FormatTime(at.UnixNano()) fmt.Fprintf(stderr, "%s: admissible at %s, master clock (the lease horizon plus clock skew); wait, there is no bypass\n", workspaceForceMoveName, wsclient.FormatTime(at.UnixNano())) } return wsExitRefused @@ -218,15 +271,30 @@ func printForcedGrant(w io.Writer, g *control.WorkspaceGrant) { // workspacePreview is the --dry-run row: advisory, writes nothing, exit 0 // whatever the answer (a failed preview call is reported by its outcome). -func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.ForcedMove, stdout, stderr io.Writer) int { +func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.ForcedMove, stdout, stderr io.Writer, answer *workspaceForceMoveAnswer) int { p, err := c.PreviewForcedMove(ctx, m) if err != nil { + if answer != nil { + answer.Code = wsclient.CodeOf(err) + } fmt.Fprintf(stderr, "%s --dry-run: %v\n", workspaceForceMoveName, err) if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown { fmt.Fprintf(stderr, "%s --dry-run: the preview failed; nothing was written\n", workspaceForceMoveName) } return workspaceExit(wsclient.OutcomeOf(err)) } + if answer != nil { + answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode() + if !p.GetAdmitted() { + if answer.Code == "" { + answer.Code = "Unknown" + } // older servers did not export a refusal code + if p.GetLostUntilNs() > p.GetMasterTimeNs() { + answer.Until = wsclient.FormatTime(p.GetLostUntilNs()) + } + } + return wsExitOK + } verdict := "not admitted" if p.GetAdmitted() { verdict = "admitted" diff --git a/seaweed-block/cmd/sw-block/workspace_json_test.go b/seaweed-block/cmd/sw-block/workspace_json_test.go new file mode 100644 index 0000000000..e8b42f3de1 --- /dev/null +++ b/seaweed-block/cmd/sw-block/workspace_json_test.go @@ -0,0 +1,138 @@ +package main + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestWorkspaceForceMoveJSONGoldenAnswers(t *testing.T) { + for _, tc := range []struct { + name string + dry, admitted bool + want string + exit int + }{ + {"preview-refused", true, false, `{"admitted":false,"until":"2026-11-21T01:05:00Z","code":"FailedPrecondition"}` + "\n", 0}, + {"preview-admitted", true, true, `{"admitted":true,"until":"","code":""}` + "\n", 0}, + {"move-refused", false, false, `{"admitted":false,"until":"2026-11-21T01:05:00Z","code":"FailedPrecondition"}` + "\n", 1}, + {"move-issued", false, true, `{"admitted":true,"until":"","code":"","move_id":"req-1","kept_gen":9,"kept_lsn":42,"lost_range":{"proven":true,"after_lsn":42,"until":"2026-11-21T01:05:00Z"}}` + "\n", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + preview := &control.WorkspaceMovePreview{Admitted: tc.admitted, MasterTimeNs: wsLostUntil.Add(-time.Minute).UnixNano(), LostUntilNs: wsLostUntil.UnixNano(), Reason: "this reason is not a machine-readable verdict"} + if !tc.admitted { + preview.Code = codes.FailedPrecondition.String() + } + f := &fakeWorkspace{status: wsHolder(), preview: preview, move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if !tc.admitted { + return nil, status.Error(codes.FailedPrecondition, "forced move admitted (misleading prose)") + } + return wsGrant(q), nil + }} + addr, _ := startFakeWorkspace(t, f) + extra := []string{"--confirm-forced", "vol@3", "--json"} + if tc.dry { + extra = append(extra, "--dry-run") + } + code, out, errs := runCLI(forceMoveArgs(addr, extra...)) + if code != tc.exit || out != tc.want { + t.Fatalf("exit=%d stdout=%q stderr=%q; want exit=%d stdout=%q", code, out, errs, tc.exit, tc.want) + } + if tc.dry && f.n("MoveWorkspace") != 0 { + t.Fatal("preview sent a move") + } + }) + } +} + +func TestWorkspaceForceMoveJSONDoesNotGuessAdmission(t *testing.T) { + for _, tc := range []struct { + name string + rpcCode codes.Code + dry, legacy bool + want string + exit int + }{ + {"transport-unknown", codes.Unavailable, false, false, `{"admitted":false,"until":"","code":"Unavailable"}` + "\n", 3}, + {"refusal-code", codes.NotFound, false, false, `{"admitted":false,"until":"","code":"NotFound"}` + "\n", 1}, + {"legacy-preview", codes.OK, true, true, `{"admitted":false,"until":"2026-11-21T01:05:00.123456789Z","code":"Unknown"}` + "\n", 0}, + {"preview-unavailable", codes.Unavailable, true, false, `{"admitted":false,"until":"","code":"Unavailable"}` + "\n", 3}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { + return nil, status.Error(tc.rpcCode, "admitted: true (untrusted prose)") + }} + if tc.legacy { + f.preview = &control.WorkspaceMovePreview{Reason: "admitted: true (legacy prose)", LostUntilNs: wsLostUntil.Add(123456789).UnixNano(), MasterTimeNs: wsLostUntil.Add(-time.Minute).UnixNano()} + } + addr, _ := startFakeWorkspace(t, f) + extra := []string{"--confirm-forced", "vol@3", "--json"} + if tc.dry { + extra = append(extra, "--dry-run") + } + code, out, errs := runCLI(forceMoveArgs(addr, extra...)) + if code != tc.exit || out != tc.want { + t.Fatalf("exit=%d out=%q stderr=%q; want %d %q", code, out, errs, tc.exit, tc.want) + } + }) + } +} + +func TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.LostRange = nil + return g, nil + }} + addr, dials := startFakeWorkspace(t, f) + code, out, _ := runCLI(forceMoveArgs(addr, "--json")) + if code != 2 || out != `{"admitted":false,"until":"","code":"InvalidArgument"}`+"\n" || *dials != 0 || f.total() != 0 { + t.Fatalf("local confirmation: %d %q dials=%d calls=%d", code, out, *dials, f.total()) + } + code, out, _ = runCLI(forceMoveArgs(addr, "--json", "--confirm-forced", "vol@3")) + if code != 4 || out != `{"admitted":true,"until":"","code":"DataLoss","move_id":"req-1","kept_gen":9,"kept_lsn":42,"lost_range":{"proven":false}}`+"\n" { + t.Fatalf("issued but unproven readout: %d %q", code, out) + } +} + +func TestWorkspaceForceMoveJSONBindsLossEvidenceToTheValidatedGrant(t *testing.T) { + for _, tc := range []struct { + name string + gen, lsn uint64 + badRange, badGrant bool + exit int + want string + }{ + {"zero-frontier", 17, 0, false, false, 0, `{"admitted":true,"until":"","code":"","move_id":"req-1","kept_gen":17,"kept_lsn":0,"lost_range":{"proven":true,"after_lsn":0,"until":"2026-11-21T01:05:00Z"}}` + "\n"}, + {"large-frontier", 19, 9007199254740993, false, false, 0, `{"admitted":true,"until":"","code":"","move_id":"req-1","kept_gen":19,"kept_lsn":9007199254740993,"lost_range":{"proven":true,"after_lsn":9007199254740993,"until":"2026-11-21T01:05:00Z"}}` + "\n"}, + {"mismatched-range", 23, 71, true, false, 4, `{"admitted":true,"until":"","code":"DataLoss","move_id":"req-1","kept_gen":23,"kept_lsn":71,"lost_range":{"proven":false}}` + "\n"}, + {"mismatched-grant", 23, 71, false, true, 3, `{"admitted":false,"until":"","code":"Unknown"}` + "\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + g := wsGrant(q) + g.HeadGen, g.RemoteLsn = tc.gen, tc.lsn + g.LostRange.HeadGen, g.LostRange.LostAfterLsn = tc.gen, tc.lsn + if tc.badRange { + g.LostRange.RequestId = "another-move" + g.LostRange.LostAfterLsn = 999 + } + if tc.badGrant { + g.VolumeId = "another-volume" + } + return g, nil + }} + addr, _ := startFakeWorkspace(t, f) + code, out, errs := runCLI(forceMoveArgs(addr, "--json", "--confirm-forced", "vol@3")) + if code != tc.exit || out != tc.want { + t.Fatalf("exit=%d out=%q stderr=%q; want %d %q", code, out, errs, tc.exit, tc.want) + } + if f.n("PreviewWorkspaceMove") != 0 { + t.Fatal("issued evidence came from a fresh preview") + } + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go index 9a6f9c55e4..eb54268c03 100644 --- a/seaweed-block/core/host/master/workspace_lost_range_readout_test.go +++ b/seaweed-block/core/host/master/workspace_lost_range_readout_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "sync" + "sync/atomic" "testing" "time" @@ -112,10 +113,19 @@ func forcedMoveHost(t *testing.T, cfg Config) (*Host, func(), control.WorkspaceS func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { logs := &syncBuffer{} headTime := time.Date(2026, 11, 21, 1, 2, 3, 0, time.UTC) + var headMode atomic.Int32 authDir := t.TempDir() cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: authDir, LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume, Logger: log.New(logs, "", 0), WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + switch headMode.Load() { + case 1: + return authority.WorkspaceHead{}, context.DeadlineExceeded + case 2: + return authority.WorkspaceHead{}, context.Canceled + case 3: + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "foreign/r1", RemoteLSN: 42}, nil + } return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, FilerMtimeNS: headTime.UnixNano()}, nil }} h, stop, client, move := forcedMoveHost(t, cfg) @@ -126,9 +136,27 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { if err != nil { t.Fatal(err) } - if pv.Admitted || pv.LostUntilNs <= pv.MasterTimeNs || pv.HeadRead || !strings.Contains(pv.Reason, "has not elapsed") { + if pv.Code != codes.FailedPrecondition.String() || pv.Admitted || pv.LostUntilNs <= pv.MasterTimeNs || pv.HeadRead || !strings.Contains(pv.Reason, "has not elapsed") { t.Fatalf("preview before the horizon: %+v", pv) } + for _, tc := range []struct { + name string + code codes.Code + change func(*control.WorkspaceMove) + }{ + {"invalid-kind", codes.InvalidArgument, func(q *control.WorkspaceMove) { q.Kind = "clean" }}, + {"unknown-volume", codes.FailedPrecondition, func(q *control.WorkspaceMove) { q.VolumeId = "unknown" }}, + {"invalid-endpoint", codes.FailedPrecondition, func(q *control.WorkspaceMove) { q.TargetDataAddr = "not-an-endpoint" }}, + } { + t.Run(tc.name, func(t *testing.T) { + q := proto.Clone(move).(*control.WorkspaceMove) + tc.change(q) + p, err := client.PreviewWorkspaceMove(ctx, q) + if err != nil || p.GetAdmitted() || p.GetCode() != tc.code.String() { + t.Fatalf("preview=%+v err=%v want %s", p, err, tc.code) + } + }) + } if _, err := client.MoveWorkspace(ctx, move); status.Code(err) != codes.FailedPrecondition { t.Fatalf("move before the horizon: %v; want FailedPrecondition", err) } @@ -141,9 +169,30 @@ func TestWorkspaceForcedMoveLostRangeOverRPC(t *testing.T) { if err != nil { t.Fatal(err) } - if !pv2.Admitted || !pv2.HeadRead || pv2.HeadGen != 9 || pv2.HeadRemoteLsn != 42 || !pv2.HeadTimeKnown || pv2.HeadTimeNs != headTime.UnixNano() || pv2.LostUntilNs != pv.LostUntilNs { + if pv2.Code != "" || !pv2.Admitted || !pv2.HeadRead || pv2.HeadGen != 9 || pv2.HeadRemoteLsn != 42 || !pv2.HeadTimeKnown || pv2.HeadTimeNs != headTime.UnixNano() || pv2.LostUntilNs != pv.LostUntilNs { t.Fatalf("preview after the horizon: %+v", pv2) } + for _, tc := range []struct { + name string + mode int32 + code codes.Code + }{ + {"head-deadline", 1, codes.DeadlineExceeded}, + {"head-canceled", 2, codes.Canceled}, + {"foreign-head", 3, codes.FailedPrecondition}, + } { + t.Run(tc.name, func(t *testing.T) { + headMode.Store(tc.mode) + p, err := client.PreviewWorkspaceMove(ctx, move) + if err != nil || p.GetAdmitted() || p.GetCode() != tc.code.String() { + t.Fatalf("preview=%+v err=%v want %s", p, err, tc.code) + } + if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { + t.Fatal("refused preview issued a move") + } + }) + } + headMode.Store(0) if st := h.Publisher().WorkspaceState("vol-f"); len(st.Moves) != 0 { t.Fatalf("preview wrote a journal record: %+v", st.Moves) } diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index de55d43470..0ea145f32e 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -544,11 +544,17 @@ func (s *services) QueryWorkspaceLostRange(ctx context.Context, q *control.Works // only once admitted, the HEAD read and HEAD rule, as the move does. A // refusal is an answer (admitted false, reason), not an RPC error. func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceMovePreview, error) { - out := &control.WorkspaceMovePreview{} + out := &control.WorkspaceMovePreview{Code: codes.FailedPrecondition.String()} + defer func() { + if out.Admitted { + out.Code = "" + } + }() if !s.host.cfg.WorkspaceRPC { return nil, status.Error(codes.FailedPrecondition, "workspace RPC disabled") } if q.GetKind() != "forced" || !q.GetForce() { + out.Code = codes.InvalidArgument.String() out.Reason = "workspace move preview: forced moves only (kind forced, force true)" out.MasterTimeNs = time.Now().UnixNano() return out, nil @@ -560,6 +566,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac defer s.host.workspaceMu.Unlock() if err := s.workspaceVolume(q.GetVolumeId()); err != nil { out.Reason = status.Convert(err).Message() + out.Code = status.Code(err).String() return nil } r, target, _, why, err := s.workspaceMoveCheckLocked(q) @@ -579,6 +586,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac default: if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { out.Admitted, out.Reason = false, err.Error() + out.Code = status.Code(workspaceError(err)).String() } } return nil @@ -598,6 +606,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId()) if err != nil { out.Admitted, out.HeadError = false, err.Error() + out.Code = status.Code(workspaceError(err)).String() out.Reason = "workspace move: HEAD read failed: " + err.Error() return out, nil } diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index 87cc29b113..00a025f939 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -926,6 +926,8 @@ type WorkspaceMovePreview struct { HeadRemoteLsn uint64 `protobuf:"varint,10,opt,name=head_remote_lsn,json=headRemoteLsn,proto3" json:"head_remote_lsn,omitempty"` HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` + // gRPC status code name for a refusal; empty when admitted. Additive output only. + Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1044,6 +1046,13 @@ func (x *WorkspaceMovePreview) GetHeadTimeKnown() bool { return false } +func (x *WorkspaceMovePreview) GetCode() string { + if x != nil { + return x.Code + } + return "" +} + type WorkspaceStatus struct { state protoimpl.MessageState `protogen:"open.v1"` Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"` @@ -1335,7 +1344,7 @@ const file_workspace_proto_rawDesc = "" + "\n" + "request_id\x18\x02 \x01(\tR\trequestId\"Z\n" + "\x13WorkspaceLostRanges\x12C\n" + - "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\x9d\x03\n" + + "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xb1\x03\n" + "\x14WorkspaceMovePreview\x12\x1a\n" + "\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" + "\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" + @@ -1353,7 +1362,8 @@ const file_workspace_proto_rawDesc = "" + " \x01(\x04R\rheadRemoteLsn\x12 \n" + "\fhead_time_ns\x18\v \x01(\x03R\n" + "headTimeNs\x12&\n" + - "\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\"\xb2\x02\n" + + "\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\x12\x12\n" + + "\x04code\x18\r \x01(\tR\x04code\"\xb2\x02\n" + "\x0fWorkspaceStatus\x12A\n" + "\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" + "\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" + diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index aadc6b579e..a11399d06e 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -80,6 +80,8 @@ message WorkspaceMovePreview { bool head_read = 5; string head_error = 6; uint64 head_gen = 7; uint64 head_epoch = 8; string head_holder = 9; uint64 head_remote_lsn = 10; int64 head_time_ns = 11; bool head_time_known = 12; + // gRPC status code name for a refusal; empty when admitted. Additive output only. + string code = 13; } message WorkspaceStatus { WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2; diff --git a/seaweed-block/core/rpc/wsclient/wsclient.go b/seaweed-block/core/rpc/wsclient/wsclient.go index fa65cf6f7a..94c9b262c7 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient.go +++ b/seaweed-block/core/rpc/wsclient/wsclient.go @@ -55,6 +55,7 @@ var ErrConfirmation = errors.New("forced move confirmation") // Error carries a classified failure. type Error struct { Outcome Outcome + Code string // original gRPC status code, when a remote call supplied one Op string Err error } @@ -74,6 +75,29 @@ func OutcomeOf(err error) Outcome { return OutcomeUnknown } +// CodeOf preserves a remote status even when the operator-facing error text +// is rewritten. Client-side checks have typed outcome defaults; no prose is parsed. +func CodeOf(err error) string { + if err == nil { + return "" + } + var e *Error + if errors.As(err, &e) && e.Code != "" { + return e.Code + } + switch OutcomeOf(err) { + case OutcomeRefusedLocally: + return codes.InvalidArgument.String() + case OutcomeRefused: + return codes.FailedPrecondition.String() + case OutcomeReadoutUnproven: + return codes.DataLoss.String() + case OutcomeNotAuthorized: + return codes.PermissionDenied.String() + } + return status.Code(err).String() +} + // classify maps a gRPC error: the master's definite answers are refusals, // DataLoss is an unproven readout, anything else leaves the outcome unknown. func classify(op string, err error) error { @@ -82,19 +106,19 @@ func classify(op string, err error) error { } switch status.Code(err) { case codes.Unauthenticated, codes.PermissionDenied: - return &Error{Outcome: OutcomeNotAuthorized, 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())} + 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())} case codes.Unavailable: // A plaintext client against blockmaster with mutual TLS: the server // closes the connection before its HTTP/2 preface. if os.Getenv(link.EnvTLSCert) == "" && strings.Contains(status.Convert(err).Message(), "error reading server preface") { - return &Error{Outcome: OutcomeNotAuthorized, Op: op, Err: fmt.Errorf("blockmaster refused this plaintext connection: it requires mutual TLS; set %s, %s and %s to a certificate in its role file and its CA", link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)} + return &Error{Outcome: OutcomeNotAuthorized, Code: status.Code(err).String(), Op: op, Err: fmt.Errorf("blockmaster refused this plaintext connection: it requires mutual TLS; set %s, %s and %s to a certificate in its role file and its CA", link.EnvTLSCert, link.EnvTLSKey, link.EnvTLSCA)} } case codes.FailedPrecondition, codes.InvalidArgument, codes.NotFound, codes.Unimplemented: - return &Error{Outcome: OutcomeRefused, Op: op, Err: errors.New(status.Convert(err).Message())} + return &Error{Outcome: OutcomeRefused, Code: status.Code(err).String(), Op: op, Err: errors.New(status.Convert(err).Message())} case codes.DataLoss: - return &Error{Outcome: OutcomeReadoutUnproven, Op: op, Err: errors.New(status.Convert(err).Message())} + return &Error{Outcome: OutcomeReadoutUnproven, Code: status.Code(err).String(), Op: op, Err: errors.New(status.Convert(err).Message())} } - return &Error{Outcome: OutcomeUnknown, Op: op, Err: err} + return &Error{Outcome: OutcomeUnknown, Code: status.Code(err).String(), Op: op, Err: err} } // ParseConfirmation checks that confirm is exactly "@" for diff --git a/seaweed-block/core/rpc/wsclient/wsclient_test.go b/seaweed-block/core/rpc/wsclient/wsclient_test.go index 2d1c9fdbf9..18aa1185d6 100644 --- a/seaweed-block/core/rpc/wsclient/wsclient_test.go +++ b/seaweed-block/core/rpc/wsclient/wsclient_test.go @@ -3,6 +3,9 @@ package wsclient import ( "context" "errors" + "fmt" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "strings" "testing" "time" @@ -222,3 +225,27 @@ func TestReadoutWording(t *testing.T) { t.Fatalf("no-HEAD readout: %s", got) } } + +func TestForceMovePreservesRemoteCodesThroughOperatorTextAndWrapping(t *testing.T) { + t.Setenv(link.EnvTLSCert, "") + for _, tc := range []struct { + code codes.Code + message string + outcome Outcome + text string + }{ + {codes.Unauthenticated, "no certificate", OutcomeNotAuthorized, "not authorized by blockmaster"}, + {codes.PermissionDenied, "role denied", OutcomeNotAuthorized, "not authorized by blockmaster"}, + {codes.DataLoss, "range unreadable", OutcomeReadoutUnproven, "range unreadable"}, + {codes.Unavailable, "error reading server preface", OutcomeNotAuthorized, "requires mutual TLS"}, + } { + t.Run(tc.code.String(), func(t *testing.T) { + f := &fakeRPC{status: &control.WorkspaceStatus{Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}}, moveErr: status.Error(tc.code, tc.message)} + _, err := New(f).ForceMove(context.Background(), testMove) + wrapped := fmt.Errorf("outer context: %w", err) + if OutcomeOf(wrapped) != tc.outcome || CodeOf(wrapped) != tc.code.String() || !strings.Contains(err.Error(), tc.text) { + t.Fatalf("outcome=%v code=%q err=%v", OutcomeOf(wrapped), CodeOf(wrapped), err) + } + }) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7d21261498..3f0aad30bc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -849,6 +849,8 @@ Notes: | `INV-WS-LOST-RANGE-PRE-ISSUE-001` | Except for the unknown outcomes of `INV-WS-LOST-RANGE-UNCERTAIN-001` and `INV-AUTH-UNCERTAIN-001` and for cancellation or deadline, a move refused or failing before its issue is answered `FailedPrecondition`, and the operator client reports a refusal (exit 1). | M2 lease: Acked or Expired → (move refused, nothing written); Expired → Moved (forced) | `core/host/master/workspace_service.go` `workspaceError`, `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/rpc/wsclient/wsclient.go` `classify`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`); `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`); `TestWorkspaceForceMove_Row5_MasterRefusal` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-CLIENT-GRANT-001` | The operator client accepts a forced grant only if it is issued, of kind forced, and matches the request's id, volume, expected holder and epoch, target replica and host, with a higher new epoch; otherwise the outcome is unknown. | M2 lease: Moved → epoch issued (client side) | `core/rpc/wsclient/wsclient.go` `checkGrant`, `ForceMove` | `TestForceMoveBindsGrantAndRange` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMoveRejectsAMismatchedAnswer` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-CLIENT-RANGE-001` | The operator client accepts a grant's lost range only if it names the grant's volume, request id, old and new epochs, old replica and HEAD generation, and starts at the grant's remote LSN; otherwise the readout is unproven. | M2 lease: Moved → epoch issued (client side) | `core/rpc/wsclient/wsclient.go` `checkRange`, `ForceMove` | `TestForceMoveBindsGrantAndRange`, `TestForceMoveGrantWithoutRangeIsUnproven` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | +| `INV-CLI-FORCED-LOSS-001` | An issued forced-move JSON answer retains the kept HEAD generation and LSN; proven lost ranges carry their kept-through LSN and time bound, while unproven ranges are explicit and supply no guessed bounds. | M2 forced move readout, output only | `cmd/sw-block/workspace.go` `workspaceForceMoveAnswer.issued` | `TestWorkspaceForceMoveJSONGoldenAnswers`, `TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits` | MoveAdmission.ReadForMove; no transition change | ACTIVE | +| `INV-CLI-FORCED-JSON-001` | Force-move JSON reports typed admission, barrier and refusal code; only a validated issued grant supplies a move id. Text output and exit codes keep their existing meanings. | M2 Expired → Moved (forced), output only | `cmd/sw-block/workspace.go`; `core/rpc/wsclient/wsclient.go`; `core/host/master/workspace_service.go` | `TestWorkspaceForceMoveJSONGoldenAnswers`, `TestWorkspaceForceMoveJSONDoesNotGuessAdmission`, `TestWorkspaceForceMoveJSONKeepsLocalConfirmationAndIssuedReadoutExits`, `TestWorkspaceForcedMoveLostRangeOverRPC` | MoveAdmission.ReadForMove; no transition change | ACTIVE | | `INV-WS-FORCED-CONFIRM-001` | The OSS operator client (`sw-block ops workspace force-move`, `wsclient.ForceMove`) sends `force: true` only when `--confirm-forced` is exactly `@` (that volume, a positive decimal epoch), and then as kind forced at that epoch with the operator's request id. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request`, `ForceMove`; `cmd/sw-block/workspace.go` `runWorkspaceForceMove` | `TestParseConfirmation`, `TestForceMoveSendsForceOnlyWithTheConfirmation` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-LOCAL-001` | A missing or malformed `--confirm-forced` is refused before any connection or RPC, with exit 2. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`; `core/rpc/wsclient/wsclient.go` `ParseConfirmation`, `request` | `TestWorkspaceForceMove_Row1_ConfirmationRefusedLocally` (`cmd/sw-block/workspace_test.go`); `TestParseConfirmation` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index f721f2d711..6e7a469659 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -405,10 +405,25 @@ sw-block ops workspace force-move --master MASTER --volume v1 \ ``` `--dry-run` writes nothing; it shows whether the move is admitted and, if not, -`admissible at