diff --git a/seaweed-block/core/hostlimit/fetch.go b/seaweed-block/core/hostlimit/fetch.go index d0dc83d554..45d37b0207 100644 --- a/seaweed-block/core/hostlimit/fetch.go +++ b/seaweed-block/core/hostlimit/fetch.go @@ -6,18 +6,16 @@ import ( "fmt" "hash/fnv" "os" - "path/filepath" "sync" "time" ) -// fetchRetry is how often a waiting fetch tries the other slots while it is -// blocked on its own: the host's slots are one pool, so a slot that frees -// elsewhere is taken within one interval. +// fetchRetry is how often a waiting fetch tries the slots again while every +// one is held. const fetchRetry = 20 * time.Millisecond -// fetchSlot is the fetch slot a key waits on when every slot is held: its -// hash, modulo the slot count. +// fetchSlot is the slot a key's tries start from: its hash, modulo the slot +// count, so concurrent fetches spread over the slots. func fetchSlot(key string, n int) int { h := fnv.New32a() _, _ = h.Write([]byte(key)) @@ -25,90 +23,125 @@ func fetchSlot(key string, n int) int { } // HoldFetch holds one of the host's FetchSlots fetch slots (files fetch-0 .. -// fetch-(N-1) in the pool, so the cap is per host and dies with its -// holders) for one chunk transfer; release gives it back. It never refuses: +// fetch-(N-1) in the pool, so the cap is per host and a slot dies with its +// holder) for one chunk transfer; release gives it back. It never refuses for +// want of a slot: // -// 1. it takes a free slot without waiting, trying from key's hash slot; -// 2. with every slot held, it blocks on its hash slot (the kernel queues the -// waiters) and, while blocked, tries the other slots every fetchRetry; -// whichever lock comes first is used and the other is released at once; -// 3. the wait is bounded by ctx: when it ends, HoldFetch returns ctx's error, -// and a lock the blocked wait gets after that is released at once. +// 1. a limiter's first fetch checks the host's configuration under +// configuration.lock, publishing it when absent, as a cut admission does: +// ErrConfig when another process uses other flags; +// 2. it takes a free slot without waiting, trying from key's hash slot; +// 3. with every slot held, it waits for its process's turn (one fetch per +// process polls) and then tries every slot each fetchRetry. The waiting +// is unordered, so other fetches can take a freed slot first; the wait is +// bounded by ctx alone and ends with ctx's error; +// 4. a slot taken when ctx has already ended is given back, and ctx's error +// returned. +// +// Every lock try is non-blocking, so a wait that ends leaves no lock request, +// descriptor or goroutine behind. func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) { if err := ctx.Err(); err != nil { return nil, err } - n := l.cfg.FetchSlots - home := fetchSlot(key, n) - open := func(i int) (*os.File, error) { - return os.OpenFile(filepath.Join(l.cfg.Directory, fmt.Sprintf("fetch-%d", i)), os.O_CREATE|os.O_RDWR, 0o600) + if err := l.checkFetchConfig(ctx); err != nil { + return nil, err } - // try takes a free slot among those try covers, without waiting; nil - // when every one is held. - try := func(skip int) (*os.File, error) { - for k := 0; k < n; k++ { - i := (home + k) % n - if i == skip { - continue - } - f, err := open(i) - if err != nil { - return nil, err - } - err = tryLock(f) - if err == nil { - return f, nil - } - _ = f.Close() - if !errors.Is(err, ErrBusy) { - return nil, err - } - } - return nil, nil + home := fetchSlot(key, l.cfg.FetchSlots) + f, err := l.tryFetch(home) + if f == nil && err == nil { + f, err = l.waitFetch(ctx, home) } - if f, err := try(-1); f != nil || err != nil { - if err != nil { - return nil, err - } - return releaseFetch(f), nil - } - homeF, err := open(home) if err != nil { return nil, err } - locked := make(chan error, 1) - go func() { locked <- lockBlocking(homeF) }() - // abandon releases the blocked wait's lock once it gets it. - abandon := func() { - go func() { - <-locked - _ = homeF.Close() - }() + if l.testFetchLocked != nil { + l.testFetchLocked() + } + if err := ctx.Err(); err != nil { + _ = f.Close() + return nil, err + } + return releaseFetch(f), nil +} + +// checkFetchConfig checks the host's configuration once per limiter. A +// configuration lock held past its bound by another admission is waited out +// within ctx; a mismatch is ErrConfig. +func (l *Limiter) checkFetchConfig(ctx context.Context) error { + if l.fetchChecked.Load() { + return nil + } + if err := l.checkPoolDir(); err != nil { + return err } - t := time.NewTicker(fetchRetry) - defer t.Stop() for { - select { - case err := <-locked: - if err != nil { - _ = homeF.Close() - return nil, err - } - return releaseFetch(homeF), nil - case <-ctx.Done(): - abandon() - return nil, ctx.Err() - case <-t.C: - f, err := try(home) - if err != nil { - abandon() - return nil, err - } - if f != nil { - abandon() - return releaseFetch(f), nil - } + guard, err := l.configGuard() + if err == nil { + _ = guard.Close() + l.fetchChecked.Store(true) + return nil } + if !errors.Is(err, ErrSlotsHeld) { + return err + } + if err := sleepCtx(ctx, fetchRetry); err != nil { + return err + } + } +} + +// tryFetch takes a free fetch slot without waiting, trying from home; nil +// when every slot is held. +func (l *Limiter) tryFetch(home int) (*os.File, error) { + n := l.cfg.FetchSlots + for k := 0; k < n; k++ { + f, err := l.poolFile(fmt.Sprintf("fetch-%d", (home+k)%n)) + if err != nil { + return nil, err + } + err = tryLock(f) + if err == nil { + return f, nil + } + _ = f.Close() + if !errors.Is(err, ErrBusy) { + return nil, err + } + } + return nil, nil +} + +// waitFetch waits for a fetch slot while every one is held: it takes its +// process's turn, so one fetch per process polls, and tries every slot each +// fetchRetry until one is free or ctx ends. +func (l *Limiter) waitFetch(ctx context.Context, home int) (*os.File, error) { + select { + case l.fetchTurn <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-l.fetchTurn }() + for { + f, err := l.tryFetch(home) + if f != nil || err != nil { + return f, err + } + if err := sleepCtx(ctx, fetchRetry); err != nil { + return nil, err + } + } +} + +// sleepCtx waits d, or until ctx ends (its error). +func sleepCtx(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil } } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index e6ec66517c..d8c7f5086c 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -151,6 +151,12 @@ type Limiter struct { // by the skip rule. It is never taken with mu held, nor mu under it. skipMu sync.Mutex stalled map[string]bool + + // fetchChecked is set once a fetch has checked the host's configuration; + // fetchTurn (capacity 1) is held by the one fetch of this process that + // polls for a slot while every slot is held. + fetchChecked atomic.Bool + fetchTurn chan struct{} } func (l *Limiter) skipAfter() time.Duration { @@ -164,7 +170,7 @@ func New(c Config) (*Limiter, error) { if err := c.Validate(); err != nil { return nil, err } - l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})} + l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{}), fetchTurn: make(chan struct{}, 1)} go l.releaseLoop() return l, nil } @@ -182,20 +188,10 @@ func Phase(volume string, period time.Duration) time.Duration { // pool checks the immutable configuration under a separate OS lock. Slot files // are never unlinked: replacing them could create a second set of live permits. func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { - info, err := os.Lstat(l.cfg.Directory) - if err != nil { + if err := l.checkPoolDir(); err != nil { return nil, err } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return nil, errors.New("hostlimit: pool must be a local directory") - } - open := func(name string) (*os.File, error) { - path := filepath.Join(l.cfg.Directory, name) - if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() { - return nil, errors.New("hostlimit: nonregular pool file") - } - return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) - } + open := l.poolFile // A ticketed Normal admission first checks its place in the queue. The // ticket files synchronise through their own locks, so this runs outside // the configuration lock and does not lengthen it. @@ -204,30 +200,11 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { return nil, err } } - guard, err := open("configuration.lock") + guard, err := l.configGuard() if err != nil { return nil, err } defer guard.Close() - if l.testBeforeConfigLock != nil { - l.testBeforeConfigLock(guard) - } - if err = lockGuard(guard); err != nil { - return nil, err - } - expected, _ := json.Marshal(l.cfg) - path := filepath.Join(l.cfg.Directory, "configuration.json") - existing, err := os.ReadFile(path) - if errors.Is(err, os.ErrNotExist) { - err = l.publishConfig(path, expected) - existing = expected - } - if err != nil { - return nil, err - } - if string(existing) != string(expected) { - return nil, ErrConfig - } if c == Normal { // The probe is held until the slot try-lock below has been made, so // no Normal admission completes after urgent work became pending. @@ -280,6 +257,60 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { return nil, ErrSlotsHeld } +// checkPoolDir refuses a pool that is not a local directory. +func (l *Limiter) checkPoolDir() error { + info, err := os.Lstat(l.cfg.Directory) + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("hostlimit: pool must be a local directory") + } + return nil +} + +// poolFile opens (creating) a regular file of the pool. +func (l *Limiter) poolFile(name string) (*os.File, error) { + path := filepath.Join(l.cfg.Directory, name) + if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() { + return nil, errors.New("hostlimit: nonregular pool file") + } + return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) +} + +// configGuard takes configuration.lock and, under it, checks the host's +// immutable configuration, publishing it when absent: ErrConfig when another +// process published other flags. The caller closes the guard, which releases +// the lock. +func (l *Limiter) configGuard() (*os.File, error) { + guard, err := l.poolFile("configuration.lock") + if err != nil { + return nil, err + } + if l.testBeforeConfigLock != nil { + l.testBeforeConfigLock(guard) + } + if err = lockGuard(guard); err != nil { + _ = guard.Close() + return nil, err + } + expected, _ := json.Marshal(l.cfg) + path := filepath.Join(l.cfg.Directory, "configuration.json") + existing, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + err = l.publishConfig(path, expected) + existing = expected + } + if err == nil && string(existing) != string(expected) { + err = ErrConfig + } + if err != nil { + _ = guard.Close() + return nil, err + } + return guard, nil +} + // guardWait bounds how long an admission waits for configuration.lock. // Another admission holds it only while it checks the configuration and // tries its slots. diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go index 0c4959fd52..ea3d6c09f3 100644 --- a/seaweed-block/core/hostlimit/lock_unix.go +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -24,14 +24,3 @@ func tryLockShared(f *os.File) error { } return err } - -// lockBlocking takes an exclusive lock on f, waiting until it is free. It -// cannot be cancelled: a caller that stops waiting closes f once it returns. -func lockBlocking(f *os.File) error { - for { - err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX) - if !errors.Is(err, syscall.EINTR) { - return err - } - } -} diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go index c3aa7ed6d4..3870ad922c 100644 --- a/seaweed-block/core/hostlimit/lock_windows.go +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -24,9 +24,3 @@ func tryLockShared(f *os.File) error { } return err } - -// lockBlocking takes an exclusive lock on f, waiting until it is free. It -// cannot be cancelled: a caller that stops waiting closes f once it returns. -func lockBlocking(f *os.File) error { - return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &windows.Overlapped{}) -} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 07806f3346..5f715d47af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, waiting for one when all are held (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. **Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once. @@ -1003,7 +1003,7 @@ Notes: | `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE | | `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE | | `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE | -| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only. With all held it waits, never refused: blocked on its hash slot and taking any other slot that frees within one retry interval; its context bounds the wait, and a slot got after that is released at once. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `fetchSlot`; `core/hostlimit/lock_unix.go`, `lock_windows.go` `lockBlocking`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossProcesses`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | +| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | | `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE | | `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index d752836b95..044a5550d7 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -15,7 +15,8 @@ These notes collect v1.1's changes as they land; v1.1 is not released. - With the limiter on, chunk fetches are capped per host: `--host-limit-fetch-slots` (default 64) fetches in flight across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a - slot (bounded by its read-miss timeout), and is never refused. + slot, in no set order and bounded by its read-miss timeout, and is never refused. A process's first fetch checks the + host's `configuration.json` as a cut admission does, so a fetch-only process with other flags is refused too. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was