mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
change: cut over to the content-named store and delete the legacy store
The runtime stores each volume in one content-named layout on the filer: immutable chunks, segments and roots are ordinary filer files, and one HEAD entry per volume carries every conditional commit. A holder claims HEAD under its granted epoch and claim id, cuts in its own session, commits by HEAD generation and position, and is fenced when its identity moves. Catalog, restore, snapshot, retention, cleaning, verify and volume delete run through the layout kernel; the master mints the layout identity, reads HEAD proofs and holds the delete reservation and lease barrier. The legacy store, its intents and its compatibility paths are removed; existing stores are recreated, not converted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f24312e39f
commit
ab747bfa47
436 files changed
+22737
-29268
No files matched your search
@@ -132,7 +132,6 @@ sw-block ops chunk restore --chunk-filer <filer> --source v1 --snapshot s1 --t
|
||||
sw-block ops chunk restore --volume v3 --status-addr <status> --status # restore progress
|
||||
sw-block ops chunk detach --volume v1 --status-addr <status> # final cut (seal); moving needs revoke + move, see docs/volume-lifecycle.md
|
||||
sw-block ops chunk volume-delete --volume v2 --chunk-filer <filer> --master <blockmaster> --request-id del-v2
|
||||
sw-block ops chunk gc --chunk-filer <filer> --master <blockmaster> # preview; --apply to reclaim
|
||||
sw-block ops chunk verify --volume v1 --chunk-filer <filer> # read-only check of the remote image
|
||||
```
|
||||
|
||||
|
||||
@@ -223,7 +223,11 @@ func TestClusterSpecCLIMissingSizeExplainsCreateVolumePrerequisite(t *testing.T)
|
||||
o2, e2, l2 := importedVolumeClients(t, p2)
|
||||
reportImportedVolume(t, o2)
|
||||
waitImportedAuthority(t, p2, e2)
|
||||
got, err := l2.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp"})
|
||||
// The earlier RPC budget belongs to the first daemon. Give this distinct
|
||||
// request the same budget after the restart, without extending either RPC.
|
||||
replayCtx, replayCancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer replayCancel()
|
||||
got, err := l2.CreateVolume(replayCtx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1048576, ReplicationFactor: 1, Protocol: "nvme", FrontendTransport: "tcp"})
|
||||
if err != nil || got.Protocol != "nvme" || got.FrontendTransport != "tcp" || got.PvcNamespace != "workspaces" || got.PvcName != "claim-v1" {
|
||||
t.Fatalf("cluster import changed existing protocol/metadata: %v %v", got, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
// layoutVolumeCreator writes only the master's initial VOLUME and unclaimed
|
||||
// HEAD. layout.CreateVolume performs exclusive writes and heals a replay
|
||||
// stopped between them without minting another identity.
|
||||
func layoutVolumeCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) error {
|
||||
return func(ctx context.Context, spec lifecycle.VolumeSpec) error {
|
||||
if cat == nil {
|
||||
return fmt.Errorf("master: layout catalog is unavailable")
|
||||
}
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{
|
||||
SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes,
|
||||
})
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func layoutVolumeReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Volume, error) {
|
||||
return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Volume, error) {
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return layout.Volume{}, err
|
||||
}
|
||||
return cat.ReadVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id})
|
||||
}
|
||||
}
|
||||
|
||||
func layoutHeadReader(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec) (layout.Head, error) {
|
||||
return func(ctx context.Context, spec lifecycle.VolumeSpec) (layout.Head, error) {
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id})
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
if !found {
|
||||
return layout.Head{}, layout.ErrHeadAbsent
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
|
||||
func layoutTargetCreator(cat *chunkstore.BCatalog) func(context.Context, lifecycle.VolumeSpec, lifecycle.VolumeSpec, string) error {
|
||||
return func(ctx context.Context, source, target lifecycle.VolumeSpec, snapshot string) error {
|
||||
sid, err := layout.ParseVolumeID(source.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tid, err := layout.ParseVolumeID(target.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = cat.Restore(ctx,
|
||||
chunkstore.VolumeRef{Name: source.VolumeID, ID: sid}, snapshot,
|
||||
chunkstore.VolumeRef{Name: target.VolumeID, ID: tid})
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
)
|
||||
|
||||
type failFirstHead struct {
|
||||
chunkstore.Filer
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (f *failFirstHead) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error {
|
||||
if e.Name == "HEAD" && f.fail {
|
||||
f.fail = false
|
||||
return errors.New("fixture: lost filer HEAD create")
|
||||
}
|
||||
return f.Filer.CreateEntry(ctx, dir, e, excl)
|
||||
}
|
||||
|
||||
type noCreateBlobs struct{}
|
||||
|
||||
func (noCreateBlobs) Put(context.Context, []byte) (string, error) {
|
||||
return "", errors.New("unexpected blob upload")
|
||||
}
|
||||
func (noCreateBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("unexpected blob read")
|
||||
}
|
||||
|
||||
func TestMasterLayoutCreatorWritesUnclaimedHeadAndReplays(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := lifecycle.VolumeSpec{VolumeID: "v", LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1}
|
||||
create := layoutVolumeCreator(cat)
|
||||
var firstGen uint64
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := create(ctx, spec); err != nil {
|
||||
t.Fatalf("create attempt %d: %v", i, err)
|
||||
}
|
||||
h, found, err := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "v", ID: id})
|
||||
if err != nil || !found {
|
||||
t.Fatalf("read HEAD after attempt %d: found=%t err=%v", i, found, err)
|
||||
}
|
||||
if i == 0 {
|
||||
firstGen = h.Gen
|
||||
} else if h.Gen != firstGen {
|
||||
t.Fatalf("replay changed HEAD generation %d -> %d", firstGen, h.Gen)
|
||||
}
|
||||
}
|
||||
st, err := cat.Store(chunkstore.VolumeRef{Name: "v", ID: id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, found, err := st.ReadVolumeRecord(ctx)
|
||||
if err != nil || !found || v.Geometry != (layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes}) {
|
||||
t.Fatalf("VOLUME=%+v found=%t err=%v", v, found, err)
|
||||
}
|
||||
h, found, err := st.ReadHead(ctx)
|
||||
if err != nil || !found || h.Epoch != 0 || h.Holder != "" || h.ClaimID != "" || h.Gen == 0 {
|
||||
t.Fatalf("unclaimed HEAD=%+v found=%t err=%v", h, found, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasterLayoutCreatorHealsCrashBetweenVolumeAndHead(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
filer := &failFirstHead{Filer: chunkstore.NewMemFiler(), fail: true}
|
||||
cat, err := chunkstore.NewBCatalog(filer, noCreateBlobs{}, "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
spec := lifecycle.VolumeSpec{VolumeID: ref.Name, LayoutID: id.String(), SizeBytes: 1 << 20, BlockSize: 4096, ChunkBytes: 4 << 20, ReplicationFactor: 1}
|
||||
create := layoutVolumeCreator(cat)
|
||||
if err := create(ctx, spec); err == nil {
|
||||
t.Fatal("first HEAD create did not fail")
|
||||
}
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, found, err := st.ReadVolumeRecord(ctx); err != nil || !found {
|
||||
t.Fatalf("VOLUME after interrupted create: found=%t err=%v", found, err)
|
||||
}
|
||||
if _, found, err := st.ReadHead(ctx); err != nil || found {
|
||||
t.Fatalf("HEAD after interrupted create: found=%t err=%v", found, err)
|
||||
}
|
||||
if err := create(ctx, spec); err != nil {
|
||||
t.Fatalf("retry did not complete HEAD: %v", err)
|
||||
}
|
||||
if h, found, err := st.ReadHead(ctx); err != nil || !found || h.Epoch != 0 {
|
||||
t.Fatalf("healed HEAD=%+v found=%t err=%v", h, found, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMasterLayoutHeadReaderRefusesAbsentHead(t *testing.T) {
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), noCreateBlobs{}, "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec := lifecycle.VolumeSpec{VolumeID: "source", LayoutID: id.String()}
|
||||
if _, err := layoutHeadReader(cat)(context.Background(), spec); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("absent source HEAD: %v; want ErrHeadAbsent", err)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
@@ -63,6 +64,10 @@ type flags struct {
|
||||
workspaceMaxClockSkew time.Duration
|
||||
workspaceRPC bool
|
||||
workspaceHEADBase string
|
||||
chunkFiler string
|
||||
chunkPath string
|
||||
chunkCollection string
|
||||
chunkReplication string
|
||||
frontendPublicationRuntimeHTTP bool
|
||||
frontendPublicationRuntimeListen string
|
||||
strictJournalIsolation bool
|
||||
@@ -122,7 +127,8 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence")
|
||||
fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound")
|
||||
fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs")
|
||||
fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc")
|
||||
fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP base containing <name>-<layout-id-prefix>/HEAD; required with --workspace-rpc")
|
||||
chunkstore.RegisterSWFSFlags(fs, &f.chunkFiler, &f.chunkPath, &f.chunkCollection, &f.chunkReplication)
|
||||
fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only")
|
||||
fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http")
|
||||
fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only")
|
||||
@@ -238,6 +244,21 @@ func run(f flags) int {
|
||||
return 1
|
||||
}
|
||||
cfg.Auth, cfg.ServerOptions = authn, serverOpts
|
||||
if f.workspaceRPC {
|
||||
cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{
|
||||
FilerGRPC: f.chunkFiler, Collection: f.chunkCollection,
|
||||
Replication: f.chunkReplication, AssignPath: f.chunkPath,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster: layout filer:", err)
|
||||
return 1
|
||||
}
|
||||
defer client.Close()
|
||||
cfg.LayoutCreateVolume = layoutVolumeCreator(cat)
|
||||
cfg.LayoutReadVolume = layoutVolumeReader(cat)
|
||||
cfg.LayoutReadHead = layoutHeadReader(cat)
|
||||
cfg.LayoutCreateTarget = layoutTargetCreator(cat)
|
||||
}
|
||||
if authn != nil {
|
||||
if days, until, err := certDaysLeft(f.auth.tlsCert, f.auth.tlsKey, time.Now()); err == nil {
|
||||
fmt.Fprintln(os.Stderr, fmt.Sprintf("blockmaster: mutual TLS on; role file %s; own certificate expires %s (%d days)", f.auth.roleFile, until.UTC().Format(time.RFC3339), days))
|
||||
@@ -245,8 +266,12 @@ func run(f flags) int {
|
||||
} else {
|
||||
warnUnauthenticated(f.listen)
|
||||
}
|
||||
// New starts no loops: bind h before Start permits any HEAD request.
|
||||
var h *master.Host
|
||||
if f.workspaceRPC {
|
||||
reader, err := master.NewWorkspaceHEADReader(f.workspaceHEADBase)
|
||||
reader, err := master.NewLayoutWorkspaceHEADReader(f.workspaceHEADBase, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) {
|
||||
return h.WorkspaceLayoutVolume(ctx, name)
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster:", err)
|
||||
return 1
|
||||
@@ -254,7 +279,7 @@ func run(f flags) int {
|
||||
cfg.WorkspaceRPC = true
|
||||
cfg.WorkspaceHeadReader = reader
|
||||
}
|
||||
h, err := master.New(cfg)
|
||||
h, err = master.New(cfg)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "blockmaster:", err)
|
||||
return 1
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The runtime uses the master-bound reader; the legacy constructor is not a
|
||||
// fallback. Every constructor/resolver caller is a classified production site.
|
||||
func TestWorkspaceLayoutHEADReaderWiring(t *testing.T) {
|
||||
want := map[string]int{"cmd/blockmaster/main.go run -> NewLayoutWorkspaceHEADReader": 1, "cmd/blockmaster/main.go run -> WorkspaceLayoutVolume": 1}
|
||||
found := map[string]int{}
|
||||
root := filepath.Join("..", "..")
|
||||
for _, top := range []string{"core", "cmd"} {
|
||||
err := filepath.WalkDir(filepath.Join(root, top), func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
|
||||
return err
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), p, nil, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, _ := filepath.Rel(root, p)
|
||||
for _, d := range f.Decls {
|
||||
fn, ok := d.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
continue
|
||||
}
|
||||
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||
c, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
name := ""
|
||||
switch x := c.Fun.(type) {
|
||||
case *ast.Ident:
|
||||
name = x.Name
|
||||
case *ast.SelectorExpr:
|
||||
name = x.Sel.Name
|
||||
}
|
||||
switch name {
|
||||
case "NewLayoutWorkspaceHEADReader", "WorkspaceLayoutVolume":
|
||||
found[filepath.ToSlash(rel)+" "+fn.Name.Name+" -> "+name]++
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(want, found) {
|
||||
t.Fatalf("HEAD reader wiring changed; classify and probe the new site: want %v, got %v", want, found)
|
||||
}
|
||||
}
|
||||
@@ -5,55 +5,55 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// Automatic GC stays default-off until restart-safe unknown-CAS settlement and
|
||||
// the 50/200-volume root-scan measurement both pass. Retention remains enabled.
|
||||
// The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD
|
||||
// hydration reader at thirty seconds. A one-minute mark fits strictly inside
|
||||
// the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry.
|
||||
func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string, masterTLS grpc.DialOption) (func(context.Context, string) error, func() error, error) {
|
||||
closeFn := func() error { return nil }
|
||||
cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL}
|
||||
if collect {
|
||||
if master == "" {
|
||||
return nil, closeFn, errors.New("automatic chunk GC requires blockmaster authority")
|
||||
}
|
||||
if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout {
|
||||
return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds")
|
||||
}
|
||||
conn, err := link.DialMaster(master, masterTLS, link.MasterReconnect())
|
||||
if err != nil {
|
||||
return nil, closeFn, err
|
||||
}
|
||||
closeFn = conn.Close
|
||||
evidence := control.NewEvidenceServiceClient(conn)
|
||||
cfg.IssuedEpoch = func(ctx context.Context, vol string) (uint64, error) {
|
||||
reply, err := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 {
|
||||
return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol)
|
||||
}
|
||||
return reply.Epoch, nil
|
||||
}
|
||||
}
|
||||
// errNoLayoutHolder: the process has no holder identity for the volume yet
|
||||
// (it is not attached, or Start has not returned), so it does not clean.
|
||||
var errNoLayoutHolder = errors.New("blockvolume: no layout holder identity for the volume")
|
||||
|
||||
// newChunkMaintenance is the holder's periodic pass over its one volume ref:
|
||||
// retention, then, when collect is set, the cleaning through the holder's
|
||||
// own layout remote (remote.Clean with the catalog's removal step), the one
|
||||
// cleaning entry: a cut or a stop cancels it through the remote's state.
|
||||
// cleanerOf returns the remote Start established; its Begin refuses unless
|
||||
// HEAD is still that holder's at its epoch, so a process that lost the
|
||||
// volume removes nothing. Automatic cleaning stays default-off; retention runs either way.
|
||||
// layoutCleaner is the holder's layout remote as the maintenance cleans
|
||||
// through it (chunkstore.LayoutRemote).
|
||||
type layoutCleaner interface {
|
||||
Clean(ctx context.Context, run func(ctx context.Context, me layout.HolderID, session string) error) error
|
||||
}
|
||||
|
||||
func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cleanerOf func(context.Context) (layoutCleaner, error), collect bool, now func() time.Time) func(context.Context, string) error {
|
||||
return func(ctx context.Context, vol string) error {
|
||||
retained, err := cat.Retain(ctx, vol, false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("retain deleted=%d not_attempted=%d: %w", len(retained.Deleted), len(retained.NotAttempted), err)
|
||||
if cat == nil || vol != ref.Name || ref.ID.IsZero() {
|
||||
return fmt.Errorf("%w: maintenance of %q, process holds %q", layout.ErrIdentity, vol, ref.Name)
|
||||
}
|
||||
if _, err := cat.Retain(ctx, ref, now(), false); err != nil {
|
||||
return fmt.Errorf("retain: %w", err)
|
||||
}
|
||||
if !collect {
|
||||
return nil
|
||||
}
|
||||
out, err := cat.ExecuteVolumeGC(ctx, vol, blobs, cfg, true)
|
||||
log.Printf("blockvolume: maintenance volume=%s mark=%s reclaimed=%d settled=%d unknown=%v", vol, out.MarkOutcome, out.Reclaimed, out.SettledCopies, out.UnknownOutcomes)
|
||||
return err
|
||||
}, closeFn, nil
|
||||
remote, err := cleanerOf(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var res chunkstore.CleanResult
|
||||
var session string
|
||||
err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error {
|
||||
session = s
|
||||
var rerr error
|
||||
res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s)
|
||||
return rerr
|
||||
})
|
||||
log.Printf("blockvolume: maintenance volume=%s clean=%s shards=%d planned=%d removed=%d", vol, session, res.Shards, res.Planned, res.Removed)
|
||||
// A cleaning refused because HEAD moved away from this holder is
|
||||
// the same fence a cut would see: classified so the provider latches.
|
||||
return chunkstore.LayoutErr(err)
|
||||
}
|
||||
}
|
||||
@@ -1,114 +1,189 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"fmt"
|
||||
"path"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type maintenanceGCFiler struct {
|
||||
chunkstore.Filer
|
||||
gcCalls, marked, freed int
|
||||
failSecond bool
|
||||
// maintenanceBlobs is an in-memory needle store.
|
||||
type maintenanceBlobs struct {
|
||||
mu sync.Mutex
|
||||
n int
|
||||
d map[string][]byte
|
||||
}
|
||||
|
||||
func (f *maintenanceGCFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if name == "_GC_MARK" {
|
||||
f.gcCalls++
|
||||
return nil, errors.New("witness: GC reached")
|
||||
}
|
||||
return f.Filer.LookupEntry(ctx, dir, name)
|
||||
func (b *maintenanceBlobs) Put(_ context.Context, data []byte) (string, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.n++
|
||||
fid := fmt.Sprintf("1,%x", b.n)
|
||||
b.d[fid] = append([]byte(nil), data...)
|
||||
return fid, nil
|
||||
}
|
||||
func (f *maintenanceGCFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if string(e.Extended["swb.snap.state"]) == chunkstore.SnapDeleting {
|
||||
if f.failSecond && f.marked == 1 {
|
||||
return errors.New("second retention mark refused")
|
||||
|
||||
func (b *maintenanceBlobs) Get(_ context.Context, fid string) ([]byte, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
d, ok := b.d[fid]
|
||||
if !ok {
|
||||
return nil, chunkstore.ErrBlobNotFound
|
||||
}
|
||||
return append([]byte(nil), d...), nil
|
||||
}
|
||||
|
||||
// failingLookups fails every entry lookup once armed (a filer gone away).
|
||||
type failingLookups struct {
|
||||
*chunkstore.MemFiler
|
||||
armed bool
|
||||
}
|
||||
|
||||
func (f *failingLookups) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if f.armed {
|
||||
return nil, errors.New("filer: unavailable")
|
||||
}
|
||||
return f.MemFiler.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
type okLease struct{}
|
||||
|
||||
func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil }
|
||||
|
||||
var maintenanceHolder = layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
|
||||
// maintenanceFixture is volume v1 started by maintenanceHolder, with one
|
||||
// orphan chunk in shard 0 that no root names.
|
||||
func maintenanceFixture(t *testing.T) (*chunkstore.BCatalog, chunkstore.VolumeRef, *failingLookups, *chunkstore.LayoutStore, layout.ChunkName) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
f := &failingLookups{MemFiler: chunkstore.NewMemFiler()}
|
||||
cat, err := chunkstore.NewBCatalog(f, &maintenanceBlobs{d: map[string][]byte{}}, "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
|
||||
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := bytes.Repeat([]byte{9}, 4096)
|
||||
orphan := layout.NameChunk(3, data)
|
||||
if err := layout.EnsureObject(ctx, s, orphan.Path(), data, "dead-session"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A real filer lists the shard directory it created; the in-memory one
|
||||
// keeps only entries.
|
||||
if err := f.CreateEntry(ctx, path.Join("/blocks", ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cat, ref, f, s, orphan
|
||||
}
|
||||
|
||||
func orphanPresent(t *testing.T, s *chunkstore.LayoutStore, n layout.ChunkName) bool {
|
||||
t.Helper()
|
||||
_, found, err := s.Stat(context.Background(), n.Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// holderCalls is the attachment's layout remote for holder me (or err when
|
||||
// the process has no holder identity yet), counting the calls.
|
||||
func holderCalls(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, me layout.HolderID, err error) (func(context.Context) (layoutCleaner, error), *int) {
|
||||
n := 0
|
||||
return func(context.Context) (layoutCleaner, error) {
|
||||
n++
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.marked++
|
||||
}
|
||||
return f.Filer.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
func (f *maintenanceGCFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
|
||||
if err == nil && path.Base(dir) == "snapnames" {
|
||||
f.freed++
|
||||
}
|
||||
return err
|
||||
return chunkstore.NewLayoutRemote(cat, ref, me)
|
||||
}, &n
|
||||
}
|
||||
|
||||
type maintenanceBlobs struct{}
|
||||
|
||||
func (maintenanceBlobs) DeleteBlob(context.Context, string) error { return nil }
|
||||
func (maintenanceBlobs) Put(context.Context, []byte) (string, error) { return "unused", nil }
|
||||
func (maintenanceBlobs) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("unexpected blob read")
|
||||
// Default-off: the pass retains and never asks for a holder or removes.
|
||||
func TestMaintenanceDefaultRetainsAndDoesNotClean(t *testing.T) {
|
||||
cat, ref, _, s, orphan := maintenanceFixture(t)
|
||||
holder, calls := holderCalls(cat, ref, maintenanceHolder, nil)
|
||||
pass := newChunkMaintenance(cat, ref, holder, false, time.Now)
|
||||
if err := pass(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *calls != 0 || !orphanPresent(t, s, orphan) {
|
||||
t.Fatalf("default pass: holder asked %d times, orphan present %v; want 0, true", *calls, orphanPresent(t, s, orphan))
|
||||
}
|
||||
}
|
||||
func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) {
|
||||
for _, partial := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "missing", true: "partial"}[partial], func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := &maintenanceGCFiler{Filer: chunkstore.NewMemFiler(), failSecond: partial}
|
||||
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
// With collect on, the holder's pass removes the orphan; a process with
|
||||
// another claim, or with no holder identity yet, removes nothing.
|
||||
func TestMaintenanceCleansOnlyAsTheHolder(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for name, tc := range map[string]struct {
|
||||
me layout.HolderID
|
||||
err error
|
||||
removed bool
|
||||
}{
|
||||
"holder": {me: maintenanceHolder, removed: true},
|
||||
"other claim": {me: layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "old"}},
|
||||
"next epoch": {me: layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"}},
|
||||
"no identity": {err: errNoLayoutHolder},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
cat, ref, _, s, orphan := maintenanceFixture(t)
|
||||
holder, _ := holderCalls(cat, ref, tc.me, tc.err)
|
||||
err := newChunkMaintenance(cat, ref, holder, true, time.Now)(ctx, "v1")
|
||||
if gone := !orphanPresent(t, s, orphan); gone != tc.removed || (err == nil) != tc.removed {
|
||||
t.Fatalf("pass: err %v, orphan removed %v; want removed %v", err, gone, tc.removed)
|
||||
}
|
||||
vol := "missing-volume"
|
||||
if partial {
|
||||
vol = "v1"
|
||||
if _, err = cat.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = cat.SetRetentionPolicy(ctx, vol, chunkstore.RetentionPolicy{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().Add(-48 * time.Hour)
|
||||
cat.SetClock(func() time.Time { return now })
|
||||
for _, name := range []string{"a", "b"} {
|
||||
if _, err = cat.CreateSnapshot(ctx, vol, chunkstore.SnapshotRequest{Name: name, RequestID: "req"}, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(time.Second)
|
||||
}
|
||||
now = time.Now()
|
||||
if tc.err != nil && !errors.Is(err, tc.err) {
|
||||
t.Fatalf("pass: %v; want %v", err, tc.err)
|
||||
}
|
||||
pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeFn()
|
||||
if err = pass(ctx, vol); err == nil {
|
||||
t.Fatal("retention failure accepted")
|
||||
}
|
||||
if f.gcCalls != 0 {
|
||||
t.Fatalf("retention failure entered GC %d times", f.gcCalls)
|
||||
}
|
||||
if partial && (f.marked != 1 || f.freed != 1) {
|
||||
t.Fatalf("partial retention effects not retained: marked=%d freed=%d err=%v", f.marked, f.freed, err)
|
||||
// HEAD is another claim's or epoch's: the refusal is the fence a
|
||||
// cut would see, so the provider latches the layer on it.
|
||||
if (name == "other claim" || name == "next epoch") && !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("pass refused as %v; want it classified as the fence", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) {
|
||||
f := chunkstore.NewMemFiler()
|
||||
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// A failed retention ends the pass before the cleaning starts.
|
||||
func TestMaintenanceRetentionFailureNeverStartsCleaning(t *testing.T) {
|
||||
cat, ref, f, s, orphan := maintenanceFixture(t)
|
||||
holder, calls := holderCalls(cat, ref, maintenanceHolder, nil)
|
||||
f.armed = true
|
||||
err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v1")
|
||||
f.armed = false
|
||||
if err == nil || *calls != 0 || !orphanPresent(t, s, orphan) {
|
||||
t.Fatalf("pass with retention failing: err %v, holder asked %d, orphan present %v", err, *calls, orphanPresent(t, s, orphan))
|
||||
}
|
||||
if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pass, closeFn, err := newChunkMaintenance(cat, nil, false, "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer closeFn()
|
||||
if err = pass(context.Background(), "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The pass serves only the volume the process was started for.
|
||||
func TestMaintenanceRefusesAnotherVolume(t *testing.T) {
|
||||
cat, ref, _, _, _ := maintenanceFixture(t)
|
||||
holder, _ := holderCalls(cat, ref, maintenanceHolder, nil)
|
||||
if err := newChunkMaintenance(cat, ref, holder, true, time.Now)(context.Background(), "v2"); !errors.Is(err, layout.ErrIdentity) {
|
||||
t.Fatalf("pass for another volume: %v; want ErrIdentity", err)
|
||||
}
|
||||
}
|
||||
@@ -15,22 +15,20 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultChunkPath = "/swblock/chunks"
|
||||
defaultChunkPath = chunkstore.DefaultChunkPath
|
||||
// Periodic HEAD publication bounds the host-loss recovery point. Scheduled
|
||||
// named snapshots are set by --chunk-snapshot-schedule.
|
||||
defaultChunkCaptureInterval = 0
|
||||
defaultChunkMaintenanceInterval = time.Hour
|
||||
defaultChunkCutTimeout = 5 * time.Minute
|
||||
defaultChunkMaintenanceTimeout = time.Minute
|
||||
defaultChunkGCGrace = time.Hour
|
||||
defaultChunkIntentTTL = time.Hour
|
||||
)
|
||||
|
||||
type chunkFlags struct {
|
||||
@@ -155,16 +153,14 @@ func (s *snapshotSchedule) Set(v string) error {
|
||||
}
|
||||
|
||||
type chunkWiring struct {
|
||||
remoteFor func(volumeID string) (storage.ChunkRemote, error)
|
||||
catalog *chunkstore.Catalog
|
||||
maintenance func(context.Context, string) error
|
||||
close func() error
|
||||
bCatalog *chunkstore.BCatalog
|
||||
close func() error
|
||||
}
|
||||
|
||||
// newChunkWiring dials the filer and refuses unless it is the only filer of
|
||||
// its group (chunkstore.CheckSingleFiler).
|
||||
func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) (chunkWiring, error) {
|
||||
client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{
|
||||
bcat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{
|
||||
FilerGRPC: c.filer,
|
||||
Collection: c.collection,
|
||||
Replication: c.replication,
|
||||
@@ -173,47 +169,42 @@ func newChunkWiring(c chunkFlags, masterTLS grpc.DialOption, master ...string) (
|
||||
if err != nil {
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
// Deployment rule: block metadata goes through exactly one filer.
|
||||
if err := client.CheckSingleFiler(context.Background()); err != nil {
|
||||
_ = client.Close()
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
cat, err := chunkstore.NewCatalog(client, c.path)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
var masterAddr string
|
||||
if len(master) > 0 {
|
||||
masterAddr = master[0]
|
||||
}
|
||||
maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr, masterTLS)
|
||||
if err != nil {
|
||||
_ = client.Close()
|
||||
return chunkWiring{}, err
|
||||
}
|
||||
return chunkWiring{
|
||||
maintenance: maintenance,
|
||||
remoteFor: func(volumeID string) (storage.ChunkRemote, error) {
|
||||
root, err := chunkVolumeRoot(c.path, volumeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chunkstore.NewSWFSChunkRemote(client, root)
|
||||
},
|
||||
catalog: cat,
|
||||
close: func() error { return errors.Join(closeMaintenance(), client.Close()) },
|
||||
bCatalog: bcat,
|
||||
close: client.Close,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// chunkAttachCheck applies the VOLUME entry's attach rules before the chunk
|
||||
// layer attaches (B9 W2 §4.2): create VOLUME from the local geometry when
|
||||
// it is missing, refuse geometry_mismatch, and refuse fork_incomplete for a
|
||||
// fork whose HEAD is not written yet.
|
||||
func chunkAttachCheck(cat *chunkstore.Catalog) func(context.Context, string, durable.ChunkGeometry) error {
|
||||
return func(ctx context.Context, volumeID string, g durable.ChunkGeometry) error {
|
||||
_, err := cat.EnsureVolume(ctx, volumeID, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks})
|
||||
return err
|
||||
// chunkAttachCheck admits only a volume the master already created in the
|
||||
// store. Starting a holder never creates VOLUME or HEAD.
|
||||
func chunkAttachCheck(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef) func(context.Context, string, durable.ChunkGeometry) error {
|
||||
return func(ctx context.Context, name string, g durable.ChunkGeometry) error {
|
||||
if cat == nil || name != ref.Name || ref.ID.IsZero() {
|
||||
return layout.ErrIdentity
|
||||
}
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, found, err := st.ReadVolumeRecord(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("%w: volume %s not created in the store", layout.ErrMissing, name)
|
||||
}
|
||||
want := layout.Geometry{SizeBytes: g.NumBlocks * uint64(g.BlockSize), BlockSize: g.BlockSize, ChunkBytes: uint64(g.ChunkBlocks) * uint64(g.BlockSize)}
|
||||
if v.Geometry != want {
|
||||
return fmt.Errorf("%w: local %+v differs from VOLUME %+v", layout.ErrGeometryMismatch, want, v.Geometry)
|
||||
}
|
||||
_, found, err = cat.ReadHead(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("%w: volume %s not created in the store", layout.ErrHeadAbsent, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,33 +213,31 @@ func chunkAttachCheck(cat *chunkstore.Catalog) func(context.Context, string, dur
|
||||
// volume record stays wrong until the operator changes the flag.
|
||||
const exitGeometryRefused = 78
|
||||
|
||||
// geometryFlagsRefusal compares the geometry flags with the volume record
|
||||
// before any local store is created, so a wrong flag never leaves a store of
|
||||
// the wrong size behind. It returns the refusal line and its exit status:
|
||||
// exitGeometryRefused (78) when the record disagrees or is there but does not
|
||||
// decode; exitWorkspaceRetry (75) when the filer could not be read (an
|
||||
// unknown, never taken as "absent"); ("", 0) when the record agrees, does
|
||||
// not exist yet (the attach
|
||||
// check creates it from the flags), or no store is being created (numBlocks
|
||||
// 0: an existing store opens with its own geometry).
|
||||
func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.Catalog, volumeID string, numBlocks uint64, blockSize uint32) (string, int) {
|
||||
// geometryFlagsRefusal reads only the immutable size_bytes, block_size and
|
||||
// chunk_bytes of VOLUME before creating a local store. An unreadable record
|
||||
// is unknown (75); corrupt bytes or a mismatch are final refusals (78).
|
||||
func geometryFlagsRefusal(ctx context.Context, cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, numBlocks uint64, blockSize uint32, chunkBlocks uint32) (string, int) {
|
||||
if numBlocks == 0 {
|
||||
return "", 0 // an existing store: the flags are not used
|
||||
}
|
||||
v, ok, err := cat.ReadVolume(ctx, volumeID)
|
||||
if err != nil && chunkstore.CodeOf(err) == chunkstore.CodeRemoteUnavailable {
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", volumeID, err), exitWorkspaceRetry
|
||||
}
|
||||
if err != nil {
|
||||
// A record that is there but does not decode stays that way: a
|
||||
// permanent refusal, not a retry loop.
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", volumeID, err), exitGeometryRefused
|
||||
}
|
||||
if !ok || (v.NumBlocks == numBlocks && v.BlockSize == blockSize) {
|
||||
return "", 0
|
||||
}
|
||||
return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d disagree with the volume record of %s (%d blocks of %d bytes); no local store was created; start it with the record's geometry",
|
||||
numBlocks, blockSize, volumeID, v.NumBlocks, v.BlockSize), exitGeometryRefused
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("blockvolume: invalid volume identity: %v", err), exitGeometryRefused
|
||||
}
|
||||
v, found, err := st.ReadVolumeRecord(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, layout.ErrMalformed) || errors.Is(err, layout.ErrCorrupt) || errors.Is(err, layout.ErrIdentity) {
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s is unreadable (corrupt: %v); no local store was created; restore or recreate the record", ref.Name, err), exitGeometryRefused
|
||||
}
|
||||
return fmt.Sprintf("blockvolume: the volume record of %s could not be read (%v); no local store was created; retrying", ref.Name, err), exitWorkspaceRetry
|
||||
}
|
||||
if !found {
|
||||
return fmt.Sprintf("blockvolume: volume %s was not created in the store; no local store was created; retry the master CreateVolume operation", ref.Name), exitGeometryRefused
|
||||
}
|
||||
if v.SizeBytes == numBlocks*uint64(blockSize) && v.BlockSize == blockSize && v.ChunkBytes == uint64(chunkBlocks)*uint64(blockSize) {
|
||||
return "", 0
|
||||
}
|
||||
return fmt.Sprintf("blockvolume: geometry_mismatch: --durable-blocks %d --durable-blocksize %d --chunk-blocks %d disagree with the volume record of %s (%d blocks of %d bytes, chunk_bytes %d); no local store was created; start it with the record's geometry", numBlocks, blockSize, chunkBlocks, ref.Name, v.SizeBytes/uint64(v.BlockSize), v.BlockSize, v.ChunkBytes), exitGeometryRefused
|
||||
}
|
||||
|
||||
// chunkHolder is how this host names itself in HEAD: <server-id>/<replica-id>
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
@@ -120,73 +121,53 @@ func TestChunkVolumeRootStaysInsideBase(t *testing.T) {
|
||||
// Before any local store is created, a geometry flag that disagrees with the
|
||||
// volume record is refused with a line naming both (78); a record the filer
|
||||
// could not deliver is refused as retryable (75), never taken as "absent";
|
||||
// a record that is there but does not decode is refused for good (78); a matching
|
||||
// record, a missing record (the attach check creates it) and an existing
|
||||
// store (no create geometry) are not refused.
|
||||
// a record that is there but does not decode is refused for good (78);
|
||||
// a missing record is also refused (78), while matching geometry proceeds.
|
||||
func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath)
|
||||
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 32768, 4096); got != "" || code != 0 {
|
||||
t.Fatalf("no record yet: %q, %d", got, code)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 65536, 4096); got != "" || code != 0 {
|
||||
t.Fatalf("matching flags refused: %q, %d", got, code)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
blocks uint64
|
||||
size uint32
|
||||
}{{32768, 4096}, {65536, 512}} {
|
||||
got, code := geometryFlagsRefusal(ctx, cat, "v1", c.blocks, c.size)
|
||||
if code != exitGeometryRefused {
|
||||
t.Fatalf("flags %d x %d: exit %d, want %d", c.blocks, c.size, code, exitGeometryRefused)
|
||||
}
|
||||
for _, want := range []string{"geometry_mismatch", "--durable-blocks", "65536 blocks of 4096 bytes"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("flags %d x %d: refusal %q lacks %q", c.blocks, c.size, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, "v1", 0, 0); got != "" || code != 0 {
|
||||
t.Fatalf("an existing store (no create geometry) must not be refused: %q, %d", got, code)
|
||||
}
|
||||
// An unreadable record: the same valid volume over a filer whose
|
||||
// lookups fail. The record is read, fails, and the start is refused as
|
||||
// retryable before anything is created.
|
||||
failing := &lookupFailFiler{MemFiler: chunkstore.NewMemFiler()}
|
||||
failCat, err := chunkstore.NewCatalog(failing, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := failCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failing.fail, failing.reads = true, 0
|
||||
for _, blocks := range []uint64{32768, 65536} { // a wrong and a right flag alike
|
||||
got, code := geometryFlagsRefusal(ctx, failCat, "v1", blocks, 4096)
|
||||
if code != exitWorkspaceRetry || !strings.Contains(got, "the volume record of v1 could not be read") || !strings.Contains(got, "no local store was created; retrying") {
|
||||
t.Fatalf("--durable-blocks %d over an unreadable record: %q, exit %d; want a retryable refusal (%d)", blocks, got, code, exitWorkspaceRetry)
|
||||
}
|
||||
}
|
||||
if failing.reads == 0 {
|
||||
t.Fatal("the unreadable-record case never read the record")
|
||||
}
|
||||
// A record that is there but does not decode: a permanent refusal
|
||||
// (78), not a retry loop, for a wrong and a right flag alike.
|
||||
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
|
||||
mem := chunkstore.NewMemFiler()
|
||||
corruptCat, err := chunkstore.NewCatalog(mem, defaultChunkPath)
|
||||
blobs := &maintenanceBlobs{d: map[string][]byte{}}
|
||||
cat, err := chunkstore.NewBCatalog(mem, blobs, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := corruptCat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 65536, BlockSize: 4096, ChunkBlocks: 1024}); err != nil {
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, ref, 32768, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "not created in the store") {
|
||||
t.Fatal("missing VOLUME must refuse attach", got, code)
|
||||
}
|
||||
g := layout.Geometry{SizeBytes: 65536 * 4096, BlockSize: 4096, ChunkBytes: 1024 * 4096}
|
||||
if _, err := cat.CreateVolume(ctx, ref, g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := path.Join(defaultChunkPath, "v1")
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); got != "" || code != 0 {
|
||||
t.Fatal(got, code)
|
||||
}
|
||||
for _, g := range []struct {
|
||||
blocks uint64
|
||||
size, chunk uint32
|
||||
}{{32768, 4096, 1024}, {65536, 512, 1024}, {65536, 4096, 512}} {
|
||||
got, code := geometryFlagsRefusal(ctx, cat, ref, g.blocks, g.size, g.chunk)
|
||||
if code != exitGeometryRefused || !strings.Contains(got, "geometry_mismatch") || !strings.Contains(got, "65536 blocks of 4096 bytes") {
|
||||
t.Fatalf("mismatch: %q %d", got, code)
|
||||
}
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, ref, 0, 0, 0); got != "" || code != 0 {
|
||||
t.Fatal(got, code)
|
||||
}
|
||||
failing := &lookupFailFiler{MemFiler: mem, fail: true}
|
||||
failCat, err := chunkstore.NewBCatalog(failing, blobs, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, failCat, ref, 65536, 4096, 1024); code != exitWorkspaceRetry || !strings.Contains(got, "could not be read") || failing.reads == 0 {
|
||||
t.Fatal(got, code, failing.reads)
|
||||
}
|
||||
dir := path.Join(defaultChunkPath, ref.Dir())
|
||||
e, err := mem.LookupEntry(ctx, dir, "VOLUME")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -195,12 +176,10 @@ func TestGeometryFlagsRefusalComparesTheRecord(t *testing.T) {
|
||||
if err := mem.UpdateEntry(ctx, dir, e, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, blocks := range []uint64{32768, 65536} {
|
||||
got, code := geometryFlagsRefusal(ctx, corruptCat, "v1", blocks, 4096)
|
||||
if code != exitGeometryRefused || !strings.Contains(got, "the volume record of v1 is unreadable (corrupt:") || !strings.Contains(got, "no local store was created") {
|
||||
t.Fatalf("--durable-blocks %d over a corrupt record: %q, exit %d; want a permanent refusal (%d)", blocks, got, code, exitGeometryRefused)
|
||||
}
|
||||
if got, code := geometryFlagsRefusal(ctx, cat, ref, 65536, 4096, 1024); code != exitGeometryRefused || !strings.Contains(got, "unreadable (corrupt:") {
|
||||
t.Fatal(got, code)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// lookupFailFiler is a MemFiler whose LookupEntry fails once fail is set; it
|
||||
@@ -219,32 +198,54 @@ func (f *lookupFailFiler) LookupEntry(ctx context.Context, dir, name string) (*f
|
||||
return f.MemFiler.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
// The attach check is the VOLUME entry's attach rules (B9 W2 §4.2): the first
|
||||
// attach creates VOLUME from the local geometry, a later attach with the same
|
||||
// geometry passes, and another geometry is refused.
|
||||
// Attach only reads the master's identified VOLUME and HEAD.
|
||||
func TestChunkAttachCheckAppliesVolumeRules(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cat, err := chunkstore.NewCatalog(chunkstore.NewMemFiler(), defaultChunkPath)
|
||||
f := &layoutAttachFiler{MemFiler: chunkstore.NewMemFiler()}
|
||||
cat, err := chunkstore.NewBCatalog(f, f, defaultChunkPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check := chunkAttachCheck(cat)
|
||||
id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff")
|
||||
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
|
||||
check := chunkAttachCheck(cat, ref)
|
||||
g := durable.ChunkGeometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
|
||||
if err := check(ctx, "v1", g); err != nil {
|
||||
t.Fatalf("first attach: %v", err)
|
||||
if err := check(ctx, "v1", g); !errors.Is(err, layout.ErrMissing) {
|
||||
t.Fatal("attach created a missing volume", err)
|
||||
}
|
||||
v, ok, err := cat.ReadVolume(ctx, "v1")
|
||||
if err != nil || !ok || v.Origin != chunkstore.OriginCreate || v.Geometry != (chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}) {
|
||||
t.Fatalf("VOLUME after the first attach: %+v ok=%v %v", v, ok, err)
|
||||
if _, found, err := cat.ReadHead(ctx, ref); err != nil || found {
|
||||
t.Fatal("attach created a missing HEAD", found, err)
|
||||
}
|
||||
if err := check(ctx, "v1", g); err != nil {
|
||||
t.Fatalf("attach with the same geometry: %v", err)
|
||||
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 8 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := g
|
||||
other.NumBlocks = 128
|
||||
if err := check(ctx, "v1", other); chunkstore.CodeOf(err) != chunkstore.CodeGeometryMismatch {
|
||||
t.Fatalf("attach with another geometry: %v, want geometry_mismatch", err)
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := check(ctx, "v1", g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h, found, err := cat.ReadHead(ctx, ref)
|
||||
if err != nil || !found || h.VolumeID != id || h.Epoch != 0 || h.Holder != "" || h.Current != nil {
|
||||
t.Fatalf("unclaimed HEAD: %+v %v", h, err)
|
||||
}
|
||||
if err := check(ctx, "other", g); !errors.Is(err, layout.ErrIdentity) {
|
||||
t.Fatalf("wrong name: %v", err)
|
||||
}
|
||||
if err := chunkAttachCheck(cat, chunkstore.VolumeRef{Name: "v1"})(ctx, "v1", g); !errors.Is(err, layout.ErrIdentity) {
|
||||
t.Fatalf("missing master id: %v", err)
|
||||
}
|
||||
if found, err := f.LookupEntry(ctx, defaultChunkPath+"/v1", "VOLUME"); err == nil || found != nil {
|
||||
t.Fatalf("legacy directory created: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type layoutAttachFiler struct{ *chunkstore.MemFiler }
|
||||
|
||||
func (*layoutAttachFiler) Put(context.Context, []byte) (string, error) {
|
||||
return "", errors.New("attach must not upload data")
|
||||
}
|
||||
func (*layoutAttachFiler) Get(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("attach must not read data")
|
||||
}
|
||||
|
||||
// HEAD names a host as <server-id>/<replica-id>: two servers serving the same
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestCutoverCreateFromSnapshot pins the public master create contract: one
|
||||
// request creates the target identity and its restored image together.
|
||||
func TestCutoverCreateFromSnapshot(t *testing.T) {
|
||||
env := startCutoverLayoutEnv(t, false)
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
source := startCutoverVolume(t, env, "restore-source", "s1")
|
||||
env.adopt(t, source, "s1")
|
||||
env.writeBlock(t, "s1", 5, pattern("restore-seam-A!!"))
|
||||
env.snapshot(t, "s1", "v1", "restore-seam")
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "restore-seam", "--target", "v2",
|
||||
"--master", env.h.masterAddr)
|
||||
target := startCutoverVolume(t, env, "restored-target", "n-v2")
|
||||
target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@")
|
||||
poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") })
|
||||
env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, map[uint64][]byte{5: pattern("restore-seam-A!!")})
|
||||
}
|
||||
|
||||
// TestCutoverWriteSnapshotKillRestartRestore follows the public path through
|
||||
// real binaries, a stock filer and the NVMe frontend. The guest is quiescent
|
||||
// at snapshot and kill; process kill is not a power-loss durability claim.
|
||||
func TestCutoverWriteSnapshotKillRestartRestore(t *testing.T) {
|
||||
env := startCutoverLayoutEnv(t, false)
|
||||
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
|
||||
source := startCutoverVolume(t, env, "source-before-kill", "s1")
|
||||
env.adopt(t, source, "s1")
|
||||
a, b, c := pattern("cutover-block-A!"), pattern("cutover-block-B!"), pattern("cutover-block-C!")
|
||||
before := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b}
|
||||
env.writeBlock(t, "s1", 5, a)
|
||||
env.writeBlock(t, "s1", 2*ladderChunkBlocks+7, b)
|
||||
env.snapshot(t, "s1", "v1", "before-kill")
|
||||
// A later synced write must survive restart but must not enter the snapshot.
|
||||
env.writeBlock(t, "s1", 4*ladderChunkBlocks+9, c)
|
||||
source.kill(t)
|
||||
if err := source.proc.Signal(syscall.Signal(0)); err == nil {
|
||||
t.Fatal("the killed source process still exists")
|
||||
}
|
||||
restarted := startCutoverVolume(t, env, "source-after-kill", "s1")
|
||||
env.adopt(t, restarted, "s1")
|
||||
after := map[uint64][]byte{5: a, 2*ladderChunkBlocks + 7: b, 4*ladderChunkBlocks + 9: c}
|
||||
env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after)
|
||||
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "before-kill", "--target", "v2",
|
||||
"--master", env.h.masterAddr)
|
||||
target := startCutoverVolume(t, env, "restored-target", "n-v2")
|
||||
target.waitLog(t, 60*time.Second, "blockvolume: volume v2 adopted as PRIMARY at r1@")
|
||||
poll(t, 60*time.Second, "restored target never ready", func() bool { return volumeFrontendReady(env.hosts["n-v2"].status, "v2") })
|
||||
env.requireBlocks(t, "n-v2", 0, ladderLastBlock+1, before)
|
||||
env.requireBlocks(t, "s1", 0, ladderLastBlock+1, after)
|
||||
}
|
||||
|
||||
func startCutoverLayoutEnv(t *testing.T, precreateTarget bool) *handoffEnv {
|
||||
t.Helper()
|
||||
var tlsCfg map[string]time.Time
|
||||
if procedureTLSOn() {
|
||||
tlsCfg = map[string]time.Time{}
|
||||
}
|
||||
return startHandoffEnvConfigured(t, 1, []string{"v2"}, tlsCfg, precreateTarget)
|
||||
}
|
||||
|
||||
func startCutoverVolume(t *testing.T, env *handoffEnv, label, host string) *daemon {
|
||||
t.Helper()
|
||||
return env.h.start(t, label, env.h.volume, env.volArgs(host)...)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
@@ -109,9 +110,13 @@ func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing
|
||||
if _, _, err = durableCreateGeometry(f); err == nil {
|
||||
t.Fatal("fresh recheck accepted original overflowing count")
|
||||
}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
|
||||
return nil, errors.New("unexpected remote access for missing open-only volume")
|
||||
}}, healthyView{})
|
||||
cfg := durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs}
|
||||
if impl == durable.ImplWALStoreChunk {
|
||||
unexpected := errors.New("unexpected layout access for missing open-only volume")
|
||||
cfg.ChunkLayoutHeadFor = func(string) (layout.StartStore, error) { return nil, unexpected }
|
||||
cfg.ChunkLayoutRemoteFor = func(string, layout.HolderID) (storage.ChunkRemote, error) { return nil, unexpected }
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBlockvolumeLayoutIdentitySelectsTheLocalRoot(t *testing.T) {
|
||||
base := []string{"--master=127.0.0.1:9333", "--server-id=s1", "--volume-id=v", "--replica-id=r1", "--data-addr=127.0.0.1:19101", "--ctrl-addr=127.0.0.1:19102", "--durable-root=" + t.TempDir()}
|
||||
first, err := parseFlags(append(append([]string{}, base...), "--layout-id=1234567890abcdef1234567890abcdef"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if filepath.Base(first.durableRoot) != "v-12345678" {
|
||||
t.Fatal(first.durableRoot)
|
||||
}
|
||||
second, err := parseFlags(append(append([]string{}, base...), "--layout-id=abcdef1290abcdef1234567890abcdef"))
|
||||
if err != nil || second.durableRoot == first.durableRoot {
|
||||
t.Fatalf("different incarnation reused local root: %v", err)
|
||||
}
|
||||
if _, err := parseFlags(append(append([]string{}, base...), "--layout-id=bad")); err == nil {
|
||||
t.Fatal("malformed identity accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//go:build subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// layoutMasterWriter gives an in-process master the layout writer a
|
||||
// production master gets from --chunk-filer: CreateVolume writes the VOLUME
|
||||
// and the unclaimed HEAD under base on the test filer before the record is
|
||||
// store-ready.
|
||||
func layoutMasterWriter(t *testing.T, cluster *w4WeedCluster, base string) func(context.Context, lifecycle.VolumeSpec) error {
|
||||
t.Helper()
|
||||
cat, client, err := chunkstore.DialBCatalog(context.Background(), chunkstore.SWFSConfig{FilerGRPC: cluster.filerGRPC, AssignPath: base})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { client.Close() })
|
||||
return func(ctx context.Context, spec lifecycle.VolumeSpec) error {
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = cat.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id}, layout.Geometry{
|
||||
SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes})
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// createStoreReadyVolume creates a volume through the master's public create,
|
||||
// the path production uses, and requires the record to come back store-ready.
|
||||
func createStoreReadyVolume(t *testing.T, h *master.Host, volume string, sizeBytes uint64) layout.VolumeID {
|
||||
t.Helper()
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
resp, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: volume, SizeBytes: sizeBytes, ReplicationFactor: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("create %s through the master: %v", volume, err)
|
||||
}
|
||||
if !resp.GetStoreReady() {
|
||||
t.Fatalf("create %s: the master answered store_ready=false", volume)
|
||||
}
|
||||
id, err := layout.ParseVolumeID(resp.GetLayoutId())
|
||||
if err != nil {
|
||||
t.Fatalf("master-minted layout id %q: %v", resp.GetLayoutId(), err)
|
||||
}
|
||||
if rec, ok := h.Lifecycle().Volumes.GetVolume(volume); !ok || !rec.StoreReady {
|
||||
t.Fatal(fmt.Sprintf("lifecycle record of %s is not store-ready after the create", volume))
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/adapter"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/memback"
|
||||
@@ -46,6 +48,7 @@ type flags struct {
|
||||
masterAddr string
|
||||
serverID string
|
||||
volumeID string
|
||||
layoutID string
|
||||
replicaID string
|
||||
dataAddr string
|
||||
ctrlAddr string
|
||||
@@ -186,6 +189,7 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.masterTLS.Key, "master-tls-key", "", "the key of --master-tls-cert (PEM)")
|
||||
fs.StringVar(&f.masterTLS.CA, "master-ca", "", "CA (PEM) blockmaster's certificate must verify against")
|
||||
fs.StringVar(&f.volumeID, "volume-id", "", "served volume (required)")
|
||||
fs.StringVar(&f.layoutID, "layout-id", "", "master-minted layout identity; when set, durable-root is the base for <volume>-<id8>")
|
||||
fs.StringVar(&f.replicaID, "replica-id", "", "served replica (required)")
|
||||
fs.StringVar(&f.dataAddr, "data-addr", "", "data-path address (required)")
|
||||
fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)")
|
||||
@@ -219,17 +223,14 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)")
|
||||
fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set")
|
||||
registerHostLimitFlags(fs, &f.chunk.hostLimit)
|
||||
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)")
|
||||
chunkstore.RegisterSWFSFlags(fs, &f.chunk.filer, &f.chunk.path, &f.chunk.collection, &f.chunk.replication)
|
||||
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
|
||||
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set")
|
||||
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+durable.MinCaptureInterval.String()+")")
|
||||
f.chunk.snapshotSchedule = defaultSnapshotSchedule
|
||||
fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off")
|
||||
fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables")
|
||||
fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification")
|
||||
fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: let the holder's maintenance pass remove chunks no root of the volume reaches (cleaning); off by default")
|
||||
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
|
||||
fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)")
|
||||
fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)")
|
||||
@@ -337,6 +338,19 @@ func parseFlags(args []string) (flags, error) {
|
||||
return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore")
|
||||
}
|
||||
}
|
||||
if f.layoutID != "" {
|
||||
id, err := layout.ParseVolumeID(f.layoutID)
|
||||
if err != nil {
|
||||
return flags{}, fmt.Errorf("--layout-id: %w", err)
|
||||
}
|
||||
if f.durableRoot == "" {
|
||||
return flags{}, fmt.Errorf("--layout-id requires --durable-root")
|
||||
}
|
||||
if err := (layout.Volume{ID: id, Name: f.volumeID, Format: layout.VolumeFormat}).CheckIdentity(); err != nil {
|
||||
return flags{}, err
|
||||
}
|
||||
f.durableRoot = filepath.Join(f.durableRoot, layout.VolumeDir(f.volumeID, id))
|
||||
}
|
||||
if f.durableRoot != "" {
|
||||
if _, _, err := durableCreateGeometry(f); err != nil {
|
||||
return flags{}, err
|
||||
@@ -684,14 +698,16 @@ func runVolume(f flags, exits *processExit) int {
|
||||
// accept connections.
|
||||
var provider frontend.Provider
|
||||
var durableProv *durable.DurableProvider
|
||||
var workspaceRemoteFor func(string) (storage.ChunkRemote, error)
|
||||
var workspaceLayoutHead layout.HeadStore
|
||||
if f.durableRoot != "" {
|
||||
blocks, blockSize, geometryErr := durableCreateGeometry(f)
|
||||
var dp *durable.DurableProvider
|
||||
cfg := durable.ProviderConfig{
|
||||
Impl: durable.ImplName(f.durableImpl),
|
||||
StorageRoot: f.durableRoot,
|
||||
BlockSize: blockSize,
|
||||
NumBlocks: blocks,
|
||||
ChunkBlocks: durable.DefaultChunkBlocks,
|
||||
WALRetentionLSNs: f.walRetentionLSNs,
|
||||
WALMultiBlockRecords: f.durableWALMultiBlockRecords,
|
||||
WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher,
|
||||
@@ -710,7 +726,6 @@ func runVolume(f flags, exits *processExit) int {
|
||||
cfg.ChunkCutTimeout = defaultChunkCutTimeout
|
||||
cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval
|
||||
cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout
|
||||
cfg.ChunkMaintenance = chunk.maintenance
|
||||
if f.workspaceLease {
|
||||
// The startup wait does not run out while the master gives no
|
||||
// reply; it ends 30 s after the first reply received after the
|
||||
@@ -721,9 +736,21 @@ func runVolume(f flags, exits *processExit) int {
|
||||
return deadline, final != ""
|
||||
}
|
||||
}
|
||||
if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 {
|
||||
if chunk.bCatalog != nil && f.chunk.snapshotSchedule.period > 0 {
|
||||
cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period
|
||||
cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep)
|
||||
cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(func(ctx context.Context, name, snapshot string, meta layout.SnapshotMeta) (chunkstore.SnapshotInfo, error) {
|
||||
p, ok := any(dp).(interface {
|
||||
SnapshotVolume(context.Context, string, string, layout.SnapshotMeta) (layout.Head, error)
|
||||
})
|
||||
if !ok {
|
||||
return chunkstore.SnapshotInfo{}, errors.New("chunk snapshot data path is not configured")
|
||||
}
|
||||
h, err := p.SnapshotVolume(ctx, name, snapshot, meta)
|
||||
if err != nil {
|
||||
return chunkstore.SnapshotInfo{}, err
|
||||
}
|
||||
return chunkstore.SnapshotInfoFromHead(name, snapshot, h), nil
|
||||
}, f.chunk.snapshotSchedule.keep)
|
||||
}
|
||||
cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy
|
||||
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
|
||||
@@ -752,18 +779,49 @@ func runVolume(f flags, exits *processExit) int {
|
||||
cfg.OnChunkDetach = h.WorkspaceStopPending
|
||||
cfg.OnChunkDetachResumed = h.WorkspaceStopResumed
|
||||
if chunkErr == nil {
|
||||
cfg.ChunkRemoteFor = chunk.remoteFor
|
||||
workspaceRemoteFor = chunk.remoteFor
|
||||
cfg.ChunkAttachCheck = chunkAttachCheck(chunk.catalog)
|
||||
|
||||
layoutID, _ := layout.ParseVolumeID(f.layoutID) // parseFlags validates a supplied id
|
||||
ref := chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID}
|
||||
cfg.ChunkAttachCheck = chunkAttachCheck(chunk.bCatalog, ref)
|
||||
cfg.ChunkLayoutHeadFor = func(name string) (layout.StartStore, error) {
|
||||
if name != ref.Name {
|
||||
return nil, layout.ErrIdentity
|
||||
}
|
||||
return chunk.bCatalog.Store(ref)
|
||||
}
|
||||
cfg.ChunkLayoutRemoteFor = func(name string, me layout.HolderID) (storage.ChunkRemote, error) {
|
||||
if name != ref.Name {
|
||||
return nil, layout.ErrIdentity
|
||||
}
|
||||
return chunkstore.NewLayoutRemote(chunk.bCatalog, ref, me)
|
||||
}
|
||||
workspaceLayoutHead, chunkErr = chunk.bCatalog.Store(ref)
|
||||
// The holder identity comes from Start (until it is wired, the
|
||||
// pass retains and does not clean).
|
||||
cfg.ChunkMaintenance = newChunkMaintenance(chunk.bCatalog, ref, func(ctx context.Context) (layoutCleaner, error) {
|
||||
if dp == nil {
|
||||
return nil, errNoLayoutHolder
|
||||
}
|
||||
r, err := dp.LayoutRemote(ctx, f.volumeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %w", errNoLayoutHolder, err)
|
||||
}
|
||||
c, ok := r.(layoutCleaner)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: the attachment's remote (%T) cannot clean", errNoLayoutHolder, r)
|
||||
}
|
||||
return c, nil
|
||||
}, f.chunk.automaticGC, time.Now)
|
||||
defer chunk.close()
|
||||
}
|
||||
}
|
||||
// Only a store about to be created takes its geometry from the flags;
|
||||
// an existing store opens with its own (blocks == 0), and a mismatch
|
||||
// between it and the record is the attach check's.
|
||||
if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.catalog != nil {
|
||||
if chunkErr == nil && geometryErr == nil && blocks != 0 && chunk.bCatalog != nil {
|
||||
readCtx, readCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
refusal, code := geometryFlagsRefusal(readCtx, chunk.catalog, f.volumeID, uint64(blocks), uint32(blockSize))
|
||||
layoutID, _ := layout.ParseVolumeID(f.layoutID)
|
||||
refusal, code := geometryFlagsRefusal(readCtx, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID}, uint64(blocks), uint32(blockSize), cfg.ChunkBlocks)
|
||||
readCancel()
|
||||
if refusal != "" {
|
||||
fmt.Fprintln(os.Stderr, refusal)
|
||||
@@ -776,7 +834,6 @@ func runVolume(f flags, exits *processExit) int {
|
||||
return code
|
||||
}
|
||||
}
|
||||
var dp *durable.DurableProvider
|
||||
err := geometryErr
|
||||
if err == nil {
|
||||
dp, err = durable.NewDurableProvider(cfg, h.ProjectionView())
|
||||
@@ -805,8 +862,9 @@ func runVolume(f flags, exits *processExit) int {
|
||||
provider = dp
|
||||
if status != nil {
|
||||
status.SetDurableStatusSource(dp)
|
||||
if f.chunk.controlEndpoint && chunk.catalog != nil {
|
||||
status.SetChunkControl(volume.NewChunkControl(dp, chunk.catalog))
|
||||
if f.chunk.controlEndpoint && chunk.bCatalog != nil {
|
||||
layoutID, _ := layout.ParseVolumeID(f.layoutID)
|
||||
status.SetChunkControl(volume.NewChunkControl(dp, chunk.bCatalog, chunkstore.VolumeRef{Name: f.volumeID, ID: layoutID}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1399,6 +1457,16 @@ func runVolume(f flags, exits *processExit) int {
|
||||
if replVolume != nil {
|
||||
drainErr = errors.Join(drainErr, replVolume.Close())
|
||||
}
|
||||
// A detached HEAD is stable until a higher grant. Read it while the
|
||||
// attachment identity is still available, then ACK only after Close succeeds.
|
||||
var detachedGen uint64
|
||||
if leaseStop != nil && drainErr == nil && workspaceLayoutHead != nil {
|
||||
var me layout.HolderID
|
||||
me, drainErr = durableProv.LayoutHolder(leaseStop.ctx, leaseStop.id.VolumeId)
|
||||
if drainErr == nil {
|
||||
detachedGen, drainErr = workspaceLayoutDetachedGeneration(leaseStop.ctx, workspaceLayoutHead, leaseStop.id, me)
|
||||
}
|
||||
}
|
||||
// T3b: close DurableProvider in correct order — Provider.Close
|
||||
// closes backends first (flags them closed) then storage files
|
||||
// (releases fd + final fsync).
|
||||
@@ -1411,9 +1479,9 @@ func runVolume(f flags, exits *processExit) int {
|
||||
shutCancel()
|
||||
}
|
||||
if leaseStop != nil {
|
||||
gen := uint64(0)
|
||||
if drainErr == nil {
|
||||
gen, drainErr = workspaceDetachedGeneration(leaseStop.ctx, workspaceRemoteFor, leaseStop.id, chunkHolder(f))
|
||||
gen := detachedGen
|
||||
if drainErr == nil && workspaceLayoutHead == nil {
|
||||
drainErr = errors.New("workspace layout HEAD unavailable for detached proof")
|
||||
}
|
||||
leaseStop.reply <- workspaceStopResult{gen: gen, err: drainErr}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
// The NVMe/TCP witness client of the real-binary tests: connect, write with
|
||||
// a flush, read back exactly.
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
)
|
||||
|
||||
// This small initiator uses the same exported wire types and admin/IO queue
|
||||
// handshake as core/frontend/nvme/client_support_test.go. It talks only to the
|
||||
// real blockvolume in this harness; no kernel device or unrelated NQN is used.
|
||||
type gap1NVMe struct {
|
||||
admin, io net.Conn
|
||||
r *nvme.Reader
|
||||
w *nvme.Writer
|
||||
cid uint16
|
||||
}
|
||||
|
||||
func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe {
|
||||
t.Helper()
|
||||
c := &gap1NVMe{}
|
||||
t.Cleanup(c.close)
|
||||
var controller uint16 = 0xffff
|
||||
for q := uint16(0); q < 2; q++ {
|
||||
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if q == 0 {
|
||||
c.admin = conn
|
||||
} else {
|
||||
c.io = conn
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
r, w := nvme.NewReader(conn), nvme.NewWriter(conn)
|
||||
if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := r.Dequeue()
|
||||
if err != nil || h.Type != 1 {
|
||||
t.Fatalf("NVMe IC response: %+v %v", h, err)
|
||||
}
|
||||
var ic nvme.ICResponse
|
||||
if err := r.Receive(&ic); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16}
|
||||
data := make([]byte, 1024)
|
||||
(&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data)
|
||||
if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := gap1NVMeReply(t, r, c.cid)
|
||||
if q == 0 {
|
||||
controller = uint16(reply.DW0)
|
||||
if controller == 0 {
|
||||
t.Fatal("no controller assigned")
|
||||
}
|
||||
}
|
||||
if q == 1 {
|
||||
c.r, c.w = r, w
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) close() {
|
||||
if c.io != nil {
|
||||
_ = c.io.Close()
|
||||
}
|
||||
if c.admin != nil {
|
||||
_ = c.admin.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse {
|
||||
t.Helper()
|
||||
h, err := r.Dequeue()
|
||||
if err != nil || h.Type != 5 {
|
||||
t.Fatalf("NVMe capsule header: %+v %v", h, err)
|
||||
}
|
||||
var reply nvme.CapsuleResponse
|
||||
if err := r.Receive(&reply); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reply.CID != cid || reply.Status != 0 {
|
||||
t.Fatalf("NVMe CID %d: %+v", cid, reply)
|
||||
}
|
||||
return reply
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) {
|
||||
t.Helper()
|
||||
if len(payload) != 4096 {
|
||||
t.Fatal("harness writes exactly one block")
|
||||
}
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
|
||||
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := c.r.Dequeue()
|
||||
if err != nil || h.Type != 9 {
|
||||
t.Fatalf("NVMe R2T: %+v %v", h, err)
|
||||
}
|
||||
var r2t nvme.R2THeader
|
||||
if err := c.r.Receive(&r2t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) {
|
||||
t.Fatalf("wrong R2T %+v", r2t)
|
||||
}
|
||||
data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))}
|
||||
if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid)
|
||||
c.cid++
|
||||
flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1}
|
||||
if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) {
|
||||
t.Helper()
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
|
||||
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := c.r.Dequeue()
|
||||
if err != nil || h.Type != 7 {
|
||||
t.Fatalf("NVMe read data: %+v %v", h, err)
|
||||
}
|
||||
var header nvme.C2HDataHeader
|
||||
if err := c.r.Receive(&header); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) {
|
||||
t.Fatalf("wrong read frame %+v length%d", header, c.r.Length())
|
||||
}
|
||||
got := make([]byte, c.r.Length())
|
||||
if err := c.r.ReceiveData(got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid)
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("fsync-acknowledged NVMe record changed after supervised restart")
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,51 @@ func sealedHeadLSN(out string, e, g uint64) (uint64, error) {
|
||||
return h.RemoteLSN, nil
|
||||
}
|
||||
|
||||
// The layout HEAD exposes the committed position and the master-minted
|
||||
// holder identity. The old storage HEAD's DetachedBy proof is not a field of
|
||||
// this format; a detached layout HEAD itself is the committed stop image.
|
||||
type layoutHeadRecord struct {
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
ClaimID string `json:"claimID"`
|
||||
Position uint64 `json:"position"`
|
||||
State string `json:"state"`
|
||||
Current json.RawMessage `json:"current"`
|
||||
}
|
||||
|
||||
func parseLayoutHead(out string) (layoutHeadRecord, error) {
|
||||
var shown struct {
|
||||
Head *layoutHeadRecord `json:"head"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &shown); err != nil || shown.Head == nil {
|
||||
return layoutHeadRecord{}, fmt.Errorf("layout show stdout has no head: %v: %q", err, out)
|
||||
}
|
||||
return *shown.Head, nil
|
||||
}
|
||||
|
||||
func sealedLayoutHeadPosition(out string, epoch, gen uint64) (uint64, error) {
|
||||
h, err := parseLayoutHead(out)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if h.Gen != gen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "detached" || len(h.Current) == 0 || string(h.Current) == "null" {
|
||||
return 0, fmt.Errorf("layout HEAD after seal %+v; want committed detached image at gen %d epoch %d holder s1/r1", h, gen, epoch)
|
||||
}
|
||||
return h.Position, nil
|
||||
}
|
||||
|
||||
func checkLayoutHeadReopened(out string, epoch, sealedGen, position uint64) error {
|
||||
h, err := parseLayoutHead(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Gen <= sealedGen || h.Epoch != epoch || h.Holder != "s1/r1" || h.ClaimID == "" || h.State != "" || h.Position != position || len(h.Current) == 0 || string(h.Current) == "null" {
|
||||
return fmt.Errorf("layout HEAD after claim %+v; want live image above gen %d at epoch %d position %d holder s1/r1", h, sealedGen, epoch, position)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkRevoke(out string, e, g uint64) error {
|
||||
if !strings.HasPrefix(out, fmt.Sprintf("revocation requested: volume v1 holder r1@%d expiry_ns ", e)) {
|
||||
return fmt.Errorf("revoke stdout %q", out)
|
||||
|
||||
@@ -22,6 +22,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// TestStandalonePlannedHandoffToTheSameHost runs the planned hand-over back
|
||||
@@ -39,7 +42,6 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) {
|
||||
// 4. blockvolume adopts the volume.
|
||||
vol1 := h.start(t, "blockvolume-1", h.volume, volArgs...)
|
||||
e := mustU(adoptedEpoch(vol1.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@")))
|
||||
vol1.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in")
|
||||
h.waitPrimary(t, e)
|
||||
|
||||
// 5. The lease.
|
||||
@@ -59,9 +61,9 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) {
|
||||
g := mustU(sealedGen(out, errOut, e))
|
||||
|
||||
// 9. The seal is in the object store.
|
||||
chunkShow := []string{"ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath}
|
||||
chunkShow := []string{"ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath}
|
||||
out, _ = h.command(t, chunkShow...)
|
||||
l := mustU(sealedHeadLSN(out, e, g))
|
||||
l := mustU(sealedLayoutHeadPosition(out, e, g))
|
||||
|
||||
// 10. Revoke with the sealed generation.
|
||||
out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1",
|
||||
@@ -99,8 +101,6 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) {
|
||||
|
||||
// 14. Start again with the same root, within the new lease (30 s).
|
||||
vol2 := h.start(t, "blockvolume-2", h.volume, volArgs...)
|
||||
vol2.waitLog(t, 60*time.Second, fmt.Sprintf(`durable: HEAD claim for volume=v1 starting: target epoch=%d holder="s1/r1"`, e2))
|
||||
must(checkClaimDone(vol2.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2))
|
||||
vol2.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume v1 adopted as PRIMARY at r1@%d", e2))
|
||||
for _, bad := range []string{"refusing to attach volume=v1", "assignment unavailable, not serving"} {
|
||||
if vol2.has(bad) {
|
||||
@@ -115,7 +115,7 @@ func TestStandalonePlannedHandoffToTheSameHost(t *testing.T) {
|
||||
|
||||
// 16. The new epoch claimed HEAD.
|
||||
out, _ = h.command(t, chunkShow...)
|
||||
must(checkHeadReopened(out, e2, g, l))
|
||||
must(checkLayoutHeadReopened(out, e2, g, l))
|
||||
|
||||
// 17. The block written before the hand-over reads back unchanged.
|
||||
c = dialNVMe(t, h.nvmeAddr, nqn)
|
||||
@@ -143,8 +143,8 @@ func TestStandaloneCleanMoveWithoutTheACKIsRefused(t *testing.T) {
|
||||
c.close()
|
||||
out, errOut := h.command(t, "ops", "chunk", "detach", "--plain", "--volume", "v1", "--status-addr", h.statusAddr, "--timeout", "120s")
|
||||
g := mustU(sealedGen(out, errOut, e))
|
||||
out, _ = h.command(t, "ops", "chunk", "show", "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath)
|
||||
mustU(sealedHeadLSN(out, e, g)) // HEAD is sealed: only the ACK is missing
|
||||
out, _ = h.command(t, "ops", "chunk", "show", "--master", h.masterAddr, "--volume", "v1", "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath)
|
||||
mustU(sealedLayoutHeadPosition(out, e, g)) // HEAD is sealed: only the ACK is missing
|
||||
vol.kill(t)
|
||||
|
||||
out, _ = h.command(t, "ops", "workspace", "revoke", "--master", h.masterAddr, "--volume", "v1", "--replica", "r1",
|
||||
@@ -185,6 +185,8 @@ type handoffEnv struct {
|
||||
// A crash test restarts exactly this owned master with the same stores.
|
||||
masterProcess *daemon
|
||||
masterArgs []string
|
||||
layoutMu sync.Mutex
|
||||
layoutIDs map[string]string
|
||||
// tls, when set, runs every process with mutual TLS (procedure_tls_harness_test.go).
|
||||
tls *procedureTLS
|
||||
}
|
||||
@@ -223,6 +225,13 @@ func startHandoffEnvWith(t *testing.T, n int, targets []string, masterArgs ...st
|
||||
// startHandoffEnvTLS is startHandoffEnvWith with mutual TLS when tlsNotAfter
|
||||
// is non-nil (it overrides chosen node certificates' expiry).
|
||||
func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, masterArgs ...string) *handoffEnv {
|
||||
return startHandoffEnvConfigured(t, n, targets, tlsNotAfter, true, masterArgs...)
|
||||
}
|
||||
|
||||
// startHandoffEnvConfigured can reserve target placement without importing a
|
||||
// VolumeRecord. The restore-create test uses that form so the master creates
|
||||
// the target's identity and restored image in one request.
|
||||
func startHandoffEnvConfigured(t *testing.T, n int, targets []string, tlsNotAfter map[string]time.Time, precreateTargets bool, masterArgs ...string) *handoffEnv {
|
||||
t.Helper()
|
||||
h := newPlannedHandoffHarness(t)
|
||||
env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/handoff-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
|
||||
@@ -252,16 +261,20 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s
|
||||
node := func(b bvHost) {
|
||||
fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", b.id, b.data, b.ctrl)
|
||||
}
|
||||
volume := func(v, server string) {
|
||||
fmt.Fprintf(&volumes, " - id: %s\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: %s\n replica_id: r1\n", v, server)
|
||||
volume := func(v, server string, create bool) {
|
||||
size := ""
|
||||
if create {
|
||||
size = " size_bytes: 268435456\n"
|
||||
}
|
||||
fmt.Fprintf(&volumes, " - id: %s\n%s replication_factor: 1\n placements:\n - server_id: %s\n replica_id: r1\n", v, size, server)
|
||||
}
|
||||
for i := 1; i <= n; i++ {
|
||||
node(env.hosts[fmt.Sprintf("s%d", i)])
|
||||
}
|
||||
volume("v1", "s1")
|
||||
volume("v1", "s1", true)
|
||||
for _, v := range targets {
|
||||
node(env.hosts["n-"+v])
|
||||
volume(v, "n-"+v)
|
||||
volume(v, "n-"+v, precreateTargets)
|
||||
}
|
||||
spec := filepath.Join(h.dir, "cluster-spec.yaml")
|
||||
must(os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n"+volumes.String()), 0o644))
|
||||
@@ -272,6 +285,7 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s
|
||||
"--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
|
||||
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://" + cluster.filerHTTP + chunkPath}, masterArgs...)
|
||||
env.masterArgs = append(env.masterArgs, "--chunk-filer", cluster.filerGRPC, "--chunk-path", chunkPath)
|
||||
master := h.start(t, "blockmaster", h.master, env.masterArgs...)
|
||||
env.masterProcess = master
|
||||
if l := master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded="); !strings.Contains(l, "listen="+h.masterAddr) {
|
||||
@@ -285,12 +299,44 @@ func startHandoffEnvTLS(t *testing.T, n int, targets []string, tlsNotAfter map[s
|
||||
env.show = []string{"ops", "workspace", "show", "--master", h.masterAddr, "--volume", "v1"}
|
||||
out, _ := h.command(t, env.show...)
|
||||
must(checkShowBeforeStart(out))
|
||||
// Cache the identities imported by the master while it is available. Some
|
||||
// tests assemble restart arguments after deliberately stopping the master.
|
||||
env.layoutIDs = make(map[string]string)
|
||||
env.layoutID("v1")
|
||||
if precreateTargets {
|
||||
for _, v := range targets {
|
||||
env.layoutID(v)
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// volArgs is the chapter's blockvolume command for one host.
|
||||
func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.hosts[id]) }
|
||||
|
||||
func (env *handoffEnv) layoutID(volume string) string {
|
||||
t := env.h.t
|
||||
t.Helper()
|
||||
env.layoutMu.Lock()
|
||||
defer env.layoutMu.Unlock()
|
||||
if id := env.layoutIDs[volume]; id != "" {
|
||||
return id
|
||||
}
|
||||
conn, err := grpc.NewClient(env.h.masterAddr, env.masterDialOption(t, "admin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
id, err := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume)
|
||||
if err != nil {
|
||||
t.Fatalf("resolve layout identity for %s: %v", volume, err)
|
||||
}
|
||||
env.layoutIDs[volume] = id.String()
|
||||
return id.String()
|
||||
}
|
||||
|
||||
// volArgsFor is the chapter's blockvolume command for b. The default
|
||||
// scheduled snapshot (daily:7, at a per-volume offset) stays on, as the page
|
||||
// says; a snapshot inside a test could only make a test fail, never pass.
|
||||
@@ -308,6 +354,7 @@ func (env *handoffEnv) volArgsFor(b bvHost) []string {
|
||||
replica = "r1"
|
||||
}
|
||||
return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", server, "--volume-id", vol, "--replica-id", replica,
|
||||
"--layout-id", env.layoutID(vol),
|
||||
"--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status,
|
||||
"--durable-root", b.root, "--durable-impl", "walstore-chunk",
|
||||
"--durable-blocks", "65536", "--durable-blocksize", "4096",
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// P12.6 / INV-WS-SEAL-REPLAY-001: a SIGKILL during plain-seal upload
|
||||
@@ -114,10 +114,9 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) {
|
||||
verified, _ := env.h.command(t, "ops", "chunk", "verify", "--volume", "v1",
|
||||
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
|
||||
"--depth", "data", "--timeout", "60s", "--bytes-per-sec", "0")
|
||||
var result chunkstore.VerifyResult
|
||||
var result layout.VerifyResult
|
||||
if err := json.Unmarshal([]byte(verified), &result); err != nil || !result.Complete ||
|
||||
result.Depth != chunkstore.VerifyData || len(result.Findings) != 0 || result.ChunksNotRead != 0 ||
|
||||
result.DistinctChunksRead == 0 {
|
||||
len(result.Findings) != 0 || result.Chunks == 0 {
|
||||
t.Fatalf("post-move data verify incomplete or corrupt: %s: %v", verified, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
@@ -267,14 +269,13 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) {
|
||||
t.Fatalf("startup overrode the pending real drain: %+v", out)
|
||||
default:
|
||||
}
|
||||
remote := storage.NewMemChunkRemote()
|
||||
_, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Epoch: 1, Holder: "s/r", Gen: 1}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := workspaceDetachedGeneration(ctx, func(string) (storage.ChunkRemote, error) { return remote, nil }, request.id, "s/r")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// The real proof reader supplies the generation to the real lease
|
||||
// worker; a constant here would not join the two safety checks.
|
||||
me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
st := layoutProofStore{h: layout.Head{Gen: 1, Epoch: 1, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true}
|
||||
gen, proofErr := workspaceLayoutDetachedGeneration(request.ctx, st, request.id, me)
|
||||
if proofErr != nil {
|
||||
t.Fatal(proofErr)
|
||||
}
|
||||
request.reply <- workspaceStopResult{gen: gen}
|
||||
finishWorkspaceLease(e, f, h, leaseDone)
|
||||
@@ -295,84 +296,132 @@ func TestWorkspacePlannedDrainOwnsStartupExpiryUntilAck(t *testing.T) {
|
||||
|
||||
// The real provider must carry the claim's filer proof to the process owner,
|
||||
// even when the master stream has never reported another replica.
|
||||
type claimExitView struct{ assigned atomic.Bool }
|
||||
type claimExitView struct {
|
||||
assigned atomic.Bool
|
||||
epoch uint64
|
||||
}
|
||||
|
||||
func (v *claimExitView) Projection() frontend.Projection {
|
||||
if !v.assigned.Load() {
|
||||
return frontend.Projection{VolumeID: "v"}
|
||||
}
|
||||
return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}
|
||||
epoch := v.epoch
|
||||
if epoch == 0 {
|
||||
epoch = 1
|
||||
}
|
||||
return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, Healthy: true}
|
||||
}
|
||||
|
||||
// A layout HEAD held by another server at the granted epoch is a final
|
||||
// refusal. The master has not delivered a newer foreign assignment, so the
|
||||
// process must derive its exit from the provider's observed HEAD.
|
||||
func TestWorkspaceForeignHeadClaimChoosesNoRetry(t *testing.T) {
|
||||
for _, deferred := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name, holder string
|
||||
want int
|
||||
}{
|
||||
{"foreign holder", "other", 78}, {"same holder higher epoch", "r", 75},
|
||||
} {
|
||||
t.Run(tc.name+map[bool]string{false: "/immediate", true: "/waiting"}[deferred], func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
h, _ := exitAuthorityHost(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 2, Holder: tc.holder, State: storage.ChunkHeadActive}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := &claimExitView{}
|
||||
view.assigned.Store(!deferred)
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := p.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if _, err = p.EnsureStorage("v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = p.RecoverVolume(ctx, "v")
|
||||
if deferred {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view.assigned.Store(true)
|
||||
} else if !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("claim refusal=%v", err)
|
||||
}
|
||||
select {
|
||||
case <-p.ChunkStartupUpdates():
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
if h.LastOtherLine() != nil {
|
||||
t.Fatal("fixture unexpectedly supplied master supersede evidence")
|
||||
}
|
||||
e := newProcessExit(ctx)
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
|
||||
t.Fatal("claim refusal did not select an exit")
|
||||
}
|
||||
select {
|
||||
case out := <-e.decision:
|
||||
if out.code != tc.want {
|
||||
t.Fatalf("claim exit=%+v want %d", out, tc.want)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil || head.Gen != 1 || head.Holder != tc.holder || remote.Puts() != 0 {
|
||||
t.Fatalf("refused claim mutated remote: %+v puts=%d err=%v", head, remote.Puts(), err)
|
||||
}
|
||||
for _, status := range p.DurableStatuses() {
|
||||
if status.Operational {
|
||||
t.Fatal("refused claim became operational")
|
||||
}
|
||||
}
|
||||
})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
headEpoch uint64
|
||||
grantEpoch uint64
|
||||
deferred bool
|
||||
wantExit bool
|
||||
}{
|
||||
{"foreign holder at granted epoch", 1, 1, false, true},
|
||||
{"foreign holder above granted epoch", 2, 1, false, true},
|
||||
{"foreign holder after assignment", 1, 1, true, true},
|
||||
{"foreign holder below granted epoch", 1, 2, false, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
testWorkspaceLayoutForeignClaimExit(t, tc.headEpoch, tc.grantEpoch, tc.deferred, tc.wantExit)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testWorkspaceLayoutForeignClaimExit(t *testing.T, headEpoch, grantEpoch uint64, deferred, wantExit bool) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreign, found, err := st.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("initial HEAD: found=%v err=%v", found, err)
|
||||
}
|
||||
foreign.Epoch, foreign.Holder, foreign.ClaimID = headEpoch, "other/r", "other-claim"
|
||||
if err := st.UpdateHead(ctx, foreign.Gen, foreign); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreign, _, err = st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := &claimExitView{epoch: grantEpoch}
|
||||
view.assigned.Store(!deferred)
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r",
|
||||
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil },
|
||||
ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) {
|
||||
return chunkstore.NewLayoutRemote(cat, ref, me)
|
||||
},
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
if _, err := p.EnsureStorage("v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = p.RecoverVolume(ctx, "v")
|
||||
if deferred {
|
||||
if err != nil {
|
||||
t.Fatalf("recovery before assignment: %v", err)
|
||||
}
|
||||
view.assigned.Store(true)
|
||||
select {
|
||||
case <-p.ChunkStartupUpdates():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("foreign layout HEAD did not end deferred startup")
|
||||
}
|
||||
} else if wantExit && !errors.Is(err, layout.ErrNotHolder) && !errors.Is(err, layout.ErrStaleEpoch) {
|
||||
t.Fatalf("layout Start refusal: %v; want not-holder or stale-epoch", err)
|
||||
}
|
||||
if !wantExit {
|
||||
if err != nil {
|
||||
t.Fatalf("newer grant did not claim: %v", err)
|
||||
}
|
||||
if _, ended := p.ChunkStartupOutcome("v"); ended {
|
||||
t.Fatal("newer grant ended startup")
|
||||
}
|
||||
claimed, _, err := st.ReadHead(ctx)
|
||||
if err != nil || claimed.Epoch != grantEpoch || claimed.Holder != "s/r" || claimed.Gen <= foreign.Gen {
|
||||
t.Fatalf("newer grant did not claim HEAD: %+v err=%v", claimed, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if _, ended := p.ChunkStartupOutcome("v"); !ended {
|
||||
t.Fatal("foreign layout HEAD did not end startup")
|
||||
}
|
||||
h, _ := exitAuthorityHost(t)
|
||||
e := newProcessExit(ctx)
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
|
||||
t.Fatal("foreign layout HEAD did not select an exit")
|
||||
}
|
||||
if out := <-e.decision; out.code != 78 {
|
||||
t.Fatalf("foreign layout HEAD chose %+v; want 78", out)
|
||||
}
|
||||
after, _, err := st.ReadHead(ctx)
|
||||
if err != nil || after.Gen != foreign.Gen || after.Holder != foreign.Holder || after.ClaimID != foreign.ClaimID {
|
||||
t.Fatalf("refused Start changed HEAD: before=%+v after=%+v err=%v", foreign, after, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,12 +434,34 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) {
|
||||
defer cancel()
|
||||
h, _ := exitAuthorityHost(t)
|
||||
root := t.TempDir()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
blobs := &maintenanceBlobs{d: map[string][]byte{}}
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), blobs, "/exit-layout")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := &claimExitView{}
|
||||
view.assigned.Store(true)
|
||||
open := func() *durable.DurableProvider {
|
||||
t.Helper()
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view)
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r",
|
||||
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return st, nil },
|
||||
ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) {
|
||||
return chunkstore.NewLayoutRemote(cat, ref, me)
|
||||
},
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -414,11 +485,13 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) {
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
before, found, err := st.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("claimed layout HEAD: found=%v err=%v", found, err)
|
||||
}
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: before.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "other", State: storage.ChunkHeadActive}); err != nil {
|
||||
foreign := before
|
||||
foreign.Epoch, foreign.Holder, foreign.ClaimID = 2, "other/r", "other-claim"
|
||||
if err := st.UpdateHead(ctx, before.Gen, foreign); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view.assigned.Store(!deferred)
|
||||
@@ -434,7 +507,7 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
} else if !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
} else if !errors.Is(err, layout.ErrStaleEpoch) {
|
||||
t.Fatalf("old root refusal=%v", err)
|
||||
}
|
||||
e := newProcessExit(ctx)
|
||||
@@ -447,94 +520,118 @@ func TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry(t *testing.T) {
|
||||
if got, err := second.LogicalStorage("v").Read(0); err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("refusal lost local acknowledged bytes: %v", err)
|
||||
}
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil || after.Gen != before.Gen+1 || after.Holder != "other" || remote.Puts() != 0 {
|
||||
t.Fatalf("refusal mutated HEAD/payload: %+v puts=%d err=%v", after, remote.Puts(), err)
|
||||
after, found, err := st.ReadHead(ctx)
|
||||
if err != nil || !found || after.Gen != before.Gen+1 || after.Holder != "other/r" || after.ClaimID != "other-claim" || blobs.n != 0 {
|
||||
t.Fatalf("refusal mutated HEAD/payload: %+v found=%v puts=%d err=%v", after, found, blobs.n, err)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The real claim reads E1/A; a late E2/C wins before E3/B's CAS.
|
||||
// The displaced HEAD is a fence for this attempt, not proof E3 was superseded.
|
||||
type displacedClaimExitRemote struct {
|
||||
storage.ChunkRemote
|
||||
epoch uint64
|
||||
raced bool
|
||||
}
|
||||
|
||||
func (r *displacedClaimExitRemote) CASHead(ctx context.Context, prev storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
if !r.raced {
|
||||
r.raced = true
|
||||
late := storage.ChunkHead{Epoch: r.epoch, Holder: "C", State: storage.ChunkHeadActive}
|
||||
if _, err := r.ChunkRemote.CASHead(ctx, prev, late); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return r.ChunkRemote.CASHead(ctx, prev, next)
|
||||
}
|
||||
|
||||
type displacedClaimExitView struct{}
|
||||
|
||||
func (displacedClaimExitView) Projection() frontend.Projection {
|
||||
return frontend.Projection{VolumeID: "v", ReplicaID: "B", Epoch: 3, Healthy: true}
|
||||
}
|
||||
|
||||
type displacedLayoutClaimStore struct {
|
||||
layout.StartStore
|
||||
epoch uint64
|
||||
raced bool
|
||||
}
|
||||
|
||||
func (s *displacedLayoutClaimStore) UpdateHead(ctx context.Context, expected uint64, next layout.Head) error {
|
||||
if !s.raced {
|
||||
s.raced = true
|
||||
current, found, err := s.StartStore.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
return errors.New("racing layout HEAD unavailable")
|
||||
}
|
||||
late := current
|
||||
late.Epoch, late.Holder, late.ClaimID = s.epoch, "C", "late-claim"
|
||||
if err := s.StartStore.UpdateHead(ctx, current.Gen, late); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.StartStore.UpdateHead(ctx, expected, next)
|
||||
}
|
||||
|
||||
// The claim's conditional update loses to another holder. A re-read at or
|
||||
// above the grant proves a final exit; below it, a new Start can claim.
|
||||
func TestWorkspaceDisplacedClaimUsesAssignedEpoch(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
epoch uint64
|
||||
want int
|
||||
final bool
|
||||
}{
|
||||
{"late lower epoch", 2, 75}, {"equal epoch foreign holder", 3, 78}, {"higher epoch foreign holder", 4, 78},
|
||||
{"late lower epoch", 2, false},
|
||||
{"equal epoch foreign holder", 3, true},
|
||||
{"higher epoch foreign holder", 4, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
h, _ := exitAuthorityHost(t)
|
||||
base := storage.NewMemChunkRemote()
|
||||
if _, err := base.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "A", State: storage.ChunkHeadActive}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := &displacedClaimExitRemote{ChunkRemote: base, epoch: tc.epoch}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, displacedClaimExitView{})
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := p.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if _, err = p.EnsureStorage("v"); err != nil {
|
||||
ref := chunkstore.VolumeRef{Name: "v", ID: id}
|
||||
cat, err := chunkstore.NewBCatalog(chunkstore.NewMemFiler(), &maintenanceBlobs{d: map[string][]byte{}}, "/exit-layout")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v"); !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("claim error=%v", err)
|
||||
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !remote.raced {
|
||||
t.Fatal("controlled CAS did not run")
|
||||
base, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := newProcessExit(ctx)
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
|
||||
t.Fatal("fenced claim did not choose an exit")
|
||||
initial, found, err := base.ReadHead(ctx)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("initial HEAD: found=%v err=%v", found, err)
|
||||
}
|
||||
select {
|
||||
case out := <-e.decision:
|
||||
if out.code != tc.want {
|
||||
t.Fatalf("displaced E%d/C at assigned E3/B chose %+v, want %d", tc.epoch, out, tc.want)
|
||||
initial.Epoch, initial.Holder, initial.ClaimID = 1, "A", "first-claim"
|
||||
if err := base.UpdateHead(ctx, initial.Gen, initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &displacedLayoutClaimStore{StartStore: base, epoch: tc.epoch}
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "B",
|
||||
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return store, nil },
|
||||
ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) {
|
||||
return chunkstore.NewLayoutRemote(cat, ref, me)
|
||||
},
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, displacedClaimExitView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
if _, err := p.EnsureStorage("v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v"); !errors.Is(err, layout.ErrPrecondition) {
|
||||
t.Fatalf("claim race: %v; want HEAD precondition", err)
|
||||
}
|
||||
if !store.raced {
|
||||
t.Fatal("controlled HEAD race did not run")
|
||||
}
|
||||
if tc.final {
|
||||
h, _ := exitAuthorityHost(t)
|
||||
e := newProcessExit(ctx)
|
||||
if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, p) {
|
||||
t.Fatal("displaced layout claim did not choose an exit")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
head, err := base.GetHead(ctx)
|
||||
if err != nil || head.Gen != 2 || head.Epoch != tc.epoch || head.Holder != "C" || base.Puts() != 0 {
|
||||
t.Fatalf("refused claim mutated HEAD/payload: %+v puts=%d err=%v", head, base.Puts(), err)
|
||||
}
|
||||
for _, status := range p.DurableStatuses() {
|
||||
if status.Operational {
|
||||
t.Fatal("displaced claim served I/O")
|
||||
if out := <-e.decision; out.code != 78 {
|
||||
t.Fatalf("displaced claim chose %+v; want 78", out)
|
||||
}
|
||||
} else if _, ended := p.ChunkStartupOutcome("v"); ended {
|
||||
t.Fatal("a lower racing epoch ended startup")
|
||||
}
|
||||
after, found, err := base.ReadHead(ctx)
|
||||
if err != nil || !found || after.Gen != initial.Gen+2 || after.Epoch != tc.epoch || after.Holder != "C" {
|
||||
t.Fatalf("refused claim changed racing HEAD: %+v found=%v err=%v", after, found, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package main
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
|
||||
// anyStart is a local root that can start from any HEAD: these tests do
|
||||
// not model the local store.
|
||||
func anyStart(layout.Head) error { return nil }
|
||||
@@ -4,9 +4,7 @@ package main_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
|
||||
@@ -16,149 +14,6 @@ import (
|
||||
// This small initiator uses the same exported wire types and admin/IO queue
|
||||
// handshake as core/frontend/nvme/client_support_test.go. It talks only to the
|
||||
// real blockvolume in this harness; no kernel device or unrelated NQN is used.
|
||||
type gap1NVMe struct {
|
||||
admin, io net.Conn
|
||||
r *nvme.Reader
|
||||
w *nvme.Writer
|
||||
cid uint16
|
||||
}
|
||||
|
||||
func gap1ConnectNVMe(t *testing.T, addr, nqn string) *gap1NVMe {
|
||||
t.Helper()
|
||||
c := &gap1NVMe{}
|
||||
t.Cleanup(c.close)
|
||||
var controller uint16 = 0xffff
|
||||
for q := uint16(0); q < 2; q++ {
|
||||
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if q == 0 {
|
||||
c.admin = conn
|
||||
} else {
|
||||
c.io = conn
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
r, w := nvme.NewReader(conn), nvme.NewWriter(conn)
|
||||
if err := w.SendHeaderOnly(0, &nvme.ICRequest{PDUFormatVersion: 0, PDUMaxR2T: 1}, 120); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := r.Dequeue()
|
||||
if err != nil || h.Type != 1 {
|
||||
t.Fatalf("NVMe IC response: %+v %v", h, err)
|
||||
}
|
||||
var ic nvme.ICResponse
|
||||
if err := r.Receive(&ic); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 0x7f, FCType: 1, CID: c.cid, D10: uint32(q) << 16}
|
||||
data := make([]byte, 1024)
|
||||
(&nvme.ConnectData{HostID: [16]byte{1, 2, 3, 4}, CNTLID: controller, SubNQN: nqn, HostNQN: "nqn.2026-11.test:gap1-host"}).Marshal(data)
|
||||
if err := w.SendWithData(4, 0, &cmd, 64, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := gap1NVMeReply(t, r, c.cid)
|
||||
if q == 0 {
|
||||
controller = uint16(reply.DW0)
|
||||
if controller == 0 {
|
||||
t.Fatal("no controller assigned")
|
||||
}
|
||||
}
|
||||
if q == 1 {
|
||||
c.r, c.w = r, w
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) close() {
|
||||
if c.io != nil {
|
||||
_ = c.io.Close()
|
||||
}
|
||||
if c.admin != nil {
|
||||
_ = c.admin.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func gap1NVMeReply(t *testing.T, r *nvme.Reader, cid uint16) nvme.CapsuleResponse {
|
||||
t.Helper()
|
||||
h, err := r.Dequeue()
|
||||
if err != nil || h.Type != 5 {
|
||||
t.Fatalf("NVMe capsule header: %+v %v", h, err)
|
||||
}
|
||||
var reply nvme.CapsuleResponse
|
||||
if err := r.Receive(&reply); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reply.CID != cid || reply.Status != 0 {
|
||||
t.Fatalf("NVMe CID %d: %+v", cid, reply)
|
||||
}
|
||||
return reply
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) writeFlush(t *testing.T, lba uint64, payload []byte) {
|
||||
t.Helper()
|
||||
if len(payload) != 4096 {
|
||||
t.Fatal("harness writes exactly one block")
|
||||
}
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 1, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
|
||||
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := c.r.Dequeue()
|
||||
if err != nil || h.Type != 9 {
|
||||
t.Fatalf("NVMe R2T: %+v %v", h, err)
|
||||
}
|
||||
var r2t nvme.R2THeader
|
||||
if err := c.r.Receive(&r2t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r2t.CCCID != c.cid || r2t.DATAO != 0 || r2t.DATAL != uint32(len(payload)) {
|
||||
t.Fatalf("wrong R2T %+v", r2t)
|
||||
}
|
||||
data := nvme.H2CDataHeader{CCCID: c.cid, TAG: r2t.TAG, DATAO: 0, DATAL: uint32(len(payload))}
|
||||
if err := c.w.SendWithData(6, 0, &data, 16, payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid)
|
||||
c.cid++
|
||||
flush := nvme.CapsuleCommand{OpCode: 0, CID: c.cid, NSID: 1}
|
||||
if err := c.w.SendHeaderOnly(4, &flush, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid) // only this completed Flush makes the record durable
|
||||
}
|
||||
|
||||
func (c *gap1NVMe) readExact(t *testing.T, lba uint64, want []byte) {
|
||||
t.Helper()
|
||||
c.cid++
|
||||
cmd := nvme.CapsuleCommand{OpCode: 2, CID: c.cid, NSID: 1, D10: uint32(lba), D11: uint32(lba >> 32)}
|
||||
if err := c.w.SendHeaderOnly(4, &cmd, 64); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := c.r.Dequeue()
|
||||
if err != nil || h.Type != 7 {
|
||||
t.Fatalf("NVMe read data: %+v %v", h, err)
|
||||
}
|
||||
var header nvme.C2HDataHeader
|
||||
if err := c.r.Receive(&header); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if header.CCCID != c.cid || header.DATAO != 0 || header.DATAL != uint32(len(want)) || c.r.Length() != uint32(len(want)) {
|
||||
t.Fatalf("wrong read frame %+v length%d", header, c.r.Length())
|
||||
}
|
||||
got := make([]byte, c.r.Length())
|
||||
if err := c.r.ReceiveData(got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gap1NVMeReply(t, c.r, c.cid)
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("fsync-acknowledged NVMe record changed after supervised restart")
|
||||
}
|
||||
}
|
||||
|
||||
// Calibration of the witness client only, not a systemd/re-grant proof.
|
||||
func TestGAP1NVMeWitnessRoundTripsAcknowledgedBlock(t *testing.T) {
|
||||
backend := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1})
|
||||
|
||||
@@ -20,9 +20,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
hostvolume "github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc"
|
||||
@@ -87,7 +90,9 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
|
||||
"--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"),
|
||||
"--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"),
|
||||
"--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1",
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base)
|
||||
"--workspace-rpc", "--workspace-head-base-url", "http://"+cluster.filerHTTP+base,
|
||||
// A workspace master writes the layout VOLUME and unclaimed HEAD itself.
|
||||
"--chunk-filer", cluster.filerGRPC, "--chunk-path", base)
|
||||
w4WaitTCP(t, masterAddr, 20*time.Second)
|
||||
admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "")
|
||||
if err != nil {
|
||||
@@ -99,8 +104,19 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
ws := control.NewWorkspaceServiceClient(conn)
|
||||
// The master mints the volume's layout identity; the holder and every
|
||||
// HEAD read name it.
|
||||
var layoutID layout.VolumeID
|
||||
waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume)
|
||||
layoutID = id
|
||||
return e == nil
|
||||
})
|
||||
args := []string{"--master", masterAddr, "--server-id", "s1",
|
||||
"--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), "--volume-id", volume, "--replica-id", "r1",
|
||||
"--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"),
|
||||
"--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(),
|
||||
"--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr,
|
||||
"--durable-root", filepath.Join(root, "store"), "--durable-impl", "walstore-chunk", "--durable-blocks", "64",
|
||||
"--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease",
|
||||
@@ -142,13 +158,19 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
|
||||
t.Logf("acknowledged NVMe record: lba=8 bytes=%d sha256=%x", len(want), sha256.Sum256(want))
|
||||
client.readExact(t, 8, want)
|
||||
client.close()
|
||||
remote := cluster.remote(t, base+"/"+volume)
|
||||
remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: volume, ID: layoutID})
|
||||
before, err := gap1ReadHead(t, remote)
|
||||
if err != nil || before.Gen == 0 {
|
||||
t.Fatalf("bootstrap HEAD: %+v %v", before, err)
|
||||
}
|
||||
gap1Systemctl(t, "kill", "--signal=KILL", "--kill-who=main", bootstrap)
|
||||
waitGAP1(t, "bootstrap still running", 10*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" })
|
||||
// HEAD as the killed holder left it (no process can move it now).
|
||||
ref := chunkstore.VolumeRef{Name: volume, ID: layoutID}
|
||||
atKill := layoutHead(t, cluster, base, ref)
|
||||
if atKill.Holder != "s1/r1" || atKill.ClaimID == "" || atKill.State != layout.StateLive {
|
||||
t.Fatalf("HEAD at the kill: %+v; want live, held by s1/r1 under a claim", atKill)
|
||||
}
|
||||
// QueryWorkspace is read-only. These real binaries and this test share
|
||||
// one WSL kernel wall clock. Use the reported MASTER expiry timestamp,
|
||||
// not ValidForNs (which ends half a skew earlier and could renew live).
|
||||
@@ -207,10 +229,20 @@ func TestSystemdExpiredStartupExits75ThenRegrantServes(t *testing.T) {
|
||||
}
|
||||
return true
|
||||
})
|
||||
after, err := gap1ReadHead(t, remote)
|
||||
if err != nil || after.Gen <= before.Gen || after.Holder != before.Holder || after.Epoch != before.Epoch {
|
||||
t.Fatalf("return did not claim HEAD: before%+v after%+v err%v", before, after, err)
|
||||
// The holder returns with its own claim at the same epoch: over an idle
|
||||
// HEAD it resumes with no HEAD write; a session of its claim left open at
|
||||
// the kill is aborted (a HEAD write) before it serves.
|
||||
after := layoutHead(t, cluster, base, ref)
|
||||
if after.Holder != atKill.Holder || after.Epoch != atKill.Epoch || after.ClaimID != atKill.ClaimID || after.State != layout.StateLive || after.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("return did not resume its claim: at kill %+v, after %+v", atKill, after)
|
||||
}
|
||||
switch {
|
||||
case atKill.Activity.Kind == layout.ActIdle && after.Gen != atKill.Gen:
|
||||
t.Fatalf("return over an idle HEAD wrote it: gen %d -> %d", atKill.Gen, after.Gen)
|
||||
case atKill.Activity.Kind != layout.ActIdle && after.Gen <= atKill.Gen:
|
||||
t.Fatalf("return left the open %s session %q: gen %d -> %d", atKill.Activity.Kind, atKill.Activity.Session, atKill.Gen, after.Gen)
|
||||
}
|
||||
t.Logf("return resumed claim %s at epoch %d: activity at kill %s, gen %d -> %d", after.ClaimID, after.Epoch, atKill.Activity.Kind, atKill.Gen, after.Gen)
|
||||
returned := gap1ConnectNVMe(t, nvmeAddr, "nqn.2026-11.test:"+stem)
|
||||
returned.readExact(t, 8, want)
|
||||
returned.writeFlush(t, 9, want)
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
//go:build linux && subprocess && chunkstore_integration
|
||||
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
master "github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// moveHost is one blockvolume process of the move test: its addresses and
|
||||
// the running binary.
|
||||
type moveHost struct {
|
||||
server, data, ctrl, status, nvme, nqn string
|
||||
cmd *exec.Cmd
|
||||
done chan error
|
||||
exited bool
|
||||
}
|
||||
|
||||
func newMoveHost(t *testing.T, server, nqn string) *moveHost {
|
||||
return &moveHost{server: server, data: leaseBinaryAddress(t), ctrl: leaseBinaryAddress(t), status: leaseBinaryAddress(t),
|
||||
nvme: leaseBinaryAddress(t), nqn: nqn}
|
||||
}
|
||||
|
||||
// start runs the blockvolume binary for vol-a as replica r1 on this host,
|
||||
// with the master-minted layout identity, and kills it at cleanup.
|
||||
func (m *moveHost) start(t *testing.T, exe, masterAddr, filerGRPC, base string, layoutID layout.VolumeID) {
|
||||
t.Helper()
|
||||
logPath := filepath.Join(t.TempDir(), m.server+".log")
|
||||
log, err := os.Create(logPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.cmd = exec.Command(exe, "--master", masterAddr, "--server-id", m.server, "--volume-id", "vol-a", "--replica-id", "r1",
|
||||
"--data-addr", m.data, "--ctrl-addr", m.ctrl, "--t1-readiness", "--status-addr", m.status,
|
||||
"--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(),
|
||||
"--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", filerGRPC, "--chunk-path", base,
|
||||
"--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", m.nvme, "--nvme-subsysnqn", m.nqn)
|
||||
stripSystemdForTestLockDir(m.cmd)
|
||||
m.cmd.Stdout, m.cmd.Stderr = log, log
|
||||
if err := m.cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.done = make(chan error, 1)
|
||||
go func() { m.done <- m.cmd.Wait() }()
|
||||
t.Cleanup(func() {
|
||||
if !m.exited {
|
||||
_ = m.cmd.Process.Kill()
|
||||
select {
|
||||
case <-m.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Errorf("%s did not exit after kill", m.server)
|
||||
}
|
||||
}
|
||||
log.Close()
|
||||
if t.Failed() {
|
||||
b, _ := os.ReadFile(logPath)
|
||||
if len(b) > 14000 {
|
||||
b = b[len(b)-14000:]
|
||||
}
|
||||
t.Logf("%s log: %s", m.server, b)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// wait waits for the process to end on its own within d.
|
||||
func (m *moveHost) wait(t *testing.T, d time.Duration) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-m.done:
|
||||
m.exited = true
|
||||
case <-time.After(d):
|
||||
t.Fatalf("%s did not exit", m.server)
|
||||
}
|
||||
}
|
||||
|
||||
// projection is the volume's status as this host reports it.
|
||||
func (m *moveHost) projection() (frontend.Projection, bool) {
|
||||
c := &http.Client{Timeout: time.Second}
|
||||
resp, err := c.Get("http://" + m.status + "/status?volume=vol-a")
|
||||
if err != nil {
|
||||
return frontend.Projection{}, false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var p frontend.Projection
|
||||
return p, json.NewDecoder(resp.Body).Decode(&p) == nil
|
||||
}
|
||||
|
||||
// layoutHead reads ref's HEAD as stored (claim id included).
|
||||
func layoutHead(t *testing.T, cluster *w4WeedCluster, base string, ref chunkstore.VolumeRef) layout.Head {
|
||||
t.Helper()
|
||||
cl := cluster.client(t, base)
|
||||
cat, err := chunkstore.NewBCatalog(cl, cl, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
h, found, err := cat.ReadHead(ctx, ref)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("HEAD of %s: found %v, %v", ref.Name, found, err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// A move on the content-named layout with real processes: the master in
|
||||
// process, SeaweedFS and two blockvolume binaries. Clean: the source writes,
|
||||
// cuts and stops (HEAD detached by the source's claim), the master moves the
|
||||
// volume, the target claims HEAD at the higher epoch and reads back every
|
||||
// acknowledged write. Forced: the source is killed after its cut and one more
|
||||
// acknowledged write; after the master's barrier the forced move is issued
|
||||
// with its lost range recorded, and the target claims and reads back what the
|
||||
// cut published. HEAD's state, epoch, holder and claim are asserted at each
|
||||
// step.
|
||||
func TestIntegrationWorkspaceLayoutMove(t *testing.T) {
|
||||
if os.Getenv("CHUNKSTORE_WEED") == "" {
|
||||
t.Skip("CHUNKSTORE_WEED not set")
|
||||
}
|
||||
exe := filepath.Join(t.TempDir(), "blockvolume")
|
||||
if out, err := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".").CombinedOutput(); err != nil {
|
||||
t.Fatalf("build: %v %s", err, out)
|
||||
}
|
||||
cluster := startWorkspaceWeed(t)
|
||||
for _, kind := range []string{"clean", "forced"} {
|
||||
t.Run(kind, func(t *testing.T) { layoutMove(t, exe, cluster, kind) })
|
||||
}
|
||||
}
|
||||
|
||||
func layoutMove(t *testing.T, exe string, cluster *w4WeedCluster, kind string) {
|
||||
base := fmt.Sprintf("/workspace-move-%s-%d", kind, time.Now().UnixNano())
|
||||
var h *master.Host
|
||||
reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) {
|
||||
return h.WorkspaceLayoutVolume(ctx, name)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0",
|
||||
WorkspaceRPC: true, WorkspaceHeadReader: reader, WorkspaceMaxClockSkew: 100 * time.Millisecond,
|
||||
LayoutCreateVolume: layoutMasterWriter(t, cluster, base)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
t.Cleanup(func() {
|
||||
ctx, c := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer c()
|
||||
_ = h.Close(ctx)
|
||||
})
|
||||
src, dst := newMoveHost(t, "node-a", "nqn.2026-11.test:move-src-"+kind), newMoveHost(t, "node-b", "nqn.2026-11.test:move-dst-"+kind)
|
||||
// The master's create writes VOLUME and the unclaimed HEAD, then marks
|
||||
// the record store-ready; only a store-ready volume gets a placement.
|
||||
layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096)
|
||||
ref := chunkstore.VolumeRef{Name: "vol-a", ID: layoutID}
|
||||
for _, n := range []*moveHost{src, dst} {
|
||||
if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.server, DataAddr: n.data, CtrlAddr: n.ctrl}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err = h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{
|
||||
{VolumeID: "vol-a", ServerID: src.server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = h.ObservationHost().Ingest(authority.Observation{ServerID: src.server, ObservedAt: time.Now().UTC(),
|
||||
Slots: []authority.SlotFact{{VolumeID: "vol-a", ReplicaID: "r1", DataAddr: src.data, CtrlAddr: src.ctrl}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = h.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaseBinaryPoll(t, "no initial authority", func() bool { line, ok := h.Publisher().VolumeAuthorityLine("vol-a"); return ok && line.Epoch > 0 })
|
||||
line, _ := h.Publisher().VolumeAuthorityLine("vol-a")
|
||||
remote := cluster.remote(t, base, ref)
|
||||
|
||||
// The source serves, takes acknowledged writes, cuts.
|
||||
src.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID)
|
||||
leaseBinaryPoll(t, "source did not serve", func() bool { p, ok := src.projection(); return ok && p.Healthy && p.Epoch == line.Epoch })
|
||||
want, late := bytes.Repeat([]byte{0xD7}, 4096), bytes.Repeat([]byte{0x5A}, 4096)
|
||||
nv := gap1ConnectNVMe(t, src.nvme, src.nqn)
|
||||
nv.writeFlush(t, 8, want)
|
||||
nv.writeFlush(t, 9, want)
|
||||
leaseBinaryPoll(t, "source cut", func() bool { code, _, e := leaseBinaryPost(src.status, "cut"); return e == nil && code == 200 })
|
||||
cut := layoutHead(t, cluster, base, ref)
|
||||
if cut.Epoch != line.Epoch || cut.Holder != src.server+"/r1" || cut.ClaimID == "" || cut.State != layout.StateLive || cut.Current == nil {
|
||||
t.Fatalf("HEAD after the source's cut: %+v; want live, held by %s/r1 at epoch %d with a claim", cut, src.server, line.Epoch)
|
||||
}
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
ws := control.NewWorkspaceServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
|
||||
defer cancel()
|
||||
q := &control.WorkspaceMove{RequestId: kind + "-move", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch,
|
||||
TargetReplicaId: "r1", TargetServerId: dst.server, TargetDataAddr: dst.data, TargetCtrlAddr: dst.ctrl, Kind: kind, Force: kind == "forced"}
|
||||
if kind == "clean" {
|
||||
nv.close()
|
||||
code, b, e := leaseBinaryPost(src.status, "detach")
|
||||
if e != nil || code != 200 {
|
||||
t.Fatalf("detach: %d %s %v", code, b, e)
|
||||
}
|
||||
sealed := layoutHead(t, cluster, base, ref)
|
||||
if sealed.State != layout.StateDetached || sealed.Epoch != line.Epoch || sealed.Holder != cut.Holder || sealed.ClaimID != cut.ClaimID {
|
||||
t.Fatalf("HEAD after the detach: %+v; want detached by the source's claim %q at epoch %d", sealed, cut.ClaimID, line.Epoch)
|
||||
}
|
||||
if _, err = ws.RevokeWorkspace(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: line.Epoch}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaseBinaryPoll(t, "source did not ACK its drained stop", func() bool { s := h.Publisher().WorkspaceState("vol-a"); return s != nil && s.Ack != nil })
|
||||
src.wait(t, 15*time.Second)
|
||||
} else {
|
||||
// One more acknowledged write after the cut, then the source dies
|
||||
// without a stop: the forced move records it as possibly lost.
|
||||
nv.writeFlush(t, 10, late)
|
||||
nv.close()
|
||||
if err = src.cmd.Process.Signal(syscall.SIGKILL); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src.wait(t, 10*time.Second)
|
||||
killed := layoutHead(t, cluster, base, ref)
|
||||
if killed.State != layout.StateLive || killed.Epoch != line.Epoch || killed.ClaimID != cut.ClaimID {
|
||||
t.Fatalf("HEAD after the kill: %+v; want still the source's live claim", killed)
|
||||
}
|
||||
// The master owns the barrier: wait for its affirmative preview.
|
||||
for {
|
||||
pv, err := ws.PreviewWorkspaceMove(ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pv.Admitted {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), pv.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
before := layoutHead(t, cluster, base, ref)
|
||||
grant, err := ws.MoveWorkspace(ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !grant.Issued || grant.NewEpoch <= line.Epoch || grant.OldHost != src.server || grant.NewHost != dst.server || grant.HeadGen != before.Gen || grant.RemoteLsn != before.Position {
|
||||
t.Fatalf("grant %v not bound to HEAD %+v", grant, before)
|
||||
}
|
||||
if after := layoutHead(t, cluster, base, ref); after.Gen != before.Gen || after.Epoch != before.Epoch || after.ClaimID != before.ClaimID {
|
||||
t.Fatalf("the grant itself changed HEAD: %+v -> %+v", before, after)
|
||||
}
|
||||
if kind == "forced" {
|
||||
if grant.LostRange == nil || grant.LostRange.NewEpoch != grant.NewEpoch || grant.LostRange.OldEpoch != line.Epoch || grant.LostRange.LostAfterLsn != before.Position {
|
||||
t.Fatalf("forced grant lost range %v; want after LSN %d, epochs %d -> %d", grant.LostRange, before.Position, line.Epoch, grant.NewEpoch)
|
||||
}
|
||||
lr, err := ws.QueryWorkspaceLostRange(ctx, &control.WorkspaceLostRangeQuery{VolumeId: "vol-a", RequestId: q.RequestId})
|
||||
if err != nil || len(lr.GetRanges()) != 1 || lr.GetRanges()[0].GetLostAfterLsn() != before.Position {
|
||||
t.Fatalf("recorded lost range: %v %v", lr, err)
|
||||
}
|
||||
} else if grant.LostRange != nil {
|
||||
t.Fatalf("clean grant carries a lost range %v", grant.LostRange)
|
||||
}
|
||||
|
||||
// The target claims HEAD at the new epoch and serves what was published.
|
||||
dst.start(t, exe, h.Addr(), cluster.filerGRPC, base, layoutID)
|
||||
leaseBinaryPoll(t, "target did not serve", func() bool { p, ok := dst.projection(); return ok && p.Healthy && p.Epoch == grant.NewEpoch })
|
||||
claimed := layoutHead(t, cluster, base, ref)
|
||||
if claimed.Epoch != grant.NewEpoch || claimed.Holder != dst.server+"/r1" || claimed.State != layout.StateLive || claimed.ClaimID == "" || claimed.ClaimID == cut.ClaimID || claimed.Gen <= before.Gen {
|
||||
t.Fatalf("HEAD after the target's start: %+v; want live, held by %s/r1 at epoch %d under a new claim", claimed, dst.server, grant.NewEpoch)
|
||||
}
|
||||
if eh, err := remote.GetHead(ctx); err != nil || eh.Epoch != grant.NewEpoch || eh.State != "active" || eh.DetachedBy != nil {
|
||||
t.Fatalf("engine view of HEAD after the claim: %+v %v", eh, err)
|
||||
}
|
||||
tv := gap1ConnectNVMe(t, dst.nvme, dst.nqn)
|
||||
tv.readExact(t, 8, want)
|
||||
tv.readExact(t, 9, want)
|
||||
tv.writeFlush(t, 11, want)
|
||||
tv.readExact(t, 11, want)
|
||||
tv.close()
|
||||
t.Logf("%s move on the layout: claim %s@%d -> %s@%d, HEAD gen %d -> %d", kind, cut.ClaimID, line.Epoch, claimed.ClaimID, grant.NewEpoch, before.Gen, claimed.Gen)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
type layoutProofStore struct {
|
||||
h layout.Head
|
||||
found bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s layoutProofStore) ReadHead(context.Context) (layout.Head, bool, error) {
|
||||
return s.h, s.found, s.err
|
||||
}
|
||||
func (s layoutProofStore) UpdateHead(context.Context, uint64, layout.Head) error {
|
||||
return errors.New("proof must not write")
|
||||
}
|
||||
|
||||
func TestWorkspaceLayoutDetachedProof(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mutate func(*layoutProofStore, *control.WorkspaceIdentity, *layout.HolderID)
|
||||
want bool
|
||||
}{
|
||||
{"exact", nil, true},
|
||||
{"absent", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.found = false }, false},
|
||||
{"unknown", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) {
|
||||
s.err = errors.New("read lost")
|
||||
}, false},
|
||||
{"live", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) {
|
||||
s.h.State = layout.StateLive
|
||||
}, false},
|
||||
{"deleting", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) {
|
||||
s.h.State = layout.StateDeleting
|
||||
}, false},
|
||||
{"deleted", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) {
|
||||
s.h.State = layout.StateDeleted
|
||||
}, false},
|
||||
{"open activity", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) {
|
||||
s.h.Activity = layout.Activity{Kind: layout.ActSnap, Session: "old"}
|
||||
}, false},
|
||||
{"zero generation", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Gen = 0 }, false},
|
||||
{"other claim", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.ClaimID = "other" }, false},
|
||||
{"older HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch-- }, false},
|
||||
{"newer HEAD epoch", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Epoch++ }, false},
|
||||
{"other HEAD holder", func(s *layoutProofStore, _ *control.WorkspaceIdentity, _ *layout.HolderID) { s.h.Holder = "other/r" }, false},
|
||||
{"zero request epoch", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.Epoch = 0 }, false},
|
||||
{"zero epoch everywhere", func(s *layoutProofStore, id *control.WorkspaceIdentity, me *layout.HolderID) {
|
||||
s.h.Epoch, id.Epoch, me.Epoch = 0, 0, 0
|
||||
}, false},
|
||||
{"other request server", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ServerId = "other" }, false},
|
||||
{"other request replica", func(_ *layoutProofStore, id *control.WorkspaceIdentity, _ *layout.HolderID) { id.ReplicaId = "other" }, false},
|
||||
{"empty local claim", func(_ *layoutProofStore, _ *control.WorkspaceIdentity, me *layout.HolderID) { me.ClaimID = "" }, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
me := layout.HolderID{Epoch: 2, Holder: "s/r", ClaimID: "k"}
|
||||
id := &control.WorkspaceIdentity{VolumeId: "v", ServerId: "s", ReplicaId: "r", Epoch: 2}
|
||||
st := layoutProofStore{h: layout.Head{Gen: 7, Epoch: 2, Holder: "s/r", ClaimID: "k", State: layout.StateDetached, Activity: layout.Activity{Kind: layout.ActIdle}}, found: true}
|
||||
if tc.mutate != nil {
|
||||
tc.mutate(&st, id, &me)
|
||||
}
|
||||
gen, err := workspaceLayoutDetachedGeneration(context.Background(), st, id, me)
|
||||
if (err == nil) != tc.want || (tc.want && gen != 7) || (!tc.want && gen != 0) {
|
||||
t.Fatalf("gen=%d err=%v", gen, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type workspaceStopResult struct {
|
||||
@@ -47,22 +47,23 @@ func startWorkspaceLease(ctx context.Context, h *volume.Host) (<-chan workspaceS
|
||||
return requests, done
|
||||
}
|
||||
|
||||
// CLEAN requires a prior Detach while the lease was valid. This is read-only:
|
||||
// revocation, expiry and cancellation never manufacture a final cut/proof.
|
||||
func workspaceDetachedGeneration(ctx context.Context, remoteFor func(string) (storage.ChunkRemote, error), id *control.WorkspaceIdentity, holder string) (uint64, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
// workspaceLayoutDetachedGeneration accepts only the attached Start identity's
|
||||
// exact detached HEAD. Missing, foreign or unknown evidence never yields ACK.
|
||||
// The returned generation is diagnostic readout, not the clean-move identity:
|
||||
// the master reads this detached epoch/holder/position when recording the ACK.
|
||||
func workspaceLayoutDetachedGeneration(ctx context.Context, st layout.HeadStore, id *control.WorkspaceIdentity, me layout.HolderID) (uint64, error) {
|
||||
if id == nil || me.Epoch == 0 || id.Epoch != me.Epoch || me.Holder == "" || id.ServerId+"/"+id.ReplicaId != me.Holder || me.ClaimID == "" {
|
||||
return 0, layout.ErrNotHolder
|
||||
}
|
||||
if remoteFor == nil || id == nil {
|
||||
return 0, fmt.Errorf("workspace remote/identity missing")
|
||||
}
|
||||
remote, err := remoteFor(id.VolumeId)
|
||||
h, found, err := st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
head, err := storage.ReadDetachedChunkHead(ctx, remote, id.Epoch, holder)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
if !found {
|
||||
return 0, layout.ErrHeadAbsent
|
||||
}
|
||||
return head.Gen, nil
|
||||
if !layout.DetachedBy(h, me) {
|
||||
return 0, fmt.Errorf("workspace: no detached proof for the attached claim")
|
||||
}
|
||||
return h.Gen, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
master "github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
@@ -69,11 +70,15 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("workspace-rpc-%v", enabled), func(t *testing.T) {
|
||||
base := fmt.Sprintf("/workspace-lease-%d", time.Now().UnixNano())
|
||||
reader, err := master.NewWorkspaceHEADReader("http://" + cluster.filerHTTP + base)
|
||||
var h *master.Host
|
||||
reader, err := master.NewLayoutWorkspaceHEADReader("http://"+cluster.filerHTTP+base, func(ctx context.Context, name string) (chunkstore.VolumeRef, error) {
|
||||
return h.WorkspaceLayoutVolume(ctx, name)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, WorkspaceHeadReader: reader})
|
||||
h, err = master.New(master.Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: enabled, WorkspaceHeadReader: reader,
|
||||
LayoutCreateVolume: layoutMasterWriter(t, cluster, base)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -84,9 +89,9 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
|
||||
_ = h.Close(ctx)
|
||||
})
|
||||
dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t)
|
||||
if _, err = h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The master's create writes VOLUME and the unclaimed HEAD, then
|
||||
// marks the record store-ready; only a store-ready volume gets a placement.
|
||||
layoutID := createStoreReadyVolume(t, h, "vol-a", 64*4096)
|
||||
if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: dataAddr, CtrlAddr: ctrlAddr}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -106,7 +111,7 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease")
|
||||
cmd := exec.Command(exe, "--master", h.Addr(), "--server-id", "node-a", "--volume-id", "vol-a", "--replica-id", "r1", "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--t1-readiness", "--status-addr", statusAddr, "--durable-root", t.TempDir(), "--layout-id", layoutID.String(), "--volume-lock-dir-test-only", t.TempDir(), "--durable-impl", "walstore-chunk", "--durable-blocks", "64", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:workspace-lease")
|
||||
stripSystemdForTestLockDir(cmd)
|
||||
cmd.Stdout, cmd.Stderr = log, log
|
||||
if err = cmd.Start(); err != nil {
|
||||
@@ -144,7 +149,7 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
|
||||
e = json.NewDecoder(resp.Body).Decode(&p)
|
||||
return p, e == nil
|
||||
}
|
||||
remote := cluster.remote(t, base+"/vol-a")
|
||||
remote := cluster.remote(t, base, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID})
|
||||
if !enabled {
|
||||
leaseBinaryPoll(t, "unleased host did not adopt assignment", func() bool { p, ok := projection(); return ok && p.Epoch == line.Epoch })
|
||||
// Exercise an actual cut request, not just the status presentation.
|
||||
@@ -206,9 +211,18 @@ func TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown(t *testing.T) {
|
||||
t.Fatal("NVMe frontend still accepts after shutdown")
|
||||
}
|
||||
if !enabled {
|
||||
head, e := remote.GetHead(context.Background())
|
||||
if e != nil || head.Gen != 0 {
|
||||
t.Fatal("unleased binary changed HEAD", head, e)
|
||||
// No claim was ever made: HEAD is absent, or the unclaimed
|
||||
// HEAD the create wrote (no holder, epoch 0).
|
||||
cl := cluster.client(t, base)
|
||||
cat, e := chunkstore.NewBCatalog(cl, cl, base)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
head, found, e := cat.ReadHead(ctx, chunkstore.VolumeRef{Name: "vol-a", ID: layoutID})
|
||||
cancel()
|
||||
if e != nil || found && (head.Holder != "" || head.Epoch != 0 || head.ClaimID != "") {
|
||||
t.Fatal("unleased binary changed HEAD", head, found, e)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type workspaceProofRemote struct {
|
||||
storage.ChunkRemote
|
||||
head storage.ChunkHead
|
||||
err error
|
||||
reads int
|
||||
}
|
||||
|
||||
func (r *workspaceProofRemote) GetHead(context.Context) (storage.ChunkHead, error) {
|
||||
r.reads++
|
||||
return r.head, r.err
|
||||
}
|
||||
|
||||
func TestWorkspaceRevocationUsesExactStoredSeal(t *testing.T) {
|
||||
for _, name := range []string{"valid", "zero-epoch", "empty-holder", "active", "missing-proof", "proof-gen", "proof-epoch", "proof-holder", "foreign-holder", "foreign-epoch", "zero-gen", "read-error"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := storage.ChunkHead{Gen: 7, Epoch: 2, Holder: "s/r", State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "s/r"}}
|
||||
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}
|
||||
holder := "s/r"
|
||||
r := &workspaceProofRemote{head: h}
|
||||
switch name {
|
||||
case "zero-epoch":
|
||||
id.Epoch = 0
|
||||
r.head.Epoch = 0
|
||||
r.head.DetachedBy.Epoch = 0
|
||||
case "empty-holder":
|
||||
holder = ""
|
||||
r.head.Holder = ""
|
||||
r.head.DetachedBy.Holder = ""
|
||||
case "active":
|
||||
r.head.State = storage.ChunkHeadActive
|
||||
case "missing-proof":
|
||||
r.head.DetachedBy = nil
|
||||
case "zero-gen":
|
||||
r.head.Gen = 0
|
||||
r.head.DetachedBy.Gen = 0
|
||||
case "proof-epoch":
|
||||
r.head.DetachedBy.Epoch = 1
|
||||
case "proof-holder":
|
||||
r.head.DetachedBy.Holder = "other/r"
|
||||
case "foreign-epoch":
|
||||
r.head.Epoch = 1
|
||||
case "proof-gen":
|
||||
r.head.DetachedBy.Gen = 6
|
||||
case "foreign-holder":
|
||||
r.head.Holder = "other/r"
|
||||
case "read-error":
|
||||
r.err = errors.New("HEAD answer lost")
|
||||
}
|
||||
gen, err := workspaceDetachedGeneration(context.Background(), func(string) (storage.ChunkRemote, error) { return r, nil }, id, holder)
|
||||
if name == "valid" {
|
||||
if err != nil || gen != 7 || r.reads != 1 {
|
||||
t.Fatalf("stored seal: gen%d reads%d err%v", gen, r.reads, err)
|
||||
}
|
||||
} else if err == nil || gen != 0 {
|
||||
t.Fatalf("unproven ACK gen%d err%v", gen, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"math"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
@@ -225,9 +227,17 @@ func (c *w4WeedCluster) client(t *testing.T, assignPath string) *chunkstore.SWFS
|
||||
return cl
|
||||
}
|
||||
|
||||
func (c *w4WeedCluster) remote(t *testing.T, root string) *chunkstore.ChunkRemote {
|
||||
// remote reads ref's HEAD under base as the chunk engine sees it, through the
|
||||
// layout remote of an observer that holds nothing: its epoch, holder and
|
||||
// claim match no HEAD, so it never rolls a session back or writes.
|
||||
func (c *w4WeedCluster) remote(t *testing.T, base string, ref chunkstore.VolumeRef) *chunkstore.LayoutRemote {
|
||||
t.Helper()
|
||||
r, err := chunkstore.NewSWFSChunkRemote(c.client(t, root), root)
|
||||
cl := c.client(t, base)
|
||||
cat, err := chunkstore.NewBCatalog(cl, cl, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := chunkstore.NewLayoutRemote(cat, ref, layout.HolderID{Epoch: math.MaxUint64, Holder: "test-observer", ClaimID: "observer"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -23,8 +23,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -73,11 +73,9 @@ func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Durat
|
||||
|
||||
func runOpsChunk(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|verify|volume-delete|restore", false)
|
||||
return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|detach|show|usage|verify|volume-delete|restore|release|retain", false)
|
||||
}
|
||||
switch args[0] {
|
||||
case "gc":
|
||||
return chunkGC(args[1:], stdout, stderr)
|
||||
case "cut":
|
||||
return chunkCut(args[1:], stdout, stderr)
|
||||
case "snapshot":
|
||||
@@ -88,12 +86,12 @@ func runOpsChunk(args []string, stdout, stderr io.Writer) int {
|
||||
return chunkSnapshots(args[1:], stdout, stderr)
|
||||
case "snapshot-delete":
|
||||
return chunkSnapshotDelete(args[1:], stdout, stderr)
|
||||
case "fork":
|
||||
return chunkFork(args[1:], stdout, stderr)
|
||||
case "show":
|
||||
return chunkShow(args[1:], stdout, stderr)
|
||||
case "usage":
|
||||
return chunkUsage(args[1:], stdout, stderr)
|
||||
case "release":
|
||||
return chunkRelease(args[1:], stdout, stderr)
|
||||
case "retain":
|
||||
return chunkRetain(args[1:], stdout, stderr)
|
||||
case "verify":
|
||||
@@ -233,10 +231,10 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
|
||||
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume, --status-addr and --name are required", false)
|
||||
}
|
||||
if pin {
|
||||
if class != "" && class != chunkstore.SnapshotClassPinned {
|
||||
if class != "" && class != layout.ClassPinned {
|
||||
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--pin conflicts with --class "+class, false)
|
||||
}
|
||||
class = chunkstore.SnapshotClassPinned
|
||||
class = layout.ClassPinned
|
||||
}
|
||||
if expires < 0 || expires > 0 && expiresAtNs != 0 {
|
||||
return chunkFail("snapshot", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--expires must be positive and does not combine with --expires-at-ns", false)
|
||||
@@ -300,32 +298,6 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
|
||||
return chunkPost("detach", statusAddr, "/chunk/detach", timeout, body, stdout, stderr)
|
||||
}
|
||||
|
||||
// chunkCatalog opens the catalog under --chunk-path on --chunk-filer.
|
||||
// It returns exit -1 on success, else the exit code after reporting.
|
||||
// chunkCatalog dials the filer and opens the catalog; a command that writes
|
||||
// (writes) first passes the single-filer start check.
|
||||
func chunkCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) {
|
||||
if filer == "" {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false)
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if writes {
|
||||
if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 {
|
||||
_ = closeFn()
|
||||
return nil, nil, exit
|
||||
}
|
||||
}
|
||||
cat, err := chunkstore.NewCatalog(f, base)
|
||||
if err != nil {
|
||||
_ = closeFn()
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
return cat, closeFn, -1
|
||||
}
|
||||
|
||||
// chunkResult prints v as JSON, or err as "<code>: <message>".
|
||||
func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
|
||||
if err != nil {
|
||||
@@ -335,6 +307,8 @@ func chunkResult(name string, v any, err error, stdout, stderr io.Writer) int {
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, ce.Code, ce.Detail(), ce.Retryable)
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, chunkstore.CodeDeadlineExceeded, err.Error(), true)
|
||||
case layoutCode(err) != "":
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, layoutCode(err), err.Error(), errors.Is(err, layout.ErrPrecondition))
|
||||
default:
|
||||
return chunkFail(name, stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
}
|
||||
@@ -392,143 +366,3 @@ func writeAll(w io.Writer, p []byte) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func chunkSnapshots(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("snapshots", stderr)
|
||||
var (
|
||||
volumeID, filer, base, prefix, startAfter string
|
||||
limit int
|
||||
includeDeleting bool
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.StringVar(&prefix, "prefix", "", "only names with this prefix")
|
||||
fs.StringVar(&startAfter, "start-after", "", "list after this name (the previous page's next)")
|
||||
fs.IntVar(&limit, "limit", 0, "page size (0: the default)")
|
||||
fs.BoolVar(&includeDeleting, "include-deleting", false, "also list snapshots marked deleting")
|
||||
fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" {
|
||||
return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
list, next, err := cat.ListSnapshots(ctx, volumeID, chunkstore.ListOptions{Prefix: prefix, StartAfter: startAfter, Limit: limit, IncludeDeleting: includeDeleting})
|
||||
return chunkResult("snapshots", chunkstore.NewSnapshotListBody(volumeID, list, next), err, stdout, stderr)
|
||||
}
|
||||
|
||||
func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("snapshot-delete", stderr)
|
||||
var (
|
||||
volumeID, filer, base, name string
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&name, "name", "", "snapshot name")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" || name == "" {
|
||||
return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
state, err := cat.DeleteSnapshot(ctx, volumeID, name)
|
||||
return chunkResult("snapshot-delete", chunkstore.SnapshotDeleteBody{VolumeID: volumeID, Name: name, State: state}, err, stdout, stderr)
|
||||
}
|
||||
|
||||
func chunkFork(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("fork", stderr)
|
||||
var (
|
||||
filer, base, source, snapshot, target, requestID string
|
||||
timeout time.Duration
|
||||
)
|
||||
labels := labelFlags{}
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.StringVar(&source, "source", "", "source volume id")
|
||||
fs.StringVar(&snapshot, "snapshot", "", "source snapshot name")
|
||||
fs.StringVar(&target, "target", "", "new volume id")
|
||||
fs.StringVar(&requestID, "request-id", "", "idempotency id; generated and printed when empty (reuse it to retry)")
|
||||
fs.Var(labels, "label", "key=value label (repeatable)")
|
||||
fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout (the fork's own HEAD deadline is OpDeadline)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if source == "" || snapshot == "" || target == "" {
|
||||
return chunkFail("fork", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required", false)
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = newRequestID()
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("fork", filer, base, true, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
res, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID, Labels: map[string]string(labels)})
|
||||
return chunkResult("fork", res, err, stdout, stderr)
|
||||
}
|
||||
|
||||
// chunkShow prints one volume's VOLUME entry and HEAD from the filer (§0.1).
|
||||
func chunkShow(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("show", stderr)
|
||||
var (
|
||||
volumeID, filer, base string
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.DurationVar(&timeout, "timeout", 30*time.Second, "filer timeout")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" {
|
||||
return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("show", filer, base, false, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
v, hasVolume, err := cat.ReadVolume(ctx, volumeID)
|
||||
if err != nil {
|
||||
return chunkResult("show", nil, err, stdout, stderr)
|
||||
}
|
||||
h, hasHead, err := cat.ReadHead(ctx, volumeID)
|
||||
if err != nil {
|
||||
return chunkResult("show", nil, err, stdout, stderr)
|
||||
}
|
||||
var vp *chunkstore.VolumeInfo
|
||||
if hasVolume {
|
||||
vp = &v
|
||||
}
|
||||
var hp *storage.ChunkHead
|
||||
if hasHead {
|
||||
hp = &h
|
||||
}
|
||||
return chunkResult("show", chunkstore.NewVolumeShowBody(volumeID, vp, hp), nil, stdout, stderr)
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// restoreCreateRPC is the one master transition for a restore. Tests replace
|
||||
// it with an in-process master; the CLI never creates a target in the filer.
|
||||
var restoreCreateRPC = func(ctx context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
conn, err := link.DialMasterFromEnv(master)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
return control.NewLifecycleServiceClient(conn).CreateVolume(ctx, req)
|
||||
}
|
||||
|
||||
// bCatalog dials the filer and opens the volume catalog; a command that
|
||||
// writes first passes the single-filer start check. It returns exit -1 on
|
||||
// success, else the exit code after reporting.
|
||||
func bCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.BCatalog, func() error, int) {
|
||||
if filer == "" {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false)
|
||||
}
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
fail := func(msg string) (*chunkstore.BCatalog, func() error, int) {
|
||||
_ = closeFn()
|
||||
return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false)
|
||||
}
|
||||
if writes {
|
||||
if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 {
|
||||
_ = closeFn()
|
||||
return nil, nil, exit
|
||||
}
|
||||
}
|
||||
blobs, ok := f.(chunkstore.Blobs)
|
||||
if !ok {
|
||||
return fail("the filer client does not reach the volume servers")
|
||||
}
|
||||
cat, err := chunkstore.NewBCatalog(f, blobs, base)
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
return cat, closeFn, -1
|
||||
}
|
||||
|
||||
// volumeFlags name a volume; its layout id is resolved through the
|
||||
// master's volume record (never minted, never read from the filer).
|
||||
type volumeFlags struct {
|
||||
name string
|
||||
cmd *bCommand
|
||||
}
|
||||
|
||||
// resolveVolumeID resolves a volume name to its layout id at the master.
|
||||
// Tests replace it.
|
||||
var resolveVolumeID = func(ctx context.Context, master, name string) (layout.VolumeID, error) {
|
||||
conn, err := link.DialMasterFromEnv(master)
|
||||
if err != nil {
|
||||
return layout.VolumeID{}, err
|
||||
}
|
||||
defer conn.Close()
|
||||
return lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), name)
|
||||
}
|
||||
|
||||
func (c *bCommand) bindVolume(v *volumeFlags, flagName, what string) {
|
||||
v.cmd = c
|
||||
c.fs.StringVar(&v.name, flagName, "", what+" name")
|
||||
}
|
||||
|
||||
func (v volumeFlags) ref(flagName string) (chunkstore.VolumeRef, error) {
|
||||
if v.name == "" {
|
||||
return chunkstore.VolumeRef{}, errors.New("--" + flagName + " is required")
|
||||
}
|
||||
if v.cmd.master == "" {
|
||||
return chunkstore.VolumeRef{}, errors.New("--master is required (it resolves the volume's layout id)")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), v.cmd.timeout)
|
||||
defer cancel()
|
||||
id, err := resolveVolumeID(ctx, v.cmd.master, v.name)
|
||||
if err != nil {
|
||||
return chunkstore.VolumeRef{}, fmt.Errorf("resolve --%s %q at the master: %w", flagName, v.name, err)
|
||||
}
|
||||
return chunkstore.VolumeRef{Name: v.name, ID: id}, nil
|
||||
}
|
||||
|
||||
// bCommand parses a catalog command's flags (with --chunk-filer,
|
||||
// --chunk-path and --timeout) and opens the catalog.
|
||||
type bCommand struct {
|
||||
fs *flag.FlagSet
|
||||
filer, base, master string
|
||||
timeout time.Duration
|
||||
stdout, stderr io.Writer
|
||||
}
|
||||
|
||||
func newBCommand(name string, timeout time.Duration, stdout, stderr io.Writer) *bCommand {
|
||||
c := &bCommand{fs: chunkFlagSet(name, stderr), stdout: stdout, stderr: stderr}
|
||||
c.fs.StringVar(&c.filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
c.fs.StringVar(&c.base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
c.fs.DurationVar(&c.timeout, "timeout", timeout, "filer timeout")
|
||||
c.fs.StringVar(&c.master, "master", "", "blockmaster gRPC address (resolves each volume's layout id)")
|
||||
return c
|
||||
}
|
||||
|
||||
// run parses args, resolves the refs, opens the catalog and calls do.
|
||||
func (c *bCommand) run(args []string, writes bool, refs func() error, do func(context.Context, *chunkstore.BCatalog) (any, error)) int {
|
||||
name := chunkName(c.fs)
|
||||
if err := c.fs.Parse(args); err != nil {
|
||||
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if err := refs(); err != nil {
|
||||
return chunkFail(name, c.stdout, c.stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
cat, closeFn, exit := bCatalog(name, c.filer, c.base, writes, c.timeout, c.stdout, c.stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
|
||||
defer cancel()
|
||||
v, err := do(ctx, cat)
|
||||
return chunkResult(name, v, err, c.stdout, c.stderr)
|
||||
}
|
||||
|
||||
// SnapshotEntry is one named snapshot of a volume's HEAD.
|
||||
type SnapshotEntry struct {
|
||||
Name string `json:"name"`
|
||||
Root string `json:"root"`
|
||||
Dependents []string `json:"dependents,omitempty"`
|
||||
}
|
||||
|
||||
// chunkSnapshots lists a volume's named snapshots, in name order.
|
||||
func chunkSnapshots(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("snapshots", 30*time.Second, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
var prefix string
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
c.fs.StringVar(&prefix, "prefix", "", "only names with this prefix")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
h, found, err := cat.ReadHead(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, layout.ErrHeadAbsent
|
||||
}
|
||||
out := []SnapshotEntry{}
|
||||
for n, s := range h.Snapshots {
|
||||
if !strings.HasPrefix(n, prefix) {
|
||||
continue
|
||||
}
|
||||
e := SnapshotEntry{Name: n, Root: s.Root.String()}
|
||||
for _, d := range s.Dependents {
|
||||
e.Dependents = append(e.Dependents, layout.VolumeDir(d.Target, d.TargetID))
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(a, b int) bool { return out[a].Name < out[b].Name })
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
|
||||
// chunkSnapshotDelete removes a named snapshot; refused while a restore
|
||||
// target depends on it.
|
||||
func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("snapshot-delete", 30*time.Second, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
var name string
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
c.fs.StringVar(&name, "name", "", "snapshot name")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, true, func() (err error) {
|
||||
if name == "" {
|
||||
return errors.New("--name is required")
|
||||
}
|
||||
ref, err = vol.ref("volume")
|
||||
return err
|
||||
}, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
if _, err := cat.DeleteSnapshot(ctx, ref, name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]string{"volume": ref.Dir(), "name": name, "state": "absent"}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// chunkShow prints a volume's VOLUME record and HEAD.
|
||||
func chunkShow(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("show", 30*time.Second, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
s, err := cat.Store(ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body := struct {
|
||||
Volume *layout.Volume `json:"volume"`
|
||||
Head *layout.Head `json:"head"`
|
||||
}{}
|
||||
if v, ok, err := s.ReadVolumeRecord(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if ok {
|
||||
body.Volume = &v
|
||||
}
|
||||
if h, ok, err := s.ReadHead(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if ok {
|
||||
body.Head = &h
|
||||
}
|
||||
return body, nil
|
||||
})
|
||||
}
|
||||
|
||||
// chunkUsage prints a volume's snapshots, dependents and the chunks its
|
||||
// current image names.
|
||||
func chunkUsage(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("usage", 60*time.Second, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, false, func() (err error) { ref, err = vol.ref("volume"); return err }, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
return cat.Usage(ctx, ref)
|
||||
})
|
||||
}
|
||||
|
||||
// chunkRestore creates a restore target from a source snapshot: the
|
||||
// target reads the snapshot's chunks from the source's pool until its own
|
||||
// writes replace them; the snapshot cannot be deleted while it depends on
|
||||
// it. The target's layout id comes from its master record.
|
||||
func chunkRestore(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("restore", 6*time.Minute, stdout, stderr)
|
||||
var source, target, snapshot, requestID string
|
||||
c.fs.StringVar(&source, "source", "", "source volume name")
|
||||
c.fs.StringVar(&target, "target", "", "new volume name")
|
||||
c.fs.StringVar(&snapshot, "snapshot", "", "source snapshot name")
|
||||
c.fs.StringVar(&requestID, "request-id", "", "stable identity for retries of this restore")
|
||||
if err := c.fs.Parse(args); err != nil {
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if source == "" || target == "" || snapshot == "" || c.master == "" || source == target {
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --target, --snapshot and --master are required; source and target must differ", false)
|
||||
}
|
||||
if requestID == "" {
|
||||
sum := sha256.Sum256([]byte(target + "\x00" + source + "\x00" + snapshot))
|
||||
requestID = "restore-" + hex.EncodeToString(sum[:16])
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
|
||||
defer cancel()
|
||||
resp, err := restoreCreateRPC(ctx, c.master, &control.CreateVolumeRequest{
|
||||
VolumeId: target, SourceVolume: source, SourceSnapshot: snapshot, CreateRequestId: requestID,
|
||||
})
|
||||
if err != nil {
|
||||
switch status.Code(err) {
|
||||
case codes.NotFound:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "snapshot_not_found", err.Error(), false)
|
||||
case codes.AlreadyExists:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "target_exists", err.Error(), false)
|
||||
case codes.InvalidArgument:
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
case codes.FailedPrecondition:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, "not_admitted", err.Error(), false)
|
||||
case codes.Unavailable, codes.DeadlineExceeded:
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, err.Error(), true)
|
||||
default:
|
||||
return chunkResult("restore", nil, err, stdout, stderr)
|
||||
}
|
||||
}
|
||||
if resp.GetVolumeId() != target || !resp.GetStoreReady() {
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeUnavailableCLI, "master did not confirm the restored target is store-ready", true)
|
||||
}
|
||||
id, err := layout.ParseVolumeID(resp.GetLayoutId())
|
||||
if err != nil {
|
||||
return chunkResult("restore", nil, err, stdout, stderr)
|
||||
}
|
||||
return chunkResult("restore", map[string]string{"source": source, "snapshot": snapshot, "target": (chunkstore.VolumeRef{Name: target, ID: id}).Dir(), "request_id": requestID}, nil, stdout, stderr)
|
||||
}
|
||||
|
||||
// chunkRelease removes a restore target from its source snapshot's
|
||||
// dependents once the target is deleted or no longer names the source's
|
||||
// chunks; a target without HEAD (a restore that never finished) is
|
||||
// tombstoned first so it can never be created later.
|
||||
func chunkRelease(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("release", 30*time.Second, stdout, stderr)
|
||||
var src, tgt volumeFlags
|
||||
c.bindVolume(&src, "source", "source volume")
|
||||
c.bindVolume(&tgt, "target", "restore target")
|
||||
var sref, tref chunkstore.VolumeRef
|
||||
return c.run(args, true, func() (err error) {
|
||||
if sref, err = src.ref("source"); err != nil {
|
||||
return err
|
||||
}
|
||||
tref, err = tgt.ref("target")
|
||||
return err
|
||||
}, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
if _, err := cat.ReleaseTarget(ctx, sref, tref); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]string{"source": sref.Dir(), "target": tref.Dir(), "state": "released"}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// layoutCode is the error code of a layout kernel refusal ("" for any
|
||||
// other error); a lost conditional update is the one retryable code.
|
||||
func layoutCode(err error) string {
|
||||
for _, c := range []struct {
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{layout.ErrNoSnapshot, "snapshot_not_found"},
|
||||
{layout.ErrHasDependents, "snapshot_has_dependents"},
|
||||
{layout.ErrForeignSource, "restore_source_not_own"},
|
||||
{layout.ErrHeadAbsent, "volume_not_found"},
|
||||
{layout.ErrExists, "target_exists"},
|
||||
{layout.ErrVolumeDeleting, "volume_deleting"},
|
||||
{layout.ErrHolderActive, "not_admitted"},
|
||||
{chunkstore.ErrNotAdmitted, "not_admitted"},
|
||||
{layout.ErrTargetLive, "target_live"},
|
||||
{layout.ErrIdentity, "identity_mismatch"},
|
||||
{layout.ErrGeometryMismatch, "geometry_mismatch"},
|
||||
{layout.ErrPrecondition, "conflict"},
|
||||
{retain.ErrInvalidPolicy, "invalid_policy"},
|
||||
} {
|
||||
if errors.Is(err, c.err) {
|
||||
return c.code
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// chunkRetain: sw-block ops chunk retain --volume v --master m
|
||||
// --chunk-filer host:port [--dry-run] applies the volume's retention policy:
|
||||
// it deletes the expired snapshots by the automatic snapshot delete, which
|
||||
// refuses a pinned snapshot or one a restore target depends on. With
|
||||
// --set-policy it stores the policy given by the --keep-* flags in the
|
||||
// volume's RETENTION entry instead; a policy change applies from the next
|
||||
// pass.
|
||||
func chunkRetain(args []string, stdout, stderr io.Writer) int {
|
||||
c := newBCommand("retain", 5*time.Minute, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
var keepYounger time.Duration
|
||||
var dryRun, setPolicy bool
|
||||
var keepNewest, keepHourly, keepDaily, keepWeekly int
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
c.fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing")
|
||||
c.fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it")
|
||||
c.fs.IntVar(&keepNewest, "keep-newest", retain.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots")
|
||||
c.fs.DurationVar(&keepYounger, "keep-younger", retain.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this")
|
||||
c.fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours")
|
||||
c.fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days")
|
||||
c.fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks")
|
||||
var ref chunkstore.VolumeRef
|
||||
// The start check runs only for a pass that writes.
|
||||
writes := true
|
||||
for _, a := range args {
|
||||
if a == "--dry-run" || a == "-dry-run" || a == "--dry-run=true" {
|
||||
writes = false
|
||||
}
|
||||
}
|
||||
return c.run(args, writes, func() (err error) {
|
||||
if setPolicy && dryRun {
|
||||
return errors.New("--set-policy and --dry-run do not combine")
|
||||
}
|
||||
ref, err = vol.ref("volume")
|
||||
return err
|
||||
}, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
if setPolicy {
|
||||
p := retain.Policy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly}
|
||||
if err := cat.SetRetention(ctx, ref, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"volume": ref.Dir(), "policy": p, "policySet": true}, nil
|
||||
}
|
||||
return cat.Retain(ctx, ref, chunkRetainNow(), dryRun)
|
||||
})
|
||||
}
|
||||
|
||||
// chunkRetainNow is the wall clock retention decides by. Tests replace it.
|
||||
var chunkRetainNow = time.Now
|
||||
@@ -0,0 +1,431 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
// memChunkStore is a filer with its volume servers: entries in memory,
|
||||
// needle payloads by fid.
|
||||
type memChunkStore struct {
|
||||
*chunkstore.MemFiler
|
||||
mu sync.Mutex
|
||||
blobs map[string][]byte
|
||||
}
|
||||
|
||||
func newMemChunkStore() *memChunkStore {
|
||||
return &memChunkStore{MemFiler: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}
|
||||
}
|
||||
|
||||
func (m *memChunkStore) Put(_ context.Context, data []byte) (string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
fid := fmt.Sprintf("1,%x", len(m.blobs)+1)
|
||||
m.blobs[fid] = append([]byte(nil), data...)
|
||||
return fid, nil
|
||||
}
|
||||
|
||||
func (m *memChunkStore) Get(_ context.Context, fid string) ([]byte, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
b, ok := m.blobs[fid]
|
||||
if !ok {
|
||||
return nil, chunkstore.ErrBlobNotFound
|
||||
}
|
||||
return append([]byte(nil), b...), nil
|
||||
}
|
||||
|
||||
// testIDs is the master's volume records the commands resolve against:
|
||||
// every volume a test names through volArgs.
|
||||
var testIDs sync.Map
|
||||
|
||||
// useMemChunkStore makes every ops chunk command dial store and resolve
|
||||
// names against testIDs.
|
||||
func useMemChunkStore(t *testing.T, store *memChunkStore) {
|
||||
t.Helper()
|
||||
prev, prevResolve, prevRestore := dialChunkFiler, resolveVolumeID, restoreCreateRPC
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
|
||||
resolveVolumeID = testResolve
|
||||
restoreCreateRPC = func(ctx context.Context, _ string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
sid, err := testResolve(ctx, "", req.GetSourceVolume())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tid, err := testResolve(ctx, "", req.GetVolumeId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = cat.Restore(ctx, chunkstore.VolumeRef{Name: req.GetSourceVolume(), ID: sid}, req.GetSourceSnapshot(), chunkstore.VolumeRef{Name: req.GetVolumeId(), ID: tid})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &control.CreateVolumeResponse{VolumeId: req.GetVolumeId(), LayoutId: tid.String(), StoreReady: true}, nil
|
||||
}
|
||||
t.Cleanup(func() { dialChunkFiler, resolveVolumeID, restoreCreateRPC = prev, prevResolve, prevRestore })
|
||||
}
|
||||
|
||||
func testResolve(_ context.Context, _ string, name string) (layout.VolumeID, error) {
|
||||
if id, ok := testIDs.Load(name); ok {
|
||||
return id.(layout.VolumeID), nil
|
||||
}
|
||||
return layout.VolumeID{}, status.Error(codes.NotFound, "volume not found")
|
||||
}
|
||||
|
||||
type okLease struct{}
|
||||
|
||||
func (okLease) OldLeaseEnded(context.Context, uint64) error { return nil }
|
||||
|
||||
// cliVolume creates v with one chunk and a snapshot named snap of it,
|
||||
// through the layout kernel's own steps.
|
||||
func cliVolume(t *testing.T, store *memChunkStore, name, snap string) chunkstore.VolumeRef {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := chunkstore.VolumeRef{Name: name, ID: id}
|
||||
cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ := cat.Store(v)
|
||||
me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
if _, err := layout.Start(ctx, s, okLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunBegin(ctx, s, me, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte("chunk of " + name)
|
||||
ch := layout.NameChunk(1, data)
|
||||
next := map[uint64]layout.Ref{1: {Owner: name, OwnerID: id, Chunk: ch}}
|
||||
root, segs, _ := layout.Build(next)
|
||||
rn, rb, _ := layout.NameRoot(root)
|
||||
objs := map[string][]byte{ch.Path(): data, rn.Path(): rb}
|
||||
for n, b := range segs {
|
||||
objs[n.Path()] = b
|
||||
}
|
||||
for rel, b := range objs {
|
||||
if err := layout.EnsureObject(ctx, s, rel, b, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := layout.RunCommit(ctx, s, s, name, me, layout.CommitRequest{Session: "s1", Next: next, Position: 1, Snapshot: snap}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func volArgs(flag string, v chunkstore.VolumeRef) []string {
|
||||
testIDs.Store(v.Name, v.ID)
|
||||
return []string{"--" + flag, v.Name}
|
||||
}
|
||||
|
||||
func cliArgs(cmd string, parts ...[]string) []string {
|
||||
out := []string{cmd, "--chunk-filer", "filer:18888", "--master", "m:1"}
|
||||
for _, p := range parts {
|
||||
out = append(out, p...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The catalog commands on the layout: list, show, usage, restore, release
|
||||
// refused while the target names the source, snapshot delete refused while
|
||||
// depended on, and their error codes.
|
||||
func TestOpsChunk_CatalogCommands(t *testing.T) {
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
src := cliVolume(t, store, "src", "daily")
|
||||
tid, _ := layout.NewVolumeID()
|
||||
tgt := chunkstore.VolumeRef{Name: "t", ID: tid}
|
||||
|
||||
code, out, errs := runChunk(cliArgs("snapshots", volArgs("volume", src))...)
|
||||
var list []SnapshotEntry
|
||||
if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 1 || list[0].Name != "daily" {
|
||||
t.Fatalf("snapshots: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("show", volArgs("volume", src))...); code != 0 || !strings.Contains(out, `"Name":"src"`) || !strings.Contains(out, `"Epoch":1`) {
|
||||
t.Fatalf("show: %d %q", code, out)
|
||||
}
|
||||
if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 || !strings.Contains(out, tgt.Dir()) {
|
||||
t.Fatalf("restore: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("usage", volArgs("volume", tgt))...); code != 0 || !strings.Contains(out, `"foreign_chunks":1`) {
|
||||
t.Fatalf("target usage: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" {
|
||||
t.Fatalf("delete a depended-on snapshot: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("release", volArgs("source", src), volArgs("target", tgt))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "target_live" {
|
||||
t.Fatalf("release of a target still naming the source: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "weekly"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_not_found" {
|
||||
t.Fatalf("restore of a missing snapshot: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk("snapshots", "--chunk-filer", "f:1", "--volume", "src"); code != 2 || !strings.Contains(out, "--master is required") {
|
||||
t.Fatalf("snapshots without --master: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("snapshots", []string{"--volume", "unknown-to-the-master"})...); code != 2 || !strings.Contains(out, "resolve --volume") {
|
||||
t.Fatalf("snapshots of a volume the master does not know: %d %q", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeLifecycle is the blockmaster's delete authority: the reservation is
|
||||
// refused while held (a live line); leaseAfterReserve grants a lease right
|
||||
// after the reservation is committed (a grant racing the admission), which
|
||||
// the master's check then reports; every call is recorded.
|
||||
type fakeLifecycle struct {
|
||||
control.UnimplementedLifecycleServiceServer
|
||||
mu sync.Mutex
|
||||
held bool
|
||||
leaseAfterReserve bool
|
||||
reserved, leased bool
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (f *fakeLifecycle) record(name string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, name)
|
||||
}
|
||||
|
||||
func (f *fakeLifecycle) ReserveVolumeDeletion(_ context.Context, r *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
|
||||
f.record("reserve")
|
||||
if f.held {
|
||||
return nil, status.Error(codes.FailedPrecondition, "volume has a live authority line")
|
||||
}
|
||||
f.reserved = true
|
||||
if f.leaseAfterReserve {
|
||||
f.leased = true
|
||||
}
|
||||
return &control.MarkVolumeDeletingResponse{Known: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeLifecycle) CheckVolumeNoLiveLease(context.Context, *control.MarkVolumeDeletingRequest) (*control.MarkVolumeDeletingResponse, error) {
|
||||
f.record("check")
|
||||
if !f.reserved || f.leased {
|
||||
return nil, status.Error(codes.FailedPrecondition, "a line of the volume holds a live lease")
|
||||
}
|
||||
return &control.MarkVolumeDeletingResponse{Known: true}, nil
|
||||
}
|
||||
|
||||
func startFakeLifecycle(t *testing.T, f *fakeLifecycle) string {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
control.RegisterLifecycleServiceServer(srv, f)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
return lis.Addr().String()
|
||||
}
|
||||
|
||||
// volume-delete: refused while the master holds the volume (nothing
|
||||
// written); a volume whose snapshot has a dependent is refused and the
|
||||
// permanent reservation retained; a restore target deletes and releases its source.
|
||||
func TestOpsChunk_VolumeDeleteOnTheLayout(t *testing.T) {
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
src := cliVolume(t, store, "src", "daily")
|
||||
tid, _ := layout.NewVolumeID()
|
||||
tgt := chunkstore.VolumeRef{Name: "t", ID: tid}
|
||||
if code, out, errs := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"})...); code != 0 {
|
||||
t.Fatalf("restore: %d %q %q", code, out, errs)
|
||||
}
|
||||
del := func(lc *fakeLifecycle, v chunkstore.VolumeRef) (int, string) {
|
||||
addr := startFakeLifecycle(t, lc)
|
||||
code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r1"})...)
|
||||
return code, out
|
||||
}
|
||||
objects := func(v chunkstore.VolumeRef) int {
|
||||
cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
u, err := cat.Usage(context.Background(), v)
|
||||
if err != nil {
|
||||
return -1
|
||||
}
|
||||
return u.OwnChunks + u.ForeignChunks
|
||||
}
|
||||
held := &fakeLifecycle{held: true}
|
||||
if code, out := del(held, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(held.calls, ",") != "reserve" {
|
||||
t.Fatalf("delete of a held volume: %d %q calls %v", code, out, held.calls)
|
||||
}
|
||||
// A grant racing the reservation: the master's check between the HEAD
|
||||
// read and the update refuses, and nothing is deleted.
|
||||
race := &fakeLifecycle{leaseAfterReserve: true}
|
||||
if code, out := del(race, tgt); code != chunkExitFailed || chunkErrorOut(t, out).Code != "not_admitted" || strings.Join(race.calls, ",") != "reserve,check" || objects(tgt) != 1 {
|
||||
t.Fatalf("delete with a lease granted after the reservation: %d %q calls %v objects %d; want refused by the check, nothing deleted", code, out, race.calls, objects(tgt))
|
||||
}
|
||||
if h, _, _ := func() (layout.Head, bool, error) {
|
||||
cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
return cat.ReadHead(context.Background(), tgt)
|
||||
}(); h.State != layout.StateLive {
|
||||
t.Fatalf("HEAD after the refused delete: %s; want live", h.State)
|
||||
}
|
||||
if code, out := del(&fakeLifecycle{}, src); code != chunkExitFailed || chunkErrorOut(t, out).Code != "snapshot_has_dependents" {
|
||||
t.Fatalf("delete of a depended-on source: %d %q", code, out)
|
||||
}
|
||||
ok := &fakeLifecycle{}
|
||||
if code, out := del(ok, tgt); code != 0 || !strings.Contains(out, `"state":"deleted"`) || strings.Join(ok.calls, ",") != "reserve,check" {
|
||||
t.Fatalf("delete of the target: %d %q calls %v", code, out, ok.calls)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"})...); code != 0 {
|
||||
t.Fatalf("delete the released snapshot: %d %q", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
// A volume never created: snapshots refuses volume_not_found, show prints
|
||||
// a null head, volume-delete refuses before asking the master.
|
||||
func TestOpsChunk_AbsentVolume(t *testing.T) {
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
id, _ := layout.NewVolumeID()
|
||||
v := chunkstore.VolumeRef{Name: "never", ID: id}
|
||||
if code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" {
|
||||
t.Fatalf("snapshots of an absent volume: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("show", volArgs("volume", v))...); code != 0 || !strings.Contains(out, `"head":null`) {
|
||||
t.Fatalf("show of an absent volume: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v))...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" {
|
||||
t.Fatalf("retain of an absent volume: %d %q", code, out)
|
||||
}
|
||||
lc := &fakeLifecycle{}
|
||||
addr := startFakeLifecycle(t, lc)
|
||||
if code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "r"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "volume_not_found" || len(lc.calls) != 0 {
|
||||
t.Fatalf("delete of an absent volume: %d %q calls %v; want volume_not_found before any admission", code, out, lc.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// addSnapshot names v's current image again as snapshot name (a new
|
||||
// snapshot transaction with no new chunks).
|
||||
func addSnapshot(t *testing.T, store *memChunkStore, v chunkstore.VolumeRef, name string, meta layout.SnapshotMeta, session string, position uint64) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
s, _ := cat.Store(v)
|
||||
me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
h, _, _ := s.ReadHead(ctx)
|
||||
r, _ := layout.NewReader(defaultChunkPathCLI, v.Dir(), s.Fetch)
|
||||
img, err := r.Open(ctx, *h.Current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, _, _ := img.Resolve(ctx, 1)
|
||||
m := map[uint64]layout.Ref{1: ref}
|
||||
if _, err := layout.RunBegin(ctx, s, me, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root, segs, _ := layout.Build(m)
|
||||
rn, rb, _ := layout.NameRoot(root)
|
||||
objs := map[string][]byte{rn.Path(): rb}
|
||||
for n, b := range segs {
|
||||
objs[n.Path()] = b
|
||||
}
|
||||
for rel, b := range objs {
|
||||
if err := layout.EnsureObject(ctx, s, rel, b, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: session, Prev: m, Next: m, Position: position, Snapshot: name, Meta: meta}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// retain stores a policy with --set-policy and applies it: the newest
|
||||
// unpinned snapshots by creation time are kept, the expired ones deleted,
|
||||
// a pinned one kept, one a restore target depends on refused and
|
||||
// reported; --dry-run writes nothing.
|
||||
func TestOpsChunk_Retain(t *testing.T) {
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
v := cliVolume(t, store, "v", "")
|
||||
now := time.Unix(20_000_000, 0)
|
||||
prevNow := chunkRetainNow
|
||||
chunkRetainNow = func() time.Time { return now }
|
||||
t.Cleanup(func() { chunkRetainNow = prevNow })
|
||||
for i, f := range []struct {
|
||||
name string
|
||||
hours int
|
||||
class string
|
||||
}{{"n1", 1, layout.ClassSemantic}, {"n2", 2, layout.ClassSemantic}, {"n3", 3, layout.ClassSemantic}, {"n4", 4, layout.ClassSemantic}, {"keep", 9, layout.ClassPinned}} {
|
||||
addSnapshot(t, store, v, f.name, layout.SnapshotMeta{CreatedNs: now.Add(-time.Duration(f.hours) * time.Hour).UnixNano(), Class: f.class}, fmt.Sprintf("s%d", i+2), uint64(i+2))
|
||||
}
|
||||
tid, _ := layout.NewVolumeID()
|
||||
if code, out, errs := runChunk(cliArgs("restore", volArgs("source", v), volArgs("target", chunkstore.VolumeRef{Name: "t", ID: tid}), []string{"--snapshot", "n4"})...); code != 0 {
|
||||
t.Fatalf("restore: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "2", "--keep-younger", "0s"})...); code != 0 || !strings.Contains(out, `"policySet":true`) {
|
||||
t.Fatalf("set policy: %d %q %q", code, out, errs)
|
||||
}
|
||||
run := func(extra ...string) chunkstore.RetainResult {
|
||||
t.Helper()
|
||||
code, out, errs := runChunk(cliArgs("retain", volArgs("volume", v), extra)...)
|
||||
var r chunkstore.RetainResult
|
||||
if code != 0 || json.Unmarshal([]byte(out), &r) != nil {
|
||||
t.Fatalf("retain %v: %d %q %q", extra, code, out, errs)
|
||||
}
|
||||
return r
|
||||
}
|
||||
if dry := run("--dry-run"); strings.Join(dry.Deleted, ",") != "n3,n4" {
|
||||
t.Fatalf("dry run: %+v", dry)
|
||||
}
|
||||
got := run()
|
||||
if strings.Join(got.Deleted, ",") != "n3" || strings.Join(got.Refused, ",") != "n4" {
|
||||
t.Fatalf("retain: deleted %v refused %v; want n3 and n4 refused", got.Deleted, got.Refused)
|
||||
}
|
||||
code, out, _ := runChunk(cliArgs("snapshots", volArgs("volume", v))...)
|
||||
var list []SnapshotEntry
|
||||
if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list) != 4 {
|
||||
t.Fatalf("after retain: %d %q; want keep,n1,n2,n4", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--dry-run"})...); code != 2 {
|
||||
t.Fatalf("--set-policy with --dry-run: %d %q", code, out)
|
||||
}
|
||||
if code, out, _ := runChunk(cliArgs("retain", volArgs("volume", v), []string{"--set-policy", "--keep-newest", "-1"})...); code != chunkExitFailed || chunkErrorOut(t, out).Code != "invalid_policy" {
|
||||
t.Fatalf("negative policy: %d %q", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof(t *testing.T) {
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
v := cliVolume(t, store, "leased", "daily")
|
||||
lc := &fakeLifecycle{leased: true}
|
||||
addr := startFakeLifecycle(t, lc)
|
||||
code, out, _ := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", addr, "--request-id", "delete-v"})...)
|
||||
if code == 0 {
|
||||
t.Fatalf("deleted a volume with live lease: %q calls=%v", out, lc.calls)
|
||||
}
|
||||
if got := strings.Join(lc.calls, ","); got != "reserve,check" {
|
||||
t.Fatalf("authority path=%s", got)
|
||||
}
|
||||
cat, _ := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
h, found, err := cat.ReadHead(context.Background(), v)
|
||||
if err != nil || !found || h.State != layout.StateLive {
|
||||
t.Fatalf("HEAD changed despite refused proof: %+v %v %v", h, found, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The operator must never replace the master's proof with local admission.
|
||||
func TestChunkVolumeDeleteAuthorityRPCSites(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
file string
|
||||
want map[string]int
|
||||
}{
|
||||
{"chunk_volume_delete.go", map[string]int{"ReserveVolumeDeletion": 1, "CheckVolumeNoLiveLease": 1, "DialMasterFromEnv": 1}},
|
||||
// resolveVolumeID reads the name binding; restoreCreateRPC makes the
|
||||
// restore's one master CreateVolume call (TestOpsChunkRestoreUsesOnlyMasterCreate).
|
||||
{"chunk_b.go", map[string]int{"DialMasterFromEnv": 2}},
|
||||
{"../../core/host/master/volume_delete_authority.go", map[string]int{"VolumeDeleteAuthority": 2, "Reserve": 1, "NoLiveLease": 1}},
|
||||
} {
|
||||
f, err := parser.ParseFile(token.NewFileSet(), tc.file, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]int{}
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
switch sel.Sel.Name {
|
||||
case "Dial", "DialMasterFromEnv", "ReserveVolumeDeletion", "CheckVolumeNoLiveLease", "MarkVolumeDeleting", "AbortVolumeDeleting", "CommitVolumeDeleting", "VolumeDeleteAuthority", "Reserve", "NoLiveLease":
|
||||
got[sel.Sel.Name]++
|
||||
}
|
||||
return true
|
||||
})
|
||||
for site, n := range got {
|
||||
if tc.want[site] != n {
|
||||
t.Errorf("%s: authority site %s=%d, want %d", tc.file, site, n, tc.want[site])
|
||||
}
|
||||
}
|
||||
for site, n := range tc.want {
|
||||
if got[site] != n {
|
||||
t.Errorf("%s: missing authority site %s=%d, want %d", tc.file, site, got[site], n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
)
|
||||
|
||||
// Same clock seam as GCConfig; production always uses wall time. Tests can
|
||||
// advance grace without sleeping while using actual master/store services.
|
||||
var chunkGCNow = time.Now
|
||||
|
||||
func chunkGC(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("gc", stderr)
|
||||
var filer, base, master string
|
||||
var apply bool
|
||||
var grace, ttl, timeout time.Duration
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace")
|
||||
fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address")
|
||||
fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only")
|
||||
fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)")
|
||||
fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry")
|
||||
fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls")
|
||||
if e := fs.Parse(args); e != nil {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false)
|
||||
}
|
||||
if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false)
|
||||
}
|
||||
f, closeFn, e := dialChunkFiler(filer)
|
||||
if e != nil {
|
||||
return chunkResult("gc", nil, e, stdout, stderr)
|
||||
}
|
||||
defer closeFn()
|
||||
if apply {
|
||||
if exit := refuseUnlessSingleFiler("gc", f, timeout, stdout, stderr); exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
}
|
||||
blobs, ok := f.(chunkstore.BlobDeleter)
|
||||
if !ok {
|
||||
return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false)
|
||||
}
|
||||
cat, e := chunkstore.NewCatalog(f, base)
|
||||
if e != nil {
|
||||
return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, e.Error(), false)
|
||||
}
|
||||
evidence, closeMaster, e := masterEvidence(master)
|
||||
if e != nil {
|
||||
return chunkResult("gc", nil, e, stdout, stderr)
|
||||
}
|
||||
defer closeMaster()
|
||||
issuedEpoch := func(ctx context.Context, vol string) (uint64, error) {
|
||||
reply, e := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol})
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 {
|
||||
return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol)
|
||||
}
|
||||
return reply.Epoch, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
out, e := cat.ExecuteGC(ctx, blobs, chunkstore.GCConfig{Grace: grace, IntentTTL: ttl, Now: chunkGCNow, IssuedEpoch: issuedEpoch}, apply)
|
||||
return chunkGCResult(out, e, stdout, stderr)
|
||||
}
|
||||
|
||||
// masterEvidence dials the blockmaster's evidence service (gc and
|
||||
// volume-delete read volume status from it).
|
||||
func masterEvidence(master string) (control.EvidenceServiceClient, func() error, error) {
|
||||
conn, e := link.DialMasterFromEnv(master)
|
||||
if e != nil {
|
||||
return nil, nil, e
|
||||
}
|
||||
return control.NewEvidenceServiceClient(conn), conn.Close, nil
|
||||
}
|
||||
|
||||
// Error status and code remain failures, but a failure must not erase known
|
||||
// effects or imply that a lost write response means the write did not commit.
|
||||
func chunkGCResult(out chunkstore.GCExecution, err error, stdout, stderr io.Writer) int {
|
||||
if err == nil {
|
||||
return chunkResult("gc", out, nil, stdout, stderr)
|
||||
}
|
||||
body := struct {
|
||||
chunkErrBody
|
||||
GC chunkstore.GCExecution `json:"gc"`
|
||||
}{GC: out}
|
||||
body.Code, body.Message = codeInternalCLI, err.Error()
|
||||
var ce *chunkstore.CatalogError
|
||||
switch {
|
||||
case errors.As(err, &ce):
|
||||
body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk gc: %s: %s\n", body.Code, body.Message)
|
||||
// chunkResult also propagates output errors; either outcome remains FAIL.
|
||||
chunkResult("gc", body, nil, stdout, stderr)
|
||||
return chunkExitFailed
|
||||
}
|
||||
@@ -1,379 +0,0 @@
|
||||
//go:build chunkstore_integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// No mocked filer, needle service or authority RPC. Only the GC clock is
|
||||
// advanced so the test exercises two grace-separated marks without a long soak.
|
||||
func TestIntegration_OpsChunkGC_RealMasterAndStore(t *testing.T) {
|
||||
weed := os.Getenv("CHUNKSTORE_WEED")
|
||||
if weed == "" {
|
||||
t.Fatal("CHUNKSTORE_WEED required: real-service acceptance must not silently skip")
|
||||
}
|
||||
filer := startGCWeed(t, weed)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
const base = "/swblock/gc-cli-test"
|
||||
s, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{FilerGRPC: filer, Collection: "swblock", AssignPath: base})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
// Wait for the real volume registration/assign path, bounded by ctx.
|
||||
var unboundFID string
|
||||
for {
|
||||
unboundFID, err = s.Put(ctx, []byte("readiness"))
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal(err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
// Verify persisted configuration, not shell exit alone. SaveInsideFiler
|
||||
// stores this small configuration inline in the actual filer.
|
||||
conf, err := s.LookupEntry(ctx, "/etc/seaweedfs", "filer.conf")
|
||||
if err != nil || len(conf.GetChunks()) != 0 {
|
||||
t.Fatalf("fsync configuration unavailable: %v %v", conf, err)
|
||||
}
|
||||
var persisted struct {
|
||||
Locations []struct {
|
||||
LocationPrefix string `json:"locationPrefix"`
|
||||
Collection string `json:"collection"`
|
||||
Fsync bool `json:"fsync"`
|
||||
} `json:"locations"`
|
||||
}
|
||||
if err := json.Unmarshal(conf.Content, &persisted); err != nil || len(persisted.Locations) != 1 {
|
||||
t.Fatalf("invalid filer configuration: %s %v", conf.Content, err)
|
||||
}
|
||||
rule := persisted.Locations[0]
|
||||
if rule.LocationPrefix != "/swblock/" || rule.Collection != "swblock" || !rule.Fsync {
|
||||
t.Fatalf("unexpected filer configuration: %s", conf.Content)
|
||||
}
|
||||
t.Logf("verified filer configuration: %s", conf.Content)
|
||||
cat, err := chunkstore.NewCatalog(s, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = cat.EnsureVolume(ctx, "vol-a", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote, err := chunkstore.NewSWFSChunkRemote(s, base+"/vol-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte("exact reachable bytes")
|
||||
for _, key := range []string{"live", "held", "copy", "orphan"} {
|
||||
if err = remote.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Epoch = 1
|
||||
h.Holder = "holder-a"
|
||||
h.RemoteLSN = 1
|
||||
h.Chunks = map[uint64]storage.ChunkRef{0: {Key: "live", SHA256: sha256.Sum256(data)}}
|
||||
flat := h
|
||||
segmented, segmentIntents, err := remote.PrepareManifest(ctx, flat, h, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h = segmented
|
||||
h.Gen, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 0}, h)
|
||||
if err == nil {
|
||||
for _, id := range segmentIntents {
|
||||
if err = remote.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if h.Segments == nil || len(h.Segments) != 1 {
|
||||
t.Fatal("real-service acceptance requires a segmented root")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = cat.CreateSnapshot(ctx, "vol-a", chunkstore.SnapshotRequest{Name: "saved", RequestID: "gc-snapshot"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = remote.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "holder-a", Keys: []string{"held"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Old-format copy intents have no deadline: they must remain roots.
|
||||
if _, err = remote.PutIntent(ctx, storage.ChunkIntent{Gen: h.Gen, Epoch: 1, Holder: "snapshot:vol-a/pending/attempt", Keys: []string{"copy"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := gcTestMasterConfig(t)
|
||||
cfg.LifecycleStoreDir = t.TempDir()
|
||||
m, err := master.New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
t.Cleanup(func() {
|
||||
c, stop := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer stop()
|
||||
if err := m.Close(c); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
// The remote catalog VOLUME is distinct from the master's desired-volume
|
||||
// registry. Register the live RF1 volume before observations mint authority.
|
||||
if _, err = m.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 64 * 4096, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "vol-a", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "vol-a", ServerID: "node-a", ReplicaID: "r2", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = m.ObservationHost().Ingest(authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(), Slots: []authority.SlotFact{{VolumeID: "vol-a", ReplicaID: "r2", DataAddr: "127.0.0.1:9202", CtrlAddr: "127.0.0.1:9102"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
status, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "vol-a"})
|
||||
if err != nil || !status.GetAssigned() || status.GetEpoch() != 1 {
|
||||
t.Fatalf("real authority: %v %v", status, err)
|
||||
}
|
||||
oldClock := chunkGCNow
|
||||
defer func() { chunkGCNow = oldClock }()
|
||||
now := time.Now().Add(2 * time.Hour)
|
||||
chunkGCNow = func() time.Time { return now }
|
||||
call := func(apply bool) chunkstore.GCExecution {
|
||||
t.Helper()
|
||||
args := []string{"gc", "--master", m.Addr(), "--chunk-filer", filer, "--chunk-path", base}
|
||||
if apply {
|
||||
args = append(args, "--apply")
|
||||
}
|
||||
rc, out, stderr := runChunk(args...)
|
||||
if rc != 0 {
|
||||
t.Fatalf("gc rc=%d %s %s", rc, out, stderr)
|
||||
}
|
||||
var result chunkstore.GCExecution
|
||||
if err := json.Unmarshal([]byte(out), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("apply=%v %s", apply, out)
|
||||
return result
|
||||
}
|
||||
preview := call(false)
|
||||
for _, kind := range []string{"HEAD", "snapshot", "capture_intent", "retained_copy_intent"} {
|
||||
found := false
|
||||
for _, r := range preview.Roots {
|
||||
found = found || r.Kind == kind
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("missing root %s: %+v", kind, preview)
|
||||
}
|
||||
}
|
||||
if preview.MarkSaved || preview.Reclaimed != 0 || len(preview.WouldDelete) != 0 {
|
||||
t.Fatalf("first preview: %+v", preview)
|
||||
}
|
||||
first := call(true)
|
||||
if !first.MarkSaved || first.Reclaimed != 0 {
|
||||
t.Fatalf("first mark: %+v", first)
|
||||
}
|
||||
now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second)
|
||||
preview = call(false)
|
||||
if preview.Reclaimed != 0 || len(preview.WouldDelete) != 1 || preview.WouldDelete[0].Key != "orphan" {
|
||||
t.Fatalf("mature preview: %+v", preview)
|
||||
}
|
||||
if got, err := remote.Get(ctx, "orphan"); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("preview deleted blob: %q %v", got, err)
|
||||
}
|
||||
if got, err := s.Get(ctx, preview.WouldDelete[0].FID); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("raw orphan before delete: %q %v", got, err)
|
||||
}
|
||||
applied := call(true)
|
||||
if applied.Reclaimed != 1 || applied.ExpiredIntents != 0 || !applied.MarkSaved {
|
||||
t.Fatalf("apply: %+v", applied)
|
||||
}
|
||||
if _, err := s.Get(ctx, preview.WouldDelete[0].FID); err == nil {
|
||||
t.Fatal("raw orphan needle still readable after DELETE")
|
||||
}
|
||||
if _, err = remote.Get(ctx, "orphan"); err == nil {
|
||||
t.Fatal("orphan still readable")
|
||||
}
|
||||
for _, key := range []string{"live", "held", "copy"} {
|
||||
if got, err := remote.Get(ctx, key); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("lost root %s: %q %v", key, got, err)
|
||||
}
|
||||
}
|
||||
intents, err := remote.ListIntents(ctx)
|
||||
if err != nil || len(intents) != 2 {
|
||||
t.Fatalf("lost intent: %v %v", intents, err)
|
||||
}
|
||||
snaps, _, err := cat.ListSnapshots(ctx, "vol-a", chunkstore.ListOptions{})
|
||||
if err != nil || len(snaps) != 1 {
|
||||
t.Fatalf("lost snapshot: %v %v", snaps, err)
|
||||
}
|
||||
if err = remote.Put(ctx, "orphan", data); err == nil {
|
||||
t.Fatal("GC removed permanent binding tombstone")
|
||||
}
|
||||
|
||||
// The real authority runtime issues a higher epoch; the actual remote HEAD
|
||||
// must also advance before the capture intent can be retired. No lease clock
|
||||
// or fabricated epoch callback is used by the CLI.
|
||||
if _, err := m.FailbackAuthorityRuntime().ExecuteFailback(ctx, authority.FailbackRuntimeRequest{
|
||||
VolumeID: "vol-a", ReplicaID: "r1", TargetDataAddr: "127.0.0.1:9201", TargetCtrlAddr: "127.0.0.1:9101",
|
||||
ExpectedCurrentReplicaID: "r2", ExpectedCurrentEpoch: 1, AckEligible: true, FrontendFencedBeforeFailback: true,
|
||||
DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
issued, err := control.NewEvidenceServiceClient(conn).QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: "vol-a"})
|
||||
if err != nil || issued.GetEpoch() <= 1 {
|
||||
t.Fatalf("higher issued epoch: %v %v", issued, err)
|
||||
}
|
||||
stillHeld := call(false)
|
||||
if len(stillHeld.WouldExpireIntents) != 0 {
|
||||
t.Fatal("issued epoch without HEAD fence expired intent")
|
||||
}
|
||||
cur, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := cur
|
||||
next.Epoch = issued.Epoch
|
||||
next.Holder = "holder-b"
|
||||
if _, err = remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expired := call(true)
|
||||
if expired.ExpiredIntents != 1 || expired.Reclaimed != 0 {
|
||||
t.Fatalf("fenced intent admission: %+v", expired)
|
||||
}
|
||||
now = now.Add(time.Hour + chunkstore.DefaultGCClockSkew + time.Second)
|
||||
reclaimed := call(true)
|
||||
if reclaimed.Reclaimed != 1 || len(reclaimed.WouldDelete) != 1 || reclaimed.WouldDelete[0].Key != "held" {
|
||||
t.Fatalf("expired capture: %+v", reclaimed)
|
||||
}
|
||||
if got, err := s.Get(ctx, unboundFID); err != nil || string(got) != "readiness" {
|
||||
t.Fatalf("unbound needle reclaimed: %q %v", got, err)
|
||||
}
|
||||
for _, key := range []string{"live", "copy"} {
|
||||
if got, err := remote.Get(ctx, key); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("lost surviving root %s: %q %v", key, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startGCWeed(t *testing.T, weed string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
used := map[int]bool{}
|
||||
port := func() int {
|
||||
t.Helper()
|
||||
for p := 21000; p < 40000; p++ {
|
||||
if used[p] || used[p+10000] {
|
||||
continue
|
||||
}
|
||||
a, e := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p))
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
b, e := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p+10000))
|
||||
a.Close()
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
b.Close()
|
||||
used[p] = true
|
||||
used[p+10000] = true
|
||||
return p
|
||||
}
|
||||
t.Fatal("no free ports")
|
||||
return 0
|
||||
}
|
||||
mp, vp, fp := port(), port(), port()
|
||||
run := func(args ...string) {
|
||||
t.Helper()
|
||||
cmd := exec.Command(weed, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
t.Cleanup(func() {
|
||||
_ = cmd.Process.Kill()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("weed child did not settle")
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, name := range []string{"m", "v", "f"} {
|
||||
if err := os.MkdirAll(filepath.Join(dir, name), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
masterAddr := fmt.Sprintf("127.0.0.1:%d", mp)
|
||||
run("master", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", mp), "-mdir="+filepath.Join(dir, "m"), "-volumeSizeLimitMB=256", "-defaultReplication=000")
|
||||
wait := func(p int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
c, e := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", p), 100*time.Millisecond)
|
||||
if e == nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("weed port %d not ready", p)
|
||||
}
|
||||
wait(mp)
|
||||
run("volume", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", vp), "-dir="+filepath.Join(dir, "v"), "-master="+masterAddr, "-max=32")
|
||||
run("filer", "-ip=127.0.0.1", fmt.Sprintf("-port=%d", fp), "-master="+masterAddr, "-defaultStoreDir="+filepath.Join(dir, "f"))
|
||||
wait(fp + 10000)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
configure := exec.CommandContext(ctx, weed, "shell", "-master="+masterAddr, fmt.Sprintf("-filer=127.0.0.1:%d", fp))
|
||||
configure.Dir = dir
|
||||
configure.Stdin = strings.NewReader("fs.configure -locationPrefix=/swblock/ -collection=swblock -fsync -apply\n")
|
||||
configure.Stdout, configure.Stderr = io.Discard, io.Discard
|
||||
configure.WaitDelay = 2 * time.Second
|
||||
if err := configure.Run(); err != nil {
|
||||
t.Fatalf("configure filer durability: %v", err)
|
||||
}
|
||||
return fmt.Sprintf("127.0.0.1:%d", fp+10000)
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Centralize the temporary authority runtime configuration separately from
|
||||
// chunk-upload callers. Authority is issued by the real master runtime;
|
||||
// callers never seed durable authority records directly.
|
||||
func gcTestMasterConfig(t *testing.T) master.Config {
|
||||
t.Helper()
|
||||
return master.Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"}
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
)
|
||||
|
||||
type gcCLIStore struct {
|
||||
writes int
|
||||
blobs map[string][]byte
|
||||
failDeleteAt int
|
||||
afterUpdate func(*filerpb.Entry) error
|
||||
*chunkstore.MemFiler
|
||||
deletes int
|
||||
}
|
||||
|
||||
func (s *gcCLIStore) Put(_ context.Context, data []byte) (string, error) {
|
||||
if s.blobs == nil {
|
||||
s.blobs = map[string][]byte{}
|
||||
}
|
||||
fid := fmt.Sprintf("1,%d", len(s.blobs)+1)
|
||||
s.blobs[fid] = append([]byte{}, data...)
|
||||
return fid, nil
|
||||
}
|
||||
func (s *gcCLIStore) Get(_ context.Context, fid string) ([]byte, error) {
|
||||
b, ok := s.blobs[fid]
|
||||
if !ok {
|
||||
return nil, errors.New("missing blob")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
func (s *gcCLIStore) DeleteBlob(_ context.Context, fid string) error {
|
||||
s.deletes++
|
||||
delete(s.blobs, fid)
|
||||
if s.deletes == s.failDeleteAt {
|
||||
return errors.New("delete response lost")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestOpsChunkGC_DefaultIsReadOnly(t *testing.T) {
|
||||
h, e := master.New(gcTestMasterConfig(t))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
h.Start()
|
||||
defer func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if e := h.Close(ctx); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}()
|
||||
store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}
|
||||
old := dialChunkFiler
|
||||
defer func() { dialChunkFiler = old }()
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
|
||||
code, out, errs := runChunk("gc", "--master", h.Addr(), "--chunk-filer", "local-test", "--chunk-path", "/gc-test")
|
||||
if code != 0 {
|
||||
t.Fatalf("missing safe GC entrypoint: exit=%d out=%s stderr=%s", code, out, errs)
|
||||
}
|
||||
var report struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
Roots []any `json:"roots"`
|
||||
WouldDelete []any `json:"would_delete"`
|
||||
}
|
||||
if e := json.Unmarshal([]byte(out), &report); e != nil || !report.DryRun || report.Roots == nil || report.WouldDelete == nil {
|
||||
t.Fatalf("incomplete dry-run report: %s %v", out, e)
|
||||
}
|
||||
entries, e := store.ListEntries(context.Background(), "/gc-test", "", "", 100)
|
||||
if e != nil || len(entries) != 0 || store.deletes != 0 || store.writes != 0 {
|
||||
t.Fatalf("default GC mutated store: entries=%d deletes=%d err=%v", len(entries), store.deletes, e)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *gcCLIStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, excl bool) error {
|
||||
s.writes++
|
||||
return s.MemFiler.CreateEntry(ctx, dir, e, excl)
|
||||
}
|
||||
func (s *gcCLIStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
s.writes++
|
||||
if err := s.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.afterUpdate != nil {
|
||||
return s.afterUpdate(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *gcCLIStore) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
s.writes++
|
||||
return s.MemFiler.DeleteEntry(ctx, dir, name, expected)
|
||||
}
|
||||
|
||||
func TestOpsChunkGC_InvalidAdmissionHasNoStoreEffects(t *testing.T) {
|
||||
old := dialChunkFiler
|
||||
defer func() { dialChunkFiler = old }()
|
||||
calls := 0
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
calls++
|
||||
t.Fatal("invalid request reached store")
|
||||
return nil, nil, nil
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"gc"},
|
||||
{"gc", "--chunk-filer", "store", "--master", "master", "--grace", "5m"},
|
||||
{"gc", "--chunk-filer", "store", "--master", "master", "--intent-ttl", "0"},
|
||||
{"gc", "--chunk-filer", "store", "--master", "master", "--timeout", "0"},
|
||||
{"gc", "--chunk-filer", "store", "--master", "master", "unexpected"},
|
||||
} {
|
||||
rc, _, _ := runChunk(args...)
|
||||
if rc != 2 {
|
||||
t.Fatalf("invalid %v: exit=%d", args, rc)
|
||||
}
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Fatalf("invalid admission dialed %d times", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func gcPartialFixture(t *testing.T) (*gcCLIStore, *time.Time) {
|
||||
t.Helper()
|
||||
store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}
|
||||
oldDial, oldClock := dialChunkFiler, chunkGCNow
|
||||
t.Cleanup(func() { dialChunkFiler = oldDial; chunkGCNow = oldClock })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
|
||||
now := time.Now().Add(2 * time.Hour)
|
||||
chunkGCNow = func() time.Time { return now }
|
||||
ctx := context.Background()
|
||||
if err := store.CreateEntry(ctx, "/gc-partial", &filerpb.Entry{Name: "v1", IsDirectory: true}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cat, err := chunkstore.NewCatalog(store, "/gc-partial")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote, err := chunkstore.NewChunkRemote(store, store, "/gc-partial/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"orphan-a", "orphan-b"} {
|
||||
if err = remote.Put(ctx, key, []byte(key)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return store, &now
|
||||
}
|
||||
func runPartialGC() (int, string, string) {
|
||||
return runChunk("gc", "--master", "127.0.0.1:1", "--chunk-filer", "local", "--chunk-path", "/gc-partial", "--apply")
|
||||
}
|
||||
func TestOpsChunkGC_FinalWriteResponseLostReportsUnknown(t *testing.T) {
|
||||
store, now := gcPartialFixture(t)
|
||||
store.afterUpdate = func(e *filerpb.Entry) error {
|
||||
if e.Name == "_GC_MARK" && strings.Contains(string(e.Content), `"ready":true`) {
|
||||
return errors.New("final write response lost")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
rc, out, _ := runPartialGC()
|
||||
if rc != 1 {
|
||||
t.Fatalf("lost response must fail: rc=%d %s", rc, out)
|
||||
}
|
||||
entry, err := store.LookupEntry(context.Background(), "/gc-partial", "_GC_MARK")
|
||||
if err != nil || !strings.Contains(string(entry.Content), `"ready":true`) {
|
||||
t.Fatalf("fixture did not commit completed mark: %v %v", entry, err)
|
||||
}
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
GC struct {
|
||||
MarkOutcome string `json:"mark_outcome"`
|
||||
Unknown []string `json:"unknown_outcomes"`
|
||||
} `json:"gc"`
|
||||
}
|
||||
if err = json.Unmarshal([]byte(out), &body); err != nil || body.Code == "" || body.GC.MarkOutcome != "unknown" || len(body.GC.Unknown) != 1 || body.GC.Unknown[0] != "completed_mark_write" {
|
||||
t.Fatalf("lost committed outcome discarded: %s %v", out, err)
|
||||
}
|
||||
store.afterUpdate = nil
|
||||
*now = now.Add(2 * time.Hour)
|
||||
rc, out, _ = runPartialGC()
|
||||
var success chunkstore.GCExecution
|
||||
if err = json.Unmarshal([]byte(out), &success); rc != 0 || err != nil || success.Reclaimed != 2 {
|
||||
t.Fatalf("committed mark was not reusable despite error: %d %s %v", rc, out, err)
|
||||
}
|
||||
}
|
||||
func TestOpsChunkGC_PartialReclaimReportsKnownAndUnknown(t *testing.T) {
|
||||
store, now := gcPartialFixture(t)
|
||||
if rc, out, _ := runPartialGC(); rc != 0 {
|
||||
t.Fatalf("first mark: %d %s", rc, out)
|
||||
}
|
||||
*now = now.Add(2 * time.Hour)
|
||||
store.failDeleteAt = 2
|
||||
rc, out, _ := runPartialGC()
|
||||
if rc != 1 {
|
||||
t.Fatalf("partial failure exit=%d %s", rc, out)
|
||||
}
|
||||
// Both requests took effect, but only the first was acknowledged. The
|
||||
// second is UNKNOWN to the caller; it must not be counted as known success.
|
||||
if store.deletes != 2 || len(store.blobs) != 0 {
|
||||
t.Fatal("partial-effect fixture was not exercised")
|
||||
}
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
GC struct {
|
||||
Reclaimed int
|
||||
MarkOutcome string `json:"mark_outcome"`
|
||||
Unknown []string `json:"unknown_outcomes"`
|
||||
} `json:"gc"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &body); err != nil || body.Code == "" || body.GC.Reclaimed != 1 || body.GC.MarkOutcome != "in_progress" || len(body.GC.Unknown) != 1 || body.GC.Unknown[0] != "reclamation" {
|
||||
t.Fatalf("partial effects discarded or overclaimed: %s %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
type gcFailedMarkLookup struct {
|
||||
*gcCLIStore
|
||||
lookups int
|
||||
}
|
||||
|
||||
func (s *gcFailedMarkLookup) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if name == "_GC_MARK" {
|
||||
s.lookups++
|
||||
return nil, errors.New("mark lookup unavailable")
|
||||
}
|
||||
return s.gcCLIStore.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
func TestOpsChunkGC_FailedMarkLookupPreservesUnknownUnbound(t *testing.T) {
|
||||
for _, apply := range []bool{false, true} {
|
||||
name := "dry-run"
|
||||
if apply {
|
||||
name = "apply"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
store := &gcFailedMarkLookup{gcCLIStore: &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}}
|
||||
old := dialChunkFiler
|
||||
t.Cleanup(func() { dialChunkFiler = old })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
|
||||
args := []string{"gc", "--master", "127.0.0.1:1", "--chunk-filer", "local", "--chunk-path", "/gc-lookup"}
|
||||
if apply {
|
||||
args = append(args, "--apply")
|
||||
}
|
||||
rc, out, stderr := runChunk(args...)
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
GC chunkstore.GCExecution `json:"gc"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rc != 1 || body.Code == "" || !strings.Contains(stderr, "mark lookup unavailable") || !body.GC.UnknownUnbound || body.GC.MarkOutcome != "not_attempted" || body.GC.DryRun == apply || body.GC.MarkSaved || store.lookups != 1 || store.writes != 0 || store.deletes != 0 {
|
||||
t.Fatalf("failed lookup misreported/mutated: rc=%d out=%s stderr=%s lookups=%d writes=%d deletes=%d", rc, out, stderr, store.lookups, store.writes, store.deletes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpsChunkGC_PermanentDeleteReportsFailureWithSavedCoverage(t *testing.T) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
out := chunkstore.GCExecution{MarkOutcome: "complete", MarkSaved: true, GCResult: chunkstore.GCResult{
|
||||
Reclaimed: 1, FailedDeletes: []chunkstore.GCDeleteFailure{{GCObject: chunkstore.GCObject{Volume: "v1", Key: "bad", FID: "3,bad"}, Error: "http 400"}},
|
||||
}}
|
||||
rc := chunkGCResult(out, chunkstore.ErrBlobDeleteRejected, &stdout, &stderr)
|
||||
var body struct {
|
||||
GC chunkstore.GCExecution `json:"gc"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rc != 1 || !body.GC.MarkSaved || body.GC.MarkOutcome != "complete" || body.GC.Reclaimed != 1 || len(body.GC.FailedDeletes) != 1 || body.GC.FailedDeletes[0].FID != "3,bad" {
|
||||
t.Fatalf("partial failure lost saved coverage or object identity: rc=%d body=%s", rc, stdout.String())
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type manifestFixtureFiler struct {
|
||||
@@ -37,24 +35,3 @@ func (f *manifestFixtureFiler) Get(_ context.Context, id string) ([]byte, error)
|
||||
}
|
||||
return append([]byte(nil), b...), nil
|
||||
}
|
||||
|
||||
func prepareFixtureHead(t *testing.T, f *manifestFixtureFiler, h storage.ChunkHead) storage.ChunkHead {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
r, err := chunkstore.NewChunkRemote(f, f, defaultChunkPathCLI+"/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, h, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// These fixtures hand the completed cut directly to the catalog; the
|
||||
// snapshot/fork operations establish their own reachability intents.
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -6,7 +6,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -14,7 +13,6 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
)
|
||||
|
||||
type failWriter struct{}
|
||||
@@ -60,20 +58,12 @@ func TestOpsChunk_OversizedResponseIsRefused(t *testing.T) {
|
||||
|
||||
func TestOpsChunk_LostResultFailsTheCommand(t *testing.T) {
|
||||
srv, _ := chunkServer(t, 200, `{"volumeID":"v1","cutLSN":9}`)
|
||||
mem := chunkstore.NewMemFiler()
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
v := cliVolume(t, store, "v1", "s1")
|
||||
commands := map[string][]string{
|
||||
"cut (HTTP)": {"ops", "chunk", "cut", "--volume", "v1", "--status-addr", srv.URL},
|
||||
"snapshots (filer)": {"ops", "chunk", "snapshots", "--volume", "v1", "--chunk-filer", "filer:18888"},
|
||||
"snapshots (filer)": append([]string{"ops"}, append([]string{"chunk"}, cliArgs("snapshots", volArgs("volume", v))...)...),
|
||||
}
|
||||
for name, args := range commands {
|
||||
for wname, w := range map[string]io.Writer{"failing": failWriter{}, "short": shortWriter{}} {
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
)
|
||||
|
||||
// chunkRestore restores a snapshot into a new independent volume, or drives
|
||||
// an existing restore.
|
||||
//
|
||||
// With --source, --snapshot and --target it creates the target volume from
|
||||
// the snapshot (Catalog.Restore, idempotent by --request-id) and, when
|
||||
// --status-addr names the blockvolume serving the target, starts the restore
|
||||
// driver there and prints its status (the create result goes to stderr). With --volume and --status-addr it
|
||||
// starts (or joins) the driver of an existing restore and prints its status;
|
||||
// --status only prints the status. The driver runs in blockvolume and
|
||||
// outlives this call.
|
||||
func chunkRestore(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("restore", stderr)
|
||||
var (
|
||||
volumeID, statusAddr string
|
||||
filer, base, source, snapshot, target, requestID string
|
||||
statusOnly bool
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "restored volume id (drive an existing restore)")
|
||||
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL serving the restored volume (with --chunk-control-endpoint)")
|
||||
fs.BoolVar(&statusOnly, "status", false, "print the restore status without starting a run")
|
||||
fs.StringVar(&source, "source", "", "source volume id (create a restore)")
|
||||
fs.StringVar(&snapshot, "snapshot", "", "source snapshot name (create a restore)")
|
||||
fs.StringVar(&target, "target", "", "new volume id (create a restore)")
|
||||
fs.StringVar(&requestID, "request-id", "", "idempotency id for the create; generated and printed when empty (reuse it to retry)")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port (create a restore)")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.DurationVar(&timeout, "timeout", 6*time.Minute, "filer timeout for the create")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
create := source != "" || snapshot != "" || target != ""
|
||||
switch {
|
||||
case create && volumeID != "":
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "use --source/--snapshot/--target to create a restore, or --volume to drive one, not both", false)
|
||||
case create && (source == "" || snapshot == "" || target == ""):
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--source, --snapshot and --target are required to create a restore", false)
|
||||
case create && statusOnly:
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--status reads an existing restore: use it with --volume", false)
|
||||
case !create && (volumeID == "" || statusAddr == ""):
|
||||
return chunkFail("restore", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required (or --source, --snapshot and --target to create a restore)", false)
|
||||
}
|
||||
if !create {
|
||||
body := map[string]any{"volumeID": volumeID, "statusOnly": statusOnly}
|
||||
return chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr)
|
||||
}
|
||||
|
||||
if requestID == "" {
|
||||
requestID = newRequestID()
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk restore: request id %s (reuse it to retry)\n", requestID)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("restore", filer, base, true, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
res, err := cat.Restore(ctx, chunkstore.ForkRequest{Source: source, Snapshot: snapshot, Target: target, RequestID: requestID})
|
||||
if err != nil || statusAddr == "" {
|
||||
if err == nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk restore: %s created; attach it, then run: sw-block ops chunk restore --volume %s --status-addr <its blockvolume>\n", target, target)
|
||||
}
|
||||
return chunkResult("restore", res, err, stdout, stderr)
|
||||
}
|
||||
created, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
return chunkFail("restore", stdout, stderr, chunkExitFailed, codeInternalCLI, err.Error(), false)
|
||||
}
|
||||
// stdout stays one JSON document (the driver status); the create result
|
||||
// goes to stderr.
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk restore: created %s\n", created)
|
||||
body := map[string]any{"volumeID": target}
|
||||
code := chunkPost("restore", statusAddr, "/chunk/restore", 30*time.Second, body, stdout, stderr)
|
||||
if code != ops.VolumeStatusExitOK {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk restore: %s was created, but the restore did not start at %s (is the target attached there?); once it is, run: sw-block ops chunk restore --volume %s --status-addr <its blockvolume>\n", target, statusAddr, target)
|
||||
}
|
||||
return code
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestOpsChunk_RestoreStartsAndReportsStatus(t *testing.T) {
|
||||
var got []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/chunk/restore" || r.Method != http.MethodPost {
|
||||
http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
got = append(got, body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"volumeID":"v2","phase":"owning","running":true,"foreign":3}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
for _, args := range [][]string{{"restore", "--volume", "v2", "--status-addr", srv.URL}, {"restore", "--volume", "v2", "--status-addr", srv.URL, "--status"}} {
|
||||
var out, errb bytes.Buffer
|
||||
if code := runOpsChunk(args, &out, &errb); code != 0 || !strings.Contains(out.String(), `"phase":"owning"`) {
|
||||
t.Fatalf("%v: exit %d out %q err %q", args, code, out.String(), errb.String())
|
||||
}
|
||||
}
|
||||
if len(got) != 2 || got[0]["volumeID"] != "v2" || got[0]["statusOnly"] != false || got[1]["statusOnly"] != true {
|
||||
t.Fatalf("requests %v: want a start, then a status-only call", got)
|
||||
}
|
||||
var out, errb bytes.Buffer
|
||||
if code := runOpsChunk([]string{"restore", "--status-addr", srv.URL}, &out, &errb); code == 0 {
|
||||
t.Fatal("restore without --volume must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
// restoreSource publishes volume src with one chunk and snapshot s1 in a
|
||||
// fresh store, and routes the CLI's filer dial to it.
|
||||
func restoreSource(t *testing.T, base string) (*gcCLIStore, *chunkstore.Catalog) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
store := &gcCLIStore{MemFiler: chunkstore.NewMemFiler()}
|
||||
old := dialChunkFiler
|
||||
t.Cleanup(func() { dialChunkFiler = old })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
|
||||
cat, err := chunkstore.NewCatalog(store, base)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
|
||||
if _, err := cat.EnsureVolume(ctx, "src", geo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := chunkstore.NewChunkRemote(store, store, base+"/src")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := make([]byte, 8*4096)
|
||||
data[0] = 0x7
|
||||
if err := r.Put(ctx, "chunks/e1/c0/k", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k", SHA256: sha256.Sum256(data)}}}
|
||||
h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
_ = r.DeleteIntent(ctx, id)
|
||||
}
|
||||
if _, err := cat.CreateSnapshot(ctx, "src", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, cat
|
||||
}
|
||||
|
||||
// --source/--snapshot/--target creates the restore volume (idempotent by
|
||||
// request id); without --status-addr it says how to start the driver.
|
||||
func TestOpsChunk_RestoreCreatesTheTarget(t *testing.T) {
|
||||
_, cat := restoreSource(t, "/rs")
|
||||
args := []string{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs"}
|
||||
code, out, errs := runChunk(args...)
|
||||
if code != 0 || !strings.Contains(out, `"dst"`) || !strings.Contains(errs, "--volume dst") {
|
||||
t.Fatalf("create: exit %d out %s err %s", code, out, errs)
|
||||
}
|
||||
v, ok, err := cat.ReadVolume(context.Background(), "dst")
|
||||
if err != nil || !ok || v.Origin != chunkstore.OriginRestore {
|
||||
t.Fatalf("target: %+v ok=%v %v, want a restore volume", v, ok, err)
|
||||
}
|
||||
if code, out, errs := runChunk(args...); code != 0 {
|
||||
t.Fatalf("retry with the same request id: exit %d out %s err %s", code, out, errs)
|
||||
}
|
||||
for _, bad := range [][]string{
|
||||
{"restore", "--source", "src", "--target", "dst", "--chunk-filer", "x"},
|
||||
{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--volume", "dst", "--chunk-filer", "x"},
|
||||
{"restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--status", "--chunk-filer", "x"},
|
||||
} {
|
||||
if code, _, _ := runChunk(bad...); code == 0 {
|
||||
t.Fatalf("%v accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With --status-addr the create then starts the driver for the target on
|
||||
// that blockvolume, in one command.
|
||||
func TestOpsChunk_RestoreCreatesAndStartsTheDriver(t *testing.T) {
|
||||
_, cat := restoreSource(t, "/rs2")
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"volumeID":"dst","phase":"hydrating","running":true}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
code, out, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs2", "--status-addr", srv.URL)
|
||||
if code != 0 || !strings.Contains(out, `"phase":"hydrating"`) || !strings.Contains(errs, "created ") {
|
||||
t.Fatalf("create and start: exit %d out %s err %s", code, out, errs)
|
||||
}
|
||||
var one map[string]any
|
||||
if err := json.Unmarshal([]byte(out), &one); err != nil {
|
||||
t.Fatalf("stdout is not one JSON document: %v (%s)", err, out)
|
||||
}
|
||||
if got["volumeID"] != "dst" || got["statusOnly"] != nil {
|
||||
t.Fatalf("driver request %v, want a start for dst", got)
|
||||
}
|
||||
if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok {
|
||||
t.Fatal("the target was not created before the driver start")
|
||||
}
|
||||
}
|
||||
|
||||
// A start that fails after the create (the target not attached there yet)
|
||||
// says the target exists and how to start the restore later.
|
||||
func TestOpsChunk_RestoreCreateThenStartRefusedSaysHowToResume(t *testing.T) {
|
||||
_, cat := restoreSource(t, "/rs3")
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_, _ = w.Write([]byte(`{"code":"not_chunk_volume","message":"volume dst not open","retryable":false}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
code, _, errs := runChunk("restore", "--source", "src", "--snapshot", "s1", "--target", "dst", "--request-id", "rq", "--chunk-filer", "x", "--chunk-path", "/rs3", "--status-addr", srv.URL)
|
||||
if code == 0 || !strings.Contains(errs, "dst was created") || !strings.Contains(errs, "--volume dst") {
|
||||
t.Fatalf("refused start: exit %d err %s", code, errs)
|
||||
}
|
||||
if _, ok, _ := cat.ReadVolume(context.Background(), "dst"); !ok {
|
||||
t.Fatal("the target must exist after the create")
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
)
|
||||
|
||||
// chunkUsage: sw-block ops chunk usage --volume v --chunk-filer host:port
|
||||
// prints the volume's space accounting and retention policy (from
|
||||
// manifests and filer listings; no chunk data reads).
|
||||
func chunkUsage(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("usage", stderr)
|
||||
var (
|
||||
volumeID, filer, base string
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.DurationVar(&timeout, "timeout", 60*time.Second, "filer timeout")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" {
|
||||
return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("usage", filer, base, false, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
u, err := cat.Usage(ctx, volumeID)
|
||||
return chunkResult("usage", u, err, stdout, stderr)
|
||||
}
|
||||
|
||||
// chunkRetain: sw-block ops chunk retain --volume v --chunk-filer host:port
|
||||
// [--dry-run] applies the volume's retention policy (deletes the expired
|
||||
// snapshots; GC reclaims their chunks). With --set-policy it stores the
|
||||
// policy given by the --keep-* flags on the VOLUME entry instead.
|
||||
func chunkRetain(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("retain", stderr)
|
||||
var (
|
||||
volumeID, filer, base string
|
||||
timeout, keepYounger time.Duration
|
||||
dryRun, setPolicy bool
|
||||
keepNewest, keepHourly, keepDaily, keepWeekly int
|
||||
)
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.DurationVar(&timeout, "timeout", 5*time.Minute, "bound for this pass")
|
||||
fs.BoolVar(&dryRun, "dry-run", false, "list what would be deleted; write nothing")
|
||||
fs.BoolVar(&setPolicy, "set-policy", false, "store the --keep-* policy on the volume instead of applying it")
|
||||
fs.IntVar(&keepNewest, "keep-newest", chunkstore.DefaultKeepNewest, "with --set-policy: keep the newest N unpinned snapshots")
|
||||
fs.DurationVar(&keepYounger, "keep-younger", chunkstore.DefaultKeepYounger, "with --set-policy: keep every snapshot younger than this")
|
||||
fs.IntVar(&keepHourly, "keep-hourly", 0, "with --set-policy: keep the newest snapshot of each of the last N hours")
|
||||
fs.IntVar(&keepDaily, "keep-daily", 0, "with --set-policy: keep the newest snapshot of each of the last N days")
|
||||
fs.IntVar(&keepWeekly, "keep-weekly", 0, "with --set-policy: keep the newest snapshot of each of the last N weeks")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" || timeout <= 0 {
|
||||
return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required and --timeout must be positive", false)
|
||||
}
|
||||
if setPolicy && dryRun {
|
||||
return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
if setPolicy {
|
||||
p := chunkstore.RetentionPolicy{KeepNewest: keepNewest, KeepYoungerNs: int64(keepYounger), KeepHourly: keepHourly, KeepDaily: keepDaily, KeepWeekly: keepWeekly}
|
||||
if err := cat.SetRetentionPolicy(ctx, volumeID, p); err != nil {
|
||||
return chunkResult("retain", nil, err, stdout, stderr)
|
||||
}
|
||||
return chunkResult("retain", map[string]any{"volumeID": volumeID, "policy": p, "policySet": true}, nil, stdout, stderr)
|
||||
}
|
||||
res, err := cat.Retain(ctx, volumeID, dryRun)
|
||||
if err != nil && res.VolumeID != "" {
|
||||
// The pass stopped part way: report what it did (confirmed
|
||||
// deletions, the failing snapshot with whether its outcome is
|
||||
// uncertain, what it never reached) with the error, and fail.
|
||||
return retainPartial(res, err, stdout, stderr)
|
||||
}
|
||||
return chunkResult("retain", res, err, stdout, stderr)
|
||||
}
|
||||
|
||||
// retainOutput is a retention result together with the error that
|
||||
// stopped it.
|
||||
type retainOutput struct {
|
||||
chunkstore.RetentionResult
|
||||
Error *chunkErrBody `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func retainPartial(res chunkstore.RetentionResult, err error, stdout, stderr io.Writer) int {
|
||||
body := chunkErrBody{Code: chunkstore.CodeOf(err), Message: err.Error(), Retryable: true}
|
||||
var ce *chunkstore.CatalogError
|
||||
if errors.As(err, &ce) {
|
||||
body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable}
|
||||
}
|
||||
if body.Code == "" {
|
||||
body.Code = codeInternalCLI
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk retain: %s: %s (deleted %d, not attempted %d)\n", body.Code, body.Message, len(res.Deleted), len(res.NotAttempted))
|
||||
out, mErr := json.Marshal(retainOutput{RetentionResult: res, Error: &body})
|
||||
if mErr != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk retain: %v\n", mErr)
|
||||
return chunkExitFailed
|
||||
}
|
||||
if wErr := writeAll(stdout, append(out, '\n')); wErr != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk retain: write the result: %v\n", wErr)
|
||||
}
|
||||
return chunkExitFailed
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// failingFiler fails the UpdateEntry calls fail picks, after or before
|
||||
// applying them.
|
||||
type failingFiler struct {
|
||||
*chunkstore.MemFiler
|
||||
fail func(dir, name string) bool
|
||||
afterApply bool
|
||||
}
|
||||
|
||||
func (f *failingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
if f.fail != nil && f.fail(dir, e.GetName()) {
|
||||
if f.afterApply {
|
||||
if err := f.MemFiler.UpdateEntry(ctx, dir, e, expected); err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.New("response lost")
|
||||
}
|
||||
return errors.New("filer unavailable")
|
||||
}
|
||||
return f.MemFiler.UpdateEntry(ctx, dir, e, expected)
|
||||
}
|
||||
|
||||
// retain that fails part way prints what it confirmed, the failing
|
||||
// snapshot (uncertain) and what it never reached, with the error, and
|
||||
// exits nonzero; a lost response is finished by the next run.
|
||||
func TestOpsChunk_RetainReportsPartialProgress(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ff := &failingFiler{MemFiler: chunkstore.NewMemFiler()}
|
||||
fm := newManifestFixtureFiler(ff)
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return fm, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(fm, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := time.Now().Add(-48 * time.Hour)
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, fm, head)
|
||||
for i := 0; i < 4; i++ {
|
||||
at := base.Add(time.Duration(i) * time.Minute)
|
||||
cat.SetClock(func() time.Time { return at })
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i)}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"}
|
||||
if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "0", "--keep-younger", "0s"}, filer...)...); code != 0 {
|
||||
t.Fatalf("set policy: %d %q %q", code, out, errs)
|
||||
}
|
||||
// Expired newest first: s3, s2, s1, s0. The mark of s2 fails.
|
||||
ff.fail = func(dir, _ string) bool { return strings.HasSuffix(dir, "/snaps/s2") }
|
||||
type partial struct {
|
||||
chunkstore.RetentionResult
|
||||
Error *chunkErrBody `json:"error"`
|
||||
}
|
||||
code, out, errs := runChunk(append([]string{"retain"}, filer...)...)
|
||||
var p partial
|
||||
if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Error == nil || p.Failed == nil {
|
||||
t.Fatalf("failing retain: exit %d %q %q; want nonzero with the partial result", code, out, errs)
|
||||
}
|
||||
if strings.Join(p.Deleted, ",") != "s3" || p.Failed.Name != "s2" || !p.Failed.Uncertain || strings.Join(p.NotAttempted, ",") != "s1,s0" {
|
||||
t.Fatalf("partial result: %+v", p)
|
||||
}
|
||||
if !strings.Contains(errs, "deleted 1, not attempted 2") {
|
||||
t.Fatalf("stderr %q; want the counts", errs)
|
||||
}
|
||||
|
||||
ff.afterApply = true // the mark lands, its response is lost
|
||||
code, out, _ = runChunk(append([]string{"retain"}, filer...)...)
|
||||
if code == 0 || json.Unmarshal([]byte(out), &p) != nil || p.Failed == nil || p.Failed.Name != "s2" || !p.Failed.Uncertain {
|
||||
t.Fatalf("lost response: exit %d %q", code, out)
|
||||
}
|
||||
ff.fail = nil
|
||||
code, out, errs = runChunk(append([]string{"retain"}, filer...)...)
|
||||
var done chunkstore.RetentionResult
|
||||
if code != 0 || json.Unmarshal([]byte(out), &done) != nil || strings.Join(done.Deleted, ",") != "s1,s0,s2" {
|
||||
t.Fatalf("rerun: %d %q %q; want s1, s0 and the half-deleted s2", code, out, errs)
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// snapshot --pin / --class / --expires send the retention class and the
|
||||
// expiry; conflicting flags are refused before any request.
|
||||
func TestOpsChunk_SnapshotPinAndExpires(t *testing.T) {
|
||||
srv, got := chunkServer(t, 200, `{"volumeID":"v1","name":"s1"}`)
|
||||
before := time.Now()
|
||||
if code, _, errs := runChunk("snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s1", "--request-id", "r", "--pin", "--expires", "1h"); code != 0 {
|
||||
t.Fatalf("snapshot --pin --expires: %d %q", code, errs)
|
||||
}
|
||||
body := (*got)[0].body
|
||||
exp, _ := body["expiresAtNs"].(float64)
|
||||
if body["class"] != chunkstore.SnapshotClassPinned || exp < float64(before.Add(time.Hour).UnixNano())-1e9 {
|
||||
t.Fatalf("pinned request: %+v", body)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"--pin", "--class", "semantic"},
|
||||
{"--expires", "1h", "--expires-at-ns", "5"},
|
||||
{"--expires", "-1s"},
|
||||
} {
|
||||
a := append([]string{"snapshot", "--volume", "v1", "--status-addr", srv.URL, "--name", "s2"}, args...)
|
||||
if code, out, _ := runChunk(a...); code == 0 || !strings.Contains(out, codeBadRequestCLI) {
|
||||
t.Fatalf("snapshot %v: exit %d %q; want a bad request", args, code, out)
|
||||
}
|
||||
}
|
||||
if len(*got) != 1 {
|
||||
t.Fatalf("refused flags still sent requests: %d", len(*got))
|
||||
}
|
||||
}
|
||||
|
||||
// usage and retain run catalog-direct against the filer: set a policy,
|
||||
// dry-run, apply, and see the accounting follow.
|
||||
func TestOpsChunk_UsageAndRetain(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := newManifestFixtureFiler(chunkstore.NewMemFiler())
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := time.Now().Add(-48 * time.Hour)
|
||||
cat.SetClock(func() time.Time { return old })
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, mem, head)
|
||||
for i := 0; i < 5; i++ {
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: fmt.Sprintf("s%d", i), RequestID: fmt.Sprintf("r%d", i), Class: chunkstore.SnapshotClassSemantic}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"}
|
||||
if code, out, errs := runChunk(append([]string{"retain", "--set-policy", "--keep-newest", "2", "--keep-younger", "1m"}, filer...)...); code != 0 || !strings.Contains(out, `"policySet":true`) {
|
||||
t.Fatalf("set policy: %d %q %q", code, out, errs)
|
||||
}
|
||||
code, out, errs := runChunk(append([]string{"retain", "--dry-run"}, filer...)...)
|
||||
var dry chunkstore.RetentionResult
|
||||
if code != 0 || json.Unmarshal([]byte(out), &dry) != nil || !dry.DryRun || dry.Expired != 3 || len(dry.Deleted) != 0 {
|
||||
t.Fatalf("dry run: %d %q %q", code, out, errs)
|
||||
}
|
||||
code, out, errs = runChunk(append([]string{"retain"}, filer...)...)
|
||||
var applied chunkstore.RetentionResult
|
||||
if code != 0 || json.Unmarshal([]byte(out), &applied) != nil || len(applied.Deleted) != 3 || applied.Kept != 2 {
|
||||
t.Fatalf("retain: %d %q %q", code, out, errs)
|
||||
}
|
||||
code, out, errs = runChunk(append([]string{"usage"}, filer...)...)
|
||||
var u chunkstore.VolumeUsage
|
||||
if code != 0 || json.Unmarshal([]byte(out), &u) != nil || len(u.Snapshots) != 2 || u.Policy.KeepNewest != 2 || !u.PolicySet {
|
||||
t.Fatalf("usage: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, _ := runChunk("retain", "--volume", "v1", "--chunk-filer", "f:1", "--set-policy", "--dry-run"); code == 0 || !strings.Contains(out, codeBadRequestCLI) {
|
||||
t.Fatalf("--set-policy --dry-run: %d %q; want a bad request", code, out)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// ops chunk show prints a volume's VOLUME entry and HEAD from the filer;
|
||||
// either is null when it does not exist (B9 W2 appendix).
|
||||
func TestOpsChunk_Show(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := newManifestFixtureFiler(chunkstore.NewMemFiler())
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", geo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "s1/r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
head = prepareFixtureHead(t, mem, head)
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.Fork(ctx, chunkstore.ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
show := func(vol string) chunkstore.VolumeShowBody {
|
||||
t.Helper()
|
||||
code, out, errs := runChunk("show", "--volume", vol, "--chunk-filer", "f:1")
|
||||
var b chunkstore.VolumeShowBody
|
||||
if code != 0 || json.Unmarshal([]byte(out), &b) != nil {
|
||||
t.Fatalf("show %s: %d %q %q", vol, code, out, errs)
|
||||
}
|
||||
return b
|
||||
}
|
||||
fork := show("v2")
|
||||
if fork.Volume == nil || fork.Volume.Origin != chunkstore.OriginFork || fork.Volume.NumBlocks != 64 || fork.Volume.Parent == nil ||
|
||||
fork.Volume.Parent.VolumeID != "v1" || fork.Volume.Parent.Snapshot != "s1" {
|
||||
t.Fatalf("show v2 VOLUME: %+v", fork.Volume)
|
||||
}
|
||||
if fork.Head == nil || fork.Head.Gen != 1 || fork.Head.Epoch != 0 || fork.Head.RemoteLSN != 42 || fork.Head.State != "active" ||
|
||||
fork.Head.ChunkCount != 1 || fork.Head.DetachedBy != nil {
|
||||
t.Fatalf("show v2 HEAD: %+v", fork.Head)
|
||||
}
|
||||
// A created volume carries its initial HEAD (gen 1, epoch 0, no chunks).
|
||||
if src := show("v1"); src.Volume == nil || src.Volume.Origin != chunkstore.OriginCreate || src.Head == nil || src.Head.Gen != 1 ||
|
||||
src.Head.Epoch != 0 || src.Head.RemoteLSN != 0 || src.Head.ChunkCount != 0 || src.Head.State != "active" {
|
||||
t.Fatalf("show v1 (VOLUME and its initial HEAD): %+v %+v", src.Volume, src.Head)
|
||||
}
|
||||
if none := show("v9"); none.Volume != nil || none.Head != nil || none.VolumeID != "v9" {
|
||||
t.Fatalf("show of a volume that does not exist: %+v", none)
|
||||
}
|
||||
if code, out, _ := runChunk("show", "--chunk-filer", "f:1"); code != 2 || chunkErrorOut(t, out).Code != "bad_request" {
|
||||
t.Fatalf("show without --volume: exit %d %q", code, out)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,10 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Every ops chunk command that writes chunk metadata runs the
|
||||
@@ -15,10 +19,16 @@ import (
|
||||
// when the filer is not the only one of its group; read-only commands (and
|
||||
// read-only modes) do not run it.
|
||||
func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) {
|
||||
mem := chunkstore.NewMemFiler()
|
||||
mem := newMemChunkStore()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
prevResolve := resolveVolumeID
|
||||
t.Cleanup(func() { resolveVolumeID = prevResolve })
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil }
|
||||
id := []string{"--master", "m:1"}
|
||||
src := []string{"--source", "v1", "--master", "m:1"}
|
||||
tgt := []string{"--target", "v2"}
|
||||
checks := 0
|
||||
checkSingleFiler = func(context.Context, chunkstore.Filer) error {
|
||||
checks++
|
||||
@@ -26,11 +36,10 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) {
|
||||
}
|
||||
filer := []string{"--chunk-filer", "filer:18888"}
|
||||
writing := map[string][]string{
|
||||
"snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...),
|
||||
"fork": append([]string{"ops", "chunk", "fork", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "r"}, filer...),
|
||||
"retain": append([]string{"ops", "chunk", "retain", "--volume", "v1"}, filer...),
|
||||
"volume-delete": append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, filer...),
|
||||
"gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...),
|
||||
"snapshot-delete": append(append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, id...), filer...),
|
||||
"release": append(append(append([]string{"ops", "chunk", "release"}, src...), tgt...), filer...),
|
||||
"retain": append(append([]string{"ops", "chunk", "retain", "--volume", "v1"}, id...), filer...),
|
||||
"volume-delete": append(append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, id...), filer...),
|
||||
}
|
||||
for name, args := range writing {
|
||||
before := checks
|
||||
@@ -44,11 +53,10 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
readOnly := map[string][]string{
|
||||
"snapshots": append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, filer...),
|
||||
"show": append([]string{"ops", "chunk", "show", "--volume", "v1"}, filer...),
|
||||
"usage": append([]string{"ops", "chunk", "usage", "--volume", "v1"}, filer...),
|
||||
"retain --dry-run": append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, filer...),
|
||||
"gc (read-only)": append([]string{"ops", "chunk", "gc", "--master", "m:1"}, filer...),
|
||||
"snapshots": append(append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, id...), filer...),
|
||||
"show": append(append([]string{"ops", "chunk", "show", "--volume", "v1"}, id...), filer...),
|
||||
"usage": append(append([]string{"ops", "chunk", "usage", "--volume", "v1"}, id...), filer...),
|
||||
"retain --dry-run": append(append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, id...), filer...),
|
||||
}
|
||||
for name, args := range readOnly {
|
||||
before := checks
|
||||
@@ -60,13 +68,57 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Restore has one master authority call. The master owns the filer check
|
||||
// and target creation; the CLI must never write the filer independently.
|
||||
func TestOpsChunkRestoreUsesOnlyMasterCreate(t *testing.T) {
|
||||
prevDial, prevRestore := dialChunkFiler, restoreCreateRPC
|
||||
t.Cleanup(func() { dialChunkFiler, restoreCreateRPC = prevDial, prevRestore })
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
t.Fatal("restore CLI contacted the filer")
|
||||
return nil, nil, nil
|
||||
}
|
||||
calls := 0
|
||||
var firstID string
|
||||
restoreCreateRPC = func(_ context.Context, master string, req *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
calls++
|
||||
if master != "m:1" || req.GetVolumeId() != "v2" || req.GetSourceVolume() != "v1" || req.GetSourceSnapshot() != "s1" || req.GetCreateRequestId() == "" {
|
||||
t.Fatalf("restore RPC: master=%q req=%+v", master, req)
|
||||
}
|
||||
if firstID == "" {
|
||||
firstID = req.GetCreateRequestId()
|
||||
}
|
||||
if req.GetCreateRequestId() != firstID {
|
||||
t.Fatal("retry changed request id")
|
||||
}
|
||||
return &control.CreateVolumeResponse{VolumeId: "v2", LayoutId: (layout.VolumeID{1}).String(), StoreReady: true}, nil
|
||||
}
|
||||
args := []string{"ops", "chunk", "restore", "--master", "m:1", "--source", "v1", "--target", "v2", "--snapshot", "s1"}
|
||||
for i := 0; i < 2; i++ {
|
||||
var out, errs bytes.Buffer
|
||||
if code := run(args, &out, &errs); code != 0 {
|
||||
t.Fatalf("restore replay: code=%d out=%q err=%q", code, out.String(), errs.String())
|
||||
}
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("restore made %d RPCs; want one per invocation", calls)
|
||||
}
|
||||
restoreCreateRPC = func(context.Context, string, *control.CreateVolumeRequest) (*control.CreateVolumeResponse, error) {
|
||||
return nil, status.Error(codes.Unavailable, "filer unreachable")
|
||||
}
|
||||
var out, errs bytes.Buffer
|
||||
if code := run(args, &out, &errs); code != chunkExitFailed || !strings.Contains(out.String(), `"retryable":true`) || !strings.Contains(out.String(), codeUnavailableCLI) {
|
||||
t.Fatalf("uncertain restore must be retryable: code=%d out=%q err=%q", code, out.String(), errs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The start check runs within the command's own --timeout: a check stalled
|
||||
// on its filer or master (here one that blocks until its context ends) ends
|
||||
// the command at the timeout, as a retryable refusal.
|
||||
func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) {
|
||||
mem := chunkstore.NewMemFiler()
|
||||
prevDial, prevCheck := dialChunkFiler, checkSingleFiler
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck })
|
||||
prevDial, prevCheck, prevResolve := dialChunkFiler, checkSingleFiler, resolveVolumeID
|
||||
t.Cleanup(func() { dialChunkFiler, checkSingleFiler, resolveVolumeID = prevDial, prevCheck, prevResolve })
|
||||
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return layout.VolumeID{1}, nil }
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error {
|
||||
<-ctx.Done()
|
||||
@@ -74,8 +126,7 @@ func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) {
|
||||
}
|
||||
filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"}
|
||||
for name, args := range map[string][]string{
|
||||
"snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...),
|
||||
"gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...),
|
||||
"snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--master", "m:1", "--name", "s1"}, filer...),
|
||||
} {
|
||||
done := make(chan struct{})
|
||||
var out, errb bytes.Buffer
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -12,7 +11,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
type chunkRoute struct {
|
||||
@@ -130,71 +129,13 @@ func TestOpsChunk_ErrorsAreJSONOnStdout(t *testing.T) {
|
||||
t.Fatalf("unreachable blockvolume: %+v, want remote_unavailable and retryable", e)
|
||||
}
|
||||
|
||||
mem := chunkstore.NewMemFiler()
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
if code, out, _ := runChunk("fork", "--chunk-filer", "f:1", "--source", "v1", "--snapshot", "s9", "--target", "v2", "--request-id", "r"); code != chunkExitFailed {
|
||||
t.Fatalf("fork of a missing snapshot: exit %d %q", code, out)
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
src := cliVolume(t, store, "v1", "s1")
|
||||
tid, _ := layout.NewVolumeID()
|
||||
if code, out, _ := runChunk(cliArgs("restore", volArgs("source", src), volArgs("target", chunkstore.VolumeRef{Name: "v2", ID: tid}), []string{"--snapshot", "s9"})...); code != chunkExitFailed {
|
||||
t.Fatalf("restore of a missing snapshot: exit %d %q", code, out)
|
||||
} else if e := chunkErrorOut(t, out); e.Code != "snapshot_not_found" || e.Retryable {
|
||||
t.Fatalf("fork of a missing snapshot: %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
// snapshots, snapshot-delete and fork go to the filer directly.
|
||||
func TestOpsChunk_FilerCommands(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := chunkstore.NewMemFiler()
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := storage.ChunkHead{Gen: 2, Epoch: 1, Holder: "r1", RemoteLSN: 42, State: storage.ChunkHeadActive,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e1/c0/k"}}}
|
||||
manifestMem := newManifestFixtureFiler(mem)
|
||||
cat, err = chunkstore.NewCatalog(manifestMem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return manifestMem, func() error { return nil }, nil
|
||||
}
|
||||
head = prepareFixtureHead(t, manifestMem, head)
|
||||
if _, err := cat.CreateSnapshot(ctx, "v1", chunkstore.SnapshotRequest{Name: "s1", RequestID: "r"}, head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
code, out, errs := runChunk("snapshots", "--volume", "v1", "--chunk-filer", "filer:18888")
|
||||
var list chunkstore.SnapshotListBody
|
||||
if code != 0 || json.Unmarshal([]byte(out), &list) != nil || len(list.Snapshots) != 1 || list.Snapshots[0].Name != "s1" || list.Snapshots[0].CutLSN != 42 {
|
||||
t.Fatalf("snapshots: %d %q %q", code, out, errs)
|
||||
}
|
||||
code, out, errs = runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1")
|
||||
var fork chunkstore.ForkResult
|
||||
if code != 0 || json.Unmarshal([]byte(out), &fork) != nil || fork.Target != "v2" || fork.HeadGen != 1 || fork.RemoteLSN != 42 || fork.Replayed ||
|
||||
!strings.Contains(out, `"remoteLSN":42`) {
|
||||
t.Fatalf("fork: %d %q %q", code, out, errs)
|
||||
}
|
||||
if code, out, _ := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "f1"); code != 0 || !strings.Contains(out, `"replayed":true`) {
|
||||
t.Fatalf("fork retry: %d %q", code, out)
|
||||
}
|
||||
if code, _, errs := runChunk("fork", "--chunk-filer", "filer:18888", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "other"); code != chunkExitFailed || !strings.Contains(errs, "target_exists") {
|
||||
t.Fatalf("fork with another request id: %d %q", code, errs)
|
||||
}
|
||||
// The first delete frees the name; a repeated one finds it absent.
|
||||
for i, want := range []string{`"state":"deleting"`, `"state":"absent"`} {
|
||||
code, out, errs = runChunk("snapshot-delete", "--volume", "v1", "--name", "s1", "--chunk-filer", "filer:18888")
|
||||
if code != 0 || !strings.Contains(out, want) {
|
||||
t.Fatalf("snapshot-delete #%d: %d %q %q, want %s", i+1, code, out, errs, want)
|
||||
}
|
||||
}
|
||||
if code, _, _ := runChunk("snapshots", "--volume", "v1"); code != 2 {
|
||||
t.Fatalf("snapshots without --chunk-filer: exit %d, want 2", code)
|
||||
t.Fatalf("restore of a missing snapshot: %+v", e)
|
||||
}
|
||||
}
|
||||
@@ -11,19 +11,22 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
)
|
||||
|
||||
// chunkVerify: sw-block ops chunk verify --volume v --chunk-filer host:port
|
||||
// checks the volume's remote image against its HEAD (and, on request, its
|
||||
// snapshots), read-only (chunkstore.Catalog.Verify). Exit 0: clean; 3: the
|
||||
// pass completed with findings; 1: it could not complete (the partial result
|
||||
// is printed with the error); 2: usage.
|
||||
// checks the volume's store read-only: VOLUME, HEAD, every root HEAD names
|
||||
// (the current image and every snapshot), their segments and chunks
|
||||
// (chunkstore.VerifyLayout). --orphans also reports the volume's own names
|
||||
// that no reachable root names (it never deletes them). Exit 0: clean; 3:
|
||||
// the pass completed with findings; 1: it could not complete (the partial
|
||||
// result is printed with the reason); 2: usage.
|
||||
func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("verify", stderr)
|
||||
var (
|
||||
volumeID, filer, base, snapshot, depth string
|
||||
allSnapshots bool
|
||||
allSnapshots, orphans bool
|
||||
concurrency int
|
||||
bytesPerSec int64
|
||||
timeout time.Duration
|
||||
@@ -31,11 +34,12 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.StringVar(&snapshot, "snapshot", "", "also check this snapshot")
|
||||
fs.BoolVar(&allSnapshots, "all-snapshots", false, "also check every snapshot")
|
||||
fs.StringVar(&depth, "depth", string(chunkstore.VerifyBindings), "meta, bindings or data (data reads every chunk once)")
|
||||
fs.IntVar(&concurrency, "concurrency", chunkstore.DefaultVerifyConcurrency, "chunk reads in flight (depth data)")
|
||||
fs.Int64Var(&bytesPerSec, "bytes-per-sec", chunkstore.DefaultVerifyBytesPerSecond, "pace chunk reads (depth data); 0 leaves them unpaced")
|
||||
fs.StringVar(&snapshot, "snapshot", "", "accepted for compatibility: every snapshot HEAD names is always checked")
|
||||
fs.BoolVar(&allSnapshots, "all-snapshots", false, "accepted for compatibility: every snapshot HEAD names is always checked")
|
||||
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name")
|
||||
fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)")
|
||||
fs.IntVar(&concurrency, "concurrency", 1, "accepted for compatibility: chunks are read one at a time")
|
||||
fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "accepted for compatibility: chunk reads are not paced")
|
||||
fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
@@ -49,37 +53,37 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
usage := func(msg string) int {
|
||||
return chunkFail("verify", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, msg, false)
|
||||
}
|
||||
d := chunkstore.VerifyDepth(depth)
|
||||
d := map[string]string{"meta": layout.DepthNames, "bindings": layout.DepthNames, "data": layout.DepthFull}[depth]
|
||||
switch {
|
||||
case fs.NArg() != 0:
|
||||
return usage("unexpected arguments")
|
||||
case volumeID == "":
|
||||
return usage("--volume is required")
|
||||
case d != chunkstore.VerifyMeta && d != chunkstore.VerifyBindings && d != chunkstore.VerifyData:
|
||||
case filer == "":
|
||||
return usage("--chunk-filer is required")
|
||||
case d == "":
|
||||
return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth))
|
||||
case snapshot != "" && allSnapshots:
|
||||
return usage("--snapshot and --all-snapshots do not combine")
|
||||
case d == chunkstore.VerifyData && !timeoutSet:
|
||||
case d == layout.DepthFull && !timeoutSet:
|
||||
return usage("--depth data reads every chunk: give an explicit --timeout for the pass")
|
||||
case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0:
|
||||
return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative")
|
||||
}
|
||||
// One bound for the whole pass, the single-filer start check included:
|
||||
// the deadline starts before the check. Verify writes nothing, but it
|
||||
// runs the check (writes=true): against a split filer view it would
|
||||
// report false findings.
|
||||
// One bound for the whole pass, the single-filer start check included.
|
||||
// Verify writes nothing, but against a split filer view it would report
|
||||
// false findings, so it runs the check.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
cat, closeFn, exit := chunkCatalog("verify", filer, base, true, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
f, closeFn, err := dialChunkFiler(filer)
|
||||
if err != nil {
|
||||
return usage(err.Error())
|
||||
}
|
||||
defer closeFn()
|
||||
if bytesPerSec == 0 {
|
||||
bytesPerSec = -1 // the library's "unpaced"
|
||||
if exit := refuseUnlessSingleFiler("verify", f, timeout, stdout, stderr); exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
res, err := cat.Verify(ctx, volumeID, chunkstore.VerifyOptions{Depth: d, Snapshot: snapshot, AllSnapshots: allSnapshots,
|
||||
Concurrency: concurrency, BytesPerSecond: bytesPerSec})
|
||||
res, err := chunkstore.VerifyLayout(ctx, f, base, volumeID, layout.VerifyOptions{Depth: d, Orphans: orphans})
|
||||
if err != nil {
|
||||
return verifyIncomplete(res, err, stdout, stderr)
|
||||
}
|
||||
@@ -92,12 +96,12 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: write the result: %v\n", err)
|
||||
return chunkExitFailed
|
||||
}
|
||||
if !res.Complete {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: incomplete: %s\n", volumeID, res.Incomplete)
|
||||
return chunkExitFailed
|
||||
}
|
||||
if len(res.Findings) != 0 {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings %v\n", volumeID, len(res.Findings), res.FindingsByClass)
|
||||
if res.ChunksNotRead != 0 {
|
||||
// READ_ERROR is not damage: those objects were not verified.
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d could not be read and were not verified; re-run\n", volumeID, res.ChunksNotRead)
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %d findings\n", volumeID, len(res.Findings))
|
||||
return chunkExitFindings
|
||||
}
|
||||
return ops.VolumeStatusExitOK
|
||||
@@ -105,20 +109,20 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
|
||||
|
||||
// verifyJSON is the result as one JSON object whose findings array holds
|
||||
// one finding per line.
|
||||
func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) {
|
||||
func verifyJSON(res layout.VerifyResult) ([]byte, error) {
|
||||
findings := res.Findings
|
||||
res.Findings = nil
|
||||
head, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
const tail = `"findings":null}`
|
||||
const tail = `"Findings":null}`
|
||||
if !bytes.HasSuffix(head, []byte(tail)) {
|
||||
return nil, errors.New("verify result: unexpected field order")
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
buf.Write(head[:len(head)-len(tail)])
|
||||
buf.WriteString(`"findings":[`)
|
||||
buf.WriteString(`"Findings":[`)
|
||||
for i, f := range findings {
|
||||
line, err := json.Marshal(f)
|
||||
if err != nil {
|
||||
@@ -139,17 +143,13 @@ func verifyJSON(res chunkstore.VerifyResult) ([]byte, error) {
|
||||
|
||||
// verifyIncomplete prints the error body with the partial result under
|
||||
// "verify", and fails.
|
||||
func verifyIncomplete(res chunkstore.VerifyResult, err error, stdout, stderr io.Writer) int {
|
||||
func verifyIncomplete(res layout.VerifyResult, err error, stdout, stderr io.Writer) int {
|
||||
body := struct {
|
||||
chunkErrBody
|
||||
Verify chunkstore.VerifyResult `json:"verify"`
|
||||
Verify layout.VerifyResult `json:"verify"`
|
||||
}{Verify: res}
|
||||
body.Code, body.Message = codeInternalCLI, err.Error()
|
||||
var ce *chunkstore.CatalogError
|
||||
switch {
|
||||
case errors.As(err, &ce):
|
||||
body.Code, body.Message, body.Retryable = ce.Code, ce.Detail(), ce.Retryable
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
body.Code, body.Retryable = chunkstore.CodeDeadlineExceeded, true
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk verify: %s: %s (incomplete)\n", body.Code, body.Message)
|
||||
|
||||
@@ -3,22 +3,22 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// verifyCLIFixture is volume v1 with two published chunks on an in-memory
|
||||
// filer and blob store; it returns the store and the HEAD.
|
||||
func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) {
|
||||
// verifyCLIFixture is volume v1 on the content-named layout (VOLUME, HEAD,
|
||||
// one root naming chunks 0 and 1) on an in-memory filer and blob store; it
|
||||
// returns the store and chunk 1's pool path.
|
||||
func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
mem := newManifestFixtureFiler(chunkstore.NewMemFiler())
|
||||
@@ -27,49 +27,55 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, storage.ChunkHead) {
|
||||
return mem, func() error { return nil }, nil
|
||||
}
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
root := path.Join(defaultChunkPathCLI, "v1")
|
||||
put := func(rel string, b []byte) {
|
||||
p := path.Join(root, rel)
|
||||
if err := mem.CreateEntry(ctx, path.Dir(p), &filerpb.Entry{Name: path.Base(p), Content: b}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := chunkstore.NewChunkRemote(mem, mem, defaultChunkPathCLI+"/v1")
|
||||
vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
put(layout.VolumeName, vb)
|
||||
manifest := map[uint64]layout.Ref{}
|
||||
var last string
|
||||
for idx := uint64(0); idx < 2; idx++ {
|
||||
data := bytes.Repeat([]byte{byte(0x30 + idx)}, 8*4096)
|
||||
key := fmt.Sprintf("chunks/e1/c%d/k", idx)
|
||||
if err := r.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
|
||||
data := bytes.Repeat([]byte{byte(0x30 + idx)}, 4096)
|
||||
c := layout.NameChunk(idx, data)
|
||||
put(c.Path(), data)
|
||||
manifest[idx] = layout.Ref{Owner: "v1", OwnerID: id, Chunk: c}
|
||||
last = c.Path()
|
||||
}
|
||||
h, ids, err := r.PrepareManifest(ctx, cur, h, 8*4096)
|
||||
r, segs, err := layout.Build(manifest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h); err != nil {
|
||||
for n, b := range segs {
|
||||
put(n.Path(), b)
|
||||
}
|
||||
rn, rb, err := layout.NameRoot(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put(rn.Path(), rb)
|
||||
hb, err := layout.Head{VolumeID: id, Epoch: 1, Holder: "s/r", ClaimID: "c", Activity: layout.Activity{Kind: layout.ActIdle}, Current: &rn}.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return mem, h
|
||||
put(layout.HeadName, hb)
|
||||
return mem, path.Join(root, last)
|
||||
}
|
||||
|
||||
func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult {
|
||||
func decodeVerify(t *testing.T, out string) layout.VerifyResult {
|
||||
t.Helper()
|
||||
var res chunkstore.VerifyResult
|
||||
if err := json.Unmarshal([]byte(out), &res); err != nil || res.VolumeID == "" {
|
||||
var res layout.VerifyResult
|
||||
if err := json.Unmarshal([]byte(out), &res); err != nil {
|
||||
t.Fatalf("stdout is not a verify result: %q (%v)", out, err)
|
||||
}
|
||||
return res
|
||||
@@ -78,41 +84,38 @@ func decodeVerify(t *testing.T, out string) chunkstore.VerifyResult {
|
||||
// verify's exit codes: 0 clean, 3 completed with findings, 1 could not
|
||||
// complete, 2 usage; the result is one JSON object with one finding per line.
|
||||
func TestOpsChunk_VerifyExitCodes(t *testing.T) {
|
||||
mem, h := verifyCLIFixture(t)
|
||||
mem, chunk1 := verifyCLIFixture(t)
|
||||
filer := []string{"--volume", "v1", "--chunk-filer", "filer:18888"}
|
||||
|
||||
code, out, errs := runChunk(append([]string{"verify"}, filer...)...)
|
||||
res := decodeVerify(t, out)
|
||||
if code != 0 || !res.Complete || res.Depth != chunkstore.VerifyBindings || len(res.Findings) != 0 || res.ChunksChecked != 2 ||
|
||||
!strings.Contains(out, `"findings":[]`) || len(res.HeadGens) != 1 || res.HeadGens[0] != h.Gen {
|
||||
if code != 0 || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 || res.Roots != 1 || !strings.Contains(out, `"Findings":[]`) {
|
||||
t.Fatalf("clean verify: %d %q %q", code, out, errs)
|
||||
}
|
||||
code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--bytes-per-sec", "0"}, filer...)...)
|
||||
if res = decodeVerify(t, out); code != 0 || res.DistinctChunksRead != 2 || res.BytesRead != 2*8*4096 {
|
||||
code, out, errs = runChunk(append([]string{"verify", "--depth", "data", "--timeout", "10s", "--orphans"}, filer...)...)
|
||||
if res = decodeVerify(t, out); code != 0 || !res.Complete || len(res.Findings) != 0 || !res.OrphansChecked {
|
||||
t.Fatalf("clean data verify: %d %q %q", code, out, errs)
|
||||
}
|
||||
|
||||
// A binding gone: completed with a finding.
|
||||
own := strings.TrimPrefix(h.Chunks[1].Key, "@v1/")
|
||||
if err := mem.DeleteEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own), nil); err != nil {
|
||||
// A chunk gone: completed with a finding.
|
||||
if err := mem.DeleteEntry(context.Background(), path.Dir(chunk1), path.Base(chunk1), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, out, errs = runChunk(append([]string{"verify"}, filer...)...)
|
||||
res = decodeVerify(t, out)
|
||||
if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingBindingMissing ||
|
||||
res.FindingsByClass[chunkstore.FindingBindingMissing] != 1 || !strings.Contains(errs, "1 findings") {
|
||||
t.Fatalf("verify with a missing binding: %d %q %q", code, out, errs)
|
||||
if chunkExitFindings != 3 || code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 ||
|
||||
res.Findings[0].Class != layout.FindMissing || !strings.Contains(errs, "1 findings") {
|
||||
t.Fatalf("verify with a missing chunk: %d %q %q", code, out, errs)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(out), "\n")
|
||||
if len(lines) != 3 || !strings.HasPrefix(lines[1], `{"volume":"v1"`) || !strings.Contains(lines[1], `"class":"BINDING_MISSING"`) || lines[2] != "]}" {
|
||||
if len(lines) != 3 || !strings.Contains(lines[1], `"Class":"MISSING"`) || lines[2] != "]}" {
|
||||
t.Fatalf("findings are not one per line:\n%s", out)
|
||||
}
|
||||
|
||||
// Could not complete: the error body, with what was covered.
|
||||
code, out, _ = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888")
|
||||
if e := chunkErrorOut(t, out); code != chunkExitFailed || e.Code != chunkstore.CodeNotChunkVolume || !strings.Contains(out, `"verify":{`) ||
|
||||
!strings.Contains(out, `"incomplete":"error"`) {
|
||||
t.Fatalf("verify of a missing volume: %d %q", code, out)
|
||||
// Could not complete: a volume without VOLUME/HEAD.
|
||||
code, out, errs = runChunk("verify", "--volume", "nope", "--chunk-filer", "filer:18888")
|
||||
if res = decodeVerify(t, out); code != chunkExitFailed || res.Complete || !strings.Contains(errs, "incomplete") {
|
||||
t.Fatalf("verify of a missing volume: %d %q %q", code, out, errs)
|
||||
}
|
||||
|
||||
for _, args := range [][]string{
|
||||
@@ -136,37 +139,30 @@ func TestOpsChunk_VerifyExitCodes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// unreadableStore fails every read of one needle with an error that is not
|
||||
// "not found" (a volume server answering 503).
|
||||
// unreadableStore fails every read of one path with an error that is not
|
||||
// "not found" (a filer answering 503).
|
||||
type unreadableStore struct {
|
||||
*manifestFixtureFiler
|
||||
fid string
|
||||
bad string
|
||||
}
|
||||
|
||||
func (s unreadableStore) Get(ctx context.Context, fid string) ([]byte, error) {
|
||||
if fid == s.fid {
|
||||
return nil, fmt.Errorf("chunkstore: read %s: http 503 from volume:8080", fid)
|
||||
func (s unreadableStore) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if path.Join(dir, name) == s.bad {
|
||||
return nil, fmt.Errorf("filer: lookup %s: unavailable (503)", s.bad)
|
||||
}
|
||||
return s.manifestFixtureFiler.Get(ctx, fid)
|
||||
return s.manifestFixtureFiler.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
// A chunk that cannot be read is READ_ERROR (not verified), and the pass
|
||||
// exits 3: it did not verify everything.
|
||||
func TestOpsChunk_VerifyReadErrorExits3(t *testing.T) {
|
||||
mem, h := verifyCLIFixture(t)
|
||||
own := strings.TrimPrefix(h.Chunks[0].Key, "@v1/")
|
||||
e, err := mem.LookupEntry(context.Background(), path.Join(defaultChunkPathCLI, "v1", "keys"), url.PathEscape(own))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := unreadableStore{mem, string(e.Extended["swb.fid"])}
|
||||
// A chunk that cannot be read is not judged: the pass could not complete
|
||||
// (exit 1) and says why.
|
||||
func TestOpsChunk_VerifyReadErrorIsIncomplete(t *testing.T) {
|
||||
mem, chunk1 := verifyCLIFixture(t)
|
||||
store := unreadableStore{mem, chunk1}
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
|
||||
return store, func() error { return nil }, nil
|
||||
}
|
||||
code, out, errs := runChunk("verify", "--volume", "v1", "--chunk-filer", "filer:18888", "--depth", "data", "--timeout", "10s")
|
||||
res := decodeVerify(t, out)
|
||||
if code != chunkExitFindings || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != chunkstore.FindingReadError ||
|
||||
res.ChunksNotRead != 1 || res.ReadRetries != 2 || !strings.Contains(errs, "not verified") {
|
||||
if code != chunkExitFailed || !strings.Contains(out, "503") || !strings.Contains(errs, "incomplete") {
|
||||
t.Fatalf("verify with an unreadable chunk: %d %q %q", code, out, errs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -12,76 +11,67 @@ import (
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/link"
|
||||
)
|
||||
|
||||
// chunkVolumeDelete: sw-block ops chunk volume-delete <vol> --chunk-filer
|
||||
// host:port --master host:port deletes a chunk volume (Catalog.DeleteVolume)
|
||||
// after the blockmaster admits it (MarkVolumeDeleting: refused while the
|
||||
// volume has live or pending authority; afterwards nothing assigns, places
|
||||
// or binds it again). A failure prints what was done with the error.
|
||||
// chunkVolumeDelete: sw-block ops chunk volume-delete --volume v
|
||||
// --chunk-filer host:port --master host:port --request-id r deletes a
|
||||
// volume in the layout kernel's order. The blockmaster holds the delete's
|
||||
// authority: ReserveVolumeDeletion commits the reservation (refused while
|
||||
// an authority line is live; no grant for the volume after it; never given
|
||||
// back), and CheckVolumeNoLiveLease runs between the HEAD read and the
|
||||
// update that marks HEAD deleting. A refused delete leaves the volume
|
||||
// reserved; rerun with the same --request-id once its cause is cleared. A
|
||||
// rerun on a deleted volume sweeps any object that landed late.
|
||||
func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int {
|
||||
fs := chunkFlagSet("volume-delete", stderr)
|
||||
var (
|
||||
volumeID, filer, base, master, requestID string
|
||||
timeout time.Duration
|
||||
)
|
||||
fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes (or gives back) its earlier admission")
|
||||
fs.StringVar(&volumeID, "volume", "", "volume id (or the first argument)")
|
||||
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
|
||||
fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address (admits the delete)")
|
||||
fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this delete")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
|
||||
}
|
||||
if volumeID == "" && fs.NArg() == 1 {
|
||||
volumeID = fs.Arg(0)
|
||||
} else if fs.NArg() != 0 {
|
||||
return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "give the volume once, as an argument or --volume", false)
|
||||
}
|
||||
if volumeID == "" || master == "" || requestID == "" || timeout <= 0 {
|
||||
return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false)
|
||||
}
|
||||
cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, timeout, stdout, stderr)
|
||||
if exit >= 0 {
|
||||
return exit
|
||||
}
|
||||
defer closeFn()
|
||||
conn, err := link.DialMasterFromEnv(master)
|
||||
if err != nil {
|
||||
return chunkResult("volume-delete", nil, err, stdout, stderr)
|
||||
}
|
||||
defer conn.Close()
|
||||
admit := &masterAdmission{lc: control.NewLifecycleServiceClient(conn), token: requestID}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
res, err := cat.DeleteVolume(ctx, volumeID, admit)
|
||||
if err != nil {
|
||||
return volumeDeletePartial(res, err, stdout, stderr)
|
||||
}
|
||||
return chunkResult("volume-delete", res, nil, stdout, stderr)
|
||||
c := newBCommand("volume-delete", time.Minute, stdout, stderr)
|
||||
var vol volumeFlags
|
||||
var requestID string
|
||||
c.bindVolume(&vol, "volume", "volume")
|
||||
c.fs.StringVar(&requestID, "request-id", "", "this delete's operation id; a rerun with the same id resumes it")
|
||||
var ref chunkstore.VolumeRef
|
||||
return c.run(args, true, func() (err error) {
|
||||
if c.master == "" || requestID == "" || c.timeout <= 0 {
|
||||
return errors.New("--master and --request-id are required; --timeout must be positive")
|
||||
}
|
||||
ref, err = vol.ref("volume")
|
||||
return err
|
||||
}, func(ctx context.Context, cat *chunkstore.BCatalog) (any, error) {
|
||||
conn, err := link.DialMasterFromEnv(c.master)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
auth := &masterAuthority{lc: control.NewLifecycleServiceClient(conn), req: &control.MarkVolumeDeletingRequest{VolumeId: ref.Name, Token: requestID}}
|
||||
if err := cat.DeleteVolume(ctx, ref, auth); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]string{"volume": ref.Dir(), "state": "deleted"}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// masterAdmission is the delete's reservation at the blockmaster, held
|
||||
// under the operation's request id: a rerun with the same id adopts the
|
||||
// hold an earlier run left (e.g. after a lost response), so its give-back
|
||||
// releases it, while another operation's hold stays.
|
||||
type masterAdmission struct {
|
||||
lc control.LifecycleServiceClient
|
||||
token string
|
||||
// masterAuthority is the layout delete's authority, held by the
|
||||
// blockmaster: both operations are its RPCs, nothing is decided here.
|
||||
type masterAuthority struct {
|
||||
lc control.LifecycleServiceClient
|
||||
req *control.MarkVolumeDeletingRequest
|
||||
}
|
||||
|
||||
func (m *masterAdmission) req(vol string) *control.MarkVolumeDeletingRequest {
|
||||
return &control.MarkVolumeDeletingRequest{VolumeId: vol, Token: m.token}
|
||||
func (m *masterAuthority) Reserve(ctx context.Context) error {
|
||||
_, err := m.lc.ReserveVolumeDeletion(ctx, m.req)
|
||||
return authorityErr(err)
|
||||
}
|
||||
|
||||
// admissionErr: FailedPrecondition and InvalidArgument are definite
|
||||
func (m *masterAuthority) NoLiveLease(ctx context.Context) error {
|
||||
_, err := m.lc.CheckVolumeNoLiveLease(ctx, m.req)
|
||||
return authorityErr(err)
|
||||
}
|
||||
|
||||
// authorityErr: FailedPrecondition and InvalidArgument are definite
|
||||
// refusals; anything else (unavailable, deadline, a lost response) leaves
|
||||
// the outcome unknown.
|
||||
func admissionErr(err error) error {
|
||||
// the outcome unknown and a rerun decides.
|
||||
func authorityErr(err error) error {
|
||||
switch status.Code(err) {
|
||||
case codes.OK:
|
||||
return nil
|
||||
@@ -90,39 +80,3 @@ func admissionErr(err error) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *masterAdmission) Admit(ctx context.Context, vol string) error {
|
||||
_, err := m.lc.MarkVolumeDeleting(ctx, m.req(vol))
|
||||
return admissionErr(err)
|
||||
}
|
||||
|
||||
func (m *masterAdmission) Commit(ctx context.Context, vol string) error {
|
||||
_, err := m.lc.CommitVolumeDeleting(ctx, m.req(vol))
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *masterAdmission) Abort(ctx context.Context, vol string) error {
|
||||
_, err := m.lc.AbortVolumeDeleting(ctx, m.req(vol))
|
||||
return err
|
||||
}
|
||||
|
||||
// volumeDeletePartial prints what a failed delete did, with the error, and
|
||||
// fails.
|
||||
func volumeDeletePartial(res chunkstore.VolumeDeleteResult, err error, stdout, stderr io.Writer) int {
|
||||
body := chunkErrBody{Code: codeInternalCLI, Message: err.Error()}
|
||||
var ce *chunkstore.CatalogError
|
||||
if errors.As(err, &ce) {
|
||||
body = chunkErrBody{Code: ce.Code, Message: ce.Detail(), Retryable: ce.Retryable}
|
||||
}
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk volume-delete: %s: %s (headMarked=%t completed=%t uncertain=%t)\n", body.Code, body.Message, res.HeadMarked, res.Completed, res.Uncertain)
|
||||
out, mErr := json.Marshal(struct {
|
||||
chunkstore.VolumeDeleteResult
|
||||
Error *chunkErrBody `json:"error"`
|
||||
}{res, &body})
|
||||
if mErr == nil {
|
||||
if wErr := writeAll(stdout, append(out, '\n')); wErr != nil {
|
||||
fmt.Fprintf(stderr, "sw-block ops chunk volume-delete: write the result: %v\n", wErr)
|
||||
}
|
||||
}
|
||||
return chunkExitFailed
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// The real command reserves through the real master while a first lease
|
||||
// request is paused at RPC ingress. At the command's CAS-time lease check,
|
||||
// resume that request: committed exclusion must refuse it before the check
|
||||
// can certify absence. The authority package separately pauses every writer
|
||||
// immediately before its grant lock; this test composes the transport path.
|
||||
func TestOpsChunkVolumeDeleteClosesAPausedFirstGrant(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
paused, resume := make(chan struct{}), make(chan struct{})
|
||||
grantResult := make(chan error, 1)
|
||||
var checked atomic.Bool
|
||||
intercept := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, next grpc.UnaryHandler) (any, error) {
|
||||
switch info.FullMethod {
|
||||
case control.WorkspaceService_RenewWorkspaceLease_FullMethodName:
|
||||
close(paused)
|
||||
select {
|
||||
case <-resume:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
case control.LifecycleService_CheckVolumeNoLiveLease_FullMethodName:
|
||||
close(resume)
|
||||
select {
|
||||
case err := <-grantResult:
|
||||
if status.Code(err) != codes.FailedPrecondition {
|
||||
return nil, status.Errorf(codes.Internal, "paused grant escaped reservation: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
checked.Store(true)
|
||||
}
|
||||
return next(ctx, req)
|
||||
}
|
||||
cfg := master.Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
|
||||
ServerOptions: []grpc.ServerOption{grpc.ChainUnaryInterceptor(intercept)},
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}
|
||||
h, stop := startDeleteMaster(t, cfg)
|
||||
defer stop()
|
||||
seedForcedVolumeLease(t, h, false)
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
go func() {
|
||||
_, err := control.NewWorkspaceServiceClient(conn).RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1})
|
||||
grantResult <- err
|
||||
}()
|
||||
select {
|
||||
case <-paused:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("first grant did not reach RPC ingress")
|
||||
}
|
||||
store := newMemChunkStore()
|
||||
useMemChunkStore(t, store)
|
||||
v := cliVolume(t, store, "vol-f", "daily")
|
||||
code, out, stderr := runChunk(cliArgs("volume-delete", volArgs("volume", v), []string{"--master", h.Addr(), "--request-id", "paused-first-grant"})...)
|
||||
if code != 0 || !checked.Load() {
|
||||
t.Fatalf("delete exit=%d checked=%v out=%s err=%s", code, checked.Load(), out, stderr)
|
||||
}
|
||||
cat, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, found, err := cat.ReadHead(ctx, v)
|
||||
if err != nil || !found || head.State != layout.StateDeleted {
|
||||
t.Fatalf("final HEAD: %+v found=%v err=%v", head, found, err)
|
||||
}
|
||||
if !h.Lifecycle().Deletions.CommittedSnapshot("vol-f") {
|
||||
t.Fatal("command did not commit the real master's reservation")
|
||||
}
|
||||
if s := h.Publisher().WorkspaceState("vol-f"); s != nil && s.Lease != nil {
|
||||
t.Fatalf("late request created a lease: %+v", s.Lease)
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"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"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type volumeDeleteOutput struct {
|
||||
chunkstore.VolumeDeleteResult
|
||||
Error *chunkErrBody `json:"error"`
|
||||
}
|
||||
|
||||
func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient {
|
||||
t.Helper()
|
||||
c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
return control.NewLifecycleServiceClient(c)
|
||||
}
|
||||
|
||||
func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) {
|
||||
t.Helper()
|
||||
h, err := master.New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
return h, func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = h.Close(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// volume-delete against a real master runtime: argument checks; a held
|
||||
// volume and a volume with a snapshot are refused with the admission given
|
||||
// back (usable again); a lost first admission is adopted and given back by
|
||||
// a rerun with the same request id (usable after a master restart); a
|
||||
// completed delete is committed (never created again).
|
||||
func TestOpsChunk_VolumeDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mem := chunkstore.NewMemFiler()
|
||||
prev := dialChunkFiler
|
||||
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil }
|
||||
t.Cleanup(func() { dialChunkFiler = prev })
|
||||
cat, err := chunkstore.NewCatalog(mem, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
geo := chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
|
||||
for _, vol := range []string{"v1", "v2", "v3"} {
|
||||
if _, err := cat.EnsureVolume(ctx, vol, geo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// v2 is attached: its HEAD names a holder.
|
||||
r, err := chunkstore.NewChunkRemote(mem, &gcCLIStore{MemFiler: mem}, defaultChunkPathCLI+"/v2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// v3 has a snapshot.
|
||||
h3, _, err := cat.ReadHead(ctx, "v3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cat.CreateSnapshot(ctx, "v3", chunkstore.SnapshotRequest{Name: "s", RequestID: "rs"}, h3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, args := range [][]string{
|
||||
{"volume-delete", "--chunk-filer", "f:1", "--request-id", "x", "v1"}, // no --master
|
||||
{"volume-delete", "--chunk-filer", "f:1", "--master", "m:1", "v1"}, // no --request-id
|
||||
{"volume-delete", "--master", "m:1", "--request-id", "x", "--chunk-filer", "f:1"}, // no volume
|
||||
{"volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "x", "v2", "extra"}, // two volumes
|
||||
} {
|
||||
if code, out, _ := runChunk(args...); code == 0 || !strings.Contains(out, codeBadRequestCLI) {
|
||||
t.Fatalf("%v: %d %q; want a bad request", args, code, out)
|
||||
}
|
||||
}
|
||||
|
||||
cfg := gcTestMasterConfig(t)
|
||||
cfg.LifecycleStoreDir = t.TempDir() // the reservation store lives here
|
||||
h, stop := startDeleteMaster(t, cfg)
|
||||
lc := lifecycleClient(t, h.Addr())
|
||||
run := func(vol, op string) (int, volumeDeleteOutput) {
|
||||
t.Helper()
|
||||
code, out, _ := runChunk("volume-delete", "--chunk-filer", "f:1", "--master", h.Addr(), "--request-id", op, vol)
|
||||
var got volumeDeleteOutput
|
||||
if err := json.Unmarshal([]byte(out), &got); err != nil {
|
||||
t.Fatalf("volume-delete %s: %q", vol, out)
|
||||
}
|
||||
return code, got
|
||||
}
|
||||
usable := func(vol string) {
|
||||
t.Helper()
|
||||
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatalf("create %s: %v; want usable", vol, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Held: refused, admission given back.
|
||||
if code, got := run("v2", "op-v2"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeInUse || !got.Admitted || !got.AdmissionAborted || got.Completed {
|
||||
t.Fatalf("delete of attached v2: %d %+v", code, got)
|
||||
}
|
||||
usable("v2")
|
||||
|
||||
// A first invocation's admission landed and its reply was lost (the
|
||||
// master holds op-v3); the rerun with the same request id meets the
|
||||
// snapshot, gives back and so releases that hold too.
|
||||
if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "v3", Token: "op-v3"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, got := run("v3", "op-v3"); code == 0 || got.Error == nil || got.Error.Code != chunkstore.CodeVolumeHasSnapshots || !got.Reverted || !got.AdmissionAborted {
|
||||
t.Fatalf("rerun of v3's delete: %d %+v; want volume_has_snapshots, reverted, given back", code, got)
|
||||
}
|
||||
stop()
|
||||
h, stop = startDeleteMaster(t, cfg) // restart: the given-back id stays usable
|
||||
defer stop()
|
||||
lc = lifecycleClient(t, h.Addr())
|
||||
usable("v3")
|
||||
if _, err := cat.EnsureVolume(ctx, "v3", geo); err != nil {
|
||||
t.Fatalf("attach v3 after the refused delete: %v", err)
|
||||
}
|
||||
|
||||
// Completed: committed, never created again.
|
||||
code, got := run("v1", "op-v1")
|
||||
if code != 0 || got.VolumeID != "v1" || !got.Completed || !got.Committed {
|
||||
t.Fatalf("delete v1: %d %+v", code, got)
|
||||
}
|
||||
if _, err := cat.EnsureVolume(ctx, "v1", geo); chunkstore.CodeOf(err) != chunkstore.CodeVolumeDeleted {
|
||||
t.Fatalf("recreate v1: %v; want volume_deleted", err)
|
||||
}
|
||||
if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v1", SizeBytes: 1 << 20, ReplicationFactor: 1}); status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("create v1 after its committed delete: %v; want FailedPrecondition", err)
|
||||
}
|
||||
}
|
||||
@@ -2293,11 +2293,9 @@ func usage(w io.Writer) {
|
||||
fmt.Fprintln(w, " sw-block ops chunk cut|detach --volume <id> --status-addr <addr|url> [--min-lsn <n>] [--timeout <d>]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk snapshot --volume <id> --status-addr <addr|url> --name <name> [--label k=v]... [--request-id <id>] [--consistency crash|app]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk snapshots|snapshot-delete --volume <id> [--name <name>] --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk fork --chunk-filer <host:port> [--chunk-path /swblock/chunks] --source <id> --snapshot <name> --target <id> [--request-id <id>] [--label k=v]...")
|
||||
fmt.Fprintln(w, " sw-block ops chunk show --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk gc --chunk-filer <host:port> --master <blockmaster-grpc> [--chunk-path /swblock/chunks] [--apply] [--grace 1h] [--intent-ttl 1h] [--timeout 1m]")
|
||||
fmt.Fprintln(w, " sw-block ops chunk verify --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks] [--snapshot <name>|--all-snapshots] [--depth meta|bindings|data]")
|
||||
fmt.Fprintln(w, " [--concurrency 2] [--bytes-per-sec 33554432] [--timeout <d>] (read-only; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
|
||||
fmt.Fprintln(w, " sw-block ops chunk verify --volume <id> --chunk-filer <host:port> [--chunk-path /swblock/chunks] [--depth meta|bindings|data] [--orphans] [--timeout <d>]")
|
||||
fmt.Fprintln(w, " (read-only; every root HEAD names is checked; exit 0 clean, 3 findings, 1 incomplete; --depth data needs --timeout)")
|
||||
fmt.Fprintln(w, " sw-block ops volume-unheld --path <volume-file> (exit 0: no process on this host holds it; local filesystems only)")
|
||||
fmt.Fprintln(w, " sw-block ops workspace force-move --master <addr> --volume <id> --target-host <server-id> --target-data <addr> --target-ctrl <addr> --request-id <id> --confirm-forced <volume>@<epoch> [--dry-run]")
|
||||
fmt.Fprintln(w, " sw-block ops workspace lost-range --master <addr> --volume <id> [--request-id <id>] (authority only; no bypass: see `sw-block ops workspace help`)")
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/master"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
)
|
||||
|
||||
func lifecycleClient(t *testing.T, addr string) control.LifecycleServiceClient {
|
||||
t.Helper()
|
||||
c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { c.Close() })
|
||||
return control.NewLifecycleServiceClient(c)
|
||||
}
|
||||
|
||||
func startDeleteMaster(t *testing.T, cfg master.Config) (*master.Host, func()) {
|
||||
t.Helper()
|
||||
if cfg.WorkspaceRPC && cfg.LayoutCreateVolume == nil {
|
||||
store := newMemChunkStore()
|
||||
catalog, err := chunkstore.NewBCatalog(store, store, defaultChunkPathCLI)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.LayoutCreateVolume = func(ctx context.Context, spec lifecycle.VolumeSpec) error {
|
||||
id, err := layout.ParseVolumeID(spec.LayoutID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = catalog.CreateVolume(ctx, chunkstore.VolumeRef{Name: spec.VolumeID, ID: id},
|
||||
layout.Geometry{SizeBytes: spec.SizeBytes, BlockSize: spec.BlockSize, ChunkBytes: spec.ChunkBytes})
|
||||
return err
|
||||
}
|
||||
}
|
||||
h, err := master.New(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Start()
|
||||
return h, func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = h.Close(ctx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package main
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
|
||||
// anyStart is a local root that can start from any HEAD: these tests do
|
||||
// not model the local store.
|
||||
func anyStart(layout.Head) error { return nil }
|
||||
@@ -21,6 +21,10 @@ import (
|
||||
// seedForcedVolume makes r1 on node-a the holder of vol-f at epoch 1 (lease
|
||||
// renewed once) with a prepared target binding on node-b.
|
||||
func seedForcedVolume(t *testing.T, h *master.Host) {
|
||||
seedForcedVolumeLease(t, h, true)
|
||||
}
|
||||
|
||||
func seedForcedVolumeLease(t *testing.T, h *master.Host, renew bool) {
|
||||
t.Helper()
|
||||
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
@@ -64,6 +68,9 @@ func seedForcedVolume(t *testing.T, h *master.Host) {
|
||||
t.Fatal("no authority line for vol-f")
|
||||
}
|
||||
}
|
||||
if !renew {
|
||||
return
|
||||
}
|
||||
if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -163,6 +163,9 @@ type Publisher struct {
|
||||
workspaceNow func() time.Time
|
||||
workspaceTTL time.Duration
|
||||
workspaceMaxClockSkew time.Duration
|
||||
// Rebuilt from committed lifecycle deletion reservations before serving.
|
||||
// Writes hold mu then leaseMu; readers hold either existing grant lock.
|
||||
deleteReserved map[string]bool
|
||||
|
||||
// Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only
|
||||
// leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is
|
||||
@@ -178,6 +181,8 @@ type Publisher struct {
|
||||
// testAfterIssuePublish, when set by a test, runs under mu right after
|
||||
// an issued move's lease view is published.
|
||||
testAfterIssuePublish func(volume string)
|
||||
// Set before concurrent test requests; nil in production.
|
||||
testBeforeGrantLock func(site string)
|
||||
}
|
||||
|
||||
// PublicationAdmission surrounds an ordinary mint with local ownership/lifetime
|
||||
@@ -471,7 +476,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr
|
||||
return err
|
||||
}
|
||||
|
||||
p.beforeWorkspaceGrantLock("publication")
|
||||
p.mu.Lock()
|
||||
if p.deleteReserved[ask.VolumeID] {
|
||||
p.mu.Unlock()
|
||||
return ErrWorkspaceDeleteReserved
|
||||
}
|
||||
if p.workspaceUncertain[ask.VolumeID] {
|
||||
p.mu.Unlock()
|
||||
if grant != nil {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Start relies on a granted higher epoch, not elapsed time at the volume.
|
||||
// These are all epoch constructors and reassign request producers in the
|
||||
// authority package. All request producers converge on applyWithWorkspaceMove:
|
||||
// an enrolled LOCAL volume refuses an ordinary reassign, and a workspace
|
||||
// grant is revalidated by prepareWorkspaceMoveLocked under the mint lock.
|
||||
// Genesis placement has no predecessor; reload copies durable epochs. NET
|
||||
// promotion and failback use ordinary reassign, never a LOCAL lease bypass.
|
||||
func TestLayoutGrantedEpochIssuerSites(t *testing.T) {
|
||||
want := map[string]int{
|
||||
"authority.go applyWithWorkspaceMove epoch assignment": 1,
|
||||
"authority.go reloadFromStore epoch": 1,
|
||||
"authority.go applyWithWorkspaceMove epoch": 2,
|
||||
"controller.go decideVolume reassign": 2,
|
||||
"failback_runtime.go ExecuteFailback reassign": 1,
|
||||
"workspace.go MoveWorkspace reassign": 1,
|
||||
"authority.go apply applyWithWorkspaceMove": 2,
|
||||
"workspace.go MoveWorkspace applyWithWorkspaceMove": 1,
|
||||
"authority.go applyWithWorkspaceMove prepareWorkspaceMoveLocked": 1,
|
||||
}
|
||||
got := map[string]int{}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range files {
|
||||
if strings.HasSuffix(p, "_test.go") {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sites, err := layoutEpochSites(p, raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for k, n := range sites {
|
||||
got[k] += n
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("epoch issuers changed; enumerate each proof/barrier and add its probe: got=%v want=%v", got, want)
|
||||
}
|
||||
// Existing behavioral probes pin the deciding guards: clean needs detached
|
||||
// HEAD plus ACK; forced needs the lease barrier, including restart; an
|
||||
// ordinary failover cannot bypass an enrolled workspace's guarded move.
|
||||
}
|
||||
|
||||
func layoutEpochSites(path string, raw []byte) (map[string]int, error) {
|
||||
f, err := parser.ParseFile(token.NewFileSet(), path, raw, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]int{}
|
||||
for _, d := range f.Decls {
|
||||
fn, ok := d.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
continue
|
||||
}
|
||||
record := func(kind string) { out[path+" "+fn.Name.Name+" "+kind]++ }
|
||||
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||
if assign, ok := n.(*ast.AssignStmt); ok {
|
||||
for _, lhs := range assign.Lhs {
|
||||
if sel, ok := lhs.(*ast.SelectorExpr); ok && sel.Sel.Name == "Epoch" {
|
||||
record("epoch assignment")
|
||||
}
|
||||
}
|
||||
}
|
||||
if inc, ok := n.(*ast.IncDecStmt); ok {
|
||||
if sel, ok := inc.X.(*ast.SelectorExpr); ok && sel.Sel.Name == "Epoch" {
|
||||
record("epoch assignment")
|
||||
}
|
||||
}
|
||||
|
||||
if call, ok := n.(*ast.CallExpr); ok {
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "applyWithWorkspaceMove" || sel.Sel.Name == "prepareWorkspaceMoveLocked") {
|
||||
record(sel.Sel.Name)
|
||||
}
|
||||
}
|
||||
lit, ok := n.(*ast.CompositeLit)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
typ := ""
|
||||
switch x := lit.Type.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
typ = x.Sel.Name
|
||||
case *ast.Ident:
|
||||
typ = x.Name
|
||||
}
|
||||
for _, e := range lit.Elts {
|
||||
kv, ok := e.(*ast.KeyValueExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
key, ok := kv.Key.(*ast.Ident)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if typ == "AssignmentInfo" && key.Name == "Epoch" {
|
||||
record("epoch")
|
||||
}
|
||||
if typ == "AssignmentAsk" && key.Name == "Intent" {
|
||||
if id, ok := kv.Value.(*ast.Ident); ok && id.Name == "IntentReassign" {
|
||||
record("reassign")
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func TestLayoutEpochEnumerationRejectsANewIssuer(t *testing.T) {
|
||||
got, err := layoutEpochSites("new.go", []byte(`package authority; func bypass(){ _ = adapter.AssignmentInfo{Epoch: 99}; _ = AssignmentAsk{Intent:IntentReassign} }`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["new.go bypass epoch"] != 1 || got["new.go bypass reassign"] != 1 {
|
||||
t.Fatal("new issuer escaped enumeration", got)
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ type WorkspaceLease struct {
|
||||
type WorkspaceRevokeAck struct {
|
||||
ReplicaID string
|
||||
Epoch, HeadGen uint64
|
||||
Holder string
|
||||
RemoteLSN uint64
|
||||
}
|
||||
|
||||
type WorkspaceMoveRecord struct {
|
||||
@@ -188,13 +190,14 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
|
||||
}
|
||||
|
||||
func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error {
|
||||
// INV-WS-SAME-HOST-CLEAN-MOVE-001: clean moves may reuse the host,
|
||||
// but every move preserves its logical replica slot.
|
||||
// A same-host clean move still needs its seal/ACK; a forced recovery
|
||||
// still needs its expired lease barrier and persisted lost range.
|
||||
// Every move preserves its logical replica slot.
|
||||
// Refuse before locking or persisting a reservation/authority epoch.
|
||||
if req.ExpectedReplicaID != req.TargetReplicaID {
|
||||
return fmt.Errorf("workspace move: v1 requires the same logical replica id")
|
||||
}
|
||||
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || (req.ExpectedHost == req.TargetHost && (req.Kind != "clean" || req.Force)) || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
|
||||
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
|
||||
req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") {
|
||||
return fmt.Errorf("workspace move: invalid request")
|
||||
}
|
||||
@@ -264,6 +267,10 @@ func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest,
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
p.mu.Lock()
|
||||
if p.deleteReserved[req.VolumeID] {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceMoveRecord{}, ErrWorkspaceDeleteReserved
|
||||
}
|
||||
r, replay, err := p.issuedWorkspaceReplayLocked(req)
|
||||
p.mu.Unlock()
|
||||
if err != nil {
|
||||
@@ -305,7 +312,7 @@ func (p *Publisher) BeginWorkspaceRevocation(ctx context.Context, volume, holder
|
||||
return p.persistWorkspaceLocked(volume, s)
|
||||
}
|
||||
|
||||
func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, ack WorkspaceRevokeAck) error {
|
||||
func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, ack WorkspaceRevokeAck, h WorkspaceHead) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -313,16 +320,23 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a
|
||||
defer p.mu.Unlock()
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
s := cloneWorkspace(p.workspace[volume])
|
||||
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.HeadGen == 0 || s == nil || s.Lease == nil || !s.Lease.Revoking {
|
||||
if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking {
|
||||
return fmt.Errorf("workspace revoke ACK: stale or unsolicited")
|
||||
}
|
||||
if !h.Detached || h.Deleting || h.Epoch != ack.Epoch || h.Holder != ack.Holder {
|
||||
return fmt.Errorf("workspace revoke ACK: no detached HEAD for this holder")
|
||||
}
|
||||
ack.RemoteLSN = h.RemoteLSN
|
||||
lease := *s.Lease
|
||||
lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano())
|
||||
if p.WorkspaceLeaseValidity(lease) == 0 {
|
||||
return fmt.Errorf("workspace revoke ACK: lease expired; forced move required")
|
||||
}
|
||||
if s.Ack != nil && *s.Ack != ack {
|
||||
return fmt.Errorf("workspace revoke ACK changed")
|
||||
if s.Ack != nil {
|
||||
if s.Ack.ReplicaID != ack.ReplicaID || s.Ack.Epoch != ack.Epoch || s.Ack.Holder != ack.Holder || s.Ack.RemoteLSN != ack.RemoteLSN {
|
||||
return fmt.Errorf("workspace revoke ACK changed")
|
||||
}
|
||||
return nil // generation is readout only; retain the original ACK
|
||||
}
|
||||
s.Ack = &ack
|
||||
return p.persistWorkspaceLocked(volume, s)
|
||||
@@ -529,7 +543,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra
|
||||
return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder")
|
||||
}
|
||||
if q.Kind == "clean" {
|
||||
if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen {
|
||||
if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != h.Epoch || s.Ack.Holder != h.Holder || s.Ack.RemoteLSN != h.RemoteLSN {
|
||||
return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// A stopped image is stable while operator metadata may still change HEAD.
|
||||
// Neither a snapshot deletion nor a restore dependency invalidates its ACK.
|
||||
func TestWorkspaceCleanMoveAfterStoppedSnapshotMetadataChanges(t *testing.T) {
|
||||
for _, op := range []string{"DeleteSnapshot", "AddDependent"} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock())
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
ctx := context.Background()
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := layout.RootName{Hash: layout.Hash{1}}
|
||||
h := layout.Head{Gen: 7, Epoch: 1, Holder: "host/r", Position: 42, State: layout.StateDetached, Current: &root, Activity: layout.Activity{Kind: layout.ActIdle}, Snapshots: map[string]layout.Snapshot{"s": {Root: root, Position: 42}}}
|
||||
var next layout.Head
|
||||
var changed bool
|
||||
var err error
|
||||
if op == "DeleteSnapshot" {
|
||||
next, changed, err = h.DeleteSnapshot("s")
|
||||
} else {
|
||||
id, e := layout.NewVolumeID()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next, changed, err = h.AddDependent("s", layout.Dependent{Target: "restore", TargetID: id}, root)
|
||||
}
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("operator transition: changed=%t err=%v", changed, err)
|
||||
}
|
||||
next.Gen++ // the filer's successful conditional metadata write
|
||||
req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "next", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"}
|
||||
grant, err := p.MoveWorkspace(ctx, req, WorkspaceHead{Gen: next.Gen, Epoch: next.Epoch, Holder: next.Holder, RemoteLSN: next.Position, Detached: next.State == layout.StateDetached})
|
||||
if err != nil || !grant.Issued {
|
||||
t.Fatalf("clean move after %s: grant=%+v err=%v; want admitted", op, grant, err)
|
||||
}
|
||||
if grant.HeadGen != next.Gen || grant.RemoteLSN != h.Position {
|
||||
t.Fatalf("readout lost: %+v", grant)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A generation is readout only on both ACK receipt and move admission.
|
||||
func TestWorkspaceStopProofNeverBranchesOnGeneration(t *testing.T) {
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "workspace.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, decl := range f.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if !ok || (fn.Name.Name != "AckWorkspaceRevocation" && fn.Name.Name != "prepareWorkspaceMoveLocked") {
|
||||
continue
|
||||
}
|
||||
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||
cond, ok := n.(*ast.IfStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
ast.Inspect(cond.Cond, func(n ast.Node) bool {
|
||||
if s, ok := n.(*ast.SelectorExpr); ok && (s.Sel.Name == "HeadGen" || s.Sel.Name == "Gen") {
|
||||
t.Errorf("%s branches on generation instead of stop identity", fn.Name.Name)
|
||||
}
|
||||
return true
|
||||
})
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceAckReplayKeepsOriginalGenerationReadout(t *testing.T) {
|
||||
p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock())
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
ctx := context.Background()
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack := WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack.HeadGen = 99
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err != nil {
|
||||
t.Fatal("metadata-only ACK replay refused", err)
|
||||
}
|
||||
if p.WorkspaceState("v").Ack.HeadGen != 7 {
|
||||
t.Fatal("replay replaced the original generation readout")
|
||||
}
|
||||
ack.RemoteLSN++
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", ack, WorkspaceHead{Detached: true, Epoch: ack.Epoch, Holder: ack.Holder, RemoteLSN: ack.RemoteLSN}); err == nil {
|
||||
t.Fatal("different stopped image replay accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceAckValidatesTheObservedStoppedHead(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
head WorkspaceHead
|
||||
admit bool
|
||||
}{
|
||||
{"same stop, changed generation", WorkspaceHead{Gen: 99, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, true},
|
||||
{"still live", WorkspaceHead{Epoch: 1, Holder: "host/r", RemoteLSN: 42}, false},
|
||||
{"foreign epoch", WorkspaceHead{Epoch: 2, Holder: "host/r", Detached: true}, false},
|
||||
{"foreign holder", WorkspaceHead{Epoch: 1, Holder: "other/r", Detached: true}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock())
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
ctx := context.Background()
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, Holder: "host/r", HeadGen: 7, RemoteLSN: 999}, tc.head)
|
||||
if (err == nil) != tc.admit {
|
||||
t.Fatalf("admit=%t: %v", tc.admit, err)
|
||||
}
|
||||
ack := p.WorkspaceState("v").Ack
|
||||
if !tc.admit && ack != nil {
|
||||
t.Fatal("refusal persisted an ACK")
|
||||
}
|
||||
if tc.admit && (ack == nil || ack.RemoteLSN != tc.head.RemoteLSN) {
|
||||
t.Fatalf("ACK did not persist the authoritative position: %+v", ack)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceCleanMoveRequiresTheAckedStopIdentity(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
head WorkspaceHead
|
||||
admit bool
|
||||
}{
|
||||
{"same stop, changed generation", WorkspaceHead{Gen: 99, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}, true},
|
||||
{"not detached", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42}, false},
|
||||
{"other epoch", WorkspaceHead{Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true}, false},
|
||||
{"other holder", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true}, false},
|
||||
{"other position", WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 43, Detached: true}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := newLeasePublisher(t, &failingStore{}, time.Second, newTestClock())
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
ctx := context.Background()
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "next", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"}
|
||||
got, err := p.MoveWorkspace(ctx, req, tc.head)
|
||||
if (err == nil) != tc.admit || got.Issued != tc.admit {
|
||||
t.Fatalf("admit=%t: %+v %v", tc.admit, got, err)
|
||||
}
|
||||
if !tc.admit && len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("refusal wrote a reservation")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeletionReservationGuardSites(t *testing.T) {
|
||||
// A new field access or grant-bound writer must join the causal controls.
|
||||
flagSites := map[string]bool{
|
||||
"ReserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true,
|
||||
"applyWithWorkspaceMove": true, "MoveWorkspace": true,
|
||||
"RenewWorkspaceLease": true, "firstWorkspaceGrant": true,
|
||||
"regrantWorkspaceLease": true, "extendWorkspaceLease": true,
|
||||
}
|
||||
boundSites := map[string]bool{
|
||||
"publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true,
|
||||
"RenewWorkspaceLease": true, "regrantWorkspaceLease": true,
|
||||
"extendWorkspaceLease": true,
|
||||
// Reply-only copies never increase published validity.
|
||||
"WorkspaceLeaseReply": true, "AckWorkspaceRevocation": true,
|
||||
// Copies the published horizon into the leaf view under mu -> leaseMu.
|
||||
"deriveLeaseLocked": true,
|
||||
// Positive lease construction and publication, or a plain clone.
|
||||
"newWorkspaceLease": true, "firstWorkspaceGrant": true,
|
||||
"issueWorkspaceMove": true, "cloneWorkspace": true,
|
||||
}
|
||||
seenFlag, seenBound := map[string]bool{}, map[string]bool{}
|
||||
entries, err := os.ReadDir(".")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !strings.HasSuffix(e.Name(), ".go") || strings.HasSuffix(e.Name(), "_test.go") {
|
||||
continue
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), filepath.Clean(e.Name()), nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, d := range f.Decls {
|
||||
name := "package initializer"
|
||||
if fn, ok := d.(*ast.FuncDecl); ok {
|
||||
name = fn.Name.Name
|
||||
}
|
||||
ast.Inspect(d, func(n ast.Node) bool {
|
||||
if s, ok := n.(*ast.SelectorExpr); ok && s.Sel.Name == "deleteReserved" {
|
||||
seenFlag[name] = true
|
||||
if !flagSites[name] {
|
||||
t.Errorf("unclassified deletion flag reader/writer %s in %s", name, e.Name())
|
||||
}
|
||||
}
|
||||
if a, ok := n.(*ast.AssignStmt); ok {
|
||||
for _, lhs := range a.Lhs {
|
||||
if s, ok := lhs.(*ast.SelectorExpr); ok && (s.Sel.Name == "deadline" || s.Sel.Name == "horizon" || s.Sel.Name == "ExpiresAtNS" || s.Sel.Name == "Lease") {
|
||||
seenBound[name] = true
|
||||
if !boundSites[name] {
|
||||
t.Errorf("unclassified lease bound writer %s in %s", name, e.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if kv, ok := n.(*ast.KeyValueExpr); ok {
|
||||
if key, ok := kv.Key.(*ast.Ident); ok && (key.Name == "ExpiresAtNS" || key.Name == "Lease" || key.Name == "deadline" || key.Name == "horizon") {
|
||||
seenBound[name] = true
|
||||
if !boundSites[name] {
|
||||
t.Errorf("unclassified lease constructor %s in %s", name, e.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
if call, ok := n.(*ast.CallExpr); ok {
|
||||
if fn, ok := call.Fun.(*ast.SelectorExpr); ok && fn.Sel.Name == "newWorkspaceLease" && !boundSites[name] {
|
||||
t.Errorf("unclassified lease grant constructor caller %s in %s", name, e.Name())
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
for name := range flagSites {
|
||||
if !seenFlag[name] {
|
||||
t.Errorf("missing reservation guard at %s", name)
|
||||
}
|
||||
}
|
||||
for name := range boundSites {
|
||||
if !seenBound[name] {
|
||||
t.Errorf("missing bound classification %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrWorkspaceDeleteReserved = errors.New("workspace: deletion is committed")
|
||||
|
||||
// ErrWorkspaceDeleteRefused means the early reservation check refused before
|
||||
// calling persist. Context and persistence errors never carry this sentinel.
|
||||
var ErrWorkspaceDeleteRefused = errors.New("workspace: deletion refused before persistence")
|
||||
|
||||
func (p *Publisher) beforeWorkspaceGrantLock(site string) {
|
||||
if p.testBeforeGrantLock != nil {
|
||||
p.testBeforeGrantLock(site)
|
||||
}
|
||||
}
|
||||
|
||||
// ReserveWorkspaceDeletion persists the existing lifecycle reservation as
|
||||
// committed, then closes all grant writers under mu -> leaseMu. persist must
|
||||
// not reenter Publisher. A replay does no I/O. On startup, call this for every
|
||||
// reloaded committed reservation before serving requests (persist is then nil).
|
||||
func (p *Publisher) ReserveWorkspaceDeletion(ctx context.Context, volume string, persist func() error) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if volume == "" {
|
||||
return errors.New("workspace delete: volume is required")
|
||||
}
|
||||
if p.deleteReserved[volume] {
|
||||
return nil
|
||||
}
|
||||
// An operator's delete of a volume still served is refused before the
|
||||
// irreversible step: nothing is persisted while a lease is live now.
|
||||
// This decides nothing for safety (the closed grant writers and the
|
||||
// check at the delete's HEAD update do); it stops an outage by mistake.
|
||||
if persist != nil {
|
||||
if err := p.liveLeaseLocked(volume); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrWorkspaceDeleteRefused, err)
|
||||
}
|
||||
}
|
||||
if persist != nil {
|
||||
if err := persist(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
if p.deleteReserved == nil {
|
||||
p.deleteReserved = map[string]bool{}
|
||||
}
|
||||
p.deleteReserved[volume] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoLiveWorkspaceLease checks the deletion's stable lease premise.
|
||||
func (p *Publisher) NoLiveWorkspaceLease(ctx context.Context, volume string) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !p.deleteReserved[volume] {
|
||||
return errors.New("workspace delete: committed reservation required")
|
||||
}
|
||||
return p.liveLeaseLocked(volume)
|
||||
}
|
||||
|
||||
// liveLeaseLocked reports a lease of volume that may still be live (or
|
||||
// that cannot be proven absent). Caller holds mu.
|
||||
func (p *Publisher) liveLeaseLocked(volume string) error {
|
||||
// A skipped authority record is not evidence that its lease never existed.
|
||||
// Until recovery identifies it, do not certify absence from a partial load.
|
||||
if len(p.loadErrs) != 0 {
|
||||
return errors.New("workspace delete: authority records were skipped during recovery; lease absence is unknown")
|
||||
}
|
||||
if p.workspaceUncertain[volume] {
|
||||
return errors.New("workspace delete: lease persistence uncertain; restart required")
|
||||
}
|
||||
if s := p.workspace[volume]; s != nil && s.Lease != nil {
|
||||
until, _, err := p.forcedMoveBarrierLocked(volume, s.Lease)
|
||||
if err != nil {
|
||||
return fmt.Errorf("workspace delete: live until %s: %w", time.Unix(0, until).UTC().Format(time.RFC3339Nano), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type deleteGrantStore struct{ failingStore }
|
||||
|
||||
func (*deleteGrantStore) LoadWorkspaceLostRanges() (map[string][]WorkspaceLostRange, []error, error) {
|
||||
return map[string][]WorkspaceLostRange{}, nil, nil
|
||||
}
|
||||
|
||||
type skippedDeleteStore struct{ deleteGrantStore }
|
||||
|
||||
func (*skippedDeleteStore) LoadWithSkips() ([]DurableRecord, []error, error) {
|
||||
return nil, []error{errors.New("corrupt authority record")}, nil
|
||||
}
|
||||
|
||||
func TestDeleteCannotProveNoLeaseFromASkippedAuthorityRecord(t *testing.T) {
|
||||
p := NewPublisher(nil, WithStore(&skippedDeleteStore{}))
|
||||
if err := p.ReserveWorkspaceDeletion(context.Background(), "v", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil {
|
||||
t.Fatal("a partial authority load proved lease absence")
|
||||
}
|
||||
}
|
||||
|
||||
// A delete of a volume still served is refused before anything is
|
||||
// persisted, and the holder keeps renewing: a mistaken delete is not an
|
||||
// outage. Once the lease has lapsed the reservation commits.
|
||||
func TestDeleteOfALiveVolumeIsRefusedBeforePersisting(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
persisted := false
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { persisted = true; return nil }); !errors.Is(err, ErrWorkspaceDeleteRefused) || !strings.Contains(err.Error(), "live until") || persisted {
|
||||
t.Fatalf("reserve of a live volume: %v (persisted %t); want refused, nothing persisted", err, persisted)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatalf("the holder's renewal after a refused delete: %v", err)
|
||||
}
|
||||
c.at(1000)
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { persisted = true; return nil }); err != nil || !persisted {
|
||||
t.Fatalf("reserve after the lease lapsed: %v (persisted %t)", err, persisted)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("a committed delete extended a holder lease")
|
||||
}
|
||||
}
|
||||
|
||||
// A committed reservation reloaded at startup (persist nil) while a lease
|
||||
// record exists stops every grant and waits for the whole lease.
|
||||
func TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("committed delete extended a holder lease")
|
||||
}
|
||||
// First horizon is 45 s, plus the default skew of 20 s. Host validity
|
||||
// expiring earlier is insufficient evidence for deleting remote data.
|
||||
c.at(64)
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err == nil || !strings.Contains(err.Error(), "live until") {
|
||||
t.Fatalf("before durable horizon + skew: %v", err)
|
||||
}
|
||||
c.at(65)
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil {
|
||||
t.Fatal("expired regrant reopened a committed delete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteReservationMustBeDurableBeforeItCanProveNoLease(t *testing.T) {
|
||||
p := NewPublisher(nil)
|
||||
errDisk := errors.New("reservation sync failed")
|
||||
if err := p.ReserveWorkspaceDeletion(context.Background(), "v", func() error { return errDisk }); !errors.Is(err, errDisk) {
|
||||
t.Fatalf("persist error: %v", err)
|
||||
}
|
||||
if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil {
|
||||
t.Fatal("a failed reservation proved no lease")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteReservationPersistenceDoesNotBlockLiveRenewal(t *testing.T) {
|
||||
c := newTestClock()
|
||||
p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c)
|
||||
// Another volume's holder renews while v's reservation is on disk.
|
||||
bindAndGrant(t, p, "w", "r")
|
||||
entered, release, reserved := make(chan struct{}), make(chan struct{}), make(chan error, 1)
|
||||
go func() {
|
||||
reserved <- p.ReserveWorkspaceDeletion(context.Background(), "v", func() error {
|
||||
close(entered)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
<-entered
|
||||
renewed := make(chan error, 1)
|
||||
go func() { _, err := p.RenewWorkspaceLease(context.Background(), "w", "r", 1); renewed <- err }()
|
||||
select {
|
||||
case err := <-renewed:
|
||||
close(release)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
close(release)
|
||||
t.Fatal("live renewal waited on reservation disk I/O")
|
||||
}
|
||||
if err := <-reserved; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); !errors.Is(err, ErrWorkspaceDeleteReserved) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, site := range []string{"publication", "first grant", "regrant", "renewal", "extension", "move"} {
|
||||
t.Run(site, func(t *testing.T) {
|
||||
c := newTestClock()
|
||||
store := &deleteGrantStore{}
|
||||
p := newLeasePublisher(t, store, 30*time.Second, c)
|
||||
if site != "publication" {
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if site != "first grant" {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if site == "regrant" || site == "move" {
|
||||
c.at(100)
|
||||
}
|
||||
paused, resume := make(chan struct{}), make(chan struct{})
|
||||
p.testBeforeGrantLock = func(at string) {
|
||||
if at == site || (site == "move" && at == "publication") {
|
||||
close(paused)
|
||||
<-resume
|
||||
}
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
switch site {
|
||||
case "publication":
|
||||
done <- p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind})
|
||||
case "extension":
|
||||
p.extWG.Add(1)
|
||||
p.extendWorkspaceLease("v", "r", 1, c.sec(100))
|
||||
done <- nil
|
||||
case "move":
|
||||
_, err := p.MoveWorkspace(ctx, WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "a", TargetHost: "b", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, WorkspaceHead{Gen: 1, Epoch: 1, Holder: "a/r"})
|
||||
done <- err
|
||||
default:
|
||||
_, err := p.RenewWorkspaceLease(ctx, "v", "r", 1)
|
||||
done <- err
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-paused:
|
||||
case err := <-done:
|
||||
t.Fatalf("request did not reach %s boundary: %v", site, err)
|
||||
}
|
||||
// The delete is admitted once the old lease has lapsed (a live one
|
||||
// refuses it early); the paused writer must still be closed.
|
||||
c.at(100)
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", func() error { return nil }); err != nil {
|
||||
close(resume)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writes := len(store.records)
|
||||
close(resume)
|
||||
err := <-done
|
||||
if site != "extension" && !errors.Is(err, ErrWorkspaceDeleteReserved) {
|
||||
t.Fatalf("paused %s: %v", site, err)
|
||||
}
|
||||
if len(store.records) != writes {
|
||||
t.Fatalf("paused %s wrote after the no-live-lease proof", site)
|
||||
}
|
||||
if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil {
|
||||
t.Fatalf("paused %s invalidated the proof: %v", site, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteReservationReplayAndRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c := newTestClock()
|
||||
store := &deleteGrantStore{}
|
||||
p := newLeasePublisher(t, store, 30*time.Second, c)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
writes := 0
|
||||
persist := func() error { writes++; return nil }
|
||||
c.at(70) // the lease has lapsed: a live one refuses the delete early
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", persist); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.ReserveWorkspaceDeletion(ctx, "v", persist); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if writes != 1 {
|
||||
t.Fatalf("reservation persisted %d times", writes)
|
||||
}
|
||||
// The fake preserves the latest complete authority record; the lifecycle
|
||||
// reservation is independently reloaded by master.New before serving.
|
||||
last := store.records[len(store.records)-1]
|
||||
c.at(100)
|
||||
loaded := newLeasePublisher(t, &deleteGrantStore{failingStore: failingStore{records: []DurableRecord{last}}}, 30*time.Second, c)
|
||||
if err := loaded.ReserveWorkspaceDeletion(ctx, "v", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := loaded.RenewWorkspaceLease(ctx, "v", "r", 1); !errors.Is(err, ErrWorkspaceDeleteReserved) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A restart conservatively starts a fresh TTL deadline, even though the
|
||||
// old persisted horizon has passed. It too must expire with the skew.
|
||||
c.at(149)
|
||||
if err := loaded.NoLiveWorkspaceLease(ctx, "v"); err == nil {
|
||||
t.Fatal("restart deadline was ignored")
|
||||
}
|
||||
c.at(150)
|
||||
if err := loaded.NoLiveWorkspaceLease(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteReservationContextAndPersistenceFailuresStayUnknown(t *testing.T) {
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
expired, stop := context.WithDeadline(context.Background(), time.Unix(0, 0))
|
||||
defer stop()
|
||||
disk := errors.New("disk response lost")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
failure error
|
||||
}{
|
||||
{"cancel", canceled, context.Canceled},
|
||||
{"deadline", expired, context.DeadlineExceeded},
|
||||
{"persist", context.Background(), disk},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, newTestClock())
|
||||
err := p.ReserveWorkspaceDeletion(tc.ctx, "v", func() error { return disk })
|
||||
if !errors.Is(err, tc.failure) || errors.Is(err, ErrWorkspaceDeleteRefused) {
|
||||
t.Fatalf("failure classification=%v", err)
|
||||
}
|
||||
if err := p.NoLiveWorkspaceLease(context.Background(), "v"); err == nil {
|
||||
t.Fatal("failed reservation proved lease absence")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func TestWorkspaceExpiredLeaseCannotAcknowledgeCLEAN(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err == nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err == nil {
|
||||
t.Fatal("expired lease recorded a CLEAN revocation ACK")
|
||||
}
|
||||
if p.WorkspaceState("v").Ack != nil {
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) {
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 1, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(100 * time.Millisecond)
|
||||
|
||||
@@ -178,7 +178,7 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check("revocation")
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check("ack")
|
||||
@@ -878,7 +878,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) {
|
||||
writersDone <- fmt.Errorf("revocation: %w", err)
|
||||
return
|
||||
}
|
||||
err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7})
|
||||
err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42})
|
||||
clock.Resume()
|
||||
if err != nil {
|
||||
writersDone <- fmt.Errorf("ack: %w", err)
|
||||
|
||||
@@ -222,6 +222,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
p.beforeWorkspaceGrantLock("renewal")
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
// unlock releases leaseMu on a path that grants nothing and logs a due
|
||||
@@ -232,6 +233,10 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(summary)
|
||||
}
|
||||
if p.deleteReserved[volume] {
|
||||
unlock()
|
||||
return WorkspaceLease{}, ErrWorkspaceDeleteReserved
|
||||
}
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch {
|
||||
unlock()
|
||||
@@ -316,7 +321,12 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
// its holder's lease. A host whose first renewal fails does not fence: it has
|
||||
// no deadline yet and retries. The durable horizon starts at now+1.5*TTL.
|
||||
func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.beforeWorkspaceGrantLock("first grant")
|
||||
p.mu.Lock()
|
||||
if p.deleteReserved[volume] {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceLease{}, ErrWorkspaceDeleteReserved
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch {
|
||||
p.mu.Unlock()
|
||||
@@ -353,12 +363,16 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
|
||||
// reusing the forced-move barrier so the old process's validity is past.
|
||||
// The live renewal path releases leaseMu before entering this writer.
|
||||
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
|
||||
p.beforeWorkspaceGrantLock("regrant")
|
||||
// INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt;
|
||||
// a returning process can retry after that writer has settled.
|
||||
if !p.mu.TryLock() {
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: authority writer busy; retry")
|
||||
}
|
||||
defer p.mu.Unlock()
|
||||
if p.deleteReserved[volume] {
|
||||
return WorkspaceLease{}, ErrWorkspaceDeleteReserved
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceLease{}, err
|
||||
}
|
||||
@@ -409,6 +423,7 @@ func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time
|
||||
// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write.
|
||||
func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) {
|
||||
defer p.extWG.Done()
|
||||
p.beforeWorkspaceGrantLock("extension")
|
||||
var note string
|
||||
defer func() {
|
||||
if note != "" {
|
||||
@@ -427,7 +442,7 @@ func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, tr
|
||||
p.leaseMu.Lock()
|
||||
closing := p.leaseClosing
|
||||
p.leaseMu.Unlock()
|
||||
if closing {
|
||||
if closing || p.deleteReserved[volume] {
|
||||
return
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
|
||||
@@ -101,7 +101,7 @@ func TestWorkspaceCleanMoveRecordsNoLostRange(t *testing.T) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7, Holder: "old-node/old", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := WorkspaceMoveRequest{RequestID: "c", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1,
|
||||
|
||||
@@ -3,14 +3,13 @@ package authority
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
|
||||
)
|
||||
|
||||
type regrantStorageView struct{}
|
||||
@@ -22,33 +21,29 @@ func (regrantStorageView) Projection() frontend.Projection {
|
||||
// These component controls obtain the real authority re-grant before opening
|
||||
// the returning file-backed provider. They do not model a second live process.
|
||||
func TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut(t *testing.T) {
|
||||
testWorkspaceRegrantStorage(t, false, false)
|
||||
testWorkspaceRegrantStorage(t)
|
||||
}
|
||||
|
||||
func TestWorkspaceLeaseRegrantCannotUnsealSameEpoch(t *testing.T) {
|
||||
testWorkspaceRegrantStorage(t, true, false)
|
||||
}
|
||||
|
||||
func TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD(t *testing.T) {
|
||||
testWorkspaceRegrantStorage(t, false, true)
|
||||
}
|
||||
|
||||
func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) {
|
||||
// The B-layout equivalents of the removed legacy-only cases are
|
||||
// TestLayoutPlainDetachLostReplyRestartReplaysProof and
|
||||
// TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot.
|
||||
func testWorkspaceRegrantStorage(t *testing.T) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
disk, _ := newTempStore(t)
|
||||
clock := newTestClock()
|
||||
p := newLeasePublisher(t, disk, time.Second, clock)
|
||||
bindAndGrant(t, p, "v", "r")
|
||||
remote := storage.NewMemChunkRemote()
|
||||
fixture := testutil.NewLayoutFixture(t, "v", 64, 4)
|
||||
root := t.TempDir()
|
||||
open := func() *durable.DurableProvider {
|
||||
t.Helper()
|
||||
provider, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
cfg := durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64,
|
||||
BlockSize: 4096, ChunkBlocks: 4,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, regrantStorageView{})
|
||||
}
|
||||
fixture.Configure(&cfg)
|
||||
provider, err := durable.NewDurableProvider(cfg, regrantStorageView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -81,14 +76,9 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write(4096, b) // completed Sync, deliberately absent from the last HEAD
|
||||
if sealed {
|
||||
if _, _, err := first.DetachVolumePlain(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
before, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("HEAD before regrant: found=%v err=%v", found, err)
|
||||
}
|
||||
if err := first.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -97,26 +87,8 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) {
|
||||
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal("returning process could not obtain the authority re-grant", err)
|
||||
}
|
||||
if fresh {
|
||||
root = t.TempDir()
|
||||
b = make([]byte, 4096) // the absent local log cannot be claimed as present
|
||||
}
|
||||
second := open()
|
||||
_, err = second.RecoverVolume(ctx, "v")
|
||||
if sealed {
|
||||
after, readErr := remote.GetHead(ctx)
|
||||
if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || !reflect.DeepEqual(after, before) {
|
||||
t.Fatal("same-epoch re-grant reactivated the seal", after, err, readErr)
|
||||
}
|
||||
blocked, openErr := second.Open(ctx, "v")
|
||||
if openErr != nil {
|
||||
t.Fatal(openErr)
|
||||
}
|
||||
if _, readErr := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) {
|
||||
t.Fatal("sealed re-granted process exposed guest I/O", readErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -130,25 +102,31 @@ func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) {
|
||||
t.Fatal("return lost locally acknowledged bytes", i, err)
|
||||
}
|
||||
}
|
||||
claimed, err := remote.GetHead(ctx)
|
||||
if err != nil || claimed.Gen <= before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.RemoteLSN != before.RemoteLSN {
|
||||
t.Fatal("return served without the new generation fence", claimed, err)
|
||||
claimed, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref)
|
||||
if err != nil || !found || claimed.Gen != before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.ClaimID != before.ClaimID || claimed.Position != before.Position {
|
||||
t.Fatal("same-root return changed the B HEAD before the first cut", claimed, err)
|
||||
}
|
||||
if _, err := second.CaptureVolume(ctx, "v"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
final, err := remote.GetHead(ctx)
|
||||
if fresh {
|
||||
if err != nil || !reflect.DeepEqual(final, claimed) {
|
||||
t.Fatal("empty-root return published bytes/frontier absent from HEAD", final, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || final.RemoteLSN <= before.RemoteLSN {
|
||||
final, found, err := fixture.Catalog.ReadHead(ctx, fixture.Ref)
|
||||
if err != nil || !found || final.Position <= before.Position {
|
||||
t.Fatal("first returning cut did not cover the local log", final, err)
|
||||
}
|
||||
payload, err := remote.Get(ctx, final.Chunks[0].Key)
|
||||
if err != nil || len(payload) < 8192 || !bytes.Equal(payload[:4096], a) || !bytes.Equal(payload[4096:8192], b) {
|
||||
st, err := fixture.Catalog.Store(fixture.Ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch)
|
||||
if err != nil || final.Current == nil {
|
||||
t.Fatal("first cut has no B image", err)
|
||||
}
|
||||
image, err := reader.Open(ctx, *final.Current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chunk, err := image.Chunk(ctx, 0)
|
||||
if err != nil || chunk.Zero || len(chunk.Data) < 8192 || !bytes.Equal(chunk.Data[:4096], a) || !bytes.Equal(chunk.Data[4096:8192], b) {
|
||||
t.Fatal("first cut did not publish the full acknowledged image", err)
|
||||
}
|
||||
}
|
||||
@@ -191,7 +191,7 @@ func TestWorkspaceLeaseSealedAckNeverRegrants(t *testing.T) {
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// ACK is the master's durable evidence for this holder's sealed generation.
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed generation and its
|
||||
// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed image and its
|
||||
// durable ACK remain a clean-move proof after the lease expires overnight.
|
||||
func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
@@ -22,25 +22,20 @@ func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) {
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clock.at(86400)
|
||||
for _, bad := range []WorkspaceHead{
|
||||
{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42},
|
||||
{Gen: 8, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true},
|
||||
{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 43, Detached: true},
|
||||
{Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true},
|
||||
{Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true},
|
||||
} {
|
||||
if _, err := p.MoveWorkspace(ctx, req, bad); err == nil {
|
||||
t.Fatal("same-host move bypassed sealed-generation proof", bad)
|
||||
t.Fatal("same-host move bypassed sealed-image proof", bad)
|
||||
}
|
||||
}
|
||||
forced := req
|
||||
forced.Kind, forced.Force = "forced", true
|
||||
if _, err := p.MoveWorkspace(ctx, forced, head); err == nil {
|
||||
t.Fatal("same-host forced move accepted")
|
||||
}
|
||||
if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("refusal reserved or published authority", line)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A lost local image can rejoin on the same host only through a new epoch
|
||||
// with the same lease barrier and durable loss record as a cross-host move.
|
||||
func TestWorkspaceSameHostForcedMoveRecordsLostRange(t *testing.T) {
|
||||
for _, restart := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "running", true: "reloaded"}[restart], func(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
p, now, barrier := forcedLostRangeFixture(t, disk, restart)
|
||||
req := forcedLostRangeReq
|
||||
req.TargetHost = req.ExpectedHost
|
||||
*now = barrier.Add(-time.Nanosecond)
|
||||
if p.PreviewWorkspaceForcedMove(req).Admitted {
|
||||
t.Fatal("same-host preview bypassed the live lease barrier")
|
||||
}
|
||||
if _, err := p.MoveWorkspace(context.Background(), req, forcedLostRangeHead); err == nil {
|
||||
t.Fatal("same-host forced move bypassed the live lease barrier")
|
||||
}
|
||||
if len(p.WorkspaceLostRanges("v")) != 0 || len(p.WorkspaceState("v").Moves) != 0 {
|
||||
t.Fatal("refused move wrote a loss record or reservation")
|
||||
}
|
||||
*now = barrier.Add(time.Nanosecond)
|
||||
if preview := p.PreviewWorkspaceForcedMove(req); !preview.Admitted {
|
||||
t.Fatalf("same-host recovery preview refused after barrier: %s", preview.Reason)
|
||||
}
|
||||
grant, err := p.MoveWorkspace(context.Background(), req, forcedLostRangeHead)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !grant.Issued || grant.NewEpoch != 2 || grant.OldHost != grant.NewHost {
|
||||
t.Fatalf("wrong same-host successor: %+v", grant)
|
||||
}
|
||||
want := WorkspaceLostRange{RequestID: req.RequestID, NewEpoch: 2, OldReplicaID: "old", OldEpoch: 1, LostAfterLSN: 42, LostUntilNS: barrier.UnixNano()}
|
||||
for _, checked := range []*Publisher{p, NewPublisher(nil, WithStore(disk))} {
|
||||
if got := checked.WorkspaceLostRanges("v"); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("same-host recovery lost the durable loss report: %+v", got)
|
||||
}
|
||||
}
|
||||
if replay, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{}); err != nil || replay != grant {
|
||||
t.Fatalf("same-host replay changed grant: %+v %v", replay, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) {
|
||||
if _, err := p.MoveWorkspace(ctx, req, head); err == nil {
|
||||
t.Fatal("clean without ack")
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err == nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "", RemoteLSN: 0}); err == nil {
|
||||
t.Fatal("unsolicited ack accepted")
|
||||
}
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "old", 1); err != nil {
|
||||
@@ -128,7 +128,7 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) {
|
||||
if err != nil || !lease.Revoking {
|
||||
t.Fatal("revocation not delivered", lease, err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "old", Epoch: 1, HeadGen: 7, Holder: "old-node/old", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad := head
|
||||
@@ -137,9 +137,9 @@ func TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck(t *testing.T) {
|
||||
t.Fatal("attached head accepted")
|
||||
}
|
||||
bad = head
|
||||
bad.Gen++
|
||||
bad.RemoteLSN++
|
||||
if _, err := p.MoveWorkspace(ctx, req, bad); err == nil {
|
||||
t.Fatal("different generation accepted")
|
||||
t.Fatal("different sealed position accepted")
|
||||
}
|
||||
r, err := p.MoveWorkspace(ctx, req, head)
|
||||
if err != nil || r.NewEpoch != 2 || !r.Issued {
|
||||
|
||||
@@ -40,7 +40,7 @@ func cleanMoveToGrantee(t *testing.T, store AuthorityStore, now *time.Time) (*Pu
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 1, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
@@ -145,7 +145,7 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) {
|
||||
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 2); err != nil {
|
||||
t.Fatal("revoke the grantee's issued lease:", err)
|
||||
}
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen}); err != nil {
|
||||
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}, WorkspaceHead{Detached: true, Epoch: 2, Holder: predecessorHead.Holder, RemoteLSN: predecessorHead.RemoteLSN}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clean := forcedFromGrantee("clean-2")
|
||||
|
||||
@@ -49,7 +49,7 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
now = start.Add(tc.elapsed)
|
||||
err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7})
|
||||
err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "host/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "host/r", RemoteLSN: 42})
|
||||
if (err == nil) != tc.allowed {
|
||||
t.Fatalf("ACK allowed=%t, want %t: %v", err == nil, tc.allowed, err)
|
||||
}
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
package chunkstore
|
||||
|
||||
// The JSON bodies of a snapshot listing and a snapshot delete (B9 W2 §3.3,
|
||||
// §3.4), shared by blockvolume's /chunk/* routes and the sw-block CLI, which
|
||||
// reads the filer directly; and the body of `sw-block ops chunk show`.
|
||||
// Snapshot listing and deletion bodies shared by blockvolume's /chunk/*
|
||||
// routes and the sw-block CLI.
|
||||
|
||||
import "github.com/seaweedfs/seaweed-block/core/storage"
|
||||
import "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
|
||||
// SnapshotListItem is one listed snapshot, exactly §3.3's fields.
|
||||
// SnapshotListItem is one listed snapshot.
|
||||
type SnapshotListItem struct {
|
||||
Name string `json:"name"`
|
||||
HeadGen uint64 `json:"headGen"`
|
||||
HeadEpoch uint64 `json:"headEpoch"`
|
||||
CutLSN uint64 `json:"cutLSN"`
|
||||
CreatedNs int64 `json:"createdNs"`
|
||||
State string `json:"state"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Consistency string `json:"consistency"`
|
||||
Parent *Parent `json:"parent"`
|
||||
Class string `json:"class,omitempty"`
|
||||
ExpiresAtNs int64 `json:"expiresAtNs,omitempty"`
|
||||
Root string `json:"root,omitempty"`
|
||||
Dependents []layout.Dependent `json:"dependents,omitempty"`
|
||||
Name string `json:"name"`
|
||||
HeadGen uint64 `json:"headGen"`
|
||||
HeadEpoch uint64 `json:"headEpoch"`
|
||||
CutLSN uint64 `json:"cutLSN"`
|
||||
CreatedNs int64 `json:"createdNs"`
|
||||
State string `json:"state"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Consistency string `json:"consistency"`
|
||||
Parent *Parent `json:"parent"`
|
||||
}
|
||||
|
||||
// SnapshotListBody is a listing page: the snapshots after the request's
|
||||
@@ -32,7 +35,7 @@ type SnapshotListBody struct {
|
||||
func NewSnapshotListBody(vol string, list []SnapshotInfo, next string) SnapshotListBody {
|
||||
body := SnapshotListBody{VolumeID: vol, Snapshots: make([]SnapshotListItem, 0, len(list)), Next: next}
|
||||
for _, s := range list {
|
||||
body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch,
|
||||
body.Snapshots = append(body.Snapshots, SnapshotListItem{Name: s.Name, Root: s.Root, Dependents: s.Dependents, Class: s.Class, ExpiresAtNs: s.ExpiresAtNs, HeadGen: s.HeadGen, HeadEpoch: s.HeadEpoch,
|
||||
CutLSN: s.CutLSN, CreatedNs: s.CreatedNs, State: s.State, ChunkCount: s.ChunkCount, Labels: s.Labels,
|
||||
Consistency: s.Consistency, Parent: s.Parent})
|
||||
}
|
||||
@@ -45,59 +48,3 @@ type SnapshotDeleteBody struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// VolumeShowBody is one volume's VOLUME entry and HEAD (sw-block ops chunk
|
||||
// show); each is null when it does not exist.
|
||||
type VolumeShowBody struct {
|
||||
VolumeID string `json:"volumeID"`
|
||||
Volume *VolumeShow `json:"volume"`
|
||||
Head *HeadShow `json:"head"`
|
||||
}
|
||||
|
||||
// VolumeShow is the VOLUME entry (§4.2).
|
||||
type VolumeShow struct {
|
||||
Origin string `json:"origin"`
|
||||
NumBlocks uint64 `json:"numBlocks"`
|
||||
BlockSize uint32 `json:"blockSize"`
|
||||
ChunkBlocks uint32 `json:"chunkBlocks"`
|
||||
CreatedNs int64 `json:"createdNs"`
|
||||
Parent *Parent `json:"parent"`
|
||||
}
|
||||
|
||||
// HeadShow is the HEAD; a HEAD without a state is active.
|
||||
type HeadShow struct {
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remoteLSN"`
|
||||
State string `json:"state"`
|
||||
DetachedBy *DetachedByShow `json:"detachedBy"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
}
|
||||
|
||||
// DetachedByShow is the detach proof in a detached HEAD.
|
||||
type DetachedByShow struct {
|
||||
Holder string `json:"holder"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Gen uint64 `json:"gen"`
|
||||
}
|
||||
|
||||
// NewVolumeShowBody is vol's show body from what exists.
|
||||
func NewVolumeShowBody(vol string, v *VolumeInfo, h *storage.ChunkHead) VolumeShowBody {
|
||||
body := VolumeShowBody{VolumeID: vol}
|
||||
if v != nil {
|
||||
body.Volume = &VolumeShow{Origin: v.Origin, NumBlocks: v.NumBlocks, BlockSize: v.BlockSize, ChunkBlocks: v.ChunkBlocks,
|
||||
CreatedNs: v.CreatedNs, Parent: v.Parent}
|
||||
}
|
||||
if h != nil {
|
||||
state := h.State
|
||||
if state == "" {
|
||||
state = storage.ChunkHeadActive
|
||||
}
|
||||
body.Head = &HeadShow{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: state, ChunkCount: manifestCount(*h)}
|
||||
if d := h.DetachedBy; d != nil {
|
||||
body.Head.DetachedBy = &DetachedByShow{Holder: d.Holder, Epoch: d.Epoch, Gen: d.Gen}
|
||||
}
|
||||
}
|
||||
return body
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type attachLookupProjection struct{}
|
||||
|
||||
func (attachLookupProjection) Projection() frontend.Projection {
|
||||
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true}
|
||||
}
|
||||
|
||||
// Attach lookup errors fail closed; INV-WS-CLAIM-BEFORE-SERVE-001.
|
||||
// Real gRPC lookup errors pass through SWFS and a fresh durable provider.
|
||||
// An existing HEAD must never become a bootstrap claim or an I/O-ready volume.
|
||||
func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) {
|
||||
for _, code := range []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.PermissionDenied, codes.Internal} {
|
||||
t.Run(code.String(), func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
head := storage.ChunkHead{Gen: 7, Epoch: 3, Holder: "node/r1", State: storage.ChunkHeadActive}
|
||||
entry, err := headEntry(head)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &fakeFilerGRPC{lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: entry}}
|
||||
swfs := startFakeFiler(t, f)
|
||||
remote, err := NewChunkRemote(swfs, newFakeBlobs(), "/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := remote.GetHead(ctx)
|
||||
if err != nil || before.Gen != 7 {
|
||||
t.Fatalf("pre-existing HEAD=%+v error=%v", before, err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
// The absence sentinel inside an Unavailable message is still an error.
|
||||
f.lookupErr = status.Error(code, "lookup failed: "+filerNotFoundText)
|
||||
f.mu.Unlock()
|
||||
if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) {
|
||||
t.Fatalf("failed lookup became an absent HEAD: head=%+v error=%v", h, err)
|
||||
}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16,
|
||||
ChunkHolder: "node/r1",
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, attachLookupProjection{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) {
|
||||
t.Fatalf("attach error=%v; want preserved %s", err, code)
|
||||
}
|
||||
if err := p.AdmitsIO("v1"); err == nil {
|
||||
t.Fatal("failed HEAD lookup admitted guest I/O")
|
||||
}
|
||||
f.mu.Lock()
|
||||
created, updated := f.lastCreate, f.lastUpdate
|
||||
f.lookupErr = nil
|
||||
f.mu.Unlock()
|
||||
if created != nil || updated != nil {
|
||||
t.Fatalf("failed lookup attempted a HEAD CAS: create=%+v update=%+v", created, updated)
|
||||
}
|
||||
after, err := remote.GetHead(ctx)
|
||||
if err != nil || after.Gen != head.Gen || after.Holder != head.Holder || after.Epoch != head.Epoch {
|
||||
t.Fatalf("failed attach changed HEAD: %+v error=%v", after, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,333 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// VolumeRef names a volume as the master's volume record does: its name
|
||||
// and its layout volume id. Its directory is layout.VolumeDir(name, id),
|
||||
// never reused.
|
||||
type VolumeRef struct {
|
||||
Name string
|
||||
ID layout.VolumeID
|
||||
}
|
||||
|
||||
// Dir is the volume's directory name under the store's base.
|
||||
func (v VolumeRef) Dir() string { return layout.VolumeDir(v.Name, v.ID) }
|
||||
|
||||
// BCatalog is the volume catalog on the content-named layout: every
|
||||
// operation is a layout kernel step over the volume's filer store.
|
||||
type BCatalog struct {
|
||||
f Filer
|
||||
b Blobs
|
||||
base string
|
||||
}
|
||||
|
||||
// NewBCatalog returns the catalog of the volumes under base.
|
||||
func NewBCatalog(f Filer, b Blobs, base string) (*BCatalog, error) {
|
||||
if f == nil || b == nil || !path.IsAbs(base) || path.Clean(base) != base {
|
||||
return nil, errors.New("chunkstore: catalog needs a filer, blobs and a clean base")
|
||||
}
|
||||
return &BCatalog{f: f, b: b, base: base}, nil
|
||||
}
|
||||
|
||||
// Store returns the volume's filer store.
|
||||
func (c *BCatalog) Store(v VolumeRef) (*LayoutStore, error) {
|
||||
return NewLayoutStore(c.f, c.b, path.Join(c.base, v.Dir()), v.ID)
|
||||
}
|
||||
|
||||
func (c *BCatalog) open(v VolumeRef) (*LayoutStore, *layout.Reader, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
r, err := layout.NewReader(c.base, v.Dir(), s.Fetch)
|
||||
return s, r, err
|
||||
}
|
||||
|
||||
// CreateVolume creates the volume with its unclaimed HEAD.
|
||||
func (c *BCatalog) CreateVolume(ctx context.Context, v VolumeRef, geometry layout.Geometry) (layout.Head, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
return layout.CreateVolume(ctx, s, layout.Volume{ID: v.ID, Name: v.Name, Format: layout.VolumeFormat, Geometry: geometry})
|
||||
}
|
||||
|
||||
// ReadVolume returns the source's immutable VOLUME record; a restore takes
|
||||
// its geometry from this record rather than operator flags.
|
||||
func (c *BCatalog) ReadVolume(ctx context.Context, v VolumeRef) (layout.Volume, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return layout.Volume{}, err
|
||||
}
|
||||
got, found, err := s.ReadVolumeRecord(ctx)
|
||||
if err != nil {
|
||||
return layout.Volume{}, err
|
||||
}
|
||||
if !found {
|
||||
return layout.Volume{}, layout.ErrMissing
|
||||
}
|
||||
if got.ID != v.ID || got.Name != v.Name {
|
||||
return layout.Volume{}, layout.ErrIdentity
|
||||
}
|
||||
return got, nil
|
||||
}
|
||||
|
||||
// ReadHead reads the volume's HEAD.
|
||||
func (c *BCatalog) ReadHead(ctx context.Context, v VolumeRef) (layout.Head, bool, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return layout.Head{}, false, err
|
||||
}
|
||||
return s.ReadHead(ctx)
|
||||
}
|
||||
|
||||
// DeleteSnapshot removes the named snapshot; refused while it has
|
||||
// dependents.
|
||||
func (c *BCatalog) DeleteSnapshot(ctx context.Context, v VolumeRef, name string) (layout.Head, error) {
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
return layout.RunDeleteSnapshot(ctx, s, name)
|
||||
}
|
||||
|
||||
// Restore creates target from the source's named snapshot: the target is
|
||||
// recorded as the snapshot's dependent, the snapshot's root and segments
|
||||
// are copied into the target's directory, then the target is created with
|
||||
// that root as its current image.
|
||||
func (c *BCatalog) Restore(ctx context.Context, src VolumeRef, snapshot string, target VolumeRef) (layout.Head, error) {
|
||||
ss, sr, err := c.open(src)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
ts, err := c.Store(target)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
copyRoot := func(ctx context.Context, rn layout.RootName) error {
|
||||
raw, err := c.fetchVerified(ctx, ss, src, rn.Path(), rn.Hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := layout.DecodeRoot(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
segs := map[layout.SegName][]byte{}
|
||||
for _, n := range root.Segments {
|
||||
if segs[n], err = c.fetchVerified(ctx, ss, src, n.Path(), n.Hash); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
got, err := layout.PrepareRoot(ctx, ts, root, segs, "restore-"+target.ID.String())
|
||||
if err == nil && got != rn {
|
||||
err = fmt.Errorf("%w: root %s re-encodes as %s", layout.ErrCorrupt, rn, got)
|
||||
}
|
||||
return err
|
||||
}
|
||||
source, found, err := ss.ReadVolumeRecord(ctx)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
if !found {
|
||||
return layout.Head{}, layout.ErrMissing
|
||||
}
|
||||
return layout.CreateTarget(ctx, ss, sr, snapshot, ts, layout.Volume{ID: target.ID, Name: target.Name, Format: layout.VolumeFormat, Geometry: source.Geometry}, copyRoot)
|
||||
}
|
||||
|
||||
func (c *BCatalog) fetchVerified(ctx context.Context, s *LayoutStore, v VolumeRef, rel string, want layout.Hash) ([]byte, error) {
|
||||
p := path.Join(c.base, v.Dir(), rel)
|
||||
raw, found, err := s.Fetch(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("%w: %s", layout.ErrMissing, p)
|
||||
}
|
||||
if layout.Sum(raw) != want {
|
||||
return nil, fmt.Errorf("%w: %s does not hash to its name", layout.ErrCorrupt, p)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
// ReleaseTarget removes target from the source's dependents once the
|
||||
// target is deleted or no longer names the source's chunks (the operator's
|
||||
// remove-dependent; a target without HEAD is tombstoned first).
|
||||
func (c *BCatalog) ReleaseTarget(ctx context.Context, src, target VolumeRef) (layout.Head, error) {
|
||||
ss, err := c.Store(src)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
ts, tr, err := c.open(target)
|
||||
if err != nil {
|
||||
return layout.Head{}, err
|
||||
}
|
||||
return layout.OperatorReleaseDependent(ctx, ss, ts, tr, target.ID)
|
||||
}
|
||||
|
||||
// DeleteVolume deletes the volume in the kernel's order. The sources it is
|
||||
// released from are the volumes its roots name chunks of (read from its
|
||||
// references, never from a name given); its objects are every pool,
|
||||
// segment and root entry in its directory, listed after HEAD is deleting.
|
||||
// A re-run on a deleted volume sweeps any object that landed late.
|
||||
func (c *BCatalog) DeleteVolume(ctx context.Context, v VolumeRef, auth layout.DeleteAuthority) error {
|
||||
s, r, err := c.open(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h, found, err := s.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
return layout.ErrHeadAbsent
|
||||
}
|
||||
owners, err := foreignOwners(ctx, r, h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var sources []layout.HeadStore
|
||||
for _, o := range owners {
|
||||
ss, err := c.Store(o)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sources = append(sources, ss)
|
||||
}
|
||||
list := func(ctx context.Context) ([]string, error) { return c.listObjects(ctx, v) }
|
||||
return layout.DeleteVolume(ctx, s, auth, v.ID, sources, s, list)
|
||||
}
|
||||
|
||||
// foreignOwners returns the volumes, other than h's own, whose chunks a
|
||||
// root in h names, from the references themselves.
|
||||
func foreignOwners(ctx context.Context, r *layout.Reader, h layout.Head) ([]VolumeRef, error) {
|
||||
roots := map[layout.RootName]bool{}
|
||||
if h.Current != nil {
|
||||
roots[*h.Current] = true
|
||||
}
|
||||
for _, s := range h.Snapshots {
|
||||
roots[s.Root] = true
|
||||
}
|
||||
seen := map[VolumeRef]bool{}
|
||||
for rn := range roots {
|
||||
refs, err := rootRefs(ctx, r, rn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if ref.OwnerID != h.VolumeID {
|
||||
seen[VolumeRef{Name: ref.Owner, ID: ref.OwnerID}] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]VolumeRef, 0, len(seen))
|
||||
for o := range seen {
|
||||
out = append(out, o)
|
||||
}
|
||||
sort.Slice(out, func(a, b int) bool { return out[a].Dir() < out[b].Dir() })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// rootRefs returns every chunk reference the root names.
|
||||
func rootRefs(ctx context.Context, r *layout.Reader, rn layout.RootName) ([]layout.Ref, error) {
|
||||
var out []layout.Ref
|
||||
err := r.EachRef(ctx, rn, layout.AllShards, func(_ uint64, ref layout.Ref) bool { out = append(out, ref); return true })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// listObjects lists the volume's pool, segment and root entries.
|
||||
func (c *BCatalog) listObjects(ctx context.Context, v VolumeRef) ([]string, error) {
|
||||
dir := path.Join(c.base, v.Dir())
|
||||
var out []string
|
||||
buckets, err := c.listAll(ctx, path.Join(dir, layout.PoolDir))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, b := range buckets {
|
||||
names, err := c.listAll(ctx, path.Join(dir, layout.PoolDir, b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, n := range names {
|
||||
out = append(out, path.Join(layout.PoolDir, b, n))
|
||||
}
|
||||
}
|
||||
for _, sub := range []string{layout.SegDir, layout.RootDir} {
|
||||
names, err := c.listAll(ctx, path.Join(dir, sub))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, n := range names {
|
||||
out = append(out, path.Join(sub, n))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *BCatalog) listAll(ctx context.Context, dir string) ([]string, error) {
|
||||
var out []string
|
||||
after := ""
|
||||
for {
|
||||
es, err := c.f.ListEntries(ctx, dir, "", after, 1000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range es {
|
||||
out = append(out, e.Name)
|
||||
}
|
||||
if len(es) < 1000 {
|
||||
return out, nil
|
||||
}
|
||||
after = es[len(es)-1].Name
|
||||
}
|
||||
}
|
||||
|
||||
// Usage is what a volume's HEAD holds: its snapshots, their dependents, and
|
||||
// the chunks its current image names, its own and other volumes'.
|
||||
type Usage struct {
|
||||
Snapshots int `json:"snapshots"`
|
||||
Dependents int `json:"dependents"`
|
||||
OwnChunks int `json:"own_chunks"`
|
||||
ForeignChunks int `json:"foreign_chunks"`
|
||||
}
|
||||
|
||||
// Usage reads the volume's usage from its HEAD and current root.
|
||||
func (c *BCatalog) Usage(ctx context.Context, v VolumeRef) (Usage, error) {
|
||||
s, r, err := c.open(v)
|
||||
if err != nil {
|
||||
return Usage{}, err
|
||||
}
|
||||
h, found, err := s.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return Usage{}, err
|
||||
}
|
||||
if !found {
|
||||
return Usage{}, layout.ErrHeadAbsent
|
||||
}
|
||||
u := Usage{Snapshots: len(h.Snapshots)}
|
||||
for _, sn := range h.Snapshots {
|
||||
u.Dependents += len(sn.Dependents)
|
||||
}
|
||||
if h.Current != nil {
|
||||
refs, err := rootRefs(ctx, r, *h.Current)
|
||||
if err != nil {
|
||||
return Usage{}, err
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if ref.OwnerID == h.VolumeID {
|
||||
u.OwnChunks++
|
||||
} else {
|
||||
u.ForeignChunks++
|
||||
}
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
type okDeleteAuthority struct{}
|
||||
|
||||
func (okDeleteAuthority) Reserve(context.Context) error { return nil }
|
||||
func (okDeleteAuthority) NoLiveLease(context.Context) error { return nil }
|
||||
|
||||
// commitSnapshot makes v hold one chunk at index 1 and a snapshot named
|
||||
// name of it, through the kernel's own steps: Start, Begin, objects, Commit.
|
||||
func commitSnapshot(t *testing.T, c *BCatalog, v VolumeRef, data []byte, name string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunBegin(ctx, s, me, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch := layout.NameChunk(1, data)
|
||||
if err := layout.EnsureObject(ctx, s, ch.Path(), data, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: ch}}
|
||||
root, segs, err := layout.Build(next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for n, b := range segs {
|
||||
if err := layout.EnsureObject(ctx, s, n.Path(), b, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rn, rb, err := layout.NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := layout.EnsureObject(ctx, s, rn.Path(), rb, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunCommit(ctx, s, s, v.Name, me, layout.CommitRequest{Session: "s1", Next: next, Position: 1, Snapshot: name}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func newRef(t *testing.T, name string) VolumeRef {
|
||||
t.Helper()
|
||||
id, err := layout.NewVolumeID()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return VolumeRef{Name: name, ID: id}
|
||||
}
|
||||
|
||||
// A restore target reads the source's chunk through its copied root; the
|
||||
// source's snapshot cannot be deleted while the target depends on it; the
|
||||
// target's delete releases it, and then the snapshot deletes.
|
||||
func TestBCatalog_RestoreThenDeleteTheTarget(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src, tgt := newRef(t, "src"), newRef(t, "t")
|
||||
if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte("source chunk")
|
||||
commitSnapshot(t, c, src, data, "daily")
|
||||
|
||||
th, err := c.Restore(ctx, src, "daily", tgt)
|
||||
if err != nil {
|
||||
t.Fatalf("restore: %v", err)
|
||||
}
|
||||
if th.Holder != "" || th.Current == nil {
|
||||
t.Fatalf("target HEAD %+v; want unclaimed with the copied root", th)
|
||||
}
|
||||
ts, tr, err := c.open(tgt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img, err := tr.Open(ctx, *th.Current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := img.Chunk(ctx, 1)
|
||||
if err != nil || string(got.Data) != string(data) || got.Ref.OwnerID != src.ID {
|
||||
t.Fatalf("target reads chunk 1: %+v %v; want the source's bytes", got, err)
|
||||
}
|
||||
if u, err := c.Usage(ctx, tgt); err != nil || u.ForeignChunks != 1 || u.OwnChunks != 0 {
|
||||
t.Fatalf("target usage %+v %v", u, err)
|
||||
}
|
||||
if u, err := c.Usage(ctx, src); err != nil || u.Dependents != 1 || u.OwnChunks != 1 {
|
||||
t.Fatalf("source usage %+v %v", u, err)
|
||||
}
|
||||
if _, err := c.Restore(ctx, src, "daily", tgt); err != nil {
|
||||
t.Fatalf("restore again: %v; want a replay", err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, src, "daily"); !errors.Is(err, layout.ErrHasDependents) {
|
||||
t.Fatalf("delete a depended-on snapshot: %v; want ErrHasDependents", err)
|
||||
}
|
||||
|
||||
if err := c.DeleteVolume(ctx, tgt, okDeleteAuthority{}); err != nil {
|
||||
t.Fatalf("delete the target: %v", err)
|
||||
}
|
||||
if h, _, err := ts.ReadHead(ctx); err != nil || h.State != layout.StateDeleted {
|
||||
t.Fatalf("target HEAD after delete: %+v %v", h, err)
|
||||
}
|
||||
if objs, err := c.listObjects(ctx, tgt); err != nil || len(objs) != 0 {
|
||||
t.Fatalf("target objects after delete: %v %v", objs, err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, src, "daily"); err != nil {
|
||||
t.Fatalf("delete the released snapshot: %v", err)
|
||||
}
|
||||
if v, ok, err := ts.ReadVolumeRecord(ctx); err != nil || !ok || v.ID != tgt.ID {
|
||||
t.Fatalf("target VOLUME after delete: %+v %t %v; want kept", v, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A snapshot of a restore target names the source's chunks, so it cannot
|
||||
// itself be a restore source (dependency depth stays one).
|
||||
func TestBCatalog_RestoreOfARestoreTargetIsRefused(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src, tgt, again := newRef(t, "src"), newRef(t, "t"), newRef(t, "t2")
|
||||
if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commitSnapshot(t, c, src, []byte("x"), "daily")
|
||||
if _, err := c.Restore(ctx, src, "daily", tgt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ts, _ := c.Store(tgt)
|
||||
me := layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
if _, err := layout.Start(ctx, ts, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, _, _ := ts.ReadHead(ctx)
|
||||
if _, err := layout.RunBegin(ctx, ts, me, "s2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img, _ := layout.NewReader("/blocks", tgt.Dir(), ts.Fetch)
|
||||
im, _ := img.Open(ctx, *h.Current)
|
||||
ref, _, _ := im.Resolve(ctx, 1)
|
||||
prev := map[uint64]layout.Ref{1: ref}
|
||||
root, segs, _ := layout.Build(prev)
|
||||
for n, b := range segs {
|
||||
if err := layout.EnsureObject(ctx, ts, n.Path(), b, "s2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rn, rb, _ := layout.NameRoot(root)
|
||||
if err := layout.EnsureObject(ctx, ts, rn.Path(), rb, "s2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunCommit(ctx, ts, ts, tgt.Name, me, layout.CommitRequest{Session: "s2", Prev: prev, Next: prev, Position: 2, Snapshot: "copy"}); err != nil {
|
||||
t.Fatalf("snapshot of the target: %v", err)
|
||||
}
|
||||
if _, err := c.Restore(ctx, tgt, "copy", again); !errors.Is(err, layout.ErrForeignSource) {
|
||||
t.Fatalf("restore from a snapshot naming another volume's chunks: %v; want ErrForeignSource", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A restore target that was never started still names the source's
|
||||
// chunks: the operator's release of it is refused, and the source keeps its
|
||||
// dependent.
|
||||
func TestBCatalog_ReleaseOfAnUnstartedRestoreTargetIsRefused(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := NewBCatalog(newFakeFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src, tgt := newRef(t, "src"), newRef(t, "t")
|
||||
if _, err := c.CreateVolume(ctx, src, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commitSnapshot(t, c, src, []byte("data"), "daily")
|
||||
if _, err := c.Restore(ctx, src, "daily", tgt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.ReleaseTarget(ctx, src, tgt); !errors.Is(err, layout.ErrTargetLive) {
|
||||
t.Fatalf("release of an unstarted restore target: %v; want ErrTargetLive", err)
|
||||
}
|
||||
if h, _, _ := c.ReadHead(ctx, src); len(h.Snapshots["daily"].Dependents) != 1 {
|
||||
t.Fatalf("source dependents after the refused release: %+v", h.Snapshots["daily"].Dependents)
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// errCrashed is what a filer call returns once the process that issued it
|
||||
// is dead.
|
||||
var errCrashed = errors.New("crashed")
|
||||
|
||||
// crashFiler models a blockvolume killed in the middle of a catalog
|
||||
// operation: at the chosen filer call it dies, before or after that call
|
||||
// reaches the filer, and from then on no call of it reaches the filer, so
|
||||
// none of its cleanup runs. Blob calls are not intercepted (snapshot create
|
||||
// writes entries only).
|
||||
type crashFiler struct {
|
||||
manifestFilerBlobs
|
||||
mu sync.Mutex
|
||||
dead bool
|
||||
match func(op, p string) bool // the call at which the process dies
|
||||
after bool // the call reaches the filer, its reply is lost
|
||||
}
|
||||
|
||||
func (c *crashFiler) gate(op, p string) (pass, die bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.dead {
|
||||
return false, false
|
||||
}
|
||||
if c.match(op, p) {
|
||||
c.dead = true
|
||||
return c.after, true
|
||||
}
|
||||
return true, false
|
||||
}
|
||||
|
||||
func (c *crashFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
|
||||
if pass, _ := c.gate("lookup", path.Join(dir, name)); !pass {
|
||||
return nil, errCrashed
|
||||
}
|
||||
return c.manifestFilerBlobs.LookupEntry(ctx, dir, name)
|
||||
}
|
||||
|
||||
func (c *crashFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
pass, die := c.gate("create", path.Join(dir, e.GetName()))
|
||||
if !pass {
|
||||
return errCrashed
|
||||
}
|
||||
err := c.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl)
|
||||
if die {
|
||||
return errCrashed
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *crashFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
|
||||
pass, die := c.gate("update", path.Join(dir, e.GetName()))
|
||||
if !pass {
|
||||
return errCrashed
|
||||
}
|
||||
err := c.manifestFilerBlobs.UpdateEntry(ctx, dir, e, expected)
|
||||
if die {
|
||||
return errCrashed
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *crashFiler) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
|
||||
if pass, _ := c.gate("list", dir); !pass {
|
||||
return nil, errCrashed
|
||||
}
|
||||
return c.manifestFilerBlobs.ListEntries(ctx, dir, prefix, startAfter, limit)
|
||||
}
|
||||
|
||||
func (c *crashFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
|
||||
pass, die := c.gate("delete", path.Join(dir, name))
|
||||
if !pass {
|
||||
return errCrashed
|
||||
}
|
||||
err := c.manifestFilerBlobs.DeleteEntry(ctx, dir, name, expected)
|
||||
if die {
|
||||
return errCrashed
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// TestCatalogRestartAfterAbandonedSnapshot: a snapshot create of s1 whose
|
||||
// process dies at each of its filer steps (after the name record, after the
|
||||
// intent, with the attempt create lost before or after it applied, after the
|
||||
// create before the intent is dropped), then a catalog restarted over the
|
||||
// same filer. Whatever the step:
|
||||
// - the create never answers success unless its attempt entry was
|
||||
// written;
|
||||
// - the list shows s1 only if its attempt entry was written, and then as
|
||||
// the snapshot of the cut HEAD, never a partial one;
|
||||
// - a retry with the same request id completes s1, listed once;
|
||||
// - a new snapshot of another name is taken and listed;
|
||||
// - when s1 is abandoned unpublished, its name record still holds the name
|
||||
// (another request gets snapshot_exists) and blocks volume delete
|
||||
// (volume_has_snapshots), and deleting s1 settles it: the name is free
|
||||
// and the volume delete completes.
|
||||
func TestCatalogRestartAfterAbandonedSnapshot(t *testing.T) {
|
||||
isName := func(p string) bool { return p == path.Join(catBase, "v1", snapNamesDir, "s1") }
|
||||
isIntent := func(p string) bool { return strings.HasPrefix(p, path.Join(catBase, "v1", intentsDir)+"/") }
|
||||
isAttempt := func(p string) bool { return isSnapPath(p, "v1", "s1") }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
op string
|
||||
at func(string) bool
|
||||
after bool
|
||||
published bool // the attempt entry was written before the crash
|
||||
}{
|
||||
{"after the name record", "create", isName, true, false},
|
||||
{"after the intent", "create", isIntent, true, false},
|
||||
{"attempt create lost before it applied", "create", isAttempt, false, false},
|
||||
{"attempt create applied, reply lost", "create", isAttempt, true, true},
|
||||
{"before the intent is dropped", "delete", isIntent, false, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f, b, _, h := deleteFixture(t)
|
||||
ctx := context.Background()
|
||||
detachHead(t, f, b, "v1")
|
||||
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: tc.after,
|
||||
match: func(op, p string) bool { return op == tc.op && tc.at(p) }}
|
||||
dying, err := NewCatalog(crashed, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A crash before the attempt entry is written cannot return success;
|
||||
// once it is written the create has succeeded (the intent drop
|
||||
// after it is best effort), whatever the caller then hears.
|
||||
if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil && !tc.published {
|
||||
t.Fatal("the create returned success although its process died before publishing")
|
||||
}
|
||||
crashed.mu.Lock()
|
||||
died := crashed.dead
|
||||
crashed.mu.Unlock()
|
||||
if !died {
|
||||
t.Fatalf("the create never reached the step %q", tc.name)
|
||||
}
|
||||
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list := func() []SnapshotInfo {
|
||||
t.Helper()
|
||||
l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
switch l := list(); {
|
||||
case !tc.published && len(l) != 0:
|
||||
t.Fatalf("an unpublished snapshot is listed after the restart: %+v", l)
|
||||
case tc.published && (len(l) != 1 || l[0].Name != "s1" || l[0].HeadGen != h.Gen || l[0].State != SnapActive):
|
||||
t.Fatalf("after the restart the list is %+v; want s1 of HEAD gen %d, active", l, h.Gen)
|
||||
}
|
||||
|
||||
if !tc.published {
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); CodeOf(err) != CodeSnapshotExists {
|
||||
t.Fatalf("another request for the abandoned name: %v; want snapshot_exists (the name record holds it)", err)
|
||||
}
|
||||
if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots {
|
||||
t.Fatalf("volume delete with the abandoned name record: %v; want volume_has_snapshots", err)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h)
|
||||
if err != nil || info.Name != "s1" || info.HeadGen != h.Gen {
|
||||
t.Fatalf("retry with the same request id after the restart: %+v %v", info, err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil {
|
||||
t.Fatalf("the next snapshot after the restart: %v", err)
|
||||
}
|
||||
if l := list(); len(l) != 2 || l[0].Name != "s1" || l[1].Name != "s2" {
|
||||
t.Fatalf("after the retry and the next snapshot the list is %+v; want s1, s2 once each", l)
|
||||
}
|
||||
|
||||
for _, name := range []string{"s1", "s2"} {
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", name); err != nil {
|
||||
t.Fatalf("delete %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if l := list(); len(l) != 0 {
|
||||
t.Fatalf("after deleting both the list is %+v", l)
|
||||
}
|
||||
if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed {
|
||||
t.Fatalf("volume delete after the snapshots are deleted: %+v %v", res, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete: an abandoned,
|
||||
// never-published s1 (the process died after its name record) is settled by
|
||||
// deleting it without a retry: the name is then free for another request and
|
||||
// the volume delete is no longer blocked by it.
|
||||
func TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete(t *testing.T) {
|
||||
f, b, _, h := deleteFixture(t)
|
||||
ctx := context.Background()
|
||||
detachHead(t, f, b, "v1")
|
||||
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true,
|
||||
match: func(op, p string) bool { return op == "create" && p == path.Join(catBase, "v1", snapNamesDir, "s1") }}
|
||||
dying, err := NewCatalog(crashed, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil {
|
||||
t.Fatal("the create returned success although its process died")
|
||||
}
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting {
|
||||
t.Fatalf("delete of the abandoned s1: %q %v", st, err)
|
||||
}
|
||||
if l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 {
|
||||
t.Fatalf("list after settling: %+v %v", l, err)
|
||||
}
|
||||
if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed {
|
||||
t.Fatalf("volume delete after settling the abandoned name: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A snapshot or fork copy intent records its publication deadline, and the
|
||||
// publishing create runs under a context bounded by that deadline (W5).
|
||||
// The deadline is now metadata only:
|
||||
// a sweep settles a dead attempt by a tombstone claim (catalog_tombstone).
|
||||
|
||||
func TestCatalog_CopyIntentRecordsItsDeadline(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
t0 := time.Unix(1_800_000_000, 0)
|
||||
c.SetClock(func() time.Time { return t0 })
|
||||
holdFirst(f, catBase+"/v1/snaps/s1/")
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r", SourceReadAt: t0}, h); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("held snapshot create: %v", err)
|
||||
}
|
||||
in := intentsOf(t, f, "v1")
|
||||
if len(in) != 1 || in[0].DeadlineNs != t0.Add(DefaultOpDeadline).UnixNano() {
|
||||
t.Fatalf("snapshot intent %+v; want deadline %d", in, t0.Add(DefaultOpDeadline).UnixNano())
|
||||
}
|
||||
|
||||
f.deferCreate = nil
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
holdFirst(f, catBase+"/v2/HEAD")
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("held fork HEAD create: %v", err)
|
||||
}
|
||||
if fin := intentsOf(t, f, "v2"); len(fin) != 1 || fin[0].DeadlineNs != t0.Add(DefaultOpDeadline).UnixNano() {
|
||||
t.Fatalf("fork intent %+v; want deadline %d", fin, t0.Add(DefaultOpDeadline).UnixNano())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalog_PublishIsBoundedByTheDeadline(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
c.OpDeadline = 300 * time.Millisecond
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s0", RequestID: "r0"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, path string
|
||||
run func() error
|
||||
}{
|
||||
{"snapshot", catBase + "/v1/snaps/s1", func() error {
|
||||
_, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h)
|
||||
return err
|
||||
}},
|
||||
{"fork", catBase + "/v2/HEAD", func() error {
|
||||
_, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s0", Target: "v2", RequestID: "f"})
|
||||
return err
|
||||
}},
|
||||
} {
|
||||
stalled := tc.path
|
||||
f.stallCreate = func(p string) bool { return p == stalled || strings.HasPrefix(p, stalled+"/") }
|
||||
done := make(chan error, 1)
|
||||
start := time.Now()
|
||||
go func() { done <- tc.run() }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if CodeOf(err) != CodeOutcomeUnknown || time.Since(start) > 2*time.Second {
|
||||
t.Fatalf("%s against a filer that never answers: %v after %v; want outcome_unknown by the deadline", tc.name, err, time.Since(start))
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s: the publishing create outlived its deadline (still waiting after 5s)", tc.name)
|
||||
}
|
||||
f.stallCreate = nil
|
||||
}
|
||||
}
|
||||
|
||||
// A delayed source read must not create a target, and an expired attempt
|
||||
// after VOLUME must not create a copy intent, even one it later deletes.
|
||||
func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) {
|
||||
for _, origin := range []string{OriginFork, OriginRestore} {
|
||||
for _, stage := range []string{"source_read", "volume_written", "live"} {
|
||||
t.Run(origin+"/"+stage, func(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
now := time.Unix(1800000000, 0)
|
||||
c.SetClock(func() time.Time { return now })
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := now
|
||||
volumeWrites, intentWrites := 0, 0
|
||||
f.afterLookup = func(p string) {
|
||||
if stage == "source_read" && isSnapPath(p, "v1", "s1") {
|
||||
now = start.Add(DefaultOpDeadline)
|
||||
}
|
||||
}
|
||||
f.beforeCreate = func(p string) {
|
||||
if p == catBase+"/v2/VOLUME" {
|
||||
volumeWrites++
|
||||
if stage == "volume_written" {
|
||||
now = start.Add(DefaultOpDeadline)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(p, catBase+"/v2/intents/") {
|
||||
intentWrites++
|
||||
}
|
||||
}
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
|
||||
var err error
|
||||
if origin == OriginFork {
|
||||
_, err = c.Fork(ctx, req)
|
||||
} else {
|
||||
_, err = c.Restore(ctx, req)
|
||||
}
|
||||
f.afterLookup, f.beforeCreate = nil, nil
|
||||
if stage == "live" {
|
||||
if err != nil || volumeWrites != 1 || intentWrites != 1 {
|
||||
t.Fatalf("live attempt: err=%v VOLUME=%d intents=%d", err, volumeWrites, intentWrites)
|
||||
}
|
||||
return
|
||||
}
|
||||
if CodeOf(err) != CodeDeadlineExceeded {
|
||||
t.Fatalf("expired attempt: %v", err)
|
||||
}
|
||||
wantVolume := 0
|
||||
if stage == "volume_written" {
|
||||
wantVolume = 1
|
||||
}
|
||||
if volumeWrites != wantVolume || intentWrites != 0 {
|
||||
t.Fatalf("expired attempt wrote VOLUME=%d intents=%d; want %d and 0", volumeWrites, intentWrites, wantVolume)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil {
|
||||
t.Fatal("expired attempt published HEAD")
|
||||
}
|
||||
if intents := intentsOf(t, f, "v2"); len(intents) != 0 {
|
||||
t.Fatalf("expired attempt left intents: %+v", intents)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The frozen flat snapshot forces the manifest-upgrade path to create an
|
||||
// intent before uploading its segment; count creates, even if later removed.
|
||||
func TestFork_ExpiredLegacyPreparationWritesNoIntent(t *testing.T) {
|
||||
for _, origin := range []string{OriginFork, OriginRestore} {
|
||||
for _, expired := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("%s/expired=%t", origin, expired), func(t *testing.T) {
|
||||
f, c, r := preF4ForkFixture(t, false)
|
||||
now := time.Unix(1800000000, 0)
|
||||
start := now
|
||||
c.SetClock(func() time.Time { return now })
|
||||
intents := 0
|
||||
f.beforeCreate = func(p string) {
|
||||
if p == catBase+"/v3/VOLUME" && expired {
|
||||
now = start.Add(DefaultOpDeadline)
|
||||
}
|
||||
if strings.HasPrefix(p, catBase+"/v3/intents/") {
|
||||
intents++
|
||||
}
|
||||
}
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "legacy-deadline"}
|
||||
var err error
|
||||
if origin == OriginFork {
|
||||
_, err = c.Fork(context.Background(), req)
|
||||
} else {
|
||||
_, err = c.Restore(context.Background(), req)
|
||||
}
|
||||
f.beforeCreate = nil
|
||||
if expired {
|
||||
if CodeOf(err) != CodeDeadlineExceeded || intents != 0 {
|
||||
t.Fatalf("expired legacy attempt: err=%v intent creates=%d; want deadline and zero", err, intents)
|
||||
}
|
||||
if _, err := f.LookupEntry(context.Background(), catBase+"/v3", headName); err == nil {
|
||||
t.Fatal("expired legacy attempt published HEAD")
|
||||
}
|
||||
} else {
|
||||
if err != nil || intents != 2 {
|
||||
t.Fatalf("live legacy attempt: err=%v intent creates=%d; want success and upgrade+copy intents", err, intents)
|
||||
}
|
||||
dst, err := NewChunkRemote(f, r.b, catBase+"/v3")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertLegacyImage(t, dst)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// Schedules where the filer holds an attempt's create and runs it after the
|
||||
// attempt has returned (second review of #111, P1). The rule (W5): an
|
||||
// attempt deletes only its own intent, and only once its own create is
|
||||
// confirmed or can never apply; never another attempt's, even under the same
|
||||
// request, since that attempt's create may still land.
|
||||
|
||||
// holdFirst makes the filer hold the first create of p (p ending in "/":
|
||||
// the first create under it).
|
||||
func holdFirst(f *fakeFiler, p string) {
|
||||
held := false
|
||||
f.deferCreate = func(q string, _ *filerpb.Entry) bool {
|
||||
if held || !(q == p || strings.HasSuffix(p, "/") && strings.HasPrefix(q, p)) {
|
||||
return false
|
||||
}
|
||||
held = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// holdFirstBehindAnother holds the first create of p and, in the same
|
||||
// moment, lets another attempt of the same request write p (a copy of the
|
||||
// held entry stamped with another attempt id).
|
||||
func holdFirstBehindAnother(f *fakeFiler, p string) {
|
||||
held := false
|
||||
f.deferCreate = func(q string, e *filerpb.Entry) bool {
|
||||
if q != p || held {
|
||||
return false
|
||||
}
|
||||
held = true
|
||||
other := proto.Clone(e).(*filerpb.Entry)
|
||||
other.Extended["swb.attempt"] = []byte("0-00000000000000ff")
|
||||
f.entries[q] = other
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// gcRemove removes an entry, as GC does after a delete.
|
||||
func gcRemove(f *fakeFiler, p string) {
|
||||
f.mu.Lock()
|
||||
delete(f.entries, p)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
// assertKeysProtected fails unless every key is named by an intent of vol.
|
||||
func assertKeysProtected(t *testing.T, f *fakeFiler, vol string, keys []string) {
|
||||
t.Helper()
|
||||
named := map[string]bool{}
|
||||
for _, in := range intentsOf(t, f, vol) {
|
||||
for _, k := range in.Keys {
|
||||
named[k] = true
|
||||
}
|
||||
}
|
||||
for _, k := range keys {
|
||||
if !named[k] {
|
||||
t.Fatalf("key %s of the late entry is named by no intent of %s: GC may delete it", k, vol)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lateSnapshotKeys(t *testing.T, f *fakeFiler, vol, name string) []string {
|
||||
t.Helper()
|
||||
dir := path.Join(catBase, vol, snapsDir)
|
||||
e, err := f.LookupEntry(context.Background(), dir, name)
|
||||
if err != nil {
|
||||
t.Fatalf("the held create did not land: %v", err)
|
||||
}
|
||||
info, _, err := decodeSnap(path.Join(dir, name), e)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sortedKeysOf(info.Head(), "")
|
||||
}
|
||||
|
||||
func lateHeadKeys(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string) []string {
|
||||
t.Helper()
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
h, err := r.GetHead(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("the held HEAD create did not land: %v", err)
|
||||
}
|
||||
return sortedKeysOf(h, "")
|
||||
}
|
||||
|
||||
// Attempt A's snapshot create is held. Retry B of the same request takes
|
||||
// over A's attempt path (the name record names it) and publishes there,
|
||||
// deleting only B's intent. A's held insert can never land: the path is
|
||||
// taken, and attempt paths are never removed, not even by DeleteSnapshot.
|
||||
// A sweep then finds A's attempt published.
|
||||
func TestCatalog_HeldSnapshotCreateKeepsItsIntent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
holdFirst(f, catBase+"/v1/snaps/s1/")
|
||||
req := SnapshotRequest{Name: "s1", RequestID: "r"}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("attempt A, create held: %v, want outcome_unknown", err)
|
||||
}
|
||||
a := intentsOf(t, f, "v1")
|
||||
if len(a) != 1 {
|
||||
t.Fatalf("attempt A left %d intents, want its own", len(a))
|
||||
}
|
||||
attempt := path.Base(snapPath(t, f, "v1", "s1"))
|
||||
if a[0].Holder != "snapshot:v1/s1/"+attempt {
|
||||
t.Fatalf("intent holder %q, want it to name the attempt %s", a[0].Holder, attempt)
|
||||
}
|
||||
if info, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil || info.State != SnapActive {
|
||||
t.Fatalf("retry B: %+v %v", info, err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v1"); len(in) != 1 || in[0].ID != a[0].ID {
|
||||
t.Fatalf("after B: intents %+v, want only A's %s", in, a[0].ID)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := f.releaseDeferredCreates(); n != 0 {
|
||||
t.Fatalf("A's held insert landed (%d applied); its attempt path is held for good", n)
|
||||
}
|
||||
if claimed, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || claimed {
|
||||
t.Fatalf("sweep over A's published attempt: claimed=%v %v; want published", claimed, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A sweep settles a dead attempt by claiming its path with an aborted
|
||||
// tombstone: the late insert fails, the name reads as aborted until it is
|
||||
// deleted, and then the name can be reused.
|
||||
func TestCatalog_SweepTombstonesADeadSnapshotAttempt(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
holdFirst(f, catBase+"/v1/snaps/s1/")
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("attempt with a held create: %v", err)
|
||||
}
|
||||
attempt := path.Base(snapPath(t, f, "v1", "s1"))
|
||||
if claimed, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || !claimed {
|
||||
t.Fatalf("sweep over the dead attempt: claimed=%v %v", claimed, err)
|
||||
}
|
||||
if n := f.releaseDeferredCreates(); n != 0 {
|
||||
t.Fatalf("the dead attempt's late insert landed over the tombstone (%d applied)", n)
|
||||
}
|
||||
if again, err := c.AbortSnapshot(ctx, "v1", "s1", attempt); err != nil || !again {
|
||||
t.Fatalf("a repeated sweep: claimed=%v %v; want the tombstone found", again, err)
|
||||
}
|
||||
for _, include := range []bool{false, true} {
|
||||
if list, _, err := c.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: include}); err != nil || len(list) != 0 {
|
||||
t.Fatalf("list (includeDeleting=%v) shows the aborted attempt: %+v %v", include, list, err)
|
||||
}
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound {
|
||||
t.Fatalf("fork from the aborted attempt: %v; want snapshot_not_found", err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists {
|
||||
t.Fatalf("retry of the aborted request: %v; want snapshot_exists until the name is deleted", err)
|
||||
}
|
||||
if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting {
|
||||
t.Fatalf("delete of the aborted name: %q %v", st, err)
|
||||
}
|
||||
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r2"}, h)
|
||||
if err != nil || info.State != SnapActive {
|
||||
t.Fatalf("snapshot after the name was freed: %+v %v", info, err)
|
||||
}
|
||||
if p := snapPath(t, f, "v1", "s1"); path.Base(p) == attempt {
|
||||
t.Fatal("the new snapshot reused the aborted attempt's path")
|
||||
}
|
||||
}
|
||||
|
||||
// Another request holding the name refuses before any intent is written.
|
||||
func TestCatalog_NameHeldByAnotherRequestWritesNoIntent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
// Another request takes the name between this request's check and its
|
||||
// name record create.
|
||||
f.failCreate = func(p string) error {
|
||||
if p != catBase+"/v1/"+snapNamesDir+"/s1" {
|
||||
return nil
|
||||
}
|
||||
other, _ := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: "v1", Name: "s1", RequestID: "other", Attempt: "1-00000000000000aa"})
|
||||
f.entries[p] = other
|
||||
return ErrExists
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); CodeOf(err) != CodeSnapshotExists {
|
||||
t.Fatalf("name held by another request: %v, want snapshot_exists", err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v1"); len(in) != 0 {
|
||||
t.Fatalf("a refused name left %d intents", len(in))
|
||||
}
|
||||
}
|
||||
|
||||
// Fork: attempt A's HEAD create is held; retry B completes the fork and
|
||||
// deletes only B's intent; a replay C deletes none. The target's HEAD is
|
||||
// later removed; A's held create lands with its qualified keys protected.
|
||||
func TestFork_HeldHeadCreateKeepsItsIntent(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := catBase + "/v2/HEAD"
|
||||
holdFirst(f, p)
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
|
||||
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("attempt A, HEAD create held: %v, want outcome_unknown", err)
|
||||
}
|
||||
a := intentsOf(t, f, "v2")
|
||||
if len(a) != 1 {
|
||||
t.Fatalf("attempt A left %d intents, want its own", len(a))
|
||||
}
|
||||
if res, err := c.Fork(ctx, req); err != nil || res.Replayed {
|
||||
t.Fatalf("retry B: %+v %v", res, err)
|
||||
}
|
||||
if res, err := c.Fork(ctx, req); err != nil || !res.Replayed {
|
||||
t.Fatalf("replay C: %+v %v", res, err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v2"); len(in) != 1 || in[0].ID != a[0].ID {
|
||||
t.Fatalf("after B and C: intents %+v, want only A's %s (A's HEAD create is still held)", in, a[0].ID)
|
||||
}
|
||||
gcRemove(f, p)
|
||||
if n := f.releaseDeferredCreates(); n != 1 {
|
||||
t.Fatalf("A's held HEAD create applied %d times, want 1", n)
|
||||
}
|
||||
assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2"))
|
||||
}
|
||||
|
||||
// Fork: attempt A's HEAD create is held while another attempt writes HEAD.
|
||||
// A reports the completed fork and keeps its own intent.
|
||||
func TestFork_HeldHeadCreateBehindAnotherAttempt(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := catBase + "/v2/HEAD"
|
||||
holdFirstBehindAnother(f, p)
|
||||
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if in := intentsOf(t, f, "v2"); len(in) != 1 {
|
||||
t.Fatalf("attempt A (err %v) left %d intents; its held create needs its own", err, len(in))
|
||||
}
|
||||
if err != nil || !res.Replayed || res.HeadGen != 1 {
|
||||
t.Fatalf("attempt A behind another attempt: %+v %v, want the completed fork", res, err)
|
||||
}
|
||||
gcRemove(f, p)
|
||||
if n := f.releaseDeferredCreates(); n != 1 {
|
||||
t.Fatalf("A's held HEAD create applied %d times, want 1", n)
|
||||
}
|
||||
assertKeysProtected(t, f, "v2", lateHeadKeys(t, f, b, "v2"))
|
||||
}
|
||||
|
||||
// The filer's "already exists" answer to a fork's HEAD create: HEAD is there
|
||||
// (only this request writes it), so the fork is complete and the attempt
|
||||
// deletes its own intent.
|
||||
func TestFork_RefusedHeadCreateDropsItsIntent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
|
||||
if _, err := c.Fork(ctx, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// HEAD is written by another attempt after this attempt finds it absent
|
||||
// and before this attempt's create.
|
||||
p := catBase + "/v2/HEAD"
|
||||
head := f.entries[p]
|
||||
gcRemove(f, p)
|
||||
f.beforeCreate = func(q string) {
|
||||
if path.Dir(q) == catBase+"/v2/intents" {
|
||||
f.entries[p] = head
|
||||
}
|
||||
}
|
||||
res, err := c.Fork(ctx, req)
|
||||
if err != nil || !res.Replayed || res.HeadGen != 1 {
|
||||
t.Fatalf("refused HEAD create: %+v %v, want the completed fork", res, err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v2"); len(in) != 0 {
|
||||
t.Fatalf("a refused HEAD create left %d intents", len(in))
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Interleaved sweeps and name reuse (review of #119 r4): every decision is
|
||||
// taken from ONE read of the entry acted on, and a fork's or snapshot's
|
||||
// success from re-reading the entry it tried to create.
|
||||
|
||||
func abortedHeadEntry(t *testing.T) *filerpb.Entry {
|
||||
t.Helper()
|
||||
he, err := headEntry(storage.ChunkHead{Gen: 1, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadAborted})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return he
|
||||
}
|
||||
|
||||
// A sweep claims the fork's HEAD right after the attach gate's first read:
|
||||
// the gate must not pass the aborted HEAD.
|
||||
func TestEnsureVolume_OneHeadReadDecides(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
holdFirst(f, catBase+"/v2/HEAD")
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("fork with a held HEAD create: %v", err)
|
||||
}
|
||||
tomb := abortedHeadEntry(t)
|
||||
done := false
|
||||
f.afterLookup = func(p string) {
|
||||
if p == catBase+"/v2/HEAD" && !done {
|
||||
done = true
|
||||
f.entries[p] = tomb // the sweep wins right after the first read
|
||||
}
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(err) != CodeForkIncomplete {
|
||||
t.Fatalf("attach with a sweep between reads: %v; want fork_incomplete", err)
|
||||
}
|
||||
f.afterLookup = nil
|
||||
}
|
||||
|
||||
// A sweep claims the fork's HEAD after the fork wrote its intent and before
|
||||
// its HEAD create: the fork lost, so it must not report success.
|
||||
func TestFork_LosesToASweepBeforeItsHeadCreate(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tomb := abortedHeadEntry(t)
|
||||
f.beforeCreate = func(p string) {
|
||||
if path.Dir(p) == catBase+"/v2/intents" {
|
||||
f.entries[catBase+"/v2/HEAD"] = tomb
|
||||
}
|
||||
}
|
||||
if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("fork that lost to a sweep: %+v %v; want target_exists", res, err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v2"); len(in) != 0 {
|
||||
t.Fatalf("a fork that lost to a tombstone left %d intents", len(in))
|
||||
}
|
||||
f.beforeCreate = nil
|
||||
}
|
||||
|
||||
// The name is deleted and reused by another request between a snapshot's
|
||||
// create and its completion: the caller gets its own attempt, not the name's
|
||||
// new owner.
|
||||
func TestCatalog_SnapshotCompletionReadsItsOwnAttempt(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
f.failCreateAfterApply = func(p string) error {
|
||||
if isSnapPath(p, "v1", "s1") {
|
||||
return errTransport // applied; the response is lost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
reused := false
|
||||
f.afterLookup = func(p string) {
|
||||
if reused || !isSnapPath(p, "v1", "s1") {
|
||||
return
|
||||
}
|
||||
reused = true
|
||||
// Meanwhile: the name is deleted and taken by request rB, whose
|
||||
// snapshot carries other labels.
|
||||
attB := "1-00000000000000bb"
|
||||
rec, _ := nameRecordEntry(nameRecord{Format: snapFormat, VolumeID: "v1", Name: "s1", RequestID: "rB", Attempt: attB})
|
||||
f.entries[catBase+"/v1/"+snapNamesDir+"/s1"] = rec
|
||||
other := proto.Clone(f.entries[p]).(*filerpb.Entry)
|
||||
var doc snapDoc
|
||||
_ = json.Unmarshal(other.Content, &doc)
|
||||
doc.RequestID, doc.Labels = "rB", map[string]string{"who": "b"}
|
||||
other.Content, _ = json.Marshal(doc)
|
||||
other.Name = attB
|
||||
other.Extended[extReq] = []byte("rB")
|
||||
f.entries[path.Join(path.Dir(p), attB)] = other
|
||||
}
|
||||
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "rA", Labels: map[string]string{"who": "a"}}, h)
|
||||
if err != nil || info.Labels["who"] != "a" {
|
||||
t.Fatalf("completion after the name was reused: %+v %v; want the caller's own snapshot (labels who=a)", info, err)
|
||||
}
|
||||
f.afterLookup, f.failCreateAfterApply = nil, nil
|
||||
}
|
||||
|
||||
// A sweep's tombstone lands on the attempt path before the create: the
|
||||
// create is refused for good and reported aborted, never as this attempt's.
|
||||
func TestCatalog_SnapshotTombstoneIsNeverThisAttempt(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
f.beforeCreate = func(p string) {
|
||||
if path.Dir(p) != catBase+"/v1/intents" {
|
||||
return
|
||||
}
|
||||
re := f.entries[catBase+"/v1/"+snapNamesDir+"/s1"]
|
||||
attempt := string(re.Extended[extAttempt])
|
||||
tomb, _ := c.abortedSnapEntry("v1", "s1", attempt)
|
||||
f.entries[catBase+"/v1/snaps/s1/"+attempt] = tomb
|
||||
}
|
||||
_, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
|
||||
if CodeOf(err) != CodeSnapshotExists || !strings.Contains(err.Error(), "aborted") {
|
||||
t.Fatalf("create over its own attempt's tombstone: %v; want the aborted refusal", err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v1"); len(in) != 0 {
|
||||
t.Fatalf("an attempt that lost to a tombstone left %d intents", len(in))
|
||||
}
|
||||
f.beforeCreate = nil
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
)
|
||||
|
||||
// TestCatalogReplayOfASnapshotBeingDeletedIsNotSuccess: s1 is created by
|
||||
// request r1, then deleted by a process that dies after marking it deleting
|
||||
// and before freeing its name (the name record still names r1's attempt).
|
||||
// A retry of r1, through a restarted catalog, must not answer success for
|
||||
// the snapshot being deleted, neither from the replay check nor from the
|
||||
// create: both refuse it as snapshot_deleting, and the snapshot stays
|
||||
// deleting and unlisted.
|
||||
func TestCatalogReplayOfASnapshotBeingDeletedIsNotSuccess(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
req := SnapshotRequest{Name: "s1", RequestID: "r1"}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", req, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nameRecord := path.Join(catBase, "v1", snapNamesDir, "s1")
|
||||
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}},
|
||||
match: func(op, p string) bool { return op == "delete" && p == nameRecord }}
|
||||
dying, err := NewCatalog(crashed, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dying.DeleteSnapshot(ctx, "v1", "s1"); err == nil {
|
||||
t.Fatal("the delete returned success although its process died before freeing the name")
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, path.Dir(nameRecord), path.Base(nameRecord)); err != nil {
|
||||
t.Fatalf("the name record should still exist after the crash: %v", err)
|
||||
}
|
||||
|
||||
r, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info, replayed, err := r.SnapshotReplay(ctx, "v1", req); replayed || CodeOf(err) != CodeSnapshotDeleting {
|
||||
t.Errorf("the replay check of a snapshot being deleted: %+v replayed %v, %v; want snapshot_deleting", info, replayed, err)
|
||||
}
|
||||
if info, err := r.CreateSnapshot(ctx, "v1", req, h); CodeOf(err) != CodeSnapshotDeleting {
|
||||
t.Errorf("a retry of the create of a snapshot being deleted: %+v, %v; want snapshot_deleting", info, err)
|
||||
}
|
||||
if l, _, err := r.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 {
|
||||
t.Fatalf("the snapshot being deleted is listed: %+v %v", l, err)
|
||||
}
|
||||
if l, _, err := r.ListSnapshots(ctx, "v1", ListOptions{IncludeDeleting: true}); err != nil || len(l) != 1 || l[0].State != SnapDeleting {
|
||||
t.Fatalf("the snapshot must stay deleting: %+v %v", l, err)
|
||||
}
|
||||
}
|
||||
|
||||
// peerPublishFiler models a peer (an earlier attempt of the same request)
|
||||
// that, just before this create writes the attempt entry, publishes that
|
||||
// same attempt and has it deleted: the create's initial replay check saw the
|
||||
// attempt unpublished, and its exclusive create then finds the peer's entry,
|
||||
// now deleting.
|
||||
type peerPublishFiler struct {
|
||||
manifestFilerBlobs
|
||||
attemptDir string
|
||||
peer func(ctx context.Context, dir string, e *filerpb.Entry)
|
||||
done bool
|
||||
}
|
||||
|
||||
func (p *peerPublishFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
|
||||
if !p.done && dir == p.attemptDir {
|
||||
p.done = true
|
||||
p.peer(ctx, dir, e)
|
||||
}
|
||||
return p.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl)
|
||||
}
|
||||
|
||||
// TestCatalogCreateFindingItsAttemptDeletingIsNotSuccess: r1's first attempt
|
||||
// at s1 died after its name record. A retry of r1 passes the replay check
|
||||
// (the attempt is unpublished) and, as it writes the attempt entry, a peer
|
||||
// with the same request publishes that attempt and deletes it. The retry's
|
||||
// exclusive create finds the peer's entry, now deleting: it must refuse it
|
||||
// as snapshot_deleting, not answer success.
|
||||
func TestCatalogCreateFindingItsAttemptDeletingIsNotSuccess(t *testing.T) {
|
||||
f, b, _, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
req := SnapshotRequest{Name: "s1", RequestID: "r1"}
|
||||
nameRecord := path.Join(catBase, "v1", snapNamesDir, "s1")
|
||||
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true,
|
||||
match: func(op, p string) bool { return op == "create" && p == nameRecord }}
|
||||
dying, err := NewCatalog(crashed, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := dying.CreateSnapshot(ctx, "v1", req, h); err == nil {
|
||||
t.Fatal("the first attempt returned success although its process died after the name record")
|
||||
}
|
||||
|
||||
inner := manifestFilerBlobs{f, gcBlobs{b}}
|
||||
peer, err := NewCatalog(inner, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pf := &peerPublishFiler{manifestFilerBlobs: inner, attemptDir: path.Join(catBase, "v1", snapsDir, "s1")}
|
||||
pf.peer = func(ctx context.Context, dir string, e *filerpb.Entry) {
|
||||
if err := inner.CreateEntry(ctx, dir, e, true); err != nil {
|
||||
t.Errorf("the peer's publish of the same attempt: %v", err)
|
||||
return
|
||||
}
|
||||
if st, err := peer.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting {
|
||||
t.Errorf("the peer's delete: %q %v", st, err)
|
||||
}
|
||||
}
|
||||
r, err := NewCatalog(pf, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info, replayed, err := r.SnapshotReplay(ctx, "v1", req); err != nil || replayed {
|
||||
t.Fatalf("before the retry the replay check must see the attempt unpublished: %+v %v %v", info, replayed, err)
|
||||
}
|
||||
info, err := r.CreateSnapshot(ctx, "v1", req, h)
|
||||
if !pf.done {
|
||||
t.Fatal("the retry never reached the exclusive create of its attempt")
|
||||
}
|
||||
if CodeOf(err) != CodeSnapshotDeleting {
|
||||
t.Fatalf("the retry found its attempt deleting: %+v, %v; want snapshot_deleting", info, err)
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
var errTransport = errors.New("fake: transport error")
|
||||
|
||||
func sha256Of(b []byte) [32]byte { return sha256.Sum256(b) }
|
||||
|
||||
func intentsOf(t *testing.T, f *fakeFiler, vol string) []storage.ChunkIntent {
|
||||
t.Helper()
|
||||
r, _ := NewChunkRemote(f, newFakeBlobs(), catBase+"/"+vol)
|
||||
got, err := r.ListIntents(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func sortedKeysOf(h storage.ChunkHead, qualify string) []string {
|
||||
var out []string
|
||||
for _, k := range headKeys(h) {
|
||||
if qualify != "" && !strings.HasPrefix(k, "@") {
|
||||
k = "@" + qualify + "/" + k
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func sameStrings(a, b []string) bool {
|
||||
sort.Strings(a)
|
||||
sort.Strings(b)
|
||||
return strings.Join(a, "\x00") == strings.Join(b, "\x00")
|
||||
}
|
||||
|
||||
// An uncertain snapshot create keeps the intent that protects the
|
||||
// snapshot's keys (review of #111, P1). A retry with the same
|
||||
// request id publishes the snapshot and deletes only its own intent: from
|
||||
// the catalog's view the first create may still land, so its intent stays
|
||||
// (W5 rule; second review).
|
||||
func TestCatalog_SnapshotUncertainCreateKeepsIntent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
f.failCreate = func(p string) error {
|
||||
if isSnapPath(p, "v1", "s1") {
|
||||
return errTransport
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
|
||||
if CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("uncertain create: %v, want outcome_unknown", err)
|
||||
}
|
||||
in := intentsOf(t, f, "v1")
|
||||
if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "")) {
|
||||
t.Fatalf("after an uncertain create the intent must still protect the snapshot's keys: %+v", in)
|
||||
}
|
||||
f.failCreate = nil
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatalf("retry: %v", err)
|
||||
}
|
||||
if got := intentsOf(t, f, "v1"); len(got) != 1 || got[0].ID != in[0].ID {
|
||||
t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
// A create that applied but lost its response is confirmed by the re-read.
|
||||
func TestCatalog_SnapshotAppliedResponseLostIsConfirmed(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
f.failCreateAfterApply = func(p string) error {
|
||||
if isSnapPath(p, "v1", "s1") {
|
||||
return errTransport
|
||||
}
|
||||
return nil
|
||||
}
|
||||
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h)
|
||||
if err != nil || info.HeadGen != h.Gen {
|
||||
t.Fatalf("applied create with a lost response: %+v %v", info, err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v1"); len(in) != 0 {
|
||||
t.Fatalf("a confirmed snapshot left %d intents", len(in))
|
||||
}
|
||||
}
|
||||
|
||||
// The same for the fork's HEAD create, with the qualified keys protected in
|
||||
// the target.
|
||||
func TestFork_UncertainHeadCreateKeepsIntent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.failCreate = func(p string) error {
|
||||
if p == catBase+"/v2/HEAD" {
|
||||
return errTransport
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("uncertain HEAD create: %v, want outcome_unknown", err)
|
||||
}
|
||||
in := intentsOf(t, f, "v2")
|
||||
if len(in) != 1 || !sameStrings(in[0].Keys, sortedKeysOf(h, "v1")) {
|
||||
t.Fatalf("after an uncertain HEAD create the intent must still protect the qualified keys: %+v", in)
|
||||
}
|
||||
f.failCreate = nil
|
||||
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if err != nil || res.Replayed {
|
||||
t.Fatalf("retry: %+v %v", res, err)
|
||||
}
|
||||
if got := intentsOf(t, f, "v2"); len(got) != 1 || got[0].ID != in[0].ID {
|
||||
t.Fatalf("after the retry: intents %+v, want only the first attempt's %s", got, in[0].ID)
|
||||
}
|
||||
|
||||
// Applied, response lost: confirmed by the re-read.
|
||||
f.failCreateAfterApply = func(p string) error {
|
||||
if p == catBase+"/v3/HEAD" {
|
||||
return errTransport
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "g"}); err != nil {
|
||||
t.Fatalf("applied HEAD create with a lost response: %v", err)
|
||||
}
|
||||
if in := intentsOf(t, f, "v3"); len(in) != 0 {
|
||||
t.Fatalf("a confirmed fork left %d intents", len(in))
|
||||
}
|
||||
}
|
||||
|
||||
// An incomplete fork resumes only onto the image its first attempt bound,
|
||||
// and a request id reused with other parameters is refused (P1).
|
||||
func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.failCreate = func(p string) error {
|
||||
if p == catBase+"/v2/HEAD" {
|
||||
return errTransport
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("first attempt: %v", err)
|
||||
}
|
||||
f.failCreate = nil
|
||||
|
||||
// The same request id with another snapshot is refused.
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("request id reused for another snapshot: %v, want target_exists", err)
|
||||
}
|
||||
|
||||
// Forks do not hold their parent: the delete goes through while the
|
||||
// fork is incomplete, and the image binding below guards the retry.
|
||||
// s1 is deleted and recreated over a newer source image.
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name
|
||||
t.Fatal(err)
|
||||
}
|
||||
r1, _ := NewChunkRemote(f, b, catBase+"/v1")
|
||||
if err := r1.Put(ctx, "chunks/e1/c5/new", chunkBytes(0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 99, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
for k, v := range h.Chunks {
|
||||
next.Chunks[k] = v
|
||||
}
|
||||
next.Chunks[5] = storage.ChunkRef{Key: "chunks/e1/c5/new", SHA256: sha256Of(chunkBytes(0x55))}
|
||||
next, ids, err := r1.PrepareManifest(ctx, h, next, h.ChunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r1.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: 1}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Gen = gen
|
||||
for _, id := range ids {
|
||||
if err := r1.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r-new"}, next); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("resume after the snapshot changed image: %v, want target_exists", err)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, catBase+"/v2", "HEAD"); err == nil {
|
||||
t.Fatal("a fork resumed onto another image and wrote HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// A completed fork replays its recorded result without reading the source:
|
||||
// after the source snapshot is deleting, and after the target advanced (P2).
|
||||
func TestFork_CompletedReplayIndependentOfSource(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if err != nil || !again.Replayed {
|
||||
t.Fatalf("replay after the source snapshot started deleting: %+v %v", again, err)
|
||||
}
|
||||
again.Replayed = false
|
||||
if again != first {
|
||||
t.Fatalf("replayed %+v, recorded %+v", again, first)
|
||||
}
|
||||
// The target's holder advances HEAD; the replay still reports the fork.
|
||||
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
|
||||
cur, _ := r2.GetHead(ctx)
|
||||
adv := cur
|
||||
adv.Epoch, adv.Holder, adv.RemoteLSN = 1, "host-2", 50
|
||||
if _, err := r2.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, adv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
later, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if err != nil || !later.Replayed || later.HeadGen != 1 || later.RemoteLSN != first.RemoteLSN || later.SourceGen != first.SourceGen {
|
||||
t.Fatalf("replay after the target advanced: %+v %v", later, err)
|
||||
}
|
||||
}
|
||||
@@ -1,677 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const catBase = "/swblock/chunks"
|
||||
|
||||
var catGeo = Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}
|
||||
|
||||
// publishSource writes chunks for vol and installs a HEAD (epoch 1,
|
||||
// remote_lsn 42) over the current one (the initial HEAD the VOLUME entry
|
||||
// came with, if any) through the real ChunkRemote; it returns the HEAD.
|
||||
func publishSource(t *testing.T, f *fakeFiler, b *fakeBlobs, vol string, chunks map[uint64][]byte) storage.ChunkHead {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
r, err := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: 42, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
for idx, data := range chunks {
|
||||
key := "chunks/e1/c" + string(rune('0'+idx)) + "/k"
|
||||
if err := r.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Chunks[idx] = storage.ChunkRef{Key: key, SHA256: sha256.Sum256(data)}
|
||||
}
|
||||
cur, err := r.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, intents, err := r.PrepareManifest(ctx, cur, h, uint64(catGeo.BlockSize)*uint64(catGeo.ChunkBlocks))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Gen = gen
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// snapPath is the attempt path the name record of vol/name points at.
|
||||
func snapPath(t *testing.T, f *fakeFiler, vol, name string) string {
|
||||
t.Helper()
|
||||
e, err := f.LookupEntry(context.Background(), path.Join(catBase, vol, snapNamesDir), name)
|
||||
if err != nil {
|
||||
t.Fatalf("name record %s/%s: %v", vol, name, err)
|
||||
}
|
||||
return path.Join(catBase, vol, snapsDir, name, string(e.Extended[extAttempt]))
|
||||
}
|
||||
|
||||
// isSnapPath reports whether p is an attempt path of vol/name.
|
||||
func isSnapPath(p, vol, name string) bool {
|
||||
return strings.HasPrefix(p, path.Join(catBase, vol, snapsDir, name)+"/")
|
||||
}
|
||||
|
||||
func newCat(t *testing.T, f *fakeFiler) *Catalog {
|
||||
t.Helper()
|
||||
c, err := NewCatalog(f, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func chunkBytes(fill byte) []byte {
|
||||
return bytes.Repeat([]byte{fill}, int(catGeo.ChunkBlocks)*int(catGeo.BlockSize))
|
||||
}
|
||||
|
||||
func catalogFixture(t *testing.T) (*fakeFiler, *fakeBlobs, *Catalog, storage.ChunkHead) {
|
||||
t.Helper()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(context.Background(), "v1", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := publishSource(t, f, b, "v1", map[uint64][]byte{0: chunkBytes(0x10), 3: chunkBytes(0x13)})
|
||||
return f, b, c, h
|
||||
}
|
||||
|
||||
func assertNoFilerChunks(t *testing.T, f *fakeFiler) {
|
||||
t.Helper()
|
||||
for _, e := range f.allWritten() {
|
||||
if len(e.Chunks) != 0 {
|
||||
t.Fatalf("entry %q written with filer chunks", e.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalog_SnapshotCreateExclusive(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
s1, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a", Labels: map[string]string{"agent.step": "npm-ci"}}, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s1.Replayed || s1.HeadGen != h.Gen || s1.HeadEpoch != 1 || s1.CutLSN != 42 || s1.ChunkCount != 2 || s1.State != SnapActive || s1.Consistency != "crash" {
|
||||
t.Fatalf("created %+v", s1)
|
||||
}
|
||||
again, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-a"}, h)
|
||||
if err != nil || !again.Replayed || again.HeadGen != s1.HeadGen {
|
||||
t.Fatalf("same request id: %+v %v, want a replay", again, err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req-b"}, h); CodeOf(err) != CodeSnapshotExists {
|
||||
t.Fatalf("other request id: %v, want snapshot_exists", err)
|
||||
}
|
||||
for _, bad := range []string{"", ".hidden", "HEAD", "snaps", "a/b", strings.Repeat("x", 129)} {
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: bad, RequestID: "r"}, h); CodeOf(err) != CodeInvalidName {
|
||||
t.Errorf("name %q: %v, want invalid_name", bad, err)
|
||||
}
|
||||
}
|
||||
assertNoFilerChunks(t, f)
|
||||
// The stored HEAD copy is byte-for-byte the HEAD document.
|
||||
sp := snapPath(t, f, "v1", "s1")
|
||||
e, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp))
|
||||
var doc snapDoc
|
||||
if err := json.Unmarshal(e.Content, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
headEnt, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
|
||||
if !bytes.Equal(doc.Head, headEnt.Content) {
|
||||
t.Fatal("snapshot's head is not the HEAD document")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalog_SnapshotEntryNeverCarriesChunks(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoFilerChunks(t, f)
|
||||
sp := snapPath(t, f, "v1", "s1")
|
||||
f.mu.Lock()
|
||||
f.entries[sp].Chunks = []*filerpb.FileChunk{{FileId: "3,01"}}
|
||||
f.mu.Unlock()
|
||||
if _, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err == nil || CodeOf(err) == CodeSnapshotNotFound {
|
||||
t.Fatalf("a snapshot entry with filer chunks listed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalog_ListPagesAndFilters(t *testing.T) {
|
||||
_, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
for _, n := range []string{"a1", "a2", "b1", "b2", "b3"} {
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: n, RequestID: n}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "b2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names := func(s []SnapshotInfo) string {
|
||||
var out []string
|
||||
for _, x := range s {
|
||||
out = append(out, x.Name)
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
page, next, err := c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2})
|
||||
if err != nil || names(page) != "a1,a2" || next != "a2" {
|
||||
t.Fatalf("page 1: %s next %q %v", names(page), next, err)
|
||||
}
|
||||
page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next})
|
||||
if names(page) != "b1,b3" || next != "b3" {
|
||||
t.Fatalf("page 2 (deleting b2 skipped): %s next %q", names(page), next)
|
||||
}
|
||||
page, next, _ = c.ListSnapshots(ctx, "v1", ListOptions{Limit: 2, StartAfter: next})
|
||||
if names(page) != "" || next != "" {
|
||||
t.Fatalf("page 3: %s next %q", names(page), next)
|
||||
}
|
||||
// A deleted snapshot no longer holds its name, so even includeDeleting
|
||||
// does not list it (its attempt path stays for GC).
|
||||
page, _, _ = c.ListSnapshots(ctx, "v1", ListOptions{Prefix: "b", IncludeDeleting: true})
|
||||
if names(page) != "b1,b3" {
|
||||
t.Fatalf("prefix b with deleting: %s, want the deleted b2 gone with its name", names(page))
|
||||
}
|
||||
if page, _, err := c.ListSnapshots(ctx, "v9", ListOptions{}); err != nil || len(page) != 0 {
|
||||
t.Fatalf("volume without snapshots: %v %v", page, err)
|
||||
}
|
||||
vols, err := c.ListVolumes(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = vols // the fake filer has no directory entries; the real filer is covered by the integration test
|
||||
}
|
||||
|
||||
func TestCatalog_DeleteMarksThenIdempotent(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sp := snapPath(t, f, "v1", "s1")
|
||||
before, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp))
|
||||
f.mu.Lock()
|
||||
deletesBefore := f.deletes
|
||||
f.mu.Unlock()
|
||||
st, err := c.DeleteSnapshot(ctx, "v1", "s1")
|
||||
if err != nil || st != SnapDeleting {
|
||||
t.Fatalf("delete: %q %v", st, err)
|
||||
}
|
||||
after, _ := f.LookupEntry(ctx, path.Dir(sp), path.Base(sp))
|
||||
if !bytes.Equal(before.Content, after.Content) || string(after.Extended[extSnapState]) != SnapDeleting || len(after.Extended[extSnapDeletedNs]) == 0 {
|
||||
t.Fatal("delete must only mark the attempt entry (content unchanged, state deleting, deleted_ns set)")
|
||||
}
|
||||
// The name is freed (its record removed); the attempt path stays.
|
||||
if _, err := f.LookupEntry(ctx, catBase+"/v1/"+snapNamesDir, "s1"); err == nil {
|
||||
t.Fatal("delete left the name record: the name is not freed")
|
||||
}
|
||||
if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapAbsent {
|
||||
t.Fatalf("repeated delete: %q %v, want absent (the name is free)", st, err)
|
||||
}
|
||||
if st, err := c.DeleteSnapshot(ctx, "v1", "nope"); err != nil || st != SnapAbsent {
|
||||
t.Fatalf("delete of a missing snapshot: %q %v", st, err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
removed := f.deletes - deletesBefore
|
||||
f.mu.Unlock()
|
||||
if removed != 1 {
|
||||
t.Fatalf("DeleteSnapshot removed %d entries; it must remove only the name record", removed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFork_HeadIsEpochZeroWithQualifiedKeys(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intentsAtHead := -1
|
||||
f.beforeCreate = func(p string) {
|
||||
if p == catBase+"/v2/HEAD" {
|
||||
intentsAtHead = 0
|
||||
for k := range f.entries {
|
||||
if strings.HasPrefix(k, catBase+"/v2/intents/") {
|
||||
intentsAtHead++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if intentsAtHead != 1 {
|
||||
t.Fatalf("intents in v2 when its HEAD was written: %d, want 1", intentsAtHead)
|
||||
}
|
||||
if got, _ := f.ListEntries(ctx, catBase+"/v2/intents", "", "", 0); len(got) != 0 {
|
||||
t.Fatalf("fork left %d intents", len(got))
|
||||
}
|
||||
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
|
||||
head, err := r2.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if head.Gen != 1 || head.Epoch != 0 || head.Holder != "" || head.RemoteLSN != 42 || len(head.Chunks) != 2 {
|
||||
t.Fatalf("fork HEAD %+v: want gen 1, epoch 0, no holder, the snapshot's remote_lsn 42", head)
|
||||
}
|
||||
for idx, ref := range head.Chunks {
|
||||
src := h.Chunks[idx]
|
||||
if ref.Key != qualifyManifestKey("v1", src.Key) || ref.SHA256 != src.SHA256 {
|
||||
t.Fatalf("chunk %d ref %+v, want @v1/%s with the same hash", idx, ref, src.Key)
|
||||
}
|
||||
}
|
||||
if res.HeadGen != 1 || res.HeadEpoch != 0 || res.QualifiedRefs != 1 || res.ChunkCount != 2 || res.SourceGen != h.Gen || res.RemoteLSN != 42 || res.Replayed {
|
||||
t.Fatalf("result %+v", res)
|
||||
}
|
||||
v, ok, err := c.ReadVolume(ctx, "v2")
|
||||
if err != nil || !ok || v.Origin != OriginFork || v.Geometry != catGeo || v.Parent == nil || v.Parent.VolumeID != "v1" || v.Parent.Snapshot != "s1" || v.Parent.Gen != h.Gen {
|
||||
t.Fatalf("fork VOLUME %+v %v %v", v, ok, err)
|
||||
}
|
||||
again, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-1"})
|
||||
if err != nil || !again.Replayed {
|
||||
t.Fatalf("retried fork: %+v %v", again, err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork-2"}); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("fork onto an existing volume: %v, want target_exists", err)
|
||||
}
|
||||
assertNoFilerChunks(t, f)
|
||||
}
|
||||
|
||||
func TestFork_ForkOfForkKeepsOriginalOwner(t *testing.T) {
|
||||
f, b, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r2, _ := NewChunkRemote(f, b, catBase+"/v2")
|
||||
h2, _ := r2.GetHead(ctx)
|
||||
if _, err := c.CreateSnapshot(ctx, "v2", SnapshotRequest{Name: "t1", RequestID: "r2"}, h2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v2", Snapshot: "t1", Target: "v3", RequestID: "f2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r3, _ := NewChunkRemote(f, b, catBase+"/v3")
|
||||
h3, _ := r3.GetHead(ctx)
|
||||
for idx, ref := range h3.Chunks {
|
||||
if ref.Key != qualifyManifestKey("v1", h.Chunks[idx].Key) {
|
||||
t.Fatalf("second-level fork chunk %d names %q, want the original owner @v1/%s", idx, ref.Key, h.Chunks[idx].Key)
|
||||
}
|
||||
if got, err := r3.Get(ctx, ref.Key); err != nil || sha256.Sum256(got) != ref.SHA256 {
|
||||
t.Fatalf("v3 reads chunk %d through its ref: %v", idx, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFork_RefusalsAndDeadline(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "nope", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound {
|
||||
t.Fatalf("fork of a missing snapshot: %v", err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "gone", RequestID: "g"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, "v1", "gone"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Deleting frees the name: a fork of it finds no snapshot.
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "gone", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeSnapshotNotFound {
|
||||
t.Fatalf("fork of a deleted snapshot: %v, want snapshot_not_found", err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "../x", RequestID: "f"}); CodeOf(err) != CodeInvalidName {
|
||||
t.Fatalf("fork onto a non-plain volume id: %v", err)
|
||||
}
|
||||
// The clock passes OpDeadline between reading the snapshot and the HEAD write.
|
||||
start := time.Unix(1000, 0)
|
||||
calls := 0
|
||||
c.SetClock(func() time.Time {
|
||||
calls++
|
||||
if calls > 2 {
|
||||
return start.Add(DefaultOpDeadline + time.Second)
|
||||
}
|
||||
return start
|
||||
})
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); CodeOf(err) != CodeDeadlineExceeded {
|
||||
t.Fatalf("late fork: %v, want deadline_exceeded", err)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, catBase+"/v4", "HEAD"); err == nil {
|
||||
t.Fatal("a fork past its deadline wrote a HEAD")
|
||||
}
|
||||
c.SetClock(time.Now)
|
||||
// A retry of the expired attempt succeeds under a fresh deadline.
|
||||
if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed {
|
||||
t.Fatalf("retry after the late attempt: %+v %v", res, err)
|
||||
}
|
||||
// A fork whose VOLUME is written but HEAD is not refuses to attach.
|
||||
s1, err := c.readSnap(ctx, "v1", "s1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest, _ := headDigest(s1.Head())
|
||||
vol := VolumeInfo{Format: volumeFormat, VolumeID: "v5", Geometry: catGeo, Origin: OriginFork, Parent: &Parent{VolumeID: "v1", Snapshot: "s1", Gen: h.Gen},
|
||||
Fork: &ForkRecord{RequestID: "crashed", Source: "v1", Snapshot: "s1", SourceGen: h.Gen, HeadSHA256: digest, RemoteLSN: 42, ChunkCount: 2, QualifiedRefs: 2}}
|
||||
ve, _ := volumeEntry(vol, "crashed")
|
||||
if err := f.CreateEntry(ctx, catBase+"/v5", ve, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v5", catGeo); CodeOf(err) != CodeForkIncomplete {
|
||||
t.Fatalf("attach of an incomplete fork: %v, want fork_incomplete", err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v5", RequestID: "crashed"}); err != nil {
|
||||
t.Fatalf("retry completes the crashed fork: %v", err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v5", catGeo); err != nil {
|
||||
t.Fatalf("attach after the fork completed: %v", err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v5", Geometry{NumBlocks: 128, BlockSize: 4096, ChunkBlocks: 8}); CodeOf(err) != CodeGeometryMismatch {
|
||||
t.Fatalf("attach with other geometry: %v, want geometry_mismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
// End to end over the walstore chunk layer: a fork attached as a fresh host
|
||||
// reads exactly the snapshot's image, lazily, through the owner-qualified
|
||||
// refs; its own first cut writes only into its own keys/.
|
||||
func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const blocks, chunkBlocks = 64, 8
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
c := newCat(t, f)
|
||||
geo := Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: chunkBlocks}
|
||||
dir := t.TempDir()
|
||||
attach := func(vol string, fresh bool, epoch uint64) (*storage.WALStore, storage.ChunkLayer) {
|
||||
if _, err := c.EnsureVolume(ctx, vol, geo); err != nil && !fresh {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := filepath.Join(dir, vol)
|
||||
s, err := storage.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh}
|
||||
if fresh {
|
||||
// This low-level fixture bypasses the provider: perform the same
|
||||
// takeover and durable frontier seed before attaching its layer.
|
||||
head, err := storage.ClaimChunkHead(ctx, r, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SeedChunkFrontier(head.RemoteLSN); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
|
||||
}
|
||||
l, err := storage.AttachChunkLayer(s, r, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s, l
|
||||
}
|
||||
src, layer := attach("v1", true, 1) // a new, empty source volume
|
||||
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)
|
||||
}
|
||||
}
|
||||
cut, err := layer.Cut(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, cut.Head); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The source keeps writing after the snapshot; the fork must not see it.
|
||||
if _, err := src.Write(9, bytes.Repeat([]byte{0xee}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Cut(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fork, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dst, dlayer := attach("v2", true, 1)
|
||||
dst.AdvanceFrontier(fork.RemoteLSN) // the fork's log continues from the copied remote_lsn (W4b's job in production)
|
||||
zero := make([]byte, 4096)
|
||||
for lba := uint32(0); lba < blocks; lba++ {
|
||||
got, err := dst.Read(lba)
|
||||
if err != nil {
|
||||
t.Fatalf("fork read %d: %v", lba, err)
|
||||
}
|
||||
exp, ok := want[lba]
|
||||
if !ok {
|
||||
exp = zero
|
||||
}
|
||||
if !bytes.Equal(got, exp) {
|
||||
t.Fatalf("fork block %d = %x..., want the snapshot's %x...", lba, got[:2], exp[:2])
|
||||
}
|
||||
}
|
||||
keysBefore, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0)
|
||||
if _, err := dst.Write(40, bytes.Repeat([]byte{0x40}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r2, err := dlayer.Cut(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("fork's first cut: %v", err)
|
||||
}
|
||||
if r2.Head.Epoch != 1 || r2.Head.RemoteLSN < 1 {
|
||||
t.Fatalf("fork's first HEAD %+v", r2.Head)
|
||||
}
|
||||
keysAfter, _ := f.ListEntries(ctx, catBase+"/v1/keys", "", "", 0)
|
||||
if len(keysAfter) != len(keysBefore) {
|
||||
t.Fatalf("the fork's cut wrote %d keys into the source volume", len(keysAfter)-len(keysBefore))
|
||||
}
|
||||
if own, _ := f.ListEntries(ctx, catBase+"/v2/keys", "", "", 0); len(own) != 2 {
|
||||
t.Fatalf("the fork's cut wrote %d keys of its own, want one data chunk and one manifest", len(own))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalog_SnapshotIntentAroundEntry(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
seen := -1
|
||||
f.beforeCreate = func(p string) {
|
||||
if isSnapPath(p, "v1", "s1") {
|
||||
seen = 0
|
||||
for k := range f.entries {
|
||||
if strings.HasPrefix(k, catBase+"/v1/intents/") {
|
||||
seen++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if seen != 1 {
|
||||
t.Fatalf("intents when the snapshot entry was written: %d, want 1", seen)
|
||||
}
|
||||
if got, _ := f.ListEntries(ctx, catBase+"/v1/intents", "", "", 0); len(got) != 0 {
|
||||
t.Fatalf("snapshot left %d intents", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// The HEAD document carries "state" ("active" by every normal cut) and,
|
||||
// only when detached, "detachedBy" {holder, epoch, gen} naming its own
|
||||
// holder, epoch and generation; a document without "state" reads as active,
|
||||
// and an inconsistent detachedBy is refused.
|
||||
func TestHeadDoc_StateAndDetachedBy(t *testing.T) {
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
r, _ := NewChunkRemote(f, b, catBase+"/v1")
|
||||
ctx := context.Background()
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadActive})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, _ := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
|
||||
if !strings.Contains(string(e.Content), `"state":"active"`) || strings.Contains(string(e.Content), "detachedBy") {
|
||||
t.Fatalf("an active HEAD document: %s", e.Content)
|
||||
}
|
||||
det := storage.ChunkHead{Epoch: 1, Holder: "h", RemoteLSN: 5, Chunks: map[uint64]storage.ChunkRef{}, State: storage.ChunkHeadDetached,
|
||||
DetachedBy: &storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: gen, Epoch: 1}, det); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := r.GetHead(ctx)
|
||||
if err != nil || h.State != storage.ChunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != (storage.ChunkDetachedBy{Holder: "h", Epoch: 1, Gen: gen + 1}) {
|
||||
t.Fatalf("detached HEAD read back as %+v %v", h, err)
|
||||
}
|
||||
|
||||
// An older document without "state" reads as active.
|
||||
e, _ = f.LookupEntry(ctx, catBase+"/v1", "HEAD")
|
||||
var doc map[string]any
|
||||
_ = json.Unmarshal(e.Content, &doc)
|
||||
delete(doc, "state")
|
||||
delete(doc, "detachedBy")
|
||||
old, _ := json.Marshal(doc)
|
||||
f.mu.Lock()
|
||||
f.entries[catBase+"/v1/HEAD"].Content = old
|
||||
f.mu.Unlock()
|
||||
if h, err := r.GetHead(ctx); err != nil || h.State == storage.ChunkHeadDetached {
|
||||
t.Fatalf("a HEAD without state: %+v %v, want active", h, err)
|
||||
}
|
||||
// detachedBy that is not the HEAD's own holder/epoch/gen is refused.
|
||||
doc["state"] = "detached"
|
||||
doc["detachedBy"] = map[string]any{"holder": "h", "epoch": 1, "gen": gen} // stale gen
|
||||
bad, _ := json.Marshal(doc)
|
||||
f.mu.Lock()
|
||||
f.entries[catBase+"/v1/HEAD"].Content = bad
|
||||
f.mu.Unlock()
|
||||
if _, err := r.GetHead(ctx); err == nil {
|
||||
t.Fatal("a detached HEAD with another generation in detachedBy was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// Production serialization end to end: the walstore chunk layer's Detach,
|
||||
// over the SeaweedFS remote, writes HEAD to the filer with exactly the
|
||||
// ruled fields, in one CAS with the final cut.
|
||||
func TestDetach_ProductionSerializedHead(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
p := filepath.Join(t.TempDir(), "v1")
|
||||
s, err := storage.CreateWALStoreWithOptions(p, 64, 4096, storage.WALStoreOptions{ChunkBlocks: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, catBase+"/v1")
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: 8, Epoch: 3, Holder: "host-a"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(9, bytes.Repeat([]byte{9}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := l.Detach(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e, err := f.LookupEntry(ctx, catBase+"/v1", "HEAD")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var doc struct {
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
RemoteLSN uint64 `json:"remote_lsn"`
|
||||
State string `json:"state"`
|
||||
DetachedBy map[string]any `json:"detachedBy"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Content, &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Gen != 1 || doc.State != "detached" || doc.Holder != "host-a" || doc.Epoch != 3 || doc.RemoteLSN != res.H {
|
||||
t.Fatalf("serialized HEAD: %s", e.Content)
|
||||
}
|
||||
if len(doc.DetachedBy) != 3 || doc.DetachedBy["holder"] != "host-a" || doc.DetachedBy["epoch"] != float64(3) || doc.DetachedBy["gen"] != float64(1) {
|
||||
t.Fatalf("serialized detachedBy %v, want exactly {holder host-a, epoch 3, gen 1}", doc.DetachedBy)
|
||||
}
|
||||
if string(e.Extended[extGen]) != "1" || len(e.Chunks) != 0 {
|
||||
t.Fatalf("HEAD entry extended gen %q, filer chunks %d", e.Extended[extGen], len(e.Chunks))
|
||||
}
|
||||
}
|
||||
|
||||
// A created volume gets its initial HEAD with the VOLUME entry (integration
|
||||
// ruling F1): gen 1, epoch 0, no holder, remote_lsn 0, no chunks. An existing
|
||||
// HEAD is kept, and a missing one is created again on the next attach.
|
||||
func TestCatalog_EnsureVolumeCreatesTheInitialHead(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
c := newCat(t, f)
|
||||
if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, ok, err := c.ReadHead(ctx, "v1")
|
||||
if err != nil || !ok || h.Gen != 1 || h.Epoch != 0 || h.Holder != "" || h.RemoteLSN != 0 || len(h.Chunks) != 0 || h.State != storage.ChunkHeadActive {
|
||||
t.Fatalf("initial HEAD: %+v ok=%v %v", h, ok, err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again, _, _ := c.ReadHead(ctx, "v1"); again.Gen != 1 {
|
||||
t.Fatalf("a repeated attach replaced the HEAD: %+v", again)
|
||||
}
|
||||
|
||||
// A volume published before VOLUME entries existed keeps its HEAD.
|
||||
pub := publishSource(t, f, b, "v2", map[uint64][]byte{0: chunkBytes(0x10)})
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept, _, _ := c.ReadHead(ctx, "v2"); kept.Gen != pub.Gen || manifestCount(kept) != 1 || kept.Segments[0] != pub.Segments[0] {
|
||||
t.Fatalf("an existing HEAD was replaced by the initial one: %+v, published %+v", kept, pub)
|
||||
}
|
||||
|
||||
// VOLUME written, HEAD lost before it (an interrupted first attach).
|
||||
f.mu.Lock()
|
||||
delete(f.entries, catBase+"/v1/HEAD")
|
||||
f.mu.Unlock()
|
||||
if _, err := c.EnsureVolume(ctx, "v1", catGeo); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h, ok, _ := c.ReadHead(ctx, "v1"); !ok || h.Gen != 1 {
|
||||
t.Fatalf("the initial HEAD was not created again: %+v ok=%v", h, ok)
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// A sweep settles a dead fork by claiming the target's HEAD, the fork's
|
||||
// publishing entry, with an aborted HEAD tombstone (W5): the late HEAD
|
||||
// insert fails, a retry is refused, and the volume
|
||||
// never attaches.
|
||||
func TestFork_SweepTombstonesADeadFork(t *testing.T) {
|
||||
f, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
holdFirst(f, catBase+"/v2/HEAD")
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
|
||||
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeOutcomeUnknown {
|
||||
t.Fatalf("fork with a held HEAD create: %v", err)
|
||||
}
|
||||
if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed {
|
||||
t.Fatalf("sweep over the dead fork: claimed=%v %v", claimed, err)
|
||||
}
|
||||
if n := f.releaseDeferredCreates(); n != 0 {
|
||||
t.Fatalf("the dead fork's late HEAD landed over the tombstone (%d applied)", n)
|
||||
}
|
||||
if again, err := c.AbortFork(ctx, "v2"); err != nil || !again {
|
||||
t.Fatalf("a repeated sweep: claimed=%v %v; want the tombstone found", again, err)
|
||||
}
|
||||
if hd, ok, err := c.ReadHead(ctx, "v2"); err != nil || !ok || hd.State != storage.ChunkHeadAborted || len(hd.Chunks) != 0 {
|
||||
t.Fatalf("target HEAD after the sweep: %+v ok=%v %v", hd, ok, err)
|
||||
}
|
||||
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeTargetExists {
|
||||
t.Fatalf("retry of the aborted fork: %v; want target_exists", err)
|
||||
}
|
||||
if _, err := c.EnsureVolume(ctx, "v2", catGeo); CodeOf(err) != CodeForkIncomplete {
|
||||
t.Fatalf("attach of the aborted fork: %v; want fork_incomplete", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The tombstone loses to a published fork: the fork's keys are reachable
|
||||
// through its HEAD, and its replay still works.
|
||||
func TestFork_TombstoneLosesToPublishedFork(t *testing.T) {
|
||||
_, _, c, h := catalogFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
|
||||
if _, err := c.Fork(ctx, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := c.AbortFork(ctx, "v2"); err != nil || claimed {
|
||||
t.Fatalf("sweep over a published fork: claimed=%v %v; want published", claimed, err)
|
||||
}
|
||||
if res, err := c.Fork(ctx, req); err != nil || !res.Replayed {
|
||||
t.Fatalf("replay after a refused sweep: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
@@ -1,645 +0,0 @@
|
||||
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
|
||||
// <root>/intents/<id> one entry per live intent (<gen>-<nonce>): the keys a
|
||||
// holder is about to publish; GC treats them as roots
|
||||
//
|
||||
// The chunk layer names chunks itself (immutable keys) while SeaweedFS
|
||||
// assigns needle ids, so a key entry binds the two.
|
||||
//
|
||||
// A key may be owner-qualified, "@<owner>/<key>": the binding then lives in
|
||||
// the owner volume's keys/ directory, <base>/<owner>/keys/, where <base> is
|
||||
// the parent of this volume's root. A fork's HEAD names its parent's chunks
|
||||
// this way, so the fork shares them without copying any binding. The layer
|
||||
// never generates a key starting with "@"; Get resolves qualified keys and
|
||||
// Put refuses them (a volume only ever writes its own keys). 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"
|
||||
"strings"
|
||||
"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"
|
||||
kindChunkIntent = "chunkintent"
|
||||
|
||||
headName = "HEAD"
|
||||
keysDir = "keys"
|
||||
intentsDir = "intents"
|
||||
|
||||
// intentFormat is the only intent document format this code reads.
|
||||
intentFormat = 1
|
||||
// listPage is the page size of a full directory listing.
|
||||
listPage = 1000
|
||||
|
||||
// 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
|
||||
|
||||
assigns assignCounters // reservations made by upload rounds
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// CheckVolumeID accepts a volume id that is one plain path element, so a
|
||||
// volume's directory, or a qualified key's owner, stays inside the base.
|
||||
func CheckVolumeID(id string) error {
|
||||
if id == "" || id == "." || id == ".." || strings.ContainsAny(id, "/\\") {
|
||||
return fmt.Errorf("chunkstore: volume id %q is not a plain path element", id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keyLocation returns the directory and entry name holding key's binding:
|
||||
// the owner's keys/ directory for "@<owner>/<key>", this volume's otherwise.
|
||||
func (r *ChunkRemote) keyLocation(key string) (dir, name string, err error) {
|
||||
if err := storage.ValidChunkKey(key); err != nil {
|
||||
return "", "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
||||
}
|
||||
if !strings.HasPrefix(key, "@") {
|
||||
name, err := keyName(key)
|
||||
return r.keyDir(), name, err
|
||||
}
|
||||
owner, own, ok := strings.Cut(key[1:], "/")
|
||||
if !ok || own == "" {
|
||||
return "", "", fmt.Errorf("%w: %q is not \"@<owner>/<key>\"", ErrInvalidKey, key)
|
||||
}
|
||||
if err := CheckVolumeID(owner); err != nil {
|
||||
return "", "", fmt.Errorf("%w: %q: %v", ErrInvalidKey, key, err)
|
||||
}
|
||||
return path.Join(path.Dir(r.root), owner, keysDir), url.PathEscape(own), nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return r.putObject(ctx, key, data, "")
|
||||
}
|
||||
|
||||
func (r *ChunkRemote) putObject(ctx context.Context, key string, data []byte, object string) error {
|
||||
name, err := r.ownKeyName(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.knownKey(key) {
|
||||
return storage.ErrChunkKeyExists
|
||||
}
|
||||
fid, err := r.b.Put(ctx, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.bindKey(ctx, key, name, fid, data, object)
|
||||
}
|
||||
|
||||
// ownKeyName checks that key is one of this volume's own keys and returns
|
||||
// its binding's entry name.
|
||||
func (r *ChunkRemote) ownKeyName(key string) (string, error) {
|
||||
if err := storage.ValidChunkKey(key); err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
||||
}
|
||||
if strings.HasPrefix(key, "@") {
|
||||
return "", fmt.Errorf("%w: %q is owner-qualified; a volume writes only its own keys", ErrInvalidKey, key)
|
||||
}
|
||||
return keyName(key)
|
||||
}
|
||||
|
||||
// knownKey reports whether key is already bound (as far as this remote saw).
|
||||
func (r *ChunkRemote) knownKey(key string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
_, known := r.fids[key]
|
||||
return known
|
||||
}
|
||||
|
||||
// bindKey binds key to the stored needle fid with an exclusive create.
|
||||
func (r *ChunkRemote) bindKey(ctx context.Context, key, name, fid string, data []byte, object string) error {
|
||||
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 object == "segment" {
|
||||
e.Extended["swb.object"] = []byte("segment")
|
||||
e.Attributes.FileSize = uint64(len(data))
|
||||
}
|
||||
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) {
|
||||
dir, name, err := r.keyLocation(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, dir, 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)
|
||||
}
|
||||
|
||||
// ReclaimKey deletes the needle bound to one of this volume's own keys
|
||||
// with GC's step (reclaimBinding): the binding is tombstoned, the exact fid
|
||||
// deleted, the binding kept for ever and marked done. It decides nothing:
|
||||
// the caller must know that no HEAD, snapshot, fork or intent references
|
||||
// key. An owner-qualified key is refused.
|
||||
func (r *ChunkRemote) ReclaimKey(ctx context.Context, key string, blobs BlobDeleter) error {
|
||||
if err := storage.ValidChunkKey(key); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
||||
}
|
||||
if strings.HasPrefix(key, "@") {
|
||||
return fmt.Errorf("%w: %q is owner-qualified; a volume reclaims only its own keys", ErrInvalidKey, key)
|
||||
}
|
||||
name, err := keyName(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e, err := r.f.LookupEntry(ctx, r.keyDir(), name)
|
||||
if err != nil {
|
||||
return 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 fmt.Errorf("chunkstore: chunk key %q: entry is not a chunk key binding", key)
|
||||
}
|
||||
return reclaimBinding(ctx, r.f, blobs, r.keyDir(), e)
|
||||
}
|
||||
|
||||
// Delete is not supported; see ErrDeleteUnsupported.
|
||||
func (r *ChunkRemote) Delete(context.Context, string) error { return ErrDeleteUnsupported }
|
||||
|
||||
type intentDoc struct {
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
Format int `json:"format"`
|
||||
Gen uint64 `json:"gen"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Holder string `json:"holder"`
|
||||
Keys []string `json:"keys"`
|
||||
CreatedNs int64 `json:"created_ns"`
|
||||
// DeadlineNs: a copy intent's publication deadline (0: a capture intent).
|
||||
DeadlineNs int64 `json:"deadline_ns,omitempty"`
|
||||
}
|
||||
|
||||
func (r *ChunkRemote) intentDir() string { return path.Join(r.root, intentsDir) }
|
||||
|
||||
// PutIntent writes <root>/intents/<gen>-<nonce> with an exclusive create.
|
||||
// The entry is durable when the filer's fsync rule covers the chunk path,
|
||||
// the same condition as for HEAD.
|
||||
func (r *ChunkRemote) PutIntent(ctx context.Context, in storage.ChunkIntent) (string, error) {
|
||||
return putIntent(ctx, r.f, r.root, in)
|
||||
}
|
||||
|
||||
// putIntent writes an intent under <root>/intents/; the catalog uses it for
|
||||
// snapshots and forks, which have no ChunkRemote.
|
||||
func putIntent(ctx context.Context, f Filer, root string, in storage.ChunkIntent) (string, error) {
|
||||
for _, k := range in.Keys {
|
||||
if err := storage.ValidChunkKey(k); err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
||||
}
|
||||
}
|
||||
id, err := storage.NewChunkIntentID(in.Gen)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
now := time.Now()
|
||||
body, err := json.Marshal(intentDoc{Format: intentFormat, Gen: in.Gen, Epoch: in.Epoch, Holder: in.Holder, Keys: in.Keys, CreatedNs: now.UnixNano(), DeadlineNs: in.DeadlineNs, Segments: in.Segments, ChunkBytes: in.ChunkBytes})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
e := &filerpb.Entry{
|
||||
Name: id,
|
||||
Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Mtime: now.Unix(), Crtime: now.Unix(), FileMode: 0o644, Mime: "application/json"},
|
||||
Extended: map[string][]byte{
|
||||
extKind: []byte(kindChunkIntent),
|
||||
extGen: []byte(strconv.FormatUint(in.Gen, 10)),
|
||||
extEpoch: []byte(strconv.FormatUint(in.Epoch, 10)),
|
||||
extHolder: []byte(in.Holder),
|
||||
},
|
||||
Content: body,
|
||||
}
|
||||
if err := f.CreateEntry(ctx, path.Join(root, intentsDir), e, true); err != nil {
|
||||
return "", fmt.Errorf("chunkstore: put intent %s: %w", id, err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// DeleteIntent removes <root>/intents/<id> and nothing else; a missing
|
||||
// intent is not an error.
|
||||
func (r *ChunkRemote) DeleteIntent(ctx context.Context, id string) error {
|
||||
if !storage.ValidChunkIntentID(id) {
|
||||
return fmt.Errorf("chunkstore: intent id %q is not \"<gen>-<nonce>\"", id)
|
||||
}
|
||||
return r.f.DeleteEntry(ctx, r.intentDir(), id, nil)
|
||||
}
|
||||
|
||||
// ListIntents lists every entry under <root>/intents/. An entry that is not
|
||||
// a well-formed intent fails the listing, so GC never misses a root.
|
||||
func (r *ChunkRemote) ListIntents(ctx context.Context) ([]storage.ChunkIntent, error) {
|
||||
var out []storage.ChunkIntent
|
||||
after := ""
|
||||
for {
|
||||
page, err := r.f.ListEntries(ctx, r.intentDir(), "", after, listPage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range page {
|
||||
in, err := decodeIntent(path.Join(r.intentDir(), e.GetName()), e)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, in)
|
||||
}
|
||||
if len(page) < listPage {
|
||||
return out, nil
|
||||
}
|
||||
after = page[len(page)-1].GetName()
|
||||
}
|
||||
}
|
||||
|
||||
func decodeIntent(p string, e *filerpb.Entry) (storage.ChunkIntent, error) {
|
||||
fail := func(format string, a ...any) (storage.ChunkIntent, error) {
|
||||
return storage.ChunkIntent{}, fmt.Errorf("chunkstore: intent %s: "+format, append([]any{p}, a...)...)
|
||||
}
|
||||
if len(e.GetChunks()) != 0 {
|
||||
return fail("carries %d filer chunks", len(e.Chunks))
|
||||
}
|
||||
if k := string(e.Extended[extKind]); k != kindChunkIntent {
|
||||
return fail("kind %q, want %q", k, kindChunkIntent)
|
||||
}
|
||||
if !storage.ValidChunkIntentID(e.GetName()) {
|
||||
return fail("name is not \"<gen>-<nonce>\"")
|
||||
}
|
||||
var doc intentDoc
|
||||
if err := json.Unmarshal(e.GetContent(), &doc); err != nil {
|
||||
return fail("decode: %v", err)
|
||||
}
|
||||
if doc.Format != intentFormat {
|
||||
return fail("format %d not supported (want %d)", doc.Format, intentFormat)
|
||||
}
|
||||
if !strings.HasPrefix(e.GetName(), strconv.FormatUint(doc.Gen, 10)+"-") ||
|
||||
string(e.Extended[extEpoch]) != strconv.FormatUint(doc.Epoch, 10) || string(e.Extended[extHolder]) != doc.Holder {
|
||||
return fail("name or extended gen/epoch/holder disagree with the document")
|
||||
}
|
||||
return storage.ChunkIntent{ID: e.GetName(), Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder,
|
||||
Keys: append([]string(nil), doc.Keys...), CreatedNs: doc.CreatedNs, DeadlineNs: doc.DeadlineNs, Segments: doc.Segments, ChunkBytes: doc.ChunkBytes}, nil
|
||||
}
|
||||
|
||||
type headDoc struct {
|
||||
Levels int `json:"levels,omitempty"`
|
||||
Segments map[uint64]storage.ChunkSegment `json:"segments,omitempty"`
|
||||
ChunkBytes uint64 `json:"chunk_bytes,omitempty"`
|
||||
ChunkCount int `json:"chunk_count,omitempty"`
|
||||
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,omitempty"`
|
||||
// State is "active" or "detached"; a document without it is active.
|
||||
// DetachedBy names the holder whose final cut (this generation) a
|
||||
// detached HEAD is; it is absent unless State is detached.
|
||||
State string `json:"state,omitempty"`
|
||||
DetachedBy *detachedByDoc `json:"detachedBy,omitempty"`
|
||||
}
|
||||
|
||||
type detachedByDoc struct {
|
||||
Holder string `json:"holder"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
Gen uint64 `json:"gen"`
|
||||
}
|
||||
|
||||
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) {
|
||||
h, err := r.getHeadRoot(ctx)
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
return r.resolveManifest(ctx, h)
|
||||
}
|
||||
|
||||
// GetHeadRoot validates publication identity without reading segment bodies.
|
||||
func (r *ChunkRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
|
||||
return r.getHeadRoot(ctx)
|
||||
}
|
||||
|
||||
// getHeadRoot validates the root and its CAS attributes without reading any
|
||||
// immutable segment. CASHead only needs authority and lineage from this root.
|
||||
func (r *ChunkRemote) getHeadRoot(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
|
||||
}
|
||||
// Read the LSN under the same generation/epoch guard used by UpdateEntry.
|
||||
// A competing write after this read makes the conditional update fail;
|
||||
// no successful CAS can lower the committed lineage frontier.
|
||||
current, err := r.getHeadRoot(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if current.State == storage.ChunkHeadDeleting || current.State == storage.ChunkHeadPurging || current.State == storage.ChunkHeadDeleted {
|
||||
// A delete passed its linearization point: nothing moves this HEAD
|
||||
// again (the catalog writes the delete's own transitions).
|
||||
return 0, fmt.Errorf("%w: %w", storage.ErrChunkHeadPrecondition, storage.ErrChunkHeadDeleted)
|
||||
}
|
||||
if current.Gen != expected.Gen || current.Epoch != expected.Epoch || next.RemoteLSN < current.RemoteLSN {
|
||||
return 0, storage.ErrChunkHeadPrecondition
|
||||
}
|
||||
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,
|
||||
State: h.State}
|
||||
if h.DetachedBy != nil {
|
||||
doc.DetachedBy = &detachedByDoc{Holder: h.DetachedBy.Holder, Epoch: h.DetachedBy.Epoch, Gen: h.DetachedBy.Gen}
|
||||
}
|
||||
if h.Segments == nil {
|
||||
if len(h.Chunks) != 0 {
|
||||
return nil, errors.New("chunkstore: data HEAD requires a segmented manifest and geometry")
|
||||
}
|
||||
doc.Chunks = map[uint64]refDoc{}
|
||||
}
|
||||
if h.Segments != nil {
|
||||
if err := validateRoot(h); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Format = 3
|
||||
doc.Levels = 1
|
||||
doc.Chunks = nil
|
||||
doc.Segments = h.Segments
|
||||
doc.ChunkBytes = h.ChunkBytes
|
||||
doc.ChunkCount = h.ManifestChunkCount
|
||||
}
|
||||
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)
|
||||
}
|
||||
h, err := decodeHeadDoc(p, e.GetContent())
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
// 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(h.Gen, 10) ||
|
||||
string(e.Extended[extEpoch]) != strconv.FormatUint(h.Epoch, 10) ||
|
||||
string(e.Extended[extHolder]) != h.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], h.Gen, h.Epoch, h.Holder)
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
// decodeHeadDoc decodes and checks a HEAD document: HEAD's own content, or
|
||||
// the copy a snapshot embeds.
|
||||
func decodeHeadDoc(p string, content []byte) (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...)...)
|
||||
}
|
||||
doc, err := decodeFormatHead(content)
|
||||
if err != nil {
|
||||
return fail("decode: %v", err)
|
||||
}
|
||||
if doc.Gen == 0 {
|
||||
return fail("generation 0")
|
||||
}
|
||||
switch doc.State {
|
||||
case "", storage.ChunkHeadActive:
|
||||
if doc.DetachedBy != nil {
|
||||
return fail("detachedBy on a HEAD that is not detached")
|
||||
}
|
||||
case storage.ChunkHeadAborted:
|
||||
// A sweep's tombstone over a dead fork's HEAD (gen 1, no chunks).
|
||||
if doc.DetachedBy != nil || len(doc.Chunks) != 0 {
|
||||
return fail("an aborted HEAD with content")
|
||||
}
|
||||
case storage.ChunkHeadDeleting, storage.ChunkHeadPurging:
|
||||
// A delete's mark over the HEAD it read (deleting: still revertible;
|
||||
// purging: committed): content and any detach record kept.
|
||||
case storage.ChunkHeadDeleted:
|
||||
// A deleted volume's tombstone (no chunks, no holder).
|
||||
if doc.DetachedBy != nil || len(doc.Chunks) != 0 || doc.Holder != "" {
|
||||
return fail("a deleted HEAD with content")
|
||||
}
|
||||
case storage.ChunkHeadDetached:
|
||||
d := doc.DetachedBy
|
||||
if d == nil || d.Gen != doc.Gen || d.Holder != doc.Holder || d.Epoch != doc.Epoch {
|
||||
return fail("detached HEAD whose detachedBy %+v is not its own holder, epoch and generation", d)
|
||||
}
|
||||
default:
|
||||
return fail("state %q", doc.State)
|
||||
}
|
||||
h := storage.ChunkHead{Gen: doc.Gen, Epoch: doc.Epoch, Holder: doc.Holder, RemoteLSN: doc.RemoteLSN,
|
||||
Chunks: make(map[uint64]storage.ChunkRef, len(doc.Chunks)), State: doc.State}
|
||||
if doc.DetachedBy != nil {
|
||||
h.DetachedBy = &storage.ChunkDetachedBy{Holder: doc.DetachedBy.Holder, Epoch: doc.DetachedBy.Epoch, Gen: doc.DetachedBy.Gen}
|
||||
}
|
||||
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, Encoding: "full", BirthLSN: doc.RemoteLSN}
|
||||
copy(cr.SHA256[:], sum)
|
||||
h.Chunks[idx] = cr
|
||||
}
|
||||
if doc.Format == 2 || doc.Format == 3 {
|
||||
if len(doc.Chunks) != 0 {
|
||||
return fail("segmented root contains flat chunks")
|
||||
}
|
||||
h.Segments = doc.Segments
|
||||
if h.Segments == nil {
|
||||
h.Segments = map[uint64]storage.ChunkSegment{}
|
||||
}
|
||||
h.ChunkBytes = doc.ChunkBytes
|
||||
h.ManifestChunkCount = doc.ChunkCount
|
||||
if err := validateRoot(h); err != nil {
|
||||
return h, err
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
// DecodeHeadDocument validates a persisted flat or segmented root without
|
||||
// fetching data. Control-plane readers share the same representation checks.
|
||||
func DecodeHeadDocument(name string, body []byte) (storage.ChunkHead, error) {
|
||||
return decodeHeadDoc(name, body)
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
//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()
|
||||
return startWeedWith(t, "")
|
||||
}
|
||||
|
||||
// startWeedWith starts the cluster with security (the contents of a
|
||||
// security.toml in its working directory; "" for none).
|
||||
func startWeedWith(t *testing.T, security string) *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)
|
||||
}
|
||||
}
|
||||
if security != "" {
|
||||
if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(security), 0o600); 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
|
||||
}
|
||||
|
||||
// publishIntegrationHead uses the real format-3 manifest path before publishing data.
|
||||
func publishIntegrationHead(t *testing.T, r *ChunkRemote, base, next storage.ChunkHead, chunkBytes uint64) storage.ChunkHead {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
next, intents, err := r.PrepareManifest(ctx, base, next, chunkBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next.Gen, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: base.Gen, Epoch: base.Epoch}, next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next.Gen != base.Gen+1 {
|
||||
t.Fatalf("published generation %d, want %d", next.Gen, base.Gen+1)
|
||||
}
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
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 := publishIntegrationHead(t, a, storage.ChunkHead{}, storage.ChunkHead{Epoch: 1, Holder: "a", RemoteLSN: 7, Chunks: map[uint64]storage.ChunkRef{4: ref(key, d)}}, 16384)
|
||||
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.
|
||||
takeover := h1
|
||||
takeover.Epoch, takeover.Holder = 2, "b"
|
||||
if gen, err := b.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, takeover); 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.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
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,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s, l
|
||||
}
|
||||
src, layer := attach("a", true) // a new, empty source volume
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Intents live in <root>/intents/<gen>-<nonce>, carry no filer chunks, list
|
||||
// back with what was written, and DeleteIntent removes only its own id.
|
||||
func TestChunkRemote_IntentsRoundTripAndNonce(t *testing.T) {
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
r, err := NewChunkRemote(f, b, "/swblock/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
a, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 3, Epoch: 1, Holder: "h1", Keys: []string{"chunks/e1/c0/x-1", "@v0/chunks/e1/c1/y-2"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 3, Epoch: 1, Holder: "h1", Keys: []string{"chunks/e1/c2/z-3"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a == c || !strings.HasPrefix(a, "3-") || !strings.HasPrefix(c, "3-") {
|
||||
t.Fatalf("ids %q %q: want distinct \"3-<nonce>\"", a, c)
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, "/swblock/chunks/v1/intents", a); err != nil {
|
||||
t.Fatalf("intent %q not at <root>/intents/: %v", a, err)
|
||||
}
|
||||
for _, e := range f.allWritten() {
|
||||
if len(e.Chunks) != 0 {
|
||||
t.Fatalf("entry %q written with filer chunks", e.Name)
|
||||
}
|
||||
}
|
||||
got, err := r.ListIntents(ctx)
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatalf("ListIntents: %+v %v", got, err)
|
||||
}
|
||||
for _, in := range got {
|
||||
if in.ID == a && (in.Gen != 3 || in.Epoch != 1 || in.Holder != "h1" || len(in.Keys) != 2 || in.Keys[1] != "@v0/chunks/e1/c1/y-2" || in.CreatedNs == 0) {
|
||||
t.Fatalf("intent %q listed as %+v", a, in)
|
||||
}
|
||||
}
|
||||
if err := r.DeleteIntent(ctx, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.DeleteIntent(ctx, a); err != nil {
|
||||
t.Fatalf("deleting a missing intent: %v", err)
|
||||
}
|
||||
got, _ = r.ListIntents(ctx)
|
||||
if len(got) != 1 || got[0].ID != c {
|
||||
t.Fatalf("after DeleteIntent(%q): %+v", a, got)
|
||||
}
|
||||
if err := r.DeleteIntent(ctx, "../HEAD"); err == nil {
|
||||
t.Fatal("DeleteIntent accepted an id that is not \"<gen>-<nonce>\"")
|
||||
}
|
||||
if _, err := f.LookupEntry(ctx, "/swblock/chunks/v1", "HEAD"); err == nil {
|
||||
t.Fatal("unexpected HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed intent entry fails the listing: GC must never miss a root.
|
||||
func TestChunkRemote_ListIntentsRefusesMalformed(t *testing.T) {
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
r, _ := NewChunkRemote(f, b, "/swblock/chunks/v1")
|
||||
ctx := context.Background()
|
||||
if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 1, Epoch: 1, Holder: "h", Keys: []string{"k"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := r.ListIntents(ctx)
|
||||
f.mu.Lock()
|
||||
f.entries[path.Join("/swblock/chunks/v1/intents", got[0].ID)].Content = []byte("{not json")
|
||||
f.mu.Unlock()
|
||||
if _, err := r.ListIntents(ctx); err == nil {
|
||||
t.Fatal("a malformed intent listed without error")
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// The SeaweedFS remote enforces the chunk key domain (non-empty valid UTF-8)
|
||||
// at Put and PutIntent before anything is written, and keys inside the
|
||||
// domain, Unicode and owner-qualified ones included, round-trip exactly
|
||||
// through the key bindings and the intent documents.
|
||||
func TestChunkRemote_KeyDomainEnforcedBeforePersistence(t *testing.T) {
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
r, err := NewChunkRemote(f, b, "/swblock/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
for _, bad := range []string{"chunks/\xff/c0", "a\xc3"} {
|
||||
if err := r.Put(ctx, bad, []byte("x")); !errors.Is(err, ErrInvalidKey) {
|
||||
t.Errorf("Put(%q): %v, want ErrInvalidKey", bad, err)
|
||||
}
|
||||
if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 1, Epoch: 1, Holder: "h", Keys: []string{"ok", bad}}); !errors.Is(err, ErrInvalidKey) {
|
||||
t.Errorf("PutIntent with %q: %v, want ErrInvalidKey", bad, err)
|
||||
}
|
||||
}
|
||||
if puts, _, _ := b.counts(); puts != 0 || len(f.allWritten()) != 0 {
|
||||
t.Fatalf("refused calls wrote %d needles and %d entries", puts, len(f.allWritten()))
|
||||
}
|
||||
|
||||
data := bytes.Repeat([]byte{0x33}, 4096)
|
||||
if err := r.Put(ctx, "chunks/é/ü-1", data); err != nil {
|
||||
t.Fatalf("Put of a Unicode key: %v", err)
|
||||
}
|
||||
fresh, _ := NewChunkRemote(f, b, "/swblock/chunks/v1") // no cached binding
|
||||
if got, err := fresh.Get(ctx, "chunks/é/ü-1"); err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatalf("Get of a Unicode key through its stored binding: %v", err)
|
||||
}
|
||||
keys := []string{"chunks/é/ü-1", "@v0/chunks/e1/c0/x-1", "日本/鍵"}
|
||||
if _, err := r.PutIntent(ctx, storage.ChunkIntent{Gen: 2, Epoch: 1, Holder: "h", Keys: keys}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := fresh.ListIntents(ctx)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("ListIntents: %+v %v", got, err)
|
||||
}
|
||||
for i, k := range keys {
|
||||
if got[0].Keys[i] != k {
|
||||
t.Fatalf("intent key %d listed as %q, stored %q", i, got[0].Keys[i], k)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func qualifiedRemotes(t *testing.T) (*fakeFiler, *fakeBlobs, *ChunkRemote, *ChunkRemote) {
|
||||
t.Helper()
|
||||
f, b := newFakeFiler(), newFakeBlobs()
|
||||
src, err := NewChunkRemote(f, b, "/swblock/chunks/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dst, err := NewChunkRemote(f, b, "/swblock/chunks/v2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f, b, src, dst
|
||||
}
|
||||
|
||||
// A fork's HEAD names its parent's chunks as "@<owner>/<key>"; Get must find
|
||||
// the binding in the owner volume's keys/ directory.
|
||||
func TestChunkRemote_GetResolvesQualifiedKey(t *testing.T) {
|
||||
_, _, src, dst := qualifiedRemotes(t)
|
||||
ctx := context.Background()
|
||||
data := bytes.Repeat([]byte{0x5a}, 4096)
|
||||
if err := src.Put(ctx, "chunks/e1/c0/n-1", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := dst.Get(ctx, "@v1/chunks/e1/c0/n-1")
|
||||
if err != nil {
|
||||
t.Fatalf("Get of a key owned by v1 from v2: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, data) {
|
||||
t.Fatal("qualified Get returned other bytes")
|
||||
}
|
||||
// The plain key in v2's own directory does not exist.
|
||||
if _, err := dst.Get(ctx, "chunks/e1/c0/n-1"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("unqualified Get of v1's key from v2: %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Writes only ever go to the volume's own directory: a qualified key is
|
||||
// refused before any needle or binding is written.
|
||||
func TestChunkRemote_PutRefusesQualifiedKey(t *testing.T) {
|
||||
f, b, _, dst := qualifiedRemotes(t)
|
||||
err := dst.Put(context.Background(), "@v1/chunks/e1/c0/n-1", []byte("x"))
|
||||
if !errors.Is(err, ErrInvalidKey) {
|
||||
t.Fatalf("Put of a qualified key: %v, want ErrInvalidKey", err)
|
||||
}
|
||||
if puts, _, _ := b.counts(); puts != 0 {
|
||||
t.Fatalf("a refused Put stored %d needles", puts)
|
||||
}
|
||||
if n := len(f.allWritten()); n != 0 {
|
||||
t.Fatalf("a refused Put wrote %d filer entries", n)
|
||||
}
|
||||
}
|
||||
|
||||
// The owner of a qualified key is one plain path element, so a key can never
|
||||
// reach outside the chunk base or into the volume's own HEAD.
|
||||
func TestChunkRemote_QualifiedKeyOwnerIsValidated(t *testing.T) {
|
||||
_, _, _, dst := qualifiedRemotes(t)
|
||||
for _, key := range []string{"@", "@v1", "@v1/", "@/k", "@../v1/k", "@./k", `@v\1/k`} {
|
||||
if _, err := dst.Get(context.Background(), key); !errors.Is(err, ErrInvalidKey) {
|
||||
t.Errorf("Get(%q): %v, want ErrInvalidKey", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,391 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
// Upload rounds over batch assign. The n objects of one round are split into
|
||||
// G = min(8, ceil(n/64)) groups (object i goes to group i % G, as slot i / G),
|
||||
// and each group takes one reservation for all its slots, made when its
|
||||
// first object is uploaded. So a round costs G assigns instead of n, its
|
||||
// objects still spread over up to G volumes, and a round with no upload
|
||||
// makes none.
|
||||
//
|
||||
// A slot is frozen once an upload was sent for it: until that upload is
|
||||
// resolved (stored and bound, or definitely not stored), every retry uses
|
||||
// the same fid, whatever happens to the group's ranges. Ranges change only
|
||||
// for slots with no upload outstanding:
|
||||
// - a short grant is topped up by a reservation for the remaining slots;
|
||||
// - a refusal before append (read-only or full volume) moves this and the
|
||||
// later slots of the group to a fresh range, at most roundMaxReplacements
|
||||
// times per group;
|
||||
// - a range whose token is past its stated expiry (less a skew) is never
|
||||
// sent to: an upload is sent under that deadline, and a slot frozen on
|
||||
// an expired range is resolved by reading its fid back first (the exact
|
||||
// bytes: bind it; definitely absent: a fresh range takes it).
|
||||
// A rejected token (401) and used-up replacements end the object for good
|
||||
// (storage.ErrChunkPutFinal). A reservation reply that arrives after the
|
||||
// group's ranges changed is discarded (its ids stay unused). AssignCounts
|
||||
// counts every reservation attempt, by reason, failed ones included.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
const (
|
||||
roundGroupSize = 64
|
||||
roundMaxGroups = 8
|
||||
roundMaxReplacements = 3
|
||||
)
|
||||
|
||||
// AssignCounts counts the reservation attempts this remote's upload rounds
|
||||
// made. Each attempt is counted once, by why it was made, whether or not it
|
||||
// succeeded; Failed counts the ones that returned no usable range.
|
||||
type AssignCounts struct {
|
||||
Initial int64 // the first attempt of each group
|
||||
Short int64 // top-ups after a short grant
|
||||
Capacity int64 // replacements after a refusal before append
|
||||
Expired int64 // replacements of ranges whose token expired before use
|
||||
Retry int64 // attempts after a failed, lost or discarded reply
|
||||
Failed int64 // attempts that returned an error or were discarded
|
||||
}
|
||||
|
||||
// Extra is every attempt beyond the initial ones.
|
||||
func (a AssignCounts) Extra() int64 { return a.Short + a.Capacity + a.Expired + a.Retry }
|
||||
|
||||
type assignCounters struct{ initial, short, capacity, expired, retry, failed atomic.Int64 }
|
||||
|
||||
// AssignCounts reports the reservation attempts made so far.
|
||||
func (r *ChunkRemote) AssignCounts() AssignCounts {
|
||||
return AssignCounts{
|
||||
Initial: r.assigns.initial.Load(),
|
||||
Short: r.assigns.short.Load(),
|
||||
Capacity: r.assigns.capacity.Load(),
|
||||
Expired: r.assigns.expired.Load(),
|
||||
Retry: r.assigns.retry.Load(),
|
||||
Failed: r.assigns.failed.Load(),
|
||||
}
|
||||
}
|
||||
|
||||
var _ storage.ChunkPutRounds = (*ChunkRemote)(nil)
|
||||
|
||||
// BeginPutRound starts a round of n objects of objSize bytes. Without batch
|
||||
// support in the blob store, the round is one Put per object.
|
||||
func (r *ChunkRemote) BeginPutRound(n, objSize int) storage.ChunkPutRound {
|
||||
rb, ok := r.b.(rangeBlobs)
|
||||
if !ok || n <= 0 {
|
||||
return plainRound{r}
|
||||
}
|
||||
g := min(roundMaxGroups, (n+roundGroupSize-1)/roundGroupSize)
|
||||
rd := &putRound{r: r, rb: rb, n: n, size: uint64(max(objSize, 0)), groups: make([]*roundGroup, g)}
|
||||
for j := range rd.groups {
|
||||
// Group j holds objects j, j+g, j+2g, ...
|
||||
rd.groups[j] = &roundGroup{slots: (n - j + g - 1) / g, pins: map[int]slotPin{}, owners: map[int]chan struct{}{}}
|
||||
}
|
||||
return rd
|
||||
}
|
||||
|
||||
type plainRound struct{ r *ChunkRemote }
|
||||
|
||||
func (p plainRound) Put(ctx context.Context, _ int, key string, data []byte) error {
|
||||
return p.r.Put(ctx, key, data)
|
||||
}
|
||||
|
||||
type putRound struct {
|
||||
r *ChunkRemote
|
||||
rb rangeBlobs
|
||||
n int
|
||||
size uint64
|
||||
groups []*roundGroup
|
||||
}
|
||||
|
||||
type reserveReason int
|
||||
|
||||
const (
|
||||
reserveInitial reserveReason = iota
|
||||
reserveShort
|
||||
reserveCapacity
|
||||
reserveExpired
|
||||
reserveRetry
|
||||
)
|
||||
|
||||
// roundGroup's ranges cover its slots [0, end) as consecutive spans.
|
||||
type roundGroup struct {
|
||||
slots int
|
||||
|
||||
mu sync.Mutex
|
||||
spans []roundSpan
|
||||
ver int // bumped by every change to spans other than an append
|
||||
reserving chan struct{} // non-nil while a reservation is in flight
|
||||
replacements int
|
||||
next reserveReason // why the next reservation is made
|
||||
pins map[int]slotPin
|
||||
owners map[int]chan struct{} // slot -> held by one Put at a time
|
||||
}
|
||||
|
||||
type roundSpan struct {
|
||||
from int
|
||||
rng blobRange
|
||||
}
|
||||
|
||||
// slotPin freezes a slot on the fid an upload was sent to; stored records
|
||||
// that the upload succeeded (only its binding is outstanding).
|
||||
type slotPin struct {
|
||||
rng blobRange
|
||||
off int
|
||||
stored bool
|
||||
}
|
||||
|
||||
func (g *roundGroup) end() int {
|
||||
if len(g.spans) == 0 {
|
||||
return 0
|
||||
}
|
||||
last := g.spans[len(g.spans)-1]
|
||||
return last.from + last.rng.count
|
||||
}
|
||||
|
||||
// lookup returns the range and offset of slot s, if reserved. g.mu held.
|
||||
func (g *roundGroup) lookup(s int) (blobRange, int, bool) {
|
||||
for _, sp := range g.spans {
|
||||
if s >= sp.from && s < sp.from+sp.rng.count {
|
||||
return sp.rng, s - sp.from, true
|
||||
}
|
||||
}
|
||||
return blobRange{}, 0, false
|
||||
}
|
||||
|
||||
// own makes the caller the only Put working on slot s until release.
|
||||
func (g *roundGroup) own(ctx context.Context, s int) (release func(), err error) {
|
||||
for {
|
||||
g.mu.Lock()
|
||||
held, busy := g.owners[s]
|
||||
if !busy {
|
||||
done := make(chan struct{})
|
||||
g.owners[s] = done
|
||||
g.mu.Unlock()
|
||||
return func() {
|
||||
g.mu.Lock()
|
||||
delete(g.owners, s)
|
||||
g.mu.Unlock()
|
||||
close(done)
|
||||
}, nil
|
||||
}
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-held:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *roundGroup) pin(s int, p slotPin) {
|
||||
g.mu.Lock()
|
||||
g.pins[s] = p
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *roundGroup) unpin(s int) {
|
||||
g.mu.Lock()
|
||||
delete(g.pins, s)
|
||||
g.mu.Unlock()
|
||||
}
|
||||
|
||||
func (g *roundGroup) pinned(s int) (slotPin, bool) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
p, ok := g.pins[s]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
// retire drops slots s and later of the span using rng, so they take a fresh
|
||||
// range (slots with an upload outstanding keep their pinned fid); it reports
|
||||
// false once the group's replacements are used up. A span already replaced
|
||||
// (by a concurrent upload) is left as is.
|
||||
func (g *roundGroup) retire(rng blobRange, s int, why reserveReason) bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
for k, sp := range g.spans {
|
||||
if sp.rng.base != rng.base {
|
||||
continue
|
||||
}
|
||||
if g.replacements >= roundMaxReplacements {
|
||||
return false
|
||||
}
|
||||
g.replacements++
|
||||
g.next = why
|
||||
g.ver++
|
||||
if s <= sp.from {
|
||||
g.spans = g.spans[:k]
|
||||
} else {
|
||||
g.spans[k].rng.count = s - sp.from
|
||||
g.spans = g.spans[:k+1]
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (rd *putRound) count(why reserveReason) {
|
||||
switch why {
|
||||
case reserveInitial:
|
||||
rd.r.assigns.initial.Add(1)
|
||||
case reserveShort:
|
||||
rd.r.assigns.short.Add(1)
|
||||
case reserveCapacity:
|
||||
rd.r.assigns.capacity.Add(1)
|
||||
case reserveExpired:
|
||||
rd.r.assigns.expired.Add(1)
|
||||
case reserveRetry:
|
||||
rd.r.assigns.retry.Add(1)
|
||||
}
|
||||
}
|
||||
|
||||
// slot returns slot s's range and offset, reserving the group's remaining
|
||||
// slots when s is not covered yet. Concurrent callers share one reservation;
|
||||
// waiting follows ctx. A reply after ctx ends, or after the group's ranges
|
||||
// changed while it was in flight, is not used.
|
||||
func (rd *putRound) slot(ctx context.Context, g *roundGroup, s int) (blobRange, int, error) {
|
||||
for {
|
||||
g.mu.Lock()
|
||||
if rng, off, ok := g.lookup(s); ok {
|
||||
g.mu.Unlock()
|
||||
return rng, off, nil
|
||||
}
|
||||
if wait := g.reserving; wait != nil {
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-wait:
|
||||
continue
|
||||
case <-ctx.Done():
|
||||
return blobRange{}, 0, ctx.Err()
|
||||
}
|
||||
}
|
||||
from, ver, why := g.end(), g.ver, g.next
|
||||
done := make(chan struct{})
|
||||
g.reserving = done
|
||||
g.mu.Unlock()
|
||||
|
||||
rd.count(why)
|
||||
rng, err := rd.rb.reserve(ctx, g.slots-from, rd.size)
|
||||
if err == nil {
|
||||
err = ctx.Err()
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.reserving = nil
|
||||
close(done)
|
||||
switch {
|
||||
case err != nil:
|
||||
rd.r.assigns.failed.Add(1)
|
||||
g.next = reserveRetry
|
||||
case g.ver != ver || g.end() != from:
|
||||
// The ranges changed while this reply was in flight: its ids
|
||||
// stay unused, and the uncovered slots are reserved again.
|
||||
rd.r.assigns.failed.Add(1)
|
||||
g.next = reserveRetry
|
||||
default:
|
||||
g.spans = append(g.spans, roundSpan{from: from, rng: rng})
|
||||
g.next = reserveShort // only a short grant leaves slots uncovered now
|
||||
}
|
||||
g.mu.Unlock()
|
||||
if err != nil {
|
||||
return blobRange{}, 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// final marks an outcome no retry can change.
|
||||
func final(err error) error { return errors.Join(storage.ErrChunkPutFinal, err) }
|
||||
|
||||
// Put stores object i under key in its group's range and binds key to it.
|
||||
func (rd *putRound) Put(ctx context.Context, i int, key string, data []byte) error {
|
||||
if i < 0 || i >= rd.n {
|
||||
return fmt.Errorf("chunkstore: round object %d outside a round of %d", i, rd.n)
|
||||
}
|
||||
name, err := rd.r.ownKeyName(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rd.r.knownKey(key) {
|
||||
return storage.ErrChunkKeyExists
|
||||
}
|
||||
g := rd.groups[i%len(rd.groups)]
|
||||
s := i / len(rd.groups)
|
||||
release, err := g.own(ctx, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
p, frozen := g.pinned(s)
|
||||
if !frozen {
|
||||
rng, off, err := rd.slot(ctx, g, s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p = slotPin{rng: rng, off: off}
|
||||
}
|
||||
fid, err := p.rng.fid(p.off)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.stored {
|
||||
if err := rd.r.bindKey(ctx, key, name, fid, data, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
g.unpin(s)
|
||||
return nil
|
||||
}
|
||||
dl, hasDL := p.rng.sendDeadline()
|
||||
if hasDL && !time.Now().Before(dl) {
|
||||
if frozen {
|
||||
// An earlier upload to fid is unresolved: read it back
|
||||
// before giving the fid up.
|
||||
got, perr := rd.rb.probe(ctx, p.rng, p.off)
|
||||
switch {
|
||||
case perr == nil && bytes.Equal(got, data):
|
||||
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
|
||||
continue
|
||||
case perr == nil:
|
||||
return final(fmt.Errorf("chunkstore: round object %d: %s holds other bytes", i, fid))
|
||||
case !errors.Is(perr, errBlobAbsent):
|
||||
return fmt.Errorf("chunkstore: round object %d: earlier upload to %s unresolved: %w", i, fid, perr)
|
||||
}
|
||||
g.unpin(s)
|
||||
}
|
||||
if !g.retire(p.rng, s, reserveExpired) {
|
||||
return final(fmt.Errorf("chunkstore: round object %d: token expired before upload, replacements used up", i))
|
||||
}
|
||||
continue
|
||||
}
|
||||
pctx, cancel := ctx, context.CancelFunc(func() {})
|
||||
if hasDL {
|
||||
pctx, cancel = context.WithDeadline(ctx, dl)
|
||||
}
|
||||
g.pin(s, p) // sent: frozen until resolved
|
||||
err = rd.rb.putRange(pctx, p.rng, p.off, data)
|
||||
cancel()
|
||||
switch {
|
||||
case err == nil:
|
||||
g.pin(s, slotPin{rng: p.rng, off: p.off, stored: true})
|
||||
continue
|
||||
case errors.Is(err, errRangeRefused):
|
||||
g.unpin(s) // definitely not stored
|
||||
if !g.retire(p.rng, s, reserveCapacity) {
|
||||
return final(fmt.Errorf("chunkstore: round object %d: %w (replacements used up)", i, err))
|
||||
}
|
||||
continue
|
||||
case errors.Is(err, errRangeAuth):
|
||||
g.unpin(s) // definitely not stored
|
||||
return final(err)
|
||||
}
|
||||
return err // outcome unknown: the slot stays frozen on fid
|
||||
}
|
||||
}
|
||||
@@ -1,726 +0,0 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// rangeFake is a blob store with batch reservations: each reserve hands out
|
||||
// a new volume id; puts are recorded by fid. Hooks shape the replies.
|
||||
type rangeFake struct {
|
||||
*fakeBlobs
|
||||
mu sync.Mutex
|
||||
nextVid int
|
||||
reserves []int // requested counts, in order
|
||||
grant func(requested int) int
|
||||
auth func() string
|
||||
refuse func(fid string) error // non-nil: the put fails with it (nothing stored)
|
||||
// reserveHook, when set, runs before each reserve (call counts from 1);
|
||||
// an error fails the reserve. It decides itself whether to follow ctx.
|
||||
reserveHook func(ctx context.Context, call int) error
|
||||
// putHook, when set, decides each put: store the bytes or not, and the
|
||||
// error to return (a stored put with an error is a lost reply).
|
||||
putHook func(ctx context.Context, fid string) (store bool, err error)
|
||||
puts []string
|
||||
putAuth map[string]string
|
||||
putDL map[string]time.Time // deadline of the context each put was sent under
|
||||
}
|
||||
|
||||
func newRangeFake() *rangeFake {
|
||||
return &rangeFake{fakeBlobs: newFakeBlobs(), nextVid: 1, putAuth: map[string]string{}, putDL: map[string]time.Time{}}
|
||||
}
|
||||
|
||||
func (b *rangeFake) reserve(ctx context.Context, n int, _ uint64) (blobRange, error) {
|
||||
b.mu.Lock()
|
||||
b.reserves = append(b.reserves, n)
|
||||
call := len(b.reserves)
|
||||
hook := b.reserveHook
|
||||
b.mu.Unlock()
|
||||
if hook != nil {
|
||||
if err := hook(ctx, call); err != nil {
|
||||
return blobRange{}, err
|
||||
}
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
count := n
|
||||
if b.grant != nil {
|
||||
count = b.grant(n)
|
||||
}
|
||||
auth := ""
|
||||
if b.auth != nil {
|
||||
auth = b.auth()
|
||||
}
|
||||
vid := b.nextVid
|
||||
b.nextVid++
|
||||
return blobRange{base: fmt.Sprintf("%d,0a0b0c0d0e", vid), count: count, url: "fake:1", auth: auth}, nil
|
||||
}
|
||||
|
||||
func (b *rangeFake) putRange(ctx context.Context, r blobRange, i int, data []byte) error {
|
||||
fid, err := r.fid(i)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.puts = append(b.puts, fid)
|
||||
b.putAuth[fid] = r.auth
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
b.putDL[fid] = dl
|
||||
}
|
||||
refuse, hook := b.refuse, b.putHook
|
||||
b.mu.Unlock()
|
||||
store, perr := true, error(nil)
|
||||
if refuse != nil {
|
||||
if err := refuse(fid); err != nil {
|
||||
store, perr = false, err
|
||||
}
|
||||
}
|
||||
if hook != nil {
|
||||
store, perr = hook(ctx, fid)
|
||||
}
|
||||
if store {
|
||||
b.fakeBlobs.mu.Lock()
|
||||
b.fakeBlobs.data[fid] = append([]byte(nil), data...)
|
||||
b.fakeBlobs.mu.Unlock()
|
||||
}
|
||||
return perr
|
||||
}
|
||||
|
||||
func (b *rangeFake) probe(_ context.Context, r blobRange, i int) ([]byte, error) {
|
||||
fid, err := r.fid(i)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.fakeBlobs.mu.Lock()
|
||||
defer b.fakeBlobs.mu.Unlock()
|
||||
d, ok := b.fakeBlobs.data[fid]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w %s", errBlobAbsent, fid)
|
||||
}
|
||||
return append([]byte(nil), d...), nil
|
||||
}
|
||||
|
||||
func (b *rangeFake) putList() []string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]string(nil), b.puts...)
|
||||
}
|
||||
|
||||
func (b *rangeFake) reserveCounts() []int {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]int(nil), b.reserves...)
|
||||
}
|
||||
|
||||
func roundRemote(t *testing.T, b *rangeFake) *ChunkRemote {
|
||||
t.Helper()
|
||||
r, err := NewChunkRemote(newFakeFiler(), b, "/swblock/vols/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func roundKey(i int) string { return fmt.Sprintf("k%05d", i) }
|
||||
|
||||
// putAll runs one round of n objects with w concurrent workers.
|
||||
func putAll(t *testing.T, r *ChunkRemote, n, w int) error {
|
||||
t.Helper()
|
||||
rd := r.BeginPutRound(n, 4096)
|
||||
var mu sync.Mutex
|
||||
next := 0
|
||||
var first error
|
||||
var wg sync.WaitGroup
|
||||
for j := 0; j < w; j++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
mu.Lock()
|
||||
i := next
|
||||
next++
|
||||
mu.Unlock()
|
||||
if i >= n {
|
||||
return
|
||||
}
|
||||
if err := rd.Put(context.Background(), i, roundKey(i), []byte(roundKey(i))); err != nil {
|
||||
mu.Lock()
|
||||
if first == nil {
|
||||
first = err
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return first
|
||||
}
|
||||
|
||||
func checkBound(t *testing.T, r *ChunkRemote, n int) {
|
||||
t.Helper()
|
||||
for i := 0; i < n; i++ {
|
||||
got, err := r.Get(context.Background(), roundKey(i))
|
||||
if err != nil || !bytes.Equal(got, []byte(roundKey(i))) {
|
||||
t.Fatalf("key %d: %q %v", i, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// D objects take G = min(8, ceil(D/64)) reservations, balanced across the
|
||||
// groups; D = 0 makes none. Every key is bound to its own fid.
|
||||
func TestChunkRound_GroupsPerRound(t *testing.T) {
|
||||
for _, c := range []struct{ d, g int }{{0, 0}, {1, 1}, {64, 1}, {65, 2}, {512, 8}, {513, 8}, {1000, 8}} {
|
||||
t.Run(fmt.Sprint(c.d), func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
r := roundRemote(t, b)
|
||||
if err := putAll(t, r, c.d, 16); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := b.reserveCounts()
|
||||
if len(got) != c.g {
|
||||
t.Fatalf("%d reservations %v for %d objects, want %d", len(got), got, c.d, c.g)
|
||||
}
|
||||
total, lo, hi := 0, c.d, 0
|
||||
for _, n := range got {
|
||||
total += n
|
||||
lo, hi = min(lo, n), max(hi, n)
|
||||
}
|
||||
if total != c.d || (c.g > 0 && hi-lo > 1) {
|
||||
t.Fatalf("reservations %v: want %d ids balanced within one", got, c.d)
|
||||
}
|
||||
checkBound(t, r, c.d)
|
||||
seen := map[string]bool{}
|
||||
for i := 0; i < c.d; i++ {
|
||||
fid := r.fids[roundKey(i)]
|
||||
if seen[fid] {
|
||||
t.Fatalf("fid %s bound twice", fid)
|
||||
}
|
||||
seen[fid] = true
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != int64(c.g) || a.Extra() != 0 {
|
||||
t.Fatalf("assign counts %+v, want %d initial, no extras", a, c.g)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A short grant is topped up by a reservation for the remainder, counted as
|
||||
// an extra, not an initial assign.
|
||||
func TestChunkRound_ShortGrantReservesRemainder(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
first := true
|
||||
b.grant = func(n int) int {
|
||||
if first {
|
||||
first = false
|
||||
return n / 2
|
||||
}
|
||||
return n
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
if err := putAll(t, r, 10, 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := b.reserveCounts(); len(got) != 2 || got[0] != 10 || got[1] != 5 {
|
||||
t.Fatalf("reservations %v, want [10 5]", got)
|
||||
}
|
||||
checkBound(t, r, 10)
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Short != 1 || a.Extra() != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// A definite capacity refusal leaves objects already stored on the old range
|
||||
// alone and moves the rest of the group to a fresh range; a volume that keeps
|
||||
// refusing ends the round after a bounded number of replacements.
|
||||
func TestChunkRound_CapacityRefusalReplacesRemainder(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
b.refuse = func(fid string) error {
|
||||
// The first volume is full from its third id on.
|
||||
if fid == "1,0a0b0c0d0e_2" || fid == "1,0a0b0c0d0e_3" {
|
||||
return errRangeRefused
|
||||
}
|
||||
return nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
if err := putAll(t, r, 6, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkBound(t, r, 6)
|
||||
if r.fids[roundKey(0)] != "1,0a0b0c0d0e" || r.fids[roundKey(1)] != "1,0a0b0c0d0e_1" {
|
||||
t.Fatalf("committed prefix moved: %s %s", r.fids[roundKey(0)], r.fids[roundKey(1)])
|
||||
}
|
||||
if got := b.reserveCounts(); len(got) != 2 || got[1] != 4 {
|
||||
t.Fatalf("reservations %v, want a fresh range for the remaining 4", got)
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
|
||||
b2 := newRangeFake()
|
||||
b2.refuse = func(string) error { return errRangeRefused }
|
||||
r2 := roundRemote(t, b2)
|
||||
err := putAll(t, r2, 3, 1)
|
||||
if !errors.Is(err, errRangeRefused) {
|
||||
t.Fatalf("always-full volumes: %v; want the refusal after bounded replacements", err)
|
||||
}
|
||||
if got := b2.reserveCounts(); len(got) != 1+roundMaxReplacements {
|
||||
t.Fatalf("%d reservations %v; want 1 + %d replacements, then stop", len(got), got, roundMaxReplacements)
|
||||
}
|
||||
}
|
||||
|
||||
// An expired token is never sent: the remainder gets a fresh range. A 401 is
|
||||
// terminal: no replacement.
|
||||
func TestChunkRound_TokenExpiryAndAuth(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
calls := 0
|
||||
b.auth = func() string {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return jwtWithExp(time.Now().Add(-time.Minute).Unix())
|
||||
}
|
||||
return jwtWithExp(time.Now().Add(time.Hour).Unix())
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
if err := putAll(t, r, 3, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkBound(t, r, 3)
|
||||
b.mu.Lock()
|
||||
for fid, a := range b.putAuth {
|
||||
if exp, ok := (blobRange{auth: a}).sendDeadline(); !ok || exp.Before(time.Now()) {
|
||||
t.Fatalf("upload to %s sent with an expired token", fid)
|
||||
}
|
||||
}
|
||||
b.mu.Unlock()
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
|
||||
b2 := newRangeFake()
|
||||
b2.refuse = func(string) error { return errRangeAuth }
|
||||
r2 := roundRemote(t, b2)
|
||||
if err := putAll(t, r2, 2, 1); !errors.Is(err, errRangeAuth) {
|
||||
t.Fatalf("401: %v", err)
|
||||
}
|
||||
if got := b2.reserveCounts(); len(got) != 1 {
|
||||
t.Fatalf("reservations %v after a 401; want no replacement", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A transient failure leaves the slot frozen: the retry sends the same fid.
|
||||
func TestChunkRound_RetryKeepsTheSlot(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
failed := false
|
||||
b.refuse = func(fid string) error {
|
||||
if fid == "1,0a0b0c0d0e_1" && !failed {
|
||||
failed = true
|
||||
return errors.New("connection reset")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(2, 4096)
|
||||
ctx := context.Background()
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil {
|
||||
t.Fatal("transient failure reported success")
|
||||
}
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.mu.Lock()
|
||||
puts := append([]string(nil), b.puts...)
|
||||
b.mu.Unlock()
|
||||
if len(puts) != 3 || puts[1] != "1,0a0b0c0d0e_1" || puts[2] != "1,0a0b0c0d0e_1" {
|
||||
t.Fatalf("uploads %v; want the retry on the same fid", puts)
|
||||
}
|
||||
if got := b.reserveCounts(); len(got) != 1 {
|
||||
t.Fatalf("reservations %v; a transient failure takes no new range", got)
|
||||
}
|
||||
// A bound key is never rebound.
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte("other")); !errors.Is(err, storage.ErrChunkKeyExists) {
|
||||
t.Fatalf("rebinding a key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// waitFor waits for ch, failing t after a bound.
|
||||
func waitFor(t *testing.T, ch <-chan struct{}, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
}
|
||||
|
||||
// releaser closes a channel once; registered as cleanup before any worker
|
||||
// that waits on it starts, so a failing test never strands that worker.
|
||||
func releaser(t *testing.T) (ch chan struct{}, release func()) {
|
||||
ch = make(chan struct{})
|
||||
var once sync.Once
|
||||
release = func() { once.Do(func() { close(ch) }) }
|
||||
t.Cleanup(release)
|
||||
return ch, release
|
||||
}
|
||||
|
||||
// A reservation waiting on the filer ends with the caller's context when it
|
||||
// follows it; one that ignores it is still joined (Put does not return
|
||||
// before it), and its late successful reply never starts an upload.
|
||||
func TestChunkRound_ReserveFollowsTheCaller(t *testing.T) {
|
||||
t.Run("cooperative", func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
hold, _ := releaser(t)
|
||||
entered := make(chan struct{})
|
||||
b.reserveHook = func(ctx context.Context, _ int) error {
|
||||
close(entered)
|
||||
select {
|
||||
case <-hold:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
joined := false
|
||||
t.Cleanup(func() { // ends and joins the worker whatever happens below
|
||||
cancel()
|
||||
if joined {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("Put never returned")
|
||||
}
|
||||
})
|
||||
go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }()
|
||||
waitFor(t, entered, "the reservation call")
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
joined = true
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancelled reservation: %v", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("Put did not end with its context")
|
||||
}
|
||||
})
|
||||
t.Run("uncooperative", func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
hold, release := releaser(t)
|
||||
entered := make(chan struct{})
|
||||
b.reserveHook = func(context.Context, int) error { close(entered); <-hold; return nil } // ignores ctx
|
||||
r := roundRemote(t, b)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x")) }()
|
||||
t.Cleanup(func() { // joins the worker whatever happens below
|
||||
release()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("Put never returned")
|
||||
}
|
||||
})
|
||||
waitFor(t, entered, "the reservation call")
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
done <- err
|
||||
t.Fatalf("Put returned (%v) while its admitted reservation call was still running", err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
release() // the late reply is a success
|
||||
select {
|
||||
case err := <-done:
|
||||
done <- err
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("late reply after the caller gave up: %v", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("Put did not return after its reservation call did")
|
||||
}
|
||||
if puts := b.putList(); len(puts) != 0 {
|
||||
t.Fatalf("uploads %v after the caller gave up", puts)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A replacement reply that arrives after a lower slot retired the group's
|
||||
// ranges is discarded: the group is reserved again from its first uncovered
|
||||
// slot, so no slot is left uncovered (and no zero-id reservation is asked).
|
||||
func TestChunkRound_StaleReplacementIsDiscarded(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(4, 4096).(*putRound)
|
||||
g := rd.groups[0]
|
||||
second := make(chan struct{})
|
||||
var secondOnce sync.Once
|
||||
release, releaseAll := releaser(t)
|
||||
b.reserveHook = func(ctx context.Context, call int) error {
|
||||
if call == 2 {
|
||||
secondOnce.Do(func() { close(second) })
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
slot0Sent := make(chan struct{})
|
||||
b.putHook = func(ctx context.Context, fid string) (bool, error) {
|
||||
switch fid {
|
||||
case "1,0a0b0c0d0e_1": // slot 1: refused at once
|
||||
return false, errRangeRefused
|
||||
case "1,0a0b0c0d0e": // slot 0: sent, refused once the replacement is in flight
|
||||
close(slot0Sent)
|
||||
select {
|
||||
case <-second:
|
||||
case <-ctx.Done():
|
||||
return false, ctx.Err()
|
||||
}
|
||||
return false, errRangeRefused
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
errs := make(chan error, 2)
|
||||
started := 0
|
||||
t.Cleanup(func() { // release and join every worker started
|
||||
releaseAll()
|
||||
cancel()
|
||||
for ; started > 0; started-- {
|
||||
select {
|
||||
case <-errs:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("a round worker never returned")
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
started++
|
||||
go func() { errs <- rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))) }()
|
||||
waitFor(t, slot0Sent, "slot 0's upload")
|
||||
started++
|
||||
go func() { errs <- rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))) }()
|
||||
waitFor(t, second, "the replacement reservation")
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for { // slot 0's refusal retires the rest of the group meanwhile
|
||||
g.mu.Lock()
|
||||
v := g.ver
|
||||
g.mu.Unlock()
|
||||
if v == 2 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("group version %d; slot 0's refusal never retired the range", v)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
releaseAll()
|
||||
for started > 0 {
|
||||
select {
|
||||
case err := <-errs:
|
||||
started-- // joined, before any Fatal: cleanup must not wait for it again
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("a round worker did not finish")
|
||||
}
|
||||
}
|
||||
got := b.reserveCounts()
|
||||
for _, n := range got {
|
||||
if n <= 0 {
|
||||
t.Fatalf("reservations %v: asked for %d ids", got, n)
|
||||
}
|
||||
}
|
||||
if len(got) != 3 || got[0] != 4 || got[1] != 3 || got[2] != 4 {
|
||||
t.Fatalf("reservations %v; want [4 3 4] (the stale [1,4) reply discarded)", got)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if fid := r.fids[roundKey(i)]; !strings.HasPrefix(fid, "3,") {
|
||||
t.Fatalf("slot %d bound to %s; want the fresh range", i, fid)
|
||||
}
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Capacity != 1 || a.Retry != 1 || a.Failed != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// A lost reservation reply is counted: the retry is an extra attempt.
|
||||
func TestChunkRound_LostReservationReplyIsCounted(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
b.reserveHook = func(_ context.Context, call int) error {
|
||||
if call == 1 {
|
||||
return errors.New("lost assign reply")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(1, 4096)
|
||||
ctx := context.Background()
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte("x")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Retry != 1 || a.Failed != 1 || a.Extra() != 1 {
|
||||
t.Fatalf("assign counts %+v; want 1 initial + 1 retry, 1 failed", a)
|
||||
}
|
||||
}
|
||||
|
||||
// An upload whose reply was lost keeps its fid: a retry after the group's
|
||||
// lower slot retired the range, or after the token expired, does not move
|
||||
// it. Past expiry the fid is read back: the exact bytes are bound there,
|
||||
// definitely absent bytes go to a fresh range.
|
||||
func TestChunkRound_AmbiguousUploadKeepsItsFid(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Run("lower slot retires the range", func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
lost := true
|
||||
b.putHook = func(_ context.Context, fid string) (bool, error) {
|
||||
switch {
|
||||
case fid == "1,0a0b0c0d0e_1" && lost:
|
||||
lost = false
|
||||
return false, errors.New("connection reset") // outcome unknown to the client
|
||||
case fid == "1,0a0b0c0d0e":
|
||||
return false, errRangeRefused
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(2, 4096)
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rd.Put(ctx, 1, roundKey(1), []byte(roundKey(1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fid := r.fids[roundKey(1)]; fid != "1,0a0b0c0d0e_1" {
|
||||
t.Fatalf("retried slot bound to %s; want its first fid", fid)
|
||||
}
|
||||
if fid := r.fids[roundKey(0)]; !strings.HasPrefix(fid, "2,") {
|
||||
t.Fatalf("refused slot bound to %s; want the fresh range", fid)
|
||||
}
|
||||
})
|
||||
for _, stored := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("token expires, stored=%v", stored), func(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
calls := 0
|
||||
b.auth = func() string {
|
||||
calls++
|
||||
if calls == 1 { // expires (less skew) about a second from now
|
||||
return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix())
|
||||
}
|
||||
return jwtWithExp(time.Now().Add(time.Hour).Unix())
|
||||
}
|
||||
lost := true
|
||||
b.putHook = func(context.Context, string) (bool, error) {
|
||||
if lost {
|
||||
lost = false
|
||||
return stored, errors.New("reply lost")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
rd := r.BeginPutRound(1, 4096)
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err == nil {
|
||||
t.Fatal("lost reply reported success")
|
||||
}
|
||||
b.mu.Lock()
|
||||
first := b.putAuth["1,0a0b0c0d0e"]
|
||||
b.mu.Unlock()
|
||||
dl, _ := (blobRange{auth: first}).sendDeadline()
|
||||
time.Sleep(time.Until(dl) + 10*time.Millisecond)
|
||||
if err := rd.Put(ctx, 0, roundKey(0), []byte(roundKey(0))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fid, puts := r.fids[roundKey(0)], b.putList()
|
||||
if stored {
|
||||
if fid != "1,0a0b0c0d0e" || len(puts) != 1 {
|
||||
t.Fatalf("stored upload: bound %s after uploads %v; want its first fid, no resend", fid, puts)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(fid, "2,") || len(puts) != 2 {
|
||||
t.Fatalf("absent upload: bound %s after uploads %v; want a fresh range", fid, puts)
|
||||
}
|
||||
if a := r.AssignCounts(); a.Initial != 1 || a.Expired != 1 {
|
||||
t.Fatalf("assign counts %+v", a)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An upload is sent under its token's send deadline: a queued upload ends
|
||||
// there, not at the caller's later deadline.
|
||||
func TestChunkRound_UploadCarriesTheTokenDeadline(t *testing.T) {
|
||||
b := newRangeFake()
|
||||
b.auth = func() string { return jwtWithExp(time.Now().Add(jwtSendSkew + time.Second).Unix()) }
|
||||
b.putHook = func(ctx context.Context, _ string) (bool, error) {
|
||||
<-ctx.Done() // queued until its context ends
|
||||
return false, ctx.Err()
|
||||
}
|
||||
r := roundRemote(t, b)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := r.BeginPutRound(1, 4096).Put(ctx, 0, roundKey(0), []byte("x"))
|
||||
if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 10*time.Second {
|
||||
t.Fatalf("queued upload: %v after %v; want it ended at the token's deadline", err, time.Since(start))
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for f, a := range b.putAuth {
|
||||
dl, _ := (blobRange{auth: a}).sendDeadline()
|
||||
if !b.putDL[f].Equal(dl) {
|
||||
t.Fatalf("upload to %s sent under deadline %v; want the token's %v", f, b.putDL[f], dl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A rejected token and used-up replacements are final for the caller; a
|
||||
// transient failure is not.
|
||||
func TestChunkRound_FinalOutcomes(t *testing.T) {
|
||||
put := func(b *rangeFake) error {
|
||||
return roundRemote(t, b).BeginPutRound(1, 4096).Put(context.Background(), 0, roundKey(0), []byte("x"))
|
||||
}
|
||||
b := newRangeFake()
|
||||
b.refuse = func(string) error { return errRangeAuth }
|
||||
if err := put(b); !errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("401: %v; want final", err)
|
||||
}
|
||||
b2 := newRangeFake()
|
||||
b2.refuse = func(string) error { return errRangeRefused }
|
||||
if err := put(b2); !errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("replacements used up: %v; want final", err)
|
||||
}
|
||||
b3 := newRangeFake()
|
||||
b3.refuse = func(string) error { return errors.New("connection reset") }
|
||||
if err := put(b3); err == nil || errors.Is(err, storage.ErrChunkPutFinal) {
|
||||
t.Fatalf("transient failure: %v; want retryable", err)
|
||||
}
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
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)})
|
||||
legacy := want.Chunks[3]
|
||||
legacy.Encoding, legacy.BirthLSN = "full", want.RemoteLSN
|
||||
want.Chunks[3] = legacy
|
||||
want, intents, err := r.PrepareManifest(ctx, storage.ChunkHead{}, want, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gen, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, want)
|
||||
if err != nil || gen != 1 {
|
||||
t.Fatalf("first CAS = %d, %v; want gen 1", gen, err)
|
||||
}
|
||||
for _, id := range intents {
|
||||
if err := r.DeleteIntent(ctx, id); err != nil {
|
||||
t.Fatal(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"))})
|
||||
h.Gen = 1
|
||||
if err := f.CreateEntry(ctx, testRoot, legacyHeadFixture(t, h), true); 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.CreateWALStoreWithOptions(p, blocks, 4096, storage.WALStoreOptions{ChunkBlocks: chunkBlocks})
|
||||
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,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s, l
|
||||
}
|
||||
|
||||
src, layer := attach("a", true) // a new, empty source volume
|
||||
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 != 5 { // chunks 0, 1, 2 and 7, plus their manifest segment
|
||||
t.Fatalf("capture stored %d needles; want 4 data chunks plus one manifest", 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 != 5 { // four data chunks and one manifest fetched once
|
||||
t.Fatalf("fresh host fetched %d needles; want 4 data chunks plus one manifest", gets)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// cleanPage is the number of pool names one removal step plans at once
|
||||
// (a variable only so tests can page with a small one).
|
||||
var cleanPage uint32 = 1000
|
||||
|
||||
// CleanResult is what one cleaning pass removed.
|
||||
type CleanResult struct {
|
||||
Shards int // pool shards listed
|
||||
Planned int // candidate names read
|
||||
Removed int // names deleted
|
||||
}
|
||||
|
||||
// RemoveUnreachableAll is the cleaning's removal step over every pool shard
|
||||
// of v, page by page, for a holder whose clean(session) is open on HEAD
|
||||
// (opened by the holder's layout remote, LayoutRemote.Clean):
|
||||
// layout.RemoveUnreachable validates HEAD after reading each page's tags,
|
||||
// so it removes nothing unless clean(session) is this holder's.
|
||||
func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me layout.HolderID, session string) (res CleanResult, err error) {
|
||||
s, r, err := c.open(v)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
shards, err := s.List(ctx, path.Join(c.base, v.Dir(), layout.PoolDir))
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
for _, name := range shards {
|
||||
shard, perr := strconv.ParseUint(name, 10, 64)
|
||||
if perr != nil || strconv.FormatUint(shard, 10) != name {
|
||||
return res, errors.Join(layout.ErrCorrupt, errors.New("chunkstore: pool shard "+strconv.Quote(name)))
|
||||
}
|
||||
res.Shards++
|
||||
after := ""
|
||||
for {
|
||||
page, err := s.ListChunkCandidates(ctx, shard, after, cleanPage)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
}
|
||||
res.Planned += len(page)
|
||||
removed, err := layout.RemoveUnreachable(ctx, s, r, s, me, session, shard, page)
|
||||
res.Removed += len(removed)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if uint32(len(page)) < cleanPage {
|
||||
break
|
||||
}
|
||||
after = page[len(page)-1].String()
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// cleanFixture is v with chunk 1 live in the current root and in snapshot
|
||||
// "s", plus orphans: chunk 2 in shard 0 and chunk ShardSize+3 in shard 1.
|
||||
func cleanFixture(t *testing.T) (*BCatalog, VolumeRef, *LayoutStore, []layout.ChunkName) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := newRef(t, "v1")
|
||||
if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commitSnapshot(t, c, v, bytes.Repeat([]byte{7}, 4096), "s")
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var orphans []layout.ChunkName
|
||||
for _, idx := range []uint64{2, layout.ShardSize + 3} {
|
||||
data := bytes.Repeat([]byte{byte(idx)}, 4096)
|
||||
n := layout.NameChunk(idx, data)
|
||||
if err := layout.EnsureObject(ctx, s, n.Path(), data, "dead-session"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orphans = append(orphans, n)
|
||||
}
|
||||
// A real filer lists the shard directories it created for these
|
||||
// entries; the in-memory filer keeps only the entries, so add them.
|
||||
pool := path.Join(c.base, v.Dir(), layout.PoolDir)
|
||||
for _, d := range []string{"0", "1"} {
|
||||
if err := c.f.CreateEntry(ctx, pool, &filerpb.Entry{Name: d, IsDirectory: true}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return c, v, s, orphans
|
||||
}
|
||||
|
||||
func present(t *testing.T, s *LayoutStore, n layout.ChunkName) bool {
|
||||
t.Helper()
|
||||
_, found, err := s.Stat(context.Background(), n.Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
var cleanHolder = layout.HolderID{Epoch: 1, Holder: "s/r", ClaimID: "k"}
|
||||
|
||||
// cleanVia runs one cleaning pass the way the holder's maintenance does:
|
||||
// through the holder's layout remote (LayoutRemote.Clean) with the
|
||||
// catalog's removal step.
|
||||
func cleanVia(ctx context.Context, c *BCatalog, v VolumeRef, me layout.HolderID) (CleanResult, *LayoutRemote, error) {
|
||||
r, err := NewLayoutRemote(c, v, me)
|
||||
if err != nil {
|
||||
return CleanResult{}, nil, err
|
||||
}
|
||||
var res CleanResult
|
||||
err = r.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error {
|
||||
var rerr error
|
||||
res, rerr = c.RemoveUnreachableAll(ctx, v, me, s)
|
||||
return rerr
|
||||
})
|
||||
return res, r, err
|
||||
}
|
||||
|
||||
// The holder's pass removes every orphan in every shard, keeps what the
|
||||
// current root and the snapshot name, and leaves HEAD idle. With a page of
|
||||
// one name the shard cursor is exercised too.
|
||||
func TestBCatalog_CleanRemovesOnlyUnreachable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
prev := cleanPage
|
||||
cleanPage = 1
|
||||
t.Cleanup(func() { cleanPage = prev })
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
live := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
|
||||
res, _, err := cleanVia(ctx, c, v, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Shards != 2 || res.Planned != 3 || res.Removed != 2 {
|
||||
t.Fatalf("clean: %+v; want 2 shards, 3 planned, 2 removed", res)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, s, n) {
|
||||
t.Fatalf("orphan %s survived the cleaning", n)
|
||||
}
|
||||
}
|
||||
if !present(t, s, live) {
|
||||
t.Fatal("the chunk the roots name was removed")
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("HEAD after clean: %+v %v; want idle", h.Activity, err)
|
||||
}
|
||||
// A second pass finds nothing more.
|
||||
if res, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil || res.Removed != 0 {
|
||||
t.Fatalf("second clean: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the holder at HEAD's epoch cleans: another holder, an old epoch or
|
||||
// another claim is refused at Begin, and nothing is removed.
|
||||
func TestBCatalog_CleanIsHolderOnly(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
for name, me := range map[string]layout.HolderID{
|
||||
"other holder": {Epoch: 1, Holder: "x/y", ClaimID: "k"},
|
||||
"other claim": {Epoch: 1, Holder: "s/r", ClaimID: "other"},
|
||||
"old epoch": {Epoch: 0, Holder: "s/r", ClaimID: "k"},
|
||||
} {
|
||||
if _, _, err := cleanVia(ctx, c, v, me); err == nil {
|
||||
t.Fatalf("%s: clean succeeded; want refused", name)
|
||||
}
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, s, n) {
|
||||
t.Fatalf("a refused clean removed %s", n)
|
||||
}
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("HEAD after refusals: %+v %v; want idle", h.Activity, err)
|
||||
}
|
||||
}
|
||||
|
||||
// While the holder's cut session is open the cleaning cannot begin
|
||||
// (ErrBusy) and removes nothing; the open session is left as it was.
|
||||
func TestBCatalog_CleanWaitsForAnOpenSnapshot(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
r, err := NewLayoutRemote(c, v, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap, err := r.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error {
|
||||
_, rerr := c.RemoveUnreachableAll(ctx, v, me, s)
|
||||
return rerr
|
||||
}); !errors.Is(err, layout.ErrBusy) {
|
||||
t.Fatalf("clean during a snapshot: %v; want ErrBusy", err)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, s, n) {
|
||||
t.Fatalf("clean during a snapshot removed %s", n)
|
||||
}
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
if err != nil || h.Activity != (layout.Activity{Kind: layout.ActSnap, Session: snap}) {
|
||||
t.Fatalf("HEAD after the refused clean: %+v %v; want the snapshot session open", h.Activity, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A pass that fails after Begin still closes the cleaning, so snapshots are
|
||||
// not blocked by it.
|
||||
func TestBCatalog_CleanClosesOnError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, _, _ := cleanFixture(t)
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := path.Join(c.base, v.Dir(), layout.PoolDir)
|
||||
if err := s.f.CreateEntry(ctx, pool, layoutEntry("x", nil), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, layout.ErrCorrupt) {
|
||||
t.Fatalf("clean over a malformed shard: %v; want ErrCorrupt", err)
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
if err != nil || h.Activity.Kind != layout.ActIdle {
|
||||
t.Fatalf("HEAD after a failed clean: %+v %v; want idle", h.Activity, err)
|
||||
}
|
||||
}
|
||||
|
||||
// commitImage commits, as cleanHolder in a fresh session, the manifest next
|
||||
// (prev is HEAD's current manifest), uploading data, at position, with a
|
||||
// named snapshot of it.
|
||||
func commitImage(t *testing.T, s *LayoutStore, vol string, session string, prev, next map[uint64]layout.Ref, data map[uint64][]byte, position uint64, snapshot string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, err := layout.RunBegin(ctx, s, cleanHolder, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for idx, ref := range next {
|
||||
if b, ok := data[idx]; ok {
|
||||
if err := layout.EnsureObject(ctx, s, ref.Chunk.Path(), b, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
root, segs, err := layout.Build(next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for n, b := range segs {
|
||||
if err := layout.EnsureObject(ctx, s, n.Path(), b, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rn, rb, err := layout.NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := layout.EnsureObject(ctx, s, rn.Path(), rb, session); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.RunCommit(ctx, s, s, vol, cleanHolder, layout.CommitRequest{Session: session, Prev: prev, Next: next, Position: position, Snapshot: snapshot}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Release-blocking (cleaning end to end on the catalog): snapshot s1 of X,
|
||||
// overwrite the chunk with Y, snapshot s2, delete s1, clean: X's chunk is
|
||||
// gone, the pool shrinks by exactly it, and the current image and s2 still
|
||||
// read Y.
|
||||
func TestBCatalog_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v := newRef(t, "v1")
|
||||
if _, err := c.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := c.Store(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layout.Start(ctx, s, okClaimLease{}, layout.HolderID{Epoch: 1, Holder: "s/r"}, layout.LocalRoot{Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, ClaimID: "k", Fresh: true, CanStartFrom: anyStart}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
x, y := bytes.Repeat([]byte{'X'}, 4096), bytes.Repeat([]byte{'Y'}, 4096)
|
||||
cx, cy := layout.NameChunk(1, x), layout.NameChunk(1, y)
|
||||
m1 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: cx}}
|
||||
m2 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: cy}}
|
||||
commitImage(t, s, v.Name, "w1", map[uint64]layout.Ref{}, m1, map[uint64][]byte{1: x}, 1, "s1")
|
||||
commitImage(t, s, v.Name, "w2", m1, m2, map[uint64][]byte{1: y}, 2, "s2")
|
||||
if err := c.f.CreateEntry(ctx, path.Join(c.base, v.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Control: while s1 still names X, the cleaning removes nothing.
|
||||
if res, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil || res.Removed != 0 || !present(t, s, cx) {
|
||||
t.Fatalf("clean with s1 held: %+v %v; want nothing removed", res, err)
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, v, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := c.listObjects(ctx, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, _, err := cleanVia(ctx, c, v, cleanHolder)
|
||||
if err != nil || res.Removed != 1 {
|
||||
t.Fatalf("clean: %+v %v; want exactly X's chunk removed", res, err)
|
||||
}
|
||||
after, err := c.listObjects(ctx, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(after) != len(before)-1 || present(t, s, cx) || !present(t, s, cy) {
|
||||
t.Fatalf("objects %d -> %d, X present %v, Y present %v; want one fewer, X gone, Y kept", len(before), len(after), present(t, s, cx), present(t, s, cy))
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, r, err := c.open(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, rn := range map[string]layout.RootName{"current": *h.Current, "s2": h.Snapshots["s2"].Root} {
|
||||
img, err := r.Open(ctx, rn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch, err := img.Chunk(ctx, 1)
|
||||
if err != nil || !bytes.Equal(ch.Data, y) {
|
||||
t.Fatalf("%s reads chunk 1: %v (Y=%v); want Y intact", name, err, bytes.Equal(ch.Data, y))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
//go:build chunkstore_integration
|
||||
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const concurrentCASWeedSHA256 = "5fafd54e10ee307a7fd7246ca6763d0069cefbef47f9a86ce722f304b162da7b"
|
||||
|
||||
type casRPCResult struct {
|
||||
index int
|
||||
code codes.Code
|
||||
}
|
||||
type casRPCGate struct {
|
||||
filerpb.SeaweedFilerClient
|
||||
index int
|
||||
arrived chan<- int
|
||||
release <-chan struct{}
|
||||
responses chan<- casRPCResult
|
||||
expected storage.ChunkHeadVersion
|
||||
}
|
||||
|
||||
// This gate does not implement CAS: every operation delegates to a real filer
|
||||
// RPC. It holds updates AFTER all client pre-reads so a client-side refusal
|
||||
// cannot masquerade as evidence of the server's conditional-write contract.
|
||||
func (c *casRPCGate) UpdateEntry(ctx context.Context, in *filerpb.UpdateEntryRequest, opts ...grpc.CallOption) (*filerpb.UpdateEntryResponse, error) {
|
||||
if in.Entry.GetName() != headName || string(in.ExpectedExtended[extGen]) != strconv.FormatUint(c.expected.Gen, 10) || string(in.ExpectedExtended[extEpoch]) != strconv.FormatUint(c.expected.Epoch, 10) {
|
||||
return nil, fmt.Errorf("unexpected HEAD CAS precondition: gen=%q epoch=%q", in.ExpectedExtended[extGen], in.ExpectedExtended[extEpoch])
|
||||
}
|
||||
select {
|
||||
case c.arrived <- c.index:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-c.release:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
resp, err := c.SeaweedFilerClient.UpdateEntry(ctx, in, opts...)
|
||||
c.responses <- casRPCResult{c.index, status.Code(err)}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func requireConcurrentCASWeed(t *testing.T) {
|
||||
t.Helper()
|
||||
binary := os.Getenv("CHUNKSTORE_WEED")
|
||||
if binary == "" {
|
||||
t.Skip("CHUNKSTORE_WEED not set")
|
||||
}
|
||||
f, err := os.Open(binary)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := fmt.Sprintf("%x", h.Sum(nil)); got != concurrentCASWeedSHA256 {
|
||||
t.Fatalf("weed must be pinned mono 8b582399d build: SHA256=%s want %s", got, concurrentCASWeedSHA256)
|
||||
}
|
||||
t.Logf("real filer binary SHA256=%s (mono 8b582399d)", concurrentCASWeedSHA256)
|
||||
}
|
||||
|
||||
func TestIntegration_ConcurrentHEADCASRealFiler(t *testing.T) {
|
||||
requireConcurrentCASWeed(t)
|
||||
cluster := startWeed(t)
|
||||
const root = "/swblock/chunks/concurrent-cas"
|
||||
reader := cluster.remote(t, root)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
initial := storage.ChunkHead{Epoch: 1, Holder: "initial", RemoteLSN: 1, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
if gen, err := reader.CASHead(ctx, storage.ChunkHeadVersion{}, initial); err != nil || gen != 1 {
|
||||
t.Fatalf("seed: gen=%d err=%v", gen, err)
|
||||
}
|
||||
// Multiple expected values exercise generation advancement, not just create.
|
||||
for round := 0; round < 4; round++ {
|
||||
t.Run(fmt.Sprintf("generation-%d", round+1), func(t *testing.T) {
|
||||
current, err := reader.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := storage.ChunkHeadVersion{Gen: current.Gen, Epoch: current.Epoch}
|
||||
const n = 16
|
||||
roundCtx, roundCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
arrived := make(chan int, n)
|
||||
release := make(chan struct{})
|
||||
responses := make(chan casRPCResult, n)
|
||||
var once sync.Once
|
||||
var wg sync.WaitGroup
|
||||
joined := make(chan struct{})
|
||||
type result struct {
|
||||
index int
|
||||
gen uint64
|
||||
err error
|
||||
}
|
||||
results := make(chan result, n)
|
||||
proposals := make([]storage.ChunkHead, n)
|
||||
// Construct clients on the test goroutine: each has its own real connection.
|
||||
remotes := make([]*ChunkRemote, n)
|
||||
for i := 0; i < n; i++ {
|
||||
client := cluster.client(t, root)
|
||||
client.fc = &casRPCGate{SeaweedFilerClient: client.fc, index: i, arrived: arrived, release: release, responses: responses, expected: expected}
|
||||
remotes[i], err = NewSWFSChunkRemote(client, root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proposals[i] = storage.ChunkHead{Epoch: current.Epoch, Holder: fmt.Sprintf("writer-%d-%d", round, i), RemoteLSN: current.RemoteLSN + uint64(i) + 1, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{}}
|
||||
}
|
||||
defer func() {
|
||||
roundCancel()
|
||||
once.Do(func() { close(release) })
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("CAS callers did not join after cancellation")
|
||||
}
|
||||
}()
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
gen, err := remotes[i].CASHead(roundCtx, expected, proposals[i])
|
||||
results <- result{i, gen, err}
|
||||
}(i)
|
||||
}
|
||||
go func() { wg.Wait(); close(joined) }()
|
||||
seen := map[int]bool{}
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case id := <-arrived:
|
||||
if seen[id] {
|
||||
t.Fatalf("duplicate RPC admission %d", id)
|
||||
}
|
||||
seen[id] = true
|
||||
case <-roundCtx.Done():
|
||||
t.Fatalf("only %d/%d reached actual UpdateEntry after pre-read: %v", len(seen), n, roundCtx.Err())
|
||||
}
|
||||
}
|
||||
once.Do(func() { close(release) })
|
||||
winners := []int{}
|
||||
losers := 0
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case r := <-results:
|
||||
if r.err == nil {
|
||||
if r.gen != expected.Gen+1 {
|
||||
t.Fatalf("winner gen=%d want %d", r.gen, expected.Gen+1)
|
||||
}
|
||||
winners = append(winners, r.index)
|
||||
} else if errors.Is(r.err, storage.ErrChunkHeadPrecondition) {
|
||||
losers++
|
||||
} else {
|
||||
t.Fatalf("caller %d has non-conflict failure: %v", r.index, r.err)
|
||||
}
|
||||
case <-roundCtx.Done():
|
||||
t.Fatal("CAS results timed out", roundCtx.Err())
|
||||
}
|
||||
}
|
||||
if len(winners) != 1 || losers != n-1 {
|
||||
t.Fatalf("same expected %+v: winners=%v typed conflicts=%d; want 1 and %d", expected, winners, losers, n-1)
|
||||
}
|
||||
rpcOK, rpcConflict := 0, 0
|
||||
rpcSeen := map[int]bool{}
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case r := <-responses:
|
||||
if rpcSeen[r.index] {
|
||||
t.Fatalf("duplicate RPC response %d", r.index)
|
||||
}
|
||||
rpcSeen[r.index] = true
|
||||
switch r.code {
|
||||
case codes.OK:
|
||||
rpcOK++
|
||||
if r.index != winners[0] {
|
||||
t.Fatalf("RPC winner %d != caller winner %d", r.index, winners[0])
|
||||
}
|
||||
case codes.FailedPrecondition:
|
||||
rpcConflict++
|
||||
default:
|
||||
t.Fatalf("unexpected real RPC status %s", r.code)
|
||||
}
|
||||
case <-roundCtx.Done():
|
||||
t.Fatal("missing real RPC result", roundCtx.Err())
|
||||
}
|
||||
}
|
||||
if rpcOK != 1 || rpcConflict != n-1 {
|
||||
t.Fatalf("real RPC OK=%d FailedPrecondition=%d", rpcOK, rpcConflict)
|
||||
}
|
||||
winner := proposals[winners[0]]
|
||||
winner.Gen = expected.Gen + 1
|
||||
wantEntry, err := headEntry(winner)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// An independent client verifies exact winner bytes, not just generation.
|
||||
fresh := cluster.client(t, root)
|
||||
gotEntry, err := fresh.LookupEntry(roundCtx, root, headName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(gotEntry.Content, wantEntry.Content) {
|
||||
t.Fatalf("final HEAD does not equal winner %d", winners[0])
|
||||
}
|
||||
for _, key := range []string{extGen, extEpoch, extHolder} {
|
||||
if !bytes.Equal(gotEntry.Extended[key], wantEntry.Extended[key]) {
|
||||
t.Fatalf("winner xattr %s mismatch", key)
|
||||
}
|
||||
}
|
||||
got, err := reader.GetHead(roundCtx)
|
||||
if err != nil || got.Gen != winner.Gen || got.Epoch != winner.Epoch || got.Holder != winner.Holder || got.RemoteLSN != winner.RemoteLSN {
|
||||
t.Fatalf("decoded final HEAD=%+v err=%v want winner %+v", got, err, winner)
|
||||
}
|
||||
t.Logf("expected gen=%d epoch=%d: %d actual RPCs, winner=%d gen=%d, %d typed server/caller conflicts, final HEAD exact", expected.Gen, expected.Epoch, n, winners[0], winner.Gen, losers)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package chunkstore
|
||||
|
||||
// Control response types and error codes are shared by the layout catalog,
|
||||
// the status HTTP routes and the operator CLI.
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// DefaultOpDeadline bounds a snapshot or fork from reading its source to
|
||||
// its final write (spec §2.3).
|
||||
const DefaultOpDeadline = 5 * time.Minute
|
||||
|
||||
// ErrNotAdmitted marks a delete admission error that is a definite refusal
|
||||
// (nothing was recorded). Any other admission error leaves the outcome
|
||||
// unknown.
|
||||
var ErrNotAdmitted = errors.New("chunkstore: volume delete not admitted")
|
||||
|
||||
const (
|
||||
// SnapActive and SnapDeleting are a snapshot's states.
|
||||
SnapActive = "active"
|
||||
SnapDeleting = "deleting"
|
||||
// SnapAbsent is DeleteSnapshot's answer for a snapshot that is not there.
|
||||
SnapAbsent = "absent"
|
||||
|
||||
// DefaultScheduleKeep is the count kept when the newest scheduled
|
||||
// snapshot carries no valid retain.LabelScheduleKeep (the label, on a
|
||||
// scheduled snapshot, is how many its schedule keeps).
|
||||
DefaultScheduleKeep = 7
|
||||
|
||||
CodeInvalidClass = "invalid_class"
|
||||
CodeInvalidPolicy = "invalid_policy"
|
||||
)
|
||||
|
||||
// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI
|
||||
// report them.
|
||||
const (
|
||||
CodeNotChunkVolume = "not_chunk_volume"
|
||||
CodeInvalidName = "invalid_name"
|
||||
CodeSnapshotExists = "snapshot_exists"
|
||||
CodeSnapshotNotFound = "snapshot_not_found"
|
||||
CodeSnapshotDeleting = "snapshot_deleting"
|
||||
CodeTargetExists = "target_exists"
|
||||
CodeGeometryMismatch = "geometry_mismatch"
|
||||
CodeDeadlineExceeded = "deadline_exceeded"
|
||||
CodeRemoteUnavailable = "remote_unavailable"
|
||||
CodeOutcomeUnknown = "outcome_unknown"
|
||||
CodeInvalidLabel = "invalid_label"
|
||||
)
|
||||
|
||||
// CatalogError is a typed control-plane failure.
|
||||
type CatalogError struct {
|
||||
Code string
|
||||
Message string
|
||||
Retryable bool
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *CatalogError) Error() string {
|
||||
if e.Err != nil {
|
||||
return fmt.Sprintf("chunkstore: %s: %s: %v", e.Code, e.Message, e.Err)
|
||||
}
|
||||
return fmt.Sprintf("chunkstore: %s: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
func (e *CatalogError) Unwrap() error { return e.Err }
|
||||
|
||||
// Detail is the error without its code: the message, and the cause if any
|
||||
// (an error body carries the code in its own field).
|
||||
func (e *CatalogError) Detail() string {
|
||||
if e.Err != nil {
|
||||
return fmt.Sprintf("%s: %v", e.Message, e.Err)
|
||||
}
|
||||
return e.Message
|
||||
}
|
||||
|
||||
// CodeOf returns the control-plane code of err, or "" when it has none.
|
||||
func CodeOf(err error) string {
|
||||
var ce *CatalogError
|
||||
if errors.As(err, &ce) {
|
||||
return ce.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func catErr(code string, retryable bool, err error, format string, a ...any) error {
|
||||
return &CatalogError{Code: code, Message: fmt.Sprintf(format, a...), Retryable: retryable, Err: err}
|
||||
}
|
||||
|
||||
// remoteErr wraps a filer failure as remote_unavailable, keeping the cause.
|
||||
func remoteErr(err error, format string, a ...any) error {
|
||||
return catErr(CodeRemoteUnavailable, true, err, format, a...)
|
||||
}
|
||||
|
||||
// Parent is a forked volume's source.
|
||||
type Parent struct {
|
||||
VolumeID string `json:"volume_id"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
Gen uint64 `json:"gen"`
|
||||
}
|
||||
|
||||
// SnapshotInfo describes one snapshot, with the field names of the HTTP API
|
||||
// (spec §3.2-§3.3).
|
||||
type SnapshotInfo struct {
|
||||
Root string `json:"root,omitempty"`
|
||||
Dependents []layout.Dependent `json:"dependents,omitempty"`
|
||||
VolumeID string `json:"volumeID"`
|
||||
Name string `json:"name"`
|
||||
HeadGen uint64 `json:"headGen"`
|
||||
HeadEpoch uint64 `json:"headEpoch"`
|
||||
CutLSN uint64 `json:"cutLSN"`
|
||||
CreatedNs int64 `json:"createdNs"`
|
||||
State string `json:"state"`
|
||||
ChunkCount int `json:"chunkCount"`
|
||||
ManifestBytes int `json:"manifestBytes"`
|
||||
Consistency string `json:"consistency"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Parent *Parent `json:"parent"`
|
||||
ExpiresAtNs int64 `json:"expiresAtNs"`
|
||||
Replayed bool `json:"replayed"`
|
||||
Class string `json:"class"`
|
||||
|
||||
attempt string // the attempt the name resolved to, when read by name
|
||||
|
||||
head storage.ChunkHead
|
||||
}
|
||||
|
||||
// Head returns the HEAD the snapshot copied.
|
||||
func (s SnapshotInfo) Head() storage.ChunkHead { return s.head }
|
||||
|
||||
type ListOptions struct {
|
||||
Prefix string
|
||||
StartAfter string
|
||||
Limit int
|
||||
IncludeDeleting bool
|
||||
}
|
||||
|
||||
// ValidateSnapshotClass refuses a class other than "", "semantic",
|
||||
// "pinned" and "scheduled" (invalid_class).
|
||||
func ValidateSnapshotClass(class string) error {
|
||||
switch class {
|
||||
case "", layout.ClassSemantic, layout.ClassPinned, layout.ClassScheduled:
|
||||
return nil
|
||||
}
|
||||
return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, layout.ClassSemantic, layout.ClassPinned, layout.ClassScheduled)
|
||||
}
|
||||
Loaded 100 of 436 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user