sw-block: retire-host answers 0/2/75/1 with --json; a forced move's preview carries the typed reason

retire-host follows finalize-format's contract: exit 0 retired, 2 refused,
75 the master could not be reached, 1 any other failure or usage error, and
--json prints result, reason, server, volumes and message for every outcome.
The master's HOST_HOLDS_WORK refusal names each held volume in its typed
metadata. The forced-move preview answers the typed reason the move itself
would carry (reason_code, e.g. BINARY_TOO_OLD), and force-move --dry-run
--json shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-02 07:04:38 -08:00
1 parent 14016ef705
commit 59a0ebca91
11 files changed
+223 -25

No files matched your search

+66 -16
View File
@@ -223,8 +223,22 @@ func finalizeHosts(md map[string]string) []finalizeHost {
return hosts
}
// retireAnswer is retire-host's --json answer, one shape for every outcome.
// Result is retired, refused, unavailable or failed; Reason the master's
// typed reason (or the gRPC code, "" on success); Volumes the volumes the
// host still holds when the retire is refused for them (empty otherwise).
type retireAnswer struct {
Result string `json:"result"`
Reason string `json:"reason"`
Server string `json:"server"`
Volumes []string `json:"volumes"`
Message string `json:"message"`
}
// runClusterRetireHost removes a registered host from the node inventory.
// The master refuses it while the host holds a lease or an assignment.
// The master refuses it while the host holds a lease or an assignment. Exit
// codes as finalize-format's: 0 retired, 2 refused, 75 the master could not
// be reached (EX_TEMPFAIL), 1 any other failure, a usage error included.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
@@ -232,31 +246,67 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
server := fs.String("server", "", "the server id to retire (required)")
confirm := fs.String("confirm", "", "the same server id again (required)")
timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer")
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s]")
return ops.VolumeStatusExitInvalid
// Declared for parsing and help only; the mode is read from the
// arguments as a whole, so a bad option in any position cannot half-parse it.
fs.Bool("json", false, "print the typed answer as JSON: result, reason, server, volumes, message")
jsonMode := jsonRequested(args)
answer := retireAnswer{Volumes: []string{}}
defer func() {
if jsonMode {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host: 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 retire-host:", msg)
return code
}
if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" {
fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s] [--json]")
answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master, --server and --confirm are required"
return finalizeExitFailed
}
answer.Server = *server
c, closeFn, err := clusterLifecycleDial(*master)
if err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", err)
return ops.VolumeStatusExitUnhealthy
return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail)
}
defer closeFn()
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster retire-host:", 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.Volumes = retireVolumes(md)
return fail("refused", reason, msg, finalizeExitRefused)
case codes.Unavailable, codes.DeadlineExceeded:
return fail("unavailable", reason, msg, finalizeExitTempFail)
}
return fail("failed", reason, msg, finalizeExitFailed)
}
fmt.Fprintf(stdout, "host %s retired\n", *server)
return ops.VolumeStatusExitOK
answer.Result, answer.Message = "retired", "host retired from the node inventory"
if !jsonMode {
fmt.Fprintf(stdout, "host %s retired\n", *server)
}
return finalizeExitOK
}
// clusterExit maps a master error to the CLI's exit codes: a malformed
// request is 2 (as a usage error); a refusal or an unreachable master is 1.
func clusterExit(err error) int {
if status.Code(err) == codes.InvalidArgument {
return ops.VolumeStatusExitInvalid
// retireVolumes reads the held volumes from the refusal's typed metadata,
// sorted.
func retireVolumes(md map[string]string) []string {
vols := []string{}
for k := range md {
if v, ok := strings.CutPrefix(k, lifecycleclient.VolumeMetadataPrefix); ok {
vols = append(vols, v)
}
}
return ops.VolumeStatusExitUnhealthy
sort.Strings(vols)
return vols
}
@@ -142,3 +142,83 @@ func TestClusterFinalizeFormatBadOptionAnswersJSONWithoutAnRPC(t *testing.T) {
t.Fatalf("a malformed command sent %d finalize RPCs", calls)
}
}
// retire-host's answer is typed like finalize-format's: exit 0 retired, 2
// refused (the held volumes from the master's typed metadata, never its
// message text), 75 the master could not be reached, 1 any other failure or
// a usage error; --json prints the same keys for every outcome.
func TestClusterRetireHostTypedAnswer(t *testing.T) {
holds := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"),
lifecycleclient.ReasonHostHoldsWork, map[string]string{
lifecycleclient.VolumeMetadataPrefix + "v2": "busy",
lifecycleclient.VolumeMetadataPrefix + "v1": "busy",
}).Err()
for _, tc := range []struct {
name string
err error
dialErr error
args []string
exit int
result string
reason string
volumes []string
}{
{name: "retired", exit: 0, result: "retired"},
{name: "holds-work", err: holds, exit: 2, result: "refused", reason: lifecycleclient.ReasonHostHoldsWork, volumes: []string{"v1", "v2"}},
{name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"},
{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: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"},
{name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"},
} {
t.Run(tc.name, func(t *testing.T) {
calls := 0
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
calls++
if tc.err != nil {
return nil, tc.err
}
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
}}
withClusterMaster(t, f)
if tc.dialErr != nil {
clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr }
}
args := tc.args
if args == nil {
args = []string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy", "--json"}
}
var out, errOut bytes.Buffer
code := run(args, &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{"message", "reason", "result", "server", "volumes"}; !reflect.DeepEqual(names, want) {
t.Fatalf("--json keys %v, want %v for every outcome", names, want)
}
var a retireAnswer
if err := json.Unmarshal(out.Bytes(), &a); err != nil {
t.Fatal(err)
}
if a.Result != tc.result || a.Reason != tc.reason {
t.Fatalf("answer %+v, want result %q reason %q", a, tc.result, tc.reason)
}
if want := tc.volumes; want == nil && len(a.Volumes) != 0 || want != nil && !reflect.DeepEqual(a.Volumes, want) {
t.Fatalf("volumes %v, want %v", a.Volumes, want)
}
if tc.name == "usage" && calls != 0 {
t.Fatalf("a usage error sent %d retire RPCs", calls)
}
})
}
}
@@ -76,7 +76,7 @@ func TestClusterFinalizeFormat(t *testing.T) {
}
}
// retire-host sends the server id and its confirm; a refusal exits 1.
// retire-host sends the server id and its confirm; a refusal exits 2.
func TestClusterRetireHost(t *testing.T) {
var got *control.RetireHostRequest
f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
@@ -91,11 +91,11 @@ func TestClusterRetireHost(t *testing.T) {
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") {
t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") {
t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String())
}
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 2 {
t.Fatalf("retire without --confirm: exit %d, want 2", code)
if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 1 {
t.Fatalf("retire without --confirm: exit %d, want 1", code)
}
}
+1
View File
@@ -292,6 +292,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced
if answer != nil {
answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode()
if !p.GetAdmitted() {
answer.Reason = p.GetReasonCode()
if answer.Code == "" {
answer.Code = "Unknown"
} // older servers did not export a refusal code
@@ -173,3 +173,27 @@ func TestWorkspaceForceMoveJSONCarriesOnlyTheTypedReason(t *testing.T) {
})
}
}
// force-move --dry-run --json carries the preview's typed reason (the reason
// the move itself would carry); a refusal with only message text carries
// none.
func TestWorkspaceForceMovePreviewJSONCarriesTheTypedReason(t *testing.T) {
for _, tc := range []struct {
name string
preview *control.WorkspaceMovePreview
want string
}{
{"typed", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0", Code: "FailedPrecondition", ReasonCode: lifecycleclient.ReasonBinaryTooOld}, lifecycleclient.ReasonBinaryTooOld},
{"text-only", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0 (binary_too_old)", Code: "FailedPrecondition"}, ""},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeWorkspace{status: wsHolder(), preview: tc.preview}
addr, _ := startFakeWorkspace(t, f)
code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run", "--json"))
var a workspaceForceMoveAnswer
if json.Unmarshal([]byte(out), &a) != nil || a.Admitted || a.Code != "FailedPrecondition" || a.Reason != tc.want {
t.Fatalf("exit=%d out=%q err=%q answer=%+v; want reason %q", code, out, errOut, a, tc.want)
}
})
}
}
+10 -1
View File
@@ -377,6 +377,15 @@ func (e errHostHoldsWork) Error() string {
return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", "))
}
// metadata keys each held volume for the refusal's typed detail.
func (e errHostHoldsWork) metadata() map[string]string {
md := make(map[string]string, len(e.volumes))
for _, v := range e.volumes {
md[lifecycleclient.VolumeMetadataPrefix+v] = e.server
}
return md
}
// FinalizeFormat raises the cluster's format level to 1 (FormatGate:
// Finalize; FormatGateMaster: the one durable step). It is refused while any
// registered host has not reported reads_level >= 1 since this master
@@ -480,7 +489,7 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
var holds errHostHoldsWork
switch {
case errors.As(err, &holds):
return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork).Err()
return nil, lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork, holds.metadata()).Err()
case err != nil:
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
@@ -129,6 +129,12 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) {
if got := reasonOf(moveErr); got != wantReason {
t.Fatalf("level 1: MoveWorkspace onto node-b: reason %q, want %q", got, wantReason)
}
// The forced move's preview answers the same typed reason.
pv, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "p1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true})
if err != nil || pv.GetAdmitted() || pv.GetReasonCode() != wantReason {
t.Fatalf("level 1: preview of a forced move onto node-b: %+v %v, want reason_code %q", pv, err, wantReason)
}
})
}
}
@@ -278,6 +284,10 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) {
if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonHostHoldsWork || !strings.Contains(status.Convert(err).Message(), "held") {
t.Fatalf("retire of a host holding a placement: %v (reason %q)", err, reasonOf(err))
}
// The held volumes are typed too: one metadata entry per volume.
if _, md := lifecycleclient.ReasonDetail(err); len(md) != 1 || md[lifecycleclient.VolumeMetadataPrefix+"held"] != "node-b" {
t.Fatalf("retire refusal metadata %v, want volume.held = node-b", md)
}
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition {
t.Fatalf("retire with a confirm that does not match: %v", err)
}
@@ -583,6 +583,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
if err := s.workspaceVolume(q.GetVolumeId()); err != nil {
out.Reason = status.Convert(err).Message()
out.Code = status.Code(err).String()
out.ReasonCode = lifecycleclient.Reason(err)
return nil
}
r, target, _, why, err := s.workspaceMoveCheckLocked(q)
@@ -594,7 +595,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS
switch {
case why.text != "":
out.Admitted, out.Reason = false, why.text
out.Admitted, out.Reason, out.ReasonCode = false, why.text, why.reason
case !pv.Admitted:
out.Reason = pv.Reason
case pv.Replay:
@@ -603,6 +604,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
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()
out.ReasonCode = lifecycleclient.Reason(workspaceError(err))
}
}
return nil
@@ -623,6 +625,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac
if err != nil {
out.Admitted, out.HeadError = false, err.Error()
out.Code = status.Code(workspaceError(err)).String()
out.ReasonCode = lifecycleclient.Reason(workspaceError(err))
out.Reason = "workspace move: HEAD read failed: " + err.Error()
return out, nil
}
+16 -3
View File
@@ -932,7 +932,11 @@ type WorkspaceMovePreview struct {
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"`
Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"`
// The refusal's typed reason (the reason a MoveWorkspace refusal would carry
// in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or
// when the refusal has none. Additive output only.
ReasonCode string `protobuf:"bytes,14,opt,name=reason_code,json=reasonCode,proto3" json:"reason_code,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -1058,6 +1062,13 @@ func (x *WorkspaceMovePreview) GetCode() string {
return ""
}
func (x *WorkspaceMovePreview) GetReasonCode() string {
if x != nil {
return x.ReasonCode
}
return ""
}
type WorkspaceStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"`
@@ -1350,7 +1361,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\"\xb1\x03\n" +
"\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xd2\x03\n" +
"\x14WorkspaceMovePreview\x12\x1a\n" +
"\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" +
"\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" +
@@ -1369,7 +1380,9 @@ const file_workspace_proto_rawDesc = "" +
"\fhead_time_ns\x18\v \x01(\x03R\n" +
"headTimeNs\x12&\n" +
"\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\x12\x12\n" +
"\x04code\x18\r \x01(\tR\x04code\"\xb2\x02\n" +
"\x04code\x18\r \x01(\tR\x04code\x12\x1f\n" +
"\vreason_code\x18\x0e \x01(\tR\n" +
"reasonCode\"\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" +
@@ -67,3 +67,7 @@ func ReasonDetail(err error) (string, map[string]string) {
// HostMetadataPrefix keys one refused host in a reason's metadata:
// "host.<server id>" maps to what that host reported.
const HostMetadataPrefix = "host."
// VolumeMetadataPrefix keys one volume in a reason's metadata:
// "volume.<volume id>" maps to the host that holds it.
const VolumeMetadataPrefix = "volume."
@@ -84,6 +84,10 @@ message WorkspaceMovePreview {
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;
// The refusal's typed reason (the reason a MoveWorkspace refusal would carry
// in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or
// when the refusal has none. Additive output only.
string reason_code = 14;
}
message WorkspaceStatus {
WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2;