mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Clear lease stop-pending when a detach aborts and serving resumes
A detach whose final cut provably did not publish resumes serving, but the stop-pending mark set at the start of the detach stayed latched on the host and on its lease guard, so a host that kept serving renewed about four times a second for good instead of once per renewal delay. The detach hook now returns an attempt token, and the provider calls a second hook with that token only after it resumed serving on a proven abort. The host clears stop-pending, on itself and on its guard, only for the latest attempt, so an older attempt's resume cannot clear a newer pending detach; an applied, fenced or unknown outcome keeps it. Tests: the guard's sleep is now observable through a scheduling seam, so the cadence test asserts the delay chosen after each renewal and the kick path separately, with no wall-clock window; the detach hook is witnessed before the drain starts; test workers are joined, bounded and failing on timeout, before their providers are closed. The invariants document gains the StopPending mode of the lease guard (scheduling only, no admission or ACK change) and INV-WS-STOP-PENDING-001. Comments now say that 250 ms bounds the sleep after a completed renewal, not the time from a revocation to its ACK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c0297da05a
commit
3de728e23d
10 files changed
+622
-169
No files matched your search
@@ -674,9 +674,11 @@ func run(f flags) int {
|
||||
cfg.ChunkCOWSpillLimit = f.chunk.hostLimit.COWBytes
|
||||
}
|
||||
}
|
||||
// A detach is a graceful stop: the lease guard polls for the
|
||||
// revocation that follows instead of waiting out its renewal delay.
|
||||
// A detach is a graceful stop: the lease guard renews at a short
|
||||
// cadence for the revocation that follows instead of waiting out
|
||||
// its renewal delay, until the detach provably aborts and resumes.
|
||||
cfg.OnChunkDetach = h.WorkspaceStopPending
|
||||
cfg.OnChunkDetachResumed = h.WorkspaceStopResumed
|
||||
if chunkErr == nil {
|
||||
cfg.ChunkRemoteFor = chunk.remoteFor
|
||||
workspaceRemoteFor = chunk.remoteFor
|
||||
|
||||
@@ -181,9 +181,14 @@ type ProviderConfig struct {
|
||||
DetachFreezeTimeout time.Duration
|
||||
// OnChunkDetach, optional, is called with the volume id when DetachVolume
|
||||
// starts a detach (a graceful stop), before the drain and final cut, so
|
||||
// the host can watch for the coming lease revocation. It runs under the
|
||||
// volume's attach lock: it must not block or call back into the provider.
|
||||
OnChunkDetach func(volumeID string)
|
||||
// the host can watch for the coming lease revocation; it returns a token
|
||||
// for this attempt. OnChunkDetachResumed, optional, is called with that
|
||||
// token only when the detach provably did not happen and serving resumed;
|
||||
// a detach that applied, fenced or whose outcome is unknown never calls
|
||||
// it. Both run under the volume's attach lock: they must not block or
|
||||
// call back into the provider.
|
||||
OnChunkDetach func(volumeID string) uint64
|
||||
OnChunkDetachResumed func(volumeID string, attempt uint64)
|
||||
// ChunkDirtyThreshold is the number of candidate chunks above which
|
||||
// a cut pre-copies (stages) chunks before its barrier, in rounds of
|
||||
// this size; copy-before-write copies the rest outside the barrier.
|
||||
|
||||
@@ -915,8 +915,12 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
|
||||
trace("cut", dl)
|
||||
}
|
||||
h.chunkDetach = true
|
||||
var resumed func() // tells the host this attempt aborted and serving resumed
|
||||
if hook := p.cfg.OnChunkDetach; hook != nil {
|
||||
hook(volumeID)
|
||||
attempt := hook(volumeID)
|
||||
if done := p.cfg.OnChunkDetachResumed; done != nil {
|
||||
resumed = func() { done(volumeID, attempt) }
|
||||
}
|
||||
}
|
||||
if stop := p.testDetachStopIO; stop != nil {
|
||||
err = stop(cutCtx)
|
||||
@@ -949,7 +953,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
|
||||
case how == storage.DetachFenced:
|
||||
return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err)
|
||||
default:
|
||||
return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err)
|
||||
return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err, resumed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -960,8 +964,8 @@ const (
|
||||
|
||||
// resumeAfterDetach undoes a detach that provably did not happen: the
|
||||
// periodic cuts restart, the stop is lifted, and the volume serves again.
|
||||
// The caller holds h.attachMu.
|
||||
func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error {
|
||||
// Only then is resumed (if set) called. The caller holds h.attachMu.
|
||||
func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error, resumed func()) error {
|
||||
p.mu.Lock()
|
||||
closed := p.closed || h.chunk != layer
|
||||
if !closed {
|
||||
@@ -973,6 +977,9 @@ func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer
|
||||
}
|
||||
h.chunkDetach = false
|
||||
h.backend.SetOperational(true, "chunk detach aborted: serving resumed")
|
||||
if resumed != nil {
|
||||
resumed()
|
||||
}
|
||||
log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause)
|
||||
return fmt.Errorf("%w: %w", ErrDetachAborted, cause)
|
||||
}
|
||||
|
||||
@@ -2,41 +2,80 @@ package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func hookedProvider(t *testing.T) (*durable.DurableProvider, func() []string) {
|
||||
// detachHooks records the detach hooks: each detach gets the next token.
|
||||
type detachHooks struct {
|
||||
mu sync.Mutex
|
||||
next uint64
|
||||
started []string
|
||||
resumed []string
|
||||
}
|
||||
|
||||
func (k *detachHooks) detach(id string) uint64 {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
k.next++
|
||||
k.started = append(k.started, id)
|
||||
return k.next
|
||||
}
|
||||
|
||||
func (k *detachHooks) resume(id string, attempt uint64) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
k.resumed = append(k.resumed, fmt.Sprintf("%s#%d", id, attempt))
|
||||
}
|
||||
|
||||
func (k *detachHooks) calls() (started, resumed []string) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
return append([]string(nil), k.started...), append([]string(nil), k.resumed...)
|
||||
}
|
||||
|
||||
// hookedProvider is detachFixture's volume (one cut published, one dirty
|
||||
// block) with both detach hooks wired.
|
||||
func hookedProvider(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend, *detachHooks) {
|
||||
t.Helper()
|
||||
remote := storage.NewMemChunkRemote()
|
||||
var mu sync.Mutex
|
||||
var calls []string
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
k := &detachHooks{}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk,
|
||||
StorageRoot: t.TempDir(),
|
||||
BlockSize: 4096,
|
||||
NumBlocks: pcBlocks,
|
||||
ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
OnChunkDetach: func(id string) {
|
||||
mu.Lock()
|
||||
calls = append(calls, id)
|
||||
mu.Unlock()
|
||||
},
|
||||
Impl: durable.ImplWALStoreChunk,
|
||||
StorageRoot: t.TempDir(),
|
||||
BlockSize: 4096,
|
||||
NumBlocks: pcBlocks,
|
||||
ChunkBlocks: pcChunkBlocks,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
OnChunkDetach: k.detach,
|
||||
OnChunkDetachResumed: k.resume,
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
t.Fatalf("NewDurableProvider: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
openRecovered(t, p)
|
||||
return p, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), calls...)
|
||||
ctx := context.Background()
|
||||
b, err := p.Open(ctx, "v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(ctx, 4096, block(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.CutVolume(ctx, "v1", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write(ctx, 8192, block(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return remote, p, b, k
|
||||
}
|
||||
|
||||
// A detach (graceful stop) tells the host once, with the volume id; the
|
||||
@@ -44,21 +83,116 @@ func hookedProvider(t *testing.T) (*durable.DurableProvider, func() []string) {
|
||||
func TestWALStoreChunk_DetachCallsStopHook(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Run("detach", func(t *testing.T) {
|
||||
p, calls := hookedProvider(t)
|
||||
_, p, _, k := hookedProvider(t)
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := calls(); len(got) != 1 || got[0] != "v1" {
|
||||
t.Fatalf("detach hook calls %q, want [v1]", got)
|
||||
if started, resumed := k.calls(); len(started) != 1 || started[0] != "v1" || len(resumed) != 0 {
|
||||
t.Fatalf("detach hook calls %q, resumed %q; want [v1], none", started, resumed)
|
||||
}
|
||||
})
|
||||
t.Run("fence-stop", func(t *testing.T) {
|
||||
p, calls := hookedProvider(t)
|
||||
_, p, _, k := hookedProvider(t)
|
||||
if err := p.Backend("v1").StopIO(ctx, "workspace lease fenced"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := calls(); len(got) != 0 {
|
||||
t.Fatalf("lease-fence StopIO called the detach hook: %q", got)
|
||||
if started, resumed := k.calls(); len(started) != 0 || len(resumed) != 0 {
|
||||
t.Fatalf("lease-fence StopIO called the detach hooks: %q %q", started, resumed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The hook runs before the drain starts (and so before the final cut, which
|
||||
// follows the drain): the host learns of the stop while guest I/O is still
|
||||
// being drained, not after.
|
||||
func TestWALStoreChunk_DetachHookPrecedesDrain(t *testing.T) {
|
||||
_, p, _, k := hookedProvider(t)
|
||||
drains, hookedAtDrain := 0, -1
|
||||
durable.SetTestDetachStopIO(p, func(ctx context.Context) error {
|
||||
drains++
|
||||
started, _ := k.calls()
|
||||
hookedAtDrain = len(started)
|
||||
return p.Backend("v1").StopIO(ctx, "chunk detach: I/O stopped until a new attach")
|
||||
})
|
||||
r, _, err := p.DetachVolume(context.Background(), "v1")
|
||||
if err != nil || r.Head.State != storage.ChunkHeadDetached {
|
||||
t.Fatalf("detach: %+v %v", r, err)
|
||||
}
|
||||
if drains != 1 {
|
||||
t.Fatalf("drain ran %d times, want 1", drains)
|
||||
}
|
||||
if hookedAtDrain != 1 {
|
||||
t.Fatalf("detach hook calls when the drain started: %d, want 1 (the hook precedes the drain)", hookedAtDrain)
|
||||
}
|
||||
}
|
||||
|
||||
// The resume hook is called with the attempt's own token exactly when a
|
||||
// failed detach provably did not happen and serving resumed; a detach that
|
||||
// applied, is fenced, or whose outcome is unknown never calls it.
|
||||
func TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Run("refused-cas-aborts", func(t *testing.T) {
|
||||
remote, p, b, k := hookedProvider(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "precondition" })
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err)
|
||||
}
|
||||
if _, resumed := k.calls(); len(resumed) != 1 || resumed[0] != "v1#1" {
|
||||
t.Fatalf("resume hook calls %q, want [v1#1]", resumed)
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
})
|
||||
t.Run("failed-drain-aborts-each-attempt", func(t *testing.T) {
|
||||
remote, p, b, k := hookedProvider(t)
|
||||
durable.SetTestDetachStopIO(p, func(context.Context) error { return context.Canceled })
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach %d with a failed drain: %v; want ErrDetachAborted", i+1, err)
|
||||
}
|
||||
}
|
||||
if _, resumed := k.calls(); len(resumed) != 2 || resumed[0] != "v1#1" || resumed[1] != "v1#2" {
|
||||
t.Fatalf("resume hook calls %q, want [v1#1 v1#2] (each attempt's own token)", resumed)
|
||||
}
|
||||
durable.SetTestDetachStopIO(p, nil)
|
||||
assertServing(t, p, b, remote)
|
||||
})
|
||||
t.Run("applied-lost-reply", func(t *testing.T) {
|
||||
remote, p, _, k := hookedProvider(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "applied-lost" })
|
||||
if r, _, err := p.DetachVolume(ctx, "v1"); err != nil || r.Head.State != storage.ChunkHeadDetached {
|
||||
t.Fatalf("detach whose CAS applied: %+v %v; want the detached result", r, err)
|
||||
}
|
||||
if _, resumed := k.calls(); len(resumed) != 0 {
|
||||
t.Fatalf("resume hook called on an applied detach: %q", resumed)
|
||||
}
|
||||
})
|
||||
t.Run("unknown", func(t *testing.T) {
|
||||
remote, p, _, k := hookedProvider(t)
|
||||
remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected })
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err)
|
||||
}
|
||||
if _, resumed := k.calls(); len(resumed) != 0 {
|
||||
t.Fatalf("resume hook called on an unknown detach outcome: %q", resumed)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.getHeadErr = nil })
|
||||
})
|
||||
t.Run("fenced", func(t *testing.T) {
|
||||
remote, p, _, k := hookedProvider(t)
|
||||
cur, err := remote.MemChunkRemote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newer := cur
|
||||
newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder"
|
||||
if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("detach against a newer epoch: %v; want fenced", err)
|
||||
}
|
||||
if _, resumed := k.calls(); len(resumed) != 0 {
|
||||
t.Fatalf("resume hook called on a fenced detach: %q", resumed)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -171,7 +171,11 @@ type Host struct {
|
||||
// workspaceLeaseMu -> guard.mu; never hold either across RPC or drain.
|
||||
workspaceLeaseMu sync.Mutex
|
||||
workspaceLeaseFenced bool
|
||||
// workspaceStopPending is the guard's stop-pending mode, kept here for a
|
||||
// guard installed later; workspaceStopAttempt numbers detach attempts so
|
||||
// only the latest one's resume clears it.
|
||||
workspaceStopPending bool
|
||||
workspaceStopAttempt uint64
|
||||
readyOnce atomic.Bool
|
||||
readyMarkerMu sync.Mutex
|
||||
supportingReadyMarks map[string]struct{}
|
||||
|
||||
@@ -39,21 +39,28 @@ type WorkspaceLeaseGuard struct {
|
||||
// because the shutdown it triggers is otherwise silent (issue #205).
|
||||
cause string
|
||||
logged bool
|
||||
// stopPending is set by StopPending and never cleared: a detached host
|
||||
// does not serve again under this guard. kick wakes Run from its sleep.
|
||||
// stopPending is a scheduling-only mode, it changes no admission or ACK
|
||||
// rule: set by StopPending when a detach starts, cleared by
|
||||
// ClearStopPending only when that detach provably did not happen and
|
||||
// serving resumed; otherwise it lasts until the guard fences. kick wakes
|
||||
// Run from its sleep.
|
||||
stopPending bool
|
||||
kick chan struct{}
|
||||
// after schedules Run's sleep between renewals (time.After; tests
|
||||
// replace it before Run starts to observe the delays chosen).
|
||||
after func(time.Duration) <-chan time.Time
|
||||
}
|
||||
|
||||
// stopPendingPoll is the renewal cadence while a stop is pending, so the
|
||||
// master's revocation is seen within this bound instead of the normal
|
||||
// renewal delay (up to 10 s).
|
||||
// stopPendingPoll caps Run's sleep after a completed renewal while a stop is
|
||||
// pending (the normal sleep is up to 10 s). It bounds scheduling only: a kick
|
||||
// does not interrupt a renewal already in flight, and the time from a
|
||||
// revocation to its ACK also includes that renewal, the drain and the ACK.
|
||||
const stopPendingPoll = 250 * time.Millisecond
|
||||
|
||||
// StopPending records that a graceful stop of this workspace has begun (the
|
||||
// chunk layer is being detached) and wakes Run to renew at once; from then on
|
||||
// Run renews every stopPendingPoll until the guard fences. Idempotent, safe
|
||||
// from any goroutine, never blocks and makes no RPC.
|
||||
// chunk layer is being detached) and wakes Run to renew at once; while it
|
||||
// stays pending Run sleeps at most stopPendingPoll between renewals.
|
||||
// Idempotent, safe from any goroutine, never blocks and makes no RPC.
|
||||
func (g *WorkspaceLeaseGuard) StopPending() {
|
||||
g.mu.Lock()
|
||||
g.stopPending = true
|
||||
@@ -64,6 +71,42 @@ func (g *WorkspaceLeaseGuard) StopPending() {
|
||||
}
|
||||
}
|
||||
|
||||
// ClearStopPending leaves stop-pending after a detach that provably did not
|
||||
// happen (serving resumed): Run's next sleep is the normal renewal delay
|
||||
// again, and a kick not yet consumed is dropped. Never blocks, makes no RPC.
|
||||
func (g *WorkspaceLeaseGuard) ClearStopPending() {
|
||||
g.mu.Lock()
|
||||
g.stopPending = false
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-g.kick:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// renewDelay is Run's sleep after a renewal: a third of the remaining lease
|
||||
// (1 s before any grant) within [50 ms, 10 s], and at most stopPendingPoll
|
||||
// while a stop is pending.
|
||||
func (g *WorkspaceLeaseGuard) renewDelay() time.Duration {
|
||||
g.mu.Lock()
|
||||
delay := g.until.Sub(g.now()) / 3
|
||||
if g.until.IsZero() {
|
||||
delay = time.Second
|
||||
}
|
||||
pending := g.stopPending
|
||||
g.mu.Unlock()
|
||||
if delay < 50*time.Millisecond {
|
||||
delay = 50 * time.Millisecond
|
||||
}
|
||||
if delay > 10*time.Second {
|
||||
delay = 10 * time.Second
|
||||
}
|
||||
if pending && delay > stopPendingPoll {
|
||||
delay = stopPendingPoll
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
// fenceLocked latches the fence and records its first cause. Caller holds mu.
|
||||
func (g *WorkspaceLeaseGuard) fenceLocked(cause string) {
|
||||
g.fenced = true
|
||||
@@ -99,7 +142,7 @@ func NewWorkspaceLeaseGuard(base frontend.ProjectionView, client WorkspaceLeaseC
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch}, stop: stop, now: now, kick: make(chan struct{}, 1)}, nil
|
||||
return &WorkspaceLeaseGuard{base: base, client: client, id: control.WorkspaceIdentity{VolumeId: id.VolumeId, ReplicaId: id.ReplicaId, Epoch: id.Epoch}, stop: stop, now: now, kick: make(chan struct{}, 1), after: time.After}, nil
|
||||
}
|
||||
|
||||
func (g *WorkspaceLeaseGuard) Projection() frontend.Projection {
|
||||
@@ -286,22 +329,7 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error {
|
||||
if closed {
|
||||
return err
|
||||
}
|
||||
g.mu.Lock()
|
||||
delay := g.until.Sub(g.now()) / 3
|
||||
if g.until.IsZero() {
|
||||
delay = time.Second
|
||||
}
|
||||
pending := g.stopPending
|
||||
g.mu.Unlock()
|
||||
if delay < 50*time.Millisecond {
|
||||
delay = 50 * time.Millisecond
|
||||
}
|
||||
if delay > 10*time.Second {
|
||||
delay = 10 * time.Second
|
||||
}
|
||||
if pending && delay > stopPendingPoll {
|
||||
delay = stopPendingPoll
|
||||
}
|
||||
wake := g.after(g.renewDelay())
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
g.operation.Lock()
|
||||
@@ -312,7 +340,7 @@ func (g *WorkspaceLeaseGuard) Run(ctx context.Context) error {
|
||||
err := g.drain(ctx, false)
|
||||
g.operation.Unlock()
|
||||
return err
|
||||
case <-time.After(delay):
|
||||
case <-wake:
|
||||
case <-g.kick:
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -12,11 +13,42 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// stopPendingClient grants 30 s leases (normal renewal delay 10 s) and
|
||||
// records when each renewal arrived; revoking makes the next reply revoke.
|
||||
// joinTimeout bounds a test's wait for a lease worker it cancelled. The
|
||||
// guard's own drain budget is 5 s for the stop callback plus 2 s for an ACK;
|
||||
// the join allows that and leaves margin for scheduling and settlement.
|
||||
const joinTimeout = 15 * time.Second
|
||||
|
||||
// startJoined runs run in a worker. Before the worker starts it registers the
|
||||
// cleanup that cancels it, waits for it (at most joinTimeout; a timeout fails
|
||||
// the test) and only after the worker is seen done runs teardown, so a failed
|
||||
// assertion never closes resources under a still-running worker.
|
||||
func startJoined(t *testing.T, run func(context.Context) error, teardown func()) <-chan error {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done, finished := make(chan error, 1), make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-finished:
|
||||
if teardown != nil {
|
||||
teardown()
|
||||
}
|
||||
case <-time.After(joinTimeout):
|
||||
t.Errorf("lease worker not joined within %s of its cancel; teardown skipped", joinTimeout)
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
done <- run(ctx)
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
// stopPendingClient grants 30 s leases (normal renewal delay 10 s) and counts
|
||||
// renewals; revoking makes the next reply revoke.
|
||||
type stopPendingClient struct {
|
||||
mu sync.Mutex
|
||||
at []time.Time
|
||||
renewals int
|
||||
revoking bool
|
||||
acks int
|
||||
}
|
||||
@@ -25,7 +57,7 @@ func (c *stopPendingClient) client() workspaceTestClient {
|
||||
return workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.at = append(c.at, time.Now())
|
||||
c.renewals++
|
||||
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second), Revoking: c.revoking}, nil
|
||||
}, ack: func() error {
|
||||
c.mu.Lock()
|
||||
@@ -35,85 +67,115 @@ func (c *stopPendingClient) client() workspaceTestClient {
|
||||
}}
|
||||
}
|
||||
|
||||
func (c *stopPendingClient) renewals() []time.Time {
|
||||
func (c *stopPendingClient) count() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return append([]time.Time(nil), c.at...)
|
||||
return c.renewals
|
||||
}
|
||||
|
||||
func awaitRenewals(t *testing.T, c *stopPendingClient, n int, within time.Duration) []time.Time {
|
||||
// scheduler replaces the guard's sleep: it records every delay Run chooses
|
||||
// after a renewal and wakes Run only when the test fires it, so the cadence
|
||||
// is asserted on the delay itself, with no wall-clock window.
|
||||
type scheduler struct {
|
||||
delays chan time.Duration
|
||||
wake chan time.Time
|
||||
}
|
||||
|
||||
func newScheduler(g *WorkspaceLeaseGuard) *scheduler {
|
||||
s := &scheduler{delays: make(chan time.Duration, 16), wake: make(chan time.Time)}
|
||||
g.after = func(d time.Duration) <-chan time.Time {
|
||||
s.delays <- d
|
||||
return s.wake
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// next is the delay Run chose after its latest renewal. A Run that never
|
||||
// renews again (a kick it ignored) fails here, after a generous bound.
|
||||
func (s *scheduler) next(t *testing.T, what string) time.Duration {
|
||||
t.Helper()
|
||||
end := time.Now().Add(within)
|
||||
for {
|
||||
at := c.renewals()
|
||||
if len(at) >= n {
|
||||
return at
|
||||
}
|
||||
if time.Now().After(end) {
|
||||
t.Fatalf("%d renewals within %s, want %d", len(at), within, n)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
select {
|
||||
case d := <-s.delays:
|
||||
return d
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s: Run did not renew and schedule its next sleep", what)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// While no stop is pending a 30 s lease renews every 10 s; StopPending
|
||||
// renews at once and then every stopPendingPoll, so the revocation that
|
||||
// follows a detach fences within a poll, not within a renewal delay.
|
||||
func TestWorkspaceLeaseStopPendingPollsFast(t *testing.T) {
|
||||
func (s *scheduler) fire(t *testing.T) {
|
||||
t.Helper()
|
||||
select {
|
||||
case s.wake <- time.Now():
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Run is not sleeping on the scheduler")
|
||||
}
|
||||
}
|
||||
|
||||
// pendingSleepBound is the documented stop-pending bound
|
||||
// (INV-WS-STOP-PENDING-001), written out so a changed stopPendingPoll fails.
|
||||
const pendingSleepBound = 250 * time.Millisecond
|
||||
|
||||
// The schedule, step by step: a 30 s lease sleeps ~10 s; StopPending renews
|
||||
// at once (the kick, without the sleep ending) and every following sleep is
|
||||
// at most pendingSleepBound; ClearStopPending restores the normal sleep; a
|
||||
// revocation then fences and ACKs.
|
||||
func TestWorkspaceLeaseStopPendingSchedule(t *testing.T) {
|
||||
c := &stopPendingClient{}
|
||||
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, c.client(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- g.Run(ctx) }()
|
||||
awaitRenewals(t, c, 1, 5*time.Second)
|
||||
s := newScheduler(g)
|
||||
done := startJoined(t, g.Run, nil)
|
||||
|
||||
// Normal cadence: nothing more for a while (the next renewal is ~10 s out).
|
||||
time.Sleep(time.Second)
|
||||
if n := len(c.renewals()); n != 1 {
|
||||
t.Fatalf("%d renewals in the first second of a 30 s lease, want 1", n)
|
||||
if d := s.next(t, "first renewal"); d <= 5*time.Second {
|
||||
t.Fatalf("sleep %s after renewing a 30 s lease, want the normal ~10 s", d)
|
||||
}
|
||||
|
||||
kicked := time.Now()
|
||||
g.StopPending()
|
||||
g.StopPending() // idempotent, never blocks
|
||||
at := awaitRenewals(t, c, 2, time.Second)
|
||||
if d := at[1].Sub(kicked); d > 200*time.Millisecond {
|
||||
t.Fatalf("first renewal %s after StopPending, want immediate", d)
|
||||
// The kick alone wakes Run: the scheduled sleep is never fired here.
|
||||
if d := s.next(t, "renewal on the StopPending kick"); d > pendingSleepBound {
|
||||
t.Fatalf("sleep %s after the kicked renewal, want at most %s", d, pendingSleepBound)
|
||||
}
|
||||
if n := c.count(); n != 2 {
|
||||
t.Fatalf("%d renewals after the kick, want 2", n)
|
||||
}
|
||||
s.fire(t)
|
||||
if d := s.next(t, "renewal while pending"); d > pendingSleepBound {
|
||||
t.Fatalf("sleep %s after a renewal while a stop is pending, want at most %s", d, pendingSleepBound)
|
||||
}
|
||||
|
||||
// Pending cadence: ~250 ms, so 1.5 s holds about 6 more renewals.
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
at = c.renewals()
|
||||
extra := len(at) - 2
|
||||
if extra < 3 || extra > 10 {
|
||||
t.Fatalf("%d renewals in 1.5 s while a stop is pending, want about 6 (every %s)", extra, stopPendingPoll)
|
||||
g.ClearStopPending()
|
||||
s.fire(t)
|
||||
if d := s.next(t, "renewal after clear"); d <= 5*time.Second {
|
||||
t.Fatalf("sleep %s after ClearStopPending, want the normal ~10 s again", d)
|
||||
}
|
||||
if n := c.count(); n != 4 {
|
||||
t.Fatalf("%d renewals, want 4 (a stale kick must not add one)", n)
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.revoking = true
|
||||
c.mu.Unlock()
|
||||
revoked := time.Now()
|
||||
s.fire(t)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("revocation ACK path: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("guard did not fence on the revocation within 2 s of it")
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("guard did not fence on the revocation")
|
||||
}
|
||||
if d := time.Since(revoked); d > time.Second {
|
||||
t.Fatalf("fenced %s after the revocation, want within a poll", d)
|
||||
}
|
||||
if g.FenceCause() != "revoked by the master" || c.acks != 1 {
|
||||
t.Fatalf("cause %q acks %d", g.FenceCause(), c.acks)
|
||||
c.mu.Lock()
|
||||
acks := c.acks
|
||||
c.mu.Unlock()
|
||||
if g.FenceCause() != "revoked by the master" || acks != 1 {
|
||||
t.Fatalf("cause %q acks %d", g.FenceCause(), acks)
|
||||
}
|
||||
}
|
||||
|
||||
// StopPending before Run and on a guard that already fenced never blocks.
|
||||
// StopPending and ClearStopPending before Run, repeated, never block.
|
||||
func TestWorkspaceLeaseStopPendingNeverBlocks(t *testing.T) {
|
||||
c := &stopPendingClient{}
|
||||
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, c.client(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, nil)
|
||||
@@ -124,92 +186,267 @@ func TestWorkspaceLeaseStopPendingNeverBlocks(t *testing.T) {
|
||||
go func() {
|
||||
for i := 0; i < 5; i++ {
|
||||
g.StopPending()
|
||||
g.ClearStopPending()
|
||||
g.StopPending()
|
||||
}
|
||||
close(finished)
|
||||
}()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("StopPending blocked")
|
||||
t.Fatal("StopPending/ClearStopPending blocked")
|
||||
}
|
||||
}
|
||||
|
||||
// Host wiring: the provider's detach hook, connected to the host, makes the
|
||||
// real lease runtime see the revocation that follows a detach within a
|
||||
// poll, where the 30 s lease's renewal delay would be 10 s.
|
||||
func TestWorkspaceHostDetachHookFencesWithinPoll(t *testing.T) {
|
||||
var stopped atomic.Bool
|
||||
wire := &runtimeLeaseServer{ttl: 30 * time.Second, stopped: &stopped}
|
||||
h := workspaceRuntimeHost(t, runtimeWire(t, wire), true)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
var hooked atomic.Int32
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1",
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
OnChunkDetach: func(id string) { hooked.Add(1); h.WorkspaceStopPending(id) }}, h.ProjectionView())
|
||||
func guardPending(g *WorkspaceLeaseGuard) bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
return g.stopPending
|
||||
}
|
||||
|
||||
// Detach attempts are numbered: only the latest attempt's resume clears
|
||||
// stop-pending, on the host and on the installed guard; an older attempt's,
|
||||
// another volume's or a repeated resume changes nothing.
|
||||
func TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt(t *testing.T) {
|
||||
h := workspaceRuntimeHost(t, "127.0.0.1:1", true)
|
||||
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, (&stopPendingClient{}).client(), &control.WorkspaceIdentity{VolumeId: "v1", ReplicaId: "r1", Epoch: 3}, func(context.Context) (uint64, error) { return 7, nil }, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Close() })
|
||||
h.view.workspaceGuard.Store(g)
|
||||
pending := func() (bool, bool) {
|
||||
h.workspaceLeaseMu.Lock()
|
||||
defer h.workspaceLeaseMu.Unlock()
|
||||
return h.workspaceStopPending, guardPending(g)
|
||||
}
|
||||
if a := h.WorkspaceStopPending("other"); a != 0 {
|
||||
t.Fatalf("another volume's detach got token %d, want 0", a)
|
||||
}
|
||||
if hp, gp := pending(); hp || gp {
|
||||
t.Fatal("another volume's detach set stop-pending")
|
||||
}
|
||||
older := h.WorkspaceStopPending("v1")
|
||||
newer := h.WorkspaceStopPending("v1")
|
||||
if older == 0 || newer == older {
|
||||
t.Fatalf("attempt tokens %d, %d: want distinct and non-zero", older, newer)
|
||||
}
|
||||
h.WorkspaceStopResumed("v1", older)
|
||||
if hp, gp := pending(); !hp || !gp {
|
||||
t.Fatalf("an older attempt's resume cleared a newer pending detach (host %v, guard %v)", hp, gp)
|
||||
}
|
||||
h.WorkspaceStopResumed("other", newer)
|
||||
h.WorkspaceStopResumed("v1", 0)
|
||||
if hp, gp := pending(); !hp || !gp {
|
||||
t.Fatal("a resume for another volume or token 0 cleared stop-pending")
|
||||
}
|
||||
h.WorkspaceStopResumed("v1", newer)
|
||||
if hp, gp := pending(); hp || gp {
|
||||
t.Fatalf("the latest attempt's resume left stop-pending (host %v, guard %v)", hp, gp)
|
||||
}
|
||||
if d := g.renewDelay(); d <= stopPendingPoll {
|
||||
t.Fatalf("sleep %s after the resume, want the normal delay", d)
|
||||
}
|
||||
h.WorkspaceStopPending("v1")
|
||||
h.WorkspaceStopResumed("v1", newer) // the resumed attempt again: stale now
|
||||
if hp, gp := pending(); !hp || !gp {
|
||||
t.Fatal("a stale resume cleared a later detach")
|
||||
}
|
||||
}
|
||||
|
||||
// detachFaultRemote makes the next detach fail one way.
|
||||
type detachFaultRemote struct {
|
||||
*storage.MemChunkRemote
|
||||
mu sync.Mutex
|
||||
casMode string // "refuse": precondition, not applied; "lost": not applied, error
|
||||
getHeadErr error
|
||||
}
|
||||
|
||||
var errInjectedRemote = errors.New("injected remote fault")
|
||||
|
||||
func (r *detachFaultRemote) set(mode string, headErr error) {
|
||||
r.mu.Lock()
|
||||
r.casMode, r.getHeadErr = mode, headErr
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *detachFaultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
r.mu.Lock()
|
||||
err := r.getHeadErr
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return storage.ChunkHead{}, err
|
||||
}
|
||||
return r.MemChunkRemote.GetHead(ctx)
|
||||
}
|
||||
|
||||
func (r *detachFaultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
r.mu.Lock()
|
||||
mode := r.casMode
|
||||
r.casMode = ""
|
||||
r.mu.Unlock()
|
||||
switch mode {
|
||||
case "refuse":
|
||||
return 0, storage.ErrChunkHeadPrecondition
|
||||
case "lost":
|
||||
return 0, errInjectedRemote
|
||||
}
|
||||
return r.MemChunkRemote.CASHead(ctx, expected, next)
|
||||
}
|
||||
|
||||
// detachHost is a leased workspace host whose provider reports detaches to
|
||||
// it through both hooks, as blockvolume wires them.
|
||||
type detachHost struct {
|
||||
h *Host
|
||||
p *durable.DurableProvider
|
||||
wire *runtimeLeaseServer
|
||||
remote *detachFaultRemote
|
||||
done <-chan error
|
||||
}
|
||||
|
||||
func newDetachHost(t *testing.T) *detachHost {
|
||||
t.Helper()
|
||||
var stopped atomic.Bool
|
||||
d := &detachHost{wire: &runtimeLeaseServer{ttl: 30 * time.Second, stopped: &stopped}, remote: &detachFaultRemote{MemChunkRemote: storage.NewMemChunkRemote()}}
|
||||
d.h = workspaceRuntimeHost(t, runtimeWire(t, d.wire), true)
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8, ChunkHolder: "node-a/r1",
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return d.remote, nil },
|
||||
OnChunkDetach: d.h.WorkspaceStopPending,
|
||||
OnChunkDetachResumed: d.h.WorkspaceStopResumed}, d.h.ProjectionView())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.p = p
|
||||
handedOver := false
|
||||
t.Cleanup(func() { // only while no runtime exists; see handedOver below
|
||||
if !handedOver {
|
||||
_ = p.Close()
|
||||
}
|
||||
})
|
||||
if _, err = p.EnsureStorage("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
stopAt := make(chan time.Time, 1)
|
||||
done, finished := make(chan error, 1), make(chan struct{})
|
||||
// On a failed assertion the runtime still drains: let it finish before
|
||||
// the provider is closed (cleanups run in reverse order).
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
done <- h.RunWorkspaceLease(ctx, func(c context.Context, id *control.WorkspaceIdentity) (uint64, error) {
|
||||
stopAt <- time.Now()
|
||||
// From here the provider is closed only by the joined teardown, after the
|
||||
// runtime is seen done.
|
||||
handedOver = true
|
||||
d.done = startJoined(t, func(ctx context.Context) error {
|
||||
return d.h.RunWorkspaceLease(ctx, func(c context.Context, id *control.WorkspaceIdentity) (uint64, error) {
|
||||
if err := p.Backend("v1").StopIO(c, "workspace lease fenced"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stopped.Store(true)
|
||||
head, err := remote.GetHead(c)
|
||||
head, err := d.remote.MemChunkRemote.GetHead(c)
|
||||
return head.Gen, err
|
||||
})
|
||||
}()
|
||||
}, func() { _ = p.Close() })
|
||||
runtimeAwait(t, "leased operational provider", func() bool {
|
||||
st := p.DurableStatuses()
|
||||
return h.ProjectionView().Projection().Healthy && len(st) == 1 && st[0].Operational
|
||||
return d.h.ProjectionView().Projection().Healthy && len(st) == 1 && st[0].Operational && d.h.view.workspaceGuard.Load() != nil
|
||||
})
|
||||
if _, _, err := p.DetachVolume(ctx, "v1"); err != nil {
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *detachHost) pending() bool {
|
||||
d.h.workspaceLeaseMu.Lock()
|
||||
defer d.h.workspaceLeaseMu.Unlock()
|
||||
g := d.h.view.workspaceGuard.Load()
|
||||
return d.h.workspaceStopPending || (g != nil && guardPending(g))
|
||||
}
|
||||
|
||||
func (d *detachHost) renewals() int {
|
||||
d.wire.mu.Lock()
|
||||
defer d.wire.mu.Unlock()
|
||||
return d.wire.renewals
|
||||
}
|
||||
|
||||
// Host wiring: the provider's detach hook makes the real lease runtime see
|
||||
// the revocation that follows a detach soon after it, where the 30 s lease's
|
||||
// renewal delay would be 10 s.
|
||||
func TestWorkspaceHostDetachHookFencesWithinPoll(t *testing.T) {
|
||||
d := newDetachHost(t)
|
||||
if _, _, err := d.p.DetachVolume(context.Background(), "v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hooked.Load() != 1 {
|
||||
t.Fatalf("detach hook called %d times, want 1", hooked.Load())
|
||||
if !d.pending() {
|
||||
t.Fatal("a detach did not set stop-pending")
|
||||
}
|
||||
wire.mu.Lock()
|
||||
wire.revoking = true
|
||||
wire.mu.Unlock()
|
||||
d.wire.mu.Lock()
|
||||
d.wire.revoking = true
|
||||
d.wire.mu.Unlock()
|
||||
revoked := time.Now()
|
||||
select {
|
||||
case at := <-stopAt:
|
||||
if d := at.Sub(revoked); d > 2*time.Second {
|
||||
t.Fatalf("host stopped %s after the revocation, want within a poll", d)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("host did not see the revocation within 3 s of a detach (renewal delay is 10 s)")
|
||||
}
|
||||
if err := runtimeDone(t, done); err != nil {
|
||||
if err := runtimeDone(t, d.done); err != nil {
|
||||
t.Fatalf("revocation ACK path: %v", err)
|
||||
}
|
||||
wire.mu.Lock()
|
||||
acks := wire.acks
|
||||
wire.mu.Unlock()
|
||||
if took := time.Since(revoked); took > 3*time.Second {
|
||||
t.Fatalf("revocation ACKed %s after it, want well inside the 10 s renewal delay", took)
|
||||
}
|
||||
d.wire.mu.Lock()
|
||||
acks := d.wire.acks
|
||||
d.wire.mu.Unlock()
|
||||
if acks != 1 {
|
||||
t.Fatalf("acks %d, want 1", acks)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed detach that provably did not happen resumes serving and leaves
|
||||
// stop-pending: the guard is back on its normal renewal delay. A detach whose
|
||||
// outcome is unknown, or that is fenced, stays stopped and stays pending.
|
||||
func TestWorkspaceHostFailedDetachStopPendingByOutcome(t *testing.T) {
|
||||
t.Run("aborted-resumes-normal-cadence", func(t *testing.T) {
|
||||
d := newDetachHost(t)
|
||||
d.remote.set("refuse", nil)
|
||||
if _, _, err := d.p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) {
|
||||
t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err)
|
||||
}
|
||||
if st := d.p.DurableStatuses(); len(st) != 1 || !st[0].Operational {
|
||||
t.Fatal("serving did not resume after the aborted detach")
|
||||
}
|
||||
if d.pending() {
|
||||
t.Fatal("stop-pending survived a detach that provably aborted and resumed serving")
|
||||
}
|
||||
if delay := d.h.view.workspaceGuard.Load().renewDelay(); delay <= stopPendingPoll {
|
||||
t.Fatalf("guard sleep %s after the resume, want the normal delay", delay)
|
||||
}
|
||||
// The sleep already running when the resume came is at most one poll;
|
||||
// after it the guard renews once more and then sleeps ~10 s. Pending,
|
||||
// it would renew about four times a second.
|
||||
time.Sleep(4 * stopPendingPoll)
|
||||
before := d.renewals()
|
||||
time.Sleep(8 * stopPendingPoll)
|
||||
if after := d.renewals(); after != before {
|
||||
t.Fatalf("%d renewals in %s after the resume, want none (normal cadence)", after-before, 8*stopPendingPoll)
|
||||
}
|
||||
})
|
||||
t.Run("unknown-stays-pending", func(t *testing.T) {
|
||||
d := newDetachHost(t)
|
||||
d.remote.set("lost", errInjectedRemote)
|
||||
if _, _, err := d.p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err)
|
||||
}
|
||||
if !d.pending() {
|
||||
t.Fatal("stop-pending cleared on an unknown detach outcome")
|
||||
}
|
||||
d.remote.set("", nil)
|
||||
})
|
||||
t.Run("fenced-stays-pending", func(t *testing.T) {
|
||||
d := newDetachHost(t)
|
||||
ctx := context.Background()
|
||||
cur, err := d.remote.MemChunkRemote.GetHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newer := cur
|
||||
newer.Epoch, newer.Holder = max(cur.Epoch, 3)+1, "another-holder" // above the host's assignment epoch 3
|
||||
if _, err := d.remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := d.p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
t.Fatalf("detach against a newer epoch: %v; want fenced", err)
|
||||
}
|
||||
if !d.pending() {
|
||||
t.Fatal("stop-pending cleared on a fenced detach")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -58,18 +58,43 @@ func (h *Host) runWorkspaceLease(ctx context.Context, stop func(context.Context,
|
||||
}
|
||||
|
||||
// WorkspaceStopPending is called when a graceful stop of volumeID has begun
|
||||
// (its chunk layer is being detached): the lease guard then polls the master
|
||||
// at a short cadence so it fences soon after the revocation instead of at its
|
||||
// next normal renewal. Other volume ids are ignored. Never blocks.
|
||||
func (h *Host) WorkspaceStopPending(volumeID string) {
|
||||
// (its chunk layer is being detached): the lease guard renews at once and
|
||||
// then sleeps at most stopPendingPoll between renewals, instead of its normal
|
||||
// renewal delay, so it sees the revocation that follows sooner. Scheduling
|
||||
// only: what the guard admits or ACKs is unchanged. It returns this detach
|
||||
// attempt's token for WorkspaceStopResumed; other volume ids are ignored
|
||||
// (token 0). Never blocks.
|
||||
func (h *Host) WorkspaceStopPending(volumeID string) uint64 {
|
||||
if volumeID != h.cfg.VolumeID {
|
||||
return 0
|
||||
}
|
||||
h.workspaceLeaseMu.Lock()
|
||||
defer h.workspaceLeaseMu.Unlock()
|
||||
h.workspaceStopAttempt++
|
||||
h.workspaceStopPending = true
|
||||
if g := h.view.workspaceGuard.Load(); g != nil {
|
||||
g.StopPending()
|
||||
}
|
||||
return h.workspaceStopAttempt
|
||||
}
|
||||
|
||||
// WorkspaceStopResumed is called when the detach attempt that returned
|
||||
// attempt provably did not happen and the volume serves again: stop-pending
|
||||
// ends and the guard returns to its normal renewal delay. A token other than
|
||||
// the latest attempt's (an older attempt, 0, another volume) changes nothing,
|
||||
// so an old attempt's resume never clears a newer pending detach. Never blocks.
|
||||
func (h *Host) WorkspaceStopResumed(volumeID string, attempt uint64) {
|
||||
if volumeID != h.cfg.VolumeID || attempt == 0 {
|
||||
return
|
||||
}
|
||||
h.workspaceLeaseMu.Lock()
|
||||
defer h.workspaceLeaseMu.Unlock()
|
||||
h.workspaceStopPending = true
|
||||
if !h.workspaceStopPending || attempt != h.workspaceStopAttempt {
|
||||
return
|
||||
}
|
||||
h.workspaceStopPending = false
|
||||
if g := h.view.workspaceGuard.Load(); g != nil {
|
||||
g.StopPending()
|
||||
g.ClearStopPending()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +78,7 @@ type runtimeLeaseServer struct {
|
||||
ttl time.Duration
|
||||
disabled, blocked, revoking bool
|
||||
blockedCalls int // renewals that arrived while blocked
|
||||
renewals int // every renewal that arrived
|
||||
acks int
|
||||
ackGen uint64
|
||||
first chan struct{}
|
||||
@@ -88,6 +89,7 @@ type runtimeLeaseServer struct {
|
||||
func (s *runtimeLeaseServer) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
|
||||
s.once.Do(func() { close(s.first) })
|
||||
s.mu.Lock()
|
||||
s.renewals++
|
||||
ttl, disabled, blocked, revoking := s.ttl, s.disabled, s.blocked, s.revoking
|
||||
s.mu.Unlock()
|
||||
if disabled {
|
||||
|
||||
@@ -149,6 +149,10 @@ stateDiagram-v2
|
||||
[*] --> NoLease
|
||||
NoLease --> Valid: renewal reply for this volume, replica and epoch
|
||||
Valid --> Valid: renewal before the local deadline
|
||||
Valid --> StopPending: detach started (renew at once)
|
||||
StopPending --> StopPending: renewal, then sleep at most 250 ms
|
||||
StopPending --> Valid: that detach provably aborted, serving resumed
|
||||
StopPending --> Fenced: deadline passed, invalid reply, or revoking
|
||||
Valid --> Fenced: deadline passed, invalid reply, or revoking
|
||||
Fenced --> Drained: frontend and cuts stopped
|
||||
Drained --> Acked: revocation acknowledged with the HEAD gen
|
||||
@@ -170,7 +174,10 @@ stateDiagram-v2
|
||||
| From | To | Guard | Enforced in | Protects |
|
||||
|---|---|---|---|---|
|
||||
| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` |
|
||||
| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` |
|
||||
| Valid, StopPending | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` |
|
||||
| Valid | StopPending | a chunk detach of this volume starts (before its drain); the guard renews at once. Scheduling only: StopPending admits, fences and ACKs exactly as Valid | `core/frontend/durable/provider_chunk.go` `DetachVolume`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`; `core/host/volume/workspace_lease.go` `StopPending` | `INV-WS-STOP-PENDING-001` |
|
||||
| StopPending | StopPending | each sleep after a completed renewal is at most `stopPendingPoll` (250 ms); a renewal already in flight is not interrupted | `core/host/volume/workspace_lease.go` `renewDelay`, `Run` | `INV-WS-STOP-PENDING-001` |
|
||||
| StopPending | Valid | only the latest detach attempt, provably not applied, with serving resumed; an applied, fenced or unknown outcome, or an older attempt's resume, leaves StopPending | `core/frontend/durable/provider_chunk.go` `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `ClearStopPending` | `INV-WS-STOP-PENDING-001` |
|
||||
| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` |
|
||||
| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` |
|
||||
| (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` |
|
||||
@@ -436,6 +443,7 @@ Notes:
|
||||
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE |
|
||||
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
|
||||
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
|
||||
| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
|
||||
|
||||
@@ -444,6 +452,7 @@ Notes:
|
||||
- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary.
|
||||
- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits).
|
||||
- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model.
|
||||
- `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged.
|
||||
|
||||
### B.5 Workspace: the cut pipeline
|
||||
|
||||
|
||||
Reference in new issue
Block a user