feat(storage): drain admission before authoritative pre-copy barrier

This commit is contained in:
pingqiu committed 2026-11-20 06:13:08 -08:00
1 parent ffce8c1dd6
commit f337e8de99
5 files changed
+92 -13

No files matched your search

@@ -2,6 +2,7 @@ package durable
import (
"context"
"errors"
"fmt"
"sync"
"time"
@@ -132,6 +133,15 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(),
}
return release, err
}
b.mu.Unlock()
if err := b.readyCheck(); err != nil && !errors.Is(err, frontend.ErrBackendBusy) {
return nil, err
}
b.mu.Lock()
if b.precopy != p {
b.mu.Unlock()
continue
}
w := &precopyWaiter{ready: make(chan struct{})}
p.waiters = append(p.waiters, w)
if !p.active && len(p.waiters) == 1 {
@@ -139,6 +149,9 @@ func (b *StorageBackend) admitPrecopy(ctx context.Context, admit func() (func(),
}
deadline := p.started.Add(precopyQueueBudget)
b.mu.Unlock()
if hook := b.testPrecopyQueued; hook != nil {
hook()
}
waitCtx, cancel := context.WithDeadline(ctx, deadline)
select {
case <-w.ready:
@@ -935,7 +935,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
var r storage.ChunkCutResult
if p.cfg.ChunkDetachPrecopy {
owner, ok := layer.(interface {
PrecopyDetach(context.Context, func() bool) (storage.ChunkCutResult, error)
PrecopyDetachWithAdmission(context.Context, func(context.Context) (func(), error), func() bool) (storage.ChunkCutResult, error)
})
if !ok {
return r, 0, fmt.Errorf("%w: layer lacks pre-copy", storage.ErrPrecopyUnknown)
@@ -944,7 +944,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
notifyDetach()
// Cancel/join the periodic owner before any final freeze, while serving.
p.stopChunkLoop(h)
r, err = owner.PrecopyDetach(hostlimit.WithClass(cutCtx, hostlimit.Urgent), func() bool {
r, err = owner.PrecopyDetachWithAdmission(hostlimit.WithClass(cutCtx, hostlimit.Urgent), h.backend.BeginPrecopyPause, func() bool {
if !h.backend.TryStopIO("chunk pre-copy: final detached cut") {
return false
}
@@ -148,7 +148,8 @@ const maxFullBlockBatchBlocks = 64
type StorageBackend struct {
// testBeforeIOLock, test-only, runs in admit after the readiness check,
// right before the I/O lock (an arrival handshake for queued I/O).
testBeforeIOLock func()
testBeforeIOLock func()
testPrecopyQueued func() // after FIFO registration, outside mu
// Runs outside locks after a read registers its readiness notification.
testBeforeReadReadyWait func()
testAfterAttachRefusal func()
@@ -488,8 +489,11 @@ func (b *StorageBackend) TryStopIO(evidence string) bool {
// A drained admission pause excludes late gate callers even if they still
// hold ioMu's read side. Their final registration check cannot reach storage.
if b.mu.TryLock() {
if b.precopy != nil && b.precopy.active {
if b.precopy != nil {
defer b.mu.Unlock()
if !b.precopy.active {
return false
}
if b.admittedIO != 0 || b.closed || !b.operational.Load() {
return false
}
+30 -4
View File
@@ -54,6 +54,7 @@ const defaultReadMissTimeout = 30 * time.Second
type chunkLayerImpl struct {
// capMu serializes pre-copy admission and its recent measurements.
precopyFreeze func(uint64, time.Time) bool
precopyPrepare func(context.Context) (func(), error)
precopySamples []precopySample
precopyPause func(time.Duration)
@@ -905,6 +906,31 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
// paused too. LockWaitNs reports that wait on its own.
payloadBeforeBarrier = st.PayloadNs
pauseStart = time.Now()
var releasePrecopy func()
if prepare := l.precopyPrepare; prepare != nil {
releasePrecopy, _ = prepare(ctx)
}
defer func() {
if releasePrecopy != nil && !detach {
releasePrecopy()
}
}()
if cause := context.Cause(ctx); cause != nil {
if releasePrecopy != nil {
releasePrecopy()
releasePrecopy = nil
}
l.dropIntents(ctx, intents)
return chunkCutResult{}, cause
}
// Resume rejected tentative admission before any ordinary COW upload.
unlockCapture := func() {
l.s.captureMu.Unlock()
if !detach && releasePrecopy != nil {
releasePrecopy()
releasePrecopy = nil
}
}
if hook := l.testBeforeBarrierLockHook; hook != nil {
hook()
}
@@ -917,7 +943,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
hook(h)
}
if err != nil {
l.s.captureMu.Unlock()
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
l.dropIntents(ctx, intents) // a clean abort: staged keys are released
return chunkCutResult{}, fmt.Errorf("storage: capture sync: %w", err)
@@ -977,7 +1003,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
if h < baseHead.RemoteLSN && !l.supersededBy(baseHead) {
l.s.captureMu.Unlock()
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
// HEAD holds the image of a later LSN than this host's log has
// reached: publishing would move remote_lsn backwards. Refused
@@ -997,7 +1023,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if copyErr == nil {
w.budget = budget
}
l.s.captureMu.Unlock()
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
copyStart = time.Now()
if copyErr == nil {
@@ -1029,7 +1055,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
}
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
}
l.s.captureMu.Unlock()
unlockCapture()
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
}
st.CopyNs = time.Since(copyStart).Nanoseconds()
+41 -5
View File
@@ -13,10 +13,11 @@ var (
)
const (
precopyAttempts = 5
precopyDuration = 60 * time.Second
precopyAllowance = 1200 * time.Millisecond
precopyMargin = 100 * time.Millisecond
precopyAttempts = 5
precopyDuration = 60 * time.Second
precopyAllowance = 1200 * time.Millisecond
precopyMargin = 100 * time.Millisecond
precopyDrainBound = 100 * time.Millisecond
)
type precopySample struct {
@@ -27,6 +28,8 @@ type precopySample struct {
// PrecopyReport records admission estimates, not a worst-case latency proof.
type PrecopyReport struct {
Drain time.Duration `json:"drainNs"`
DrainTimedOut bool `json:"drainTimedOut"`
Attempts int `json:"attempts"`
TailBytes uint64 `json:"tailBytes"`
Fixed time.Duration `json:"fixedNs"`
@@ -62,6 +65,16 @@ func (r *PrecopyReport) Finish(elapsed time.Duration, extraCAS uint64, failed bo
// capMu owns the callback and samples; no owner lock is taken while waiting
// for capMu. The callback must never wait for an I/O holding a backend read lock.
func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool) (ChunkCutResult, error) {
return l.precopyDetach(ctx, nil, stopIO)
}
// prepare closes frontend admission and drains before the store barrier. Its
// release reopens only that tentative admission; it must not undo a host fence.
func (l *chunkLayerImpl) PrecopyDetachWithAdmission(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) {
return l.precopyDetach(ctx, prepare, stopIO)
}
func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context.Context) (func(), error), stopIO func() bool) (ChunkCutResult, error) {
if stopIO == nil {
return ChunkCutResult{}, fmt.Errorf("%w: missing I/O stop", ErrPrecopyUnknown)
}
@@ -83,6 +96,20 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool)
var frozenAt time.Time
var casAtFreeze uint64
var pauseTotal, longestPause time.Duration
var drain time.Duration
var drainErr error
if prepare != nil {
l.precopyPrepare = func(ctx context.Context) (func(), error) {
dc, cancel := context.WithTimeout(ctx, precopyDrainBound)
defer cancel()
start := time.Now()
release, err := prepare(dc)
drain = time.Since(start)
drainErr = err
return release, err
}
}
l.precopyPause = func(pause time.Duration) {
pauseTotal += pause
if pause > longestPause {
@@ -91,6 +118,15 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool)
}
l.precopyFreeze = func(tail uint64, barrierStart time.Time) bool {
report = l.precopyEstimate(tail, report.Attempts)
report.Drain = drain
report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded)
if drainErr != nil {
report.Reason = "drain_refused"
if report.DrainTimedOut {
report.Reason = "drain_timeout"
}
return false
}
spent := time.Since(barrierStart)
if spent > report.Fixed {
report.Estimate += spent - report.Fixed
@@ -110,7 +146,7 @@ func (l *chunkLayerImpl) PrecopyDetach(ctx context.Context, stopIO func() bool)
frozenAt, casAtFreeze = barrierStart, countCAS()
return true
}
defer func() { l.precopyFreeze = nil; l.precopyPause = nil }()
defer func() { l.precopyFreeze = nil; l.precopyPause = nil; l.precopyPrepare = nil }()
for attempt := 1; attempt <= precopyAttempts; attempt++ {
report.Attempts = attempt
if err := ctx.Err(); err != nil {