From 2aec1d503b6034d0f6a1503a2e1d0bd1b3bbe31e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 28 Nov 2026 16:28:31 -0800 Subject: [PATCH] feat: add read-only shell inspections and ordered cluster checks --- seaweed-block/cmd/sw-block/main.go | 4 + seaweed-block/cmd/sw-block/shell.go | 228 ++++++++++ seaweed-block/cmd/sw-block/shell_check.go | 415 ++++++++++++++++++ .../cmd/sw-block/shell_check_rows.go | 18 + seaweed-block/cmd/sw-block/shell_test.go | 147 +++++++ seaweed-block/docs/design/inspection-shell.md | 52 +++ 6 files changed, 864 insertions(+) create mode 100644 seaweed-block/cmd/sw-block/shell.go create mode 100644 seaweed-block/cmd/sw-block/shell_check.go create mode 100644 seaweed-block/cmd/sw-block/shell_check_rows.go create mode 100644 seaweed-block/cmd/sw-block/shell_test.go create mode 100644 seaweed-block/docs/design/inspection-shell.md diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index 3bfedcd99f..ac26704bce 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -99,6 +99,9 @@ func run(args []string, stdout, stderr io.Writer) int { if args[0] == "volume" { return runVolume(args[1:], stdout, stderr) } + if args[0] == "shell" { + return runShell(args[1:], os.Stdin, stdout, stderr) + } if args[0] != "ops" { fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0]) usage(stderr) @@ -2294,6 +2297,7 @@ func normalizeObservationVolumeArgs(args []string) []string { func usage(w io.Writer) { fmt.Fprintln(w, "usage:") fmt.Fprintln(w, " sw-block --version") + fmt.Fprintln(w, " sw-block shell -master [-filer ] [-chunkPath ] [-c ]") fmt.Fprintln(w, " sw-block ops status --volume --master --status-addr --out ") fmt.Fprintln(w, " sw-block ops inventory --namespace [--master ] --out ") fmt.Fprintln(w, " sw-block ops cluster --namespace [--master |--master-api ] [-o json]") diff --git a/seaweed-block/cmd/sw-block/shell.go b/seaweed-block/cmd/sw-block/shell.go new file mode 100644 index 0000000000..b6304e6b49 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell.go @@ -0,0 +1,228 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" +) + +type inspectionShell struct { + master, filer, chunkPath, statusAddr, serverID string + timeout, maxClockSkew time.Duration +} + +func runShell(args []string, input io.Reader, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("sw-block shell", flag.ContinueOnError) + fs.SetOutput(stderr) + s := inspectionShell{} + var command string + 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") + 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']") + return 2 + } + if command != "" { + return s.execute(command, stdout, stderr) + } + interactive := false + if f, ok := input.(*os.File); ok { + if info, err := f.Stat(); err == nil { + interactive = info.Mode()&os.ModeCharDevice != 0 + } + } + scanner := bufio.NewScanner(input) + scanner.Buffer(make([]byte, 4096), 64<<10) + code := 0 + for { + if interactive { + fmt.Fprint(stdout, "sw-block> ") + } + if !scanner.Scan() { + break + } + line := strings.TrimSpace(scanner.Text()) + if line == "quit" || line == "exit" { + break + } + if line == "" { + continue + } + if c := s.execute(line, stdout, stderr); c != 0 { + code = c + } + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(stderr, err) + return 2 + } + return code +} + +// Shell words support quoting, but never variable expansion or command execution. +func inspectionWords(line string) ([]string, error) { + var words []string + var word strings.Builder + var quote rune + escaped, active := false, false + for _, r := range line { + if escaped { + word.WriteRune(r) + escaped = false + active = true + continue + } + if r == '\\' && quote != '\'' { + escaped = true + active = true + continue + } + if quote != 0 { + if r == quote { + quote = 0 + } else { + word.WriteRune(r) + } + active = true + continue + } + if r == '\'' || r == '"' { + quote = r + active = true + continue + } + if r == ' ' || r == '\t' { + if active { + words = append(words, word.String()) + word.Reset() + active = false + } + continue + } + word.WriteRune(r) + active = true + } + if quote != 0 || escaped { + return nil, errors.New("unfinished quote or escape") + } + if active { + words = append(words, word.String()) + } + return words, nil +} + +func (s inspectionShell) execute(line string, stdout, stderr io.Writer) int { + words, err := inspectionWords(line) + if err != nil { + fmt.Fprintln(stderr, err) + return 2 + } + if len(words) == 0 { + return 0 + } + name, args := words[0], words[1:] + if name == "help" { + fmt.Fprintln(stdout, "cluster.status, cluster.check [volume], volume.list, volume.status , volume.explain , snapshot.list , store.show , store.usage , volume.verify ; each supports -o json; quit") + return 0 + } + format := "text" + var positional []string + for i := 0; i < len(args); i++ { + if args[i] == "-o" { + i++ + if i == len(args) { + return 2 + } + format = args[i] + } else { + positional = append(positional, args[i]) + } + } + if format != "text" && format != "json" { + fmt.Fprintln(stderr, "output must be text or json") + return 2 + } + if name == "cluster.check" { + if len(positional) > 1 { + fmt.Fprintln(stderr, "cluster.check accepts at most one volume") + return 2 + } + volume := "" + if len(positional) == 1 { + volume = positional[0] + } + return s.check(volume, format, stdout, stderr) + } + if name == "snapshot.list" || name == "store.show" || name == "store.usage" || name == "volume.verify" { + if len(positional) != 1 || s.filer == "" { + fmt.Fprintf(stderr, "%s requires a volume and shell -filer\n", name) + return 2 + } + run := map[string]func([]string, io.Writer, io.Writer) int{"snapshot.list": chunkSnapshots, "store.show": chunkShow, "store.usage": chunkUsage, "volume.verify": chunkVerify}[name] + return run([]string{"--master", s.master, "--chunk-filer", s.filer, "--chunk-path", s.chunkPath, "--timeout", s.timeout.String(), "--volume", positional[0]}, stdout, stderr) + } + if name != "cluster.status" && name != "volume.list" && name != "volume.status" && name != "volume.explain" { + fmt.Fprintf(stderr, "unknown inspection command %q; use help\n", name) + return 2 + } + want := 0 + if name == "volume.status" || name == "volume.explain" { + want = 1 + } + if len(positional) != want { + fmt.Fprintf(stderr, "%s needs %d volume arguments\n", name, want) + return 2 + } + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + cluster, err := readMasterClusterEvidence(ctx, s.master) + if err != nil { + fmt.Fprintf(stderr, "%s: %v\n", name, err) + return 1 + } + var value any = cluster + text := ops.RenderClusterEvidenceText(cluster) + if name == "volume.list" { + value = cluster.Volumes + } + if want == 1 { + found := false + for _, v := range cluster.Volumes { + if v.VolumeID == positional[0] { + value = v + text = ops.RenderVolumeEvidenceText(v) + found = true + break + } + } + if !found { + fmt.Fprintf(stderr, "volume %q not found\n", positional[0]) + return 1 + } + } + if format == "json" { + if err := json.NewEncoder(stdout).Encode(value); err != nil { + fmt.Fprintln(stderr, err) + return 1 + } + } else { + fmt.Fprint(stdout, text) + } + return 0 +} diff --git a/seaweed-block/cmd/sw-block/shell_check.go b/seaweed-block/cmd/sw-block/shell_check.go new file mode 100644 index 0000000000..8e880d566c --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_check.go @@ -0,0 +1,415 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/ops" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type inspectionCheck struct { + ID, Title, Reach, Cure string + Run func(*inspectionObservation) checkFinding +} + +type checkFinding struct{ Status, Finding 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} } + +type holderInspection struct { + VolumeID, ReplicaID, Version, NotReadyReason string + Epoch uint64 + FrontendPrimaryReady *bool +} +type durableInspection struct { + ProcessID string + Volumes []struct { + VolumeID string + Chunk *struct { + Attached bool + Stats *struct { + LastCutNs int64 + CutsFailed uint64 + PendingUnresolved bool + } + ScheduledSnapshot *struct { + Overdue bool `json:"snapshot_overdue"` + LastFailure *struct{ Code string } `json:"lastFailure"` + } + CurrentCut *struct { + Phase string `json:"phase"` + AttemptStartedAt time.Time `json:"attempt_started_at"` + } + } + } +} +type inspectedVolume struct { + evidence ops.VolumeEvidence + lease *control.WorkspaceStatus + leaseErr error + holder holderInspection + durable durableInspection + holderErr, durableErr error + local bool +} +type inspectionObservation struct { + shell inspectionShell + cluster ops.ClusterEvidence + masterErr, lifecycleErr, filerErr error + filerChecked bool + started, ended time.Time + volumes []inspectedVolume + requested string +} + +func (s inspectionShell) check(volume, format string, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(context.Background(), s.timeout) + defer cancel() + o := &inspectionObservation{shell: s, requested: volume, started: time.Now()} + o.cluster, o.masterErr = readMasterClusterEvidence(ctx, s.master) + o.ended = time.Now() + if o.masterErr == nil { + conn, err := link.DialMasterFromEnv(s.master) + o.lifecycleErr = err + if err == nil { + defer conn.Close() + client := control.NewWorkspaceServiceClient(conn) + // A nonexistent name still distinguishes a missing lifecycle store or disabled RPC. + _, err = client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "__cluster_check__"}) + if status.Code(err) == codes.NotFound { + err = nil + } + o.lifecycleErr = err + for _, v := range o.cluster.Volumes { + if volume != "" && v.VolumeID != volume { + continue + } + 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") + } + iv.durableErr = s.readHolder(ctx, "/status/durable", v.VolumeID, &iv.durable) + } + o.volumes = append(o.volumes, iv) + } + } + } + if s.filer != "" { + o.filerChecked = true + f, closeF, err := dialChunkFiler(s.filer) + if err == nil { + err = checkSingleFiler(ctx, f) + _ = closeF() + } + o.filerErr = err + } + rows := make([]inspectionResult, 0, len(inspectionChecks)) + code := 0 + for _, c := range inspectionChecks { + f := c.Run(o) + if o.masterErr != nil && c.ID != "master.reachable" && c.ID != "filer.single" { + f = checkElsewhere("master did not answer; prerequisite unavailable") + } + r := inspectionResult{ID: c.ID, Title: c.Title, Reach: c.Reach, Status: f.Status, Finding: f.Finding} + if f.Status == "FAIL" { + code = 1 + r.Cure = c.Cure + r.See = "docs/troubleshooting.md#" + c.ID + } else if f.Status == "not checked here" && code == 0 { + code = 3 + } + rows = append(rows, r) + } + if format == "json" { + if err := json.NewEncoder(stdout).Encode(rows); err != nil { + fmt.Fprintln(stderr, err) + return 1 + } + } else { + for _, r := range rows { + fmt.Fprintf(stdout, "%s %s: %s\n", r.Status, r.ID, r.Finding) + if r.Status == "FAIL" { + fmt.Fprintf(stdout, " cure: %s; see %s\n", r.Cure, r.See) + } + } + } + return code +} + +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:") + } + base := s.statusAddr + if !strings.Contains(base, "://") { + base = "http://" + base + } + u, err := url.Parse(base) + if err != nil { + return err + } + ip := net.ParseIP(u.Hostname()) + if u.Scheme != "http" || ip == nil || !ip.IsLoopback() || u.User != nil || u.RawQuery != "" || (u.Path != "" && u.Path != "/") { + return errors.New("holder status requires an explicit loopback HTTP address") + } + u.Path = path + q := url.Values{} + q.Set("volume", volume) + u.RawQuery = q.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return err + } + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("status redirects are refused") }} + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s returned HTTP %d", path, resp.StatusCode) + } + raw, err := io.ReadAll(io.LimitReader(resp.Body, (2<<20)+1)) + if err != nil { + return err + } + if len(raw) > 2<<20 { + return errors.New("status exceeds 2 MiB") + } + return json.Unmarshal(raw, dst) +} + +func primaryInspectionHost(v ops.VolumeEvidence) string { + if v.PrimaryNode != "" { + return v.PrimaryNode + } + for _, r := range v.Replicas { + if r.ReplicaID == v.PrimaryReplica { + return r.ServerID + } + } + return "" +} +func (o *inspectionObservation) each(local bool, run func(inspectedVolume) checkFinding) checkFinding { + if len(o.volumes) == 0 { + return checkElsewhere("no selected volume evidence") + } + state := "ok" + parts := []string{} + for _, v := range o.volumes { + var f checkFinding + if local && !v.local { + host := primaryInspectionHost(v.evidence) + if host == "" { + host = "unknown holder host" + } + f = checkElsewhere("run on " + host) + } else { + f = run(v) + } + if f.Status == "FAIL" { + state = "FAIL" + } else if f.Status == "not checked here" && state != "FAIL" { + state = "not checked here" + } + parts = append(parts, v.evidence.VolumeID+": "+f.Status+" "+f.Finding) + } + return checkFinding{state, strings.Join(parts, "; ")} +} +func (o *inspectionObservation) reachable() checkFinding { + if o.masterErr != nil { + return checkFail(o.masterErr.Error()) + } + return checkOK(o.shell.master + " answered") +} +func (o *inspectionObservation) lifecycle() checkFinding { + if o.lifecycleErr != nil { + return checkFail(o.lifecycleErr.Error()) + } + return checkOK("workspace query accepted") +} +func (o *inspectionObservation) version() checkFinding { + if unknownInspectionVersion(o.cluster.ProductRevision) { + return checkFail("no version reported") + } + return checkOK(o.cluster.ProductRevision) +} +func unknownInspectionVersion(v string) bool { + return v == "" || strings.Contains(strings.ToLower(v), "unknown") +} +func (o *inspectionObservation) filer() checkFinding { + if !o.filerChecked { + return checkElsewhere("set shell -filer for the single-filer check") + } + if o.filerErr != nil { + return checkFail(o.filerErr.Error()) + } + return checkOK("one filer in its group at this moment") +} +func (o *inspectionObservation) heartbeat() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if len(v.evidence.Replicas) == 0 { + return checkFail("no slot observations") + } + for _, r := range v.evidence.Replicas { + if !r.Observed { + return checkFail(r.ServerID + " not observed") + } + } + return checkOK("all slots observed; age not available") + }) +} +func (o *inspectionObservation) known() checkFinding { + if o.requested != "" && len(o.volumes) == 0 { + return checkFail(o.requested + " not found") + } + if len(o.volumes) == 0 { + return checkElsewhere("no volumes registered") + } + return checkOK(fmt.Sprintf("%d volume records", len(o.volumes))) +} +func (o *inspectionObservation) assigned() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if v.evidence.Epoch == 0 || v.evidence.PrimaryReplica == "" { + return checkFail("no primary (epoch 0)") + } + return checkOK(fmt.Sprintf("%s@%d on %s", v.evidence.PrimaryReplica, v.evidence.Epoch, primaryInspectionHost(v.evidence))) + }) +} +func (o *inspectionObservation) lease() checkFinding { + return o.each(false, func(v inspectedVolume) checkFinding { + if v.evidence.ReplicationFactor != 1 { + return checkElsewhere("workspace lease check applies to RF1") + } + if v.leaseErr != nil { + return checkFail(v.leaseErr.Error()) + } + l := v.lease.GetLease() + if l == nil || l.GetEpoch() != v.evidence.Epoch || l.GetReplicaId() != v.evidence.PrimaryReplica || l.GetValidForNs() <= 0 || l.GetRevoking() { + return checkFail("lease absent, expired, revoking or differs from the observed primary") + } + return checkOK("granted, not revoking (master observation)") + }) +} +func (o *inspectionObservation) frontend() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.holder.FrontendPrimaryReady == nil { + return checkFail("frontend readiness field unavailable") + } + if !*v.holder.FrontendPrimaryReady { + return checkFail(v.holder.NotReadyReason) + } + return checkOK("holder's frontend serves") + }) +} +func (o *inspectionObservation) cut() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.durableErr != nil { + return checkFail(v.durableErr.Error()) + } + for _, d := range v.durable.Volumes { + if d.VolumeID != v.evidence.VolumeID { + continue + } + if d.Chunk == nil || d.Chunk.Stats == nil { + return checkFail("cut counters unavailable") + } + c := d.Chunk + st := c.Stats + finding := fmt.Sprintf("last_cut_ns=%d historical_failures=%d", st.LastCutNs, st.CutsFailed) + if c.CurrentCut != nil { + finding += fmt.Sprintf(" cut in phase %s since %s", c.CurrentCut.Phase, c.CurrentCut.AttemptStartedAt.UTC().Format(time.RFC3339Nano)) + } + if st.PendingUnresolved { + return checkFail(finding + " pending HEAD outcome unresolved") + } + if c.ScheduledSnapshot != nil && c.ScheduledSnapshot.Overdue { + code := "" + if c.ScheduledSnapshot.LastFailure != nil { + code = c.ScheduledSnapshot.LastFailure.Code + } + return checkFail(finding + " snapshot_overdue " + code) + } + if st.CutsFailed > 0 { + return checkElsewhere(finding + "; one observation cannot prove a new failure; see the holder log") + } + if st.LastCutNs == 0 { + return checkElsewhere(finding + "; no completed cut since start") + } + return checkOK(finding) + } + return checkFail("selected volume absent from durable status") + }) +} +func (o *inspectionObservation) cleaning() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if v.durableErr != nil { + return checkFail(v.durableErr.Error()) + } + return checkElsewhere("last cleaning result status contract not available in this build; see maintenance log") + }) +} +func (o *inspectionObservation) versions() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if v.holderErr != nil { + return checkFail(v.holderErr.Error()) + } + if unknownInspectionVersion(o.cluster.ProductRevision) || unknownInspectionVersion(v.holder.Version) { + return checkFail("master or holder revision unavailable") + } + if o.cluster.ProductRevision != v.holder.Version { + return checkFail("blockmaster " + o.cluster.ProductRevision + ", blockvolume " + v.holder.Version) + } + return checkOK(v.holder.Version) + }) +} +func (o *inspectionObservation) clock() checkFinding { + return o.each(true, func(v inspectedVolume) checkFinding { + if o.cluster.CapturedAt.IsZero() { + return checkFail("master time unavailable") + } + rtt := o.ended.Sub(o.started) + mid := o.started.Add(rtt / 2) + diff := mid.Sub(o.cluster.CapturedAt) + if diff < 0 { + diff = -diff + } + bound := diff + rtt/2 + finding := fmt.Sprintf("local clock difference plus RTT uncertainty %s; configured max skew %s", bound, o.shell.maxClockSkew) + if bound >= o.shell.maxClockSkew/2 { + return checkFail(finding) + } + return checkOK(finding) + }) +} diff --git a/seaweed-block/cmd/sw-block/shell_check_rows.go b/seaweed-block/cmd/sw-block/shell_check_rows.go new file mode 100644 index 0000000000..272599407d --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_check_rows.go @@ -0,0 +1,18 @@ +package main + +// The order and cure paragraphs are pinned to docs/troubleshooting.md. +var inspectionChecks = []inspectionCheck{ + {ID: "master.reachable", Title: "master.reachable", Reach: "anywhere", Cure: "blockmaster did not answer at `-master`: check that it runs and that `-master` is its `--listen` address; a non-loopback address needs the client certificate the role file names.", Run: (*inspectionObservation).reachable}, + {ID: "master.lifecycle", Title: "master.lifecycle", Reach: "anywhere", Cure: "blockmaster runs without `--lifecycle-store`: walstore-chunk volumes need it, so start blockmaster with it and restart.", Run: (*inspectionObservation).lifecycle}, + {ID: "master.version", Title: "master.version", Reach: "anywhere", Cure: "blockmaster did not report its version: it is older than v1.0.1, so upgrade it first.", Run: (*inspectionObservation).version}, + {ID: "filer.single", Title: "filer.single", Reach: "master+filer", Cure: "sw-block needs exactly one filer in its filer group: remove the other filers of the group or give the block store its own group, then restart the volume hosts.", Run: (*inspectionObservation).filer}, + {ID: "host.heartbeat", Title: "host.heartbeat", Reach: "anywhere", Cure: "No fresh heartbeat from `` for this volume: check that its blockvolume unit runs and reaches `--master`, and that its clock is synchronized (a backward step beyond the freshness window expires its slots).", Run: (*inspectionObservation).heartbeat}, + {ID: "volume.known", Title: "volume.known", Reach: "anywhere", Cure: "blockmaster does not know ``: add it to the cluster spec (or register its volume record) and restart blockmaster.", Run: (*inspectionObservation).known}, + {ID: "volume.assigned", Title: "volume.assigned", Reach: "anywhere", Cure: "No primary assigned: check that `--server-id` and `--replica-id` match the volume's slot and that `--expected-slots-per-volume` equals its slot count.", Run: (*inspectionObservation).assigned}, + {ID: "volume.lease", Title: "volume.lease", Reach: "anywhere", Cure: "The holder waits for its lease: read `MasterWait.Reason` on its status page; `unreachable`, `credentials` or `identity refused` each name what to fix.", Run: (*inspectionObservation).lease}, + {ID: "volume.frontend", Title: "volume.frontend", Reach: "host", Cure: "The frontend does not serve: the status page's `NotReadyReason` names the step (listener not up yet, the durable backend admits no I/O, lease, profile).", Run: (*inspectionObservation).frontend}, + {ID: "volume.cut", Title: "volume.cut", Reach: "host", Cure: "Cuts are behind or failing: read `lastFailure.code` and the holder's log for `capture` errors; a cut that needs more than one 5-minute request is retried by the schedule.", Run: (*inspectionObservation).cut}, + {ID: "volume.cleaning", Title: "volume.cleaning", Reach: "host", Cure: "The volume's last cleaning pass failed or has not run: read its result on the holder's `/status/durable` and the holder's log; cleaning runs every `--chunk-maintenance-interval` and after a snapshot delete made by the holder.", Run: (*inspectionObservation).cleaning}, + {ID: "versions.equal", Title: "versions.equal", Reach: "host", Cure: "blockmaster and this volume's blockvolume run different releases: finish the upgrade in the documented order.", Run: (*inspectionObservation).versions}, + {ID: "clock.skew", Title: "clock.skew", Reach: "host", Cure: "This host's clock is far from blockmaster's: synchronize both to one time source (chrony, slewing, not stepping); beyond `--workspace-max-clock-skew` (20 s by default) the lease bound does not hold.", Run: (*inspectionObservation).clock}, +} diff --git a/seaweed-block/cmd/sw-block/shell_test.go b/seaweed-block/cmd/sw-block/shell_test.go new file mode 100644 index 0000000000..1e16577866 --- /dev/null +++ b/seaweed-block/cmd/sw-block/shell_test.go @@ -0,0 +1,147 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "regexp" + "strings" + "sync/atomic" + "testing" +) + +func TestShellClusterStatusReadsTheMasterWithoutKubernetes(t *testing.T) { + addr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + code := run([]string{"shell", "-master", addr, "-c", "cluster.status -o json"}, &out, &errout) + if code != 0 { + t.Fatalf("exit=%d stderr=%s stdout=%s", code, &errout, &out) + } + var body map[string]any + if err := json.Unmarshal(out.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body["schema_version"] == nil || body["volumes"] == nil { + t.Fatalf("not cluster evidence: %s", &out) + } +} + +func TestShellCheckNeverCallsOffHostChecksOK(t *testing.T) { + addr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + var requests atomic.Int32 + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + http.Error(w, "must not read off-host", 500) + })) + defer holder.Close() + code := run([]string{"shell", "-master", addr, "-server-id", "laptop", "-status-addr", holder.URL, "-c", "cluster.check -o json"}, &out, &errout) + if code == 2 { + t.Fatalf("command absent: %s", &errout) + } + var rows []struct{ ID, Status, Finding string } + if err := json.Unmarshal(out.Bytes(), &rows); err != nil { + t.Fatalf("%v: %s", err, &out) + } + if len(rows) != 13 { + t.Fatalf("got %d checks", len(rows)) + } + for _, r := range rows { + switch r.ID { + case "volume.frontend", "volume.cut", "volume.cleaning", "versions.equal", "clock.skew": + if r.Status != "not checked here" || !strings.Contains(r.Finding, "m02") { + t.Fatalf("off-host claim: %+v", r) + } + } + } + if requests.Load() != 0 { + t.Fatal("read an off-host status page") + } +} + +func TestShellCheckCuresAndOrderMatchTheTroubleshootingPage(t *testing.T) { + raw, err := os.ReadFile("../../docs/troubleshooting.md") + if err != nil { + t.Fatal(err) + } + sections := regexp.MustCompile(`(?m)^## `).Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), -1)[1:] + if len(sections) < len(inspectionChecks) { + t.Fatal("page missing checks") + } + for i, c := range inspectionChecks { + name, rest, _ := strings.Cut(sections[i], "\n") + paragraph, _, _ := strings.Cut(strings.TrimSpace(rest), "\n\n") + if strings.TrimSpace(name) != c.ID || strings.Join(strings.Fields(paragraph), " ") != c.Cure { + t.Fatalf("page/table mismatch at %s", c.ID) + } + } +} + +func TestShellReadsQuotedCommandsFromStdinAndKeepsFailures(t *testing.T) { + addr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + var out, errout bytes.Buffer + code := runShell([]string{"-master", addr}, strings.NewReader("volume.delete 'v1'\nvolume.status 'v1' -o json\nquit\n"), &out, &errout) + if code != 2 || !strings.Contains(out.String(), `"volume_id":"v1"`) || !strings.Contains(errout.String(), "unknown inspection command") { + t.Fatalf("exit=%d out=%s err=%s", code, &out, &errout) + } + for _, bad := range []string{`volume.status 'v1`, `volume.status v1\`} { + if _, err := inspectionWords(bad); err == nil { + t.Fatalf("accepted %q", bad) + } + } +} + +func TestShellCheckRefusesWrongHolderAndDoesNotFollowStatusRedirects(t *testing.T) { + addr, closeMaster := startCmdFakeMaster(t) + defer closeMaster() + for _, mode := range []string{"missing", "wrong-epoch", "missing-readiness", "redirect"} { + t.Run(mode, func(t *testing.T) { + var redirected atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { redirected.Add(1) })) + defer target.Close() + h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if mode == "redirect" { + http.Redirect(w, r, target.URL, 302) + return + } + if r.URL.Path == "/status" { + body := map[string]any{"VolumeID": "v1", "ReplicaID": "r2", "Epoch": 2, "FrontendPrimaryReady": true, "Version": "test-rev"} + if mode == "wrong-epoch" { + body["Epoch"] = 3 + } + if mode == "missing-readiness" { + delete(body, "FrontendPrimaryReady") + } + _ = json.NewEncoder(w).Encode(body) + return + } + fmtBody := map[string]any{"Volumes": []any{map[string]any{"VolumeID": "v1", "Chunk": map[string]any{"Stats": map[string]any{"LastCutNs": 1}}}}} + _ = json.NewEncoder(w).Encode(fmtBody) + })) + defer h.Close() + statusAddr := h.URL + if mode == "missing" { + statusAddr = "" + } + var out, errout bytes.Buffer + run([]string{"shell", "-master", addr, "-server-id", "m02", "-status-addr", statusAddr, "-c", "cluster.check -o json"}, &out, &errout) + var rows []inspectionResult + if err := json.Unmarshal(out.Bytes(), &rows); err != nil { + t.Fatalf("%v %s", err, &out) + } + for _, r := range rows { + if r.ID == "volume.frontend" && r.Status != "FAIL" { + t.Fatalf("wrong holder accepted: %+v", r) + } + } + if redirected.Load() != 0 { + t.Fatal("followed a status redirect") + } + }) + } +} diff --git a/seaweed-block/docs/design/inspection-shell.md b/seaweed-block/docs/design/inspection-shell.md new file mode 100644 index 0000000000..6f054ea93e --- /dev/null +++ b/seaweed-block/docs/design/inspection-shell.md @@ -0,0 +1,52 @@ +# Inspection shell + +`sw-block shell -master 127.0.0.1:9000` reads commands from stdin; `-c` runs one +command. This is a client over the existing evidence, workspace-query and filer +interfaces. It adds no server state, control RPC or authority decision. Existing +`ops` commands retain their flags and output. + +```sh +sw-block shell -master 127.0.0.1:9000 -c 'volume.list -o json' +printf 'cluster.status\nvolume.status v1 -o json\nquit\n' | sw-block shell -master 127.0.0.1:9000 +sw-block shell -master 127.0.0.1:9000 -filer 127.0.0.1:18888 -server-id host1 -status-addr 127.0.0.1:9090 -c 'cluster.check v1' +``` + +The inspection commands are `cluster.status`, `cluster.check [volume]`, +`volume.list`, `volume.status `, `volume.explain `, +`snapshot.list `, `store.show `, `store.usage ` and +`volume.verify `. `-o json` selects JSON. Store commands reuse the +existing chunk commands' JSON bodies in either output mode. Mutations are not +inspection commands; use the existing admitted `ops` paths. + +Shell flags supply the master, filer, chunk path and local holder status address +once. No endpoint is discovered from an absent master field. `-server-id` +defaults to the local hostname; set it to the local blockvolume's actual server +ID when they differ. A host check runs only when that ID matches the master's +primary host. The response must also name the observed volume, replica and epoch. +Status HTTP is restricted to explicit loopback IPs and refuses redirects. Do not +enable an unauthenticated external status listener for remote inspection. + +`cluster.check` emits the thirteen checks in the troubleshooting page's order. +Each failed line includes the same cure paragraph and a link to its page section. +Tests pin both order and cure paragraphs. Exit 0 means all checks completed +without findings, 1 reports a failed check, 2 is invalid input and 3 means at +least one check could not be performed here. Off-host or unavailable data never +becomes `ok`. A stream retains any nonzero command result even if a later command +succeeds. Quotes group words; there is no shell expansion or subprocess execution. + +These are separate read observations, not one atomic snapshot. A changed primary +can require rerunning the command. Workspace lease evidence applies to RF1 only. +Heartbeat freshness is the master's yes/no observation; the registration time is +not shown as heartbeat age. Clock skew includes round-trip uncertainty and uses +the shell's configured `-max-clock-skew`, which must match blockmaster. + +Cut failures are cumulative since process start. A single observation with a +historical failure count cannot prove a new failure; it is reported as incomplete +with the count and the log reference. Pending HEAD outcomes and overdue scheduled +snapshots are explicit findings. Missing version, readiness or cut fields are +reported as unavailable, with no inferred healthy default. + +The cleaning-result check remains incomplete until the holder's typed last-pass +status is available. Build revisions depend on the master and holder publishing +their revisions; older builds give an unavailable finding. This client does not +implement the exact HEAD-generation accounting verdict.