mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
hostlimit: background cuts wait while urgent work is pending; launch checks
- A pool file, urgent-pending, signals urgent work on the host. An urgent cut holds it shared for its lease, and HoldUrgentPending lets a caller hold it across a stop or a drain. A Normal admission probes it exclusively without waiting and, while it is held, is refused with ErrUrgentPending (an ErrSlotsHeld, so the timer waits instead of failing). Urgent admissions are unaffected. - blockvolume checks --host-limit-dir before using it and refuses to start when it is missing or not a directory, under a temporary directory (/tmp, /var/tmp, /dev/shm, the process temp dir), on a network file system (NFS, CIFS, SMB2, FUSE on Linux), or already in use with different host-limit flags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e94dbbafd6
commit
14f0d7401f
11 files changed
+286
-2
No files matched your search
@@ -678,7 +678,11 @@ func run(f flags) int {
|
||||
cfg.ChunkHolder = chunkHolder(f)
|
||||
cfg.ChunkStagger = true
|
||||
if f.chunk.hostLimit.Directory != "" {
|
||||
limiter, limitErr := hostlimit.New(f.chunk.hostLimit)
|
||||
limitErr := hostlimit.CheckLaunch(f.chunk.hostLimit)
|
||||
var limiter *hostlimit.Limiter
|
||||
if limitErr == nil {
|
||||
limiter, limitErr = hostlimit.New(f.chunk.hostLimit)
|
||||
}
|
||||
if limitErr != nil {
|
||||
chunkErr = errors.Join(chunkErr, limitErr)
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CheckLaunch refuses a host-limit configuration whose premises do not
|
||||
// hold, before the process uses it. The directory must exist as a real
|
||||
// directory, outside temporary directories that cleaners empty, on a local
|
||||
// file system (kernel file locks are not shared reliably over network
|
||||
// file systems), and a configuration already published there by other
|
||||
// processes must equal this one. The premise that every process on the
|
||||
// host uses the same directory cannot be checked from one process.
|
||||
func CheckLaunch(c Config) error {
|
||||
return checkLaunch(c, []string{"/tmp", "/var/tmp", "/dev/shm", os.TempDir()}, remoteFS)
|
||||
}
|
||||
|
||||
func checkLaunch(c Config, tempRoots []string, remote func(string) (string, bool)) error {
|
||||
if err := c.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
dir := filepath.Clean(c.Directory)
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
|
||||
}
|
||||
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s must be a directory, not a symlink or a file", dir)
|
||||
}
|
||||
for _, root := range tempRoots {
|
||||
root = filepath.Clean(root)
|
||||
if root != "" && root != "." && (dir == root || strings.HasPrefix(dir, root+string(filepath.Separator))) {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s is under %s, which temporary-file cleaners empty", dir, root)
|
||||
}
|
||||
}
|
||||
if fs, isRemote := remote(dir); isRemote {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s is on %s, a network file system; slot locks need a local one", dir, fs)
|
||||
}
|
||||
existing, err := os.ReadFile(filepath.Join(dir, "configuration.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s: %w", dir, err)
|
||||
}
|
||||
expected, _ := json.Marshal(c)
|
||||
if string(existing) != string(expected) {
|
||||
return fmt.Errorf("hostlimit: --host-limit-dir %s is in use with other host-limit flags (%s); every process on the host must use identical flags (this one: %s)", dir, existing, expected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -23,6 +23,15 @@ var ErrBusy = errors.New("hostlimit: no background slot")
|
||||
// work: retrying once one is released can succeed. Other ErrBusy results
|
||||
// (an oversized payload, an unusable pool) do not change by waiting.
|
||||
var ErrSlotsHeld = fmt.Errorf("%w: every slot is held", ErrBusy)
|
||||
|
||||
// ErrUrgentPending refuses a Normal admission while an urgent cut runs or
|
||||
// a caller holds HoldUrgentPending on the host: new background cuts wait
|
||||
// for it. It is an ErrSlotsHeld, so waiting callers treat it alike.
|
||||
var ErrUrgentPending = fmt.Errorf("%w: an urgent cut is pending", ErrSlotsHeld)
|
||||
|
||||
// urgentPendingFile is the pool file urgent work holds shared; Normal
|
||||
// admission probes it exclusively, without waiting. It has no content.
|
||||
const urgentPendingFile = "urgent-pending"
|
||||
var ErrConfig = errors.New("hostlimit: incompatible host configuration")
|
||||
var ErrRevoked = errors.New("hostlimit: cut budget revoked")
|
||||
|
||||
@@ -72,6 +81,7 @@ type Stats struct {
|
||||
}
|
||||
type lease struct {
|
||||
file *os.File
|
||||
pending *os.File // urgent only: the shared hold on urgentPendingFile
|
||||
started time.Time
|
||||
class Class
|
||||
fallback bool
|
||||
@@ -157,6 +167,20 @@ func (l *Limiter) pool(c Class) (*os.File, error) {
|
||||
if string(existing) != string(expected) {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
if c == Normal {
|
||||
probe, err := open(urgentPendingFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tryLock(probe)
|
||||
_ = probe.Close()
|
||||
if errors.Is(err, ErrBusy) {
|
||||
return nil, ErrUrgentPending
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
names := []string{}
|
||||
if c == BackgroundFill || c == Idle {
|
||||
n, prefix := l.cfg.FillSlots, "fill"
|
||||
@@ -299,6 +323,10 @@ func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (
|
||||
l.next++
|
||||
id := l.next
|
||||
x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort}
|
||||
if c == Urgent && !fallback {
|
||||
// Best effort: an urgent cut that cannot signal still runs.
|
||||
x.pending, _ = holdShared(filepath.Join(l.cfg.Directory, urgentPendingFile))
|
||||
}
|
||||
l.live[id] = x
|
||||
l.stats.Admitted++
|
||||
l.stats.PayloadReserved += payload
|
||||
@@ -399,6 +427,9 @@ func (l *Limiter) releaseLoop() {
|
||||
if x.file != nil {
|
||||
_ = x.file.Close()
|
||||
}
|
||||
if x.pending != nil {
|
||||
_ = x.pending.Close()
|
||||
}
|
||||
l.mu.Lock()
|
||||
delete(l.live, id)
|
||||
l.fallback = false
|
||||
|
||||
@@ -80,6 +80,12 @@ func TestSlotsUrgentAndJoinedRelease(t *testing.T) {
|
||||
a.Release(x)
|
||||
a.Release(x)
|
||||
settled(t, a)
|
||||
// A free normal slot is not taken while the urgent cut runs.
|
||||
if _, e = d.Admit(context.Background(), 1, nil); !errors.Is(e, ErrUrgentPending) {
|
||||
t.Fatalf("normal admission during an urgent cut: %v", e)
|
||||
}
|
||||
b.Release(y)
|
||||
settled(t, b)
|
||||
z, e := d.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
|
||||
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// lockShared waits for a shared lock on f. An exclusive holder keeps it
|
||||
// only for a non-blocking probe, so the wait is short.
|
||||
func lockShared(f *os.File) error {
|
||||
return syscall.Flock(int(f.Fd()), syscall.LOCK_SH)
|
||||
}
|
||||
@@ -15,3 +15,9 @@ func tryLock(f *os.File) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// lockShared waits for a shared lock on f. An exclusive holder keeps it
|
||||
// only for a non-blocking probe, so the wait is short.
|
||||
func lockShared(f *os.File) error {
|
||||
return windows.LockFileEx(windows.Handle(f.Fd()), 0, 0, 1, 0, &windows.Overlapped{})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// HoldUrgentPending tells every limiter using dir that urgent work is
|
||||
// pending on the host: until release is called, Normal admissions there
|
||||
// are refused with ErrUrgentPending. Callers hold it across a stop or a
|
||||
// drain, so background cuts do not take slots the stop is waiting for.
|
||||
func HoldUrgentPending(dir string) (release func(), err error) {
|
||||
f, err := holdShared(filepath.Join(dir, urgentPendingFile))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func() { _ = f.Close() }, nil
|
||||
}
|
||||
|
||||
func holdShared(path string) (*os.File, error) {
|
||||
if i, err := os.Lstat(path); err == nil && !i.Mode().IsRegular() {
|
||||
return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrInvalid}
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = lockShared(f); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// While a caller holds HoldUrgentPending, Normal admissions on the host
|
||||
// wait (ErrUrgentPending, an ErrSlotsHeld); urgent ones still run.
|
||||
func TestNormalWaitsWhileUrgentPendingIsHeld(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
l := newTest(t, c)
|
||||
release, err := HoldUrgentPending(c.Directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id, err := l.Acquire(context.Background(), Normal, nil); id != 0 || !errors.Is(err, ErrUrgentPending) || !errors.Is(err, ErrSlotsHeld) {
|
||||
t.Fatalf("normal admission with an urgent pending: id=%d err=%v", id, err)
|
||||
}
|
||||
id, err := l.Acquire(context.Background(), Urgent, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("urgent admission refused: %v", err)
|
||||
}
|
||||
l.Release(id)
|
||||
release()
|
||||
waitAdmitted(t, l, Normal)
|
||||
}
|
||||
|
||||
// An urgent cut holds the pending signal for its lease: another process's
|
||||
// Normal admission waits until the urgent cut is released.
|
||||
func TestUrgentLeaseHoldsThePendingSignal(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
a, b := newTest(t, c), newTest(t, c)
|
||||
id, err := a.Acquire(context.Background(), Urgent, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Acquire(context.Background(), Normal, nil); !errors.Is(err, ErrUrgentPending) {
|
||||
t.Fatalf("normal admission during an urgent lease: %v", err)
|
||||
}
|
||||
a.Release(id)
|
||||
waitAdmitted(t, b, Normal)
|
||||
}
|
||||
|
||||
func waitAdmitted(t *testing.T, l *Limiter, c Class) {
|
||||
t.Helper()
|
||||
for deadline := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) {
|
||||
id, err := l.Acquire(context.Background(), c, nil)
|
||||
if err == nil {
|
||||
l.Release(id)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("still refused after the pending signal ended: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckLaunch(t *testing.T) {
|
||||
local := func(string) (string, bool) { return "", false }
|
||||
c := testConfig(t)
|
||||
if err := checkLaunch(c, nil, local); err != nil {
|
||||
t.Fatalf("a fresh local directory refused: %v", err)
|
||||
}
|
||||
refused := map[string]struct {
|
||||
c Config
|
||||
roots []string
|
||||
remote func(string) (string, bool)
|
||||
want string
|
||||
}{
|
||||
"missing": {DefaultConfig(filepath.Join(c.Directory, "missing")), nil, local, "missing"},
|
||||
"temp root": {c, []string{filepath.Dir(c.Directory)}, local, "temporary-file cleaners"},
|
||||
"remote": {c, nil, func(string) (string, bool) { return "NFS", true }, "network file system"},
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "f")
|
||||
if err := os.WriteFile(file, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refused["file"] = struct {
|
||||
c Config
|
||||
roots []string
|
||||
remote func(string) (string, bool)
|
||||
want string
|
||||
}{DefaultConfig(file), nil, local, "must be a directory"}
|
||||
for name, tc := range refused {
|
||||
if err := checkLaunch(tc.c, tc.roots, tc.remote); err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("%s: %v; want %q", name, err, tc.want)
|
||||
}
|
||||
}
|
||||
// A configuration published by other processes must be identical.
|
||||
l := newTest(t, c)
|
||||
id, err := l.Acquire(context.Background(), Normal, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Release(id)
|
||||
if err := checkLaunch(c, nil, local); err != nil {
|
||||
t.Fatalf("the same flags refused: %v", err)
|
||||
}
|
||||
other := c
|
||||
other.NormalSlots = 3
|
||||
if err := checkLaunch(other, nil, local); err == nil || !strings.Contains(err.Error(), "identical flags") {
|
||||
t.Fatalf("different flags accepted: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build linux
|
||||
|
||||
package hostlimit
|
||||
|
||||
import "syscall"
|
||||
|
||||
// remoteFS names the network file system dir is on, if it is on one.
|
||||
func remoteFS(dir string) (string, bool) {
|
||||
var st syscall.Statfs_t
|
||||
if syscall.Statfs(dir, &st) != nil {
|
||||
return "", false
|
||||
}
|
||||
switch uint32(st.Type) {
|
||||
case 0x6969:
|
||||
return "NFS", true
|
||||
case 0xFF534D42:
|
||||
return "CIFS", true
|
||||
case 0xFE534D42:
|
||||
return "SMB2", true
|
||||
case 0x65735546:
|
||||
return "FUSE", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !linux
|
||||
|
||||
package hostlimit
|
||||
|
||||
// remoteFS reports no network file system where it cannot tell.
|
||||
func remoteFS(string) (string, bool) { return "", false }
|
||||
@@ -403,7 +403,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
|
||||
|
||||
## Part B. Invariant ledger
|
||||
|
||||
186 rows: 164 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 171 new.
|
||||
188 rows: 166 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 173 new.
|
||||
|
||||
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
|
||||
|
||||
@@ -592,6 +592,8 @@ Notes:
|
||||
| `INV-CUT-ERROR-PRECEDENCE-001` | A chunk-control error body reports `cut_aborted` for a local cut abort even when the abort cancelled a remote upload, but an unknown CAS outcome, a fence or a closed or detached layer joined to it keeps its own code (`outcome_unknown`, `fenced`, `closing`). | M5 Copy, Upload → Aborted (HTTP error body) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestStatusServer_ChunkErrorBodyIsTyped` (`core/host/volume/chunk_control_test.go`) | — | ACTIVE |
|
||||
| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE |
|
||||
| `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE |
|
||||
| `INV-HOST-URGENT-PENDING-001` | While an urgent cut holds its slot, or a caller holds HoldUrgentPending, every Normal admission on the host is refused with ErrUrgentPending (a held-slot wait); urgent admissions still run. | M7 host cut admission (Normal before a slot) | `core/hostlimit/limiter.go` `pool`, `Admit`; `core/hostlimit/pending.go` `HoldUrgentPending` | `TestNormalWaitsWhileUrgentPendingIsHeld`, `TestUrgentLeaseHoldsThePendingSignal` (`core/hostlimit/pending_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
|
||||
| `INV-HOST-LAUNCH-CHECK-001` | blockvolume refuses to start with a --host-limit-dir that is missing or not a directory, under a temporary directory, on a network file system, or already in use with different host-limit flags. | M7 host cut admission (process start) | `core/hostlimit/launch.go` `CheckLaunch`; `core/hostlimit/remotefs_linux.go`; `cmd/blockvolume/main.go` | `TestCheckLaunch` (`core/hostlimit/pending_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, an intent naming every key of that kind the round preallocated is durable in the filer: one for all candidate chunks, however many upload waves the round uses, and one for all new segments. | M5 Intent → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_FailedPutIntentUploadsNothing` (`core/storage/chunk_layer_intent_test.go`); `TestCutPayloadIntentCountIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
|
||||
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE |
|
||||
|
||||
Reference in new issue
Block a user