From f67517f2e47f7ec9ac7a8d08cd4853e7f57b57f0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:09:12 -0800 Subject: [PATCH] fix: refuse volume creation above the uint32 LBA capacity limit --- seaweed-block/core/csi/controller.go | 4 +++ .../core/frontend/chunkstore/catalog.go | 26 ++++++++------- seaweed-block/core/geometry/volume_size.go | 16 ++++++++++ seaweed-block/core/lifecycle/store.go | 4 +++ seaweed-block/core/storage/walstore.go | 32 +++++++++++-------- 5 files changed, 57 insertions(+), 25 deletions(-) create mode 100644 seaweed-block/core/geometry/volume_size.go diff --git a/seaweed-block/core/csi/controller.go b/seaweed-block/core/csi/controller.go index c4471f4bd9..c3032079c9 100644 --- a/seaweed-block/core/csi/controller.go +++ b/seaweed-block/core/csi/controller.go @@ -3,6 +3,7 @@ package csi import ( "context" "errors" + "github.com/seaweedfs/seaweed-block/core/geometry" "log" "strconv" "time" @@ -248,6 +249,9 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er if size <= 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "capacity is required") } + if err := geometry.ValidateVolumeSize(uint64(size)); err != nil { + return VolumeSpec{}, status.Error(codes.InvalidArgument, err.Error()) + } if len(req.GetVolumeCapabilities()) == 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "volume capabilities are required") } diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 1e1889e3d0..f6a634a16c 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1,7 +1,7 @@ package chunkstore // Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec -// §3-§5). Under the chunk base directory, per volume: +// §3-§5). Under the chunk base directory, per volume: // // //HEAD the published HEAD (ChunkRemote) // //keys/ chunk key bindings (ChunkRemote) @@ -15,7 +15,7 @@ package chunkstore // // Snapshot and fork are read-then-write. Each writes an intent naming the // keys it references before its final manifest write, and refuses that -// write once OpDeadline has passed since it read its source (spec §2.3). +// write once OpDeadline has passed since it read its source (spec §2.3). // The operation's intents are removed only once its outcome is settled: the // manifest is confirmed published (re-read shows it), or the attempt // cleanly aborted (it never sent the write, or another entry already holds @@ -30,6 +30,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "path" "strconv" "strings" @@ -74,7 +75,7 @@ const ( OriginFork = "fork" // DefaultOpDeadline bounds a snapshot or fork from reading its source to - // its final write (spec §2.3). + // its final write (spec §2.3). DefaultOpDeadline = 5 * time.Minute defaultListLimit = 100 @@ -85,7 +86,7 @@ const ( maxSnapName = 128 ) -// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI +// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI // report them. const ( CodeNotChunkVolume = "not_chunk_volume" @@ -160,7 +161,7 @@ type Parent struct { Gen uint64 `json:"gen"` } -// VolumeInfo is the VOLUME entry (spec §4.2). +// VolumeInfo is the VOLUME entry (spec §4.2). type VolumeInfo struct { Format int `json:"format"` VolumeID string `json:"volume_id"` @@ -207,7 +208,7 @@ type snapDoc struct { } // SnapshotInfo describes one snapshot, with the field names of the HTTP API -// (spec §3.2-§3.3). +// (spec §3.2-§3.3). type SnapshotInfo struct { VolumeID string `json:"volumeID"` Name string `json:"name"` @@ -268,7 +269,7 @@ type ForkRequest struct { } // ForkResult reports a fork, with the field names of the CLI output -// (spec §3.5). +// (spec §3.5). type ForkResult struct { Target string `json:"target"` Source string `json:"source"` @@ -325,7 +326,7 @@ func (c *Catalog) volRoot(vol string) (string, error) { return path.Join(c.base, vol), nil } -// CheckSnapshotName enforces the snapshot name rule (spec §4.4). +// CheckSnapshotName enforces the snapshot name rule (spec §4.4). func CheckSnapshotName(name string) error { if name == "" || len(name) > maxSnapName || strings.HasPrefix(name, ".") { return catErr(CodeInvalidName, false, nil, "snapshot name %q: 1-%d characters, not starting with '.'", name, maxSnapName) @@ -473,7 +474,7 @@ func (c *Catalog) ReadHead(ctx context.Context, vol string) (storage.ChunkHead, return h, true, nil } -// EnsureVolume applies the attach rules of spec §4.2 for a volume served +// EnsureVolume applies the attach rules of spec §4.2 for a volume served // with geometry g: it creates a missing VOLUME entry (origin create), and // refuses with geometry_mismatch when VOLUME disagrees with g, or with // fork_incomplete when VOLUME is a fork whose HEAD is not written yet. @@ -487,6 +488,9 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } if !ok { + if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) { + return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) + } v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()} e, err := volumeEntry(v, "") if err != nil { @@ -965,7 +969,7 @@ func (c *Catalog) claimName(ctx context.Context, vol, root string, req SnapshotR } // SnapshotReplay resolves a snapshot request against the catalog before -// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's +// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's // request and its attempt published, it returns that snapshot (Replayed, // true); held by another request, snapshot_exists; free, or held by req's // unpublished attempt, (zero, false, nil). It validates the whole request @@ -1049,7 +1053,7 @@ func (c *Catalog) ListSnapshots(ctx context.Context, vol string, opts ListOption } } -// DeleteSnapshot frees the name (spec §3.4, W5): +// DeleteSnapshot frees the name (spec §3.4, W5): // it marks the attempt deleting (or, when the attempt never published, // claims its path with an aborted tombstone so a late insert cannot land), // then removes the name record. The attempt path is never removed. It diff --git a/seaweed-block/core/geometry/volume_size.go b/seaweed-block/core/geometry/volume_size.go new file mode 100644 index 0000000000..0d317ede02 --- /dev/null +++ b/seaweed-block/core/geometry/volume_size.go @@ -0,0 +1,16 @@ +// Package geometry defines shared volume capacity limits at creation boundaries. +package geometry + +import "fmt" + +// MaxVolumeBytes is the uint32-LBA limit with the supported 4-KiB IO unit. +const MaxVolumeBytes uint64 = (16 << 40) - 4096 + +// ValidateVolumeSize rejects an unsupported capacity before any allocation or +// durable create. Division also makes block geometry checks overflow-safe. +func ValidateVolumeSize(size uint64) error { + if size > MaxVolumeBytes { + return fmt.Errorf("volume size %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", size, MaxVolumeBytes) + } + return nil +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 68b7243cb4..e1c5ab62e9 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "regexp" @@ -106,6 +107,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { if err := validateSpec(spec); err != nil { return VolumeRecord{}, err } + if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { + return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) + } s.mu.Lock() defer s.mu.Unlock() if existing, ok := s.records[spec.VolumeID]; ok { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index c148ce5f1f..9c1c737229 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -3,6 +3,7 @@ package storage import ( "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "sync" @@ -63,7 +64,7 @@ type WALStore struct { syncDirectFrontierMetadata func([]byte) error writeSuperblockMetadata func([]byte) error syncSuperblockMetadata func() error - flusher *flusher // background WAL→extent applier; nil if disabled + flusher *flusher // background WAL→extent applier; nil if disabled admission *walAdmission // backpressure on WAL pressure; nil if disabled // admissionTimeout is the per-Write deadline for admission. If @@ -118,7 +119,7 @@ type WALStore struct { // as fromLSN > checkpointLSN - recoveryRetentionLSNs. Zero means // strict checkpoint-driven recycle. Operator sets via // blockvolume's --wal-retention-lsns flag at store construction. - // Stored in-memory only — NOT persisted to the superblock; on + // Stored in-memory only — NOT persisted to the superblock; on // restart the daemon re-applies the flag. // // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. @@ -131,7 +132,7 @@ type WALStore struct { // --recovery-mode=dual-lane. // // nil = no gate (legacy behavior). Per docs/recovery-wiring-plan.md - // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. + // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. recycleFloorSrc RecycleFloorSource syncs atomic.Uint64 // completed logical Sync calls (test/diagnostic) @@ -191,6 +192,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt if blockSize < 0 || uint64(blockSize) > uint64(^uint32(0)) { return nil, errSuperblockBadVolume } + if err := geometry.ValidateVolumeSize(uint64(numBlocks) * uint64(blockSize)); err != nil { + return nil, err + } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return nil, err } @@ -370,7 +374,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B } s.syncSuperblockMetadata = f.Sync - // Background flusher: drains dirty map → extent, advances + // Background flusher: drains dirty map → extent, advances // checkpoint, allows WAL recycling. Defaults are conservative // for the demo workload; tunable via config in future. s.flusher = newFlusher(s, flusherConfig{}) @@ -383,7 +387,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B // returning ErrWALFull to callers under transient load. // Watermarks 0.7/0.9 match V2 config.go defaults // (WALSoftWatermark, WALHardWatermark). Admission wakes the - // flusher via NotifyUrgent — same seam V2 wires for pressure- + // flusher via NotifyUrgent — same seam V2 wires for pressure- // driven flushes. s.admissionTimeout = 30 * time.Second s.admission = newWALAdmission(walAdmissionConfig{ @@ -762,7 +766,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // WAL admission: throttle/block under WAL pressure. If admission // is disabled (admission==nil), Write proceeds immediately. The - // admission Acquire may block up to admissionTimeout — under + // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. s.beforeChunkMutation(uint64(lba), 1) s.lifecycleMu.RLock() @@ -1231,7 +1235,7 @@ func (s *WALStore) Sync() (uint64, error) { return frontier, nil } -// Boundaries returns the current R/S/H boundaries — what is durable, +// Boundaries returns the current R/S/H boundaries — what is durable, // what the WAL still retains, what's the newest write. func (s *WALStore) Boundaries() (R, S, H uint64) { s.mu.RLock() @@ -1269,7 +1273,7 @@ func (s *WALStore) BlockSize() int { return int(s.sb.BlockSize) } // persistCheckpoint to clamp checkpoint advancement against active // recover-session pin floors. Pass nil to disable. // -// Idempotent. Safe to call at any time — the gate is read under +// Idempotent. Safe to call at any time — the gate is read under // s.mu so concurrent persistCheckpoint sees a consistent value. // // Implements storage.RecycleFloorGate. @@ -1336,8 +1340,8 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { } // WriteExtentDirect installs a base block directly into the extent -// without going through the WAL append path — INV-RECV-BITMAP-CORE -// (§6.10). The receiver's per-session bitmap is the sole arbiter of +// without going through the WAL append path — INV-RECV-BITMAP-CORE +// (§6.10). The receiver's per-session bitmap is the sole arbiter of // BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / // stale-skip is intentionally bypassed. // @@ -1478,16 +1482,16 @@ func (s *WALStore) RecoveryMode() RecoveryMode { // AppliedLSNs returns a partial view of per-LBA applied LSN: only // LBAs whose latest write is still in the WAL (not yet flushed to // extent) are reported. Once an entry is flushed and the dirty-map -// entry is cleared, walstore loses per-LBA LSN tracking — the +// entry is cleared, walstore loses per-LBA LSN tracking — the // extent stores data only, not per-LBA LSN. // // PARTIAL-VIEW LIMITATION: for full per-LBA applied-LSN tracking, // walstore would need a permanent per-LBA LSN map (substrate // refactor). The replica recovery apply gate is the authoritative -// correctness boundary; this partial seed is defense-in-depth — +// correctness boundary; this partial seed is defense-in-depth — // it correctly stale-skips recovery entries for LBAs still in the // WAL window, and falls back to "appliedLSN[LBA] = 0" semantics -// for flushed LBAs (which means recovery WILL apply them — +// for flushed LBAs (which means recovery WILL apply them — // acceptable when the gate's session-only tracking + live-lane // updates fill in the gap during the session). // @@ -1512,7 +1516,7 @@ func (s *WALStore) AppliedLSNs() (map[uint32]uint64, error) { // content is non-zero. // // This honors the LogicalStorage contract: "snapshots every -// written LBA's current bytes" — including LBAs whose data has +// written LBA's current bytes" — including LBAs whose data has // been flushed out of the dirty map into the extent. Filtering // zeros preserves the "snapshot of dirty bits" semantics callers // expect (a never-written LBA shouldn't appear in the output;