mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
feat: coordinate host cut budgets with shared file-lock slots
This commit is contained in:
1 parent
26c13b50a4
commit
b1ecbee969
10 files changed
+779
-4
No files matched your search
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
@@ -29,6 +30,7 @@ const (
|
||||
)
|
||||
|
||||
type chunkFlags struct {
|
||||
hostLimit hostlimit.Config
|
||||
filer string
|
||||
path string
|
||||
collection string
|
||||
@@ -47,7 +49,7 @@ func validateChunkFlags(f flags) error {
|
||||
if f.durableImpl != "walstore-chunk" {
|
||||
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
|
||||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
|
||||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint {
|
||||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.hostLimit.Directory != "" {
|
||||
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
)
|
||||
|
||||
func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) {
|
||||
*c = hostlimit.DefaultConfig("")
|
||||
fs.StringVar(&c.Directory, "host-limit-dir", "", "shared local directory for background-cut slots; empty disables shared slots")
|
||||
fs.IntVar(&c.NormalSlots, "host-limit-normal-slots", c.NormalSlots, "host normal-cut slots; identical across processes")
|
||||
fs.IntVar(&c.UrgentSlots, "host-limit-urgent-slots", c.UrgentSlots, "host reserved urgent-cut slots")
|
||||
fs.Int64Var(&c.PayloadBytes, "host-limit-payload-bytes", c.PayloadBytes, "maximum cut payload per slot")
|
||||
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, "aggregate background upload rate across cut slots")
|
||||
fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "static-share divisor when the pool is unavailable; shared cap is not enforced")
|
||||
fs.DurationVar(&c.MaxHold, "host-limit-max-hold", c.MaxHold, "cut lease timeout; expiration aborts but waits for admitted I/O before release")
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/ublk"
|
||||
"github.com/seaweedfs/seaweed-block/core/geometry"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/recovery"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
@@ -192,6 +193,7 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device")
|
||||
fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)")
|
||||
fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set")
|
||||
registerHostLimitFlags(fs, &f.chunk.hostLimit)
|
||||
fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port")
|
||||
fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)")
|
||||
fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)")
|
||||
@@ -642,6 +644,18 @@ func run(f flags) int {
|
||||
cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers
|
||||
cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth
|
||||
cfg.ChunkHolder = chunkHolder(f)
|
||||
cfg.ChunkStagger = true
|
||||
if f.chunk.hostLimit.Directory != "" {
|
||||
limiter, limitErr := hostlimit.New(f.chunk.hostLimit)
|
||||
if limitErr != nil {
|
||||
chunkErr = errors.Join(chunkErr, limitErr)
|
||||
} else {
|
||||
defer limiter.Close()
|
||||
cfg.ChunkBudget = limiter
|
||||
cfg.ChunkPayloadMemoryBudget = f.chunk.hostLimit.PayloadBytes
|
||||
cfg.ChunkCOWSpillLimit = f.chunk.hostLimit.COWBytes
|
||||
}
|
||||
}
|
||||
if chunkErr == nil {
|
||||
cfg.ChunkRemoteFor = chunk.remoteFor
|
||||
workspaceRemoteFor = chunk.remoteFor
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) {
|
||||
c := hostlimit.DefaultConfig(t.TempDir())
|
||||
c.NormalSlots = 1
|
||||
c.UrgentSlots = 1
|
||||
holder, e := hostlimit.New(c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer holder.Close()
|
||||
x, e := holder.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer holder.Release(x)
|
||||
lim, e := hostlimit.New(c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer lim.Close()
|
||||
r := storage.NewMemChunkRemote()
|
||||
p, e := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer p.Close()
|
||||
s := openRecovered(t, p)
|
||||
if _, e = s.Write(0, block(0x72)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.Sync(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.CaptureVolume(context.Background(), "v1"); !errors.Is(e, storage.ErrChunkCaptureRefused) {
|
||||
t.Fatalf("full cut pool: %v", e)
|
||||
}
|
||||
if _, e = s.Write(1, block(0x73)); e != nil {
|
||||
t.Fatal("limiter blocked write", e)
|
||||
}
|
||||
if e = s.Sync(); e != nil {
|
||||
t.Fatal("limiter blocked Flush", e)
|
||||
}
|
||||
if b, e := s.Read(0); e != nil || b[0] != 0x72 {
|
||||
t.Fatal("limiter blocked read", e)
|
||||
}
|
||||
h, _ := r.GetHead(context.Background())
|
||||
if h.Gen != 0 {
|
||||
t.Fatal("refused cut published")
|
||||
}
|
||||
}
|
||||
@@ -188,7 +188,10 @@ type ProviderConfig struct {
|
||||
// ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default.
|
||||
ChunkPayloadMemoryBudget int64
|
||||
// ChunkBudget optionally admits cuts and accounts COW bytes through the host limiter.
|
||||
ChunkBudget storage.Budget
|
||||
ChunkBudget storage.Budget
|
||||
ChunkCOWSpillLimit int64
|
||||
// ChunkStagger spreads automatic cuts by the stable volume-ID phase.
|
||||
ChunkStagger bool
|
||||
}
|
||||
|
||||
// DurableProvider is the production frontend.Provider implementation.
|
||||
@@ -295,6 +298,7 @@ type ChunkStatus struct {
|
||||
Fenced bool
|
||||
RemoteLSN uint64
|
||||
Stats storage.ChunkLayerStats
|
||||
HostBudget any `json:",omitempty"`
|
||||
}
|
||||
|
||||
// NewDurableProvider constructs a provider. view is the ONLY
|
||||
@@ -561,6 +565,9 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus {
|
||||
if cv.layer != nil {
|
||||
cs.Attached, cs.Fenced, cs.RemoteLSN, cs.Stats = true, cv.layer.Fenced(), cv.layer.RemoteLSN(), cv.layer.Stats()
|
||||
}
|
||||
if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok {
|
||||
cs.HostBudget = budget.Snapshot()
|
||||
}
|
||||
st.Chunk = cs
|
||||
}
|
||||
out = append(out, st)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
@@ -357,6 +358,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
holder = proj.ReplicaID
|
||||
}
|
||||
bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
|
||||
if pace, ok := p.cfg.ChunkBudget.(interface {
|
||||
WaitUpload(context.Context, int) error
|
||||
}); ok {
|
||||
bound.waitUpload = pace.WaitUpload
|
||||
}
|
||||
bound.setAttach(ctx) // the attach's calls also end with the caller's ctx
|
||||
defer bound.setAttach(nil)
|
||||
var remote storage.ChunkRemote = bound
|
||||
@@ -376,6 +382,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
UploadConcurrency: p.cfg.ChunkUploadConcurrency,
|
||||
PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget,
|
||||
Budget: p.cfg.ChunkBudget,
|
||||
COWSpillLimit: p.cfg.ChunkCOWSpillLimit,
|
||||
CaptureAllowed: func() error {
|
||||
cur := p.view.Projection()
|
||||
if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID {
|
||||
@@ -462,7 +469,8 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
|
||||
// attach runs, its calls also end with the attach caller's context.
|
||||
type closeBoundRemote struct {
|
||||
storage.ChunkRemote
|
||||
done context.Context
|
||||
done context.Context
|
||||
waitUpload func(context.Context, int) error
|
||||
|
||||
mu sync.Mutex
|
||||
attach context.Context
|
||||
@@ -499,6 +507,11 @@ func (r *closeBoundRemote) bind(ctx context.Context) (context.Context, func()) {
|
||||
func (r *closeBoundRemote) Put(ctx context.Context, key string, data []byte) error {
|
||||
c, end := r.bind(ctx)
|
||||
defer end()
|
||||
if r.waitUpload != nil {
|
||||
if err := r.waitUpload(c, len(data)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return r.ChunkRemote.Put(c, key, data)
|
||||
}
|
||||
|
||||
@@ -698,6 +711,9 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
backoffMax: chunkCutBackoffMax,
|
||||
}
|
||||
s := cutSchedule{lastSuccess: time.Now()}
|
||||
if p.cfg.ChunkStagger {
|
||||
s.lastSuccess = s.lastSuccess.Add(hostlimit.Phase(volumeID, pol.interval))
|
||||
}
|
||||
t := time.NewTicker(chunkSchedulePoll)
|
||||
defer t.Stop()
|
||||
for {
|
||||
@@ -811,6 +827,9 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN
|
||||
return storage.ChunkCutResult{}, fmt.Errorf("durable: cut of %s to LSN %d: that LSN was never written (last %d)", volumeID, minLSN, last)
|
||||
}
|
||||
}
|
||||
if minLSN > 0 {
|
||||
ctx = hostlimit.WithClass(ctx, hostlimit.Urgent)
|
||||
}
|
||||
r, err := layer.Cut(ctx)
|
||||
if err != nil {
|
||||
return storage.ChunkCutResult{}, err
|
||||
@@ -876,7 +895,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st
|
||||
if err == nil {
|
||||
p.stopChunkLoop(h)
|
||||
var r storage.ChunkCutResult
|
||||
if r, err = layer.Detach(cutCtx); err == nil {
|
||||
if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil {
|
||||
return r, h.storage.NextLSN() - 1, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
// Package hostlimit coordinates background cuts across cooperating host processes.
|
||||
// Guest I/O never acquires a slot. A missing pool degrades to static rate sharing.
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrBusy = errors.New("hostlimit: no background slot")
|
||||
var ErrConfig = errors.New("hostlimit: incompatible host configuration")
|
||||
var ErrRevoked = errors.New("hostlimit: cut budget revoked")
|
||||
|
||||
type Class uint8
|
||||
|
||||
const (
|
||||
Normal Class = iota
|
||||
Urgent
|
||||
)
|
||||
|
||||
type classKey struct{}
|
||||
|
||||
func WithClass(ctx context.Context, c Class) context.Context {
|
||||
return context.WithValue(ctx, classKey{}, c)
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Directory string
|
||||
NormalSlots, UrgentSlots int
|
||||
PayloadBytes, COWBytes int64
|
||||
BytesPerSecond int64
|
||||
FallbackVolumes int
|
||||
MaxHold time.Duration
|
||||
}
|
||||
|
||||
func DefaultConfig(dir string) Config {
|
||||
return Config{dir, 3, 1, 64 << 20, 1 << 30, 64 << 20, 200, 5 * time.Minute}
|
||||
}
|
||||
func (c Config) validate() error {
|
||||
if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.UrgentSlots < 1 || c.NormalSlots+c.UrgentSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.MaxHold <= 0 {
|
||||
return errors.New("hostlimit: invalid configuration")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Stats struct {
|
||||
Active int
|
||||
PayloadReserved, COWReserved int64
|
||||
Admitted, Skipped, Fallback, Revoked, Released uint64
|
||||
FallbackActive bool
|
||||
}
|
||||
type lease struct {
|
||||
file *os.File
|
||||
payload, cow int64
|
||||
abort func(error)
|
||||
timer *time.Timer
|
||||
releasing bool
|
||||
}
|
||||
type Limiter struct {
|
||||
cfg Config
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
next uint64
|
||||
live map[uint64]*lease
|
||||
stats Stats
|
||||
closed bool
|
||||
wake chan struct{}
|
||||
done chan struct{}
|
||||
nextUpload time.Time
|
||||
fallback bool
|
||||
}
|
||||
|
||||
func New(c Config) (*Limiter, error) {
|
||||
if err := c.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l := &Limiter{cfg: c, live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})}
|
||||
l.cond = sync.NewCond(&l.mu)
|
||||
go l.releaseLoop()
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Phase is stable across process restarts; it never delays guest readiness.
|
||||
func Phase(volume string, period time.Duration) time.Duration {
|
||||
if period <= 0 {
|
||||
return 0
|
||||
}
|
||||
h := fnv.New64a()
|
||||
_, _ = h.Write([]byte(volume))
|
||||
return time.Duration(h.Sum64() % uint64(period))
|
||||
}
|
||||
|
||||
// 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) (*os.File, error) {
|
||||
info, err := os.Lstat(l.cfg.Directory)
|
||||
if 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)
|
||||
}
|
||||
guard, err := open("configuration.lock")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer guard.Close()
|
||||
if err = tryLock(guard); err != nil {
|
||||
return nil, ErrBusy
|
||||
}
|
||||
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 = os.WriteFile(path, expected, 0600)
|
||||
existing = expected
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if string(existing) != string(expected) {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
names := []string{}
|
||||
if c == Urgent {
|
||||
for i := 0; i < l.cfg.UrgentSlots; i++ {
|
||||
names = append(names, fmt.Sprintf("urgent-%d", i))
|
||||
}
|
||||
}
|
||||
for i := 0; i < l.cfg.NormalSlots; i++ {
|
||||
names = append(names, fmt.Sprintf("normal-%d", i))
|
||||
}
|
||||
for _, name := range names {
|
||||
f, e := open(name)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tryLock(f); e == nil {
|
||||
return f, nil
|
||||
}
|
||||
_ = f.Close()
|
||||
if !errors.Is(e, ErrBusy) {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return nil, ErrBusy
|
||||
}
|
||||
func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if payload < 0 || payload > l.cfg.PayloadBytes {
|
||||
return 0, ErrBusy
|
||||
}
|
||||
c, _ := ctx.Value(classKey{}).(Class)
|
||||
f, err := l.pool(c)
|
||||
if errors.Is(err, ErrBusy) {
|
||||
l.mu.Lock()
|
||||
l.stats.Skipped++
|
||||
l.mu.Unlock()
|
||||
return 0, err
|
||||
}
|
||||
if errors.Is(err, ErrConfig) {
|
||||
return 0, err
|
||||
}
|
||||
fallback := err != nil // A is deliberately degraded: no shared memory/spill cap.
|
||||
l.mu.Lock()
|
||||
if l.closed || ctx.Err() != nil || len(l.live) >= l.cfg.NormalSlots+l.cfg.UrgentSlots {
|
||||
l.stats.Skipped++
|
||||
l.mu.Unlock()
|
||||
if f != nil {
|
||||
_ = f.Close()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
return 0, ErrBusy
|
||||
}
|
||||
l.next++
|
||||
id := l.next
|
||||
x := &lease{file: f, payload: payload, abort: abort}
|
||||
l.live[id] = x
|
||||
l.stats.Admitted++
|
||||
l.stats.PayloadReserved += payload
|
||||
l.stats.Active++
|
||||
l.fallback = fallback
|
||||
l.stats.FallbackActive = fallback
|
||||
if fallback {
|
||||
l.stats.Fallback++
|
||||
l.stats.FallbackActive = true
|
||||
}
|
||||
x.timer = time.AfterFunc(l.cfg.MaxHold, func() { l.revoke(id) })
|
||||
l.mu.Unlock()
|
||||
return id, nil
|
||||
}
|
||||
func (l *Limiter) revoke(id uint64) {
|
||||
l.mu.Lock()
|
||||
x := l.live[id]
|
||||
var abort func(error)
|
||||
if x != nil && !x.releasing {
|
||||
abort = x.abort
|
||||
l.stats.Revoked++
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if abort != nil {
|
||||
abort(ErrRevoked)
|
||||
}
|
||||
}
|
||||
|
||||
// ReserveCOW is guest-path accounting only: no OS calls, RPC or waiting for a slot.
|
||||
func (l *Limiter) ReserveCOW(id uint64, n int64) error {
|
||||
l.mu.Lock()
|
||||
x := l.live[id]
|
||||
if x == nil || x.releasing || n < 0 {
|
||||
l.mu.Unlock()
|
||||
return ErrRevoked
|
||||
}
|
||||
if n > l.cfg.COWBytes-x.cow {
|
||||
abort := x.abort
|
||||
l.stats.Revoked++
|
||||
l.mu.Unlock()
|
||||
if abort != nil {
|
||||
abort(ErrRevoked)
|
||||
}
|
||||
return ErrRevoked
|
||||
}
|
||||
x.cow += n
|
||||
l.stats.COWReserved += n
|
||||
l.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release only marks settled work; one owned worker closes descriptors. Until
|
||||
// then the kernel slot remains unavailable, conservatively retaining capacity.
|
||||
func (l *Limiter) Release(id uint64) {
|
||||
l.mu.Lock()
|
||||
if x := l.live[id]; x != nil && !x.releasing {
|
||||
x.releasing = true
|
||||
x.timer.Stop()
|
||||
}
|
||||
l.mu.Unlock()
|
||||
select {
|
||||
case l.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
func (l *Limiter) releaseLoop() {
|
||||
defer close(l.done)
|
||||
for range l.wake {
|
||||
for {
|
||||
l.mu.Lock()
|
||||
var id uint64
|
||||
var x *lease
|
||||
for k, v := range l.live {
|
||||
if v.releasing {
|
||||
id, x = k, v
|
||||
break
|
||||
}
|
||||
}
|
||||
if x == nil {
|
||||
stop := l.closed && len(l.live) == 0
|
||||
l.mu.Unlock()
|
||||
if stop {
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if x.file != nil {
|
||||
_ = x.file.Close()
|
||||
}
|
||||
l.mu.Lock()
|
||||
delete(l.live, id)
|
||||
l.stats.Active--
|
||||
l.stats.PayloadReserved -= x.payload
|
||||
l.stats.COWReserved -= x.cow
|
||||
l.stats.Released++
|
||||
l.cond.Broadcast()
|
||||
l.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
func (l *Limiter) Snapshot() any { l.mu.Lock(); defer l.mu.Unlock(); return l.stats }
|
||||
|
||||
// WaitUpload paces background payload PUTs, including parallel uploader workers.
|
||||
// Static shares trade utilization for a conservative aggregate rate. It never
|
||||
// paces local WAL flushing, COW reads, or demand hydration.
|
||||
func (l *Limiter) WaitUpload(ctx context.Context, n int) error {
|
||||
if n < 0 {
|
||||
return ErrBusy
|
||||
}
|
||||
l.mu.Lock()
|
||||
div := l.cfg.NormalSlots + l.cfg.UrgentSlots
|
||||
if l.fallback {
|
||||
div = l.cfg.FallbackVolumes
|
||||
}
|
||||
rate := l.cfg.BytesPerSecond / int64(div)
|
||||
if rate < 1 {
|
||||
rate = 1
|
||||
}
|
||||
now := time.Now()
|
||||
start := l.nextUpload
|
||||
if start.Before(now) {
|
||||
start = now
|
||||
}
|
||||
duration := time.Duration(float64(n) / float64(rate) * float64(time.Second))
|
||||
l.nextUpload = start.Add(duration)
|
||||
l.mu.Unlock()
|
||||
timer := time.NewTimer(time.Until(start))
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Close cancels cuts but cannot release their physical-I/O ownership. Callers
|
||||
// must still settle their cuts and call Release; Close joins that settlement.
|
||||
func (l *Limiter) Close() {
|
||||
l.mu.Lock()
|
||||
l.closed = true
|
||||
callbacks := []func(error){}
|
||||
for _, x := range l.live {
|
||||
if !x.releasing && x.abort != nil {
|
||||
callbacks = append(callbacks, x.abort)
|
||||
}
|
||||
}
|
||||
l.mu.Unlock()
|
||||
for _, a := range callbacks {
|
||||
a(ErrRevoked)
|
||||
}
|
||||
select {
|
||||
case l.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-l.done
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testConfig(t *testing.T) Config {
|
||||
t.Helper()
|
||||
c := DefaultConfig(t.TempDir())
|
||||
c.NormalSlots = 1
|
||||
c.UrgentSlots = 1
|
||||
return c
|
||||
}
|
||||
func newTest(t *testing.T, c Config) *Limiter {
|
||||
t.Helper()
|
||||
l, e := New(c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return l
|
||||
}
|
||||
func settled(t *testing.T, l *Limiter) {
|
||||
t.Helper()
|
||||
deadline := time.After(3 * time.Second)
|
||||
tick := time.NewTicker(time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if l.Snapshot().(Stats).Active == 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatal("release did not settle")
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestSlotsUrgentAndJoinedRelease(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
a, b, d := newTest(t, c), newTest(t, c), newTest(t, c)
|
||||
defer a.Close()
|
||||
defer b.Close()
|
||||
defer d.Close()
|
||||
x, e := a.Admit(context.Background(), c.PayloadBytes, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer a.Release(x)
|
||||
if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) {
|
||||
t.Fatalf("normal bypass: %v", e)
|
||||
}
|
||||
y, e := b.Admit(WithClass(context.Background(), Urgent), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer b.Release(y)
|
||||
if _, e = d.Admit(WithClass(context.Background(), Urgent), 1, nil); !errors.Is(e, ErrBusy) {
|
||||
t.Fatalf("urgent bypass: %v", e)
|
||||
}
|
||||
a.Release(x)
|
||||
a.Release(x)
|
||||
settled(t, a)
|
||||
z, e := d.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
d.Release(z)
|
||||
settled(t, d)
|
||||
}
|
||||
func TestCOWAbortHoldsSlotUntilWorkerSettlement(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
a, b := newTest(t, c), newTest(t, c)
|
||||
defer a.Close()
|
||||
defer b.Close()
|
||||
revoked := make(chan struct{}, 1)
|
||||
x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} })
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer a.Release(x)
|
||||
if e = a.ReserveCOW(x, c.COWBytes); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = a.ReserveCOW(x, 1); !errors.Is(e, ErrRevoked) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
select {
|
||||
case <-revoked:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("no abort")
|
||||
}
|
||||
if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) {
|
||||
t.Fatalf("revocation released live I/O: %v", e)
|
||||
}
|
||||
a.Release(x)
|
||||
settled(t, a)
|
||||
}
|
||||
func TestHoldExpiryAndCloseDoNotSteal(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
c.MaxHold = 30 * time.Millisecond
|
||||
a, b := newTest(t, c), newTest(t, c)
|
||||
defer b.Close()
|
||||
revoked := make(chan struct{}, 4)
|
||||
x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} })
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
select {
|
||||
case <-revoked:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("no expiry")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { a.Close(); close(done) }()
|
||||
select {
|
||||
case <-revoked:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close did not cancel")
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("Close abandoned worker")
|
||||
default:
|
||||
}
|
||||
if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) {
|
||||
t.Fatal("lease stolen", e)
|
||||
}
|
||||
a.Release(x)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close not joined")
|
||||
}
|
||||
}
|
||||
func TestFallbackAndConfigMismatch(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
a := newTest(t, c)
|
||||
x, e := a.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
a.Release(x)
|
||||
settled(t, a)
|
||||
a.Close()
|
||||
bad := c
|
||||
bad.NormalSlots++
|
||||
b := newTest(t, bad)
|
||||
defer b.Close()
|
||||
if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrConfig) {
|
||||
t.Fatalf("config mismatch bypassed cap: %v", e)
|
||||
}
|
||||
c.Directory += "-missing"
|
||||
f := newTest(t, c)
|
||||
defer f.Close()
|
||||
x, e = f.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f.Release(x)
|
||||
settled(t, f)
|
||||
if !f.Snapshot().(Stats).FallbackActive {
|
||||
t.Fatal("degraded cap hidden")
|
||||
}
|
||||
}
|
||||
func TestRateCancellationAndPhase(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
c.BytesPerSecond = 1024
|
||||
l := newTest(t, c)
|
||||
defer l.Close()
|
||||
if e := l.WaitUpload(context.Background(), 2048); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
if e := l.WaitUpload(ctx, 2048); !errors.Is(e, context.DeadlineExceeded) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
seen := map[time.Duration]bool{}
|
||||
for i := 0; i < 200; i++ {
|
||||
v := fmt.Sprint(i)
|
||||
p := Phase(v, time.Minute)
|
||||
if p < 0 || p >= time.Minute || p != Phase(v, time.Minute) {
|
||||
t.Fatal("bad phase")
|
||||
}
|
||||
seen[p] = true
|
||||
}
|
||||
if len(seen) < 190 {
|
||||
t.Fatal("phase collision", len(seen))
|
||||
}
|
||||
}
|
||||
func TestProcessSlotHelper(t *testing.T) {
|
||||
dir := os.Getenv("SWBLOCK_TEST_LIMITER_DIR")
|
||||
if dir == "" {
|
||||
return
|
||||
}
|
||||
c := DefaultConfig(dir)
|
||||
c.NormalSlots = 1
|
||||
c.UrgentSlots = 1
|
||||
l, e := New(c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = l.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fmt.Println("HELD")
|
||||
_, _ = bufio.NewReader(os.Stdin).ReadByte()
|
||||
}
|
||||
func TestKilledProcessReleasesButLiveHolderDoesNot(t *testing.T) {
|
||||
c := testConfig(t)
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestProcessSlotHelper$")
|
||||
cmd.Env = append(os.Environ(), "SWBLOCK_TEST_LIMITER_DIR="+c.Directory)
|
||||
out, e := cmd.StdoutPipe()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
in, e := cmd.StdinPipe()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer in.Close()
|
||||
if e = cmd.Start(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }()
|
||||
ready := make(chan bool, 1)
|
||||
go func() {
|
||||
s := bufio.NewScanner(out)
|
||||
for s.Scan() {
|
||||
if s.Text() == "HELD" {
|
||||
ready <- true
|
||||
return
|
||||
}
|
||||
}
|
||||
ready <- false
|
||||
}()
|
||||
select {
|
||||
case ok := <-ready:
|
||||
if !ok {
|
||||
t.Fatal("child failed")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("child not ready")
|
||||
}
|
||||
l := newTest(t, c)
|
||||
defer l.Close()
|
||||
if _, e = l.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) {
|
||||
t.Fatalf("live child not counted: %v", e)
|
||||
}
|
||||
if e = cmd.Process.Kill(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_ = cmd.Wait()
|
||||
x, e := l.Admit(context.Background(), 1, nil)
|
||||
if e != nil {
|
||||
t.Fatal("dead child retained slot", e)
|
||||
}
|
||||
l.Release(x)
|
||||
settled(t, l)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//go:build !windows
|
||||
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func tryLock(f *os.File) error {
|
||||
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) {
|
||||
return ErrBusy
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//go:build windows
|
||||
|
||||
package hostlimit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"golang.org/x/sys/windows"
|
||||
"os"
|
||||
)
|
||||
|
||||
func tryLock(f *os.File) error {
|
||||
err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{})
|
||||
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
|
||||
return ErrBusy
|
||||
}
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user