Merge main into the finalize change: #956's retire answers

# Conflicts:
#	cmd/sw-block/cluster_format.go
#	core/lifecycle/node_inventory.go
This commit is contained in:
pingqiu committed 2026-12-02 08:01:21 -08:00
commit ed1aa53d55
18 files changed
+492 -48

No files matched your search

+74 -18
View File
@@ -114,7 +114,7 @@ type finalizeHost struct {
// refuses the store (an expected refusal, not damage). The master refuses
// it while a host that holds a volume or has reported does not read level 1,
// naming each one; an idle host with no report does not block it.
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int) {
fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
@@ -130,6 +130,9 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int {
if *jsonOut {
if err := json.NewEncoder(stdout).Encode(answer); err != nil {
fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
@@ -224,40 +227,93 @@ 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.
func runClusterRetireHost(args []string, stdout, stderr io.Writer) int {
// 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) (code int) {
fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError)
fs.SetOutput(stderr)
master := fs.String("master", "", "blockmaster gRPC address (required)")
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)
if code == finalizeExitOK {
code = finalizeExitFailed // the answer a script reads was not written
}
}
}
}()
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,111 @@ 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)
}
})
}
}
// failingWriter refuses every write: a stdout the JSON answer cannot reach.
type failingWriter struct{}
func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") }
// A --json answer that cannot be written fails the command: a script that
// reads it must not see a successful exit without an answer.
func TestClusterJSONOutputFailureFailsTheCommand(t *testing.T) {
f := &fakeClusterMaster{
finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) {
return &control.FinalizeFormatResponse{FormatLevel: 1}, nil
},
retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) {
return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil
},
}
withClusterMaster(t, f)
for _, args := range [][]string{
{"cluster", "finalize-format", "--master", "m:1", "--json"},
{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c", "--json"},
} {
var errOut bytes.Buffer
if code := run(args, failingWriter{}, &errOut); code != 1 {
t.Fatalf("%v with an unwritable stdout: exit %d, want 1 (stderr %q)", args, code, errOut.String())
}
}
}
@@ -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)
}
})
}
}
+21 -2
View File
@@ -441,6 +441,22 @@ 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, ", "))
}
// errRetireStorage is a retire that failed to remove the host's record: a
// storage failure, not a refusal (the host may still be registered).
type errRetireStorage struct{ err error }
func (e errRetireStorage) Error() string { return "retire: " + e.err.Error() }
func (e errRetireStorage) Unwrap() error { return e.err }
// 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 a
// host of finalizeHosts (one that holds work or has reported) does not read
@@ -580,7 +596,7 @@ func (h *Host) RetireHost(server, confirm string) error {
return errHostHoldsWork{server: server, volumes: vols}
}
if err := h.lifecycle.Nodes.RemoveNode(server); err != nil {
return fmt.Errorf("retire: %w", err)
return errRetireStorage{err}
}
h.reads.forget(server)
h.log.Printf("blockmaster: host %s retired from the node inventory", server)
@@ -626,9 +642,12 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques
defer s.host.workspaceMu.Unlock()
err := s.host.RetireHost(req.GetServerId(), req.GetConfirm())
var holds errHostHoldsWork
var storage errRetireStorage
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 errors.As(err, &storage):
return nil, status.Error(codes.Internal, err.Error())
case err != nil:
return nil, status.Error(codes.FailedPrecondition, err.Error())
}
@@ -130,6 +130,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)
}
})
}
}
@@ -285,9 +291,20 @@ 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)
}
// A failure to remove the host's record is a storage failure (Internal),
// not a refusal: the CLI then answers "failed", exit 1.
r.m.Lifecycle().Nodes.SetPersistHookForTest(func() error { return errors.New("injected record removal failure") })
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); status.Code(err) != codes.Internal {
t.Fatalf("retire whose record removal failed: %v, want Internal", err)
}
r.m.Lifecycle().Nodes.SetPersistHookForTest(nil)
if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil {
t.Fatalf("retire of a host holding nothing: %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
}
@@ -72,7 +72,7 @@ type NodeInventoryStore struct {
dir string
records map[string]NodeRegistration
published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001)
failWrite func() error // tests: a non-nil error fails the next record write
failWrite func() error // tests: a non-nil error fails the next record write or removal
// unsure: servers whose last ReadsLevel write failed, so the file may
// hold a value the in-memory record does not; their next write is never
// skipped as unchanged.
@@ -80,8 +80,8 @@ type NodeInventoryStore struct {
}
// SetPersistHookForTest installs (nil clears) a callback that each later
// record write of this store runs under the store mutex before the write. A
// non-nil error fails that write with nothing replaced. Tests only.
// record write or removal of this store runs under the store mutex first. A
// non-nil error fails that change with nothing changed. Tests only.
func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -211,6 +211,11 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error {
}
s.mu.Lock()
defer s.mu.Unlock()
if s.failWrite != nil {
if err := s.failWrite(); err != nil {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
}
}
delete(s.records, serverID)
if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)
+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;
@@ -455,7 +455,7 @@ func TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites(t *testing.T) {
// An attached layer without the transition protocol still refuses, writing
// nothing. Actual supported layers are covered by the chunk/provider controls.
func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing.T) {
s, path := newMappedCheckpointStoreV3(t)
s, _ := newMappedCheckpointStoreV3(t)
cfg := ctConfig(1)
cfg.Bitmap = nil
cfg.BarrierBound = 1
@@ -463,11 +463,11 @@ func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing
hooks := *s.chunk.Load()
hooks.baseTransitionV3 = nil
s.chunk.Store(&hooks)
a0, b0 := slotsV3(t, path)
a0, b0 := slotsV3Of(t, s) // the store holds the file's lock: read through it
if _, err := s.beginBaseInstallV3(0, idA); !errors.Is(err, errV3NotYet) {
t.Fatalf("begin with a chunk layer attached: err = %v, want errV3NotYet", err)
}
if a, b := slotsV3(t, path); a != a0 || b != b0 {
if a, b := slotsV3Of(t, s); a != a0 || b != b0 {
t.Fatal("a refused begin wrote a descriptor slot")
}
}
@@ -2,6 +2,7 @@ package storage
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"errors"
@@ -325,7 +326,7 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatalf("the injected cut answered %v, want its outcome unknown", err)
}
w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
last5 := w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut
var err error
var last chunkCutResult
for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish
@@ -346,6 +347,15 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) {
t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want)
}
}
// Byte for byte: the remote is exactly the written image (the baseline
// with the three writes), not merely different in the right chunks.
if want := w.imageAt(last5); !bytes.Equal(img, want) {
for at := 0; at < len(want); at += ctBlockSize {
if !bytes.Equal(img[at:at+ctBlockSize], want[at:at+ctBlockSize]) {
t.Fatalf("the remote image differs from the written one at block %d", at/ctBlockSize)
}
}
}
}
// The candidate set's OR keeps the summary, so a set ORed back is listed in
@@ -600,3 +610,122 @@ func TestACutThatAbortsAfterTakingTheRequestReissuesIt(t *testing.T) {
t.Fatalf("the next cut left request generation %d pending", got)
}
}
// The live touched set exists once the layer attaches, before any write,
// on both store formats: a first map entry change only sets a bit (never
// allocates the bitmap under the store's lock). On v1.0 the record shadow's
// attach already seeds it; v1.1's record open does not, so it is allocated
// explicitly before the hooks are published.
func TestTheTouchedSetExistsAtAttach(t *testing.T) {
for _, format := range []string{"v1.0", "v1.1"} {
t.Run(format, func(t *testing.T) {
if format == "v1.1" {
withV11Format(t)
} else {
v10Only(t)
}
s, _ := newChunkTestStore(t)
// attachChunkLayer itself, not mustAttach: its reconcile wait reads
// Stats, whose candidate listing would seed the set.
layer, err := attachChunkLayer(s, newFakeChunkRemote(), ctConfig(1))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { // bounded, as mustAttach's
done := make(chan struct{})
go func() { _ = layer.Close(); close(done) }()
select {
case <-done:
case <-time.After(ctLocalBound):
t.Errorf("chunk layer Close did not return within %v", ctLocalBound)
}
})
l := layer.(*chunkLayerImpl)
l.unkMu.Lock()
allocated := l.touched != nil
l.unkMu.Unlock()
if !allocated {
t.Fatal("no touched set after attach: the first write would allocate it under the store lock")
}
})
}
}
// The status's DirtyChunks is the exact union of the live candidates and a
// cut's in-flight ones while its upload runs (a chunk in both counts once,
// one only in flight still counts), and the in-flight part leaves the count
// once that cut's HEAD installs.
func TestStatsCountsACutsCandidatesUntilItsHeadInstalls(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
layer := mustAttach(t, s, f, ctConfig(1))
l := layer.(*chunkLayerImpl)
w := newWriteLog()
if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set
t.Fatal(err)
}
w.write(t, s, 2*ctChunkBlocks, 0x22) // chunk 2: in flight only, once flushed
w.write(t, s, 3*ctChunkBlocks, 0x33) // chunk 3: in flight, and written again below
entered, release := holdPuts(t, f)
t.Cleanup(release)
done := startCapture(t, layer)
waitKey(t, entered, "chunk upload")
w.write(t, s, 3*ctChunkBlocks+1, 0x3b) // chunk 3 again: live and in flight
w.write(t, s, 4*ctChunkBlocks, 0x44) // chunk 4: live only
mustSyncFlush(t, s) // chunk 2's write leaves the dirty map
during := l.Stats().DirtyChunks
release()
if err := waitErr(t, done, "capture"); err != nil {
t.Fatal(err)
}
after := l.Stats().DirtyChunks
if during != 3 {
t.Fatalf("during the cut's upload: %d dirty chunks, want 3 (chunk 2 in flight, 3 in both, 4 live)", during)
}
if after != 2 {
t.Fatalf("after the cut's HEAD installed: %d dirty chunks, want 2 (chunks 3 and 4, written since)", after)
}
}
// A pre-copy cut keeps its frontend drained through the candidate step, so
// every walk it makes there is pause work, charged exactly once: over the
// same drained cut with nothing to walk, k dirty chunks add 2k (the
// dirty-set visit and the judging of each), and a BASE's whole-volume pass
// over N chunks adds 2N (the pass and the judging of each). A walk charged
// before it ran, or charged twice, misses the exact delta.
func TestADrainedCutChargesItsWholeVolumeWalkToThePause(t *testing.T) {
s, _ := newChunkTestStore(t)
l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl)
if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set
t.Fatal(err)
}
l.precopyPrepare = func(context.Context) (func(), error) { return func() {}, nil } // drained to the freeze
t.Cleanup(func() { l.precopyPrepare = nil })
cut := func(what string) int64 {
t.Helper()
r, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatalf("%s: %v", what, err)
}
return r.Stats.PauseCandidateOps
}
plain := cut("a drained cut with nothing to walk")
const k = 3
l.stMu.Lock()
for i := uint64(0); i < k; i++ {
l.dirty[i] = true
}
l.stMu.Unlock()
if got, want := cut("k dirty chunks")-plain, int64(2*k); got != want {
t.Fatalf("a drained cut over %d dirty chunks charged %d more pause operations, want %d", k, got, want)
}
l.stMu.Lock()
l.allDirty = true // as after a BASE: every chunk is walked
l.stMu.Unlock()
if got, want := cut("a whole-volume pass")-plain, 2*int64(l.numChunks); got != want {
t.Fatalf("a drained cut's whole-volume pass charged %d more pause operations, want %d (the pass and the judging, %d chunks each)", got, want, l.numChunks)
}
if got := cut("nothing to walk again"); got != plain {
t.Fatalf("a drained cut with nothing to walk after them charged %d, want %d (nothing carried over)", got, plain)
}
}
+19 -2
View File
@@ -475,6 +475,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
hooks.beforeMutation = l.beforeCOWMutation
hooks.beforeDestructive = l.holdCOWDestructive
// The live touched set exists before the hooks are published: the first
// map entry change (under WALStore.mu) only sets a bit, never allocates a
// volume-sized bitmap.
l.unkMu.Lock()
l.touchedLocked(false)
l.unkMu.Unlock()
if !s.chunk.CompareAndSwap(nil, hooks) {
l.cancel()
return nil, errors.New("storage: a chunk layer is already attached")
@@ -1826,7 +1832,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
candidates, visits := l.candidatesFrom(members, h)
visits += int64(len(taken.summary)) // the summary words the walk read
l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause
for idx := range dirtyTaken {
visits++
candidates[idx] = true
@@ -1844,6 +1849,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
}
l.stMu.Unlock()
// Charged after every walk (the touched set, the dirty set, a BASE's
// whole-volume pass): a drained pre-copy frontend is still paused here.
l.pauseOp(int(visits))
candidateOracleCompare(oracleWant, candidates) // tests only
// A chunk known to hold HEAD's bytes at its current version (a clean
// fill, or a compare by a cut that did not publish) is not compared
@@ -2899,7 +2907,16 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
out.ReconcileDone = 0
l.stMu.Unlock()
out.DirtyChunks = len(l.captureCandidates())
dirty := l.captureCandidates()
// A cut's judged candidates stay counted until its HEAD installs: one the
// flush checkpointed out of the dirty map meanwhile is in neither source
// above. Read under stMu; the cut keeps its own taken set.
l.stMu.Lock()
for idx := range l.inflight {
dirty[idx] = true
}
l.stMu.Unlock()
out.DirtyChunks = len(dirty)
out.AbsentChunks = l.absentHydratable()
return out
@@ -14,6 +14,28 @@ import (
// dark: only these tests call it.
// slotsV3 decodes both descriptor slots of the file at path.
// slotsV3Of reads both descriptor slots through the open store's own file:
// a second handle cannot read a range the store holds locked (Windows).
func slotsV3Of(t *testing.T, s *WALStore) (a, b descriptorV3) {
t.Helper()
for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} {
buf := make([]byte, slotSizeV3)
if _, err := s.fd.ReadAt(buf, off); err != nil {
t.Fatal(err)
}
d, err := decodeSlotV3(buf, nil)
if err != nil {
t.Fatalf("slot %d: %v", i, err)
}
if i == 0 {
a = d
} else {
b = d
}
}
return a, b
}
func slotsV3(t *testing.T, path string) (a, b descriptorV3) {
t.Helper()
f, err := os.Open(path)
@@ -383,7 +405,7 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) {
// unchanged (same position and LSN), but it is a new write: the read must
// retry and return it, not report WAL damage.
func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage(t *testing.T) {
s, path := newStoreV3(t, WModeStrict)
s, _ := newStoreV3(t, WModeStrict)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
resolved, invalid := newHeldV3(t), newHeldV3(t)
writeSynced(t, s, 1, 1) // LSN 1
@@ -403,7 +425,7 @@ func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage
})
waitV3(t, resolved.parked, "Read after resolving LSN 2")
s.v3.testReadResolved = nil
damageRecord(t, path, 2)
damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked
if _, err := s.Recover(); err != nil { // drops LSN 2 and fences its bytes
t.Fatalf("Recover: %v", err)
}
@@ -6,6 +6,7 @@ import (
"math"
"math/rand"
"path/filepath"
"sort"
"testing"
"time"
)
@@ -181,11 +182,11 @@ func TestWALStoreV3DrainHeldIsTheFlusherPhase(t *testing.T) {
}
// A dense image written as single 4 KiB writes in random order, three
// WALs' worth, on a slow disk (every extent write takes 2 ms), with a 500 ms admission
// budget. A whole-map cycle (about 480 entries, about 1 s) frees nothing
// until it ends, so a write times out waiting for space; bounded cycles free
// space every sixteenth of the WAL, and no write times out while reclaim
// moves. The guest sees a slow disk, not errors.
// WALs' worth, on a slow disk (every extent write takes 5 ms), with an
// admission budget of half a whole-map cycle. A whole-map cycle (about 480
// entries) frees nothing until it ends, so a write times out waiting for
// space; bounded cycles free space every sixteenth of the WAL, and no write
// times out while reclaim moves. The guest sees a slow disk, not errors.
func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) {
const walSize = 2 << 20
const count = 3 * walSize / 4096
@@ -195,8 +196,17 @@ func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { _ = s.Close() })
s.admissionTimeout = 500 * time.Millisecond
s.flusher.beforeExtentWriteForTest = func() { time.Sleep(2 * time.Millisecond) }
// The slow disk is a 5 ms sleep per extent write. The admission budget is
// half a whole-map cycle (about 480 records), from the sleep as measured
// on this host: a whole-map cycle still outlasts it (the red), while a
// bounded cycle (a sixteenth of this WAL, about 32 records) leaves room
// for a slow fsync on a busy host (the budget is about 1.2 s, the bounded
// cycle's writes about 160 ms).
const delay = 5 * time.Millisecond
sleep := measuredSleep(delay)
s.admissionTimeout = 240 * sleep
t.Logf("measured sleep %v: admission budget %v", sleep, s.admissionTimeout)
s.flusher.beforeExtentWriteForTest = func() { time.Sleep(delay) }
lbas := rand.New(rand.NewSource(1)).Perm(count)
start := time.Now()
busy := 0
@@ -528,3 +538,15 @@ func TestWALStoreV3HeldDrainEndsInTheProductionDrain(t *testing.T) {
}
}
}
// measuredSleep is the median time a sleep of d actually takes on this host.
func measuredSleep(d time.Duration) time.Duration {
var got [9]time.Duration
for i := range got {
start := time.Now()
time.Sleep(d)
got[i] = time.Since(start)
}
sort.Slice(got[:], func(i, j int) bool { return got[i] < got[j] })
return got[len(got)/2]
}
@@ -869,7 +869,7 @@ func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T)
// recovery drops its cut, must not acknowledge it; a fresh Sync after the
// recovery acknowledges normally.
func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) {
s, path := newStoreV3(t, WModeLagged)
s, _ := newStoreV3(t, WModeLagged)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
h := newHeldV3(t)
writeSynced(t, s, 1, 1)
@@ -880,7 +880,7 @@ func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) {
syn := h.start(func() error { _, err := s.Sync(); return err })
waitV3(t, h.parked, "the outer Sync before its completion")
s.v3.testSyncBeforeCompletion = nil
damageRecord(t, path, 2)
damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked
if _, err := s.Recover(); err != nil {
t.Fatalf("Recover: %v", err)
}