mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Merge pull request #114 from seaweedfs/blockc/chunk-provider-swfs-r6
durable: walstore-chunk provider with a SeaweedFS chunk remote
This commit is contained in:
commit
c29f7706a9
22 files changed
+5870
-16
No files matched your search
@@ -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>/<volume-id> 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 <base>/<volumeID>; 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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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:
|
||||
//
|
||||
// <root>/HEAD the published HEAD: JSON in the entry content,
|
||||
// {gen, epoch, holder} mirrored in extended attributes
|
||||
// <root>/keys/<key> 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)
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<string, bytes> 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<string, bytes> expected_extended = 5;
|
||||
}
|
||||
|
||||
message UpdateEntryResponse {
|
||||
}
|
||||
|
||||
message DeleteEntryRequest {
|
||||
string directory = 1;
|
||||
string name = 2;
|
||||
bool is_delete_data = 4;
|
||||
bool is_recursive = 5;
|
||||
map<string, bytes> 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<string, Locations> locations_map = 1;
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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")
|
||||
)
|
||||
@@ -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)
|
||||
)
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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: <volume path>.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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user