mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge pull request #107 from seaweedfs/feat/workspace-restore-head
durable: claim HEAD before empty-host restore and fence stale serving
This commit is contained in:
commit
257263e357
19 files changed
+1471
-16
No files matched your search
@@ -411,8 +411,21 @@ func TestFork_ThenFreshHostReadsSnapshotImage(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
|
||||
l, err := storage.AttachChunkLayer(s, r, storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")})
|
||||
cfg := storage.ChunkLayerConfig{ChunkBlocks: chunkBlocks, Epoch: epoch, Holder: vol, FreshFromHead: fresh,
|
||||
Bitmap: storage.NewFileChunkBitmapStore(p + ".chunkbitmap")}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -377,6 +377,16 @@ func (r *ChunkRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer
|
||||
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.GetHead(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestHEADRefusesLSNRegressionAcrossMove(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := newTestRemote(t, newFakeFiler(), newFakeBlobs())
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{}, head(1, "old", 42, nil)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := r.GetHead(ctx)
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 41, nil)); !isPrecondition(err) {
|
||||
t.Fatalf("regressing takeover accepted: %v", err)
|
||||
}
|
||||
after, _ := r.GetHead(ctx)
|
||||
if !reflect.DeepEqual(before, after) {
|
||||
t.Fatal("refused HEAD changed")
|
||||
}
|
||||
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 1, Epoch: 1}, head(2, "new", 42, nil)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,11 @@ type ProviderConfig struct {
|
||||
// report healthy for the requested volumeID. Zero → default 5s.
|
||||
OpenTimeout time.Duration
|
||||
|
||||
// ChunkAssignmentTimeout bounds deferred startup waiting for a healthy,
|
||||
// nonzero master assignment and attach. Local recovery returns first so
|
||||
// the host can apply its assignment. Zero defaults to 30s.
|
||||
ChunkAssignmentTimeout time.Duration
|
||||
|
||||
// WALRetentionLSNs is the operator-tunable retention window past
|
||||
// the substrate's checkpoint LSN (G6 §1.A α). Zero = pre-G6
|
||||
// strict checkpoint-driven recycle. Non-zero relaxes the recycle
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type arrivingAssignment struct {
|
||||
active atomic.Bool
|
||||
seen chan struct{}
|
||||
assigned chan struct{}
|
||||
calls atomic.Uint64
|
||||
}
|
||||
|
||||
func (v *arrivingAssignment) Projection() frontend.Projection {
|
||||
zero := frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}
|
||||
if !v.active.Load() {
|
||||
return zero
|
||||
}
|
||||
if v.calls.Add(1) == 1 {
|
||||
close(v.seen)
|
||||
return zero
|
||||
}
|
||||
select {
|
||||
case <-v.assigned:
|
||||
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true}
|
||||
default:
|
||||
return zero
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreWaitsForFirstAssignment(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
|
||||
p := chunkProviderForAssignment(t, v)
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.active.Store(true)
|
||||
recoverCtx, finishRecovery := context.WithCancel(ctx)
|
||||
defer finishRecovery()
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := p.RecoverVolume(recoverCtx, "v1"); done <- err }()
|
||||
select {
|
||||
case <-v.seen:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("recovery never inspected assignment")
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("first assignment did not converge: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("local recovery must settle before assignment can be applied")
|
||||
}
|
||||
if statuses := p.DurableStatuses(); len(statuses) != 1 || statuses[0].Operational {
|
||||
t.Fatalf("unassigned backend became operational: %+v", statuses)
|
||||
}
|
||||
finishRecovery() // deferred attachment outlives a completed recovery caller
|
||||
close(v.assigned)
|
||||
for {
|
||||
statuses := p.DurableStatuses()
|
||||
if len(statuses) == 1 && statuses[0].Operational {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("assignment never became operational: %+v", statuses)
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
if _, err := p.CaptureVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func chunkProviderForAssignment(t *testing.T, v frontend.ProjectionView) *durable.DurableProvider {
|
||||
t.Helper()
|
||||
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 storage.NewMemChunkRemote(), nil },
|
||||
}, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
|
||||
func TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose(t *testing.T) {
|
||||
for _, mode := range []string{"limit", "close"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4,
|
||||
ChunkAssignmentTimeout: 40 * time.Millisecond,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) {
|
||||
t.Error("remote reached without assignment")
|
||||
return storage.NewMemChunkRemote(), nil
|
||||
},
|
||||
}, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err := p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.active.Store(true)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := p.RecoverVolume(ctx, "v1"); done <- err }()
|
||||
select {
|
||||
case <-v.seen:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("no assignment inspection")
|
||||
}
|
||||
// Local recovery must return first, so the host can apply assignment.
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("local recovery blocked on assignment")
|
||||
}
|
||||
cancel() // recovery caller no longer owns the deferred worker
|
||||
if mode == "close" {
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if mode == "close" {
|
||||
return
|
||||
}
|
||||
deadline := time.NewTimer(2 * time.Second)
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
status := p.DurableStatuses()
|
||||
if len(status) == 1 && !status[0].Operational && strings.Contains(status[0].Evidence, "deadline exceeded") {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatalf("assignment wait did not fail closed: %+v", status)
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -72,7 +72,7 @@ type chunkLineage struct {
|
||||
// host blocks it until local recovery is done) the projection has epoch 0
|
||||
// and is not healthy; a layer is never attached under that.
|
||||
func chunkAuthority(proj frontend.Projection, volumeID string) bool {
|
||||
return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0
|
||||
return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != ""
|
||||
}
|
||||
|
||||
// recoverChunk runs after a successful local Recover, generation gen. It
|
||||
@@ -113,6 +113,23 @@ func (p *DurableProvider) current(h *volHandle, gen uint64) bool {
|
||||
|
||||
func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen uint64) {
|
||||
defer p.inflight.Done()
|
||||
limit := p.cfg.ChunkAssignmentTimeout
|
||||
if limit <= 0 {
|
||||
limit = 30 * time.Second
|
||||
}
|
||||
waitCtx, endWait := context.WithTimeout(p.closeCtx, limit)
|
||||
defer endWait()
|
||||
defer func() {
|
||||
if !errors.Is(waitCtx.Err(), context.DeadlineExceeded) {
|
||||
return
|
||||
}
|
||||
// The old wait must not overwrite a newer recovery's readiness.
|
||||
h.attachMu.Lock()
|
||||
defer h.attachMu.Unlock()
|
||||
if p.current(h, gen) && h.chunk == nil {
|
||||
h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error())
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
p.mu.Lock()
|
||||
if h.waitGen == gen {
|
||||
@@ -124,7 +141,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-p.closeCtx.Done():
|
||||
case <-waitCtx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
@@ -139,7 +156,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
h.attachMu.Unlock()
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(p.closeCtx, chunkAttachTimeout)
|
||||
ctx, cancel := context.WithTimeout(waitCtx, chunkAttachTimeout)
|
||||
err := p.attachChunk(ctx, volumeID, h)
|
||||
cancel()
|
||||
if err == nil {
|
||||
@@ -160,7 +177,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen
|
||||
}
|
||||
log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err)
|
||||
select {
|
||||
case <-p.closeCtx.Done():
|
||||
case <-waitCtx.Done():
|
||||
return
|
||||
case <-time.After(chunkAttachRetry):
|
||||
}
|
||||
@@ -188,6 +205,9 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
|
||||
return errProviderClosed
|
||||
}
|
||||
h.chunk = layer
|
||||
h.backend.mu.Lock()
|
||||
h.backend.chunkFenced = layer.Fenced
|
||||
h.backend.mu.Unlock()
|
||||
if p.cfg.ChunkCaptureInterval > 0 {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
|
||||
@@ -238,7 +258,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
|
||||
remote.setAttach(ctx) // the attach's calls also end with the caller's ctx
|
||||
defer remote.setAttach(nil)
|
||||
return storage.AttachChunkLayer(ws, remote, storage.ChunkLayerConfig{
|
||||
cfg := storage.ChunkLayerConfig{
|
||||
ChunkBlocks: p.cfg.ChunkBlocks,
|
||||
Epoch: lin.epoch,
|
||||
Holder: holder,
|
||||
@@ -256,7 +276,34 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
if h.fresh {
|
||||
// Attach preparation is gated. Seed the exact observed HEAD before
|
||||
// its takeover CAS; only then finalize lazy attachment and expose I/O.
|
||||
cfg.PrepareRestore = func(head storage.ChunkHead) error {
|
||||
// No HEAD is a new lineage; preserve any pre-assignment local
|
||||
// writes instead of replacing their frontier with zero.
|
||||
if head.Gen == 0 {
|
||||
return nil
|
||||
}
|
||||
// EnsureVolume's initial ZERO HEAD is not a remote data image.
|
||||
// A local frontier already advanced before assignment belongs to
|
||||
// this bootstrap: retain its extent bytes and unknown dirty set,
|
||||
// rather than seeding backwards or installing lazy absence.
|
||||
if head.RemoteLSN == 0 && len(head.Chunks) == 0 && head.State != storage.ChunkHeadDetached && head.DetachedBy == nil && ws.NextLSN() > 1 {
|
||||
cfg.FreshFromHead = false
|
||||
return nil
|
||||
}
|
||||
return ws.SeedChunkFrontier(head.RemoteLSN)
|
||||
}
|
||||
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
|
||||
}
|
||||
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
|
||||
}
|
||||
|
||||
return storage.AttachChunkLayer(ws, remote, cfg)
|
||||
}
|
||||
|
||||
// closeBoundRemote ends every remote call when the provider closes, so a
|
||||
@@ -481,7 +528,7 @@ func chunkFenced(volumeID string, h *volHandle) error {
|
||||
|
||||
// CutVolume takes one quiesced cut of volumeID and returns what it
|
||||
// installed: the cut LSN, the HEAD (the current one when nothing changed)
|
||||
// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is
|
||||
// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is
|
||||
// MakeRemoteDurable(minLSN) returning the cut: an LSN never written is
|
||||
// refused before anything is published, and the cut must reach minLSN.
|
||||
func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) {
|
||||
@@ -507,7 +554,7 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the
|
||||
// DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the
|
||||
// volume's frontend I/O and waits (bounded by ctx) for the I/O already
|
||||
// admitted to finish, stops the periodic cuts, then publishes one cut with
|
||||
// HEAD state detached. It also returns the last LSN written. From its
|
||||
|
||||
@@ -60,7 +60,12 @@ func TestWALStoreChunk_SameReplicaOnAnotherServerIsFenced(t *testing.T) {
|
||||
if _, err := be.Write(ctx, 4096, block(2)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("a write on the fenced second server: %v; want ErrNotReady", err)
|
||||
}
|
||||
if _, err := b.CaptureVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("a cut on the fenced second server: %v; want fenced", err)
|
||||
// The canonical refusal is at Claim, before any layer is installed.
|
||||
// Later cuts must still refuse; they need not repeat a layer's fence.
|
||||
if _, err := b.CaptureVolume(ctx, "v1"); err == nil {
|
||||
t.Fatal("a cut succeeded after refused recovery")
|
||||
}
|
||||
if after, _ := remote.GetHead(ctx); after.Gen != head.Gen || after.Holder != head.Holder {
|
||||
t.Fatalf("refused cut changed HEAD: %+v", after)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func awaitRestoreCondition(t *testing.T, ctx context.Context, what string, ready func() bool) {
|
||||
t.Helper()
|
||||
for !ready() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("%s: %v", what, ctx.Err())
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreCheckpointBeforeAssignmentPreservesRemoteBytes(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
|
||||
p := chunkProvider(t, t.TempDir(), remote, view, 0)
|
||||
s := openRecovered(t, p)
|
||||
ws := s.(*storage.WALStore)
|
||||
want := block(0xD7)
|
||||
lsn, err := s.Write(33, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// FlushCount increments after checkpoint persistence AND dirty-map removal.
|
||||
// The authority stays absent until that actual cycle has fully completed.
|
||||
awaitRestoreCondition(t, ctx, "checkpoint before attach", func() bool {
|
||||
return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0
|
||||
})
|
||||
if h, _ := remote.GetHead(ctx); h.Gen != 0 {
|
||||
t.Fatal("unexpected HEAD before assignment", h)
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}))
|
||||
awaitRestoreCondition(t, ctx, "deferred attachment", func() bool {
|
||||
st := p.DurableStatuses()
|
||||
return len(st) == 1 && st[0].Operational
|
||||
})
|
||||
if h, err := p.CaptureVolume(ctx, "v1"); err != nil || h != lsn {
|
||||
t.Fatal("cut", h, err)
|
||||
}
|
||||
fresh := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
|
||||
got, err := openRecovered(t, fresh).Read(33)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("remote restore lost checkpointed bytes: got=%x err=%v", sha256.Sum256(got), err)
|
||||
}
|
||||
}
|
||||
|
||||
type publishAfterAbsentRead struct {
|
||||
storage.ChunkRemote
|
||||
once sync.Once
|
||||
beforeReturn func()
|
||||
}
|
||||
|
||||
func (r *publishAfterAbsentRead) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
h, err := r.ChunkRemote.GetHead(ctx)
|
||||
if err == nil {
|
||||
r.once.Do(r.beforeReturn)
|
||||
}
|
||||
return h, err
|
||||
}
|
||||
|
||||
func TestRestoreHEADAppearsBetweenClaimAndAttach(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
data := bytes.Repeat([]byte{0xA7}, pcChunkBlocks*4096)
|
||||
wrapped := &publishAfterAbsentRead{ChunkRemote: remote, beforeReturn: func() {
|
||||
if err := remote.Put(ctx, "old-cut", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "old-cut", SHA256: sha256.Sum256(data)}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}}
|
||||
p := chunkProvider(t, t.TempDir(), wrapped, v1View(), 0)
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = p.RecoverVolume(ctx, "v1")
|
||||
if err != nil {
|
||||
backend, openErr := p.Open(ctx, "v1")
|
||||
if openErr != nil {
|
||||
t.Fatal(openErr)
|
||||
}
|
||||
if _, readErr := backend.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) {
|
||||
t.Fatal("failed attach admitted I/O", readErr)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal("retry must claim and seed", err)
|
||||
}
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil || h.Epoch != 3 || h.Holder != "r1" {
|
||||
t.Fatalf("ready without ownership: HEAD=%+v err=%v", h, err)
|
||||
}
|
||||
if r, _, h := s.(*storage.WALStore).Boundaries(); r != 7 || h != 7 {
|
||||
t.Fatalf("ready without seed: R=%d H=%d", r, h)
|
||||
}
|
||||
if got, err := s.Read(0); err != nil || !bytes.Equal(got, data[:4096]) {
|
||||
t.Fatal("exact lazy restore changed", err)
|
||||
}
|
||||
if cut, err := p.CaptureVolume(ctx, "v1"); err != nil || cut != 7 {
|
||||
t.Fatal("capture after settled restore", cut, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//go:build linux
|
||||
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type seedSyncFaultRemote struct {
|
||||
storage.ChunkRemote
|
||||
once sync.Once
|
||||
beforeSeed func()
|
||||
}
|
||||
|
||||
func (r *seedSyncFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
head, err := r.ChunkRemote.GetHead(ctx)
|
||||
if err == nil {
|
||||
r.once.Do(r.beforeSeed)
|
||||
}
|
||||
return head, err
|
||||
}
|
||||
|
||||
// Replace only this fixture's WAL descriptor after Recover has read it and
|
||||
// before the seed's real os.File.Sync. /dev/full fsync returns EINVAL. Restore
|
||||
// the original open-file description before retry; no production fault seam.
|
||||
func failSeedFD(t *testing.T, root string) func() {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir("/proc/self/fd")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fd := -1
|
||||
for _, e := range entries {
|
||||
name, err := os.Readlink("/proc/self/fd/" + e.Name())
|
||||
if err == nil && strings.HasPrefix(name, root+string(os.PathSeparator)) {
|
||||
if fd != -1 {
|
||||
t.Fatal("more than one fixture WAL descriptor")
|
||||
}
|
||||
fd, err = strconv.Atoi(e.Name())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if fd < 0 {
|
||||
t.Fatal("fixture WAL descriptor not found")
|
||||
}
|
||||
backup, err := syscall.Dup(fd)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
full, err := os.OpenFile("/dev/full", os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
syscall.Close(backup)
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer full.Close()
|
||||
if err := syscall.Dup2(int(full.Fd()), fd); err != nil {
|
||||
syscall.Close(backup)
|
||||
t.Fatal(err)
|
||||
}
|
||||
var once sync.Once
|
||||
restore := func() {
|
||||
once.Do(func() {
|
||||
if err := syscall.Dup2(backup, fd); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
_ = syscall.Close(backup)
|
||||
})
|
||||
}
|
||||
t.Cleanup(restore)
|
||||
return restore
|
||||
}
|
||||
|
||||
func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
root := filepath.Join(t.TempDir(), "provider")
|
||||
remote := storage.NewMemChunkRemote()
|
||||
data := bytes.Repeat([]byte{0xA7}, 4*4096)
|
||||
if err := remote.Put(ctx, "seed", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 3, Holder: "r1", RemoteLSN: 7,
|
||||
Chunks: map[uint64]storage.ChunkRef{0: {Key: "seed", SHA256: sha256.Sum256(data)}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restore func()
|
||||
fault := &seedSyncFaultRemote{ChunkRemote: remote, beforeSeed: func() { restore = failSeedFD(t, root) }}
|
||||
makeProvider := func(r storage.ChunkRemote) *durable.DurableProvider {
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root,
|
||||
NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
p := makeProvider(fault)
|
||||
s, err := p.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws := s.(*storage.WALStore)
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err == nil {
|
||||
t.Fatal("real seed fsync failure was accepted")
|
||||
} else if !errors.Is(err, syscall.EINVAL) {
|
||||
t.Fatalf("expected real fsync EINVAL, got %v", err)
|
||||
} else {
|
||||
t.Logf("injected real WAL fsync failure: %v", err)
|
||||
}
|
||||
if restore == nil {
|
||||
t.Fatal("fault not exercised")
|
||||
}
|
||||
restore()
|
||||
blocked, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("failed recovery exposed backend: %v", err)
|
||||
}
|
||||
if got := ws.NextLSN(); got != 1 {
|
||||
t.Errorf("failed seed published allocator watermark %d, want 1", got)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal("same-handle retry:", err)
|
||||
}
|
||||
if r, _, h := ws.Boundaries(); r != 7 || h != 7 {
|
||||
t.Errorf("retry did not durably seed HEAD: R=%d H=%d", r, h)
|
||||
}
|
||||
if cut, err := p.CaptureVolume(ctx, "v1"); err != nil || cut != 7 {
|
||||
t.Errorf("retry cut=%d err=%v, want 7", cut, err)
|
||||
}
|
||||
if err := p.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p2 := makeProvider(remote)
|
||||
s2, err := p2.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p2.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next := s2.(*storage.WALStore).NextLSN(); next != 8 {
|
||||
t.Errorf("reopen nextLSN=%d, want 8", next)
|
||||
}
|
||||
b, err := p2.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if _, err := b.Read(ctx, 0, got); err != nil || !bytes.Equal(got, data[:4096]) {
|
||||
t.Fatal("restored bytes changed:", err)
|
||||
}
|
||||
if _, err := b.Write(ctx, 4096, bytes.Repeat([]byte{0xB8}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut, err := p2.CaptureVolume(ctx, "v1"); err != nil || cut != 8 {
|
||||
t.Fatalf("new cut=%d err=%v, want 8", cut, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreFailedSeedNeverTakesOwnership(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
root := filepath.Join(t.TempDir(), "provider")
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := 0
|
||||
watched := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() { calls++ }}
|
||||
var restore func()
|
||||
fault := &seedSyncFaultRemote{ChunkRemote: watched, beforeSeed: func() { restore = failSeedFD(t, root) }}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, WALRecoveryTestDisableFlusher: true,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return fault, nil }}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); !errors.Is(err, syscall.EINVAL) {
|
||||
t.Fatalf("seed sync should fail with EINVAL: %v", err)
|
||||
}
|
||||
if restore == nil {
|
||||
t.Fatal("real fsync fault not exercised")
|
||||
}
|
||||
restore()
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 0 || h.Gen != 1 || h.Epoch != 1 || h.Holder != "old" || h.RemoteLSN != 7 {
|
||||
t.Fatalf("failed seed changed authority: CAS=%d HEAD=%+v; want untouched old HEAD", calls, h)
|
||||
}
|
||||
if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatal("failed seed admitted I/O", err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal("same-store retry", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatal("successful retry must take ownership exactly once", calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type takeoverOrderRemote struct {
|
||||
storage.ChunkRemote
|
||||
beforeCAS func()
|
||||
}
|
||||
|
||||
func (r *takeoverOrderRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) {
|
||||
r.beforeCAS()
|
||||
return r.ChunkRemote.CASHead(ctx, v, h)
|
||||
}
|
||||
|
||||
func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var p *durable.DurableProvider
|
||||
var checked atomic.Bool
|
||||
var calls atomic.Int32
|
||||
var nextAtCAS, durableAtCAS, headAtCAS uint64
|
||||
wrapped := &takeoverOrderRemote{ChunkRemote: remote, beforeCAS: func() {
|
||||
calls.Add(1)
|
||||
if !checked.Load() {
|
||||
t.Error("takeover preceded VOLUME check")
|
||||
}
|
||||
s := p.LogicalStorage("v1")
|
||||
nextAtCAS = s.NextLSN()
|
||||
durableAtCAS, _, headAtCAS = s.Boundaries()
|
||||
if _, err := p.Backend("v1").Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Errorf("I/O admitted before takeover: %v", err)
|
||||
}
|
||||
}}
|
||||
var err error
|
||||
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 wrapped, nil },
|
||||
ChunkAttachCheck: func(context.Context, string, durable.ChunkGeometry) error { checked.Store(true); return nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls.Load() != 1 || nextAtCAS != 8 || durableAtCAS != 7 || headAtCAS != 7 {
|
||||
t.Fatalf("takeover before durable seed: CAS calls=%d nextLSN=%d durable=%d head=%d; want 1/8/7/7", calls.Load(), nextAtCAS, durableAtCAS, headAtCAS)
|
||||
}
|
||||
be, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := be.Read(ctx, 0, make([]byte, 4096)); err != nil {
|
||||
t.Fatal("ready after seed and takeover", err)
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil || h.Epoch != 3 || h.Holder != "r1" || h.RemoteLSN != 7 {
|
||||
t.Fatal(h, err)
|
||||
}
|
||||
t.Logf("VOLUME check -> seed nextLSN=%d/durable=%d -> takeover -> serve", nextAtCAS, durableAtCAS)
|
||||
}
|
||||
|
||||
// A restored restart under the same assignment must reactivate a detached
|
||||
// image before exposing I/O, not treat it as an already-settled active claim.
|
||||
func TestRestoreEqualOwnerDetachedHEADIsReactivated(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
makeProvider := func() *durable.DurableProvider {
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "node-a/r1",
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
source := makeProvider()
|
||||
openRecovered(t, source)
|
||||
be, err := source.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := block(0xA7)
|
||||
if _, err = be.Write(ctx, 4096, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = be.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, _, err := source.DetachVolume(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = source.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restarted := makeProvider()
|
||||
if _, err = restarted.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = restarted.RecoverVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Gen <= cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != storage.ChunkHeadActive || h.DetachedBy != nil || h.RemoteLSN != cut.H {
|
||||
t.Errorf("ready with stale detached proof: HEAD=%+v detached=%+v", h, cut.Head)
|
||||
}
|
||||
frontend, err := restarted.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make([]byte, 4096)
|
||||
if _, err = frontend.Read(ctx, 4096, got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("restart changed exact data")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type bootstrapBlobs struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (b *bootstrapBlobs) Put(_ context.Context, data []byte) (string, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
id := fmt.Sprintf("fid-%d", len(b.objects)+1)
|
||||
b.objects[id] = bytes.Clone(data)
|
||||
return id, nil
|
||||
}
|
||||
func (b *bootstrapBlobs) Get(_ context.Context, id string) ([]byte, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
data, ok := b.objects[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("missing blob %s", id)
|
||||
}
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
func TestRestoreEnsureVolumeZeroHEADPreservesCheckpointedBootstrap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
filer := chunkstore.NewMemFiler()
|
||||
catalog, err := chunkstore.NewCatalog(filer, "/bootstrap")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote, err := chunkstore.NewChunkRemote(filer, &bootstrapBlobs{objects: map[string][]byte{}}, "/bootstrap/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
|
||||
makeProvider := func(view *stubView) *durable.DurableProvider {
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHolder: "node-a/r1",
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
ChunkAttachCheck: func(ctx context.Context, vol string, g durable.ChunkGeometry) error {
|
||||
_, err := catalog.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: g.NumBlocks, BlockSize: g.BlockSize, ChunkBlocks: g.ChunkBlocks})
|
||||
return err
|
||||
},
|
||||
}, view)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
return p
|
||||
}
|
||||
p := makeProvider(view)
|
||||
s := openRecovered(t, p)
|
||||
ws := s.(*storage.WALStore)
|
||||
want := block(0xD7)
|
||||
lsn, err := s.Write(33, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitRestoreCondition(t, ctx, "checkpointed local bootstrap", func() bool { return ws.CheckpointLSN() >= lsn && ws.FlushCount() > 0 })
|
||||
// This production attach hook, rather than a manufactured fixture HEAD,
|
||||
// creates the initial ZERO image after the write has left the dirty map.
|
||||
_, err = catalog.EnsureVolume(ctx, "v1", chunkstore.Geometry{NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := remote.GetHead(ctx)
|
||||
if err != nil || h.Gen == 0 || h.RemoteLSN != 0 || len(h.Chunks) != 0 {
|
||||
t.Fatalf("initial ZERO HEAD: %+v %v", h, err)
|
||||
}
|
||||
view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}))
|
||||
awaitRestoreCondition(t, ctx, "ZERO HEAD bootstrap attachment", func() bool { st := p.DurableStatuses(); return len(st) == 1 && st[0].Operational })
|
||||
if got, err := p.CaptureVolume(ctx, "v1"); err != nil || got != lsn {
|
||||
t.Fatalf("capture=%d want=%d err=%v", got, lsn, err)
|
||||
}
|
||||
fresh := makeProvider(v1View())
|
||||
got, err := openRecovered(t, fresh).Read(33)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("checkpointed local bytes lost on remote restore: exact=%v err=%v", bytes.Equal(got, want), err)
|
||||
}
|
||||
}
|
||||
@@ -164,6 +164,7 @@ type StorageBackend struct {
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
chunkFenced func() bool // installed under mu; called only after releasing mu
|
||||
observer WriteObserver // optional; nil = no replication fan-out
|
||||
writeAck WriteAckPolicy
|
||||
profile writeProfile
|
||||
@@ -521,10 +522,14 @@ func (b *StorageBackend) gate() error {
|
||||
func (b *StorageBackend) readyCheck() error {
|
||||
b.mu.Lock()
|
||||
closed := b.closed
|
||||
chunkFenced := b.chunkFenced
|
||||
b.mu.Unlock()
|
||||
if closed {
|
||||
return frontend.ErrBackendClosed
|
||||
}
|
||||
if chunkFenced != nil && chunkFenced() {
|
||||
return frontend.ErrStalePrimary
|
||||
}
|
||||
if !b.operational.Load() {
|
||||
ev, _ := b.opEvidence.Load().(string)
|
||||
return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev)
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type restoreProjection struct{ projection frontend.Projection }
|
||||
|
||||
func (v restoreProjection) Projection() frontend.Projection { return v.projection }
|
||||
|
||||
type restoreRemote struct {
|
||||
storage.ChunkRemote
|
||||
gets atomic.Uint64
|
||||
}
|
||||
|
||||
func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
r.gets.Add(1)
|
||||
return r.ChunkRemote.Get(ctx, key)
|
||||
}
|
||||
|
||||
// This CPU component loop uses a real master authority runtime, two real
|
||||
// temporary-file providers and the existing in-memory ChunkRemote boundary.
|
||||
// Keep the old projection stale to model delayed assignment delivery; a HEAD
|
||||
// takeover must independently refuse its cut and then stop its frontend I/O.
|
||||
func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
m := newTestMaster(t, t.TempDir())
|
||||
defer closeTestMaster(t, m)
|
||||
seedVerifiedExistingReplicaPlacement(t, m)
|
||||
if _, err := m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a")
|
||||
remote := &restoreRemote{ChunkRemote: storage.NewMemChunkRemote()}
|
||||
open := func(line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) {
|
||||
t.Helper()
|
||||
view := restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID,
|
||||
Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}
|
||||
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() { _ = p.Close() })
|
||||
if _, err := p.EnsureStorage("vol-a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.RecoverVolume(ctx, "vol-a"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend, err := p.Open(ctx, "vol-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p, backend
|
||||
}
|
||||
oldProvider, oldBackend := open(oldLine)
|
||||
want := map[int64][]byte{0: bytes.Repeat([]byte{0xA1}, 4096), 8 * 4096: bytes.Repeat([]byte{0xB2}, 4096)}
|
||||
for offset, data := range want {
|
||||
if n, err := oldBackend.Write(ctx, offset, data); err != nil || n != len(data) {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
}
|
||||
if err := oldBackend.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := oldProvider.CaptureVolume(ctx, "vol-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
headBefore, err := remote.GetHead(ctx)
|
||||
if err != nil || headBefore.RemoteLSN != cut || len(headBefore.Chunks) != 2 {
|
||||
t.Fatalf("initial HEAD=%+v err=%v", headBefore, err)
|
||||
}
|
||||
|
||||
// The authority runtime, not either provider, allocates the next epoch.
|
||||
// Admission evidence is supplied by this fixture, as in the runtime's
|
||||
// existing tests; this is not a VM-stop or physical fencing qualification.
|
||||
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: oldLine.ReplicaID, ExpectedCurrentEpoch: oldLine.Epoch,
|
||||
AckEligible: true, FrontendFencedBeforeFailback: true,
|
||||
DurableFrontierCovered: true, NoCrossVolumeIdentityChange: true,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newLine, ok := m.Publisher().VolumeAuthorityLine("vol-a")
|
||||
if !ok || newLine.ReplicaID != "r1" || newLine.Epoch <= oldLine.Epoch {
|
||||
t.Fatalf("master did not move authority: %+v", newLine)
|
||||
}
|
||||
gets := remote.gets.Load()
|
||||
freshProvider, freshBackend := open(newLine) // unrelated empty local directory
|
||||
if remote.gets.Load() != gets {
|
||||
t.Error("restore eagerly fetched chunk bodies before any read")
|
||||
}
|
||||
claimed, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed.Epoch != newLine.Epoch || claimed.Holder != newLine.ReplicaID || claimed.RemoteLSN != cut {
|
||||
t.Errorf("restore served before HEAD takeover: HEAD epoch=%d holder=%q cut=%d; want master epoch=%d holder=%q cut=%d",
|
||||
claimed.Epoch, claimed.Holder, claimed.RemoteLSN, newLine.Epoch, newLine.ReplicaID, cut)
|
||||
}
|
||||
for offset, data := range want {
|
||||
got := make([]byte, len(data))
|
||||
if n, err := freshBackend.Read(ctx, offset, got); err != nil || n != len(got) || !bytes.Equal(got, data) {
|
||||
t.Fatalf("fresh exact read offset=%d n=%d err=%v", offset, n, err)
|
||||
}
|
||||
}
|
||||
if remote.gets.Load() <= gets {
|
||||
t.Error("fresh reads did not lazily fetch HEAD chunks")
|
||||
}
|
||||
// With assignment delivery held, the stale host can still have local dirt.
|
||||
if n, err := oldBackend.Write(ctx, 0, bytes.Repeat([]byte{0xCC}, 4096)); err != nil || n != 4096 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if _, err := oldProvider.CaptureVolume(ctx, "vol-a"); err == nil {
|
||||
t.Error("old host cut succeeded after new host restored")
|
||||
}
|
||||
if n, err := oldBackend.Read(ctx, 0, make([]byte, 4096)); err == nil || n != 0 {
|
||||
t.Errorf("old host kept serving after its refused cut: n=%d err=%v", n, err)
|
||||
}
|
||||
if n, err := oldBackend.Write(ctx, 0, make([]byte, 4096)); err == nil || n != 0 {
|
||||
t.Errorf("old host kept accepting writes after its refused cut: n=%d err=%v", n, err)
|
||||
}
|
||||
if err := oldBackend.Sync(ctx); err == nil {
|
||||
t.Error("old host kept acknowledging Sync after its refused cut")
|
||||
}
|
||||
afterStale, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(afterStale, claimed) {
|
||||
t.Errorf("stale host changed claimed HEAD: %+v", afterStale)
|
||||
}
|
||||
// A new local WAL must continue after HEAD, not restart its LSN at 1.
|
||||
want[4*4096] = bytes.Repeat([]byte{0xD4}, 4096)
|
||||
if n, err := freshBackend.Write(ctx, 4*4096, want[4*4096]); err != nil || n != 4096 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if err := freshBackend.Sync(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newCut, err := freshProvider.CaptureVolume(ctx, "vol-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if newCut <= cut {
|
||||
t.Errorf("restored WAL did not advance beyond HEAD: old=%d new=%d", cut, newCut)
|
||||
}
|
||||
newHead, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
final, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if final.Epoch != newLine.Epoch || final.Holder != newLine.ReplicaID || final.RemoteLSN != newCut || final.Gen != newHead.Gen || !reflect.DeepEqual(final.Chunks, newHead.Chunks) {
|
||||
t.Errorf("old host changed restored HEAD: %+v", final)
|
||||
}
|
||||
for offset, data := range want {
|
||||
got := make([]byte, len(data))
|
||||
if n, err := freshBackend.Read(ctx, offset, got); err != nil || n != len(got) || !bytes.Equal(got, data) {
|
||||
t.Fatalf("new host bytes changed after stale cut: offset=%d n=%d err=%v", offset, n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// SeedChunkFrontier installs an empty fresh host's inherited remote frontier.
|
||||
// Unlike AdvanceFrontier + Sync, it publishes no allocator/head watermark until
|
||||
// both the data sync and checkpoint-metadata sync have succeeded. Call before
|
||||
// attaching the chunk layer or admitting writes. Repeating after failure is safe.
|
||||
// Order: captureMu -> lifecycleMu -> mu; no remote call or layer callback.
|
||||
func (s *WALStore) SeedChunkFrontier(lsn uint64) error {
|
||||
s.captureMu.Lock()
|
||||
defer s.captureMu.Unlock()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed || s.chunk.Load() != nil {
|
||||
return errors.New("storage: seed frontier requires an open, unattached store")
|
||||
}
|
||||
if lsn == ^uint64(0) || lsn < s.checkpointLSN || s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 {
|
||||
return errors.New("storage: seed frontier cannot replace local writes or wrap LSN")
|
||||
}
|
||||
if s.checkpointLSN == lsn && s.syncedLSN >= lsn && s.nextLSN == lsn+1 {
|
||||
return nil
|
||||
}
|
||||
if err := s.syncCache(); err != nil {
|
||||
return fmt.Errorf("storage: seed data sync: %w", err)
|
||||
}
|
||||
next := *s.sb
|
||||
next.WALCheckpointLSN = lsn
|
||||
next.WALHead = s.wal.logicalHeadValue()
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := next.writeTo(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.syncDirectFrontierMetadata(buf.bytes()); err != nil {
|
||||
return fmt.Errorf("storage: seed metadata sync: %w", err)
|
||||
}
|
||||
*s.sb = next
|
||||
s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1
|
||||
s.pendingDirectFrontierLSN = 0
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) {
|
||||
s, path := newChunkTestStore(t)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
syncMetadata := s.syncDirectFrontierMetadata
|
||||
s.syncDirectFrontierMetadata = func([]byte) error { return errors.New("injected metadata fsync failure") }
|
||||
if err := s.SeedChunkFrontier(7); err == nil {
|
||||
t.Fatal("failed metadata sync accepted")
|
||||
}
|
||||
if next := s.NextLSN(); next != 1 {
|
||||
t.Fatalf("failed seed advanced NextLSN to %d", next)
|
||||
}
|
||||
if r, _, h := s.Boundaries(); r != 0 || h != 0 {
|
||||
t.Fatal("failed seed published frontier", r, h)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.syncDirectFrontierMetadata = syncMetadata
|
||||
if err := s.SeedChunkFrontier(7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.NextLSN() != 8 {
|
||||
t.Fatal("retry not seeded")
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reopened.Close()
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reopened.NextLSN() != 8 {
|
||||
t.Fatal("durable seed missing after reopen")
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err)
|
||||
}
|
||||
if cfg.RestoreGuard != nil && (head.Gen != cfg.RestoreGuard.Gen || head.Epoch != cfg.RestoreGuard.Epoch) {
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("%w: HEAD changed after restore claim/seed", errChunkHeadPrecondition)
|
||||
}
|
||||
l.head = copyHead(head)
|
||||
l.remoteLSN = head.RemoteLSN
|
||||
// A HEAD that already belongs to a newer epoch or a competing holder is
|
||||
@@ -178,6 +182,24 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
}
|
||||
|
||||
if cfg.FreshFromHead {
|
||||
// An existing HEAD defines the fresh host's lazy image. With no HEAD,
|
||||
// local writes may already have checkpointed out of the WAL dirty map:
|
||||
// preserve ALL chunks as candidates for the first hash-comparing cut.
|
||||
// Persist that obligation before publishing hooks/readiness.
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch}
|
||||
var initialDirty []uint64
|
||||
l.dirty = map[uint64]bool{}
|
||||
l.hashMode = head.Gen == 0 && s.NextLSN() > 1
|
||||
if l.hashMode {
|
||||
for idx := uint64(0); idx < l.numChunks; idx++ {
|
||||
l.dirty[idx] = true
|
||||
initialDirty = append(initialDirty, idx)
|
||||
}
|
||||
}
|
||||
if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil {
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err)
|
||||
}
|
||||
for idx := range head.Chunks {
|
||||
l.absent[idx] = true
|
||||
l.absentGen[idx]++
|
||||
@@ -259,7 +281,7 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
|
||||
return l.persistPresence()
|
||||
}
|
||||
|
||||
// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in
|
||||
// saveDirty persists dirty ∪ inflight ∪ the chunks of WAL entries still in
|
||||
// the dirty map (all chunks when a BASE block landed or the set is unknown).
|
||||
func (l *chunkLayerImpl) saveDirty() error {
|
||||
l.bmMu.Lock()
|
||||
@@ -696,6 +718,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (chunkC
|
||||
changed = append(changed, u.c.idx)
|
||||
}
|
||||
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
|
||||
// A no-op cut still observes authority: a fresh host may have
|
||||
// claimed HEAD without uploading a single chunk since our last cut.
|
||||
cur, err := l.remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
l.abortCut(all)
|
||||
return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err)
|
||||
}
|
||||
if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) {
|
||||
l.abortCut(all)
|
||||
l.stMu.Lock()
|
||||
l.fenced, l.head = true, copyHead(cur)
|
||||
l.stMu.Unlock()
|
||||
return chunkCutResult{}, errChunkLayerFenced
|
||||
}
|
||||
l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS
|
||||
return chunkCutResult{H: h, Head: copyHead(baseHead), Noop: true, FullHash: all}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ClaimChunkHead transfers only HEAD ownership, never chunk bodies. Epoch is
|
||||
// supplied by the master's projection, not allocated here. The caller must
|
||||
// persist lazy-read absence before exposing the local volume for I/O.
|
||||
// No WALStore, layer-state or provider-map lock is held across remote calls;
|
||||
// the provider may hold its per-volume attach serialization lock.
|
||||
func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfig) (ChunkHead, error) {
|
||||
if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" {
|
||||
return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder")
|
||||
}
|
||||
allowed := func() error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.CaptureAllowed != nil {
|
||||
return cfg.CaptureAllowed()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := allowed(); err != nil {
|
||||
return ChunkHead{}, err
|
||||
}
|
||||
head, err := remote.GetHead(ctx)
|
||||
if err != nil {
|
||||
return ChunkHead{}, err
|
||||
}
|
||||
if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) {
|
||||
return ChunkHead{}, ErrChunkLayerFenced
|
||||
}
|
||||
// Preparation uses exactly the validated image this CAS will protect.
|
||||
// A failing seed cannot fence the old holder before this host is ready.
|
||||
if cfg.PrepareRestore != nil {
|
||||
if err := cfg.PrepareRestore(copyHead(head)); err != nil {
|
||||
return ChunkHead{}, fmt.Errorf("storage: prepare HEAD restore: %w", err)
|
||||
}
|
||||
}
|
||||
if err := allowed(); err != nil {
|
||||
return ChunkHead{}, err
|
||||
}
|
||||
// No HEAD is a new volume, not a restore: there is no old holder to
|
||||
// fence. The first content cut keeps exclusive-create semantics.
|
||||
if head.Gen == 0 {
|
||||
return head, nil
|
||||
}
|
||||
if head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder && !chunkHeadIsDetached(head) && head.DetachedBy == nil {
|
||||
return head, allowed() // idempotent restart or settled prior claim
|
||||
}
|
||||
next := copyHead(head)
|
||||
next.Epoch, next.Holder = cfg.Epoch, cfg.Holder
|
||||
// A new holder's takeover starts serving the same image as active. The
|
||||
// previous holder's final-cut proof belongs only to its detached HEAD.
|
||||
next.State, next.DetachedBy = chunkHeadActive, nil
|
||||
if err := allowed(); err != nil {
|
||||
return ChunkHead{}, err
|
||||
}
|
||||
gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next)
|
||||
if casErr == nil {
|
||||
next.Gen = gen
|
||||
return next, allowed()
|
||||
}
|
||||
// Never blindly replay a possibly committed takeover. A re-read must
|
||||
// prove the exact proposal; otherwise the volume remains nonoperational.
|
||||
current, readErr := remote.GetHead(ctx)
|
||||
if readErr != nil {
|
||||
return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr))
|
||||
}
|
||||
if current.Gen > head.Gen && sameProposal(current, next) {
|
||||
return current, allowed()
|
||||
}
|
||||
return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClaimChunkHeadClearsProductionDetachProof(t *testing.T) {
|
||||
s, path := newChunkTestStore(t)
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := NewMemChunkRemote()
|
||||
layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old", Bitmap: NewFileChunkBitmapStore(path + ".bitmap")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Write(0, bytes.Repeat([]byte{0xD7}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detached, err := layer.Detach(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detached.Head.State != chunkHeadDetached || detached.Head.DetachedBy == nil {
|
||||
t.Fatal("producer did not detach", detached.Head)
|
||||
}
|
||||
claimed, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 2, Holder: "new"})
|
||||
if err != nil {
|
||||
t.Fatal("takeover of production detached HEAD", err)
|
||||
}
|
||||
if claimed.State != chunkHeadActive || claimed.DetachedBy != nil || claimed.RemoteLSN != detached.H {
|
||||
t.Fatalf("takeover retained detached proof or changed frontier: %+v", claimed)
|
||||
}
|
||||
}
|
||||
|
||||
type claimFaultRemote struct {
|
||||
ChunkRemote
|
||||
applied, failRead, called bool
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *claimFaultRemote) CASHead(ctx context.Context, expected ChunkHeadVersion, next ChunkHead) (uint64, error) {
|
||||
r.calls++
|
||||
r.called = true
|
||||
if r.applied {
|
||||
if _, err := r.ChunkRemote.CASHead(ctx, expected, next); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return 0, errors.New("injected lost CAS response")
|
||||
}
|
||||
func (r *claimFaultRemote) GetHead(ctx context.Context) (ChunkHead, error) {
|
||||
if r.called && r.failRead {
|
||||
return ChunkHead{}, errors.New("injected HEAD read outage")
|
||||
}
|
||||
return r.ChunkRemote.GetHead(ctx)
|
||||
}
|
||||
|
||||
func TestClaimChunkHeadSettlesUnknownWithoutReplay(t *testing.T) {
|
||||
for _, applied := range []bool{false, true} {
|
||||
for _, failRead := range []bool{false, true} {
|
||||
remote := NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7, Chunks: map[uint64]ChunkRef{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fault := &claimFaultRemote{ChunkRemote: remote, applied: applied, failRead: failRead}
|
||||
head, err := ClaimChunkHead(context.Background(), fault, ChunkLayerConfig{Epoch: 2, Holder: "new"})
|
||||
if (err == nil) != (applied && !failRead) {
|
||||
t.Fatalf("applied=%v readFail=%v err=%v", applied, failRead, err)
|
||||
}
|
||||
if fault.calls != 1 {
|
||||
t.Fatalf("CAS replayed %d times", fault.calls)
|
||||
}
|
||||
if err == nil && (head.Epoch != 2 || head.Holder != "new" || head.RemoteLSN != 7) {
|
||||
t.Fatal(head)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift(t *testing.T) {
|
||||
remote := NewMemChunkRemote()
|
||||
_, err := remote.CASHead(context.Background(), ChunkHeadVersion{}, ChunkHead{Epoch: 3, Holder: "current", Chunks: map[uint64]ChunkRef{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, cfg := range []ChunkLayerConfig{{Epoch: 2, Holder: "old"}, {Epoch: 3, Holder: "other"}} {
|
||||
if _, err := ClaimChunkHead(context.Background(), remote, cfg); !errors.Is(err, ErrChunkLayerFenced) {
|
||||
t.Fatalf("stale claim accepted: %v", err)
|
||||
}
|
||||
}
|
||||
before, _ := remote.GetHead(context.Background())
|
||||
checks := 0
|
||||
_, err = ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 4, Holder: "new", CaptureAllowed: func() error {
|
||||
checks++
|
||||
if checks == 2 {
|
||||
return errors.New("lineage moved")
|
||||
}
|
||||
return nil
|
||||
}})
|
||||
after, _ := remote.GetHead(context.Background())
|
||||
if err == nil || after.Gen != before.Gen || after.Epoch != 3 {
|
||||
t.Fatalf("drift published: head=%+v err=%v", after, err)
|
||||
}
|
||||
// An identical already-settled claim is idempotent and creates no new gen.
|
||||
if _, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 3, Holder: "current"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
final, _ := remote.GetHead(context.Background())
|
||||
if final.Gen != before.Gen {
|
||||
t.Fatal("idempotent claim advanced HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimChunkHeadFencesNoopCut(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
remote := newFakeChunkRemote()
|
||||
layer := mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(0, makeBlock(4096, 0xAA)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ClaimChunkHead(ctTimeout(t), remote, ChunkLayerConfig{Epoch: 2, Holder: "host-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) {
|
||||
t.Fatalf("stale no-op cut returned %v, want fenced", err)
|
||||
}
|
||||
if !layer.Fenced() {
|
||||
t.Fatal("no-op cut did not propagate fence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreshRestoreBitmapStartsAtClaimedHEAD(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
r := NewMemChunkRemote()
|
||||
if _, err := r.CASHead(ctTimeout(t), ChunkHeadVersion{}, ChunkHead{Epoch: 2, Holder: "host-a", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
mustAttach(t, s, r, cfg)
|
||||
hdr, dirty, ok, err := cfg.Bitmap.Load()
|
||||
if err != nil || !ok || hdr.BaseLSN != 42 || hdr.HeadGen != 1 || hdr.Epoch != 2 || hdr.Base != chunkBaseNone || len(dirty) != 0 {
|
||||
t.Fatalf("fresh bitmap not at HEAD: hdr=%+v dirty=%v ok=%v err=%v", hdr, dirty, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A no-op cut still consults remote authority. An outage there is retryable
|
||||
// remote unavailability, not an untyped failure or an ownership fence.
|
||||
func TestClaimChunkHeadNoopCutClassifiesRemoteReadFailure(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
remote := newFakeChunkRemote()
|
||||
layer := mustAttach(t, s, remote, ctConfig(1))
|
||||
if _, err := s.Write(0, makeBlock(4096, 0xA7)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := remote.GetHead(ctTimeout(t))
|
||||
remote.mu.Lock()
|
||||
remote.failGet = errFakeRemoteDown
|
||||
calls := remote.casCalls
|
||||
remote.mu.Unlock()
|
||||
_, err := layer.Capture(ctTimeout(t))
|
||||
if !errors.Is(err, ErrChunkRemoteUnavailable) || !errors.Is(err, errFakeRemoteDown) {
|
||||
t.Errorf("no-op authority read: %v; want remote unavailable and underlying cause", err)
|
||||
}
|
||||
if layer.Fenced() {
|
||||
t.Error("remote read outage latched an ownership fence")
|
||||
}
|
||||
remote.mu.Lock()
|
||||
if remote.casCalls != calls {
|
||||
t.Error("no-op read failure attempted a CAS")
|
||||
}
|
||||
remote.failGet = nil
|
||||
remote.mu.Unlock()
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal("retry after remote recovery", err)
|
||||
}
|
||||
after, _ := remote.GetHead(ctTimeout(t))
|
||||
if after.Gen != before.Gen || after.RemoteLSN != before.RemoteLSN {
|
||||
t.Fatal("no-op retry changed HEAD", before, after)
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ import (
|
||||
// fetch began); a local version always wins.
|
||||
//
|
||||
// The dirty bitmap stays off the write hot path. WAL entries carry their
|
||||
// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL
|
||||
// LBA, so the dirty set is always the persisted bitmap ∪ the chunks of WAL
|
||||
// entries above the checkpoint. The persisted bitmap may over-report, never
|
||||
// under-report.
|
||||
type chunkSink interface {
|
||||
@@ -137,7 +137,7 @@ type chunkDelta struct {
|
||||
// clears post-cut dirt.
|
||||
//
|
||||
// Restart or failover: a header equal to HEAD {RemoteLSN, Gen, Epoch} with
|
||||
// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪
|
||||
// Base == chunkBaseNone means incremental, dirty = persisted bitmap ∪
|
||||
// chunks of WAL entries above the checkpoint. A lost bitmap or any header
|
||||
// mismatch falls back to a per-chunk SHA-256 compare against HEAD's chunk
|
||||
// refs; only differing chunks are uploaded (Base == chunkBaseInstalling
|
||||
@@ -304,6 +304,16 @@ type chunkLayerConfig struct {
|
||||
// HEAD (every block absent, read lazily). False means an existing local
|
||||
// volume. Never inferred from the local contents.
|
||||
FreshFromHead bool
|
||||
// RestoreGuard binds fresh attachment to the HEAD the provider claimed
|
||||
// and durably seeded. A changed read refuses before hooks/readiness; the
|
||||
// next recovery must repeat claim and seed. Nil is for direct layer users.
|
||||
RestoreGuard *chunkHeadVersion
|
||||
// PrepareRestore runs after ClaimChunkHead validates its observed HEAD
|
||||
// and before any ownership CAS (also for an idempotent claim). The owner
|
||||
// durably seeds the local frontier and rebases cached ship cursors here,
|
||||
// while its frontend is gated. An error leaves remote ownership unchanged.
|
||||
// No store/layer/remote lock is held across the callback.
|
||||
PrepareRestore func(head chunkHead) error
|
||||
// CaptureAllowed is supplied by the store owner. It is an admission
|
||||
// check, made when a capture starts and again right before its HEAD CAS:
|
||||
// it refuses a cut during a BASE install or rebuild, or when this node is
|
||||
@@ -396,7 +406,7 @@ var (
|
||||
errChunkKeyInvalid = errors.New("storage: chunk key is not non-empty valid UTF-8")
|
||||
errChunkLayerDetached = errors.New("storage: chunk layer detached")
|
||||
errChunkCASOutcomeUnknown = errors.New("storage: chunk HEAD CAS outcome unknown")
|
||||
// The causes a control plane reports as typed codes (B9 W2 §2.2).
|
||||
// The causes a control plane reports as typed codes (B9 W2 §2.2).
|
||||
errChunkLayerClosed = errors.New("storage: chunk layer closed")
|
||||
errChunkBaseInstalling = errors.New("storage: chunk BASE install in progress")
|
||||
errChunkRemoteUnavailable = errors.New("storage: chunk remote unavailable")
|
||||
|
||||
Reference in new issue
Block a user