diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go new file mode 100644 index 0000000000..825ef0c517 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -0,0 +1,80 @@ +package main + +// --durable-impl=walstore-chunk: walstore with the chunk layer publishing +// the volume to SeaweedFS (opt-in proof of concept). Each volume's HEAD and +// chunk key bindings live under <--chunk-path>/ on the filer +// given by --chunk-filer; chunk bytes are needles on its volume servers. + +import ( + "errors" + "fmt" + "path" + "strings" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const defaultChunkPath = "/swblock/chunks" + +type chunkFlags struct { + filer string + path string + collection string + replication string + captureInterval time.Duration +} + +func validateChunkFlags(f flags) error { + c := f.chunk + if f.durableImpl != "walstore-chunk" { + if c.filer != "" || c.collection != "" || c.replication != "" || c.captureInterval != 0 || c.path != defaultChunkPath { + return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") + } + return nil + } + if f.durableRoot == "" { + return errors.New("--durable-impl=walstore-chunk requires --durable-root") + } + if c.filer == "" { + return errors.New("--durable-impl=walstore-chunk requires --chunk-filer") + } + if !path.IsAbs(c.path) || path.Clean(c.path) != c.path || c.path == "/" { + return fmt.Errorf("--chunk-path=%q must be a clean absolute filer directory other than /", c.path) + } + if c.captureInterval < 0 { + return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval) + } + return nil +} + +// newChunkRemoteFor dials the filer (lazily) and returns the provider's +// ChunkRemoteFor plus the client's closer. +func newChunkRemoteFor(c chunkFlags) (func(volumeID string) (storage.ChunkRemote, error), func() error, error) { + client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ + FilerGRPC: c.filer, + Collection: c.collection, + Replication: c.replication, + AssignPath: c.path, + }) + if err != nil { + return nil, nil, err + } + return func(volumeID string) (storage.ChunkRemote, error) { + root, err := chunkVolumeRoot(c.path, volumeID) + if err != nil { + return nil, err + } + return chunkstore.NewSWFSChunkRemote(client, root) + }, client.Close, nil +} + +// chunkVolumeRoot is /; the volume ID must be one plain +// path element so no volume can reach another volume's directory. +func chunkVolumeRoot(base, volumeID string) (string, error) { + if volumeID == "" || volumeID == "." || volumeID == ".." || strings.ContainsAny(volumeID, "/\\") { + return "", fmt.Errorf("blockvolume: volume id %q is not a plain path element", volumeID) + } + return path.Join(base, volumeID), nil +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go new file mode 100644 index 0000000000..2b5c568bc0 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -0,0 +1,49 @@ +package main + +import ( + "strings" + "testing" + "time" +) + +func TestWALStoreChunkFlags(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", + "--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=30s")) + if err != nil { + t.Fatalf("walstore-chunk with a filer: %v", err) + } + if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 30*time.Second { + t.Fatalf("parsed chunk flags = %+v", f.chunk) + } + refused := map[string][]string{ + "no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"), + "no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"), + "relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"), + "root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"), + "negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"), + "chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"), + "chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"), + } + for name, args := range refused { + if _, err := parseFlags(args); err == nil { + t.Errorf("%s: parseFlags succeeded; want an error", name) + } + } +} + +func TestChunkVolumeRootStaysInsideBase(t *testing.T) { + root, err := chunkVolumeRoot(defaultChunkPath, "v1") + if err != nil || root != defaultChunkPath+"/v1" { + t.Fatalf("chunkVolumeRoot(v1) = %q, %v", root, err) + } + for _, id := range []string{"", ".", "..", "a/b", "../v2", `a\b`} { + if r, err := chunkVolumeRoot(defaultChunkPath, id); err == nil { + t.Errorf("volume id %q mapped to %q; want refusal", id, r) + } else if !strings.Contains(err.Error(), "plain path element") { + t.Errorf("volume id %q: unexpected error %v", id, err) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 8c856dbf2b..573380023b 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -96,8 +96,10 @@ type flags struct { // parallel-walstore candidate (default smartwal). // --durable-blocks + --durable-blocksize are used on first-time // storage create. - durableRoot string - durableImpl string // "smartwal" | "walstore" | "parallel-walstore" + durableRoot string + durableImpl string // "smartwal" | "walstore" | "parallel-walstore" | "walstore-chunk" + // --chunk-*: the SeaweedFS remote of --durable-impl=walstore-chunk. + chunk chunkFlags durableBlocks uint durableBlockSize uint durableWALMultiBlockRecords bool @@ -167,7 +169,12 @@ func parseFlags(args []string) (flags, error) { fs.UintVar(&f.nvmeMaxH2C, "nvme-max-h2c-data-length", 0, "NVMe/TCP MaxH2CDataLength in bytes. 0 preserves the target default") fs.BoolVar(&f.allowExternalNVMeBind, "allow-external-nvme-bind", false, "allow NVMe to bind a non-loopback address; unauthenticated, intended only for explicit gates") fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") - fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default), walstore, or opt-in parallel-walstore; ignored unless --durable-root is set") + fs.StringVar(&f.durableImpl, "durable-impl", "smartwal", "LogicalStorage impl: smartwal (default), walstore, opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") + fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port") + fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)") + fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") + fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", 0, "walstore-chunk: publish a cut every interval while healthy; 0 = only on demand") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") fs.BoolVar(&f.durableWALMultiBlockRecords, "durable-wal-multiblock-records", false, "enable experimental walstore multi-block WAL records; default false; requires --durable-impl=walstore") @@ -217,9 +224,12 @@ func parseFlags(args []string) (flags, error) { return flags{}, err } switch f.durableImpl { - case "smartwal", "walstore", "parallel-walstore": + case "smartwal", "walstore", "parallel-walstore", "walstore-chunk": default: - return flags{}, fmt.Errorf("--durable-impl=%q invalid; want smartwal, walstore, or parallel-walstore", f.durableImpl) + return flags{}, fmt.Errorf("--durable-impl=%q invalid; want smartwal, walstore, parallel-walstore, or walstore-chunk", f.durableImpl) + } + if err := validateChunkFlags(f); err != nil { + return flags{}, err } if f.durableWALMultiBlockRecords { if f.durableRoot == "" { @@ -533,7 +543,19 @@ func run(f flags) int { WALMultiBlockRecords: f.durableWALMultiBlockRecords, WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher, } + var chunkErr error + if cfg.Impl == durable.ImplWALStoreChunk { + var closeChunkClient func() error + cfg.ChunkRemoteFor, closeChunkClient, chunkErr = newChunkRemoteFor(f.chunk) + cfg.ChunkCaptureInterval = f.chunk.captureInterval + if chunkErr == nil { + defer closeChunkClient() + } + } dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) + if chunkErr != nil { + err = chunkErr + } if err != nil { fmt.Fprintln(os.Stderr, "blockvolume: durable provider:", err) if status != nil { diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go new file mode 100644 index 0000000000..1ac0391a80 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -0,0 +1,306 @@ +package chunkstore + +// ChunkRemote: the walstore chunk layer's remote (storage.ChunkRemote) on +// SeaweedFS, over the Filer and Blobs interfaces above. +// +// Layout under one volume's root directory: +// +// /HEAD the published HEAD: JSON in the entry content, +// {gen, epoch, holder} mirrored in extended attributes +// /keys/ one write-once entry per chunk key, naming the +// needle (fid) that holds the chunk's bytes +// +// The chunk layer names chunks itself (immutable keys) while SeaweedFS +// assigns needle ids, so a key entry binds the two. It is created with +// o_excl: a key that exists is never rebound, which is the "keys are +// immutable" rule of storage.ChunkRemote. +// +// The HEAD CAS is the filer's conditional update: UpdateEntry with +// expected_extended = {swb.gen, swb.epoch} of the HEAD the caller read. +// The first HEAD is an exclusive create. Only a definite refusal maps to +// storage.ErrChunkHeadPrecondition; every other error is returned as is, +// so the chunk layer treats the outcome as unknown and re-reads HEAD. +// +// No entry ever carries filer chunks: UpdateEntry deletes chunks the new +// entry drops, so needle ids live only in entry content and extended +// attributes, which the filer does not interpret. +// +// Not implemented: reclaiming needles. Delete reports ErrDeleteUnsupported; +// superseded chunks stay stored (the chunk layer never calls Delete). + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "path" + "strconv" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Extended attribute keys; the same names the D1 manifest entries use. +const ( + extGen = "swb.gen" + extEpoch = "swb.epoch" + extHolder = "swb.holder" + extKind = "swb.kind" + extFid = "swb.fid" + + kindChunkHead = "chunkhead" + kindChunkKey = "chunkkey" + + headName = "HEAD" + keysDir = "keys" + + // headFormat is the only HEAD document format this code reads. + headFormat = 1 +) + +// ErrDeleteUnsupported: this remote does not reclaim chunks. +var ErrDeleteUnsupported = errors.New("chunkstore: chunk delete not supported") + +// ChunkRemote implements storage.ChunkRemote for one volume. +type ChunkRemote struct { + f Filer + b Blobs + root string + + mu sync.Mutex + fids map[string]string // key -> fid; key entries are write-once +} + +// NewChunkRemote returns the remote for the volume rooted at root, an +// absolute filer directory owned by that volume alone. +func NewChunkRemote(f Filer, b Blobs, root string) (*ChunkRemote, error) { + if f == nil || b == nil { + return nil, errors.New("chunkstore: chunk remote needs a filer and a blob store") + } + if !path.IsAbs(root) || path.Clean(root) != root || root == "/" { + return nil, fmt.Errorf("chunkstore: chunk remote root %q must be a clean absolute directory other than /", root) + } + return &ChunkRemote{f: f, b: b, root: root, fids: map[string]string{}}, nil +} + +func (r *ChunkRemote) keyDir() string { return path.Join(r.root, keysDir) } + +func keyName(key string) (string, error) { + if key == "" { + return "", errors.New("chunkstore: empty chunk key") + } + return url.PathEscape(key), nil // one flat directory: '/' is escaped +} + +// Put stores data as a new needle, then binds key to it with an exclusive +// create. A key that is already bound fails with storage.ErrChunkKeyExists +// and its bytes are untouched. +func (r *ChunkRemote) Put(ctx context.Context, key string, data []byte) error { + name, err := keyName(key) + if err != nil { + return err + } + r.mu.Lock() + _, known := r.fids[key] + r.mu.Unlock() + if known { + return storage.ErrChunkKeyExists + } + fid, err := r.b.Put(ctx, data) + if err != nil { + return err + } + now := time.Now().Unix() + e := &filerpb.Entry{ + Name: name, + Attributes: &filerpb.FuseAttributes{Mtime: now, Crtime: now, FileMode: 0o644}, + Extended: map[string][]byte{extKind: []byte(kindChunkKey), extFid: []byte(fid)}, + } + if err := r.f.CreateEntry(ctx, r.keyDir(), e, true); err != nil { + if errors.Is(err, ErrExists) { + return fmt.Errorf("%w: %s", storage.ErrChunkKeyExists, key) + } + return err + } + r.mu.Lock() + r.fids[key] = fid + r.mu.Unlock() + return nil +} + +// Get returns the bytes bound to key. The chunk layer checks them against +// the SHA-256 in HEAD. +func (r *ChunkRemote) Get(ctx context.Context, key string) ([]byte, error) { + name, err := keyName(key) + if err != nil { + return nil, err + } + r.mu.Lock() + fid, ok := r.fids[key] + r.mu.Unlock() + if !ok { + e, err := r.f.LookupEntry(ctx, r.keyDir(), name) + if err != nil { + return nil, fmt.Errorf("chunkstore: chunk key %q: %w", key, err) + } + if len(e.GetChunks()) != 0 || string(e.Extended[extKind]) != kindChunkKey || len(e.Extended[extFid]) == 0 { + return nil, fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key) + } + fid = string(e.Extended[extFid]) + r.mu.Lock() + r.fids[key] = fid + r.mu.Unlock() + } + return r.b.Get(ctx, fid) +} + +// Delete is not supported; see ErrDeleteUnsupported. +func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported } + +type headDoc struct { + Format int `json:"format"` + Gen uint64 `json:"gen"` + Epoch uint64 `json:"epoch"` + Holder string `json:"holder"` + RemoteLSN uint64 `json:"remote_lsn"` + Chunks map[uint64]refDoc `json:"chunks"` +} + +type refDoc struct { + Key string `json:"key"` + SHA256 string `json:"sha256"` +} + +// GetHead returns the published HEAD, or the zero HEAD (Gen 0) when none +// was ever published. An entry that exists but does not decode is an +// error, never the zero HEAD. +func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + e, err := r.f.LookupEntry(ctx, r.root, headName) + if errors.Is(err, ErrNotFound) { + return storage.ChunkHead{}, nil + } + if err != nil { + return storage.ChunkHead{}, err + } + return decodeHead(path.Join(r.root, headName), e) +} + +// CASHead installs next, at generation expected.Gen+1, only if the stored +// HEAD is still at expected. Ownership only moves forward: a proposal that +// lowers the epoch is refused. +func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + if next.Epoch < expected.Epoch { + return 0, storage.ErrChunkHeadPrecondition + } + if expected.Gen == 0 && expected.Epoch != 0 { + return 0, storage.ErrChunkHeadPrecondition // the absent HEAD has epoch 0 + } + next.Gen = expected.Gen + 1 + e, err := headEntry(next) + if err != nil { + return 0, err + } + if expected.Gen == 0 { + err = r.f.CreateEntry(ctx, r.root, e, true) + } else { + err = r.f.UpdateEntry(ctx, r.root, e, map[string][]byte{ + extGen: []byte(strconv.FormatUint(expected.Gen, 10)), + extEpoch: []byte(strconv.FormatUint(expected.Epoch, 10)), + }) + } + switch { + case err == nil: + return next.Gen, nil + case errors.Is(err, ErrPrecondition), errors.Is(err, ErrExists), errors.Is(err, ErrNotFound): + return 0, fmt.Errorf("%w: %v", storage.ErrChunkHeadPrecondition, err) + default: + return 0, err // outcome unknown: the caller re-reads HEAD + } +} + +func headEntry(h storage.ChunkHead) (*filerpb.Entry, error) { + doc := headDoc{Format: headFormat, Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, + Chunks: make(map[uint64]refDoc, len(h.Chunks))} + for idx, ref := range h.Chunks { + if ref.Key == "" { + return nil, fmt.Errorf("chunkstore: HEAD chunk %d has no key", idx) + } + doc.Chunks[idx] = refDoc{Key: ref.Key, SHA256: hex.EncodeToString(ref.SHA256[:])} + } + body, err := json.Marshal(doc) + if err != nil { + return nil, err + } + now := time.Now().Unix() + return &filerpb.Entry{ + Name: headName, + Attributes: &filerpb.FuseAttributes{ + FileSize: uint64(len(body)), + Mtime: now, + Crtime: now, + FileMode: 0o644, + Mime: "application/json", + }, + Extended: map[string][]byte{ + extGen: []byte(strconv.FormatUint(h.Gen, 10)), + extEpoch: []byte(strconv.FormatUint(h.Epoch, 10)), + extHolder: []byte(h.Holder), + extKind: []byte(kindChunkHead), + }, + Content: body, + }, nil +} + +func decodeHead(p string, e *filerpb.Entry) (storage.ChunkHead, error) { + fail := func(format string, a ...any) (storage.ChunkHead, error) { + return storage.ChunkHead{}, fmt.Errorf("chunkstore: HEAD %s: "+format, append([]any{p}, a...)...) + } + if len(e.GetChunks()) != 0 { + return fail("carries %d filer chunks; refusing (an update would let the filer delete them)", len(e.Chunks)) + } + if k := string(e.Extended[extKind]); k != kindChunkHead { + return fail("kind %q, want %q", k, kindChunkHead) + } + var doc headDoc + if err := json.Unmarshal(e.GetContent(), &doc); err != nil { + return fail("decode: %v", err) + } + if doc.Format != headFormat { + return fail("format %d not supported (want %d)", doc.Format, headFormat) + } + if doc.Gen == 0 { + return fail("generation 0") + } + // The CAS compares the extended attributes, so they must agree with the + // document or a CAS could validate against a different state. + if string(e.Extended[extGen]) != strconv.FormatUint(doc.Gen, 10) || + string(e.Extended[extEpoch]) != strconv.FormatUint(doc.Epoch, 10) || + string(e.Extended[extHolder]) != doc.Holder { + return fail("extended gen/epoch/holder (%q/%q/%q) disagree with the document (%d/%d/%q)", + e.Extended[extGen], e.Extended[extEpoch], e.Extended[extHolder], doc.Gen, doc.Epoch, doc.Holder) + } + h := storage.ChunkHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN, + Chunks: make(map[uint64]storage.ChunkRef, len(doc.Chunks))} + for idx, ref := range doc.Chunks { + sum, err := hex.DecodeString(ref.SHA256) + if err != nil || len(sum) != 32 || ref.Key == "" { + return fail("chunk %d ref invalid", idx) + } + cr := storage.ChunkRef{Key: ref.Key} + copy(cr.SHA256[:], sum) + h.Chunks[idx] = cr + } + return h, nil +} + +// NewSWFSChunkRemote is NewChunkRemote over one SWFS client, which serves +// as both the filer and the blob store. +func NewSWFSChunkRemote(c *SWFS, root string) (*ChunkRemote, error) { + return NewChunkRemote(c, c, root) +} + +var _ storage.ChunkRemote = (*ChunkRemote)(nil) diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go new file mode 100644 index 0000000000..8acc38175d --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_integration_test.go @@ -0,0 +1,275 @@ +//go:build chunkstore_integration + +// The chunk remote against real SeaweedFS processes (weed master, volume, +// filer) started as the current user. The cluster helpers are the D1 +// PoC's. Run with: +// +// CHUNKSTORE_WEED=/path/to/weed go test -tags chunkstore_integration -run Integration -v ./core/frontend/chunkstore/ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "fmt" + "math/rand" + "net" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type weedCluster struct { + master, filerHTTP, filerGRPC string + dir string + weed string +} + +func freePortPair(t *testing.T, used map[int]bool) int { + t.Helper() + for i := 0; i < 200; i++ { + p := 20000 + rand.Intn(20000) + if used[p] || used[p+10000] { + continue + } + ok := true + for _, q := range []int{p, p + 10000} { + l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", q)) + if err != nil { + ok = false + break + } + l.Close() + } + if ok { + used[p], used[p+10000] = true, true + return p + } + } + t.Fatal("no free port pair") + return 0 +} + +func waitTCP(t *testing.T, addr string, d time.Duration) { + t.Helper() + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if c, err := net.DialTimeout("tcp", addr, 200*time.Millisecond); err == nil { + c.Close() + return + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("%s not listening after %v", addr, d) +} + +func startWeed(t *testing.T) *weedCluster { + t.Helper() + weed := os.Getenv("CHUNKSTORE_WEED") + if weed == "" { + t.Skip("CHUNKSTORE_WEED not set") + } + dir := t.TempDir() + used := map[int]bool{} + mp, vp, fp := freePortPair(t, used), freePortPair(t, used), freePortPair(t, used) + c := &weedCluster{ + master: fmt.Sprintf("127.0.0.1:%d", mp), + filerHTTP: fmt.Sprintf("127.0.0.1:%d", fp), + filerGRPC: fmt.Sprintf("127.0.0.1:%d", fp+10000), + dir: dir, + weed: weed, + } + run := func(name string, args ...string) { + logf, err := os.Create(filepath.Join(dir, name+".log")) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(weed, args...) + cmd.Stdout, cmd.Stderr = logf, logf + cmd.Dir = dir + if err := cmd.Start(); err != nil { + t.Fatalf("start %s: %v", name, err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _, _ = cmd.Process.Wait() + logf.Close() + if t.Failed() { + b, _ := os.ReadFile(logf.Name()) + if len(b) > 4000 { + b = b[len(b)-4000:] + } + t.Logf("---- %s log tail ----\n%s", name, b) + } + }) + } + for _, d := range []string{"m", "v", "f"} { + if err := os.MkdirAll(filepath.Join(dir, d), 0o755); err != nil { + t.Fatal(err) + } + } + run("master", "master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000") + waitTCP(t, c.master, 20*time.Second) + run("volume", "volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+c.master, "-max=32") + run("filer", "filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+c.master, "-defaultStoreDir="+filepath.Join(dir, "f")) + waitTCP(t, c.filerGRPC, 30*time.Second) + + // Wait until an assign succeeds (volume registered, volumes growable). + cl := c.client(t, "/swblock/vols/probe") + deadline := time.Now().Add(60 * time.Second) + for { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, err := cl.Put(ctx, []byte("probe")) + cancel() + if err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("cluster never accepted a write: %v", err) + } + time.Sleep(500 * time.Millisecond) + } + return c +} + +func (c *weedCluster) client(t *testing.T, assignPath string) *SWFS { + t.Helper() + cl, err := DialSWFS(SWFSConfig{FilerGRPC: c.filerGRPC, Collection: "swblock", AssignPath: assignPath}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cl.Close() }) + return cl +} + +func (c *weedCluster) remote(t *testing.T, root string) *ChunkRemote { + t.Helper() + r, err := NewSWFSChunkRemote(c.client(t, root), root) + if err != nil { + t.Fatal(err) + } + return r +} + +func TestIntegration_ChunkRemoteContract(t *testing.T) { + c := startWeed(t) + ctx := context.Background() + const root = "/swblock/chunks/contract" + a, b := c.remote(t, root), c.remote(t, root) + + if h, err := a.GetHead(ctx); err != nil || h.Gen != 0 { + t.Fatalf("absent HEAD = %+v, %v", h, err) + } + d := bytes.Repeat([]byte("chunk-bytes-"), 1000) + const key = "chunks/e1/c4/nonce-1" + if err := a.Put(ctx, key, d); err != nil { + t.Fatalf("Put: %v", err) + } + if err := a.Put(ctx, key, []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebind on the same client: %v", err) + } + if err := b.Put(ctx, key, []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebind from another client (real o_excl): %v", err) + } + if got, err := b.Get(ctx, key); err != nil || !bytes.Equal(got, d) { + t.Fatalf("Get from another client: %d bytes, %v", len(got), err) + } + + h1 := storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{4: ref(key, d)}} + if gen, err := a.CASHead(ctx, storage.ChunkHeadVersion{}, h1); err != nil || gen != 1 { + t.Fatalf("first CAS = %d, %v", gen, err) + } + if _, err := b.CASHead(ctx, storage.ChunkHeadVersion{}, h1); !isPrecondition(err) { + t.Fatalf("racing first CAS: %v; want precondition (real o_excl)", err) + } + got, err := b.GetHead(ctx) + if err != nil || got.Gen != 1 || got.Chunks[4] != h1.Chunks[4] || got.RemoteLSN != 7 { + t.Fatalf("HEAD from another client = %+v, %v", got, err) + } + // Takeover at epoch 2, then the old holder's CAS at the version it read. + if gen, err := b.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, storage.ChunkHead{Epoch: 2, Holder: "b", RemoteLSN: 7, Chunks: h1.Chunks}); err != nil || gen != 2 { + t.Fatalf("takeover CAS = %d, %v", gen, err) + } + _, err = a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 9}) + if !isPrecondition(err) { + t.Fatalf("old holder's CAS after takeover: %v; want precondition (real FailedPrecondition)", err) + } + t.Logf("old holder refused: %v", err) + if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 2, Epoch: 2}, storage.ChunkHead{Epoch: 1, Holder: "a"}); !isPrecondition(err) { + t.Fatalf("epoch-lowering CAS: %v; want precondition", err) + } + e, err := c.client(t, root).LookupEntry(ctx, root, headName) + if err != nil { + t.Fatal(err) + } + if len(e.GetChunks()) != 0 || string(e.Extended[extGen]) != "2" || string(e.Extended[extEpoch]) != "2" { + t.Fatalf("stored HEAD entry: %d filer chunks, gen %q, epoch %q", len(e.GetChunks()), e.Extended[extGen], e.Extended[extEpoch]) + } +} + +func TestIntegration_ChunkLayerCaptureThenFreshHost(t *testing.T) { + c := startWeed(t) + ctx := context.Background() + const root = "/swblock/chunks/v1" + const blocks, chunkBlocks = 512, 64 // 256 KiB chunks + dir := t.TempDir() + attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { + p := filepath.Join(dir, name) + s, err := storage.CreateWALStore(p, blocks, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + l, err := storage.AttachChunkLayer(s, c.remote(t, root), storage.ChunkLayerConfig{ + ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, + Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s, l + } + src, layer := attach("a", false) + want := map[uint32][]byte{} + rng := rand.New(rand.NewSource(1)) + for _, lba := range []uint32{0, 63, 64, 300, 511} { + b := make([]byte, 4096) + rng.Read(b) + want[lba] = b + if _, err := src.Write(lba, b); err != nil { + t.Fatal(err) + } + } + if _, err := src.Sync(); err != nil { + t.Fatal(err) + } + start := time.Now() + if _, err := layer.Capture(ctx); err != nil { + t.Fatalf("Capture: %v", err) + } + t.Logf("capture of 4 dirty chunks: %v", time.Since(start)) + _ = src.Close() + + dst, _ := attach("b", true) + zero := make([]byte, 4096) + for lba := uint32(0); lba < blocks; lba++ { + got, err := dst.Read(lba) + if err != nil { + t.Fatalf("fresh host read %d: %v", lba, err) + } + exp, ok := want[lba] + if !ok { + exp = zero + } + if !bytes.Equal(got, exp) { + t.Fatalf("fresh host block %d differs", lba) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go new file mode 100644 index 0000000000..fe726b926c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote_test.go @@ -0,0 +1,316 @@ +package chunkstore + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "path/filepath" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const testRoot = "/swblock/chunks/v1" + +func newTestRemote(t *testing.T, f *fakeFiler, b *fakeBlobs) *ChunkRemote { + t.Helper() + r, err := NewChunkRemote(f, b, testRoot) + if err != nil { + t.Fatal(err) + } + return r +} + +func ref(key string, data []byte) storage.ChunkRef { + return storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)} +} + +func head(epoch uint64, holder string, lsn uint64, chunks map[uint64]storage.ChunkRef) storage.ChunkHead { + return storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: lsn, Chunks: chunks} +} + +func isPrecondition(err error) bool { return errors.Is(err, storage.ErrChunkHeadPrecondition) } + +func TestChunkRemote_RootMustBeCleanAbsolute(t *testing.T) { + for _, root := range []string{"", "/", "rel/dir", "/a/../b", "/a/"} { + if _, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), root); err == nil { + t.Errorf("root %q accepted", root) + } + } +} + +func TestChunkRemote_HeadRoundTripAndCAS(t *testing.T) { + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + r := newTestRemote(t, f, b) + + h0, err := r.GetHead(ctx) + if err != nil || h0.Gen != 0 || len(h0.Chunks) != 0 { + t.Fatalf("absent HEAD = %+v, %v; want the zero HEAD", h0, err) + } + d := bytes.Repeat([]byte{7}, 64) + if err := r.Put(ctx, "chunks/e1/c3/n-1", d); err != nil { + t.Fatal(err) + } + want := head(1, "a", 42, map[uint64]storage.ChunkRef{3: ref("chunks/e1/c3/n-1", d)}) + gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want) + if err != nil || gen != 1 { + t.Fatalf("first CAS = %d, %v; want gen 1", gen, err) + } + got, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if got.Gen != 1 || got.Epoch != 1 || got.Holder != "a" || got.RemoteLSN != 42 || len(got.Chunks) != 1 || got.Chunks[3] != want.Chunks[3] { + t.Fatalf("HEAD read back = %+v; want gen 1 of %+v", got, want) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want); !isPrecondition(err) { + t.Fatalf("second first-HEAD CAS: %v; want precondition", err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 0}, want); !isPrecondition(err) { + t.Fatalf("CAS at a wrong epoch: %v; want precondition", err) + } + gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 50, nil)) + if err != nil || gen != 2 { + t.Fatalf("CAS at the current version = %d, %v; want gen 2", gen, err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 60, nil)); !isPrecondition(err) { + t.Fatalf("CAS at a stale generation: %v; want precondition", err) + } + got, _ = r.GetHead(ctx) + if got.Gen != 2 || got.RemoteLSN != 50 || len(got.Chunks) != 0 { + t.Fatalf("HEAD after refused CAS = %+v; want gen 2 at LSN 50", got) + } + for _, e := range f.allWritten() { + if len(e.GetChunks()) != 0 { + t.Fatalf("entry %s written with filer chunks", e.Name) + } + } +} + +// An absent HEAD has epoch 0; an expectation of gen 0 at another epoch can +// never match and must not create HEAD. +func TestChunkRemote_AbsentHeadOnlyMatchesZeroVersion(t *testing.T) { + ctx := context.Background() + f := newFakeFiler() + r := newTestRemote(t, f, newFakeBlobs()) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Epoch: 2}, head(2, "a", 1, nil)); !isPrecondition(err) { + t.Fatalf("CAS {0,2} on an absent HEAD: %v; want precondition", err) + } + if h, _ := r.GetHead(ctx); h.Gen != 0 { + t.Fatalf("HEAD created by a refused CAS: %+v", h) + } +} + +func TestChunkRemote_EpochNeverLowers(t *testing.T) { + ctx := context.Background() + r := newTestRemote(t, newFakeFiler(), newFakeBlobs()) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(5, "b", 1, nil)); err != nil { + t.Fatal(err) + } + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 5}, head(4, "a", 2, nil)); !isPrecondition(err) { + t.Fatalf("CAS lowering the epoch: %v; want precondition", err) + } + if h, _ := r.GetHead(ctx); h.Gen != 1 || h.Epoch != 5 || h.Holder != "b" { + t.Fatalf("HEAD after refused lowering = %+v", h) + } +} + +// A takeover raises the epoch; the old holder's next CAS, at the version +// it read, is refused (the chunk layer then fences). +func TestChunkRemote_TakeoverRefusesOldHolder(t *testing.T) { + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + a, nb := newTestRemote(t, f, b), newTestRemote(t, f, b) + if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "a", 1, nil)); err != nil { + t.Fatal(err) + } + if _, err := nb.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "b", 1, nil)); err != nil { + t.Fatal(err) + } + if _, err := a.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 9, nil)); !isPrecondition(err) { + t.Fatalf("old holder's CAS after takeover: %v; want precondition", err) + } +} + +// Only a definite refusal is a precondition failure. An error whose +// outcome is unknown must come back as something else, whether or not +// the update was applied, so the chunk layer re-reads HEAD. +func TestChunkRemote_UncertainCASIsNotPrecondition(t *testing.T) { + ctx := context.Background() + boom := errors.New("transport reset") + for _, applied := range []bool{false, true} { + f := newFakeFiler() + r := newTestRemote(t, f, newFakeBlobs()) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "a", 1, nil)); err != nil { + t.Fatal(err) + } + if applied { + f.failUpdateAfterApply = func(string) error { return boom } + } else { + f.failUpdate = func(string) error { return boom } + } + _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(1, "a", 2, nil)) + if err == nil || isPrecondition(err) || !errors.Is(err, boom) { + t.Fatalf("applied=%v: uncertain CAS returned %v; want the transport error, not a precondition", applied, err) + } + f.failUpdate, f.failUpdateAfterApply = nil, nil + h, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + if wantGen := map[bool]uint64{false: 1, true: 2}[applied]; h.Gen != wantGen { + t.Fatalf("applied=%v: HEAD re-read gen %d; want %d", applied, h.Gen, wantGen) + } + } +} + +func TestChunkRemote_KeysAreWriteOnce(t *testing.T) { + ctx := context.Background() + f, b := newFakeFiler(), newFakeBlobs() + r := newTestRemote(t, f, b) + first, second := []byte("first"), []byte("second") + if err := r.Put(ctx, "chunks/e1/c0/n-1", first); err != nil { + t.Fatal(err) + } + if err := r.Put(ctx, "chunks/e1/c0/n-1", second); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a key on the same client: %v; want ErrChunkKeyExists", err) + } + if puts, _, _ := b.counts(); puts != 1 { // a known key uploads no orphan needle + t.Fatalf("refused rebind on the same client stored %d needles; want 1", puts) + } + // A second client has no cache: the exclusive create is the authority. + other := newTestRemote(t, f, b) + if err := other.Put(ctx, "chunks/e1/c0/n-1", second); !errors.Is(err, storage.ErrChunkKeyExists) { + t.Fatalf("rebinding a key from another client: %v; want ErrChunkKeyExists", err) + } + for _, c := range []*ChunkRemote{r, other, newTestRemote(t, f, b)} { + got, err := c.Get(ctx, "chunks/e1/c0/n-1") + if err != nil || !bytes.Equal(got, first) { + t.Fatalf("Get after refused rebind = %q, %v; want %q", got, err, first) + } + } + if _, err := r.Get(ctx, "chunks/e1/c0/never"); err == nil { + t.Fatal("Get of an unbound key succeeded") + } + if err := r.Delete(ctx, "chunks/e1/c0/n-1"); !errors.Is(err, ErrDeleteUnsupported) { + t.Fatalf("Delete: %v; want ErrDeleteUnsupported", err) + } +} + +// A HEAD entry that exists but cannot be trusted is an error, never the +// zero HEAD (which would let a new holder start over the volume). +func TestChunkRemote_UntrustedHeadIsAnError(t *testing.T) { + ctx := context.Background() + cases := map[string]func(e *filerpb.Entry){ + "filer chunks": func(e *filerpb.Entry) { e.Chunks = []*filerpb.FileChunk{{FileId: "3,01"}} }, + "wrong kind": func(e *filerpb.Entry) { e.Extended[extKind] = []byte("head") }, + "gen disagrees": func(e *filerpb.Entry) { e.Extended[extGen] = []byte("9") }, + "epoch disagrees": func(e *filerpb.Entry) { e.Extended[extEpoch] = []byte("9") }, + "holder disagrees": func(e *filerpb.Entry) { e.Extended[extHolder] = []byte("z") }, + "not json": func(e *filerpb.Entry) { e.Content = []byte("{") }, + "no content": func(e *filerpb.Entry) { e.Content = nil }, + "generation 0": func(e *filerpb.Entry) { + e.Content = bytes.Replace(e.Content, []byte(`"gen":1`), []byte(`"gen":0`), 1) + e.Extended[extGen] = []byte("0") + }, + "bad chunk hash": func(e *filerpb.Entry) { + e.Content = bytes.Replace(e.Content, []byte(`"sha256":"`), []byte(`"sha256":"zz`), 1) + }, + "unsupported format": func(e *filerpb.Entry) { + e.Content = bytes.Replace(e.Content, []byte(`"format":1`), []byte(`"format":2`), 1) + }, + } + for name, corrupt := range cases { + t.Run(name, func(t *testing.T) { + f := newFakeFiler() + r := newTestRemote(t, f, newFakeBlobs()) + h := head(1, "a", 1, map[uint64]storage.ChunkRef{0: ref("k", []byte("x"))}) + if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, h); err != nil { + t.Fatal(err) + } + f.mu.Lock() + corrupt(f.entries[testRoot+"/"+headName]) + f.mu.Unlock() + got, err := r.GetHead(ctx) + if err == nil { + t.Fatalf("untrusted HEAD read as %+v", got) + } + }) + } +} + +// The chunk layer end to end over this remote: a host writes and captures, +// then a fresh host reads every block lazily from HEAD. +func TestChunkRemote_ChunkLayerCaptureThenFreshHost(t *testing.T) { + ctx := context.Background() + const blocks, chunkBlocks = 64, 8 + f, b := newFakeFiler(), newFakeBlobs() + dir := t.TempDir() + + attach := func(name string, fresh bool) (*storage.WALStore, storage.ChunkLayer) { + p := filepath.Join(dir, name) + s, err := storage.CreateWALStore(p, blocks, 4096) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatal(err) + } + r := newTestRemote(t, f, b) + l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ + ChunkBlocks: chunkBlocks, Epoch: 1, Holder: name, FreshFromHead: fresh, + Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap"), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s, l + } + + src, layer := attach("a", false) + want := map[uint32][]byte{} + for _, lba := range []uint32{0, 9, 17, 63} { + want[lba] = bytes.Repeat([]byte{byte(lba + 1)}, 4096) + if _, err := src.Write(lba, want[lba]); err != nil { + t.Fatal(err) + } + } + if _, err := src.Sync(); err != nil { + t.Fatal(err) + } + h, err := layer.Capture(ctx) + if err != nil { + t.Fatalf("Capture: %v", err) + } + if layer.RemoteLSN() != h { + t.Fatalf("RemoteLSN %d after capture at %d", layer.RemoteLSN(), h) + } + puts, _, _ := b.counts() + if puts != 4 { // chunks 0, 1, 2 and 7 + t.Fatalf("capture stored %d needles; want 4", puts) + } + _ = src.Close() + + dst, _ := attach("b", true) + zero := make([]byte, 4096) + for lba := uint32(0); lba < blocks; lba++ { + got, err := dst.Read(lba) + if err != nil { + t.Fatalf("fresh host read %d: %v", lba, err) + } + exp, ok := want[lba] + if !ok { + exp = zero + } + if !bytes.Equal(got, exp) { + t.Fatalf("fresh host block %d = %x...; want %x...", lba, got[:4], exp[:4]) + } + } + if _, gets, _ := b.counts(); gets != 4 { // each published chunk fetched once + t.Fatalf("fresh host fetched %d needles; want 4", gets) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/fake_test.go b/seaweed-block/core/frontend/chunkstore/fake_test.go new file mode 100644 index 0000000000..dbcca286fa --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/fake_test.go @@ -0,0 +1,144 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "fmt" + "path" + "sync" + + "google.golang.org/protobuf/proto" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// fakeFiler is an in-memory filer with the same precondition semantics as +// seaweed-mono's UpdateEntry (validateUpdateEntryPreconditions) and +// CreateEntry(o_excl). It records every entry ever written so tests can +// check that no HEAD or snapshot entry carries chunks. +type fakeFiler struct { + mu sync.Mutex + entries map[string]*filerpb.Entry + written []*filerpb.Entry + + // failUpdate, if set, is called before an UpdateEntry is applied; a + // non-nil return fails the call and the update is NOT applied. + failUpdate func(p string) error + // failUpdateAfterApply, if set, is called after an UpdateEntry was + // applied; a non-nil return is reported to the caller (ambiguous error). + failUpdateAfterApply func(p string) error + updates int +} + +func newFakeFiler() *fakeFiler { return &fakeFiler{entries: map[string]*filerpb.Entry{}} } + +func (f *fakeFiler) LookupEntry(_ context.Context, dir, name string) (*filerpb.Entry, error) { + f.mu.Lock() + defer f.mu.Unlock() + e, ok := f.entries[path.Join(dir, name)] + if !ok { + return nil, ErrNotFound + } + return proto.Clone(e).(*filerpb.Entry), nil +} + +func (f *fakeFiler) CreateEntry(_ context.Context, dir string, e *filerpb.Entry, oExcl bool) error { + f.mu.Lock() + defer f.mu.Unlock() + p := path.Join(dir, e.Name) + if _, ok := f.entries[p]; ok && oExcl { + return fmt.Errorf("%w: %s", ErrExists, p) + } + c := proto.Clone(e).(*filerpb.Entry) + f.entries[p] = c + f.written = append(f.written, proto.Clone(e).(*filerpb.Entry)) + return nil +} + +func (f *fakeFiler) UpdateEntry(_ context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + f.mu.Lock() + defer f.mu.Unlock() + p := path.Join(dir, e.Name) + if f.failUpdate != nil { + if err := f.failUpdate(p); err != nil { + return err + } + } + cur, ok := f.entries[p] + if !ok { + return fmt.Errorf("%w: %s", ErrNotFound, p) + } + for k, want := range expected { + got, has := cur.Extended[k] + if has && !bytes.Equal(got, want) || !has && len(want) > 0 { + return fmt.Errorf("%w: extended %q changed", ErrPrecondition, k) + } + } + f.entries[p] = proto.Clone(e).(*filerpb.Entry) + f.written = append(f.written, proto.Clone(e).(*filerpb.Entry)) + f.updates++ + if f.failUpdateAfterApply != nil { + if err := f.failUpdateAfterApply(p); err != nil { + return err + } + } + return nil +} + +// bumpExtended mutates a stored entry's extended key, as another writer would. +func (f *fakeFiler) bumpExtended(p, key, val string) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[p].Extended[key] = []byte(val) +} + +func (f *fakeFiler) allWritten() []*filerpb.Entry { + f.mu.Lock() + defer f.mu.Unlock() + return append([]*filerpb.Entry(nil), f.written...) +} + +// fakeBlobs is an in-memory needle store. +type fakeBlobs struct { + mu sync.Mutex + data map[string][]byte + next int + puts int + gets int + failPut func(n int) error +} + +func newFakeBlobs() *fakeBlobs { return &fakeBlobs{data: map[string][]byte{}} } + +func (b *fakeBlobs) Put(_ context.Context, d []byte) (string, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.puts++ + if b.failPut != nil { + if err := b.failPut(b.puts); err != nil { + return "", err + } + } + b.next++ + fid := fmt.Sprintf("3,%08x", b.next) + b.data[fid] = append([]byte(nil), d...) + return fid, nil +} + +func (b *fakeBlobs) Get(_ context.Context, fid string) ([]byte, error) { + b.mu.Lock() + defer b.mu.Unlock() + b.gets++ + d, ok := b.data[fid] + if !ok { + return nil, errors.New("fake: no such fid " + fid) + } + return append([]byte(nil), d...), nil +} + +func (b *fakeBlobs) counts() (puts, gets, stored int) { + b.mu.Lock() + defer b.mu.Unlock() + return b.puts, b.gets, len(b.data) +} diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go new file mode 100644 index 0000000000..50ab1f6a27 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go @@ -0,0 +1,1456 @@ +// Minimal subset of SeaweedFS filer.proto (seaweed-mono 8b582399d, +// enterprise/weed/pb/filer.proto) used by the chunkstore PoC client. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method paths (/filer_pb.SeaweedFiler/...) +// match a real filer. Fields chunkstore never reads or writes are omitted; +// protobuf keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative filer_subset.proto + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.6 +// protoc v7.34.1 +// source: filer_subset.proto + +package filerpb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type FilerError int32 + +const ( + FilerError_OK FilerError = 0 + FilerError_ENTRY_NAME_TOO_LONG FilerError = 1 + FilerError_PARENT_IS_FILE FilerError = 2 + FilerError_EXISTING_IS_DIRECTORY FilerError = 3 + FilerError_EXISTING_IS_FILE FilerError = 4 + FilerError_ENTRY_ALREADY_EXISTS FilerError = 5 + FilerError_PRECONDITION_FAILED FilerError = 6 + FilerError_READ_ONLY FilerError = 7 +) + +// Enum value maps for FilerError. +var ( + FilerError_name = map[int32]string{ + 0: "OK", + 1: "ENTRY_NAME_TOO_LONG", + 2: "PARENT_IS_FILE", + 3: "EXISTING_IS_DIRECTORY", + 4: "EXISTING_IS_FILE", + 5: "ENTRY_ALREADY_EXISTS", + 6: "PRECONDITION_FAILED", + 7: "READ_ONLY", + } + FilerError_value = map[string]int32{ + "OK": 0, + "ENTRY_NAME_TOO_LONG": 1, + "PARENT_IS_FILE": 2, + "EXISTING_IS_DIRECTORY": 3, + "EXISTING_IS_FILE": 4, + "ENTRY_ALREADY_EXISTS": 5, + "PRECONDITION_FAILED": 6, + "READ_ONLY": 7, + } +) + +func (x FilerError) Enum() *FilerError { + p := new(FilerError) + *p = x + return p +} + +func (x FilerError) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FilerError) Descriptor() protoreflect.EnumDescriptor { + return file_filer_subset_proto_enumTypes[0].Descriptor() +} + +func (FilerError) Type() protoreflect.EnumType { + return &file_filer_subset_proto_enumTypes[0] +} + +func (x FilerError) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use FilerError.Descriptor instead. +func (FilerError) EnumDescriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{0} +} + +type LookupDirectoryEntryRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LookupDirectoryEntryRequest) Reset() { + *x = LookupDirectoryEntryRequest{} + mi := &file_filer_subset_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LookupDirectoryEntryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LookupDirectoryEntryRequest) ProtoMessage() {} + +func (x *LookupDirectoryEntryRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LookupDirectoryEntryRequest.ProtoReflect.Descriptor instead. +func (*LookupDirectoryEntryRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{0} +} + +func (x *LookupDirectoryEntryRequest) GetDirectory() string { + if x != nil { + return x.Directory + } + return "" +} + +func (x *LookupDirectoryEntryRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type LookupDirectoryEntryResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Entry *Entry `protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LookupDirectoryEntryResponse) Reset() { + *x = LookupDirectoryEntryResponse{} + mi := &file_filer_subset_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LookupDirectoryEntryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LookupDirectoryEntryResponse) ProtoMessage() {} + +func (x *LookupDirectoryEntryResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LookupDirectoryEntryResponse.ProtoReflect.Descriptor instead. +func (*LookupDirectoryEntryResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{1} +} + +func (x *LookupDirectoryEntryResponse) GetEntry() *Entry { + if x != nil { + return x.Entry + } + return nil +} + +type Entry struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + IsDirectory bool `protobuf:"varint,2,opt,name=is_directory,json=isDirectory,proto3" json:"is_directory,omitempty"` + Chunks []*FileChunk `protobuf:"bytes,3,rep,name=chunks,proto3" json:"chunks,omitempty"` + Attributes *FuseAttributes `protobuf:"bytes,4,opt,name=attributes,proto3" json:"attributes,omitempty"` + Extended map[string][]byte `protobuf:"bytes,5,rep,name=extended,proto3" json:"extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Content []byte `protobuf:"bytes,9,opt,name=content,proto3" json:"content,omitempty"` // if not empty, the file content + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Entry) Reset() { + *x = Entry{} + mi := &file_filer_subset_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Entry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Entry) ProtoMessage() {} + +func (x *Entry) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Entry.ProtoReflect.Descriptor instead. +func (*Entry) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{2} +} + +func (x *Entry) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Entry) GetIsDirectory() bool { + if x != nil { + return x.IsDirectory + } + return false +} + +func (x *Entry) GetChunks() []*FileChunk { + if x != nil { + return x.Chunks + } + return nil +} + +func (x *Entry) GetAttributes() *FuseAttributes { + if x != nil { + return x.Attributes + } + return nil +} + +func (x *Entry) GetExtended() map[string][]byte { + if x != nil { + return x.Extended + } + return nil +} + +func (x *Entry) GetContent() []byte { + if x != nil { + return x.Content + } + return nil +} + +// Only file_id is modelled: chunkstore never writes chunks, and reads them +// only to refuse a HEAD entry that carries any. +type FileChunk struct { + state protoimpl.MessageState `protogen:"open.v1"` + FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FileChunk) Reset() { + *x = FileChunk{} + mi := &file_filer_subset_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FileChunk) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileChunk) ProtoMessage() {} + +func (x *FileChunk) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileChunk.ProtoReflect.Descriptor instead. +func (*FileChunk) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{3} +} + +func (x *FileChunk) GetFileId() string { + if x != nil { + return x.FileId + } + return "" +} + +type FuseAttributes struct { + state protoimpl.MessageState `protogen:"open.v1"` + FileSize uint64 `protobuf:"varint,1,opt,name=file_size,json=fileSize,proto3" json:"file_size,omitempty"` + Mtime int64 `protobuf:"varint,2,opt,name=mtime,proto3" json:"mtime,omitempty"` // unix time in seconds + FileMode uint32 `protobuf:"varint,3,opt,name=file_mode,json=fileMode,proto3" json:"file_mode,omitempty"` + Uid uint32 `protobuf:"varint,4,opt,name=uid,proto3" json:"uid,omitempty"` + Gid uint32 `protobuf:"varint,5,opt,name=gid,proto3" json:"gid,omitempty"` + Crtime int64 `protobuf:"varint,6,opt,name=crtime,proto3" json:"crtime,omitempty"` // unix time in seconds + Mime string `protobuf:"bytes,7,opt,name=mime,proto3" json:"mime,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FuseAttributes) Reset() { + *x = FuseAttributes{} + mi := &file_filer_subset_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FuseAttributes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FuseAttributes) ProtoMessage() {} + +func (x *FuseAttributes) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FuseAttributes.ProtoReflect.Descriptor instead. +func (*FuseAttributes) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{4} +} + +func (x *FuseAttributes) GetFileSize() uint64 { + if x != nil { + return x.FileSize + } + return 0 +} + +func (x *FuseAttributes) GetMtime() int64 { + if x != nil { + return x.Mtime + } + return 0 +} + +func (x *FuseAttributes) GetFileMode() uint32 { + if x != nil { + return x.FileMode + } + return 0 +} + +func (x *FuseAttributes) GetUid() uint32 { + if x != nil { + return x.Uid + } + return 0 +} + +func (x *FuseAttributes) GetGid() uint32 { + if x != nil { + return x.Gid + } + return 0 +} + +func (x *FuseAttributes) GetCrtime() int64 { + if x != nil { + return x.Crtime + } + return 0 +} + +func (x *FuseAttributes) GetMime() string { + if x != nil { + return x.Mime + } + return "" +} + +type CreateEntryRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"` + Entry *Entry `protobuf:"bytes,2,opt,name=entry,proto3" json:"entry,omitempty"` + OExcl bool `protobuf:"varint,3,opt,name=o_excl,json=oExcl,proto3" json:"o_excl,omitempty"` + IsFromOtherCluster bool `protobuf:"varint,4,opt,name=is_from_other_cluster,json=isFromOtherCluster,proto3" json:"is_from_other_cluster,omitempty"` + Signatures []int32 `protobuf:"varint,5,rep,packed,name=signatures,proto3" json:"signatures,omitempty"` + SkipCheckParentDirectory bool `protobuf:"varint,6,opt,name=skip_check_parent_directory,json=skipCheckParentDirectory,proto3" json:"skip_check_parent_directory,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateEntryRequest) Reset() { + *x = CreateEntryRequest{} + mi := &file_filer_subset_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateEntryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateEntryRequest) ProtoMessage() {} + +func (x *CreateEntryRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateEntryRequest.ProtoReflect.Descriptor instead. +func (*CreateEntryRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{5} +} + +func (x *CreateEntryRequest) GetDirectory() string { + if x != nil { + return x.Directory + } + return "" +} + +func (x *CreateEntryRequest) GetEntry() *Entry { + if x != nil { + return x.Entry + } + return nil +} + +func (x *CreateEntryRequest) GetOExcl() bool { + if x != nil { + return x.OExcl + } + return false +} + +func (x *CreateEntryRequest) GetIsFromOtherCluster() bool { + if x != nil { + return x.IsFromOtherCluster + } + return false +} + +func (x *CreateEntryRequest) GetSignatures() []int32 { + if x != nil { + return x.Signatures + } + return nil +} + +func (x *CreateEntryRequest) GetSkipCheckParentDirectory() bool { + if x != nil { + return x.SkipCheckParentDirectory + } + return false +} + +type CreateEntryResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` + ErrorCode FilerError `protobuf:"varint,3,opt,name=error_code,json=errorCode,proto3,enum=filer_pb.FilerError" json:"error_code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateEntryResponse) Reset() { + *x = CreateEntryResponse{} + mi := &file_filer_subset_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateEntryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateEntryResponse) ProtoMessage() {} + +func (x *CreateEntryResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateEntryResponse.ProtoReflect.Descriptor instead. +func (*CreateEntryResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{6} +} + +func (x *CreateEntryResponse) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +func (x *CreateEntryResponse) GetErrorCode() FilerError { + if x != nil { + return x.ErrorCode + } + return FilerError_OK +} + +type UpdateEntryRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"` + Entry *Entry `protobuf:"bytes,2,opt,name=entry,proto3" json:"entry,omitempty"` + IsFromOtherCluster bool `protobuf:"varint,3,opt,name=is_from_other_cluster,json=isFromOtherCluster,proto3" json:"is_from_other_cluster,omitempty"` + Signatures []int32 `protobuf:"varint,4,rep,packed,name=signatures,proto3" json:"signatures,omitempty"` + ExpectedExtended map[string][]byte `protobuf:"bytes,5,rep,name=expected_extended,json=expectedExtended,proto3" json:"expected_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateEntryRequest) Reset() { + *x = UpdateEntryRequest{} + mi := &file_filer_subset_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateEntryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateEntryRequest) ProtoMessage() {} + +func (x *UpdateEntryRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateEntryRequest.ProtoReflect.Descriptor instead. +func (*UpdateEntryRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{7} +} + +func (x *UpdateEntryRequest) GetDirectory() string { + if x != nil { + return x.Directory + } + return "" +} + +func (x *UpdateEntryRequest) GetEntry() *Entry { + if x != nil { + return x.Entry + } + return nil +} + +func (x *UpdateEntryRequest) GetIsFromOtherCluster() bool { + if x != nil { + return x.IsFromOtherCluster + } + return false +} + +func (x *UpdateEntryRequest) GetSignatures() []int32 { + if x != nil { + return x.Signatures + } + return nil +} + +func (x *UpdateEntryRequest) GetExpectedExtended() map[string][]byte { + if x != nil { + return x.ExpectedExtended + } + return nil +} + +type UpdateEntryResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateEntryResponse) Reset() { + *x = UpdateEntryResponse{} + mi := &file_filer_subset_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateEntryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateEntryResponse) ProtoMessage() {} + +func (x *UpdateEntryResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateEntryResponse.ProtoReflect.Descriptor instead. +func (*UpdateEntryResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{8} +} + +type DeleteEntryRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Directory string `protobuf:"bytes,1,opt,name=directory,proto3" json:"directory,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + IsDeleteData bool `protobuf:"varint,4,opt,name=is_delete_data,json=isDeleteData,proto3" json:"is_delete_data,omitempty"` + IsRecursive bool `protobuf:"varint,5,opt,name=is_recursive,json=isRecursive,proto3" json:"is_recursive,omitempty"` + ExpectedExtended map[string][]byte `protobuf:"bytes,12,rep,name=expected_extended,json=expectedExtended,proto3" json:"expected_extended,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteEntryRequest) Reset() { + *x = DeleteEntryRequest{} + mi := &file_filer_subset_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteEntryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteEntryRequest) ProtoMessage() {} + +func (x *DeleteEntryRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteEntryRequest.ProtoReflect.Descriptor instead. +func (*DeleteEntryRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{9} +} + +func (x *DeleteEntryRequest) GetDirectory() string { + if x != nil { + return x.Directory + } + return "" +} + +func (x *DeleteEntryRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *DeleteEntryRequest) GetIsDeleteData() bool { + if x != nil { + return x.IsDeleteData + } + return false +} + +func (x *DeleteEntryRequest) GetIsRecursive() bool { + if x != nil { + return x.IsRecursive + } + return false +} + +func (x *DeleteEntryRequest) GetExpectedExtended() map[string][]byte { + if x != nil { + return x.ExpectedExtended + } + return nil +} + +type DeleteEntryResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteEntryResponse) Reset() { + *x = DeleteEntryResponse{} + mi := &file_filer_subset_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteEntryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteEntryResponse) ProtoMessage() {} + +func (x *DeleteEntryResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteEntryResponse.ProtoReflect.Descriptor instead. +func (*DeleteEntryResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{10} +} + +func (x *DeleteEntryResponse) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +type AssignVolumeRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Count int32 `protobuf:"varint,1,opt,name=count,proto3" json:"count,omitempty"` + Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"` + Replication string `protobuf:"bytes,3,opt,name=replication,proto3" json:"replication,omitempty"` + TtlSec int32 `protobuf:"varint,4,opt,name=ttl_sec,json=ttlSec,proto3" json:"ttl_sec,omitempty"` + DataCenter string `protobuf:"bytes,5,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"` + Path string `protobuf:"bytes,6,opt,name=path,proto3" json:"path,omitempty"` + Rack string `protobuf:"bytes,7,opt,name=rack,proto3" json:"rack,omitempty"` + DiskType string `protobuf:"bytes,8,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"` + DataNode string `protobuf:"bytes,9,opt,name=data_node,json=dataNode,proto3" json:"data_node,omitempty"` + ExpectedDataSize uint64 `protobuf:"varint,10,opt,name=expected_data_size,json=expectedDataSize,proto3" json:"expected_data_size,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AssignVolumeRequest) Reset() { + *x = AssignVolumeRequest{} + mi := &file_filer_subset_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AssignVolumeRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AssignVolumeRequest) ProtoMessage() {} + +func (x *AssignVolumeRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AssignVolumeRequest.ProtoReflect.Descriptor instead. +func (*AssignVolumeRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{11} +} + +func (x *AssignVolumeRequest) GetCount() int32 { + if x != nil { + return x.Count + } + return 0 +} + +func (x *AssignVolumeRequest) GetCollection() string { + if x != nil { + return x.Collection + } + return "" +} + +func (x *AssignVolumeRequest) GetReplication() string { + if x != nil { + return x.Replication + } + return "" +} + +func (x *AssignVolumeRequest) GetTtlSec() int32 { + if x != nil { + return x.TtlSec + } + return 0 +} + +func (x *AssignVolumeRequest) GetDataCenter() string { + if x != nil { + return x.DataCenter + } + return "" +} + +func (x *AssignVolumeRequest) GetPath() string { + if x != nil { + return x.Path + } + return "" +} + +func (x *AssignVolumeRequest) GetRack() string { + if x != nil { + return x.Rack + } + return "" +} + +func (x *AssignVolumeRequest) GetDiskType() string { + if x != nil { + return x.DiskType + } + return "" +} + +func (x *AssignVolumeRequest) GetDataNode() string { + if x != nil { + return x.DataNode + } + return "" +} + +func (x *AssignVolumeRequest) GetExpectedDataSize() uint64 { + if x != nil { + return x.ExpectedDataSize + } + return 0 +} + +type AssignVolumeResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + Count int32 `protobuf:"varint,4,opt,name=count,proto3" json:"count,omitempty"` + Auth string `protobuf:"bytes,5,opt,name=auth,proto3" json:"auth,omitempty"` + Collection string `protobuf:"bytes,6,opt,name=collection,proto3" json:"collection,omitempty"` + Replication string `protobuf:"bytes,7,opt,name=replication,proto3" json:"replication,omitempty"` + Error string `protobuf:"bytes,8,opt,name=error,proto3" json:"error,omitempty"` + Location *Location `protobuf:"bytes,9,opt,name=location,proto3" json:"location,omitempty"` + Replicas []*Location `protobuf:"bytes,10,rep,name=replicas,proto3" json:"replicas,omitempty"` + Fsync bool `protobuf:"varint,11,opt,name=fsync,proto3" json:"fsync,omitempty"` + ErrorCode FilerError `protobuf:"varint,12,opt,name=error_code,json=errorCode,proto3,enum=filer_pb.FilerError" json:"error_code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AssignVolumeResponse) Reset() { + *x = AssignVolumeResponse{} + mi := &file_filer_subset_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AssignVolumeResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AssignVolumeResponse) ProtoMessage() {} + +func (x *AssignVolumeResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AssignVolumeResponse.ProtoReflect.Descriptor instead. +func (*AssignVolumeResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{12} +} + +func (x *AssignVolumeResponse) GetFileId() string { + if x != nil { + return x.FileId + } + return "" +} + +func (x *AssignVolumeResponse) GetCount() int32 { + if x != nil { + return x.Count + } + return 0 +} + +func (x *AssignVolumeResponse) GetAuth() string { + if x != nil { + return x.Auth + } + return "" +} + +func (x *AssignVolumeResponse) GetCollection() string { + if x != nil { + return x.Collection + } + return "" +} + +func (x *AssignVolumeResponse) GetReplication() string { + if x != nil { + return x.Replication + } + return "" +} + +func (x *AssignVolumeResponse) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +func (x *AssignVolumeResponse) GetLocation() *Location { + if x != nil { + return x.Location + } + return nil +} + +func (x *AssignVolumeResponse) GetReplicas() []*Location { + if x != nil { + return x.Replicas + } + return nil +} + +func (x *AssignVolumeResponse) GetFsync() bool { + if x != nil { + return x.Fsync + } + return false +} + +func (x *AssignVolumeResponse) GetErrorCode() FilerError { + if x != nil { + return x.ErrorCode + } + return FilerError_OK +} + +type LookupVolumeRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + VolumeIds []string `protobuf:"bytes,1,rep,name=volume_ids,json=volumeIds,proto3" json:"volume_ids,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LookupVolumeRequest) Reset() { + *x = LookupVolumeRequest{} + mi := &file_filer_subset_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LookupVolumeRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LookupVolumeRequest) ProtoMessage() {} + +func (x *LookupVolumeRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LookupVolumeRequest.ProtoReflect.Descriptor instead. +func (*LookupVolumeRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{13} +} + +func (x *LookupVolumeRequest) GetVolumeIds() []string { + if x != nil { + return x.VolumeIds + } + return nil +} + +type Locations struct { + state protoimpl.MessageState `protogen:"open.v1"` + Locations []*Location `protobuf:"bytes,1,rep,name=locations,proto3" json:"locations,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Locations) Reset() { + *x = Locations{} + mi := &file_filer_subset_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Locations) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Locations) ProtoMessage() {} + +func (x *Locations) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Locations.ProtoReflect.Descriptor instead. +func (*Locations) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{14} +} + +func (x *Locations) GetLocations() []*Location { + if x != nil { + return x.Locations + } + return nil +} + +type Location struct { + state protoimpl.MessageState `protogen:"open.v1"` + Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"` + PublicUrl string `protobuf:"bytes,2,opt,name=public_url,json=publicUrl,proto3" json:"public_url,omitempty"` + GrpcPort uint32 `protobuf:"varint,3,opt,name=grpc_port,json=grpcPort,proto3" json:"grpc_port,omitempty"` + DataCenter string `protobuf:"bytes,4,opt,name=data_center,json=dataCenter,proto3" json:"data_center,omitempty"` + DataInRemote bool `protobuf:"varint,5,opt,name=data_in_remote,json=dataInRemote,proto3" json:"data_in_remote,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Location) Reset() { + *x = Location{} + mi := &file_filer_subset_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Location) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Location) ProtoMessage() {} + +func (x *Location) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Location.ProtoReflect.Descriptor instead. +func (*Location) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{15} +} + +func (x *Location) GetUrl() string { + if x != nil { + return x.Url + } + return "" +} + +func (x *Location) GetPublicUrl() string { + if x != nil { + return x.PublicUrl + } + return "" +} + +func (x *Location) GetGrpcPort() uint32 { + if x != nil { + return x.GrpcPort + } + return 0 +} + +func (x *Location) GetDataCenter() string { + if x != nil { + return x.DataCenter + } + return "" +} + +func (x *Location) GetDataInRemote() bool { + if x != nil { + return x.DataInRemote + } + return false +} + +type LookupVolumeResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + LocationsMap map[string]*Locations `protobuf:"bytes,1,rep,name=locations_map,json=locationsMap,proto3" json:"locations_map,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LookupVolumeResponse) Reset() { + *x = LookupVolumeResponse{} + mi := &file_filer_subset_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LookupVolumeResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LookupVolumeResponse) ProtoMessage() {} + +func (x *LookupVolumeResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LookupVolumeResponse.ProtoReflect.Descriptor instead. +func (*LookupVolumeResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{16} +} + +func (x *LookupVolumeResponse) GetLocationsMap() map[string]*Locations { + if x != nil { + return x.LocationsMap + } + return nil +} + +var File_filer_subset_proto protoreflect.FileDescriptor + +const file_filer_subset_proto_rawDesc = "" + + "\n" + + "\x12filer_subset.proto\x12\bfiler_pb\"O\n" + + "\x1bLookupDirectoryEntryRequest\x12\x1c\n" + + "\tdirectory\x18\x01 \x01(\tR\tdirectory\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\"E\n" + + "\x1cLookupDirectoryEntryResponse\x12%\n" + + "\x05entry\x18\x01 \x01(\v2\x0f.filer_pb.EntryR\x05entry\"\xb7\x02\n" + + "\x05Entry\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12!\n" + + "\fis_directory\x18\x02 \x01(\bR\visDirectory\x12+\n" + + "\x06chunks\x18\x03 \x03(\v2\x13.filer_pb.FileChunkR\x06chunks\x128\n" + + "\n" + + "attributes\x18\x04 \x01(\v2\x18.filer_pb.FuseAttributesR\n" + + "attributes\x129\n" + + "\bextended\x18\x05 \x03(\v2\x1d.filer_pb.Entry.ExtendedEntryR\bextended\x12\x18\n" + + "\acontent\x18\t \x01(\fR\acontent\x1a;\n" + + "\rExtendedEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"$\n" + + "\tFileChunk\x12\x17\n" + + "\afile_id\x18\x01 \x01(\tR\x06fileId\"\xb0\x01\n" + + "\x0eFuseAttributes\x12\x1b\n" + + "\tfile_size\x18\x01 \x01(\x04R\bfileSize\x12\x14\n" + + "\x05mtime\x18\x02 \x01(\x03R\x05mtime\x12\x1b\n" + + "\tfile_mode\x18\x03 \x01(\rR\bfileMode\x12\x10\n" + + "\x03uid\x18\x04 \x01(\rR\x03uid\x12\x10\n" + + "\x03gid\x18\x05 \x01(\rR\x03gid\x12\x16\n" + + "\x06crtime\x18\x06 \x01(\x03R\x06crtime\x12\x12\n" + + "\x04mime\x18\a \x01(\tR\x04mime\"\x82\x02\n" + + "\x12CreateEntryRequest\x12\x1c\n" + + "\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" + + "\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x12\x15\n" + + "\x06o_excl\x18\x03 \x01(\bR\x05oExcl\x121\n" + + "\x15is_from_other_cluster\x18\x04 \x01(\bR\x12isFromOtherCluster\x12\x1e\n" + + "\n" + + "signatures\x18\x05 \x03(\x05R\n" + + "signatures\x12=\n" + + "\x1bskip_check_parent_directory\x18\x06 \x01(\bR\x18skipCheckParentDirectory\"`\n" + + "\x13CreateEntryResponse\x12\x14\n" + + "\x05error\x18\x01 \x01(\tR\x05error\x123\n" + + "\n" + + "error_code\x18\x03 \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"\xd2\x02\n" + + "\x12UpdateEntryRequest\x12\x1c\n" + + "\tdirectory\x18\x01 \x01(\tR\tdirectory\x12%\n" + + "\x05entry\x18\x02 \x01(\v2\x0f.filer_pb.EntryR\x05entry\x121\n" + + "\x15is_from_other_cluster\x18\x03 \x01(\bR\x12isFromOtherCluster\x12\x1e\n" + + "\n" + + "signatures\x18\x04 \x03(\x05R\n" + + "signatures\x12_\n" + + "\x11expected_extended\x18\x05 \x03(\v22.filer_pb.UpdateEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x1aC\n" + + "\x15ExpectedExtendedEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"\x15\n" + + "\x13UpdateEntryResponse\"\xb5\x02\n" + + "\x12DeleteEntryRequest\x12\x1c\n" + + "\tdirectory\x18\x01 \x01(\tR\tdirectory\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\x12$\n" + + "\x0eis_delete_data\x18\x04 \x01(\bR\fisDeleteData\x12!\n" + + "\fis_recursive\x18\x05 \x01(\bR\visRecursive\x12_\n" + + "\x11expected_extended\x18\f \x03(\v22.filer_pb.DeleteEntryRequest.ExpectedExtendedEntryR\x10expectedExtended\x1aC\n" + + "\x15ExpectedExtendedEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\fR\x05value:\x028\x01\"+\n" + + "\x13DeleteEntryResponse\x12\x14\n" + + "\x05error\x18\x01 \x01(\tR\x05error\"\xb7\x02\n" + + "\x13AssignVolumeRequest\x12\x14\n" + + "\x05count\x18\x01 \x01(\x05R\x05count\x12\x1e\n" + + "\n" + + "collection\x18\x02 \x01(\tR\n" + + "collection\x12 \n" + + "\vreplication\x18\x03 \x01(\tR\vreplication\x12\x17\n" + + "\attl_sec\x18\x04 \x01(\x05R\x06ttlSec\x12\x1f\n" + + "\vdata_center\x18\x05 \x01(\tR\n" + + "dataCenter\x12\x12\n" + + "\x04path\x18\x06 \x01(\tR\x04path\x12\x12\n" + + "\x04rack\x18\a \x01(\tR\x04rack\x12\x1b\n" + + "\tdisk_type\x18\b \x01(\tR\bdiskType\x12\x1b\n" + + "\tdata_node\x18\t \x01(\tR\bdataNode\x12,\n" + + "\x12expected_data_size\x18\n" + + " \x01(\x04R\x10expectedDataSize\"\xdc\x02\n" + + "\x14AssignVolumeResponse\x12\x17\n" + + "\afile_id\x18\x01 \x01(\tR\x06fileId\x12\x14\n" + + "\x05count\x18\x04 \x01(\x05R\x05count\x12\x12\n" + + "\x04auth\x18\x05 \x01(\tR\x04auth\x12\x1e\n" + + "\n" + + "collection\x18\x06 \x01(\tR\n" + + "collection\x12 \n" + + "\vreplication\x18\a \x01(\tR\vreplication\x12\x14\n" + + "\x05error\x18\b \x01(\tR\x05error\x12.\n" + + "\blocation\x18\t \x01(\v2\x12.filer_pb.LocationR\blocation\x12.\n" + + "\breplicas\x18\n" + + " \x03(\v2\x12.filer_pb.LocationR\breplicas\x12\x14\n" + + "\x05fsync\x18\v \x01(\bR\x05fsync\x123\n" + + "\n" + + "error_code\x18\f \x01(\x0e2\x14.filer_pb.FilerErrorR\terrorCode\"4\n" + + "\x13LookupVolumeRequest\x12\x1d\n" + + "\n" + + "volume_ids\x18\x01 \x03(\tR\tvolumeIds\"=\n" + + "\tLocations\x120\n" + + "\tlocations\x18\x01 \x03(\v2\x12.filer_pb.LocationR\tlocations\"\x9f\x01\n" + + "\bLocation\x12\x10\n" + + "\x03url\x18\x01 \x01(\tR\x03url\x12\x1d\n" + + "\n" + + "public_url\x18\x02 \x01(\tR\tpublicUrl\x12\x1b\n" + + "\tgrpc_port\x18\x03 \x01(\rR\bgrpcPort\x12\x1f\n" + + "\vdata_center\x18\x04 \x01(\tR\n" + + "dataCenter\x12$\n" + + "\x0edata_in_remote\x18\x05 \x01(\bR\fdataInRemote\"\xc3\x01\n" + + "\x14LookupVolumeResponse\x12U\n" + + "\rlocations_map\x18\x01 \x03(\v20.filer_pb.LookupVolumeResponse.LocationsMapEntryR\flocationsMap\x1aT\n" + + "\x11LocationsMapEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12)\n" + + "\x05value\x18\x02 \x01(\v2\x13.filer_pb.LocationsR\x05value:\x028\x01*\xb4\x01\n" + + "\n" + + "FilerError\x12\x06\n" + + "\x02OK\x10\x00\x12\x17\n" + + "\x13ENTRY_NAME_TOO_LONG\x10\x01\x12\x12\n" + + "\x0ePARENT_IS_FILE\x10\x02\x12\x19\n" + + "\x15EXISTING_IS_DIRECTORY\x10\x03\x12\x14\n" + + "\x10EXISTING_IS_FILE\x10\x04\x12\x18\n" + + "\x14ENTRY_ALREADY_EXISTS\x10\x05\x12\x17\n" + + "\x13PRECONDITION_FAILED\x10\x06\x12\r\n" + + "\tREAD_ONLY\x10\a2\x83\x04\n" + + "\fSeaweedFiler\x12g\n" + + "\x14LookupDirectoryEntry\x12%.filer_pb.LookupDirectoryEntryRequest\x1a&.filer_pb.LookupDirectoryEntryResponse\"\x00\x12L\n" + + "\vCreateEntry\x12\x1c.filer_pb.CreateEntryRequest\x1a\x1d.filer_pb.CreateEntryResponse\"\x00\x12L\n" + + "\vUpdateEntry\x12\x1c.filer_pb.UpdateEntryRequest\x1a\x1d.filer_pb.UpdateEntryResponse\"\x00\x12L\n" + + "\vDeleteEntry\x12\x1c.filer_pb.DeleteEntryRequest\x1a\x1d.filer_pb.DeleteEntryResponse\"\x00\x12O\n" + + "\fAssignVolume\x12\x1d.filer_pb.AssignVolumeRequest\x1a\x1e.filer_pb.AssignVolumeResponse\"\x00\x12O\n" + + "\fLookupVolume\x12\x1d.filer_pb.LookupVolumeRequest\x1a\x1e.filer_pb.LookupVolumeResponse\"\x00BEZCgithub.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpbb\x06proto3" + +var ( + file_filer_subset_proto_rawDescOnce sync.Once + file_filer_subset_proto_rawDescData []byte +) + +func file_filer_subset_proto_rawDescGZIP() []byte { + file_filer_subset_proto_rawDescOnce.Do(func() { + file_filer_subset_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_filer_subset_proto_rawDesc), len(file_filer_subset_proto_rawDesc))) + }) + return file_filer_subset_proto_rawDescData +} + +var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 21) +var file_filer_subset_proto_goTypes = []any{ + (FilerError)(0), // 0: filer_pb.FilerError + (*LookupDirectoryEntryRequest)(nil), // 1: filer_pb.LookupDirectoryEntryRequest + (*LookupDirectoryEntryResponse)(nil), // 2: filer_pb.LookupDirectoryEntryResponse + (*Entry)(nil), // 3: filer_pb.Entry + (*FileChunk)(nil), // 4: filer_pb.FileChunk + (*FuseAttributes)(nil), // 5: filer_pb.FuseAttributes + (*CreateEntryRequest)(nil), // 6: filer_pb.CreateEntryRequest + (*CreateEntryResponse)(nil), // 7: filer_pb.CreateEntryResponse + (*UpdateEntryRequest)(nil), // 8: filer_pb.UpdateEntryRequest + (*UpdateEntryResponse)(nil), // 9: filer_pb.UpdateEntryResponse + (*DeleteEntryRequest)(nil), // 10: filer_pb.DeleteEntryRequest + (*DeleteEntryResponse)(nil), // 11: filer_pb.DeleteEntryResponse + (*AssignVolumeRequest)(nil), // 12: filer_pb.AssignVolumeRequest + (*AssignVolumeResponse)(nil), // 13: filer_pb.AssignVolumeResponse + (*LookupVolumeRequest)(nil), // 14: filer_pb.LookupVolumeRequest + (*Locations)(nil), // 15: filer_pb.Locations + (*Location)(nil), // 16: filer_pb.Location + (*LookupVolumeResponse)(nil), // 17: filer_pb.LookupVolumeResponse + nil, // 18: filer_pb.Entry.ExtendedEntry + nil, // 19: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry + nil, // 20: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry + nil, // 21: filer_pb.LookupVolumeResponse.LocationsMapEntry +} +var file_filer_subset_proto_depIdxs = []int32{ + 3, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry + 4, // 1: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk + 5, // 2: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes + 18, // 3: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry + 3, // 4: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry + 0, // 5: filer_pb.CreateEntryResponse.error_code:type_name -> filer_pb.FilerError + 3, // 6: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry + 19, // 7: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry + 20, // 8: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry + 16, // 9: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location + 16, // 10: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location + 0, // 11: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError + 16, // 12: filer_pb.Locations.locations:type_name -> filer_pb.Location + 21, // 13: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry + 15, // 14: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations + 1, // 15: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest + 6, // 16: filer_pb.SeaweedFiler.CreateEntry:input_type -> filer_pb.CreateEntryRequest + 8, // 17: filer_pb.SeaweedFiler.UpdateEntry:input_type -> filer_pb.UpdateEntryRequest + 10, // 18: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest + 12, // 19: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest + 14, // 20: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest + 2, // 21: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse + 7, // 22: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse + 9, // 23: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse + 11, // 24: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse + 13, // 25: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse + 17, // 26: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse + 21, // [21:27] is the sub-list for method output_type + 15, // [15:21] is the sub-list for method input_type + 15, // [15:15] is the sub-list for extension type_name + 15, // [15:15] is the sub-list for extension extendee + 0, // [0:15] is the sub-list for field type_name +} + +func init() { file_filer_subset_proto_init() } +func file_filer_subset_proto_init() { + if File_filer_subset_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_subset_proto_rawDesc), len(file_filer_subset_proto_rawDesc)), + NumEnums: 1, + NumMessages: 21, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_filer_subset_proto_goTypes, + DependencyIndexes: file_filer_subset_proto_depIdxs, + EnumInfos: file_filer_subset_proto_enumTypes, + MessageInfos: file_filer_subset_proto_msgTypes, + }.Build() + File_filer_subset_proto = out.File + file_filer_subset_proto_goTypes = nil + file_filer_subset_proto_depIdxs = nil +} diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto new file mode 100644 index 0000000000..dcb62a2495 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto @@ -0,0 +1,153 @@ +// Minimal subset of SeaweedFS filer.proto (seaweed-mono 8b582399d, +// enterprise/weed/pb/filer.proto) used by the chunkstore PoC client. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method paths (/filer_pb.SeaweedFiler/...) +// match a real filer. Fields chunkstore never reads or writes are omitted; +// protobuf keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative filer_subset.proto +syntax = "proto3"; + +package filer_pb; + +option go_package = "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"; + +service SeaweedFiler { + rpc LookupDirectoryEntry (LookupDirectoryEntryRequest) returns (LookupDirectoryEntryResponse) {} + rpc CreateEntry (CreateEntryRequest) returns (CreateEntryResponse) {} + rpc UpdateEntry (UpdateEntryRequest) returns (UpdateEntryResponse) {} + rpc DeleteEntry (DeleteEntryRequest) returns (DeleteEntryResponse) {} + rpc AssignVolume (AssignVolumeRequest) returns (AssignVolumeResponse) {} + rpc LookupVolume (LookupVolumeRequest) returns (LookupVolumeResponse) {} +} + +message LookupDirectoryEntryRequest { + string directory = 1; + string name = 2; +} + +message LookupDirectoryEntryResponse { + Entry entry = 1; +} + +message Entry { + string name = 1; + bool is_directory = 2; + repeated FileChunk chunks = 3; + FuseAttributes attributes = 4; + map extended = 5; + bytes content = 9; // if not empty, the file content +} + +// Only file_id is modelled: chunkstore never writes chunks, and reads them +// only to refuse a HEAD entry that carries any. +message FileChunk { + string file_id = 1; +} + +message FuseAttributes { + uint64 file_size = 1; + int64 mtime = 2; // unix time in seconds + uint32 file_mode = 3; + uint32 uid = 4; + uint32 gid = 5; + int64 crtime = 6; // unix time in seconds + string mime = 7; +} + +message CreateEntryRequest { + string directory = 1; + Entry entry = 2; + bool o_excl = 3; + bool is_from_other_cluster = 4; + repeated int32 signatures = 5; + bool skip_check_parent_directory = 6; +} + +enum FilerError { + OK = 0; + ENTRY_NAME_TOO_LONG = 1; + PARENT_IS_FILE = 2; + EXISTING_IS_DIRECTORY = 3; + EXISTING_IS_FILE = 4; + ENTRY_ALREADY_EXISTS = 5; + PRECONDITION_FAILED = 6; + READ_ONLY = 7; +} + +message CreateEntryResponse { + string error = 1; + FilerError error_code = 3; +} + +message UpdateEntryRequest { + string directory = 1; + Entry entry = 2; + bool is_from_other_cluster = 3; + repeated int32 signatures = 4; + map expected_extended = 5; +} + +message UpdateEntryResponse { +} + +message DeleteEntryRequest { + string directory = 1; + string name = 2; + bool is_delete_data = 4; + bool is_recursive = 5; + map expected_extended = 12; +} + +message DeleteEntryResponse { + string error = 1; +} + +message AssignVolumeRequest { + int32 count = 1; + string collection = 2; + string replication = 3; + int32 ttl_sec = 4; + string data_center = 5; + string path = 6; + string rack = 7; + string disk_type = 8; + string data_node = 9; + uint64 expected_data_size = 10; +} + +message AssignVolumeResponse { + string file_id = 1; + int32 count = 4; + string auth = 5; + string collection = 6; + string replication = 7; + string error = 8; + Location location = 9; + repeated Location replicas = 10; + bool fsync = 11; + FilerError error_code = 12; +} + +message LookupVolumeRequest { + repeated string volume_ids = 1; +} + +message Locations { + repeated Location locations = 1; +} + +message Location { + string url = 1; + string public_url = 2; + uint32 grpc_port = 3; + string data_center = 4; + bool data_in_remote = 5; +} + +message LookupVolumeResponse { + map locations_map = 1; +} diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go new file mode 100644 index 0000000000..b8a9cbb606 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go @@ -0,0 +1,323 @@ +// Minimal subset of SeaweedFS filer.proto (seaweed-mono 8b582399d, +// enterprise/weed/pb/filer.proto) used by the chunkstore PoC client. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method paths (/filer_pb.SeaweedFiler/...) +// match a real filer. Fields chunkstore never reads or writes are omitted; +// protobuf keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative filer_subset.proto + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.2 +// - protoc v7.34.1 +// source: filer_subset.proto + +package filerpb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + SeaweedFiler_LookupDirectoryEntry_FullMethodName = "/filer_pb.SeaweedFiler/LookupDirectoryEntry" + SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry" + SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry" + SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry" + SeaweedFiler_AssignVolume_FullMethodName = "/filer_pb.SeaweedFiler/AssignVolume" + SeaweedFiler_LookupVolume_FullMethodName = "/filer_pb.SeaweedFiler/LookupVolume" +) + +// SeaweedFilerClient is the client API for SeaweedFiler service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type SeaweedFilerClient interface { + LookupDirectoryEntry(ctx context.Context, in *LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*LookupDirectoryEntryResponse, error) + CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error) + UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error) + DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error) + AssignVolume(ctx context.Context, in *AssignVolumeRequest, opts ...grpc.CallOption) (*AssignVolumeResponse, error) + LookupVolume(ctx context.Context, in *LookupVolumeRequest, opts ...grpc.CallOption) (*LookupVolumeResponse, error) +} + +type seaweedFilerClient struct { + cc grpc.ClientConnInterface +} + +func NewSeaweedFilerClient(cc grpc.ClientConnInterface) SeaweedFilerClient { + return &seaweedFilerClient{cc} +} + +func (c *seaweedFilerClient) LookupDirectoryEntry(ctx context.Context, in *LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*LookupDirectoryEntryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(LookupDirectoryEntryResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_LookupDirectoryEntry_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *seaweedFilerClient) CreateEntry(ctx context.Context, in *CreateEntryRequest, opts ...grpc.CallOption) (*CreateEntryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CreateEntryResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_CreateEntry_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *seaweedFilerClient) UpdateEntry(ctx context.Context, in *UpdateEntryRequest, opts ...grpc.CallOption) (*UpdateEntryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(UpdateEntryResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_UpdateEntry_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *seaweedFilerClient) DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DeleteEntryResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_DeleteEntry_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *seaweedFilerClient) AssignVolume(ctx context.Context, in *AssignVolumeRequest, opts ...grpc.CallOption) (*AssignVolumeResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(AssignVolumeResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_AssignVolume_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *seaweedFilerClient) LookupVolume(ctx context.Context, in *LookupVolumeRequest, opts ...grpc.CallOption) (*LookupVolumeResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(LookupVolumeResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_LookupVolume_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// SeaweedFilerServer is the server API for SeaweedFiler service. +// All implementations must embed UnimplementedSeaweedFilerServer +// for forward compatibility. +type SeaweedFilerServer interface { + LookupDirectoryEntry(context.Context, *LookupDirectoryEntryRequest) (*LookupDirectoryEntryResponse, error) + CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error) + UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) + DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error) + AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error) + LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) + mustEmbedUnimplementedSeaweedFilerServer() +} + +// UnimplementedSeaweedFilerServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedSeaweedFilerServer struct{} + +func (UnimplementedSeaweedFilerServer) LookupDirectoryEntry(context.Context, *LookupDirectoryEntryRequest) (*LookupDirectoryEntryResponse, error) { + return nil, status.Error(codes.Unimplemented, "method LookupDirectoryEntry not implemented") +} +func (UnimplementedSeaweedFilerServer) CreateEntry(context.Context, *CreateEntryRequest) (*CreateEntryResponse, error) { + return nil, status.Error(codes.Unimplemented, "method CreateEntry not implemented") +} +func (UnimplementedSeaweedFilerServer) UpdateEntry(context.Context, *UpdateEntryRequest) (*UpdateEntryResponse, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateEntry not implemented") +} +func (UnimplementedSeaweedFilerServer) DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error) { + return nil, status.Error(codes.Unimplemented, "method DeleteEntry not implemented") +} +func (UnimplementedSeaweedFilerServer) AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error) { + return nil, status.Error(codes.Unimplemented, "method AssignVolume not implemented") +} +func (UnimplementedSeaweedFilerServer) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) { + return nil, status.Error(codes.Unimplemented, "method LookupVolume not implemented") +} +func (UnimplementedSeaweedFilerServer) mustEmbedUnimplementedSeaweedFilerServer() {} +func (UnimplementedSeaweedFilerServer) testEmbeddedByValue() {} + +// UnsafeSeaweedFilerServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SeaweedFilerServer will +// result in compilation errors. +type UnsafeSeaweedFilerServer interface { + mustEmbedUnimplementedSeaweedFilerServer() +} + +func RegisterSeaweedFilerServer(s grpc.ServiceRegistrar, srv SeaweedFilerServer) { + // If the following call panics, it indicates UnimplementedSeaweedFilerServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&SeaweedFiler_ServiceDesc, srv) +} + +func _SeaweedFiler_LookupDirectoryEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LookupDirectoryEntryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).LookupDirectoryEntry(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_LookupDirectoryEntry_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).LookupDirectoryEntry(ctx, req.(*LookupDirectoryEntryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SeaweedFiler_CreateEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateEntryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).CreateEntry(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_CreateEntry_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).CreateEntry(ctx, req.(*CreateEntryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SeaweedFiler_UpdateEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateEntryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).UpdateEntry(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_UpdateEntry_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).UpdateEntry(ctx, req.(*UpdateEntryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SeaweedFiler_DeleteEntry_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeleteEntryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).DeleteEntry(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_DeleteEntry_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).DeleteEntry(ctx, req.(*DeleteEntryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SeaweedFiler_AssignVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AssignVolumeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).AssignVolume(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_AssignVolume_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).AssignVolume(ctx, req.(*AssignVolumeRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SeaweedFiler_LookupVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LookupVolumeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).LookupVolume(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_LookupVolume_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).LookupVolume(ctx, req.(*LookupVolumeRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// SeaweedFiler_ServiceDesc is the grpc.ServiceDesc for SeaweedFiler service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "filer_pb.SeaweedFiler", + HandlerType: (*SeaweedFilerServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "LookupDirectoryEntry", + Handler: _SeaweedFiler_LookupDirectoryEntry_Handler, + }, + { + MethodName: "CreateEntry", + Handler: _SeaweedFiler_CreateEntry_Handler, + }, + { + MethodName: "UpdateEntry", + Handler: _SeaweedFiler_UpdateEntry_Handler, + }, + { + MethodName: "DeleteEntry", + Handler: _SeaweedFiler_DeleteEntry_Handler, + }, + { + MethodName: "AssignVolume", + Handler: _SeaweedFiler_AssignVolume_Handler, + }, + { + MethodName: "LookupVolume", + Handler: _SeaweedFiler_LookupVolume_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "filer_subset.proto", +} diff --git a/seaweed-block/core/frontend/chunkstore/remote.go b/seaweed-block/core/frontend/chunkstore/remote.go new file mode 100644 index 0000000000..12f8717dd7 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/remote.go @@ -0,0 +1,45 @@ +package chunkstore + +import ( + "context" + "errors" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// Filer is the metadata side chunkstore needs from a SeaweedFS filer: one +// entry per volume HEAD (and per snapshot), written with a precondition. +// +// The two SeaweedFS failure styles are normalised here: +// - CreateEntry reports a failed o_excl / condition in the response's +// ErrorCode with a nil gRPC error; +// - UpdateEntry reports a failed expected_extended as gRPC FailedPrecondition. +// +// Both become ErrExists / ErrPrecondition so callers branch on one thing. +type Filer interface { + // LookupEntry returns ErrNotFound when dir/name does not exist. + LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) + // CreateEntry with oExcl returns ErrExists when dir/name already exists. + CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error + // UpdateEntry applies e only if every expected extended key still holds + // the given value; otherwise ErrPrecondition. ErrNotFound if absent. + UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error +} + +// Blobs stores immutable chunk payloads as SeaweedFS needles. +type Blobs interface { + // Put stores data as a new needle and returns its fid. A fid is never + // reused, so a Put can never overwrite data another manifest references. + Put(ctx context.Context, data []byte) (fid string, err error) + // Get returns the whole needle payload. + Get(ctx context.Context, fid string) ([]byte, error) +} + +var ( + // ErrNotFound: the filer entry does not exist. + ErrNotFound = errors.New("chunkstore: entry not found") + // ErrExists: an exclusive create found the entry already there. + ErrExists = errors.New("chunkstore: entry already exists") + // ErrPrecondition: a conditional write lost (HEAD changed under us). + ErrPrecondition = errors.New("chunkstore: precondition failed") +) diff --git a/seaweed-block/core/frontend/chunkstore/swfs.go b/seaweed-block/core/frontend/chunkstore/swfs.go new file mode 100644 index 0000000000..eb7707a860 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs.go @@ -0,0 +1,265 @@ +package chunkstore + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// SWFSConfig configures the minimal SeaweedFS client. +type SWFSConfig struct { + FilerGRPC string // filer gRPC address, host:port (default: filer HTTP port + 10000) + Collection string // collection for chunk needles (empty = filer default / storage rule) + Replication string // replication for chunk needles (empty = filer default / storage rule) + AssignPath string // path passed to AssignVolume so filer storage rules (fsync, collection) apply + HTTPTimeout time.Duration +} + +// SWFS is a minimal SeaweedFS client built for the chunkstore PoC: +// - filer gRPC (vendored proto subset, package filerpb) for HEAD/snapshot +// entries, AssignVolume and LookupVolume; +// - plain HTTP to volume servers for needle upload (POST) and read (GET). +// +// It deliberately does not import the SeaweedFS module. +type SWFS struct { + cfg SWFSConfig + conn *grpc.ClientConn + fc filerpb.SeaweedFilerClient + http *http.Client + + mu sync.Mutex + vidCache map[string][]string // volume id -> volume server urls +} + +// filerNotFoundText is the text of seaweed-mono's filer_pb.ErrNotFound +// (pb/filer_pb/filer_pb_helper.go:261). LookupDirectoryEntry returns that raw +// sentinel, which crosses gRPC as codes.Unknown carrying only this text. +const filerNotFoundText = "no entry is found in filer store" + +// DialSWFS connects to the filer's gRPC port. The connection is lazy. +func DialSWFS(cfg SWFSConfig) (*SWFS, error) { + if cfg.FilerGRPC == "" { + return nil, errors.New("chunkstore: filer gRPC address required") + } + if cfg.HTTPTimeout == 0 { + cfg.HTTPTimeout = 60 * time.Second + } + conn, err := grpc.NewClient(cfg.FilerGRPC, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(64<<20), grpc.MaxCallSendMsgSize(64<<20))) + if err != nil { + return nil, fmt.Errorf("chunkstore: dial filer %s: %w", cfg.FilerGRPC, err) + } + return &SWFS{ + cfg: cfg, + conn: conn, + fc: filerpb.NewSeaweedFilerClient(conn), + http: &http.Client{Timeout: cfg.HTTPTimeout}, + vidCache: map[string][]string{}, + }, nil +} + +// Close releases the gRPC connection. +func (c *SWFS) Close() error { + if c.conn == nil { + return nil + } + return c.conn.Close() +} + +// LookupEntry implements Filer. +func (c *SWFS) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) { + resp, err := c.fc.LookupDirectoryEntry(ctx, &filerpb.LookupDirectoryEntryRequest{Directory: dir, Name: name}) + if err != nil { + if st, ok := status.FromError(err); ok { + if st.Code() == codes.NotFound || + (st.Code() == codes.Unknown && strings.Contains(st.Message(), filerNotFoundText)) { + return nil, ErrNotFound + } + } + return nil, fmt.Errorf("chunkstore: lookup %s/%s: %w", dir, name, err) + } + if resp.GetEntry() == nil { + return nil, ErrNotFound + } + return resp.Entry, nil +} + +// CreateEntry implements Filer. A failed o_excl or condition is reported by +// the filer in CreateEntryResponse.ErrorCode with a nil gRPC error. +func (c *SWFS) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error { + resp, err := c.fc.CreateEntry(ctx, &filerpb.CreateEntryRequest{Directory: dir, Entry: e, OExcl: oExcl}) + if err != nil { + if status.Code(err) == codes.FailedPrecondition { + return fmt.Errorf("%w: create %s/%s: %v", ErrPrecondition, dir, e.GetName(), err) + } + return fmt.Errorf("chunkstore: create %s/%s: %w", dir, e.GetName(), err) + } + switch resp.GetErrorCode() { + case filerpb.FilerError_OK: + if resp.GetError() != "" { + return fmt.Errorf("chunkstore: create %s/%s: %s", dir, e.GetName(), resp.GetError()) + } + return nil + case filerpb.FilerError_ENTRY_ALREADY_EXISTS: + return fmt.Errorf("%w: %s/%s", ErrExists, dir, e.GetName()) + case filerpb.FilerError_PRECONDITION_FAILED: + return fmt.Errorf("%w: create %s/%s", ErrPrecondition, dir, e.GetName()) + default: + return fmt.Errorf("chunkstore: create %s/%s: %s (%s)", dir, e.GetName(), resp.GetError(), resp.GetErrorCode()) + } +} + +// UpdateEntry implements Filer. A failed expected_extended comes back as gRPC +// FailedPrecondition. Any other error is ambiguous (the write may or may not +// have applied) and is returned unwrapped from the sentinels. +func (c *SWFS) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error { + _, err := c.fc.UpdateEntry(ctx, &filerpb.UpdateEntryRequest{Directory: dir, Entry: e, ExpectedExtended: expected}) + if err == nil { + return nil + } + switch status.Code(err) { + case codes.FailedPrecondition: + return fmt.Errorf("%w: update %s/%s: %v", ErrPrecondition, dir, e.GetName(), err) + case codes.NotFound: + return fmt.Errorf("%w: update %s/%s", ErrNotFound, dir, e.GetName()) + } + return fmt.Errorf("chunkstore: update %s/%s: %w", dir, e.GetName(), err) +} + +// Put implements Blobs: filer AssignVolume, then a raw HTTP POST of data to +// the assigned volume server. The body is sent as application/octet-stream +// with no Content-Encoding, so the volume server stores it uncompressed (its +// auto-compress only fires for types it is sure about; octet-stream is +// cleared to "" first, storage/needle/needle_parse_upload.go:116-119). +func (c *SWFS) Put(ctx context.Context, data []byte) (string, error) { + ar, err := c.fc.AssignVolume(ctx, &filerpb.AssignVolumeRequest{ + Count: 1, + Collection: c.cfg.Collection, + Replication: c.cfg.Replication, + Path: c.cfg.AssignPath, + ExpectedDataSize: uint64(len(data)), + }) + if err != nil { + return "", fmt.Errorf("chunkstore: assign: %w", err) + } + if ar.GetError() != "" { + return "", fmt.Errorf("chunkstore: assign: %s", ar.GetError()) + } + if ar.GetFileId() == "" || ar.GetLocation().GetUrl() == "" { + return "", fmt.Errorf("chunkstore: assign returned no fid/location") + } + u := "http://" + ar.Location.Url + "/" + ar.FileId + if ar.GetFsync() { + u += "?fsync=true" + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data)) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/octet-stream") + if ar.GetAuth() != "" { + req.Header.Set("Authorization", "BEARER "+ar.Auth) + } + resp, err := c.http.Do(req) + if err != nil { + return "", fmt.Errorf("chunkstore: upload %s: %w", ar.FileId, err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + if resp.StatusCode/100 != 2 { + return "", fmt.Errorf("chunkstore: upload %s: http %d: %s", ar.FileId, resp.StatusCode, strings.TrimSpace(string(body))) + } + var ur struct { + Error string `json:"error"` + } + if json.Unmarshal(body, &ur) == nil && ur.Error != "" { + return "", fmt.Errorf("chunkstore: upload %s: %s", ar.FileId, ur.Error) + } + return ar.FileId, nil +} + +// Get implements Blobs: resolve the fid's volume through the filer, then GET +// the needle from each location until one answers. +func (c *SWFS) Get(ctx context.Context, fid string) ([]byte, error) { + vid, _, ok := strings.Cut(fid, ",") + if !ok { + return nil, fmt.Errorf("chunkstore: bad fid %q", fid) + } + urls, err := c.lookupVolume(ctx, vid) + if err != nil { + return nil, err + } + var lastErr error + for _, host := range urls { + b, err := c.getFrom(ctx, host, fid) + if err == nil { + return b, nil + } + lastErr = err + } + c.mu.Lock() + delete(c.vidCache, vid) + c.mu.Unlock() + return nil, fmt.Errorf("chunkstore: read %s: %w", fid, lastErr) +} + +func (c *SWFS) getFrom(ctx context.Context, host, fid string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+host+"/"+fid, nil) + if err != nil { + return nil, err + } + resp, err := c.http.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("http %d from %s", resp.StatusCode, host) + } + return io.ReadAll(resp.Body) +} + +func (c *SWFS) lookupVolume(ctx context.Context, vid string) ([]string, error) { + c.mu.Lock() + urls, ok := c.vidCache[vid] + c.mu.Unlock() + if ok && len(urls) > 0 { + return urls, nil + } + resp, err := c.fc.LookupVolume(ctx, &filerpb.LookupVolumeRequest{VolumeIds: []string{vid}}) + if err != nil { + return nil, fmt.Errorf("chunkstore: lookup volume %s: %w", vid, err) + } + for _, l := range resp.GetLocationsMap()[vid].GetLocations() { + if l.GetUrl() != "" { + urls = append(urls, l.Url) + } + } + if len(urls) == 0 { + return nil, fmt.Errorf("chunkstore: volume %s has no locations", vid) + } + c.mu.Lock() + c.vidCache[vid] = urls + c.mu.Unlock() + return urls, nil +} + +var ( + _ Filer = (*SWFS)(nil) + _ Blobs = (*SWFS)(nil) +) diff --git a/seaweed-block/core/frontend/chunkstore/swfs_test.go b/seaweed-block/core/frontend/chunkstore/swfs_test.go new file mode 100644 index 0000000000..748681e3a8 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/swfs_test.go @@ -0,0 +1,270 @@ +package chunkstore + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// fakeFilerGRPC answers the real gRPC method paths with canned replies so the +// client's error mapping is tested against both SeaweedFS failure styles. +type fakeFilerGRPC struct { + filerpb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + createResp *filerpb.CreateEntryResponse + createErr error + updateErr error + lookupResp *filerpb.LookupDirectoryEntryResponse + lookupErr error + assignResp *filerpb.AssignVolumeResponse + lookupVol *filerpb.LookupVolumeResponse + + lastCreate *filerpb.CreateEntryRequest + lastUpdate *filerpb.UpdateEntryRequest + lastAssign *filerpb.AssignVolumeRequest +} + +func (f *fakeFilerGRPC) CreateEntry(_ context.Context, r *filerpb.CreateEntryRequest) (*filerpb.CreateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.lastCreate = r + if f.createErr != nil { + return nil, f.createErr + } + if f.createResp != nil { + return f.createResp, nil + } + return &filerpb.CreateEntryResponse{}, nil +} + +func (f *fakeFilerGRPC) UpdateEntry(_ context.Context, r *filerpb.UpdateEntryRequest) (*filerpb.UpdateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.lastUpdate = r + if f.updateErr != nil { + return nil, f.updateErr + } + return &filerpb.UpdateEntryResponse{}, nil +} + +func (f *fakeFilerGRPC) LookupDirectoryEntry(_ context.Context, r *filerpb.LookupDirectoryEntryRequest) (*filerpb.LookupDirectoryEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.lookupErr != nil { + return nil, f.lookupErr + } + return f.lookupResp, nil +} + +func (f *fakeFilerGRPC) AssignVolume(_ context.Context, r *filerpb.AssignVolumeRequest) (*filerpb.AssignVolumeResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.lastAssign = r + return f.assignResp, nil +} + +func (f *fakeFilerGRPC) LookupVolume(_ context.Context, r *filerpb.LookupVolumeRequest) (*filerpb.LookupVolumeResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + return f.lookupVol, nil +} + +func startFakeFiler(t *testing.T, f *fakeFilerGRPC) *SWFS { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + c, err := DialSWFS(SWFSConfig{FilerGRPC: lis.Addr().String(), Collection: "swblock", Replication: "000", AssignPath: "/swblock/vols/v1"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = c.Close() }) + return c +} + +func TestSWFS_CreateEntry_ErrorCodeStyle(t *testing.T) { + f := &fakeFilerGRPC{} + c := startFakeFiler(t, f) + ctx := context.Background() + + // CreateEntry reports o_excl loss in ErrorCode with a nil gRPC error + // (seaweed-mono server/filer_grpc_server.go CreateEntry). + f.createResp = &filerpb.CreateEntryResponse{Error: "exists", ErrorCode: filerpb.FilerError_ENTRY_ALREADY_EXISTS} + err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true) + if !errors.Is(err, ErrExists) { + t.Fatalf("ENTRY_ALREADY_EXISTS: got %v want ErrExists", err) + } + if !f.lastCreate.OExcl { + t.Fatalf("o_excl not sent") + } + + f.createResp = &filerpb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filerpb.FilerError_PRECONDITION_FAILED} + if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); !errors.Is(err, ErrPrecondition) { + t.Fatalf("PRECONDITION_FAILED: got %v want ErrPrecondition", err) + } + + // Any other non-empty Error is still a failure, never silent success. + f.createResp = &filerpb.CreateEntryResponse{Error: "parent is a file", ErrorCode: filerpb.FilerError_PARENT_IS_FILE} + if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); err == nil { + t.Fatalf("PARENT_IS_FILE: got nil error") + } + + f.createResp = &filerpb.CreateEntryResponse{} + if err := c.CreateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, true); err != nil { + t.Fatalf("ok create: %v", err) + } +} + +func TestSWFS_UpdateEntry_FailedPreconditionStyle(t *testing.T) { + f := &fakeFilerGRPC{} + c := startFakeFiler(t, f) + ctx := context.Background() + exp := map[string][]byte{"swb.gen": []byte("3"), "swb.epoch": []byte("1")} + + f.updateErr = status.Error(codes.FailedPrecondition, `extended attribute "swb.gen" changed`) + if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); !errors.Is(err, ErrPrecondition) { + t.Fatalf("FailedPrecondition: got %v want ErrPrecondition", err) + } + if string(f.lastUpdate.ExpectedExtended["swb.gen"]) != "3" || string(f.lastUpdate.ExpectedExtended["swb.epoch"]) != "1" { + t.Fatalf("expected_extended not sent: %v", f.lastUpdate.ExpectedExtended) + } + + f.updateErr = status.Error(codes.NotFound, "not found /d/x") + if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); !errors.Is(err, ErrNotFound) { + t.Fatalf("NotFound: got %v want ErrNotFound", err) + } + + f.updateErr = status.Error(codes.Unavailable, "down") + err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp) + if err == nil || errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { + t.Fatalf("Unavailable: got %v, want a plain (ambiguous) error", err) + } + + f.updateErr = nil + if err := c.UpdateEntry(ctx, "/d", &filerpb.Entry{Name: "x"}, exp); err != nil { + t.Fatalf("ok update: %v", err) + } +} + +func TestSWFS_LookupEntry_NotFoundStyles(t *testing.T) { + f := &fakeFilerGRPC{} + c := startFakeFiler(t, f) + ctx := context.Background() + + // The filer returns its raw sentinel, which crosses gRPC as Unknown. + f.lookupErr = errors.New("filer: no entry is found in filer store") + if _, err := c.LookupEntry(ctx, "/d", "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("Unknown+sentinel: got %v want ErrNotFound", err) + } + f.lookupErr = status.Error(codes.NotFound, "nope") + if _, err := c.LookupEntry(ctx, "/d", "x"); !errors.Is(err, ErrNotFound) { + t.Fatalf("NotFound: got %v want ErrNotFound", err) + } + f.lookupErr = nil + f.lookupResp = &filerpb.LookupDirectoryEntryResponse{Entry: &filerpb.Entry{Name: "x", Content: []byte("m")}} + e, err := c.LookupEntry(ctx, "/d", "x") + if err != nil || string(e.Content) != "m" { + t.Fatalf("found: %v %v", e, err) + } +} + +func TestSWFS_PutGet_RawUncompressedUpload(t *testing.T) { + var ( + mu sync.Mutex + stored = map[string][]byte{} + gotReq *http.Request + ) + vol := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fid := strings.TrimPrefix(r.URL.Path, "/") + mu.Lock() + defer mu.Unlock() + switch r.Method { + case http.MethodPost: + gotReq = r.Clone(context.Background()) + b, _ := io.ReadAll(r.Body) + stored[fid] = b + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"size":` + "1" + `}`)) + case http.MethodGet: + b, ok := stored[fid] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write(b) + } + })) + defer vol.Close() + host := strings.TrimPrefix(vol.URL, "http://") + + f := &fakeFilerGRPC{ + assignResp: &filerpb.AssignVolumeResponse{FileId: "7,01abcdef", Auth: "tok", Fsync: true, Location: &filerpb.Location{Url: host}}, + lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}}, + } + c := startFakeFiler(t, f) + ctx := context.Background() + // Text-looking data: must still go up raw (no gzip, no type sniffing). + data := bytes.Repeat([]byte("hello world\n"), 1000) + fid, err := c.Put(ctx, data) + if err != nil { + t.Fatal(err) + } + if fid != "7,01abcdef" { + t.Fatalf("fid %q", fid) + } + if f.lastAssign.Collection != "swblock" || f.lastAssign.Path != "/swblock/vols/v1" || f.lastAssign.Count != 1 { + t.Fatalf("assign request %+v", f.lastAssign) + } + mu.Lock() + r := gotReq + mu.Unlock() + if r.URL.Query().Get("fsync") != "true" { + t.Fatalf("fsync not carried onto upload: %s", r.URL.RawQuery) + } + if ct := r.Header.Get("Content-Type"); ct != "application/octet-stream" { + t.Fatalf("content-type %q", ct) + } + if ce := r.Header.Get("Content-Encoding"); ce != "" { + t.Fatalf("content-encoding %q, want none", ce) + } + if a := r.Header.Get("Authorization"); a != "BEARER tok" { + t.Fatalf("authorization %q", a) + } + got, err := c.Get(ctx, fid) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, data) { + t.Fatalf("get mismatch") + } + if _, err := c.Get(ctx, "7,0000dead"); err == nil { + t.Fatalf("get of missing fid returned nil error") + } +} + +func TestSWFS_Put_AssignErrorIsFailure(t *testing.T) { + f := &fakeFilerGRPC{assignResp: &filerpb.AssignVolumeResponse{Error: "no free volumes"}} + c := startFakeFiler(t, f) + if _, err := c.Put(context.Background(), []byte("x")); err == nil { + t.Fatalf("assign error swallowed") + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 7542300741..087fcdadb3 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. @@ -123,12 +146,37 @@ type DurableProvider struct { volumes map[string]*volHandle // keyed by volumeID opening map[string]*sync.Mutex // keyed by volumeID; serializes open/create closed bool + + // walstore-chunk: closeCtx ends with Close and cancels in-flight + // remote attachment; inflight counts RecoverVolume calls admitted + // before Close, which Close waits for before closing any store. + closeCtx context.Context + closeCancel context.CancelFunc + inflight sync.WaitGroup } type volHandle struct { storage storage.LogicalStorage backend *StorageBackend path string + + // ImplWALStoreChunk. fresh: the local volume is new and starts from + // the remote HEAD. It mirrors the durable fresh marker beside the + // volume file, written before the file is created and removed only + // after the first attach succeeded, so an interrupted initialization + // is still fresh after a restart. + fresh bool + attachMu sync.Mutex // serializes recovery and attach of this volume + // recoverGen numbers this volume's RecoverVolume calls (written under + // attachMu and p.mu). waitGen is the generation of the live authority + // wait, 0 if none: a recovered volume whose layer waits for master + // authority. A wait only acts while its generation is still the + // latest recovery's. + recoverGen uint64 + waitGen uint64 + chunk storage.ChunkLayer // after RecoverVolume + chunkStop context.CancelFunc + chunkDone chan struct{} } // VolumeStatus is a read-only diagnostic snapshot of one durable volume @@ -162,9 +210,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 @@ -175,11 +229,14 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if err := os.MkdirAll(cfg.StorageRoot, 0o755); err != nil { return nil, fmt.Errorf("durable: mkdir %s: %w", cfg.StorageRoot, err) } + closeCtx, closeCancel := context.WithCancel(context.Background()) return &DurableProvider{ - cfg: cfg, - view: view, - volumes: map[string]*volHandle{}, - opening: map[string]*sync.Mutex{}, + cfg: cfg, + view: view, + volumes: map[string]*volHandle{}, + opening: map[string]*sync.Mutex{}, + closeCtx: closeCtx, + closeCancel: closeCancel, }, nil } @@ -437,9 +494,28 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { if err := p.verifyImplOnDisk(path); err != nil { return nil, err } - return p.openExisting(volumeID, path) + h, err := p.openExisting(volumeID, path) + if err != nil || p.cfg.Impl != ImplWALStoreChunk { + return h, err + } + if h.fresh, err = fileExists(chunkFreshMarker(path)); err != nil { + _ = h.storage.Close() + return nil, fmt.Errorf("durable: stat fresh marker: %w", err) + } + return h, nil } - return p.createFresh(volumeID, path) + if p.cfg.Impl == ImplWALStoreChunk { + // Durable before the volume file exists: a crash anywhere between + // here and the first successful attach leaves a fresh volume. + if err := writeChunkFreshMarker(path); err != nil { + return nil, err + } + } + h, err := p.createFresh(volumeID, path) + if err == nil && p.cfg.Impl == ImplWALStoreChunk { + h.fresh = true + } + return h, err } // verifyImplOnDisk peeks the 4-byte magic at offset 0 and returns @@ -469,6 +545,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 +575,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 +621,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) @@ -604,15 +683,46 @@ func (p *DurableProvider) wrap(volumeID, path string, s storage.LogicalStorage) func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (RecoveryReport, error) { p.mu.Lock() h, ok := p.volumes[volumeID] + // Close empties p.volumes under the same lock that sets closed, so a + // handle found here was admitted before Close; Close waits for it. + chunked := ok && p.cfg.Impl == ImplWALStoreChunk + if chunked { + p.inflight.Add(1) + } p.mu.Unlock() if !ok { return RecoveryReport{VolumeID: volumeID}, ErrVolumeNotOpen } + var gen uint64 + if chunked { + defer p.inflight.Done() + h.attachMu.Lock() + defer h.attachMu.Unlock() + p.mu.Lock() + h.recoverGen++ // any earlier recovery's authority wait is now stale + gen = h.recoverGen + p.mu.Unlock() + } report := Recover(h.storage, volumeID) if report.Err != nil { h.backend.SetOperational(false, report.Evidence) return report, report.Err } + if chunked { + attached, err := p.recoverChunk(ctx, volumeID, h, gen) + if err != nil { + h.backend.SetOperational(false, "chunk layer attach failed: "+err.Error()) + report.Err = err + return report, err + } + if !attached { + // Recovered; I/O stays refused until the layer attaches under + // the master's assignment (the authority wait flips it). + report.Evidence += "; chunk layer awaiting master authority" + h.backend.SetOperational(false, report.Evidence) + return report, nil + } + } h.backend.SetOperational(true, report.Evidence) return report, nil } @@ -630,9 +740,15 @@ func (p *DurableProvider) Close() error { handles := p.volumes p.volumes = map[string]*volHandle{} p.mu.Unlock() + // walstore-chunk: cancel remote attachment and let every admitted + // recovery settle (it sees closed and publishes nothing) before any + // store is closed. + p.closeCancel() + p.inflight.Wait() 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..0b2b55cfe7 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -0,0 +1,409 @@ +package durable + +// walstore-chunk: attaching the storage chunk layer to a provider volume. + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "path/filepath" + "runtime" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "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") + +// ErrChunkAwaitingAuthority is returned by the chunk operations for a +// recovered volume whose layer is not attached yet because the master's +// assignment is not visible in the projection. +var ErrChunkAwaitingAuthority = errors.New("durable: chunk layer awaiting master authority") + +var ( + errProviderClosed = errors.New("durable: provider closed") + errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer") +) + +const ( + // chunkAuthorityPoll is how often a volume awaiting authority checks + // the projection. + chunkAuthorityPoll = 20 * time.Millisecond + // chunkAttachTimeout bounds one deferred attach attempt; a failed + // attempt is retried after chunkAttachRetry. + chunkAttachTimeout = 30 * time.Second + chunkAttachRetry = time.Second +) + +// chunkLineage is the authority a chunk layer publishes under: the +// projection identity at attach time. Every capture admission requires the +// current projection to be healthy and to carry this same lineage; a moved +// lineage refuses the cut instead of publishing under the old epoch. +type chunkLineage struct { + volumeID, replicaID string + epoch, endpoint uint64 +} + +// chunkAuthority: the projection names this volume, is healthy and carries +// a master-assigned epoch. Before the master's assignment is applied (the +// host blocks it until local recovery is done) the projection has epoch 0 +// and is not healthy; a layer is never attached under that. +func chunkAuthority(proj frontend.Projection, volumeID string) bool { + return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 +} + +// recoverChunk runs after a successful local Recover, generation gen. It +// attaches the layer when the projection already carries master authority +// and reports true. Otherwise it starts an authority wait bound to gen +// (which attaches as soon as the assignment is applied) and reports +// false: the volume is recovered but stays non-operational until then. +// The caller holds h.attachMu and is registered with Close. +func (p *DurableProvider) recoverChunk(ctx context.Context, volumeID string, h *volHandle, gen uint64) (bool, error) { + err := p.attachChunk(ctx, volumeID, h) + if errors.Is(err, errChunkNoAuthority) { + p.startChunkAuthorityWait(volumeID, h, gen) + return false, nil + } + return err == nil, err +} + +// startChunkAuthorityWait starts the authority wait of recovery gen, +// registered with Close like a recovery. A wait of an earlier recovery +// sees it is stale and exits on its own. +func (p *DurableProvider) startChunkAuthorityWait(volumeID string, h *volHandle, gen uint64) { + p.mu.Lock() + defer p.mu.Unlock() + if p.closed || h.waitGen == gen { + return + } + h.waitGen = gen + p.inflight.Add(1) + go p.chunkAuthorityWait(volumeID, h, gen) +} + +// current reports whether gen is still the latest recovery of h. +func (p *DurableProvider) current(h *volHandle, gen uint64) bool { + p.mu.Lock() + defer p.mu.Unlock() + return h.recoverGen == gen +} + +func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen uint64) { + defer p.inflight.Done() + defer func() { + p.mu.Lock() + if h.waitGen == gen { + h.waitGen = 0 + } + p.mu.Unlock() + }() + t := time.NewTicker(chunkAuthorityPoll) + defer t.Stop() + for { + select { + case <-p.closeCtx.Done(): + return + case <-t.C: + } + if !p.current(h, gen) { + return // a later recovery (successful or failed) owns the volume + } + if !chunkAuthority(p.view.Projection(), volumeID) { + continue + } + h.attachMu.Lock() + if !p.current(h, gen) { // re-checked under the per-volume serialization + h.attachMu.Unlock() + return + } + ctx, cancel := context.WithTimeout(p.closeCtx, chunkAttachTimeout) + err := p.attachChunk(ctx, volumeID, h) + cancel() + if err == nil { + h.backend.SetOperational(true, "chunk layer attached under master authority") + } + h.attachMu.Unlock() + switch { + case err == nil, errors.Is(err, errProviderClosed): + return + case errors.Is(err, errChunkNoAuthority): + continue + } + log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err) + select { + case <-p.closeCtx.Done(): + return + case <-time.After(chunkAttachRetry): + } + } +} + +// attachChunk attaches the chunk layer once, under the projection's +// master authority, then retires the fresh marker. The caller holds +// h.attachMu and is registered with Close. ctx bounds the attach's remote +// calls (with provider Close); it does not bound the attached layer. +func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *volHandle) error { + p.mu.Lock() + layer := h.chunk + p.mu.Unlock() + if layer == nil { + var err error + if layer, err = p.newChunkLayer(ctx, volumeID, h); err != nil { + return err + } + p.mu.Lock() + if p.closed { + // Not published: the store still owns the layer and closes it + // in WALStore.Close, which Close runs after this call settles. + p.mu.Unlock() + return errProviderClosed + } + h.chunk = layer + if p.cfg.ChunkCaptureInterval > 0 { + ctx, cancel := context.WithCancel(context.Background()) + h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + go p.chunkLoop(ctx, volumeID, layer, h.chunkDone) + } + p.mu.Unlock() + } + if h.fresh { + // The attach persisted the absence of every HEAD chunk; only now + // may a restart treat the local volume as authoritative. + if err := removeChunkFreshMarker(h.path); err != nil { + return err + } + h.fresh = false + } + return nil +} + +func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { + ws, ok := h.storage.(*storage.WALStore) + if !ok { + return nil, fmt.Errorf("durable: %s storage is %T, not a walstore", ImplWALStoreChunk, h.storage) + } + proj := p.view.Projection() + if !chunkAuthority(proj, volumeID) { + return nil, errChunkNoAuthority + } + inner, err := p.cfg.ChunkRemoteFor(volumeID) + if err != nil { + return nil, fmt.Errorf("durable: chunk remote for %s: %w", volumeID, err) + } + lin := chunkLineage{volumeID: proj.VolumeID, replicaID: proj.ReplicaID, epoch: proj.Epoch, endpoint: proj.EndpointVersion} + holder := p.cfg.ChunkHolder + if holder == "" { + holder = proj.ReplicaID + } + remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} + remote.setAttach(ctx) // the attach's calls also end with the caller's ctx + defer remote.setAttach(nil) + return storage.AttachChunkLayer(ws, remote, storage.ChunkLayerConfig{ + ChunkBlocks: p.cfg.ChunkBlocks, + Epoch: lin.epoch, + Holder: holder, + FreshFromHead: h.fresh, + ReadMissTimeout: p.cfg.ChunkReadMissTimeout, + Bitmap: storage.NewFileChunkBitmapStore(h.path + ".chunkbitmap"), + CaptureAllowed: func() error { + cur := p.view.Projection() + if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { + return fmt.Errorf("volume %s is not a healthy primary here", volumeID) + } + if cur.ReplicaID != lin.replicaID || cur.Epoch != lin.epoch || cur.EndpointVersion != lin.endpoint { + return fmt.Errorf("volume %s lineage moved from replica %q epoch %d endpoint %d to replica %q epoch %d endpoint %d", + volumeID, lin.replicaID, lin.epoch, lin.endpoint, cur.ReplicaID, cur.Epoch, cur.EndpointVersion) + } + return nil + }, + }) +} + +// closeBoundRemote ends every remote call when the provider closes, so a +// shutdown never waits on the remote for an attach or a cut. While an +// attach runs, its calls also end with the attach caller's context. +type closeBoundRemote struct { + storage.ChunkRemote + done context.Context + + mu sync.Mutex + attach context.Context +} + +func (r *closeBoundRemote) setAttach(ctx context.Context) { + r.mu.Lock() + r.attach = ctx + r.mu.Unlock() +} + +func (r *closeBoundRemote) bind(ctx context.Context) (context.Context, func()) { + r.mu.Lock() + attach := r.attach + r.mu.Unlock() + c, cancel := context.WithCancel(ctx) + stops := []func() bool{context.AfterFunc(r.done, cancel)} + if attach != nil { + stops = append(stops, context.AfterFunc(attach, cancel)) + } + // AfterFunc runs its function in a new goroutine; a context that has + // already ended must cancel before the call starts, not after it. + if r.done.Err() != nil || (attach != nil && attach.Err() != nil) { + cancel() + } + return c, func() { + for _, stop := range stops { + stop() + } + cancel() + } +} + +func (r *closeBoundRemote) Put(ctx context.Context, key string, data []byte) error { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.Put(c, key, data) +} + +func (r *closeBoundRemote) Get(ctx context.Context, key string) ([]byte, error) { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.Get(c, key) +} + +func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.GetHead(c) +} + +func (r *closeBoundRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.CASHead(c, expected, next) +} + +func (r *closeBoundRemote) Delete(ctx context.Context, key string) error { + c, end := r.bind(ctx) + defer end() + return r.ChunkRemote.Delete(c, key) +} + +// The fresh marker: .chunkfresh. + +func chunkFreshMarker(path string) string { return path + ".chunkfresh" } + +func writeChunkFreshMarker(path string) error { + m := chunkFreshMarker(path) + f, err := os.OpenFile(m, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) + if err != nil { + return fmt.Errorf("durable: fresh marker: %w", err) + } + _, werr := f.WriteString("fresh\n") + serr := f.Sync() + cerr := f.Close() + if err := errors.Join(werr, serr, cerr); err != nil { + return fmt.Errorf("durable: fresh marker: %w", err) + } + return syncParentDir(m) +} + +func removeChunkFreshMarker(path string) error { + m := chunkFreshMarker(path) + if err := os.Remove(m); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("durable: remove fresh marker: %w", err) + } + return syncParentDir(m) +} + +// syncParentDir makes a create or remove in path's directory durable. A +// directory cannot be fsynced on Windows; there it is a no-op (no Windows +// crash-durability claim). +func syncParentDir(path string) error { + if runtime.GOOS == "windows" { + return nil + } + d, err := os.Open(filepath.Dir(path)) + if err != nil { + return fmt.Errorf("durable: open directory: %w", err) + } + serr := d.Sync() + cerr := d.Close() + if err := errors.Join(serr, cerr); err != nil { + return fmt.Errorf("durable: fsync directory: %w", err) + } + 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, awaiting := h.chunk, h.waitGen != 0 + p.mu.Unlock() + if layer == nil && awaiting { + return nil, ErrChunkAwaitingAuthority + } + 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_lifetime_test.go b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go new file mode 100644 index 0000000000..1a7bc8d74c --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_lifetime_test.go @@ -0,0 +1,841 @@ +package durable_test + +// walstore-chunk provider lifetime: interrupted fresh initialization, +// publication authority bound to the attach-time lineage, and attach +// settlement against Close and against a concurrent RecoverVolume. Each +// schedule drives the real provider entry points. + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "hash/crc32" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// gatedRemote wraps a remote with failure and hold points. +type gatedRemote struct { + storage.ChunkRemote + + mu sync.Mutex + failGetHead int // fail the next N GetHead calls + holdGetHead chan struct{} // non-nil: GetHead blocks until closed + holdPut chan struct{} // non-nil: Put blocks until closed + honourCtx bool // a held call also returns when its ctx ends + holdAfter bool // GetHead reads HEAD first, then holds + entered chan string // receives "gethead"/"put" when a call is held + once sync.Once +} + +func newGated(inner storage.ChunkRemote) *gatedRemote { + return &gatedRemote{ChunkRemote: inner, entered: make(chan string, 16)} +} + +func (g *gatedRemote) hold(ctx context.Context, what string, ch chan struct{}) error { + if ch == nil { + return nil + } + g.entered <- what + if g.honourCtx { + select { + case <-ch: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } + <-ch + return nil +} + +func (g *gatedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + g.mu.Lock() + fail := g.failGetHead > 0 + if fail { + g.failGetHead-- + } + ch := g.holdGetHead + g.mu.Unlock() + if fail { + return storage.ChunkHead{}, errors.New("injected GetHead failure") + } + if g.holdAfter { + h, err := g.ChunkRemote.GetHead(ctx) + _ = g.hold(ctx, "gethead", ch) + return h, err + } + if err := g.hold(ctx, "gethead", ch); err != nil { + return storage.ChunkHead{}, err + } + return g.ChunkRemote.GetHead(ctx) +} + +func (g *gatedRemote) Put(ctx context.Context, key string, data []byte) error { + g.mu.Lock() + ch := g.holdPut + g.mu.Unlock() + if err := g.hold(ctx, "put", ch); err != nil { + return err + } + return g.ChunkRemote.Put(ctx, key, data) +} + +// release opens every hold once (safe from cleanup and from the test). +func (g *gatedRemote) release() { + g.once.Do(func() { + g.mu.Lock() + defer g.mu.Unlock() + if g.holdGetHead != nil { + close(g.holdGetHead) + } + if g.holdPut != nil { + close(g.holdPut) + } + }) +} + +func waitEntered(t *testing.T, g *gatedRemote, what string) { + t.Helper() + select { + case got := <-g.entered: + if got != what { + t.Fatalf("held call %q, want %q", got, what) + } + case <-time.After(10 * time.Second): + t.Fatalf("no %s call was held", what) + } +} + +func recvErr(t *testing.T, ch <-chan error, what string) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(10 * time.Second): + t.Fatalf("%s did not return", what) + return nil + } +} + +// seededRemote returns a remote whose HEAD publishes 0x33 at LBA 33 +// (chunk 2) and 0x64 at LBA 100 (chunk 6). +func seededRemote(t *testing.T) *storage.MemChunkRemote { + t.Helper() + remote := storage.NewMemChunkRemote() + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + s := openRecovered(t, p) + for lba, fill := range map[uint32]byte{33: 0x33, 100: 0x64} { + if _, err := s.Write(lba, block(fill)); err != nil { + t.Fatal(err) + } + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatalf("seed capture: %v", err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + return remote +} + +func readEq(t *testing.T, s storage.LogicalStorage, lba uint32, want []byte, what string) { + t.Helper() + got, err := s.Read(lba) + if err != nil { + t.Fatalf("%s: read %d: %v", what, lba, err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s: LBA %d = %x...; want %x...", what, lba, got[:4], want[:4]) + } +} + +// A fresh volume whose first attach fails is still fresh after a normal +// close and reopen: it reads HEAD, never the untouched local zeros. +func TestWALStoreChunk_FailedFreshAttachThenReopenReadsHead(t *testing.T) { + remote := seededRemote(t) + root := t.TempDir() + g := newGated(remote) + g.failGetHead = 1 + p := chunkProvider(t, root, g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err == nil { + t.Fatal("RecoverVolume succeeded although the first attach could not read HEAD") + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + p2 := chunkProvider(t, root, remote, v1View(), 0) + s := openRecovered(t, p2) + readEq(t, s, 33, block(0x33), "reopen after a failed fresh attach") + readEq(t, s, 100, block(0x64), "reopen after a failed fresh attach") +} + +// Interrupted before any attach: created, never recovered, closed. +func TestWALStoreChunk_CreatedNeverAttachedThenReopenReadsHead(t *testing.T) { + remote := seededRemote(t) + root := t.TempDir() + p := chunkProvider(t, root, remote, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + p2 := chunkProvider(t, root, remote, v1View(), 0) + s := openRecovered(t, p2) + readEq(t, s, 33, block(0x33), "reopen of a never-attached fresh volume") +} + +// Once a fresh attach succeeded the volume is no longer fresh: a restart +// keeps its local writes over HEAD and still reads untouched chunks from +// HEAD. +func TestWALStoreChunk_FreshVolumeKeepsLocalWritesAfterRestart(t *testing.T) { + remote := seededRemote(t) + root := t.TempDir() + p := chunkProvider(t, root, remote, v1View(), 0) + s := openRecovered(t, p) + if _, err := s.Write(33, block(0x77)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := p.Close(); err != nil { + t.Fatal(err) + } + p2 := chunkProvider(t, root, remote, v1View(), 0) + s2 := openRecovered(t, p2) + readEq(t, s2, 33, block(0x77), "restart after a fresh attach") + readEq(t, s2, 100, block(0x64), "restart after a fresh attach") +} + +// Publication authority is the attach-time lineage. A healthy projection +// that moved to another epoch, replica or endpoint version refuses the +// capture; the unchanged lineage still publishes. +func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) { + cases := map[string]func(p *frontend.Projection){ + "unchanged": nil, + "epoch": func(p *frontend.Projection) { p.Epoch++ }, + "replica": func(p *frontend.Projection) { p.ReplicaID = "r2" }, + "endpoint": func(p *frontend.Projection) { p.EndpointVersion++ }, + } + for name, drift := range cases { + t.Run(name, func(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) + } + if drift != nil { + proj := view.Projection() + drift(&proj) + view.set(proj) + } + _, err := p.CaptureVolume(context.Background(), "v1") + head, _ := remote.GetHead(context.Background()) + if drift == nil { + if err != nil || head.Gen != 1 { + t.Fatalf("capture under the attach lineage: %v (HEAD gen %d)", err, head.Gen) + } + return + } + if !errors.Is(err, storage.ErrChunkCaptureRefused) { + t.Fatalf("capture after %s drift: %v; want refused", name, err) + } + if head.Gen != 0 || remote.Puts() != 0 { + t.Fatalf("capture after %s drift published: HEAD gen %d, %d chunks stored", name, head.Gen, remote.Puts()) + } + }) + } +} + +// The lineage moves while the capture's upload is held, after the first +// admission check: the final admission before the CAS refuses it. +func TestWALStoreChunk_LineageDriftDuringHeldUploadRefusesPublication(t *testing.T) { + remote := storage.NewMemChunkRemote() + g := newGated(remote) + g.holdPut = make(chan struct{}) + t.Cleanup(g.release) + view := v1View() + p := chunkProvider(t, t.TempDir(), g, view, 0) + s := openRecovered(t, p) + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + errc := make(chan error, 1) + go func() { _, err := p.CaptureVolume(context.Background(), "v1"); errc <- err }() + waitEntered(t, g, "put") + proj := view.Projection() + proj.Epoch++ + view.set(proj) + g.release() + if err := recvErr(t, errc, "CaptureVolume"); !errors.Is(err, storage.ErrChunkCaptureRefused) { + t.Fatalf("capture whose lineage moved during upload: %v; want refused", err) + } + if head, _ := remote.GetHead(context.Background()); head.Gen != 0 { + t.Fatalf("stale lineage published HEAD gen %d", head.Gen) + } +} + +// Close waits for an attach that is in flight and the attach never +// publishes after shutdown: RecoverVolume fails and the volume is gone. +func TestWALStoreChunk_CloseSettlesHeldAttach(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + recErr := make(chan error, 1) + go func() { _, err := p.RecoverVolume(context.Background(), "v1"); recErr <- err }() + waitEntered(t, g, "gethead") + closed := make(chan error, 1) + go func() { closed <- p.Close() }() + select { + case <-closed: + t.Fatal("Close returned while an attach was still in flight") + case <-time.After(200 * time.Millisecond): + } + g.release() + if err := recvErr(t, recErr, "RecoverVolume"); err == nil { + t.Fatal("RecoverVolume succeeded after the provider was closed") + } + _ = recvErr(t, closed, "Close") + if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrVolumeNotOpen) { + t.Fatalf("chunk layer reachable after Close: %v", err) + } +} + +// The attach read HEAD successfully before Close; it completes after +// Close with no remote call left to cancel, and must still publish +// nothing. +func TestWALStoreChunk_AttachFinishingAfterClosePublishesNothing(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + g.holdAfter = true + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + recErr := make(chan error, 1) + go func() { _, err := p.RecoverVolume(context.Background(), "v1"); recErr <- err }() + waitEntered(t, g, "gethead") + closed := make(chan error, 1) + go func() { closed <- p.Close() }() + time.Sleep(100 * time.Millisecond) // Close is now waiting for the attach + g.release() + if err := recvErr(t, recErr, "RecoverVolume"); err == nil { + t.Fatal("RecoverVolume succeeded for an attach that finished after Close") + } + _ = recvErr(t, closed, "Close") + if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrVolumeNotOpen) { + t.Fatalf("chunk layer reachable after Close: %v", err) + } +} + +// Close cancels the attach's remote call instead of waiting on the remote. +func TestWALStoreChunk_CloseCancelsAttachRemoteCall(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + g.honourCtx = true + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + recErr := make(chan error, 1) + go func() { _, err := p.RecoverVolume(context.Background(), "v1"); recErr <- err }() + waitEntered(t, g, "gethead") + closed := make(chan error, 1) + go func() { closed <- p.Close() }() + _ = recvErr(t, closed, "Close") + if err := recvErr(t, recErr, "RecoverVolume"); err == nil { + t.Fatal("RecoverVolume succeeded after the provider was closed") + } +} + +// Two RecoverVolume calls racing on one volume both settle on a single +// attached layer. +func TestWALStoreChunk_ConcurrentRecoverAttachesOnce(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + errs := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { _, err := p.RecoverVolume(context.Background(), "v1"); errs <- err }() + } + waitEntered(t, g, "gethead") + time.Sleep(100 * time.Millisecond) // let the second call reach its attach + g.release() + for i := 0; i < 2; i++ { + if err := recvErr(t, errs, "RecoverVolume"); err != nil { + t.Fatalf("concurrent RecoverVolume: %v", err) + } + } + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatalf("capture after concurrent recovery: %v", err) + } +} + +// The caller's recovery deadline governs the attach's first remote call, +// with no Close and no hold release. +func TestWALStoreChunk_RecoverHonoursCallerDeadline(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + g.honourCtx = true + t.Cleanup(g.release) + p := chunkProvider(t, t.TempDir(), g, v1View(), 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + recErr := make(chan error, 1) + go func() { _, err := p.RecoverVolume(ctx, "v1"); recErr <- err }() + waitEntered(t, g, "gethead") + if err := recvErr(t, recErr, "RecoverVolume past its caller deadline"); err == nil { + t.Fatal("RecoverVolume succeeded although its deadline expired during attach") + } +} + +// An attached layer outlives the recovery context: main cancels it right +// after recovery, and captures must keep working. +func TestWALStoreChunk_LayerOutlivesRecoveryContext(t *testing.T) { + remote := storage.NewMemChunkRemote() + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + cancel() + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil { + t.Fatalf("capture after the recovery context ended: %v", err) + } +} + +// Recovery before the master's assignment is visible does not bind the +// layer to epoch 0: once the projection carries the assignment, the +// volume publishes under it. +func TestWALStoreChunk_AttachWaitsForMasterAuthority(t *testing.T) { + remote := storage.NewMemChunkRemote() + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) // pre-assignment + p := chunkProvider(t, t.TempDir(), remote, view, 0) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatalf("RecoverVolume before assignment: %v", err) + } + if _, err := s.Write(1, block(1)); err != nil { + t.Fatal(err) + } + // Healthy but with no master-assigned epoch is not authority either. + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})) + time.Sleep(150 * time.Millisecond) + if _, err := p.CaptureVolume(context.Background(), "v1"); err == nil { + t.Fatal("capture succeeded under a healthy projection with epoch 0") + } + if head, _ := remote.GetHead(context.Background()); head.Gen != 0 { + t.Fatalf("published under epoch 0: HEAD gen %d epoch %d", head.Gen, head.Epoch) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + deadline := time.Now().Add(10 * time.Second) + for { + _, err = p.CaptureVolume(context.Background(), "v1") + if err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("capture never succeeded under the assigned epoch: %v", err) + } + time.Sleep(20 * time.Millisecond) + } + if head, _ := remote.GetHead(context.Background()); head.Epoch != 4 { + t.Fatalf("HEAD epoch %d, want the assigned 4", head.Epoch) + } +} + +// Close while a volume still waits for authority returns and leaves no +// layer behind. +func TestWALStoreChunk_CloseWhileAwaitingAuthority(t *testing.T) { + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), view, 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + closed := make(chan error, 1) + go func() { closed <- p.Close() }() + _ = recvErr(t, closed, "Close") + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrVolumeNotOpen) { + t.Fatalf("chunk layer reachable after Close: %v", err) + } +} + +// Close settles a deferred attach that is in flight: the authority wait +// is registered like a recovery. +func TestWALStoreChunk_CloseSettlesDeferredAttach(t *testing.T) { + g := newGated(storage.NewMemChunkRemote()) + g.holdGetHead = make(chan struct{}) + t.Cleanup(g.release) + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), g, view, 0) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + waitEntered(t, g, "gethead") // the deferred attach is reading HEAD + closed := make(chan error, 1) + go func() { closed <- p.Close() }() + select { + case <-closed: + t.Fatal("Close returned while a deferred attach was still in flight") + case <-time.After(200 * time.Millisecond): + } + g.release() + _ = recvErr(t, closed, "Close") + if _, err := p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrVolumeNotOpen) { + t.Fatalf("chunk layer reachable after Close: %v", err) + } +} + +// corruptWALWrite finds the WAL record of the one write carrying fill and +// turns it into a CRC-valid write-batch record with no block count, which +// recovery refuses as a WAL integrity fault. It returns a restore func. +func corruptWALWrite(t *testing.T, path string, fill byte) func() { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + payload := bytes.Repeat([]byte{fill}, 4096) + at := bytes.Index(raw, payload) + if at < 30 || bytes.Index(raw[at+1:], payload) >= 0 { + t.Fatalf("WAL record for fill %#x not found exactly once", fill) + } + const hdr = 30 // LSN 8, Reserved 8, Type 1, Flags 1, LBA 8, Length 4 + start := at - hdr + rec := append([]byte(nil), raw[start:at+4096+8]...) + orig := append([]byte(nil), rec...) + if rec[16] != 0x01 || binary.LittleEndian.Uint64(rec[8:]) != 0 { + t.Fatalf("unexpected WAL record header % x", rec[:hdr]) + } + rec[16] = 0x04 // write batch, Reserved stays 0: invalid + binary.LittleEndian.PutUint32(rec[hdr+4096:], crc32.ChecksumIEEE(rec[:hdr+4096])) + f, err := os.OpenFile(path, os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteAt(rec, int64(start)); err != nil { + t.Fatal(err) + } + return func() { + f, err := os.OpenFile(path, os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteAt(orig, int64(start)); err != nil { + t.Fatal(err) + } + } +} + +// A deferred attach belongs to the recovery that registered it. Recovery +// A succeeds before authority; recovery B then fails on a real WAL +// integrity fault; when authority arrives, A's wait must neither attach +// nor admit I/O. A later successful recovery converges. +func TestWALStoreChunk_StaleWaiterCannotOverrideFailedRecovery(t *testing.T) { + root := t.TempDir() + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // A: ok, no authority + t.Fatalf("recovery A: %v", err) + } + if _, err := s.Write(5, block(0xA7)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + restore := corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7) + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) { // B + t.Fatalf("recovery B over a corrupt WAL record: %v; want a WAL integrity fault", err) + } + + authority := healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2}) + view.set(authority) + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + time.Sleep(300 * time.Millisecond) // many authority-wait ticks + if _, err := be.Write(ctx, 7*4096, block(1)); err == nil { + t.Fatal("I/O admitted after the latest recovery failed") + } + if _, err := p.CaptureVolume(ctx, "v1"); err == nil { + t.Fatal("chunk layer attached after the latest recovery failed") + } + + // Convergence: repair, recover again without authority, then authority. + restore() + view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // C + t.Fatalf("recovery C after repair: %v", err) + } + view.set(authority) + deadline := time.Now().Add(10 * time.Second) + for { + if _, err = be.Write(ctx, 7*4096, block(1)); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("I/O never admitted after a later successful recovery: %v", err) + } + time.Sleep(20 * time.Millisecond) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatalf("capture after convergence: %v", err) + } + readEq(t, s, 5, block(0xA7), "repaired WAL record after convergence") +} + +// A failed recovery retires the authority wait of the earlier successful +// one: the volume no longer reports a layer awaiting authority. +func TestWALStoreChunk_FailedRecoveryRetiresAuthorityWait(t *testing.T) { + root := t.TempDir() + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + if _, err := p.CaptureVolume(ctx, "v1"); errors.Is(err, durable.ErrNotChunkVolume) || err == nil { + t.Fatalf("after recovery without authority: %v; want the volume awaiting authority", err) + } + if _, err := s.Write(5, block(0xA7)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7) + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) { + t.Fatalf("failing recovery: %v", err) + } + deadline := time.Now().Add(5 * time.Second) + for { + _, err := p.CaptureVolume(ctx, "v1") + if errors.Is(err, durable.ErrNotChunkVolume) { + return + } + if time.Now().After(deadline) { + t.Fatalf("after a failed recovery: %v; want no layer and no live authority wait", err) + } + time.Sleep(20 * time.Millisecond) + } +} + +// parkingView parks exactly one Projection call once armed, until the test +// releases it with the projection it should return; that projection then +// stays current. +type parkingView struct { + *stubView + mu sync.Mutex + armed bool + parked chan struct{} + release chan frontend.Projection +} + +func (v *parkingView) arm() { + v.mu.Lock() + v.armed, v.parked, v.release = true, make(chan struct{}), make(chan frontend.Projection) + v.mu.Unlock() +} + +func (v *parkingView) Projection() frontend.Projection { + v.mu.Lock() + if !v.armed { + v.mu.Unlock() + return v.stubView.Projection() + } + v.armed = false + parked, release := v.parked, v.release + v.mu.Unlock() + close(parked) + p := <-release + v.stubView.set(p) + return p +} + +// countingRemote counts HEAD reads (an attach starts with one). +type countingRemote struct { + storage.ChunkRemote + heads atomic.Int64 +} + +func (c *countingRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + c.heads.Add(1) + return c.ChunkRemote.GetHead(ctx) +} + +// The window the per-tick check cannot cover: wait A has passed its tick +// check and is reading the projection when recovery B takes the volume and +// fails. Only the re-check under the per-volume serialization stops A. +func TestWALStoreChunk_StaleWaiterPastTickCheckCannotAttach(t *testing.T) { + root := t.TempDir() + view := &parkingView{stubView: newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})} + remote := &countingRemote{ChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + WALRecoveryTestDisableFlusher: true, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + s, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // A: ok, no authority + t.Fatalf("recovery A: %v", err) + } + if _, err := s.Write(5, block(0xA7)); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + restore := corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7) + + // Park A's wait inside its projection read, after its tick check. + view.arm() + select { + case <-view.parked: + case <-time.After(10 * time.Second): + t.Fatal("the authority wait never read the projection") + } + if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) { // B + t.Fatalf("recovery B over a corrupt WAL record: %v; want a WAL integrity fault", err) + } + authority := healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2}) + view.release <- authority // A resumes and sees authority + + deadline := time.Now().Add(10 * time.Second) + for { + _, err = p.CaptureVolume(ctx, "v1") + if !errors.Is(err, durable.ErrChunkAwaitingAuthority) { + break // A has settled + } + if time.Now().After(deadline) { + t.Fatal("the stale authority wait never settled") + } + time.Sleep(10 * time.Millisecond) + } + if !errors.Is(err, durable.ErrNotChunkVolume) { + t.Fatalf("stale wait attached a layer after the latest recovery failed: capture %v", err) + } + if n := remote.heads.Load(); n != 0 { + t.Fatalf("stale wait started a remote attach (%d HEAD reads)", n) + } + be, err := p.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err := be.Write(ctx, 7*4096, block(1)); err == nil { + t.Fatal("stale wait admitted I/O after the latest recovery failed") + } + + // Convergence: repair, recovery C without authority, then authority. + restore() + view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { // C + t.Fatalf("recovery C after repair: %v", err) + } + view.set(authority) + deadline = time.Now().Add(10 * time.Second) + for { + if _, err = be.Write(ctx, 7*4096, block(1)); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("I/O never admitted after a later successful recovery: %v", err) + } + time.Sleep(20 * time.Millisecond) + } + if _, err := p.CaptureVolume(ctx, "v1"); err != nil { + t.Fatalf("capture after convergence: %v", err) + } + readEq(t, s, 5, block(0xA7), "repaired WAL record after convergence") +} 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..ab9955873d --- /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.ChunkRemote, 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/host/volume/chunk_bootstrap_test.go b/seaweed-block/core/host/volume/chunk_bootstrap_test.go new file mode 100644 index 0000000000..a451f269dd --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_bootstrap_test.go @@ -0,0 +1,126 @@ +package volume + +// walstore-chunk in the production startup order of cmd/blockvolume: +// the host blocks local readiness, the master's assignment arrives and is +// retained, the durable provider opens and recovers the volume, readiness +// clears and SetReplicationVolume replays the assignment. Only then is +// the master-assigned epoch known; the chunk layer must publish under it. + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestWALStoreChunk_ProductionStartupPublishesUnderAssignedEpoch(t *testing.T) { + h, err := New(Config{ + MasterAddr: "127.0.0.1:1", // never dialed: no Start + ServerID: "s1", VolumeID: "v1", ReplicaID: "r1", + DataAddr: "127.0.0.1:2", CtrlAddr: "127.0.0.1:3", + EnableT1Readiness: true, + Logger: newDiscardLogger(), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = h.Close() }) + + // main.go: block readiness before Start; the assignment arrives and + // is retained, not applied. + h.BlockLocalReadiness("awaiting durable recovery") + h.applyFact(&control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: 5, EndpointVersion: 2, PeerSetGeneration: 1}) + if p := h.ProjectionView().Projection(); p.Healthy || p.Epoch != 0 { + t.Fatalf("assignment applied while readiness was blocked: %+v", p) + } + + remote := storage.NewMemChunkRemote() + dp, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: 256, + ChunkBlocks: 16, + ChunkCaptureInterval: 20 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, h.ProjectionView()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + if _, err := dp.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + recCtx, recCancel := context.WithTimeout(context.Background(), 10*time.Second) + _, recErr := dp.RecoverVolume(recCtx, "v1") + recCancel() + if recErr != nil { + t.Fatalf("RecoverVolume during blocked readiness: %v", recErr) + } + + // main.go: clear readiness, install replication; the retained + // assignment replays. + h.ClearLocalReadinessBlock() + h.SetReplicationVolume(replication.NewReplicationVolume("v1", dp.LogicalStorage("v1"))) + + openCtx, openCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer openCancel() + be, err := dp.Open(openCtx, "v1") + if err != nil { + t.Fatalf("frontend open after replay: %v", err) + } + if p := h.ProjectionView().Projection(); !p.Healthy || p.Epoch != 5 || p.EndpointVersion != 2 { + t.Fatalf("projection after replay: %+v", p) + } + data := bytes.Repeat([]byte{0x5A}, 4096) + deadline := time.Now().Add(10 * time.Second) + for { + if _, err = be.Write(context.Background(), 40*4096, data); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("frontend write never admitted: %v", err) + } + time.Sleep(20 * time.Millisecond) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + + // On-demand capture under the assigned lineage. + lsn, err := dp.CaptureVolume(context.Background(), "v1") + if err != nil { + t.Fatalf("on-demand capture after startup: %v", err) + } + head, _ := remote.GetHead(context.Background()) + if head.Epoch != 5 || head.Holder != "r1" || head.RemoteLSN != lsn { + t.Fatalf("HEAD after on-demand capture: epoch %d holder %q remote_lsn %d (want 5, r1, %d)", head.Epoch, head.Holder, head.RemoteLSN, lsn) + } + + // Periodic capture under the same lineage. + if _, err := be.Write(context.Background(), 200*4096, bytes.Repeat([]byte{0xC8}, 4096)); err != nil { + t.Fatal(err) + } + if err := be.Sync(context.Background()); err != nil { + t.Fatal(err) + } + deadline = time.Now().Add(10 * time.Second) + for { + head, _ = remote.GetHead(context.Background()) + if _, ok := head.Chunks[200/16]; ok && head.RemoteLSN > lsn { + break + } + if time.Now().After(deadline) { + t.Fatalf("periodic capture never published the second write (HEAD gen %d remote_lsn %d)", head.Gen, head.RemoteLSN) + } + time.Sleep(20 * time.Millisecond) + } + if head.Epoch != 5 { + t.Fatalf("periodic HEAD epoch %d, want 5", head.Epoch) + } +} 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) +}