diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 7542300741..c7a59d76b4 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -53,8 +53,16 @@ const ( // ImplParallelWALStore is the explicit Phase 167 candidate. It remains // opt-in until the full recovery, replication, and mounted close gates pass. ImplParallelWALStore ImplName = "parallel-walstore" + // ImplWALStoreChunk is a walstore volume with an attached chunk layer: + // an asynchronous remote copy of immutable chunks published by a HEAD + // compare-and-swap. On disk it is a walstore file. Requires + // ProviderConfig.ChunkRemoteFor. Opt-in proof of concept. + ImplWALStoreChunk ImplName = "walstore-chunk" ) +// defaultChunkBlocks is 4 MiB chunks of 4 KiB blocks. +const defaultChunkBlocks = 1024 + // ErrImplKindMismatch is returned by Open when the configured // selector does not match the on-disk superblock magic. Named so // tests can errors.Is on it. @@ -112,6 +120,21 @@ type ProviderConfig struct { // that need synced-but-uncheckpointed WAL records to survive a process // restart and prove real replay. Default false. WALRecoveryTestDisableFlusher bool + + // ChunkRemoteFor returns the remote that holds volumeID's chunks and + // HEAD. Required for ImplWALStoreChunk, ignored otherwise. + ChunkRemoteFor func(volumeID string) (storage.ChunkRemote, error) + // ChunkBlocks is the number of blocks per chunk. Zero: 1024. + ChunkBlocks uint32 + // ChunkHolder names this node in HEAD. Zero: the replica ID. + ChunkHolder string + // ChunkReadMissTimeout bounds one remote fetch of an absent block. + // Zero: the storage default. + ChunkReadMissTimeout time.Duration + // ChunkCaptureInterval runs a cut every interval while the volume's + // projection is healthy. Zero: cuts only on CaptureVolume and + // MakeVolumeRemoteDurable. + ChunkCaptureInterval time.Duration } // DurableProvider is the production frontend.Provider implementation. @@ -129,6 +152,11 @@ type volHandle struct { storage storage.LogicalStorage backend *StorageBackend path string + created bool // created by this provider (a fresh local volume) + + chunk storage.ChunkLayer // ImplWALStoreChunk, after RecoverVolume + chunkStop context.CancelFunc + chunkDone chan struct{} } // VolumeStatus is a read-only diagnostic snapshot of one durable volume @@ -162,9 +190,15 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.Impl == "" { cfg.Impl = ImplSmartWAL } - if cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore && cfg.Impl != ImplParallelWALStore { - return nil, fmt.Errorf("durable: unknown impl %q (want %q, %q, or %q)", - cfg.Impl, ImplSmartWAL, ImplWALStore, ImplParallelWALStore) + if cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore && cfg.Impl != ImplParallelWALStore && cfg.Impl != ImplWALStoreChunk { + return nil, fmt.Errorf("durable: unknown impl %q (want %q, %q, %q, or %q)", + cfg.Impl, ImplSmartWAL, ImplWALStore, ImplParallelWALStore, ImplWALStoreChunk) + } + if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil { + return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk) + } + if cfg.ChunkBlocks == 0 { + cfg.ChunkBlocks = defaultChunkBlocks } if cfg.BlockSize == 0 { cfg.BlockSize = 4096 @@ -469,6 +503,9 @@ func (p *DurableProvider) verifyImplOnDisk(path string) error { return fmt.Errorf("%w: unrecognized magic %q at %s", ErrImplKindMismatch, string(magic), path) } + if diskImpl == ImplWALStore && p.cfg.Impl == ImplWALStoreChunk { + return nil // a chunk volume is a walstore file + } if diskImpl != p.cfg.Impl { return fmt.Errorf("%w: selector=%s on-disk=%s at %s", ErrImplKindMismatch, p.cfg.Impl, diskImpl, path) @@ -496,7 +533,7 @@ func magicToImpl(magic string) (ImplName, bool) { func (p *DurableProvider) openExisting(volumeID, path string) (*volHandle, error) { var s storage.LogicalStorage switch p.cfg.Impl { - case ImplWALStore: + case ImplWALStore, ImplWALStoreChunk: ws, err := storage.OpenWALStore(path) if err != nil { return nil, fmt.Errorf("durable: OpenWALStore %s: %w", path, err) @@ -542,7 +579,7 @@ func (p *DurableProvider) createFresh(volumeID, path string) (*volHandle, error) } var s storage.LogicalStorage switch p.cfg.Impl { - case ImplWALStore: + case ImplWALStore, ImplWALStoreChunk: ws, err := storage.CreateWALStore(path, p.cfg.NumBlocks, p.cfg.BlockSize) if err != nil { return nil, fmt.Errorf("durable: CreateWALStore %s: %w", path, err) @@ -573,7 +610,12 @@ func (p *DurableProvider) createFresh(volumeID, path string) (*volHandle, error) default: return nil, fmt.Errorf("durable: unknown impl %q", p.cfg.Impl) } - return p.wrap(volumeID, path, s) + h, err := p.wrap(volumeID, path, s) + if err != nil { + return nil, err + } + h.created = true + return h, nil } // wrap builds a StorageBackend around an opened LogicalStorage @@ -613,6 +655,13 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R h.backend.SetOperational(false, report.Evidence) return report, report.Err } + if p.cfg.Impl == ImplWALStoreChunk { + if err := p.attachChunk(volumeID, h); err != nil { + h.backend.SetOperational(false, "chunk layer attach failed: "+err.Error()) + report.Err = err + return report, err + } + } h.backend.SetOperational(true, report.Evidence) return report, nil } @@ -633,6 +682,7 @@ func (p *DurableProvider) Close() error { var firstErr error for _, h := range handles { + p.stopChunkLoop(h) _ = h.backend.Close() if err := h.storage.Close(); err != nil && firstErr == nil { firstErr = fmt.Errorf("durable: close storage: %w", err) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go new file mode 100644 index 0000000000..9747c24cbb --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -0,0 +1,136 @@ +package durable + +// walstore-chunk: attaching the storage chunk layer to a provider volume. + +import ( + "context" + "errors" + "fmt" + "log" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ErrNotChunkVolume is returned by the chunk operations for a volume that +// has no attached chunk layer (another impl, or not recovered yet). +var ErrNotChunkVolume = errors.New("durable: volume has no chunk layer") + +// attachChunk attaches the chunk layer after a successful Recover. A volume +// this provider created starts from the remote HEAD (fresh host); an +// existing local volume stays authoritative. The manifest epoch is the +// master-assigned epoch from the projection, held by the layer separately +// from the frontend Identity. +func (p *DurableProvider) attachChunk(volumeID string, h *volHandle) error { + p.mu.Lock() + attached := h.chunk != nil + p.mu.Unlock() + if attached { + return nil + } + ws, ok := h.storage.(*storage.WALStore) + if !ok { + return fmt.Errorf("durable: %s storage is %T, not a walstore", ImplWALStoreChunk, h.storage) + } + remote, err := p.cfg.ChunkRemoteFor(volumeID) + if err != nil { + return fmt.Errorf("durable: chunk remote for %s: %w", volumeID, err) + } + proj := p.view.Projection() + holder := p.cfg.ChunkHolder + if holder == "" { + holder = proj.ReplicaID + } + layer, err := storage.AttachChunkLayer(ws, remote, storage.ChunkLayerConfig{ + ChunkBlocks: p.cfg.ChunkBlocks, + Epoch: proj.Epoch, + Holder: holder, + FreshFromHead: h.created, + ReadMissTimeout: p.cfg.ChunkReadMissTimeout, + Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"), + CaptureAllowed: func() error { + cur := p.view.Projection() + if cur.VolumeID != volumeID || !cur.Healthy { + return fmt.Errorf("volume %s is not a healthy primary here", volumeID) + } + return nil + }, + }) + if err != nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + h.chunk = layer + if p.cfg.ChunkCaptureInterval > 0 && !p.closed { + ctx, cancel := context.WithCancel(context.Background()) + h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + go p.chunkLoop(ctx, volumeID, layer, h.chunkDone) + } + return nil +} + +// chunkLoop takes a periodic cut. A refused cut (not a healthy primary, +// BASE install) is normal and skipped quietly. +func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}) { + defer close(done) + t := time.NewTicker(p.cfg.ChunkCaptureInterval) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + if _, err := layer.Capture(ctx); err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { + log.Printf("durable: chunk cut for volume=%s: %v", volumeID, err) + } + } +} + +func (p *DurableProvider) stopChunkLoop(h *volHandle) { + p.mu.Lock() + stop, done := h.chunkStop, h.chunkDone + h.chunkStop = nil + p.mu.Unlock() + if stop != nil { + stop() + <-done + } +} + +func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) { + p.mu.Lock() + h, ok := p.volumes[volumeID] + p.mu.Unlock() + if !ok { + return nil, ErrVolumeNotOpen + } + p.mu.Lock() + layer := h.chunk + p.mu.Unlock() + if layer == nil { + return nil, ErrNotChunkVolume + } + return layer, nil +} + +// CaptureVolume takes one quiesced cut of volumeID and publishes it to the +// remote. It returns the cut's LSN. +func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (uint64, error) { + layer, err := p.chunkLayer(volumeID) + if err != nil { + return 0, err + } + return layer.Capture(ctx) +} + +// MakeVolumeRemoteDurable returns nil only once volumeID's writes up to lsn +// are published in the remote HEAD (snapshot, detach, migrate). +func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID string, lsn uint64) error { + layer, err := p.chunkLayer(volumeID) + if err != nil { + return err + } + return layer.MakeRemoteDurable(ctx, lsn) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_test.go b/seaweed-block/core/frontend/durable/provider_chunk_test.go new file mode 100644 index 0000000000..f3e3f3f9d5 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_test.go @@ -0,0 +1,230 @@ +package durable_test + +// walstore-chunk provider wiring, against the storage package's in-memory +// remote. The chunk layer's own contract (C1-C11) is tested in +// core/storage; these tests cover the provider: selection, attach after +// recovery, fresh host vs existing volume, the capture gate and lifetime. + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + pcBlocks = 256 + pcChunkBlocks = 16 +) + +func chunkProvider(t *testing.T, root string, remote *storage.MemChunkRemote, view *stubView, interval time.Duration) *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: root, + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + ChunkCaptureInterval: interval, + ChunkRemoteFor: func(volumeID string) (storage.ChunkRemote, error) { + return remote, nil + }, + }, view) + if err != nil { + t.Fatalf("NewDurableProvider: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func openRecovered(t *testing.T, p *durable.DurableProvider) storage.LogicalStorage { + t.Helper() + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatalf("EnsureStorage: %v", err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatalf("RecoverVolume: %v", err) + } + return s +} + +func block(fill byte) []byte { return bytes.Repeat([]byte{fill}, 4096) } + +func headBlock(t *testing.T, remote *storage.MemChunkRemote, lba uint32) []byte { + t.Helper() + head, err := remote.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + ref, ok := head.Chunks[uint64(lba/pcChunkBlocks)] + if !ok { + return make([]byte, 4096) + } + b, err := remote.Get(context.Background(), ref.Key) + if err != nil { + t.Fatal(err) + } + off := int(lba%pcChunkBlocks) * 4096 + return b[off : off+4096] +} + +func v1View() *stubView { + return newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1})) +} + +func TestWALStoreChunk_RequiresRemote(t *testing.T) { + _, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, + }, v1View()) + if err == nil { + t.Fatal("walstore-chunk without ChunkRemoteFor was accepted") + } +} + +// Capture publishes the volume; after a provider restart over the same +// local root, the volume is still authoritative and the next cut is +// incremental. +func TestWALStoreChunk_CaptureAndRestart(t *testing.T) { + root := t.TempDir() + remote := storage.NewMemChunkRemote() + view := v1View() + p := chunkProvider(t, root, remote, view, 0) + s := openRecovered(t, p) + for lba := uint32(0); lba < 40; lba += 8 { // chunks 0, 0, 1, 1, 2 + if _, err := s.Write(lba, block(byte(lba+1))); err != nil { + t.Fatal(err) + } + } + h, err := p.CaptureVolume(context.Background(), "v1") + if err != nil { + t.Fatalf("CaptureVolume: %v", err) + } + head, _ := remote.GetHead(context.Background()) + if head.RemoteLSN != h || head.Epoch != 3 || head.Holder != "r1" || len(head.Chunks) != 3 { + t.Fatalf("HEAD after capture: remote_lsn %d (want %d) epoch %d holder %q chunks %d", head.RemoteLSN, h, head.Epoch, head.Holder, len(head.Chunks)) + } + for lba := uint32(0); lba < 40; lba += 8 { + if !bytes.Equal(headBlock(t, remote, lba), block(byte(lba+1))) { + t.Fatalf("HEAD LBA %d differs", lba) + } + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + + p2 := chunkProvider(t, root, remote, view, 0) + s2 := openRecovered(t, p2) + if got, _ := s2.Read(16); !bytes.Equal(got, block(17)) { + t.Fatal("restarted volume lost local data") + } + if _, err := s2.Write(100, block(0xAB)); err != nil { // chunk 6 + t.Fatal(err) + } + before := remote.Puts() + if _, err := p2.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatalf("CaptureVolume after restart: %v", err) + } + if n := remote.Puts() - before; n != 1 { + t.Fatalf("cut after restart stored %d chunks, want 1 (incremental)", n) + } + if !bytes.Equal(headBlock(t, remote, 100), block(0xAB)) { + t.Fatal("HEAD lacks the post-restart write") + } +} + +// A provider that creates the volume (a new host) starts from the remote +// HEAD and reads lazily. +func TestWALStoreChunk_FreshHostReadsFromHead(t *testing.T) { + remote := storage.NewMemChunkRemote() + view := v1View() + p := chunkProvider(t, t.TempDir(), remote, view, 0) + s := openRecovered(t, p) + if _, err := s.Write(33, block(0x33)); err != nil { + t.Fatal(err) + } + if err := p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatalf("MakeVolumeRemoteDurable: %v", err) + } + fresh := chunkProvider(t, t.TempDir(), remote, view, 0) // empty local root + s2 := openRecovered(t, fresh) + if got, err := s2.Read(33); err != nil || !bytes.Equal(got, block(0x33)) { + t.Fatalf("fresh host read: %v", err) + } +} + +func TestWALStoreChunk_CaptureNeedsHealthyProjection(t *testing.T) { + remote := storage.NewMemChunkRemote() + view := v1View() + p := chunkProvider(t, t.TempDir(), remote, view, 0) + s := openRecovered(t, p) + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + proj := view.Projection() + proj.Healthy = false + view.set(proj) + if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkCaptureRefused) { + t.Fatalf("capture with an unhealthy projection: got %v, want refused", err) + } + if remote.Puts() != 0 { + t.Fatal("a refused capture stored chunks") + } +} + +func TestWALStoreChunk_PeriodicCut(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := chunkProvider(t, t.TempDir(), remote, v1View(), 20*time.Millisecond) + s := openRecovered(t, p) + lsn, err := s.Write(50, block(0x50)) + if err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + head, _ := remote.GetHead(context.Background()) + if head.RemoteLSN >= lsn { + break + } + if time.Now().After(deadline) { + t.Fatalf("periodic cut never published LSN %d (HEAD remote_lsn %d)", lsn, head.RemoteLSN) + } + time.Sleep(10 * time.Millisecond) + } + if !bytes.Equal(headBlock(t, remote, 50), block(0x50)) { + t.Fatal("periodic cut published the wrong bytes") + } +} + +func TestWALStoreChunk_SelectorRules(t *testing.T) { + view := v1View() + // A non-chunk volume has no chunk operations. + plain, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), NumBlocks: pcBlocks}, view) + if err != nil { + t.Fatal(err) + } + defer plain.Close() + openRecovered(t, plain) + if _, err := plain.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrNotChunkVolume) { + t.Fatalf("CaptureVolume on a plain walstore volume: got %v", err) + } + // A smartwal file is not a chunk volume. + root := t.TempDir() + sw, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: root, NumBlocks: pcBlocks}, view) + if err != nil { + t.Fatal(err) + } + if _, err := sw.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + _ = sw.Close() + p := chunkProvider(t, root, storage.NewMemChunkRemote(), view, 0) + if _, err := p.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) { + t.Fatalf("walstore-chunk over a smartwal file: got %v, want ErrImplKindMismatch", err) + } +} diff --git a/seaweed-block/core/storage/chunk_bitmap_file.go b/seaweed-block/core/storage/chunk_bitmap_file.go new file mode 100644 index 0000000000..e7d78dc3dd --- /dev/null +++ b/seaweed-block/core/storage/chunk_bitmap_file.go @@ -0,0 +1,177 @@ +package storage + +// FileChunkBitmapStore is the production chunkBitmapStore: one state file +// (header + dirty-since-HEAD chunks, with a SHA-256 over its body) replaced +// atomically on every change, plus an append-only delta log with one JSON +// record per closed HEAD period. Every method is durable on return. + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sync" +) + +type FileChunkBitmapStore struct { + path string + + mu sync.Mutex + loaded bool + stored bool + hdr chunkBitmapHeader + dirty []uint64 +} + +// NewFileChunkBitmapStore returns a store at path (the delta log is +// path + ".deltas"). +func NewFileChunkBitmapStore(path string) *FileChunkBitmapStore { + return &FileChunkBitmapStore{path: path} +} + +type chunkBitmapFile struct { + Version int `json:"version"` + Header chunkBitmapHeader `json:"header"` + Dirty []uint64 `json:"dirty"` +} + +type chunkBitmapEnvelope struct { + Body json.RawMessage `json:"body"` + SHA256 string `json:"sha256"` +} + +func (b *FileChunkBitmapStore) loadLocked() error { + if b.loaded { + return nil + } + b.loaded = true + raw, err := os.ReadFile(b.path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("storage: chunk bitmap read: %w", err) + } + var env chunkBitmapEnvelope + if json.Unmarshal(raw, &env) != nil { + return nil // corrupt: treated as lost (hash-compare fallback) + } + sum := sha256.Sum256(env.Body) + if hex.EncodeToString(sum[:]) != env.SHA256 { + return nil + } + var f chunkBitmapFile + if json.Unmarshal(env.Body, &f) != nil || f.Version != 1 { + return nil + } + b.stored, b.hdr, b.dirty = true, f.Header, f.Dirty + return nil +} + +func (b *FileChunkBitmapStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64) error { + body, err := json.Marshal(chunkBitmapFile{Version: 1, Header: hdr, Dirty: dirty}) + if err != nil { + return err + } + sum := sha256.Sum256(body) + raw, err := json.Marshal(chunkBitmapEnvelope{Body: body, SHA256: hex.EncodeToString(sum[:])}) + if err != nil { + return err + } + if err := writeFileDurable(b.path, raw); err != nil { + return fmt.Errorf("storage: chunk bitmap write: %w", err) + } + // Durable on return includes the rename itself. + if err := syncDir(filepath.Dir(b.path)); err != nil { + return fmt.Errorf("storage: chunk bitmap: fsync directory: %w", err) + } + b.stored, b.hdr, b.dirty = true, hdr, append([]uint64(nil), dirty...) + return nil +} + +func (b *FileChunkBitmapStore) Load() (chunkBitmapHeader, []uint64, bool, error) { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.loadLocked(); err != nil { + return chunkBitmapHeader{}, nil, false, err + } + if !b.stored { + return chunkBitmapHeader{}, nil, false, nil + } + return b.hdr, append([]uint64(nil), b.dirty...), true, nil +} + +func (b *FileChunkBitmapStore) Save(dirty []uint64) error { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.loadLocked(); err != nil { + return err + } + return b.writeLocked(b.hdr, dirty) +} + +func (b *FileChunkBitmapStore) WriteHeader(hdr chunkBitmapHeader) error { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.loadLocked(); err != nil { + return err + } + return b.writeLocked(hdr, b.dirty) +} + +func (b *FileChunkBitmapStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, delta chunkDelta) error { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.loadLocked(); err != nil { + return err + } + rec, err := json.Marshal(delta) + if err != nil { + return err + } + f, err := os.OpenFile(b.path+".deltas", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + return fmt.Errorf("storage: chunk delta log: %w", err) + } + if _, err := f.Write(append(rec, '\n')); err != nil { + f.Close() + return fmt.Errorf("storage: chunk delta log: %w", err) + } + if err := f.Sync(); err != nil { + f.Close() + return fmt.Errorf("storage: chunk delta log: %w", err) + } + if err := f.Close(); err != nil { + return err + } + return b.writeLocked(hdr, stillDirty) +} + +// Deltas returns the archived delta records, oldest first. +func (b *FileChunkBitmapStore) Deltas() ([]chunkDelta, error) { + raw, err := os.ReadFile(b.path + ".deltas") + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var out []chunkDelta + for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) { + if len(line) == 0 { + continue + } + var d chunkDelta + if err := json.Unmarshal(line, &d); err != nil { + return nil, fmt.Errorf("storage: chunk delta log: %w", err) + } + out = append(out, d) + } + return out, nil +} + +var _ chunkBitmapStore = (*FileChunkBitmapStore)(nil) diff --git a/seaweed-block/core/storage/chunk_bitmap_file_test.go b/seaweed-block/core/storage/chunk_bitmap_file_test.go new file mode 100644 index 0000000000..829a5e6fa0 --- /dev/null +++ b/seaweed-block/core/storage/chunk_bitmap_file_test.go @@ -0,0 +1,107 @@ +package storage + +import ( + "context" + "os" + "path/filepath" + "reflect" + "testing" +) + +func TestFileChunkBitmapStore_RoundTripAndReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "vol.chunkbitmap") + b := NewFileChunkBitmapStore(path) + if _, _, ok, err := b.Load(); ok || err != nil { + t.Fatalf("empty store: ok %v err %v", ok, err) + } + if err := b.Save([]uint64{3, 7}); err != nil { + t.Fatal(err) + } + if err := b.WriteHeader(chunkBitmapHeader{Base: chunkBaseInstalling}); err != nil { + t.Fatal(err) + } + hdr, dirty, ok, err := b.Load() + if !ok || err != nil || hdr.Base != chunkBaseInstalling || !reflect.DeepEqual(dirty, []uint64{3, 7}) { + t.Fatalf("after Save+WriteHeader: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty) + } + want := chunkBitmapHeader{BaseLSN: 40, HeadGen: 3, Epoch: 2} + delta := chunkDelta{FromLSN: 10, ToLSN: 40, Gen: 3, Dirty: []uint64{3}, NewKeys: map[uint64]string{3: "k3"}} + if err := b.Reset(want, []uint64{7}, delta); err != nil { + t.Fatal(err) + } + // A new instance reads exactly the durable state. + b2 := NewFileChunkBitmapStore(path) + hdr, dirty, ok, err = b2.Load() + if !ok || err != nil || hdr != want || !reflect.DeepEqual(dirty, []uint64{7}) { + t.Fatalf("reopened: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty) + } + deltas, err := b2.Deltas() + if err != nil || len(deltas) != 1 || !reflect.DeepEqual(deltas[0], delta) { + t.Fatalf("delta log: %v %+v", err, deltas) + } +} + +func TestFileChunkBitmapStore_CorruptStateIsLost(t *testing.T) { + path := filepath.Join(t.TempDir(), "vol.chunkbitmap") + b := NewFileChunkBitmapStore(path) + if err := b.Save([]uint64{1}); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + raw[len(raw)/2] ^= 0xFF // one flipped byte + if err := os.WriteFile(path, raw, 0o600); err != nil { + t.Fatal(err) + } + if _, _, ok, err := NewFileChunkBitmapStore(path).Load(); ok || err != nil { + t.Fatalf("corrupt state: ok %v err %v, want ok=false (hash-compare fallback) and no error", ok, err) + } +} + +// The layer with the production file bitmap and the in-memory remote: +// after a crash the first cut is incremental and exact. +func TestChunkLayer_FileBitmapIncrementalAfterRestart(t *testing.T) { + s, path, crash := crashableStore(t) + remote := NewMemChunkRemote() + cfg := chunkLayerConfig{ChunkBlocks: ctChunkBlocks, Epoch: 1, Holder: "h", Bitmap: NewFileChunkBitmapStore(path + ".chunkbitmap")} + layer := mustAttach(t, s, remote, cfg) + w := newWriteLog() + w.write(t, s, 1, 0x01) // chunk 0 + w.write(t, s, 21, 0x21) // chunk 5 + if _, err := layer.Capture(context.Background()); err != nil { + t.Fatal(err) + } + w.write(t, s, 24, 0x24) // chunk 6, flushed: only the bitmap remembers it + mustSyncFlush(t, s) + w.write(t, s, 28, 0x28) // chunk 7, WAL only + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crash() + s2, _ := reopen(t, path) + cfg.Bitmap = NewFileChunkBitmapStore(path + ".chunkbitmap") // a fresh instance reads the file + layer2 := mustAttach(t, s2, remote, cfg) + before := remote.Puts() + h, err := layer2.Capture(context.Background()) + if err != nil { + t.Fatal(err) + } + if n := remote.Puts() - before; n != 2 { + t.Fatalf("first cut after restart stored %d chunks, want 2 (chunks 6 and 7)", n) + } + head, _ := remote.GetHead(context.Background()) + if head.RemoteLSN != h { + t.Fatalf("HEAD remote_lsn %d, want %d", head.RemoteLSN, h) + } + img := make([]byte, ctNumBlocks*ctBlockSize) + for idx, ref := range head.Chunks { + b, err := remote.Get(context.Background(), ref.Key) + if err != nil { + t.Fatal(err) + } + copy(img[int(idx)*ctChunkBytes:], b) + } + assertImage(t, "HEAD image after restart", img, w.imageAt(h)) +} diff --git a/seaweed-block/core/storage/chunk_memremote.go b/seaweed-block/core/storage/chunk_memremote.go new file mode 100644 index 0000000000..9c1b3598fb --- /dev/null +++ b/seaweed-block/core/storage/chunk_memremote.go @@ -0,0 +1,104 @@ +package storage + +// MemChunkRemote is an in-memory chunkRemote for development, demos and +// provider tests: immutable keys (a key that ever existed is never +// rewritten), SHA-256-checked chunk refs, the {gen, epoch} HEAD CAS, and +// monotonic ownership (a proposal never lowers the epoch). +// It has no fault injection; the contract tests use their own fake. + +import ( + "context" + "crypto/sha256" + "fmt" + "sync" +) + +type MemChunkRemote struct { + mu sync.Mutex + objs map[string][]byte + ever map[string]bool + head chunkHead + puts int +} + +func NewMemChunkRemote() *MemChunkRemote { + return &MemChunkRemote{objs: map[string][]byte{}, ever: map[string]bool{}} +} + +func (m *MemChunkRemote) Put(ctx context.Context, key string, data []byte) error { + if err := ctx.Err(); err != nil { + return err + } + m.mu.Lock() + defer m.mu.Unlock() + if m.ever[key] { + return errChunkKeyExists + } + m.objs[key] = append([]byte(nil), data...) + m.ever[key] = true + m.puts++ + return nil +} + +func (m *MemChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + m.mu.Lock() + defer m.mu.Unlock() + b, ok := m.objs[key] + if !ok { + return nil, fmt.Errorf("storage: mem remote: no key %q", key) + } + return append([]byte(nil), b...), nil +} + +func (m *MemChunkRemote) GetHead(ctx context.Context) (chunkHead, error) { + if err := ctx.Err(); err != nil { + return chunkHead{}, err + } + m.mu.Lock() + defer m.mu.Unlock() + return copyHead(m.head), nil +} + +func (m *MemChunkRemote) CASHead(ctx context.Context, expected chunkHeadVersion, next chunkHead) (uint64, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + m.mu.Lock() + defer m.mu.Unlock() + if expected.Gen != m.head.Gen || expected.Epoch != m.head.Epoch { + return 0, errChunkHeadPrecondition + } + // Ownership only moves forward: a proposal never lowers the epoch. + if next.Epoch < m.head.Epoch { + return 0, errChunkHeadPrecondition + } + for idx, ref := range next.Chunks { + b, ok := m.objs[ref.Key] + if !ok || sha256.Sum256(b) != ref.SHA256 { + return 0, fmt.Errorf("storage: mem remote: HEAD chunk %d ref %q is not stored with that hash", idx, ref.Key) + } + } + installed := copyHead(next) + installed.Gen = m.head.Gen + 1 + m.head = installed + return installed.Gen, nil +} + +func (m *MemChunkRemote) Delete(ctx context.Context, key string) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.objs, key) + return nil +} + +// Puts reports how many chunks were stored (for tests and demos). +func (m *MemChunkRemote) Puts() int { + m.mu.Lock() + defer m.mu.Unlock() + return m.puts +} + +var _ chunkRemote = (*MemChunkRemote)(nil) diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go new file mode 100644 index 0000000000..8928738c2c --- /dev/null +++ b/seaweed-block/core/storage/chunk_public.go @@ -0,0 +1,40 @@ +package storage + +// Exported surface of the chunk layer for callers outside this package: +// the durable provider and remote implementations. The aliases keep the +// contract types single-sourced in chunk_seam.go. + +type ( + ChunkRemote = chunkRemote + ChunkHead = chunkHead + ChunkHeadVersion = chunkHeadVersion + ChunkRef = chunkRef + ChunkBitmapStore = chunkBitmapStore + ChunkBitmapHeader = chunkBitmapHeader + ChunkBaseState = chunkBaseState + ChunkDelta = chunkDelta + ChunkLayerConfig = chunkLayerConfig + ChunkLayer = chunkLayer +) + +const ( + ChunkBaseNone = chunkBaseNone + ChunkBaseInstalling = chunkBaseInstalling + ChunkBaseInstalledAwaitingCut = chunkBaseInstalledAwaitingCut +) + +var ( + ErrChunkKeyExists = errChunkKeyExists + ErrChunkHeadPrecondition = errChunkHeadPrecondition + ErrChunkLayerFenced = errChunkLayerFenced + ErrChunkEvictRefused = errChunkEvictRefused + ErrChunkCaptureRefused = errChunkCaptureRefused +) + +// AttachChunkLayer attaches a chunk layer to an open, recovered WALStore. +// Attach after Recover: the dirty set and the restart rules read the +// replayed dirty map. The store owns the layer from then on and closes it +// in WALStore.Close. +func AttachChunkLayer(s *WALStore, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkLayer, error) { + return attachChunkLayer(s, remote, cfg) +}