diff --git a/seaweed-block/cmd/sw-block/shell.go b/seaweed-block/cmd/sw-block/shell.go index 0ebd29a309..150a89edb9 100644 --- a/seaweed-block/cmd/sw-block/shell.go +++ b/seaweed-block/cmd/sw-block/shell.go @@ -16,8 +16,19 @@ import ( ) type inspectionShell struct { - master, filer, chunkPath, statusAddr, serverID string - timeout, maxClockSkew time.Duration + master, filer, chunkPath, serverID string + statusAddrs statusAddrList + timeout, maxClockSkew time.Duration +} + +// statusAddrList is the repeatable -status-addr flag: the loopback status +// addresses of this host's holders, one per volume. +type statusAddrList []string + +func (l *statusAddrList) String() string { return strings.Join(*l, ",") } +func (l *statusAddrList) Set(v string) error { + *l = append(*l, v) + return nil } func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int { @@ -28,14 +39,14 @@ func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int { fs.StringVar(&s.master, "master", "", "blockmaster address") fs.StringVar(&s.filer, "filer", "", "filer address, for direct store inspections") fs.StringVar(&s.chunkPath, "chunkPath", defaultChunkPathCLI, "block metadata directory") - fs.StringVar(&s.statusAddr, "status-addr", "", "this host's loopback holder status address") + fs.Var(&s.statusAddrs, "status-addr", "a loopback holder status address on this host; repeat it, one per volume") local, _ := os.Hostname() fs.StringVar(&s.serverID, "server-id", local, "this host's blockvolume server-id") fs.DurationVar(&s.timeout, "timeout", 10*time.Second, "bound for each command") fs.DurationVar(&s.maxClockSkew, "max-clock-skew", 20*time.Second, "master's configured workspace skew bound") fs.StringVar(&command, "c", "", "one command instead of reading stdin") if fs.Parse(args) != nil || fs.NArg() != 0 || s.master == "" || s.timeout <= 0 || s.maxClockSkew <= 0 { - fmt.Fprintln(stderr, "usage: sw-block shell -master ADDR [-filer ADDR] [-status-addr ADDR -server-id ID] [-c 'cluster.status -o json']") + fmt.Fprintln(stderr, "usage: sw-block shell -master ADDR [-filer ADDR] [-status-addr ADDR ... -server-id ID] [-c 'cluster.status -o json']") return 2 } if command != "" { diff --git a/seaweed-block/cmd/sw-block/shell_check.go b/seaweed-block/cmd/sw-block/shell_check.go index e820e03104..f7372a790f 100644 --- a/seaweed-block/cmd/sw-block/shell_check.go +++ b/seaweed-block/cmd/sw-block/shell_check.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "net/url" + "reflect" "strings" "time" @@ -24,15 +25,32 @@ type inspectionCheck struct { Run func(*inspectionObservation) checkFinding } -type checkFinding struct{ Status, Finding string } +// checkFinding is one check's outcome. Cure, when set, replaces the check's +// own cure: it names the cause this finding actually found (a holder that +// does not answer is not the check's usual fault). +type checkFinding struct{ Status, Finding, Cure string } type inspectionResult struct { ID, Title, Reach, Status, Finding string Cure, See string `json:",omitempty"` } -func checkOK(s string) checkFinding { return checkFinding{"ok", s} } -func checkFail(s string) checkFinding { return checkFinding{"FAIL", s} } -func checkElsewhere(s string) checkFinding { return checkFinding{"not checked here", s} } +func checkOK(s string) checkFinding { return checkFinding{"ok", s, ""} } +func checkFail(s string) checkFinding { return checkFinding{"FAIL", s, ""} } +func checkElsewhere(s string) checkFinding { return checkFinding{"not checked here", s, ""} } + +// stoppedFinding is every per-volume check's answer for a volume the master +// reports stopped cleanly: nothing serves it, on purpose. Not a FAIL. +var stoppedFinding = checkFinding{"stopped", "stopped cleanly (its holder released the lease); attach it to serve it", ""} + +// holderUnreachableCure is the cure of every holder check whose holder status +// page did not answer: the check's own cure would name a fault it never saw. +const holderUnreachableCure = "the volume's holder did not answer its status page: check that its blockvolume runs (systemctl status) and that -status-addr is that holder's --status-addr, then run the check again." + +// checkHolderFail is a holder check's FAIL for a status page that did not +// answer. +func checkHolderFail(err error) checkFinding { + return checkFinding{"FAIL", err.Error(), holderUnreachableCure} +} type holderInspection struct { VolumeID, ReplicaID, Version, NotReadyReason string @@ -88,6 +106,7 @@ type inspectedVolume struct { holder holderInspection durable durableInspection holderErr, durableErr error + notServed string // a local volume no given -status-addr serves local bool } type inspectionObservation struct { @@ -140,12 +159,20 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse iv := inspectedVolume{evidence: v} iv.lease, iv.leaseErr = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: v.VolumeID}) iv.local = primaryInspectionHost(v) != "" && primaryInspectionHost(v) == s.serverID - if iv.local { - iv.holderErr = s.readHolder(ctx, "/status", v.VolumeID, &iv.holder) - if iv.holderErr == nil && (iv.holder.VolumeID != v.VolumeID || iv.holder.ReplicaID != v.PrimaryReplica || iv.holder.Epoch != v.Epoch) { - iv.holderErr = errors.New("holder status identity differs from master's primary") + if iv.local && v.Status != ops.ObservationStatusStopped { + addr, err := s.holderAddress(ctx, v.VolumeID, &iv.holder) + switch { + case errors.Is(err, errVolumeNotServedHere): + // Another holder on this host serves it; its address was not given. + iv.notServed = "no given -status-addr serves " + v.VolumeID + "; add its holder's status address" + case err != nil: + iv.holderErr, iv.durableErr = err, err + default: + if iv.holder.VolumeID != v.VolumeID || iv.holder.ReplicaID != v.PrimaryReplica || iv.holder.Epoch != v.Epoch { + iv.holderErr = errors.New("holder status identity differs from master's primary") + } + iv.durableErr = s.readHolderAt(ctx, addr, "/status/durable", v.VolumeID, &iv.durable) } - iv.durableErr = s.readHolder(ctx, "/status/durable", v.VolumeID, &iv.durable) } o.volumes = append(o.volumes, iv) } @@ -172,6 +199,9 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse if f.Status == "FAIL" { code = 1 r.Cure = c.Cure + if f.Cure != "" { + r.Cure = f.Cure + } r.See = "docs/troubleshooting.md#" + strings.ReplaceAll(c.ID, ".", "") } else if f.Status == "not checked here" && code == 0 { code = 3 @@ -194,11 +224,55 @@ func (s inspectionShell) checkObservation(ctx context.Context, o *inspectionObse return code } +// errHolderStatusNotFound is a holder's 404: it does not serve that volume. +var errHolderStatusNotFound = errors.New("holder does not serve this volume") + +// errVolumeNotServedHere: none of the given status addresses serves the volume. +var errVolumeNotServedHere = errors.New("no given status address serves this volume") + +// holderAddress finds which given status address serves volume (one holder +// per volume) and reads its /status into dst. +func (s inspectionShell) holderAddress(ctx context.Context, volume string, dst any) (string, error) { + return s.holderRead(ctx, "/status", volume, dst) +} + +// readHolder reads path for volume from whichever given status address +// serves it. func (s inspectionShell) readHolder(ctx context.Context, path, volume string, dst any) error { - if s.statusAddr == "" { - return errors.New("status page is off: start blockvolume with --status-addr 127.0.0.1:") + _, err := s.holderRead(ctx, path, volume, dst) + return err +} + +// holderRead tries every given status address and returns the first that +// answers path for volume. An address that does not answer (a stopped holder +// on the same host) does not hide a later one that serves the volume. When +// none serves it, the first failure other than 404 is returned; only when +// every address answered 404 is it errVolumeNotServedHere. +func (s inspectionShell) holderRead(ctx context.Context, path, volume string, dst any) (string, error) { + if len(s.statusAddrs) == 0 { + return "", errors.New("status page is off: start blockvolume with --status-addr 127.0.0.1:") } - base := s.statusAddr + var failed error + for _, addr := range s.statusAddrs { + if v := reflect.ValueOf(dst); v.Kind() == reflect.Pointer && !v.IsNil() { + v.Elem().SetZero() // nothing a failed address decoded survives + } + err := s.readHolderAt(ctx, addr, path, volume, dst) + if err == nil { + return addr, nil + } + if !errors.Is(err, errHolderStatusNotFound) && failed == nil { + failed = err + } + } + if failed != nil { + return "", failed + } + return "", errVolumeNotServedHere +} + +func (s inspectionShell) readHolderAt(ctx context.Context, addr, path, volume string, dst any) error { + base := addr if !strings.Contains(base, "://") { base = "http://" + base } @@ -224,6 +298,9 @@ func (s inspectionShell) readHolder(ctx context.Context, path, volume string, ds return err } defer resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("%s returned HTTP 404: %w", path, errHolderStatusNotFound) + } if resp.StatusCode != http.StatusOK { return fmt.Errorf("%s returned HTTP %d", path, resp.StatusCode) } @@ -253,24 +330,37 @@ func (o *inspectionObservation) each(local bool, run func(inspectedVolume) check return checkElsewhere("no selected volume evidence") } state := "ok" - allNotApplicable := true + allNotApplicable, allStopped := true, true + cure, plain := "", false // the failing volumes' cause-specific cure; plain: one failed for the check's own reason parts := []string{} for _, v := range o.volumes { var f checkFinding - if local && !v.local { + if v.evidence.Status == ops.ObservationStatusStopped { + f = stoppedFinding + } else if local && !v.local { host := primaryInspectionHost(v.evidence) if host == "" { host = "unknown holder host" } f = checkElsewhere("run on " + host) + } else if local && v.notServed != "" { + f = checkElsewhere(v.notServed) } else { f = run(v) } if f.Status != "not applicable" { allNotApplicable = false } + if f.Status != "stopped" { + allStopped = false + } if f.Status == "FAIL" { state = "FAIL" + if f.Cure != "" && cure == "" { + cure = f.Cure + } else if f.Cure == "" { + plain = true + } } else if f.Status == "not checked here" && state != "FAIL" { state = "not checked here" } @@ -278,8 +368,13 @@ func (o *inspectionObservation) each(local bool, run func(inspectedVolume) check } if state == "ok" && allNotApplicable { state = "not applicable" + } else if state == "ok" && allStopped { + state = "stopped" } - return checkFinding{state, strings.Join(parts, "; ")} + if plain { + cure = "" // a volume failed for the check's own reason: its own cure applies + } + return checkFinding{state, strings.Join(parts, "; "), cure} } func (o *inspectionObservation) reachable() checkFinding { if o.masterErr != nil { @@ -359,7 +454,7 @@ func (o *inspectionObservation) lease() checkFinding { func (o *inspectionObservation) frontend() checkFinding { return o.each(true, func(v inspectedVolume) checkFinding { if v.holderErr != nil { - return checkFail(v.holderErr.Error()) + return checkHolderFail(v.holderErr) } if v.holder.FrontendPrimaryReady == nil { return checkFail("frontend readiness field unavailable") @@ -373,10 +468,10 @@ func (o *inspectionObservation) frontend() checkFinding { func (o *inspectionObservation) chunkstore() checkFinding { return o.each(true, func(v inspectedVolume) checkFinding { if v.holderErr != nil { - return checkFail(v.holderErr.Error()) + return checkHolderFail(v.holderErr) } if v.durableErr != nil { - return checkFail(v.durableErr.Error()) + return checkHolderFail(v.durableErr) } for _, d := range v.durable.Volumes { if d.VolumeID != v.evidence.VolumeID { @@ -400,17 +495,17 @@ func (o *inspectionObservation) chunkstore() checkFinding { func (o *inspectionObservation) cut() checkFinding { return o.each(true, func(v inspectedVolume) checkFinding { if v.holderErr != nil { - return checkFail(v.holderErr.Error()) + return checkHolderFail(v.holderErr) } if v.durableErr != nil { - return checkFail(v.durableErr.Error()) + return checkHolderFail(v.durableErr) } for _, d := range v.durable.Volumes { if d.VolumeID != v.evidence.VolumeID { continue } if d.Impl == "walstore" { - return checkFinding{"not applicable", "no chunk store"} + return checkFinding{"not applicable", "no chunk store", ""} } if d.Chunk == nil || d.Chunk.Stats == nil { return checkFail("cut counters unavailable") @@ -448,17 +543,17 @@ func (o *inspectionObservation) cut() checkFinding { func (o *inspectionObservation) cleaning() checkFinding { return o.each(true, func(v inspectedVolume) checkFinding { if v.holderErr != nil { - return checkFail(v.holderErr.Error()) + return checkHolderFail(v.holderErr) } if v.durableErr != nil { - return checkFail(v.durableErr.Error()) + return checkHolderFail(v.durableErr) } for _, d := range v.durable.Volumes { if d.VolumeID != v.evidence.VolumeID { continue } if d.Impl == "walstore" { - return checkFinding{"not applicable", "no chunk store"} + return checkFinding{"not applicable", "no chunk store", ""} } if d.Chunk == nil || d.Chunk.Maintenance == nil { return checkElsewhere("last cleaning result not exposed by this build; see maintenance log") @@ -498,7 +593,7 @@ func (o *inspectionObservation) cleaning() checkFinding { func (o *inspectionObservation) versions() checkFinding { return o.each(true, func(v inspectedVolume) checkFinding { if v.holderErr != nil { - return checkFail(v.holderErr.Error()) + return checkHolderFail(v.holderErr) } if unknownInspectionVersion(o.cluster.ProductRevision) || unknownInspectionVersion(v.holder.Version) { return checkFail("master or holder revision unavailable") diff --git a/seaweed-block/cmd/sw-block/shell_test.go b/seaweed-block/cmd/sw-block/shell_test.go index 1b1064f5b7..b669680b50 100644 --- a/seaweed-block/cmd/sw-block/shell_test.go +++ b/seaweed-block/cmd/sw-block/shell_test.go @@ -19,6 +19,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -92,6 +93,21 @@ func (s inspectionControlServer) GetClusterStatus(ctx context.Context, q *contro for _, event := range r.Events { event.NodeName = "host-b" } + if s.mode == "second-volume-elsewhere" { + // A second volume on the same host, served by a holder whose status + // address is not given. + v2 := proto.Clone(r.Volumes[0]).(*control.VolumeEvidence) + v2.VolumeId = "v2" + r.Volumes = append(r.Volumes, v2) + } + if s.mode == "second-volume-stopped" { + // A second volume on the same host, stopped cleanly: the master says + // so, its holder is gone (no observation) and its lease is revoked. + v2 := proto.Clone(r.Volumes[0]).(*control.VolumeEvidence) + v2.VolumeId, v2.Status, v2.Reason = "v2", ops.ObservationStatusStopped, ops.ReasonStoppedCleanly + v2.Replicas = []*control.ReplicaEvidence{{ReplicaId: "r2", ServerId: "host-b"}} + r.Volumes = append(r.Volumes, v2) + } return r, err } func (s inspectionControlServer) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { @@ -114,12 +130,14 @@ func (s inspectionControlServer) QueryWorkspace(_ context.Context, q *control.Wo l.Revoking = true case "lease-wrong-holder": l.ReplicaId = "r3" + case "second-volume-stopped": + l.Revoking = q.GetVolumeId() == "v2" } return &control.WorkspaceStatus{Lease: l}, nil } func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) { for _, tc := range []struct{ mode, id string }{ - {"healthy", ""}, {"disabled", "master.lifecycle"}, {"store-missing", "master.lifecycle"}, {"lease-expired", "volume.lease"}, {"lease-revoking", "volume.lease"}, {"lease-wrong-holder", "volume.lease"}, + {"healthy", ""}, {"first-addr-unrelated", ""}, {"first-addr-down", ""}, {"holder-500", "volume.frontend"}, {"second-volume-elsewhere", "volume.frontend"}, {"second-volume-stopped", ""}, {"disabled", "master.lifecycle"}, {"store-missing", "master.lifecycle"}, {"lease-expired", "volume.lease"}, {"lease-revoking", "volume.lease"}, {"lease-wrong-holder", "volume.lease"}, {"frontend-false", "volume.frontend"}, {"cut-pending", "volume.cut"}, {"snapshot-overdue", "volume.cut"}, {"missing-cut-fields", "volume.cut"}, {"version-missing", "versions.equal"}, {"version-mismatch", "versions.equal"}, {"cleaning-error", "volume.cleaning"}, {"cleaning-not-run", "volume.cleaning"}, {"cleaning-running", "volume.cleaning"}, {"cleaning-missing", "volume.cleaning"}, {"missing-cleaning-head-gen", "volume.cleaning"}, {"null-cleaning-head-gen", "volume.cleaning"}, {"missing-cleaning-breakdown", "volume.cleaning"}, {"retention-only", "volume.cleaning"}, {"missing-cleaning-error", "volume.cleaning"}, {"null-cleaning-error", "volume.cleaning"}, {"completed-empty", ""}, {"completed-head-gen-note", ""}, {"failed-head-gen-note", "volume.cleaning"}, {"no-chunk-store", "volume.cut"}, @@ -137,6 +155,14 @@ func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) { defer srv.Stop() defer ln.Close() h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.mode == "holder-500" { + http.Error(w, "holder failure", http.StatusInternalServerError) + return + } + if (tc.mode == "second-volume-elsewhere" || tc.mode == "second-volume-stopped") && r.URL.Query().Get("volume") == "v2" { + http.NotFound(w, r) // this holder serves v1 only + return + } if r.URL.Path == "/status" { body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": tc.mode != "frontend-false", "Version": "test-rev"} if tc.mode == "version-missing" { @@ -207,16 +233,67 @@ func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) { })) defer h.Close() var out, errout bytes.Buffer - code := run([]string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b", "-status-addr", h.URL, "-c", "cluster.check -o json"}, &out, &errout) + args := []string{"shell", "-master", ln.Addr().String(), "-server-id", "host-b"} + if tc.mode == "first-addr-unrelated" { + // -status-addr repeats: an unrelated holder first (it serves no + // v1), then v1's own. + other := httptest.NewServer(http.NotFoundHandler()) + defer other.Close() + args = append(args, "-status-addr", other.URL) + } + if tc.mode == "first-addr-down" { + // A stopped holder's address first (connection refused), then + // v1's own: the refusal does not hide v1's holder. + down := httptest.NewServer(http.NotFoundHandler()) + downURL := down.URL + down.Close() + args = append(args, "-status-addr", downURL) + } + args = append(args, "-status-addr", h.URL) + if tc.mode == "first-addr-unrelated" { + // And another after it: every address counts, not only the last. + last := httptest.NewServer(http.NotFoundHandler()) + defer last.Close() + args = append(args, "-status-addr", last.URL) + } + args = append(args, "-c", "cluster.check -o json") + code := run(args, &out, &errout) rows := requireInspectionOutput(t, out.Bytes()) for _, r := range rows { if r.Status == "FAIL" && (r.See != "docs/troubleshooting.md#"+strings.ReplaceAll(r.ID, ".", "") || r.Cure == "") { t.Fatalf("failure lacks a working page link and cure: %+v", r) } } + // Every FAIL's cure names the cause the case injected: a holder whose + // status page did not answer gets the reachability cure on every + // holder row; any other failure gets its check's own cure. + for id, r := range rows { + if r.Status != "FAIL" { + continue + } + want := "" + for _, c := range inspectionChecks { + if c.ID == id { + want = c.Cure + } + } + if tc.mode == "holder-500" && r.Reach == "host" { + want = holderUnreachableCure + } + if id == tc.id && r.Cure != want { + t.Fatalf("%s: cure %q, want %q for this cause", id, r.Cure, want) + } + } if tc.id != "" { want := "FAIL" - if tc.mode == "cleaning-running" || tc.mode == "cleaning-missing" || tc.mode == "retention-only" || tc.mode == "missing-cleaning-error" || tc.mode == "null-cleaning-error" || tc.mode == "missing-cleaning-head-gen" || tc.mode == "null-cleaning-head-gen" || tc.mode == "missing-cleaning-breakdown" || tc.mode == "no-chunk-store" { + if tc.mode == "second-volume-elsewhere" { + for _, id := range []string{"volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning"} { + if r := rows[id]; r.Status == "FAIL" || !strings.Contains(r.Finding, "no given -status-addr serves v2") { + t.Fatalf("a volume whose status address was not given: %+v, want not checked here, never FAIL", r) + } + } + } + if tc.mode == "second-volume-elsewhere" || tc.mode == "cleaning-running" || tc.mode == "cleaning-missing" || tc.mode == "retention-only" || tc.mode == "missing-cleaning-error" || tc.mode == "null-cleaning-error" || tc.mode == "missing-cleaning-head-gen" || tc.mode == "null-cleaning-head-gen" || tc.mode == "missing-cleaning-breakdown" || tc.mode == "no-chunk-store" { want = "not checked here" } if tc.mode == "no-chunk-store" { @@ -250,6 +327,15 @@ func TestShellCheckUsesTypedLeaseReadinessCutAndVersionAnswers(t *testing.T) { if code != 3 { t.Fatalf("expected incomplete only for missing filer, exit=%d out=%s", code, &out) } + if tc.mode == "second-volume-stopped" { + // Every per-volume check answers stopped for v2, never FAIL, and + // v1's checks are unchanged (asserted ok below). + for _, id := range []string{"host.heartbeat", "volume.assigned", "volume.lease", "volume.frontend", "volume.chunkstore", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew"} { + if r := rows[id]; !strings.Contains(r.Finding, "v2: stopped") { + t.Fatalf("a cleanly stopped volume: %+v, want v2 stopped", r) + } + } + } if tc.mode == "completed-head-gen-note" { if finding := rows["volume.cleaning"].Finding; !strings.Contains(finding, "HEAD read unavailable after completed cleaning") { t.Fatalf("completed cleaning lost generation-read note: %s", finding) diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index c5641dd29d..6b0813c323 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -198,6 +198,18 @@ func (s *ObservationStore) ServerOfSlotAt(volumeID, replicaID, dataAddr, ctrlAdd return server, found } +// LatestObservedAt is the time of serverID's newest accepted observation (its +// last heartbeat), or false when the store holds none for it. +func (s *ObservationStore) LatestObservedAt(serverID string) (time.Time, bool) { + s.mu.Lock() + defer s.mu.Unlock() + obs, ok := s.observations[serverID] + if !ok || obs.ObservedAt.IsZero() { + return time.Time{}, false + } + return obs.ObservedAt, true +} + // SlotFactOnServer never substitutes a same-replica claim from another host. func (s *ObservationStore) SlotFactOnServer(serverID, volumeID, replicaID string) (SlotFact, bool) { s.mu.Lock() diff --git a/seaweed-block/core/frontend/durable/write_profile.go b/seaweed-block/core/frontend/durable/write_profile.go index 9192555c67..3087713c36 100644 --- a/seaweed-block/core/frontend/durable/write_profile.go +++ b/seaweed-block/core/frontend/durable/write_profile.go @@ -58,7 +58,7 @@ type WriteProfileStatus struct { } type DurabilityLatencyStatus struct { - Frontend iolatency.RequestStatus // per-request latency at the frontend, by stage + Frontend iolatency.RequestStatus // per-request latency at the frontend (NVMe/TCP, iSCSI and ublk), by stage BackendSync iolatency.Distribution // latency of backend syncs WAL *storage.DurabilityLatencyStatus `json:",omitempty"` // the WAL's own sync latency, where the store reports it } diff --git a/seaweed-block/core/frontend/iscsi/durability_profile_test.go b/seaweed-block/core/frontend/iscsi/durability_profile_test.go new file mode 100644 index 0000000000..5462b98aca --- /dev/null +++ b/seaweed-block/core/frontend/iscsi/durability_profile_test.go @@ -0,0 +1,44 @@ +package iscsi_test + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" + "github.com/seaweedfs/seaweed-block/core/iolatency" +) + +// profiledBackend exposes the durable backend's request profile seam. +type profiledBackend struct { + frontend.Backend + requests *iolatency.Requests +} + +func (b profiledBackend) BeginDurabilityRequest(ctx context.Context, kind string) (context.Context, *iolatency.Request) { + return b.requests.Begin(ctx, kind) +} + +// iSCSI writes and SYNCHRONIZE CACHE are counted in the frontend request +// profile, as NVMe/TCP and ublk requests are (/status/durable +// WriteProfile.DurabilityLatency.Frontend). +func TestISCSIWritesAndFlushesAreProfiled(t *testing.T) { + b := profiledBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v"}), requests: &iolatency.Requests{}} + sh := iscsi.NewSCSIHandler(iscsi.HandlerConfig{Backend: b, VolumeSize: 1 << 20}) + var write [16]byte + write[0] = iscsi.ScsiWrite10 + write[8] = 1 + for i := 0; i < 3; i++ { + if r := sh.HandleCommand(context.Background(), write, make([]byte, 512)); r.Status != iscsi.StatusGood { + t.Fatalf("write: %+v", r) + } + } + if r := sh.HandleCommand(context.Background(), [16]byte{iscsi.ScsiSyncCache10}, nil); r.Status != iscsi.StatusGood { + t.Fatalf("sync: %+v", r) + } + got := b.requests.Snapshot() + if got.Writes != 3 || got.Flushes != 1 || got.Failed != 0 { + t.Fatalf("frontend profile after 3 writes and 1 flush: writes %d flushes %d failed %d", got.Writes, got.Flushes, got.Failed) + } +} diff --git a/seaweed-block/core/frontend/iscsi/scsi.go b/seaweed-block/core/frontend/iscsi/scsi.go index 61d34c23b2..7b8e5cb283 100644 --- a/seaweed-block/core/frontend/iscsi/scsi.go +++ b/seaweed-block/core/frontend/iscsi/scsi.go @@ -213,7 +213,11 @@ func (h *SCSIHandler) HandleCommand(ctx context.Context, cdb [16]byte, dataOut [ return *r } log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE handler entry opcode=0x%02x", cdb[0]) - if err := h.backend.Sync(ctx); err != nil { + // Profiled like NVMe/TCP and ublk flushes (WriteProfile.DurabilityLatency.Frontend). + syncCtx, trace := frontend.BeginDurabilityRequest(ctx, h.backend, "flush") + err := h.backend.Sync(syncCtx) + trace.Finish(err != nil) + if err != nil { log.Printf("iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync FAILED: %v", err) return mapBackendError(ctx, err, "sync") } @@ -302,7 +306,10 @@ func (h *SCSIHandler) doWrite(ctx context.Context, lba uint64, transferLen uint3 expectedBytes, len(dataOut)) return illegalRequest(ASCInvalidFieldInCDB, 0x00, "dataOut shorter than expected") } - _, err := h.backend.Write(ctx, int64(lba)*int64(h.blockSize), dataOut[:expectedBytes]) + // Profiled like NVMe/TCP and ublk writes (WriteProfile.DurabilityLatency.Frontend). + writeCtx, trace := frontend.BeginDurabilityRequest(ctx, h.backend, "write") + _, err := h.backend.Write(writeCtx, int64(lba)*int64(h.blockSize), dataOut[:expectedBytes]) + trace.Finish(err != nil) if err != nil { log.Printf("iscsi: SCSI WRITE backend.Write FAILED lba=%d: %v", lba, err) return mapBackendError(ctx, err, "write") diff --git a/seaweed-block/core/host/master/observation_heartbeat_test.go b/seaweed-block/core/host/master/observation_heartbeat_test.go new file mode 100644 index 0000000000..c736266444 --- /dev/null +++ b/seaweed-block/core/host/master/observation_heartbeat_test.go @@ -0,0 +1,33 @@ +package master + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" +) + +// A node's last_heartbeat_at is its newest heartbeat, not its registration +// time: after a master restart the registration's SeenAt stays put while the +// node heartbeats on. +func TestObservationNodesReportTheNewestHeartbeat(t *testing.T) { + registered := time.Date(2026, 12, 3, 8, 55, 33, 0, time.UTC) + heartbeat := registered.Add(6*time.Minute + 39*time.Second) + nodes := []lifecycle.NodeRegistration{{ServerID: "s1", SeenAt: registered}, {ServerID: "s2", SeenAt: registered}} + latest := func(server string) (time.Time, bool) { + if server == "s1" { + return heartbeat, true + } + return time.Time{}, false + } + got := map[string]time.Time{} + for _, n := range observationNodes(nodes, nil, latest) { + got[n.NodeName] = n.LastHeartbeatAt + } + if !got["s1"].Equal(heartbeat) { + t.Fatalf("s1 last heartbeat %v, want its newest heartbeat %v (not the registration %v)", got["s1"], heartbeat, registered) + } + if !got["s2"].Equal(registered) { + t.Fatalf("s2 without a held heartbeat: %v, want the registration time %v", got["s2"], registered) + } +} diff --git a/seaweed-block/core/host/master/observation_snapshot.go b/seaweed-block/core/host/master/observation_snapshot.go index d93071db8a..c5593ea140 100644 --- a/seaweed-block/core/host/master/observation_snapshot.go +++ b/seaweed-block/core/host/master/observation_snapshot.go @@ -26,7 +26,7 @@ func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { return cluster } - cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements) + cluster.Nodes = observationNodes(snapshot.Nodes, snapshot.Placements, h.lastHeartbeat) cluster.Volumes = h.observationVolumes(snapshot) waits := h.grantWaits(now) for i := range cluster.Nodes { @@ -62,7 +62,19 @@ func (h *Host) ObservationSnapshot(now time.Time) ops.ClusterEvidence { return cluster } -func observationNodes(nodes []lifecycle.NodeRegistration, placements []lifecycle.PlacementIntent) []ops.NodeEvidence { +// lastHeartbeat is the time of serverID's newest heartbeat the observation +// store accepted. +func (h *Host) lastHeartbeat(serverID string) (time.Time, bool) { + if h.obs == nil || h.obs.Store() == nil { + return time.Time{}, false + } + return h.obs.Store().LatestObservedAt(serverID) +} + +// observationNodes reports each registered node with its newest heartbeat; +// a node registration's SeenAt (set when it registered, so frozen across a +// master restart) is the fallback only when no heartbeat is held. +func observationNodes(nodes []lifecycle.NodeRegistration, placements []lifecycle.PlacementIntent, lastHeartbeat func(string) (time.Time, bool)) []ops.NodeEvidence { replicaCounts := map[string]int{} for _, placement := range placements { for _, slot := range placement.Slots { @@ -85,7 +97,7 @@ func observationNodes(nodes []lifecycle.NodeRegistration, placements []lifecycle FrontendNetworkClass: node.Labels[lifecycle.FrontendNetworkClassLabel], Schedulable: true, Ready: true, - LastHeartbeatAt: node.SeenAt, + LastHeartbeatAt: nodeHeartbeat(node, lastHeartbeat), ReplicaCount: replicaCounts[node.ServerID], }) } @@ -242,9 +254,37 @@ func (h *Host) observationVolume(volumeID string, rec lifecycle.VolumeRecord, pl Message: "authority controller rejected the latest observed topology", }) } + if hasLine && line.Assigned && h.stoppedCleanly(volumeID, line) { + volume.Status = ops.ObservationStatusStopped + volume.Reason = ops.ReasonStoppedCleanly + volume.Conditions = append(volume.Conditions, ops.ObservationCondition{ + Type: "Stopped", + Status: "true", + Reason: ops.ReasonStoppedCleanly, + Severity: "info", + Message: "stopped: its holder released the lease cleanly; attach it to serve it again", + }) + } return volume } +// stoppedCleanly reports a volume stopped on purpose, from the master's own +// lease record: the revocation ACK recorded for the line's holder at its +// epoch (accepted only for a detached HEAD within the lease, and cleared by +// the next move). A lease that ended by expiry or a forced move has no such +// ACK. Missing slot observations are expected then; any other unsupported +// topology still blocks. +func (h *Host) stoppedCleanly(volumeID string, line authority.AuthorityBasis) bool { + ws := h.Publisher().WorkspaceState(volumeID) + if ws == nil || ws.Ack == nil || ws.Ack.Epoch != line.Epoch || ws.Ack.ReplicaID != line.ReplicaID { + return false + } + if unsupported, ok := h.Controller().LastUnsupported(volumeID); ok && !unsupportedReasonsAllowPromotionProbe(strings.Split(unsupported.Reason, ",")) { + return false + } + return true +} + // formatTooOldConditions names, at format level 1 and above, each server // holding volumeID (placement, authority line, topology) whose process for // it reads below the level: the grant gate refuses it (binary_too_old), and @@ -467,3 +507,12 @@ func hostFromAddr(addr string) string { } return addr } + +func nodeHeartbeat(node lifecycle.NodeRegistration, lastHeartbeat func(string) (time.Time, bool)) time.Time { + if lastHeartbeat != nil { + if at, ok := lastHeartbeat(node.ServerID); ok && at.After(node.SeenAt) { + return at + } + } + return node.SeenAt +} diff --git a/seaweed-block/core/host/master/observation_stopped_test.go b/seaweed-block/core/host/master/observation_stopped_test.go new file mode 100644 index 0000000000..a5e97f8f5c --- /dev/null +++ b/seaweed-block/core/host/master/observation_stopped_test.go @@ -0,0 +1,65 @@ +package master + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +func observedVolume(t *testing.T, cluster ops.ClusterEvidence, id string) ops.VolumeEvidence { + t.Helper() + for _, v := range cluster.Volumes { + if v.VolumeID == id { + return v + } + } + t.Fatalf("volume %s missing from %+v", id, cluster.Volumes) + return ops.VolumeEvidence{} +} + +// A volume whose holder released its lease cleanly (the master recorded its +// revocation ACK at the line's epoch) is reported stopped, from the master's +// own lease record. A revocation not yet acknowledged is not a stop, and the +// next move to a new epoch is no longer stopped. +func TestObservationReportsACleanlyStoppedVolumeStopped(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "vs") + p := h.Publisher() + if _, err := p.RenewWorkspaceLease(ctx, "vs", "r1", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "vs", "r1", 1); err != nil { + t.Fatal(err) + } + if v := observedVolume(t, h.ObservationSnapshot(time.Now().UTC()), "vs"); v.Status == ops.ObservationStatusStopped { + t.Fatalf("a revocation not yet acknowledged reads stopped: %+v", v) + } + head := authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true} + if err := p.AckWorkspaceRevocation(ctx, "vs", authority.WorkspaceRevokeAck{ReplicaID: "r1", Epoch: 1, HeadGen: head.Gen, Holder: head.Holder}, head); err != nil { + t.Fatal(err) + } + cluster := h.ObservationSnapshot(time.Now().UTC()) + v := observedVolume(t, cluster, "vs") + t.Logf("stopped: cluster=%s volume=%+v", cluster.Status, v) + if v.Status != ops.ObservationStatusStopped || v.Reason != ops.ReasonStoppedCleanly { + t.Fatalf("a cleanly stopped volume: status=%q reason=%q, want %q %q", v.Status, v.Reason, ops.ObservationStatusStopped, ops.ReasonStoppedCleanly) + } + if got := clusterStatus([]ops.VolumeEvidence{v}, nil); got != ops.ObservationStatusOK { + t.Fatalf("a cleanly stopped volume rolls the cluster up to %q, want ok", got) + } + + target := lifecycle.WorkspaceBinding{VolumeID: "vs", ServerID: "node-b", DataAddr: "127.0.0.1:20000", CtrlAddr: "127.0.0.1:20001"} + if err := h.lifecycle.WorkspaceBindings.Register(target); err != nil { + t.Fatal(err) + } + moved, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "move-1", VolumeID: "vs", ExpectedReplicaID: "r1", ExpectedHost: "node-a", ExpectedEpoch: 1, TargetReplicaID: "r1", TargetHost: target.ServerID, TargetDataAddr: target.DataAddr, TargetCtrlAddr: target.CtrlAddr, Kind: "clean"}, head) + if err != nil || !moved.Issued { + t.Fatalf("move: %+v %v", moved, err) + } + if v := observedVolume(t, h.ObservationSnapshot(time.Now().UTC()), "vs"); v.Status == ops.ObservationStatusStopped { + t.Fatalf("a volume moved to a new epoch still reads stopped: %+v", v) + } +} diff --git a/seaweed-block/core/iolatency/latency.go b/seaweed-block/core/iolatency/latency.go index c722f6000b..11ccd60abc 100644 --- a/seaweed-block/core/iolatency/latency.go +++ b/seaweed-block/core/iolatency/latency.go @@ -61,7 +61,8 @@ func (h *Histogram) Snapshot() Distribution { return s } -// Requests is the common frontend-to-backend boundary, shared by ublk and NVMe. +// Requests is the common frontend-to-backend boundary, shared by ublk, NVMe/TCP +// and iSCSI. // AckDispatch ends before the handler returns a result, not at guest receipt. type Requests struct { writeTotal, flushTotal, fuaTotal Histogram diff --git a/seaweed-block/core/ops/observation.go b/seaweed-block/core/ops/observation.go index 2035797c8b..409afade93 100644 --- a/seaweed-block/core/ops/observation.go +++ b/seaweed-block/core/ops/observation.go @@ -17,6 +17,12 @@ const ( ObservationStatusBlocked = "blocked" ObservationStatusInvalid = "invalid" ObservationStatusUnavailable = "unavailable" + // A volume stopped on purpose: its holder released its lease cleanly + // and nothing serves it. Not a fault; the cluster status ignores it. + ObservationStatusStopped = "stopped" + // ReasonStoppedCleanly: the master recorded the holder's clean release + // (its revocation ACK) for the volume's current epoch. + ReasonStoppedCleanly = "stopped_cleanly" ReasonPrimaryNodeLost = "primary_node_lost" ReasonCandidateCoversRequiredFrontier = "candidate_covers_required_frontier" diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index f616bda962..c39a41b0fb 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -132,7 +132,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Closed` | bool | the backend was closed | | `Volumes[].WriteProfile` | object | write-path counters since start | | `Volumes[].WriteProfile.DurabilityLatency` | object | latency distributions of writes, flushes and syncs | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend, by stage | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend (NVMe/TCP, iSCSI and ublk), by stage | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | end-to-end latency of writes | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | samples observed | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | their total nanoseconds | diff --git a/seaweed-block/docs/time-bounds.tsv b/seaweed-block/docs/time-bounds.tsv index da336fd872..335176192f 100644 --- a/seaweed-block/docs/time-bounds.tsv +++ b/seaweed-block/docs/time-bounds.tsv @@ -85,8 +85,8 @@ cmd/sw-block/mini.go mini time.Now().Add 1 523 per-call NONE: no model row maps cmd/sw-block/mini.go mini context.WithTimeout 1 525 per-call NONE: no model row maps this file yet one CLI request (operator --timeout) cmd/sw-block/mini.go mini time.After 1 540 control-timer NONE: no model row maps this file yet resolve-wait poll cmd/sw-block/mini.go mini time.After 2 568 control-timer NONE: no model row maps this file yet resolve-wait poll -cmd/sw-block/shell.go inspectionShell.execute context.WithTimeout 1 195 per-call NONE: no model row maps this file yet one CLI request (operator --timeout) -cmd/sw-block/shell_check.go inspectionShell.check context.WithTimeout 1 104 per-call NONE: no model row maps this file yet one CLI request (operator --timeout) +cmd/sw-block/shell.go inspectionShell.execute context.WithTimeout 1 206 per-call NONE: no model row maps this file yet one CLI request (operator --timeout) +cmd/sw-block/shell_check.go inspectionShell.check context.WithTimeout 1 123 per-call NONE: no model row maps this file yet one CLI request (operator --timeout) cmd/sw-block/snapshot_operation.go chunkObserveSnapshot context.WithTimeout 1 66 per-call SnapOps.Send one CLI request (operator --timeout) cmd/sw-block/snapshot_operation.go chunkObserveSnapshot time.NewTimer 1 113 control-timer SnapOps.Send poll or delay timer cmd/sw-block/volume_backup.go volumeSnapshot context.WithTimeout 1 136 pending-fix RestoreCommand.Abort; RestoreCommand.AbortVerify; RestoreCommand.Run; RestoreCommand.Start a cut waiter's fixed total; fix follows the cut window of #964 (one waiter PR for snapshot, backup, plain detach and stop) diff --git a/seaweed-block/docs/troubleshooting.md b/seaweed-block/docs/troubleshooting.md index a5fd5fd6e0..f590c2ff6c 100644 --- a/seaweed-block/docs/troubleshooting.md +++ b/seaweed-block/docs/troubleshooting.md @@ -1,7 +1,7 @@ # Troubleshooting `cluster.check` in `sw-block shell` runs the checks below in the order a start-up fails and prints -one line per check: `ok`, `FAIL`, `not checked here` or `not applicable`. A `FAIL` line names its section on this page. Each section +one line per check: `ok`, `FAIL`, `stopped`, `not checked here` or `not applicable`. A `FAIL` line names its section on this page. Each section begins with the same one-sentence cure the command prints, then says what you see and how to fix it. - Checks of blockmaster and the filer run on any machine that reaches them. @@ -10,6 +10,12 @@ begins with the same one-sentence cure the command prints, then says what you se host for them. They never print `ok` off the host. - On a volume host whose `blockvolume` runs with `--status-addr` empty (the default), the holder's checks fail with the cure: start `blockvolume` with `--status-addr 127.0.0.1:`. +- On the volume host, give `sw-block shell` the host's `-server-id` and one `-status-addr` per volume it serves, + for example `-server-id s1 -status-addr 127.0.0.1:9203 -status-addr 127.0.0.1:9213`. A volume whose holder's + status address is not given prints `not checked here: no given -status-addr serves `, never `FAIL`. +- A volume whose lease was released (revoked, and the holder's acknowledgement recorded) prints `stopped` in every + volume check, never `FAIL`, and does not count against the cluster status. A lease that ran out or was taken by a + forced move is not a release: its checks still fail. This page and the command come from one list; a test keeps them equal.