From 0c5ea948301820a91f10ee3547a6a9d7d2a97f1c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 04:59:39 -0800 Subject: [PATCH 1/3] chunkstore: the snapshot list and delete bodies as shared API types MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SnapshotListItem / SnapshotListBody (exactly B9 §3.3's fields) and SnapshotDeleteBody move from the volume routes to chunkstore, so the sw-block CLI, which reads the filer directly, emits the same bodies. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/chunkstore/api.go | 45 +++++++++++++++++++ .../core/host/volume/chunk_control.go | 36 +-------------- 2 files changed, 47 insertions(+), 34 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/api.go diff --git a/seaweed-block/core/frontend/chunkstore/api.go b/seaweed-block/core/frontend/chunkstore/api.go new file mode 100644 index 0000000000..243d2d7ccb --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/api.go @@ -0,0 +1,45 @@ +package chunkstore + +// The JSON bodies of a snapshot listing and a snapshot delete (B9 W2 §3.3, +// §3.4), shared by blockvolume's /chunk/* routes and the sw-block CLI, which +// reads the filer directly. + +// SnapshotListItem is one listed snapshot, exactly §3.3's fields. +type SnapshotListItem struct { + Name string `json:"name"` + HeadGen uint64 `json:"headGen"` + HeadEpoch uint64 `json:"headEpoch"` + CutLSN uint64 `json:"cutLSN"` + CreatedNs int64 `json:"createdNs"` + State string `json:"state"` + ChunkCount int `json:"chunkCount"` + Labels map[string]string `json:"labels"` + Consistency string `json:"consistency"` + Parent *Parent `json:"parent"` +} + +// SnapshotListBody is a listing page: the snapshots after the request's +// start, and next (the last name returned when more may follow, else ""). +type SnapshotListBody struct { + VolumeID string `json:"volumeID"` + Snapshots []SnapshotListItem `json:"snapshots"` + Next string `json:"next"` +} + +// NewSnapshotListBody is the listing body of vol's page list. +func NewSnapshotListBody(vol string, list []SnapshotInfo, next string) SnapshotListBody { + body := SnapshotListBody{VolumeID: vol, Snapshots: make([]SnapshotListItem, 0, len(list)), Next: next} + for _, s := range list { + body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch, + CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, ChunkCount: s.ChunkCount, Labels: s.Labels, + Consistency: s.Consistency, Parent: s.Parent}) + } + return body +} + +// SnapshotDeleteBody is a delete's result: state is SnapDeleting or SnapAbsent. +type SnapshotDeleteBody struct { + VolumeID string `json:"volumeID"` + Name string `json:"name"` + State string `json:"state"` +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 07b2926e20..f1095e15c4 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -86,32 +86,6 @@ type snapshotBody struct { Replayed bool `json:"replayed"` } -// snapshotItem is one entry of GET /chunk/snapshots, exactly §3.3's fields. -type snapshotItem struct { - Name string `json:"name"` - HeadGen uint64 `json:"headGen"` - HeadEpoch uint64 `json:"headEpoch"` - CutLSN uint64 `json:"cutLSN"` - CreatedNs int64 `json:"createdNs"` - State string `json:"state"` - ChunkCount int `json:"chunkCount"` - Labels map[string]string `json:"labels"` - Consistency string `json:"consistency"` - Parent *chunkstore.Parent `json:"parent"` -} - -type snapshotsBody struct { - VolumeID string `json:"volumeID"` - Snapshots []snapshotItem `json:"snapshots"` - Next string `json:"next"` -} - -type snapshotDeleteBody struct { - VolumeID string `json:"volumeID"` - Name string `json:"name"` - State string `json:"state"` -} - type chunkErrorBody struct { Code string `json:"code"` Message string `json:"message"` @@ -380,13 +354,7 @@ func (s *StatusServer) handleChunkSnapshots(w http.ResponseWriter, r *http.Reque writeChunkFailure(w, err) return } - body := snapshotsBody{VolumeID: vol, Snapshots: make([]snapshotItem, 0, len(list)), Next: next} - for _, s := range list { - body.Snapshots = append(body.Snapshots, snapshotItem{Name: s.Name, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch, - CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, ChunkCount: s.ChunkCount, Labels: s.Labels, - Consistency: s.Consistency, Parent: s.Parent}) - } - writeChunkJSON(w, http.StatusOK, body) + writeChunkJSON(w, http.StatusOK, chunkstore.NewSnapshotListBody(vol, list, next)) } func (s *StatusServer) handleChunkSnapshotDelete(w http.ResponseWriter, r *http.Request) { @@ -409,7 +377,7 @@ func (s *StatusServer) handleChunkSnapshotDelete(w http.ResponseWriter, r *http. writeChunkFailure(w, err) return } - writeChunkJSON(w, http.StatusOK, snapshotDeleteBody{VolumeID: req.VolumeID, Name: req.Name, State: state}) + writeChunkJSON(w, http.StatusOK, chunkstore.SnapshotDeleteBody{VolumeID: req.VolumeID, Name: req.Name, State: state}) } func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) { From 399d3a8eadae41216923d96678c03bf7b40aabac Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 05:01:44 -0800 Subject: [PATCH 2/3] sw-block: ops chunk cut|snapshot|detach|snapshots|snapshot-delete|fork MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The walstore-chunk control plane on the command line (B9 W2 §0.1, §3): - cut, snapshot and detach call a blockvolume's /chunk/* routes (--status-addr, with --chunk-control-endpoint); the request carries timeoutMs and the client waits a little longer; - snapshots, snapshot-delete and fork read and write the filer directly (--chunk-filer, --chunk-path), so they work while the volume is offline; - snapshot and fork generate a request id when none is given and print it on stderr for a retry; --label k=v repeats; - stdout carries the operation's JSON body (the route's, or the shared list/delete bodies, or the fork result with remoteLSN); a failure prints ": (retryable=...)" and exits 1; usage errors exit 2. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 350 +++++++++++++++++++++++ seaweed-block/cmd/sw-block/chunk_test.go | 147 ++++++++++ seaweed-block/cmd/sw-block/main.go | 8 +- 3 files changed, 504 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/cmd/sw-block/chunk.go create mode 100644 seaweed-block/cmd/sw-block/chunk_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go new file mode 100644 index 0000000000..77b3199d6e --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -0,0 +1,350 @@ +package main + +// sw-block ops chunk: the walstore-chunk control plane (B9 W2 §0.1, §3). +// cut, snapshot and detach call a blockvolume's /chunk/* routes +// (--status-addr). snapshots, snapshot-delete and fork read and write the +// filer directly (--chunk-filer, --chunk-path), so they work while the +// volume is offline. Each prints the operation's JSON body on stdout; a +// failure prints ": (retryable=...)" on stderr and exits 1. + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/ops" +) + +const ( + chunkExitFailed = 1 + defaultChunkPathCLI = "/swblock/chunks" + chunkResponseLimit = 64 << 20 +) + +// dialChunkFiler opens the filer for the direct commands; tests replace it. +var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { + c, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: addr}) + if err != nil { + return nil, nil, err + } + return c, c.Close, nil +} + +func runOpsChunk(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + fmt.Fprintln(stderr, "sw-block ops chunk: expected cut|snapshot|snapshots|snapshot-delete|fork|detach") + return ops.VolumeStatusExitInvalid + } + switch args[0] { + case "cut": + return chunkCut(args[1:], stdout, stderr) + case "snapshot": + return chunkSnapshot(args[1:], stdout, stderr) + case "detach": + return chunkDetach(args[1:], stdout, stderr) + case "snapshots": + return chunkSnapshots(args[1:], stdout, stderr) + case "snapshot-delete": + return chunkSnapshotDelete(args[1:], stdout, stderr) + case "fork": + return chunkFork(args[1:], stdout, stderr) + default: + fmt.Fprintf(stderr, "sw-block ops chunk: unknown subcommand %q\n", args[0]) + return ops.VolumeStatusExitInvalid + } +} + +// labelFlags collects repeated --label k=v. +type labelFlags map[string]string + +func (l labelFlags) String() string { return "" } + +func (l labelFlags) Set(v string) error { + k, val, ok := strings.Cut(v, "=") + if !ok || k == "" { + return fmt.Errorf("label %q: want key=value", v) + } + l[k] = val + return nil +} + +func newRequestID() string { + var b [16]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +func chunkFlagSet(name string, stderr io.Writer) *flag.FlagSet { + fs := flag.NewFlagSet("sw-block ops chunk "+name, flag.ContinueOnError) + fs.SetOutput(stderr) + return fs +} + +// chunkPost sends one /chunk/* request and relays the outcome. The server +// bounds the operation by timeoutMs; the client waits a little longer. +func chunkPost(name, statusAddr, route string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer) int { + base := statusAddr + if !strings.Contains(base, "://") { + base = "http://" + base + } + body["timeoutMs"] = timeout.Milliseconds() + data, err := json.Marshal(body) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return chunkExitFailed + } + ctx, cancel := context.WithTimeout(context.Background(), timeout+5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(base, "/")+route, bytes.NewReader(data)) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return ops.VolumeStatusExitInvalid + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return chunkExitFailed + } + defer resp.Body.Close() + out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit)) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: read response: %v\n", name, err) + return chunkExitFailed + } + if resp.StatusCode == http.StatusOK { + _, _ = stdout.Write(out) + return ops.VolumeStatusExitOK + } + var e struct { + Code string `json:"code"` + Message string `json:"message"` + Retryable bool `json:"retryable"` + } + if json.Unmarshal(out, &e) == nil && e.Code != "" { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s (retryable=%v)\n", name, e.Code, e.Message, e.Retryable) + } else { + fmt.Fprintf(stderr, "sw-block ops chunk %s: HTTP %d: %s\n", name, resp.StatusCode, strings.TrimSpace(string(out))) + } + return chunkExitFailed +} + +func chunkCut(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("cut", stderr) + var ( + volumeID, statusAddr string + minLSN uint64 + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.Uint64Var(&minLSN, "min-lsn", 0, "fail unless the cut reaches this LSN") + fs.DurationVar(&timeout, "timeout", 60*time.Second, "operation bound (capped at the server's OpDeadline)") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" || statusAddr == "" { + fmt.Fprintln(stderr, "sw-block ops chunk cut: --volume and --status-addr are required") + return ops.VolumeStatusExitInvalid + } + return chunkPost("cut", statusAddr, "/chunk/cut", timeout, map[string]any{"volumeID": volumeID, "minLSN": minLSN}, stdout, stderr) +} + +func chunkSnapshot(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("snapshot", stderr) + var ( + volumeID, statusAddr, name, requestID, consistency string + expiresAtNs int64 + timeout time.Duration + ) + labels := labelFlags{} + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.StringVar(&name, "name", "", "snapshot name") + fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)") + fs.StringVar(&consistency, "consistency", "crash", "crash, or app when the guest was frozen by the caller") + fs.Int64Var(&expiresAtNs, "expires-at-ns", 0, "stored for the retention policy; not enforced here") + fs.Var(labels, "label", "key=value label (repeatable)") + fs.DurationVar(&timeout, "timeout", 60*time.Second, "operation bound (capped at the server's OpDeadline)") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" || statusAddr == "" || name == "" { + fmt.Fprintln(stderr, "sw-block ops chunk snapshot: --volume, --status-addr and --name are required") + return ops.VolumeStatusExitInvalid + } + if requestID == "" { + requestID = newRequestID() + fmt.Fprintf(stderr, "sw-block ops chunk snapshot: request id %s (reuse it to retry)\n", requestID) + } + return chunkPost("snapshot", statusAddr, "/chunk/snapshot", timeout, map[string]any{"volumeID": volumeID, "name": name, + "requestID": requestID, "labels": map[string]string(labels), "consistency": consistency, "expiresAtNs": expiresAtNs}, stdout, stderr) +} + +func chunkDetach(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("detach", stderr) + var ( + volumeID, statusAddr string + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)") + fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" || statusAddr == "" { + fmt.Fprintln(stderr, "sw-block ops chunk detach: --volume and --status-addr are required") + return ops.VolumeStatusExitInvalid + } + return chunkPost("detach", statusAddr, "/chunk/detach", timeout, map[string]any{"volumeID": volumeID}, stdout, stderr) +} + +// chunkCatalog opens the catalog under --chunk-path on --chunk-filer. +func chunkCatalog(name, filer, base string, stderr io.Writer) (*chunkstore.Catalog, func() error, bool) { + if filer == "" { + fmt.Fprintf(stderr, "sw-block ops chunk %s: --chunk-filer is required\n", name) + return nil, nil, false + } + f, closeFn, err := dialChunkFiler(filer) + if err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return nil, nil, false + } + cat, err := chunkstore.NewCatalog(f, base) + if err != nil { + _ = closeFn() + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return nil, nil, false + } + return cat, closeFn, true +} + +// chunkResult prints v as JSON, or err as ": ". +func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int { + if err != nil { + var ce *chunkstore.CatalogError + if errors.As(err, &ce) { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %s: %s (retryable=%v)\n", name, ce.Code, err, ce.Retryable) + } else { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + } + return chunkExitFailed + } + enc := json.NewEncoder(stdout) + if err := enc.Encode(v); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) + return chunkExitFailed + } + return ops.VolumeStatusExitOK +} + +func chunkSnapshots(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("snapshots", stderr) + var ( + volumeID, filer, base, prefix, startAfter string + limit int + includeDeleting bool + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.StringVar(&prefix, "prefix", "", "only names with this prefix") + fs.StringVar(&startAfter, "start-after", "", "list after this name (the previous page's next)") + fs.IntVar(&limit, "limit", 0, "page size (0: the default)") + fs.BoolVar(&includeDeleting, "include-deleting", false, "also list snapshots marked deleting") + fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" { + fmt.Fprintln(stderr, "sw-block ops chunk snapshots: --volume is required") + return ops.VolumeStatusExitInvalid + } + cat, closeFn, ok := chunkCatalog("snapshots", filer, base, stderr) + if !ok { + return ops.VolumeStatusExitInvalid + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + list, next, err := cat.ListSnapshots(ctx, volumeID, chunkstore.ListOptions{Prefix: prefix, StartAfter: startAfter, Limit: limit, IncludeDeleting: includeDeleting}) + return chunkResult("snapshots", chunkstore.NewSnapshotListBody(volumeID, list, next), err, stdout, stderr) +} + +func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("snapshot-delete", stderr) + var ( + volumeID, filer, base, name string + timeout time.Duration + ) + fs.StringVar(&volumeID, "volume", "", "volume id") + fs.StringVar(&name, "name", "", "snapshot name") + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if volumeID == "" || name == "" { + fmt.Fprintln(stderr, "sw-block ops chunk snapshot-delete: --volume and --name are required") + return ops.VolumeStatusExitInvalid + } + cat, closeFn, ok := chunkCatalog("snapshot-delete", filer, base, stderr) + if !ok { + return ops.VolumeStatusExitInvalid + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + state, err := cat.DeleteSnapshot(ctx, volumeID, name) + return chunkResult("snapshot-delete", chunkstore.SnapshotDeleteBody{VolumeID: volumeID, Name: name, State: state}, err, stdout, stderr) +} + +func chunkFork(args []string, stdout, stderr io.Writer) int { + fs := chunkFlagSet("fork", stderr) + var ( + filer, base, source, snapshot, target, requestID string + timeout time.Duration + ) + labels := labelFlags{} + fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port") + fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume") + fs.StringVar(&source, "source", "", "source volume id") + fs.StringVar(&snapshot, "snapshot", "", "source snapshot name") + fs.StringVar(&target, "target", "", "new volume id") + fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)") + fs.Var(labels, "label", "key=value label (repeatable)") + fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout (the fork's own HEAD deadline is OpDeadline)") + if err := fs.Parse(args); err != nil { + return ops.VolumeStatusExitInvalid + } + if source == "" || snapshot == "" || target == "" { + fmt.Fprintln(stderr, "sw-block ops chunk fork: --source, --snapshot and --target are required") + return ops.VolumeStatusExitInvalid + } + if requestID == "" { + requestID = newRequestID() + fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) + } + cat, closeFn, ok := chunkCatalog("fork", filer, base, stderr) + if !ok { + return ops.VolumeStatusExitInvalid + } + defer closeFn() + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + res, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID, Labels: map[string]string(labels)}) + return chunkResult("fork", res, err, stdout, stderr) +} diff --git a/seaweed-block/cmd/sw-block/chunk_test.go b/seaweed-block/cmd/sw-block/chunk_test.go new file mode 100644 index 0000000000..bfa3f7a422 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_test.go @@ -0,0 +1,147 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type chunkRoute struct { + path string + body map[string]any +} + +// chunkServer answers every request with status and reply, recording it. +func chunkServer(t *testing.T, status int, reply string) (*httptest.Server, *[]chunkRoute) { + t.Helper() + var got []chunkRoute + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var m map[string]any + _ = json.Unmarshal(b, &m) + if r.Method != http.MethodPost { + t.Errorf("%s %s: want POST", r.Method, r.URL.Path) + } + got = append(got, chunkRoute{path: r.URL.Path, body: m}) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, reply) + })) + t.Cleanup(srv.Close) + return srv, &got +} + +func runChunk(args ...string) (int, string, string) { + var out, errb bytes.Buffer + code := run(append([]string{"ops", "chunk"}, args...), &out, &errb) + return code, out.String(), errb.String() +} + +func TestOpsChunk_HTTPCommandsSendSpecRequests(t *testing.T) { + srv, got := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) + addr := strings.TrimPrefix(srv.URL, "http://") + if code, out, errs := runChunk("cut", "--volume", "v1", "--status-addr", addr, "--min-lsn", "7", "--timeout", "2s"); code != 0 || out != `{"volumeID":"v1","cutLSN":9}` { + t.Fatalf("cut: %d %q %q", code, out, errs) + } + code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--label", "agent.step=npm-ci", "--consistency", "app") + if code != 0 || !strings.Contains(errs, "request id ") { + t.Fatalf("snapshot: %d %q (a generated request id must be printed)", code, errs) + } + if code, _, errs := runChunk("detach", "--volume", "v1", "--status-addr", addr); code != 0 { + t.Fatalf("detach: %d %q", code, errs) + } + if len(*got) != 3 { + t.Fatalf("requests: %+v", *got) + } + cut, snap, det := (*got)[0], (*got)[1], (*got)[2] + if cut.path != "/chunk/cut" || cut.body["volumeID"] != "v1" || cut.body["minLSN"] != float64(7) || cut.body["timeoutMs"] != float64(2000) { + t.Fatalf("cut request: %+v", cut) + } + labels, _ := snap.body["labels"].(map[string]any) + if snap.path != "/chunk/snapshot" || snap.body["name"] != "s1" || snap.body["consistency"] != "app" || labels["agent.step"] != "npm-ci" || + len(snap.body["requestID"].(string)) != 32 { + t.Fatalf("snapshot request: %+v", snap) + } + if det.path != "/chunk/detach" || det.body["volumeID"] != "v1" || det.body["timeoutMs"] != float64(120000) { + t.Fatalf("detach request: %+v", det) + } + var keys []string + for k := range snap.body { + keys = append(keys, k) + } + sort.Strings(keys) + if strings.Join(keys, ",") != "consistency,expiresAtNs,labels,name,requestID,timeoutMs,volumeID" { + t.Fatalf("snapshot request fields %v", keys) + } +} + +func TestOpsChunk_HTTPFailureIsTyped(t *testing.T) { + srv, _ := chunkServer(t, 409, `{"code":"not_primary","message":"volume v1 is not a healthy primary here","retryable":false}`) + code, out, errs := runChunk("cut", "--volume", "v1", "--status-addr", srv.URL) + if code != chunkExitFailed || out != "" || !strings.Contains(errs, "not_primary: volume v1 is not a healthy primary here (retryable=false)") { + t.Fatalf("refused cut: %d %q %q", code, out, errs) + } + if code, _, _ := runChunk("cut", "--volume", "v1"); code != 2 { + t.Fatalf("cut without --status-addr: exit %d, want 2", code) + } + if code, _, _ := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--label", "nokey"); code != 2 { + t.Fatalf("a label without '=': exit %d, want 2", code) + } +} + +// snapshots, snapshot-delete and fork go to the filer directly. +func TestOpsChunk_FilerCommands(t *testing.T) { + ctx := context.Background() + mem := chunkstore.NewMemFiler() + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive, + Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}} + if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil { + t.Fatal(err) + } + + code, out, errs := runChunk("snapshots", "--volume", "v1", "--chunk-filer", "filer:18888") + var list chunkstore.SnapshotListBody + if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list.Snapshots) != 1 || list.Snapshots[0].Name != "s1" || list.Snapshots[0].CutLSN != 42 { + t.Fatalf("snapshots: %d %q %q", code, out, errs) + } + code, out, errs = runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1") + var fork chunkstore.ForkResult + if code != 0 || json.Unmarshal([]byte(out), &fork) != nil || fork.Target != "v2" || fork.HeadGen != 1 || fork.RemoteLSN != 42 || fork.Replayed || + !strings.Contains(out, `"remoteLSN":42`) { + t.Fatalf("fork: %d %q %q", code, out, errs) + } + if code, out, _ := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1"); code != 0 || !strings.Contains(out, `"replayed":true`) { + t.Fatalf("fork retry: %d %q", code, out) + } + if code, _, errs := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "other"); code != chunkExitFailed || !strings.Contains(errs, "target_exists") { + t.Fatalf("fork with another request id: %d %q", code, errs) + } + for i := 0; i < 2; i++ { + code, out, errs = runChunk("snapshot-delete", "--volume", "v1", "--name", "s1", "--chunk-filer", "filer:18888") + if code != 0 || !strings.Contains(out, `"state":"deleting"`) { + t.Fatalf("snapshot-delete #%d: %d %q %q", i+1, code, out, errs) + } + } + if code, _, _ := runChunk("snapshots", "--volume", "v1"); code != 2 { + t.Fatalf("snapshots without --chunk-filer: exit %d, want 2", code) + } +} diff --git a/seaweed-block/cmd/sw-block/main.go b/seaweed-block/cmd/sw-block/main.go index eb8cbfe4c8..3119a74f35 100644 --- a/seaweed-block/cmd/sw-block/main.go +++ b/seaweed-block/cmd/sw-block/main.go @@ -83,7 +83,7 @@ func run(args []string, stdout, stderr io.Writer) int { return ops.VolumeStatusExitInvalid } if len(args) < 2 { - fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor") + fmt.Fprintln(stderr, "sw-block: expected subcommand ops status|inventory|list|cluster|volumes|describe|timeline|explain|report|dashboard|generate-helm-values|operator-status|lifecycle-owner|authority-executor|rebuild-target-owner|failback-target-owner|failback-executor|frontend-publication-target-owner|frontend-publication-executor|chunk") usage(stderr) return ops.VolumeStatusExitInvalid } @@ -124,6 +124,8 @@ func run(args []string, stdout, stderr io.Writer) int { return runOpsFrontendPublicationTargetOwner(args[2:], stdout, stderr) case "frontend-publication-executor": return runOpsFrontendPublicationExecutor(args[2:], stdout, stderr) + case "chunk": + return runOpsChunk(args[2:], stdout, stderr) default: fmt.Fprintf(stderr, "sw-block: unknown ops subcommand %q\n", args[1]) usage(stderr) @@ -2285,6 +2287,10 @@ func usage(w io.Writer) { fmt.Fprintln(w, " sw-block ops failback-executor [--dry-run] [--namespace ] [--enable-execution] [--execution-policy] [--failback-runtime-url ] [--interval 30s]") fmt.Fprintln(w, " sw-block ops frontend-publication-target-owner [--dry-run] [--namespace ] [--interval 30s] [--activate-targets --activation-policy --runtime-endpoint ]") fmt.Fprintln(w, " sw-block ops frontend-publication-executor [--dry-run] [--namespace ] [--enable-execution] [--execution-policy] [--frontend-publication-runtime-url ] [--interval 30s]") + fmt.Fprintln(w, " sw-block ops chunk cut|detach --volume --status-addr [--min-lsn ] [--timeout ]") + fmt.Fprintln(w, " sw-block ops chunk snapshot --volume --status-addr --name [--label k=v]... [--request-id ] [--consistency crash|app]") + fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume [--name ] --chunk-filer [--chunk-path /swblock/chunks]") + fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer [--chunk-path /swblock/chunks] --source --snapshot --target [--request-id ] [--label k=v]...") } func emptyCLI(value string) string { From 95b6b7d62e58e011997590f7b8c7d305e4fc53b6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 05:51:12 -0800 Subject: [PATCH 3/3] sw-block: ops chunk never exits 0 with its result lost An HTTP response over the 64 MiB limit is refused (read limit+1) instead of being relayed truncated, and every result write checks for a failed or short write, for the route commands and the filer commands alike. There is no retry of the operation: the error says the result was not relayed. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 31 ++++++- .../cmd/sw-block/chunk_output_test.go | 87 +++++++++++++++++++ 2 files changed, 114 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_output_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 77b3199d6e..006565b217 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -117,13 +117,22 @@ func chunkPost(name, statusAddr, route string, timeout time.Duration, body map[s return chunkExitFailed } defer resp.Body.Close() - out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit)) + out, err := io.ReadAll(io.LimitReader(resp.Body, chunkResponseLimit+1)) if err != nil { fmt.Fprintf(stderr, "sw-block ops chunk %s: read response: %v\n", name, err) return chunkExitFailed } + if int64(len(out)) > chunkResponseLimit { + // Refuse rather than relay a truncated body; the operation may have + // happened, and its result is what would be lost. + fmt.Fprintf(stderr, "sw-block ops chunk %s: HTTP %d response exceeds %d bytes; not relaying a truncated body\n", name, resp.StatusCode, chunkResponseLimit) + return chunkExitFailed + } if resp.StatusCode == http.StatusOK { - _, _ = stdout.Write(out) + if err := writeAll(stdout, out); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err) + return chunkExitFailed + } return ops.VolumeStatusExitOK } var e struct { @@ -241,14 +250,28 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int { } return chunkExitFailed } - enc := json.NewEncoder(stdout) - if err := enc.Encode(v); err != nil { + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(v); err != nil { fmt.Fprintf(stderr, "sw-block ops chunk %s: %v\n", name, err) return chunkExitFailed } + if err := writeAll(stdout, buf.Bytes()); err != nil { + fmt.Fprintf(stderr, "sw-block ops chunk %s: write the result: %v\n", name, err) + return chunkExitFailed + } return ops.VolumeStatusExitOK } +// writeAll writes p and fails on a failed or short write: a lost result +// must not exit 0. +func writeAll(w io.Writer, p []byte) error { + n, err := w.Write(p) + if err == nil && n != len(p) { + err = io.ErrShortWrite + } + return err +} + func chunkSnapshots(args []string, stdout, stderr io.Writer) int { fs := chunkFlagSet("snapshots", stderr) var ( diff --git a/seaweed-block/cmd/sw-block/chunk_output_test.go b/seaweed-block/cmd/sw-block/chunk_output_test.go new file mode 100644 index 0000000000..846a4c59a6 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_output_test.go @@ -0,0 +1,87 @@ +package main + +// The CLI never exits 0 with its result lost (review of #116): an HTTP body +// over the limit is refused rather than truncated, and a failed or short +// write of the result fails the command. + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +type failWriter struct{} + +func (failWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") } + +type shortWriter struct{} + +func (shortWriter) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + return len(p) - 1, nil +} + +func sizedServer(t *testing.T, n int) *httptest.Server { + t.Helper() + body := bytes.Repeat([]byte("a"), n) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestOpsChunk_OversizedResponseIsRefused(t *testing.T) { + var out, errb bytes.Buffer + code := run([]string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", sizedServer(t, chunkResponseLimit+1).URL}, &out, &errb) + if code != chunkExitFailed || out.Len() != 0 || !strings.Contains(errb.String(), "exceeds") { + t.Fatalf("200 body one byte over the limit: exit %d, %d bytes relayed, stderr %q; want a refusal and nothing relayed", code, out.Len(), errb.String()) + } + out.Reset() + errb.Reset() + if code := run([]string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", sizedServer(t, chunkResponseLimit).URL}, &out, &errb); code != 0 || out.Len() != chunkResponseLimit { + t.Fatalf("200 body at the limit: exit %d, %d bytes relayed, stderr %q; want it relayed whole", code, out.Len(), errb.String()) + } +} + +func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) { + srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`) + mem := chunkstore.NewMemFiler() + prev := dialChunkFiler + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + t.Cleanup(func() { dialChunkFiler = prev }) + cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI) + if err != nil { + t.Fatal(err) + } + if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { + t.Fatal(err) + } + commands := map[string][]string{ + "cut (HTTP)": {"ops", "chunk", "cut", "--volume", "v1", "--status-addr", srv.URL}, + "snapshots (filer)": {"ops", "chunk", "snapshots", "--volume", "v1", "--chunk-filer", "filer:18888"}, + } + for name, args := range commands { + for wname, w := range map[string]io.Writer{"failing": failWriter{}, "short": shortWriter{}} { + var errb bytes.Buffer + if code := run(args, w, &errb); code != chunkExitFailed || !strings.Contains(errb.String(), "write the result") { + t.Errorf("%s to a %s stdout: exit %d, stderr %q; want a failure", name, wname, code, errb.String()) + } + } + var out, errb bytes.Buffer + if code := run(args, &out, &errb); code != 0 || out.Len() == 0 { + t.Errorf("%s to a working stdout: exit %d, %q, stderr %q", name, code, out.String(), errb.String()) + } + } +}