mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
hostlimit, storage: chunk fetches are capped per host
- hostlimit: Config.FetchSlots (default 64, files fetch-0..N-1 in the pool). HoldFetch takes a free slot without waiting, from the key's hash slot; with every slot held it blocks on its hash slot (the kernel queues the waiters) and tries the other slots every 20 ms, using whichever lock comes first and releasing the other; its context bounds the wait, and a lock got after that is released at once. lockBlocking on Unix and Windows. - storage: BudgetFetch; fillOnce holds one slot across its remote read only (a read miss and a hydrate-all fill alike); a context error on the wait is the hydration path's pending, as before. - blockvolume: --host-limit-fetch-slots. Invariants: INV-HOST-FETCH-CAP-001; M7 states it. v1.1 notes carry it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9391166b25
commit
5a57e8564d
9 files changed
+144
-7
No files matched your search
@@ -16,6 +16,7 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) {
|
||||
fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot")
|
||||
fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked")
|
||||
fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)")
|
||||
fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout")
|
||||
fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release")
|
||||
fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)")
|
||||
}
|
||||
@@ -2,9 +2,20 @@ package hostlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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.
|
||||
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.
|
||||
func fetchSlot(key string, n int) int {
|
||||
@@ -13,8 +24,97 @@ func fetchSlot(key string, n int) int {
|
||||
return int(h.Sum32() % uint32(n))
|
||||
}
|
||||
|
||||
// HoldFetch holds one of the host's fetch slots for one chunk transfer
|
||||
// (seam: no cap yet).
|
||||
// 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:
|
||||
//
|
||||
// 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.
|
||||
func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) {
|
||||
return func() {}, ctx.Err()
|
||||
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)
|
||||
}
|
||||
// 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
|
||||
}
|
||||
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()
|
||||
}()
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// releaseFetch gives a fetch slot back, once: closing the file releases its
|
||||
// lock.
|
||||
func releaseFetch(f *os.File) func() {
|
||||
var once sync.Once
|
||||
return func() { once.Do(func() { _ = f.Close() }) }
|
||||
}
|
||||
@@ -63,7 +63,8 @@ type Config struct {
|
||||
// only after this long with no progress of its work (Progress). Work
|
||||
// that keeps progressing is never revoked, however long it holds.
|
||||
NoProgress time.Duration
|
||||
// FetchSlots caps the chunk fetches in flight on the host (seam).
|
||||
// FetchSlots caps the chunk fetches in flight on the host, across its
|
||||
// processes (HoldFetch): a guest read waits for a slot, never refused.
|
||||
FetchSlots int
|
||||
}
|
||||
|
||||
|
||||
@@ -24,3 +24,14 @@ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,3 +24,9 @@ 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{})
|
||||
}
|
||||
@@ -32,8 +32,9 @@ func budgetProgress(b Budget, ticket uint64) func() {
|
||||
return func() {}
|
||||
}
|
||||
|
||||
// BudgetFetch is a Budget that caps the chunk fetches in flight on the host
|
||||
// (seam).
|
||||
// BudgetFetch is a Budget that caps the chunk fetches in flight on the host:
|
||||
// HoldFetch holds one slot for one chunk transfer, waiting (bounded by ctx)
|
||||
// when every slot is held; release gives it back.
|
||||
type BudgetFetch interface {
|
||||
HoldFetch(ctx context.Context, key string) (release func(), err error)
|
||||
}
|
||||
|
||||
@@ -701,7 +701,19 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun
|
||||
l.stMu.Lock()
|
||||
version := l.chunkVersion(idx)
|
||||
l.stMu.Unlock()
|
||||
// The host's fetch cap: one slot held across the remote read only, not
|
||||
// the install. Its wait is bounded by ctx, a context error that the
|
||||
// hydration path answers as pending.
|
||||
release := func() {}
|
||||
if fb, ok := l.cfg.Budget.(BudgetFetch); ok {
|
||||
r, err := fb.HoldFetch(ctx, fmt.Sprintf("%s/%d", l.cfg.VolumeID, idx))
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("storage: chunk %d fetch slot: %w", idx, err)
|
||||
}
|
||||
release = r
|
||||
}
|
||||
data, err := l.remote.Get(ctx, ref.Key)
|
||||
release()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err)
|
||||
}
|
||||
|
||||
@@ -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. 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, 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.
|
||||
|
||||
**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,6 +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-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 |
|
||||
|
||||
@@ -13,6 +13,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released.
|
||||
chunk compared, staged or uploaded), instead of at a fixed 5 minutes of age. `--host-limit-max-hold` is kept as a
|
||||
deprecated alias of the new flag. The window must exceed one chunk's send time at the paced rate per held slot.
|
||||
|
||||
- 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.
|
||||
|
||||
## Upgrade
|
||||
- With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was
|
||||
created with, and v1.1's differ. Upgrade such a host whole: stop every process using the directory, remove
|
||||
|
||||
Reference in new issue
Block a user