Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ has a matching GitHub release whose body comes from its section below.

## [Unreleased]

### Added

- `settle = "5s"` on a `[[claim]]` hold makes the process last that long before the hold drains
anyone. A screenshot script or a launcher probe that runs for a few seconds no longer takes the
card from its holder. (#337)

### Fixed

- A `berth run` or `berth train` engine is always visible to a berthd that restarts. The run writes
its record when the engine starts, not only after its wrapper notices the lost socket, so a wrapper
that is stopped or slow cannot let the new daemon grant a second whole-card lease onto a live engine.
(#354)
- A headless `gamescope --backend headless`, the way a capture or CI harness runs it, no longer
holds the card through the built-in gamescope claim. (#337)
- A berthd that restarts now sees a live `berth run` or `berth train` engine, even when its wrapper
has not yet noticed the lost socket. Before, it could grant a second whole-card lease onto that
engine. (#354)
- `go test ./internal/cli` on a Windows machine with Berth installed no longer deletes the installed services'
launchers (`units\*.vbs` in the state directory). Three service tests ran a real uninstall or install against
the user's own state directory instead of a temporary one. (#351)
Expand Down
11 changes: 7 additions & 4 deletions docs/leasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,15 @@
## Games, apps and holds
- **Claims cover work Berth does not start.** berthd scans the process table every 2 s.
A *hold* claim keeps the card while its process runs: engines are drained and wait, with a
15 s linger so a launcher restarting the game does not bounce the card back. A *track*
claim names an app's card memory so it counts against the card without being reported as a
stowaway; nothing waits on it.
15 s linger so a launcher restarting the game does not bounce the card back. `settle` makes
the hold wait that long first, so a helper that lives a few seconds never drains anyone. A
*track* claim names an app's card memory so it counts against the card without being reported
as a stowaway; nothing waits on it.
- **Built-in pack, on by default.** Holds: Steam games (anything under Steam's `reaper`),
Lutris and gamescope on Linux; Steam libraries (`steamapps\common`), Epic, GOG, EA,
Ubisoft, Xbox and Battle.net games on Windows, with launchers, Wallpaper Engine and
Lossless Scaling left out. Tracks: Blender, DaVinci Resolve, OBS, Kdenlive, Premiere,
Lossless Scaling left out. A headless gamescope, the way a capture or CI harness runs it,
holds nothing. Tracks: Blender, DaVinci Resolve, OBS, Kdenlive, Premiere,
After Effects. `berth claims` shows every rule and what it matches now.
- **Your own rules:**

Expand All @@ -146,6 +148,7 @@
cmdline = 'train\.py' # regex; on Windows it sees the exe's full path
action = "hold" # or "track"
linger = "30s"
settle = "5s" # hold only: wait this long before draining; a short helper never takes the card
gpu = "gpu1" # hold only these cards (names or PCI addresses, comma list); default every card

[claims]
Expand Down
14 changes: 13 additions & 1 deletion internal/claims/claims.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ type Rule struct {
Action string // hold | track
NeedsMiB uint64 // hold only: 0 = the whole card
Linger time.Duration // hold only: 0 = DefaultLinger
// Settle is how long a match must last before a hold starts, so a process
// that lives a few seconds (a screenshot harness, a launcher probe) never
// drains the holder. 0 = start on the first match. Hold only.
Settle time.Duration
// GPU is the cards a hold takes, as berth run --gpu names them; "" is
// every card. Cards is GPU resolved to positions in the watcher's
// cards, nil for every card.
Expand Down Expand Up @@ -84,7 +88,9 @@ func Builtin() []Rule {
// REAPER DAW is also "reaper" and never passes SteamLaunch (#171).
{Name: "steam-game", Parent: []string{"reaper"}, ParentCmdline: `(^|\s)SteamLaunch(\s|$)`, Action: ActionHold, Builtin: true},
{Name: "lutris-game", Parent: []string{"lutris-wrapper*"}, Action: ActionHold, Builtin: true},
{Name: "gamescope", Exe: []string{"gamescope"}, Action: ActionHold, Builtin: true},
// A headless gamescope is a capture or CI harness (a screenshot script
// runs one per frame), not a game: it holds nothing (#337).
{Name: "gamescope", Exe: []string{"gamescope"}, Not: `(^|\s)--backend[= ]headless(\s|$)`, Action: ActionHold, Builtin: true},
// Windows (and Proton, whose paths look the same): games by install folder.
// Wallpaper Engine and Lossless Scaling live in the Steam library but run all
// day beside other work; holding the card for them would starve every engine.
Expand Down Expand Up @@ -125,6 +131,12 @@ func (r *Rule) Compile() error {
return fmt.Errorf("claim %q: %v", r.Name, err)
}
}
if r.Settle < 0 {
return fmt.Errorf("claim %q: settle is how long a hold waits before it drains, so it cannot be negative", r.Name)
}
if r.Settle > 0 && r.Action != ActionHold {
return fmt.Errorf("claim %q: settle names how long a hold waits before it drains; a %s claim drains nothing", r.Name, r.Action)
}
if len(r.Exe) == 0 && r.Cmdline == "" && len(r.Parent) == 0 {
return fmt.Errorf("claim %q: give exe, cmdline or parent to match on", r.Name)
}
Expand Down
86 changes: 86 additions & 0 deletions internal/claims/claims_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,21 @@ func TestBuiltinMatches(t *testing.T) {
}
}

// A headless gamescope is a capture or CI harness, not a game: it must not
// take the card away from its holder (#337).
func TestBuiltinGamescopeSkipsHeadless(t *testing.T) {
ps := []Proc{
{PID: 10, Name: "gamescope", Argv0: "gamescope", Parent: 1,
Cmdline: "gamescope --backend headless -W 1920 -H 1080 -- true"},
{PID: 11, Name: "gamescope", Argv0: "gamescope", Parent: 1,
Cmdline: "gamescope -w 2560 -h 1440 -f -- %command%"},
}
m := Match(compiled(t, Builtin()...), ps)
if got := pids(m["gamescope"]); len(got) != 1 || got[0] != 11 {
t.Fatalf("gamescope = %v, want [11]: the headless capture harness holds nothing", got)
}
}

func TestCmdlineAndFirstRuleWins(t *testing.T) {
rs := compiled(t,
Rule{Name: "training", Cmdline: `train\.py`, Action: ActionHold},
Expand All @@ -80,6 +95,8 @@ func TestCompileRejects(t *testing.T) {
{Name: "x", Parent: []string{"reaper"}, ParentCmdline: "("},
{Name: "x", Exe: []string{"a"}, GPU: "card 1"},
{Name: "x", Exe: []string{"a"}, GPU: "gpu1", Action: ActionTrack},
{Name: "x", Exe: []string{"a"}, Settle: -time.Second},
{Name: "x", Exe: []string{"a"}, Action: ActionTrack, Settle: time.Second},
} {
if err := r.Compile(); err == nil {
t.Errorf("%+v compiled", r)
Expand Down Expand Up @@ -115,6 +132,75 @@ func (f *fakeBroker) Note(e proto.Event) {
f.mu.Unlock()
}

// #337: a hold waits for its match to last the rule's settle time before it
// drains anyone. A process that lives a few seconds, a screenshot harness or
// a launcher probe, never takes the card from its holder.
func TestWatcherHoldSettles(t *testing.T) {
shot := []Proc{{PID: 10, Name: "python3", Argv0: "python3", Parent: 1, Cmdline: "python3 shot.py"}}
newWatcher := func(t *testing.T, procs *[]Proc) (*Watcher, *fakeBroker) {
t.Helper()
fb := &fakeBroker{held: make(chan struct{}, 4)}
w := &Watcher{Cards: []Broker{fb}, Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
Scan: func() ([]Proc, error) { return *procs, nil }, holds: map[string]*hold{}}
w.Rules = compiled(t, Rule{Name: "shot", Cmdline: `shot\.py`, Settle: 3 * time.Second})
return w, fb
}
held := func(t *testing.T, fb *fakeBroker) bool {
t.Helper()
select {
case <-fb.held:
return true
case <-time.After(200 * time.Millisecond):
return false
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

t.Run("waits for the settle", func(t *testing.T) {
procs := shot
w, fb := newWatcher(t, &procs)
t0 := time.Now()
w.Tick(ctx, t0)
w.Tick(ctx, t0.Add(2*time.Second))
if held(t, fb) {
t.Fatal("hold started before the match settled")
}
w.Tick(ctx, t0.Add(3*time.Second))
if !held(t, fb) {
t.Fatal("hold did not start once the match settled")
}
})

t.Run("a gap restarts the clock", func(t *testing.T) {
procs := shot
w, fb := newWatcher(t, &procs)
t0 := time.Now()
w.Tick(ctx, t0)
procs = nil
w.Tick(ctx, t0.Add(2*time.Second))
procs = shot
w.Tick(ctx, t0.Add(3*time.Second))
w.Tick(ctx, t0.Add(5*time.Second))
if held(t, fb) {
t.Fatal("hold started on time that ran before the gap")
}
w.Tick(ctx, t0.Add(6*time.Second))
if !held(t, fb) {
t.Fatal("hold did not start once the match settled after the gap")
}
})
}

// A track claim names memory and drains nothing, so its settle time is a
// contradiction the daemon refuses at load.
func TestCompileRejectsSettleOnTrack(t *testing.T) {
r := Rule{Name: "x", Exe: []string{"a"}, Action: ActionTrack, Settle: time.Second}
if err := r.Compile(); err == nil || !strings.Contains(err.Error(), "settle") {
t.Fatalf("err = %v, want settle named", err)
}
}

// A hold starts on the first match, survives a gap shorter than the linger,
// and ends once the game has been gone for the linger.
func TestWatcherHoldLifecycle(t *testing.T) {
Expand Down
44 changes: 35 additions & 9 deletions internal/claims/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ type Watcher struct {

mu sync.Mutex
holds map[string]*hold
// seen is when each hold's match was first seen, for rules with a settle
// time: the hold waits there until the process has lasted that long.
seen map[string]time.Time
}

type hold struct {
Expand Down Expand Up @@ -107,18 +110,23 @@ func (w *Watcher) Tick(ctx context.Context, now time.Time) {
case ActionHold:
h := w.holds[r.Name]
switch {
case len(m) > 0 && h == nil:
case len(m) > 0 && h == nil && w.settled(r, now):
w.start(ctx, r, m, now)
h = w.holds[r.Name]
case len(m) > 0:
case len(m) > 0 && h != nil:
h.lastSeen = now
case h != nil && now.Sub(h.lastSeen) >= r.Linger:
h.cancel()
delete(w.holds, r.Name)
w.Log.Info("claim ended", "claim", r.Name)
w.Cards[0].Note(proto.Event{Kind: proto.EvClaimEnded, Engine: "claim:" + r.Name,
Detail: fmt.Sprintf("gone for %s", r.Linger)})
h = nil
case len(m) == 0:
// The match is gone, so its settle clock is gone with it: a
// process that comes back starts the wait again.
delete(w.seen, r.Name)
if h != nil && now.Sub(h.lastSeen) >= r.Linger {
h.cancel()
delete(w.holds, r.Name)
w.Log.Info("claim ended", "claim", r.Name)
w.Cards[0].Note(proto.Event{Kind: proto.EvClaimEnded, Engine: "claim:" + r.Name,
Detail: fmt.Sprintf("gone for %s", r.Linger)})
h = nil
}
}
if h != nil {
st.Active, st.Lease = true, h.granted()
Expand All @@ -134,6 +142,24 @@ func (w *Watcher) Tick(ctx context.Context, now time.Time) {
}
}

// settled is whether a hold's match has lasted the rule's settle time. The
// first scan starts the clock and holds nothing, so a short-lived helper does
// not drain the holder (#337). Called with w.mu held.
func (w *Watcher) settled(r *Rule, now time.Time) bool {
if r.Settle <= 0 {
return true
}
if w.seen == nil {
w.seen = map[string]time.Time{}
}
first, ok := w.seen[r.Name]
if !ok {
w.seen[r.Name] = now
return false
}
return now.Sub(first) >= r.Settle
}

// onCard is the claim states as card i reports them: a hold whose rule
// names other cards is not active here. states holds one entry per rule,
// in rule order.
Expand Down
5 changes: 4 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,9 @@ type ClaimRule struct {
Action string `toml:"action,omitempty" json:"action,omitempty" yaml:"action,omitempty"`
NeedsMiB uint64 `toml:"needs_mib,omitzero" json:"needs_mib,omitempty" yaml:"needs_mib,omitempty"`
Linger Duration `toml:"linger,omitempty" json:"linger,omitempty" yaml:"linger,omitempty"`
// Settle is how long a hold's process must last before it drains the
// card, so a helper that lives a few seconds never takes it. Hold only.
Settle Duration `toml:"settle,omitempty" json:"settle,omitempty" yaml:"settle,omitempty"`
// GPU is the cards a hold takes on a node with several, as berth run
// --gpu names them; "" is every card.
GPU string `toml:"gpu,omitempty" json:"gpu,omitempty" yaml:"gpu,omitempty"`
Expand All @@ -309,7 +312,7 @@ func (c *Config) ClaimRules() ([]claims.Rule, error) {
names := map[string]bool{}
for _, r := range c.Claim {
rule := claims.Rule{Name: r.Name, Exe: r.Exe, Cmdline: r.Cmdline, Not: r.Not, Parent: r.Parent, ParentCmdline: r.ParentCmdline,
Action: r.Action, NeedsMiB: r.NeedsMiB, Linger: r.Linger.Duration, GPU: r.GPU}
Action: r.Action, NeedsMiB: r.NeedsMiB, Linger: r.Linger.Duration, Settle: r.Settle.Duration, GPU: r.GPU}
if err := rule.Compile(); err != nil {
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions internal/skill/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ name = "training"
cmdline = 'train\.py' # regex on the command line (Windows: the exe's full path)
action = "hold" # hold: drain engines while it runs; track: just name its memory
linger = "30s"
settle = "5s" # hold only: wait this long before draining; a short helper never takes the card
gpu = "gpu1" # hold only this card on a node with several; default every card

[claims]
Expand Down