machine

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 42 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package machine discovers what the machine has (cores, memory, disk, GPUs) and how loaded it is (load, pressure), and turns it into the number of workers Djinn runs at once, whether a new worker or a gate may start now, and whether a local model can run.

Index

Constants

View Source
const (
	// AutoBeat is how often auto mode reads the outside load and decides; never faster.
	AutoBeat = 20 * time.Second
	// AutoSmooth is the span of the moving average a beat reads: a test run's bursts of a minute do not break it.
	AutoSmooth = 3 * time.Minute
	// AutoDownAfter is how long the outside load stays above the high mark before auto lowers a notch.
	AutoDownAfter = 3 * time.Minute
	// AutoUpAfter is how long the outside load stays below the low marks before auto raises a notch.
	AutoUpAfter = 5 * time.Minute
	// AutoHold is the least time auto mode keeps a notch it stepped to, whatever the load does.
	AutoHold = 3 * time.Minute
	// AutoHysteresis is how far past a mark, in points of the machine, the load goes before it leaves the side it
	// reached: below 15 % it climbs, and only above 20 % does the wait start again; above 30 % it lowers, and only
	// below 25 % does that wait start again. A beat at 15.1 % no longer throws away minutes of calm (W347).
	AutoHysteresis = 5.0
)

The auto mode's pace (W253, calmed by W347). Once a beat it reads the load outside Djinn, averaged over the last AutoSmooth of what the Hourglass already measured, and steps one notch at a time: down once that average stayed above its high mark for AutoDownAfter, up once it stayed below its low marks for AutoUpAfter. A side once reached is left only AutoHysteresis points past its mark, each step starts the wait again, and a notch is held at least AutoHold.

View Source
const (
	OutlierRuns   = 3
	OutlierFactor = 4
)

OutlierRuns and OutlierFactor say when a peak measured wrong is left out of a command's cost (Peak): from OutlierRuns measured runs on, the one peak above OutlierFactor times the median of the others (W197).

View Source
const (
	MiB = 1 << 20
	GiB = 1 << 30
)

MiB is a mebibyte; GiB is a gibibyte.

View Source
const (
	MemoryWarning  = 2
	MemoryCritical = 4
)

macOS's memory pressure levels that may hold new workers: warning at the Minimal and Medium notches, critical from High up.

View Source
const CommandPeakShare = 0.5

CommandPeakShare is the most of the machine's memory a command's peak counts for in Room: a peak measured past it, a tree gone wrong or a command learned under another's key, never asks more than the machine can give (W139).

View Source
const ContainersSlice = cgroupRoot + "/djinn.slice"

ContainersSlice is where docker runs the containers of Djinn's workers, each task's in a slice of its own (wrap.Slice: --cgroup-parent=djinn-<task>.slice, which systemd places under djinn.slice). Docker's daemon owns it, outside the user's tree: its files are read, never written.

View Source
const DefaultBrakeMemory = 5

DefaultBrakeMemory is the memory brake's threshold when nothing sets it (decision Q22 B): it freezes a worker under 5 % of the machine's memory available. djinn up --brake-memory says the same default (cli.Builtins).

View Source
const Delegate = "an administrator adds Delegate=cpu cpuset io memory pids to user@.service, once"

Delegate is what an administrator does, once, for systemd to give a user the controllers.

View Source
const IntervalRetention = 90 * 24 * time.Hour

IntervalRetention is how long the gate intervals are kept: three months (decision Q49), well past the week the series and the history of the gates read at most. Some 160,000 rows: a read of a window goes by the index on the release time (TestIntervalsReadByIndex).

View Source
const KeyLength = 200

KeyLength is the most characters a command's key keeps (Key).

View Source
const LongWait = 5

LongWait is the wait for a gate, in seconds, past which a worker notices it: the Gates tab counts those apart.

View Source
const MaxSeriesPoints = 1500

MaxSeriesPoints is the most points a series is sent with: a longer range is read by buckets, each its highest values, so that a peak stays readable.

View Source
const MostBrakeMemory = 95

MostBrakeMemory is the highest threshold the brake takes, in percent: above, it would freeze a calm machine.

View Source
const NotMeasured = ""

NotMeasured is why the workers' CPU and memory are not measured here; empty: they are.

View Source
const PeakRuns = 20

PeakRuns is how many of a command's latest measured runs give the peak the gates hold it to (Peak).

View Source
const WorkerTasks = 4096

WorkerTasks is the TasksMax of a worker's scope: six times the most tasks a push check's scope held (647), so that it only stops a runaway.

Variables

View Source
var DefaultAutoMarks = AutoMarks{CPUHigh: 30, CPULow: 15, MemoryHigh: 70, MemoryLow: 60}

DefaultAutoMarks come from the developer's machine (W253, 16 cores, 31 GB). Over 3 days of its history (below, every 5 s), the CPU outside Djinn, as a minute's average, stayed under 14 % nine times out of ten and under 17 % 19 times out of 20: the desktop, the browser, the window drawn. Played on those days, 30 and 15 took 4 steps down in 3 episodes (an IDE indexing on half the machine, a browser with containers, a video call) and kept auto at Max 98 % of the time; 20 and 10 kept it at Minimal 30 % of the time. The memory outside Djinn (used memory, the kernel's and shared memory included, beyond the Djinn line) stayed under 70 % over 5 days of the Hourglass, 36 % at the median: 70 lowers only past what it saw, 60 holds the climb at its top.

View Source
var ErrNoCPULimit = errors.New("CPU limits per worker are off")

ErrNoCPULimit is why the CPU of a worker cannot be capped here: a note of ProbeScopes starts with it.

View Source
var ErrNoMemoryLimit = errors.New("memory limits per worker are off")

ErrNoMemoryLimit is why the memory of a worker cannot be capped here: a note of ProbeScopes starts with it.

View Source
var ErrNoScope = errors.New("no systemd scope per worker")

ErrNoScope is why workers do not run in a systemd scope of their own here: ProbeScopes wraps it, and Djinn runs them in their process group.

View Source
var HistoryRetention = store.Retention{Fine: 24 * time.Hour, Keep: 7 * 24 * time.Hour, Max: 400_000}

HistoryRetention is how long the series are kept in the store: the readings of every 5 s for a day, then the highest of each minute for a week; 400,000 samples at most (some 30 MB), the oldest going first.

ManualNotches is the ordered list of 5 manual operating load notches.

View Source
var NvidiaSMIArgs = []string{"--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"}

NvidiaSMIArgs are the arguments ReadGPUs expects nvidia-smi to run with.

View Source
var PSArgs = []string{"-A", "-o", "pid=,ppid=,pgid=,rss=,time="}

PSArgs are the arguments of ps that ParsePS reads: every process, its parent, its group, its resident memory in KiB and its CPU time.

View Source
var SeriesMinutes = []int32{10, 30, 60, 120, 6 * 60, 24 * 60, 7 * 24 * 60}

SeriesMinutes are the ranges a series may be asked for: 10 and 30 minutes, an hour (the Gates tab), 2 and 6 hours, a day, a week.

Functions

func Add

Add counts a run in what the command costs: the means move, the peak keeps the highest, wait and held times are tracked, percentiles computed, and recent runs recorded (up to 200).

func AgentPath added in v0.1.1

func AgentPath(goos, path, home, shell string) string

AgentPath is path, then the folders of shell (the login shell's PATH), then those of agentDirs that exist, each once: what is on path keeps its place and wins.

func AskLoginShell added in v0.1.1

func AskLoginShell() error

AskLoginShell asks the user's login shell for its PATH, which ExtendPath adds from then on. djinn up asks it once, when a launcher started it (a menu entry, the Dock, Finder): a graphical session gives its apps its own PATH, without what the user's shell profiles add (~/.zshrc's go/bin, nvm's node, an agent's own folder), so a watcher would not find gh, nor a lead go. A terminal reads those profiles, and a djinn up started from one has its PATH already. Nothing to ask on Windows, which passes the user's PATH to its apps.

func BaseSlots added in v0.1.1

func BaseSlots(s Snapshot) int

BaseSlots returns the number of slots given by the current machine rule without notch scaling.

func CgroupPIDs

func CgroupPIDs(dir string) ([]int, error)

CgroupPIDs lists the processes in the cgroup folder dir; an error when it does not exist (yet, or any more).

func CgroupRuns added in v0.4.0

func CgroupRuns(fsys fs.FS, dir, comm string) bool

CgroupRuns says whether a process of the cgroup v2 folder dir, in the file system fsys, runs the program comm (its /proc/<pid>/comm, the name the kernel keeps, cut at 15 bytes).

func CostsHandler

func CostsHandler(db *store.Store) (string, http.Handler)

CostsHandler returns the Connect handler of CommandService on the store, and its path prefix: what the commands of each project cost, as djinn gate run measures them.

func ExtendPath added in v0.1.1

func ExtendPath()

ExtendPath gives Djinn's own PATH the folders where the agents are, as they are now: AgentPath with the login shell's PATH (AskLoginShell), and the folders of the applications that ship an agent. Djinn calls it as djinn up starts and before it starts a worker or a lead, so that an agent installed while Djinn runs is found at once. It asks no shell: it only looks at folders.

func FindCommand added in v0.4.0

func FindCommand(root int, match string, skip func(pid int) bool) int

FindCommand finds the process that runs command among those root started, at any depth, leaving out each pid skip says: the shell an agent runs a command of its Bash in. It matches by the letters and digits of the command's first line (Match), which the shell's command line holds whatever the quoting; of a shell and the processes it started, the shell; of two shells, the one started last. 0 when none is found, or where the processes' command lines are not read (Windows).

func FreezeCgroup

func FreezeCgroup(dir string, frozen bool) error

FreezeCgroup freezes every process in the cgroup folder dir where it is, or thaws them: one write, which a process forking meanwhile does not escape. A frozen process still dies of SIGKILL.

func GroupPIDs added in v0.1.1

func GroupPIDs(procs []proc, pid int) []int

GroupPIDs returns the list of process IDs belonging to the process group pid or its descendants.

func Handler

func Handler(m *Monitor, running func() int, uses func() []*machinev1.WorkerUse, opts ...HandlerOption) (string, http.Handler)

Handler returns the Connect handler of MachineService on m, and its path prefix. running counts the workers that run now, uses lists what each one uses; nil counts and lists none.

func Head(key string) string

Head is what a key starts with, the program and its subcommand: go test, go tool task lint, npm run build, npx playwright test; python3 for an inline script (python3 - <<…). A command never measured is given the cost of the others of its head in its project (Peaks.Cost). "" when the key has no word, holds more than one command (gofmt -l . ; go build: its peak is the heavier one's, which no other command of its first word has), or starts with a light program (Light: sed -i, mv, cat): such a key neither lends its cost nor borrows one (W139).

func Key added in v0.4.0

func Key(command string, dirs ...string) string

A command's key is what its cost is kept and found under in its project: the same command run by another task, in another worktree or scratch folder, with other values in its environment, finds the cost measured before (G4 of L04). Key builds it from what a shell would run:

  • the folders that change with each task are named alike: the folder it runs in (dirs) becomes ".", a worktree of Djinn $WORKTREE, a scratch folder $DJINN_SCRATCH, a file under /tmp /tmp/*, any other UUID $ID;
  • a variable set for the command keeps its name, not its value (GOFLAGS=*);
  • sh -c '…' (bash, zsh, dash; -lc, -ec…) is the command it runs;
  • what only sets up the shell (cd, export, set, echo…), the wrappers that change nothing it costs (time, nohup, env, timeout 600, taskset -c 0-15…), the redirections and the filters a pipe ends with (| tail -50, | grep FAIL) are left out;
  • a here-document is a word of its command, << and a digest of its body (HereDocs), the folders named alike: the script python3 - <<'EOF' runs is its program, two scripts are two keys (W82); the commands after its body stay;
  • its words are one space apart, quoted where a shell would need it, up to KeyLength characters.

Arguments stay: go test ./... and go test ./internal/gate are two keys, the whole module and one package (W10). Key of a key is itself.

func KeyArgs added in v0.4.0

func KeyArgs(args []string, dirs ...string) string

KeyArgs is the key of the command args runs, a program and its arguments, as Key gives it: djinn gate run's.

func KillCgroup

func KillCgroup(dir string) error

KillCgroup kills every process in the cgroup folder dir, at once (cgroup.kill, since Linux 5.14).

func Light added in v0.5.0

func Light(program string) bool

Light says whether program, a command's first word past its folder, only reads or edits and runs nothing else: ls, cat, sed, mv, djinn… A command made of light ones only passes the gates with no admission (gate.Plain), and a command whose head is light lends its cost to none (Head). Anything else, a build, a test, a package manager, a script, an interpreter, a loop, is admitted.

func LoadHandler added in v0.1.1

func LoadHandler(
	home string,
	m *Monitor,
	setPolicy func(Policy),
	broadcast func(djinnv1.LoadNotch),
	workerMemory WorkerMemoryFunc,
	opts ...LoadOption,
) (string, http.Handler)

LoadHandler returns the Connect handler of LoadService and its path prefix.

func LookPath added in v0.1.1

func LookPath(name, path string) (string, error)

LookPath finds name in the folders of path, as exec.LookPath does for a worker: only absolute folders count.

func Match added in v0.4.0

func Match(command string) string

Match is what FindCommand finds a command by: the letters and digits of its first line, up to 120. A shell that runs the command holds them in its command line, in that order, however it quoted the rest.

func NotchIndex added in v0.1.1

func NotchIndex(n djinnv1.LoadNotch) int

NotchIndex returns the index of a notch among the manual notches (0 to 4), mapping LIGHT to MEDIUM (1).

func NotchName added in v0.1.1

func NotchName(notch djinnv1.LoadNotch) string

NotchName returns the lowercase name of a load notch.

func NotchTitle added in v0.1.1

func NotchTitle(notch djinnv1.LoadNotch) string

NotchTitle returns the title-case name of a notch (e.g. "Minimal", "Medium", "High", "Max", "Overclock", "Auto").

func ParseNotch added in v0.1.1

func ParseNotch(s string) (djinnv1.LoadNotch, error)

ParseNotch parses a string into a LoadNotch.

func Peak added in v0.5.0

func Peak(c *machinev1.CommandCost) uint64

Peak is the peak memory the gates hold the command c to: the 95th percentile of the peaks of its latest PeakRuns measured runs, a lone peak far above the others left out (withoutOutlier), so that a run measured wrong, a tree gone astray, stops counting once two other runs were measured, not after PeakRuns (W139, W197); its highest peak when it kept no run.

func Project added in v0.1.1

func Project(ctx context.Context, db *store.Store, taskID, dir string) (id, name string, err error)

Project gives the ID and name of the project the command ran in: the task's, or the one whose folder holds dir, the deepest first; "", "" outside any project.

func ReadAnon added in v0.4.0

func ReadAnon(fsys fs.FS, dir string) (uint64, error)

ReadAnon reads, from the cgroup v2 folder dir of the file system fsys, the anonymous memory its processes hold (memory.stat's anon, every cgroup under it counted): what they allocated, without the page cache they filled, which the kernel takes back by itself. It fails without the memory controller, or when dir does not exist.

func ReadBrake added in v0.4.0

func ReadBrake(home string) (percent int, ok bool)

ReadBrake reads the memory brake's threshold from settings.json in home (ui.v1.Settings.brake_memory_percent): ok false when the file does not say it, or says more than MostBrakeMemory.

func ReadHeavy added in v0.4.0

func ReadHeavy(home string) (memory uint64, cpu time.Duration)

ReadHeavy reads when a command is heavy from settings.json in home (ui.v1.Settings.heavy_command_memory_mib and heavy_command_cpu_seconds): past memory bytes of peak memory, or cpu of CPU time. Either is 0 when the file does not say: the gates keep their default.

func ReadIfritIdle added in v0.2.0

func ReadIfritIdle(home string) uint32

ReadIfritIdle reads the minutes without the developer before Djinn puts an ifrit out from settings.json in home (ui.v1.Settings.ifrit_idle_minutes). It returns 0 when the file does not say, or says a value out of 5 to 240.

func ReadLeadDriven added in v0.2.0

func ReadLeadDriven(home string) bool

ReadLeadDriven tells whether settings.json in home says that Djinn drives the lead (ui.v1.Settings.lead_driven, decision Q31, Q51): true unless the file says false.

func ReadNotch added in v0.1.1

func ReadNotch(home string) djinnv1.LoadNotch

ReadNotch reads the operating load notch from settings.json in home. It returns LOAD_NOTCH_MEDIUM if the file does not exist, cannot be read, or notch is unspecified. An old saved "light" maps to Medium.

func Reader

func Reader(dir string) func() (Snapshot, error)

Reader reads this machine for a monitor: Read, then the disk of dir at each reading, and the GPUs once. Reading the GPUs starts now, in the background: asking a driver may take a moment.

func SetWatchInterval added in v0.1.1

func SetWatchInterval(d time.Duration) func()

SetWatchInterval sets the minimum interval between Watch stream messages for tests.

func Summary added in v0.5.0

func Summary(costs []*machinev1.CommandCost) *machinev1.GatesSummary

Summary is what the recent runs of costs say of the gates: the requests, the waits, the highest peak and the waits for each gate in each project (its command's). A run counts under its gate, else its command's; one under none is left out. Its peak is one of costs itself, its runs kept: List sends it brief.

func WriteBrake added in v0.4.0

func WriteBrake(home string, percent int) error

WriteBrake writes the memory brake's threshold to settings.json in home, keeping the other settings.

func WriteNotch added in v0.1.1

func WriteNotch(home string, notch djinnv1.LoadNotch) error

WriteNotch writes the operating load notch to settings.json in home, preserving other settings.

Types

type AutoController added in v0.1.1

type AutoController struct {
	// contains filtered or unexported fields
}

AutoController manages the operating load notch in auto mode: between Minimal and the notch the developer chose, from the load of the programs outside Djinn alone. Djinn's own work, and the developer watching it, never lower it: the developer at the keyboard is no signal, they move the mouse precisely to watch Djinn (W253).

Once a beat (Tick, every AutoBeat) it reads the outside load's moving average over AutoSmooth. It lowers one notch when that average stayed above a high mark for AutoDownAfter, raises one when it stayed below every low mark for AutoUpAfter, and each step starts the wait again: never more than one step a beat nor a notch held less than AutoHold, a short spike moves nothing, and it comes back steadily. The wait goes on while the load stays within AutoHysteresis of the mark it passed, and the step comes once it is past the mark again: a load that hovers about a mark starts no wait again. Lowering lowers the CPU priority and starts no new worker, never pausing a running one (Decision Q124 (C)). The lead hears nothing of it: the bar shows why (Reason).

func NewAutoController added in v0.1.1

func NewAutoController(initial djinnv1.LoadNotch, opts ...AutoOption) *AutoController

NewAutoController creates an AutoController with the given initial notch and options.

func (*AutoController) Chosen added in v0.1.1

func (c *AutoController) Chosen() djinnv1.LoadNotch

Chosen returns the ceiling notch for auto mode.

func (*AutoController) Effective added in v0.1.1

func (c *AutoController) Effective() djinnv1.LoadNotch

Effective returns the operating load notch currently in effect.

func (*AutoController) IsAuto added in v0.1.1

func (c *AutoController) IsAuto() bool

IsAuto reports whether auto mode is active.

func (*AutoController) Reason added in v0.2.0

func (c *AutoController) Reason() *djinnv1.LoadAutoReason

Reason says why auto mode runs at its notch, for the bar; nil outside auto mode.

func (*AutoController) SetNotch added in v0.1.1

func (c *AutoController) SetNotch(notch djinnv1.LoadNotch) (effective djinnv1.LoadNotch, changed bool)

SetNotch updates the notch setting. If notch is LOAD_NOTCH_AUTO, auto mode is enabled, from the notch in effect held between Minimal and the chosen one, the next beat deciding; a manual notch (Minimal to Overclock) disables it and becomes the chosen one.

func (*AutoController) Tick added in v0.1.1

func (c *AutoController) Tick() (bool, djinnv1.LoadNotch)

Tick is one beat: it reads the outside load, and in auto mode steps the notch one way if that load stayed past a mark long enough. The beat reads even outside auto mode, so that switching to it starts from what was measured.

type AutoMarks added in v0.2.0

type AutoMarks struct {
	CPUHigh, CPULow       float64
	MemoryHigh, MemoryLow float64
}

AutoMarks are the outside loads, in percent of the machine, that auto mode steps at: above a high mark it lowers, below every low mark it raises, in between it holds.

type AutoOption added in v0.1.1

type AutoOption func(*AutoController)

AutoOption configures an AutoController.

func WithAutoChosen added in v0.1.1

func WithAutoChosen(notch djinnv1.LoadNotch) AutoOption

WithAutoChosen sets the ceiling notch for auto mode.

func WithAutoClock added in v0.1.1

func WithAutoClock(clock func() time.Time) AutoOption

WithAutoClock sets the clock function (used for testing with a fake clock).

func WithAutoMarks added in v0.2.0

func WithAutoMarks(marks AutoMarks) AutoOption

WithAutoMarks sets the marks auto mode steps at.

func WithAutoOnChange added in v0.1.1

func WithAutoOnChange(onChange func(djinnv1.LoadNotch)) AutoOption

WithAutoOnChange sets a callback invoked whenever the effective notch changes.

func WithAutoOutside added in v0.2.0

func WithAutoOutside(source OutsideSource) AutoOption

WithAutoOutside sets what reads the load outside Djinn; without it, auto mode holds its notch.

type BrakeSetting added in v0.4.0

type BrakeSetting struct {
	// Percent is the threshold in effect as djinn up starts; 0: no brake.
	Percent int
	// Fixed: djinn up --brake-memory, or DJINN_BRAKE_MEMORY, set it for this run; SetBrake is refused.
	Fixed bool
	// Apply gives the brake a new threshold at once (harness.Harness.SetBrake); nil: it waits for the next djinn up.
	Apply func(percent int)
}

BrakeSetting is the memory brake's threshold as LoadService shows and changes it (WithLoadBrake).

type Cost added in v0.4.0

type Cost struct {
	Peak uint64
	CPU  time.Duration
	Held time.Duration
	Head string
}

Cost is what a command was measured to cost: its peak memory, in bytes (Peak), and its CPU time, user and system, the higher of its mean and its last run's; how long it usually holds its gate, the 95th percentile of its last runs. A command never measured is given the cost of the others of its head in its project (Head), their median: Head then names it, and Held is zero.

type Disk

type Disk struct {
	Path             string
	Total, Available uint64 // bytes; Available is what Djinn may use
}

Disk is the space of the file system that holds a folder.

func ReadDisk

func ReadDisk(dir string) (*Disk, error)

ReadDisk reads the space of the file system that holds dir, through statfs.

type GPU

type GPU struct {
	Vendor        string // nvidia, amd, intel, apple, or the PCI vendor identifier of another
	Name          string // as its driver gives it; its PCI identifiers when none does
	Driver        string // nvidia, nouveau, amdgpu, i915, xe; metal on Apple Silicon; "" when none is bound
	DriverVersion string // "" when unknown
	Memory        uint64 // bytes of its own; with unified memory, the machine's; 0 when unknown
	Unified       bool   // it shares the machine's memory (Apple Silicon)
}

GPU is a graphics processor of the machine.

func AppleGPU

func AppleGPU(chip string, memory uint64) GPU

AppleGPU is the GPU of an Apple Silicon chip: its name is the chip's (machdep.cpu.brand_string), and it shares the machine's memory, through Metal.

func ReadGPUs

func ReadGPUs(fsys fs.FS, nvidiaSMI func() ([]byte, error)) []GPU

ReadGPUs reads the GPUs of a Linux machine from its /sys, fsys being the root of the file system: one per DRM card on the PCI bus, with its driver, the driver's version, and the memory of its own when the driver gives it (amdgpu). nvidiaSMI, called only when a card is NVIDIA's or when /sys shows none (WSL), runs nvidia-smi; what it gives replaces the NVIDIA cards of /sys. A /sys that cannot be read gives no GPU.

type Group

type Group struct {
	// Processes running.
	Processes int
	// CPU time, user and system, of the processes running and of the children they waited for.
	CPU time.Duration
	// Resident memory, summed over the processes: a page they share counts once per process; on macOS each one's
	// footprint, its compressed memory in, what it shares out (Footprint). Read from a cgroup, what the kernel
	// charges it (ReadCgroup).
	Memory uint64
	// Peak is the most memory the worker's cgroup held since it started; 0 without a cgroup.
	Peak uint64
}

Group is what a worker uses at one time: its process group, and every process it started, even one that left the group (a tool an agent starts in a session of its own).

func ParsePS

func ParsePS(out []byte, pid int) (Group, error)

ParsePS reads, from the output of ps with PSArgs, what the worker whose process leads group pid uses.

func ReadCgroup

func ReadCgroup(fsys fs.FS, dir string) (Group, error)

ReadCgroup reads, from a cgroup v2 folder dir (Scope.Cgroup) of the file system fsys, what the processes in it use: cgroup.procs, cpu.stat (usage_usec, every process the cgroup held, ended ones too), memory.current (what the kernel charges the cgroup: resident memory and the page cache it filled) and memory.peak (since Linux 5.19; 0 before). Without the memory controller, it fails: memory.current does not exist.

func ReadGroup

func ReadGroup(fsys fs.FS, pid int) (Group, error)

ReadGroup reads, from a Linux /proc, what the worker whose process leads group pid uses; fsys is the root of the file system. No process left: a zero Group.

func ReadSelf added in v0.1.1

func ReadSelf() (Group, error)

ReadSelf reads what Djinn's own process uses, without any process it started (its window, leads, workers, gate holders): its CPU time, from getrusage, and its resident memory.

func ReadSlice added in v0.4.0

func ReadSlice(fsys fs.FS, dir string) (Group, error)

ReadSlice reads, from the cgroup v2 folder dir of the file system fsys, what the containers of a task's slice use: its memory.current, its memory.peak and its cpu.stat count every container under it, and its processes are those of the containers' scopes. It fails when the slice does not exist: the task runs no container.

func ReadWorker

func ReadWorker(pid int, cgroup string) (Group, error)

ReadWorker reads what the worker whose process leads group pid uses: from its cgroup when it runs in one (Scope.Cgroup, ReadCgroup), else from its processes, listed at most once a second for every worker. Where workers are not measured (NotMeasured), it fails. A worker not listed yet, or listed at its exec, before it touched a page, reads as a zero Group: no reading.

type HandlerOption added in v0.1.1

type HandlerOption func(*service)

HandlerOption configures the machine service handler.

func WithDiskFolders added in v0.2.0

func WithDiskFolders(fn func() []*machinev1.DiskFolder) HandlerOption

WithDiskFolders sets the function returning the main folders on disk, biggest first, with their size.

func WithDiskFreeing added in v0.5.0

func WithDiskFreeing(fn func() *machinev1.DiskFreeing) HandlerOption

WithDiskFreeing sets the function telling how far the last pass freeing finished tasks' folders is (the harness's Freeing).

func WithDiskItems added in v0.2.0

func WithDiskItems(fn func() []*machinev1.DiskItem) HandlerOption

WithDiskItems sets the function returning the known caches and stores on the machine, biggest first.

func WithDiskMeasure added in v0.5.0

func WithDiskMeasure(state func() (time.Time, bool), measure func() bool) HandlerOption

WithDiskMeasure sets the functions telling when the disk was last measured whole and whether a measure is going (the harness's DiskState), and measuring it again now (its MeasureDisk).

func WithHistory added in v0.1.1

func WithHistory(h *History) HandlerOption

WithHistory reads the series from the store's history, which outlives a restart, rather than from memory.

func WithNetwork added in v0.2.0

func WithNetwork(fn func() *timestamppb.Timestamp) HandlerOption

WithNetwork sets the function telling since when the network is down (the harness's NetworkDownSince); nil while it is up.

func WithSeriesIntervals added in v0.1.1

func WithSeriesIntervals(fn func(cutoff time.Time, all bool) []*machinev1.GateInterval) HandlerOption

WithSeriesIntervals sets the function returning the gate intervals released after cutoff, then those held now: every admission when all is true (gate.Gates.Intervals, kept in the store for three months).

func WithSeriesRecorder added in v0.1.1

func WithSeriesRecorder(rec *SeriesRecorder) HandlerOption

WithSeriesRecorder sets the machine series recorder.

func WithSeriesWorkers added in v0.1.1

func WithSeriesWorkers(fn func(cutoff time.Time, gateIntervals []*machinev1.GateInterval) []*machinev1.WorkerSeries) HandlerOption

WithSeriesWorkers sets the function returning series of running workers.

type HereDoc added in v0.5.0

type HereDoc struct {
	Body   string
	Quoted bool
}

HereDoc is a here-document's body, as its command reads it, and whether its delimiter was quoted: the shell then expands nothing in it, no variable, no substitution.

func HereDocs added in v0.5.0

func HereDocs(command string) (code string, docs []HereDoc)

HereDocs is command without the bodies of its here-documents (<<EOF, <<-'EOF'), and the bodies, in the order of their operators. The operators and their delimiters stay in code; each body, from the line after its operator's to its delimiter's line, goes with that line. A body with no delimiter runs to the end.

type History added in v0.1.1

type History struct {
	// contains filtered or unexported fields
}

History keeps the series of the machine and of each worker in the store, so that they outlive a restart of Djinn: the readings wait in memory, then Flush writes them, every 30 s in djinn up; reading merges both.

func NewHistory added in v0.1.1

func NewHistory(db *store.Store) *History

NewHistory keeps the series in db.

func (*History) Flush added in v0.1.1

func (h *History) Flush(ctx context.Context)

Flush writes the readings waiting, and rolls up and prunes the store's samples every 10 minutes (HistoryRetention). Readings it could not write wait for the next flush, up to an hour of them.

func (*History) LastMachine added in v0.4.0

func (h *History) LastMachine(ctx context.Context) (store.Sample, bool, error)

LastMachine is the machine's latest reading kept in the store: the Hourglass's last of the djinn up before this one, read before this one samples. False when none is kept.

func (*History) Machine added in v0.1.1

func (h *History) Machine(p *machinev1.MachinePoint)

Machine records a reading of the machine.

func (*History) MachinePoints added in v0.1.1

func (h *History) MachinePoints(ctx context.Context, from, to time.Time) []*machinev1.MachinePoint

MachinePoints is the machine's series after from, until to.

func (*History) Worker added in v0.1.1

func (h *History) Worker(taskID string, p *machinev1.WorkerPoint)

Worker records a reading of the worker of a task.

func (*History) WorkerPoints added in v0.1.1

func (h *History) WorkerPoints(ctx context.Context, taskID string, from, to time.Time) []*machinev1.WorkerPoint

WorkerPoints is the series of a task's worker after from, until to.

type Intervals added in v0.4.0

type Intervals struct {
	// contains filtered or unexported fields
}

Intervals keeps the gate intervals in the store, where they outlive a restart (G10 of L04), for IntervalRetention.

func NewIntervals added in v0.4.0

func NewIntervals(db *store.Store) *Intervals

NewIntervals keeps the gate intervals in db.

func (*Intervals) Add added in v0.4.0

func (l *Intervals) Add(ctx context.Context, iv *machinev1.GateInterval)

Add keeps a gate interval released; one released over IntervalRetention ago goes, every 10 minutes. A failure is logged: the gates go on.

func (*Intervals) Since added in v0.4.0

func (l *Intervals) Since(ctx context.Context, cutoff time.Time) []*machinev1.GateInterval

Since gives the gate intervals released after cutoff, the first released first; none when the store fails.

type LoadOption added in v0.1.1

type LoadOption func(*loadService)

LoadOption configures loadService.

func WithLoadAutoController added in v0.1.1

func WithLoadAutoController(ac *AutoController) LoadOption

WithLoadAutoController sets a custom AutoController on the load service.

func WithLoadBrake added in v0.4.0

func WithLoadBrake(b BrakeSetting) LoadOption

WithLoadBrake has LoadService show the memory brake's threshold and change it (LoadService.SetBrake). Without it, it shows what settings.json says, else DefaultBrakeMemory, and a change waits for the next djinn up.

func WithLoadClock added in v0.1.1

func WithLoadClock(clock func() time.Time) LoadOption

WithLoadClock sets the clock function used for auto mode.

func WithLoadForcedWorkers added in v0.1.2

func WithLoadForcedWorkers(forced func() int) LoadOption

WithLoadForcedWorkers sets a function returning how many running workers were started or resumed by hand.

func WithLoadLowerPauses added in v0.1.2

func WithLoadLowerPauses(pauses func() bool) LoadOption

WithLoadLowerPauses sets a function telling whether lowering the notch pauses the workers above it.

func WithLoadOutside added in v0.2.0

func WithLoadOutside(source OutsideSource) LoadOption

WithLoadOutside sets what reads the load outside Djinn for auto mode (SeriesRecorder.Outside); without it, auto mode holds its notch.

func WithLoadPausedWorkers added in v0.1.1

func WithLoadPausedWorkers(paused func() int) LoadOption

WithLoadPausedWorkers sets a function returning the count of currently paused workers.

func WithLoadRunningWorkers added in v0.1.1

func WithLoadRunningWorkers(running func() int) LoadOption

WithLoadRunningWorkers sets a function returning the count of currently running workers.

func WithLoadStreamer added in v0.1.1

func WithLoadStreamer(attach func(func(ctx context.Context, send func(*djinnv1.LoadServiceWatchResponse) error) error)) LoadOption

WithLoadStreamer provides a function that can be called to stream load changes.

func WithLoadTickInterval added in v0.1.1

func WithLoadTickInterval(d time.Duration) LoadOption

WithLoadTickInterval sets the auto mode's beat (<= 0 disables the background beat); AutoBeat by default.

func WithLoadWorkerForecast added in v0.1.1

func WithLoadWorkerForecast(forecast func() uint64) LoadOption

WithLoadWorkerForecast sets a function returning the measured forecast per worker in bytes.

type Monitor

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor reads the machine at most once a second, for the scheduler and the gates.

func NewMonitor

func NewMonitor(p Policy, read func() (Snapshot, error)) *Monitor

NewMonitor is a monitor of this machine with the policy p. read, when not nil, replaces reading the machine: the tests simulate it.

func (*Monitor) Available

func (m *Monitor) Available() uint64

Available is the memory available to new programs now that holds a worker back (Policy.WorkerRoom), in bytes; 0 when unknown, and on macOS (Snapshot.ByPressure), where the pressure level holds the workers instead.

func (*Monitor) BarSlots added in v0.1.2

func (m *Monitor) BarSlots(n djinnv1.LoadNotch) int

BarSlots is the most workers the notch n itself lets run now (Policy.BarSlots), djinn up --workers holding.

func (*Monitor) Capacity

func (m *Monitor) Capacity() (slots int, rule, pressure string)

Capacity is the most workers the machine runs at once and its rule, a worker forecast at its measured peak (SetWorkerPeak), and why it is under pressure ("" when it is not).

func (*Monitor) NotchSlots added in v0.1.2

func (m *Monitor) NotchSlots() []NotchSlots

NotchSlots is the most workers each manual notch lets run now, as the scheduler weighs them (Capacity): the load bar shows these, so that what it says a notch runs is what the scheduler lets run there (W577). djinn up --workers holds for every notch.

func (*Monitor) Policy

func (m *Monitor) Policy() Policy

Policy is the monitor's policy.

func (*Monitor) Pressure

func (m *Monitor) Pressure() string

Pressure says why the machine is under pressure now, or "".

func (*Monitor) SetPolicy added in v0.1.1

func (m *Monitor) SetPolicy(p Policy)

SetPolicy sets the monitor's policy.

func (*Monitor) SetWorkerMemory added in v0.1.1

func (m *Monitor) SetWorkerMemory(resident func() uint64)

SetWorkerMemory gives the resident memory of Djinn's running workers, in bytes, which each snapshot carries (Snapshot.WorkersResident): djinn up gives the harness's (harness.Harness.Resident). It must not call the monitor.

func (*Monitor) SetWorkerPeak added in v0.4.0

func (m *Monitor) SetWorkerPeak(peak func() uint64)

SetWorkerPeak gives the typical measured peak memory of a worker, in bytes, 0 while none is measured: djinn up gives the harness's (harness.Harness.WorkerPeak). The slots weigh it in place of the notch's WorkerPeak, so that the scheduler, the load bar and djinn load get forecast a worker as its measures do. It must not call the monitor.

func (*Monitor) Snapshot

func (m *Monitor) Snapshot() Snapshot

Snapshot is the machine, read at most a second ago, with the resident memory of Djinn's running workers read now. A reading that fails keeps what is known: the cores.

func (*Monitor) Total added in v0.1.1

func (m *Monitor) Total() uint64

Total is the total memory of the machine in bytes; 0 when unknown.

type NotchSlots added in v0.1.2

type NotchSlots struct {
	Notch djinnv1.LoadNotch
	Slots int
}

NotchSlots is the most workers a notch lets run on the machine as it is now.

type Outside added in v0.2.0

type Outside struct {
	CPU, Memory float64
	// Whether each is measured: the machine's CPU is read on Linux, Djinn's memory on Linux and macOS.
	CPUKnown, MemoryKnown bool
}

Outside is the machine's load outside Djinn: its CPU and memory beyond Djinn's own tree (the Hourglass's Djinn line: djinn up, its window, its workers and all they started), in percent of the machine.

type OutsideSource added in v0.2.0

type OutsideSource func(since time.Time) (Outside, bool)

OutsideSource reads the load outside Djinn measured after since, averaged (SeriesRecorder.Outside); false when nothing was measured since.

type Peaks

type Peaks struct {
	// contains filtered or unexported fields
}

Peaks reads what each command was measured to cost, for the gates.

func NewPeaks

func NewPeaks(db *store.Store) *Peaks

NewPeaks reads the costs in the store.

func (*Peaks) Ask added in v0.1.1

func (p *Peaks) Ask(ctx context.Context, gate, taskID, dir, command string)

Ask counts a run asked of the command in its project: the task's, else the one holding dir; the hold of gate asked is journaled. Nothing is counted outside any project, nor when the store fails: the gate is granted all the same.

func (*Peaks) Cost added in v0.4.0

func (p *Peaks) Cost(ctx context.Context, taskID, dir, command string) Cost

Cost is what the command was measured to cost in its project: the task's, else the one holding dir, found by its key (Key); never measured, what the others of its head cost. It is zero when neither was measured, or outside any project.

func (*Peaks) Record added in v0.4.0

Record counts a run of a command that Djinn measured itself, as djinn gate run would send it: a worker's command admitted by the gates (djinn gate hook). Nothing is counted outside any project; a failure is logged.

type Policy

type Policy struct {
	// Notch is the operating load slider notch that controls how much of the machine Djinn uses.
	Notch djinnv1.LoadNotch
	// Workers, when above 0, is the number of workers, whatever the machine (djinn up --workers).
	Workers int
	// One worker per CoresPerWorker cores, and per MemoryPerWorker bytes beyond MemoryReserve; the smaller wins,
	// between 1 and MaxWorkers.
	CoresPerWorker  int
	MemoryPerWorker uint64
	MemoryReserve   uint64
	MaxWorkers      int
	// WorkerMemory, when above 0, is the most memory a worker may hold, in bytes, where it runs in a systemd scope
	// of its own (Scopes, djinn up --worker-memory): past it, the kernel reclaims, then kills a process of the worker.
	// 0, the default: no ceiling. An expert setting, never tied to operating load notches.
	WorkerMemory uint64
	// WorkerMemoryGuard, when above 0, is an optional guardrail factor (typically 2 to 3) applied to the provider's
	// observed typical peak (median of latest WorkerPeaks finished workers) to set a dynamic MemoryMax ceiling for
	// each worker, at least its forecast (peak + WorkerMargin). 0, the default: disabled.
	// Without measurements (measured == 0), no ceiling is set. Never tied to operating load notches.
	WorkerMemoryGuard float64
	// The machine is under pressure when, over the last 10 seconds, tasks waited for the CPU at least CPUPressure
	// percent of the time, or for memory at least MemoryPressure percent (PSI "some").
	CPUPressure    float64
	MemoryPressure float64
	// Without PSI: when the load average per core reaches LoadPerCore, or the memory available falls below
	// MemoryFree of the total. On macOS, for now, neither: Djinn delegates to the system, and only its critical memory
	// pressure level holds a worker or a gate (pressure, Q103 B). MemoryLevel, the level that holds where a system
	// reports one but delegation does not apply: 0 means critical.
	LoadPerCore float64
	MemoryFree  float64
	MemoryLevel int
	// A gate goes to a command measured in its project only when the memory available, less the peaks of the
	// commands holding a gate, holds its peak plus CommandMargin (Room); a command never measured goes as it comes.
	// Djinn's recommendation: the developer may change it.
	CommandMargin uint64
	// Another worker starts only when the memory available, less what the workers running may still take, holds the
	// typical peak of a worker of its provider plus WorkerMargin. The typical peak is the median of the peaks of the
	// latest WorkerPeaks finished workers of that provider; WorkerPeak while none is measured. A running worker may
	// still take the typical peak of its provider less what it uses now; one not read yet, all of it.
	WorkerPeak   uint64
	WorkerPeaks  int
	WorkerMargin uint64
	// Percentile is the percentile of a worker's memory series it is engaged at (95, 80, 70, 60 or 50): a running
	// worker at that percentile of its own readings, a new one at the median of the latest WorkerPeaks finished
	// workers' value at it. The higher the notch, the lower: builds and tests spike a worker's memory, and the gates
	// already serialize them. 0 is 95.
	Percentile int
	// Share is the fraction of machine capacity this policy grants (0.20 to 1.50).
	Share float64
	// MemoryShare is the maximum fraction of total RAM Djinn may commit in peak forecasts (0.20 to 1.50).
	// On max (1.0), all RAM except WorkerMargin may be committed; overclock (1.50) may exceed what the rule engages.
	MemoryShare float64
	// Auto is whether the operating load is currently managed by auto mode.
	Auto bool
	// A local model runs on an NVIDIA or AMD GPU, its driver loaded, with ModelGPUMemory of its own; on Apple
	// Silicon with ModelMemory of unified memory; else on the CPU, slowly, with ModelMemory. Its weights need
	// ModelDisk free on the disk of the data folder.
	ModelGPUMemory uint64
	ModelMemory    uint64
	ModelDisk      uint64
}

Policy turns a snapshot into a number of workers and a pressure verdict. Every threshold is a field: the defaults are DefaultPolicy.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy is the policy Djinn runs with: medium operating load. A worker is mostly an agent waiting for its model; the heavy commands it runs (builds, tests, code generation) go through gates. Two cores and 2 GiB a worker leaves room for them.

func NotchPolicy added in v0.1.1

func NotchPolicy(notch djinnv1.LoadNotch) Policy

NotchPolicy returns the policy of the operating load notch. Medium is the default policy Djinn runs with.

func (Policy) AvailableMemory added in v0.1.1

func (p Policy) AvailableMemory(s Snapshot) uint64

AvailableMemory returns the memory available to new programs: s.MemoryAvailable, or s.MemoryTotal when available is unknown.

func (Policy) BarSlots added in v0.1.2

func (p Policy) BarSlots(s Snapshot) int

BarSlots is the most workers the notch itself lets run, before the memory's share of Slots: its share of the CPU rule's slots, at least 1; djinn up --workers when set. It changes only with the notch: lowering the notch pauses the workers above it, never a dip of the memory available, which pausing would not free.

func (Policy) BaseSlots added in v0.1.1

func (p Policy) BaseSlots(s Snapshot, peaks ...uint64) (int, string)

BaseSlots is the number of worker slots the machine allows today under the standard rule: min of what CPU allows and what memory allows, up to 16, at least 1.

func (Policy) BindingResource added in v0.1.1

func (p Policy) BindingResource(s Snapshot, peaks ...uint64) string

BindingResource reports which resource limits worker capacity: "memory" or "cpu".

func (Policy) CPUSlots added in v0.1.1

func (p Policy) CPUSlots(s Snapshot) int

CPUSlots returns the worker slots allowed by the CPU rule before notch scaling: one worker per 2 cores, at least 1, up to MaxWorkers.

func (Policy) CommitMemory added in v0.1.1

func (p Policy) CommitMemory(s Snapshot) uint64

CommitMemory returns the memory Djinn could use with no worker running: the memory available plus what its running workers hold (s.WorkersResident), which the memory available already leaves out; at most the total. Counting the workers' own memory both out of what is available and into what they engage would count it twice.

func (Policy) CommittableLimit added in v0.1.1

func (p Policy) CommittableLimit(available uint64) uint64

CommittableLimit is the maximum memory Djinn commits to peak forecasts, available being the memory Djinn could use with no worker running (CommitMemory: free + reclaimable + its running workers' own). Djinn's engaged memory never exceeds the notch's share of it beyond the reserve, with Overclock included only up to the reserve (at most available). It returns 0 when available is 0 or unknown.

func (Policy) EngagedAt added in v0.1.1

func (p Policy) EngagedAt() string

EngagedAt says at which percentile of its memory a worker is engaged, and why: "engaged at p50 (overclock)".

func (Policy) GatePressure added in v0.5.0

func (p Policy) GatePressure(s Snapshot) string

GatePressure says why the machine is under pressure for the gates, or "" when it is not: Pressure, but macOS's level holds a gate at critical only, whatever the notch. At warning, only a heavy command waits, and for MemoryWait at most (Warned): warning is frequent and passing on a busy Mac, and a gate waiting on it without end held the work.

func (Policy) LocalModel

func (p Policy) LocalModel(s Snapshot) (bool, string)

LocalModel says whether a local open-weight model can run on the machine, and why: dispatch asks one only where it can (T07). The first usable GPU decides; without one, the memory.

func (Policy) MemoryPercentile added in v0.1.1

func (p Policy) MemoryPercentile() int

MemoryPercentile is the percentile a worker is engaged at (Percentile): 95 when unset.

func (Policy) MemorySlots added in v0.1.1

func (p Policy) MemorySlots(s Snapshot, peaks ...uint64) int

MemorySlots returns the worker slots allowed by memory at 100% (usable memory / worker forecast) before notch scaling: usable memory is available plus the running workers' own, minus reserve (UsableMemory); forecast is measured peak per worker or default; at least 1, up to MaxWorkers. A machine whose memory is unknown, or judged by its pressure level (ByPressure), returns MaxWorkers.

func (Policy) NotchName added in v0.1.1

func (p Policy) NotchName() string

NotchName is the name of the policy's load notch.

func (Policy) NotchTitle added in v0.1.1

func (p Policy) NotchTitle() string

NotchTitle returns the title-case name of the policy's load notch.

func (Policy) Pressure

func (p Policy) Pressure(s Snapshot) string

Pressure says why the machine is under pressure, or "" when it is not. Under pressure, no worker starts and no gate is granted; what runs goes on.

func (Policy) Room

func (p Policy) Room(s Snapshot, command string, peak, held uint64) string

Room says why the machine cannot hold the command yet, its measured peak memory being peak, or "" when it can: the memory available, less held (the peaks of the commands holding a gate, which may not have reached them yet), holds the peak plus CommandMargin, the peak counted at CommandPeakShare of the memory at most. A command never measured (peak 0), a machine whose memory is unknown, or a command that nothing measured holds a gate beside (held 0) has room: alone, waiting frees nothing for it (W139). On macOS (ByPressure), the memory available never holds a command: the pressure level does (GatePressure, Warned).

func (Policy) RuleMemory added in v0.1.1

func (p Policy) RuleMemory(total uint64) uint64

RuleMemory returns the memory the rule would engage on a machine with total RAM.

func (Policy) Slots

func (p Policy) Slots(s Snapshot, peaks ...uint64) (int, string)

Slots is the most workers the machine runs at once, and the rule that gave it. Workers allowed = the notch's share of min(what the CPU rule allows, what the memory allows), where memory allows (memory Djinn may engage at that notch) / (the measured peak forecast per worker); the memory Djinn may engage counts its running workers' own back in (CommitMemory), so a worker's memory does not take a slot from the others. On macOS (ByPressure), the memory rule drops: the notch's share of the CPU rule counts the workers, and the pressure level holds new ones (Pressure).

func (Policy) Typical

func (p Policy) Typical(peaks []uint64) (uint64, int)

Typical is the typical peak memory of a worker, and how many measured peaks gave it: the median of the first WorkerPeaks of peaks, the latest first; WorkerPeak and 0 when none is measured. With an even count, the mean of the two in the middle.

func (Policy) UsableMemory added in v0.1.1

func (p Policy) UsableMemory(s Snapshot) uint64

UsableMemory returns the memory Djinn could use beyond the reserve, its running workers' included: max(0, CommitMemory - MemoryReserve).

func (Policy) Warned added in v0.5.0

func (p Policy) Warned(s Snapshot, command string, held uint64) string

Warned says why a heavy command waits for its gate while macOS reports memory pressure, warning or worse (MemoryLevel), or "" when it need not: what Room reads, Activity Monitor's Memory Used left out, does not see the compressor fill, and warning is the kernel's word that it does (Q86 A). Like Room, a command no measured command holds a gate beside (held 0) goes: waiting frees nothing of Djinn's for it. The gates bound this wait as Room's. Linux has no level (0): never.

func (Policy) WorkerForecast added in v0.1.1

func (p Policy) WorkerForecast(peaks ...uint64) uint64

WorkerForecast returns the forecast peak memory per worker (typical peak plus WorkerMargin). Without measurements, it returns WorkerPeak + WorkerMargin (1.5 GiB by default).

func (Policy) WorkerMemoryCeiling added in v0.1.1

func (p Policy) WorkerMemoryCeiling(peak uint64, measured int) uint64

WorkerMemoryCeiling returns the memory ceiling in bytes for a worker of a provider, evaluating the guardrail (if WorkerMemoryGuard > 0) against the hard ceiling WorkerMemory. Returns 0 when no ceiling applies.

func (Policy) WorkerMemoryMax added in v0.1.1

func (p Policy) WorkerMemoryMax(factor float64, peak uint64, measured int) uint64

WorkerMemoryMax calculates the dynamic memory ceiling (MemoryMax in bytes) for a worker of a provider with observed peak and measured count, using the guardrail factor. When factor <= 0 or measured == 0, the guardrail sets no ceiling (returns 0). When measured > 0, it returns at least the current forecast (peak + WorkerMargin), and factor * peak if larger.

func (Policy) WorkerRoom

func (p Policy) WorkerRoom(total, available, resident, held, engaged uint64, provider string, peak uint64, measured int) string

WorkerRoom says why the machine cannot hold another worker of provider yet, or "" when it can. Two checks:

  • engaged (what the workers running are engaged at, their resident memory included) plus the new worker's forecast stays within CommittableLimit of the memory Djinn could use with no worker running: available plus resident, the running workers' resident memory, which available already leaves out;
  • the memory available, less held (what the workers running may still take beyond what they hold), holds peak, the typical memory of a worker of provider measured over measured workers (Typical), plus WorkerMargin.

A machine whose memory is unknown (available 0) has room.

type Pressure

type Pressure struct {
	Some float64 // at least one task waited
	Full float64 // every task waited
}

Pressure is how much of the last 10 seconds tasks waited for a resource, in percent: Linux's pressure stall information.

type Scope

type Scope struct {
	// Unit names it: djinn-<task code>-<uuid8>.scope.
	Unit string
	// Prefix runs a command in it, the command appended. The scope keeps the process: same PID, same process group,
	// same streams.
	Prefix []string
	// Cgroup is its folder, under /sys/fs/cgroup; it exists from the time systemd-run makes the scope until its last
	// process ends. Empty when unknown.
	Cgroup string
}

Scope is the scope of one process a worker starts: its unit, the command it runs under, its cgroup.

type Scopes

type Scopes struct {
	// CPU caps each worker at this percent of one core (CPUQuota, djinn up --worker-cpu); 0: uncapped.
	CPU int
	// Memory caps each worker's memory at this many bytes (MemoryMax, Policy.WorkerMemory); 0: no ceiling.
	Memory uint64
	// Tasks caps each worker's processes and threads (TasksMax, WorkerTasks), whatever they run: it stops a fork bomb
	// and nothing else. 0: uncapped, where systemd does not give the user the pids controller.
	Tasks uint64
	// MemoryController is true when systemd gives the memory controller to the user's scopes.
	MemoryController bool
	// contains filtered or unexported fields
}

Scopes start each worker in a systemd user scope of its own, without root: a cgroup that holds every process the worker starts, even one that leaves its process group, so that stopping, pausing and measuring it take the whole tree. ProbeScopes makes them.

func ProbeScopes

func ProbeScopes(ctx context.Context, cpu int, memory uint64) (*Scopes, []string, error)

ProbeScopes returns the scopes that run each worker in a systemd user scope of its own, its CPU capped at cpu percent of one core (150 is a core and a half) and its memory at memory bytes, 0 capping nothing. It starts one such scope first and reads its cgroup. An error wrapping ErrNoScope says why there is none: Djinn runs workers as they are. A cap that would not hold is set to 0, and a note says why.

func (*Scopes) New

func (s *Scopes) New(name string) Scope

New is the scope of a process of the worker name (a task's code): a unit of its own each time, since systemd keeps the name of an ended scope a little while.

func (*Scopes) NewWithMemory added in v0.1.1

func (s *Scopes) NewWithMemory(name string, memory uint64) Scope

NewWithMemory is the scope of a process of the worker name with an explicit memory ceiling in bytes (0: no ceiling).

func (*Scopes) Plain added in v0.2.0

func (s *Scopes) Plain(name string) Scope

Plain is the scope of a command Djinn runs itself (a push check, under its gate), name its gate: djinn-gate-<name>, with no cap, so that the Djinn line counts all it uses, the processes that end first too.

func (*Scopes) Slice added in v0.2.0

func (s *Scopes) Slice() string

Slice is the cgroup folder that holds the scopes, under /sys/fs/cgroup; "" when unknown.

type SeriesRecorder added in v0.1.1

type SeriesRecorder struct {
	// contains filtered or unexported fields
}

SeriesRecorder records machine and Djinn process consumption samples over time.

func NewSeriesRecorder added in v0.1.1

func NewSeriesRecorder(m *Monitor, readWorker func(pid int, cgroup string) (Group, error)) *SeriesRecorder

NewSeriesRecorder returns a recorder for machine metrics.

func (*SeriesRecorder) AddPoint added in v0.1.1

func (r *SeriesRecorder) AddPoint(p *machinev1.MachinePoint)

AddPoint appends a pre-built machine point (used in tests).

func (*SeriesRecorder) Keep added in v0.1.1

func (r *SeriesRecorder) Keep(h *History)

Keep keeps each sample in h too, the store's series that outlive a restart.

func (*SeriesRecorder) Outside added in v0.2.0

func (r *SeriesRecorder) Outside(since time.Time) (Outside, bool)

Outside is the load outside Djinn over the points measured after since: the machine's CPU and memory beyond the Djinn line, averaged; false when no point came since. It reads what the samples hold, nothing of the machine: the auto mode's beat costs a walk of the last points.

func (*SeriesRecorder) Points added in v0.1.1

func (r *SeriesRecorder) Points(cutoff time.Time) []*machinev1.MachinePoint

Points returns all recorded machine points since cutoff.

func (*SeriesRecorder) ReadSelf added in v0.1.1

func (r *SeriesRecorder) ReadSelf(read func() (Group, error))

ReadSelf reads Djinn's own process alone with read: ReadSelf in djinn up.

func (*SeriesRecorder) ReadWork added in v0.2.0

func (r *SeriesRecorder) ReadWork(read func() (Work, error))

ReadWork reads Djinn's work with read (ReadWork in djinn up): the Djinn line counts its cgroups and processes in place of its tree.

func (*SeriesRecorder) Sample added in v0.1.1

func (r *SeriesRecorder) Sample()

Sample collects one measurement point from the machine and Djinn process.

func (*SeriesRecorder) SetFS added in v0.1.1

func (r *SeriesRecorder) SetFS(fsys fs.FS)

SetFS overrides the filesystem for testing /proc.

func (*SeriesRecorder) WriteAbove added in v0.4.0

func (r *SeriesRecorder) WriteAbove(percent float64)

WriteAbove keeps each reading of the machine at or above percent of its memory in the store at once, not at the next flush: a machine that goes down with its memory full keeps the reading that says so, which the next djinn up reads (cmd/djinn/held.go). 0, the default, waits for the flush.

type Snapshot

type Snapshot struct {
	OS, Arch        string
	Cores           int
	MemoryTotal     uint64 // bytes; 0 when unknown
	MemoryAvailable uint64 // bytes available to new programs
	Load1           float64
	LoadKnown       bool
	CPU, Memory     *Pressure // nil without PSI
	// MemoryLevel is macOS's memory pressure level (kern.memorystatus_vm_pressure_level): 1 normal, 2 warning,
	// 4 critical; 0 when unknown.
	MemoryLevel int
	Disk        *Disk // the data folder's; nil when unknown
	GPUs        []GPU
	Time        time.Time
	// WorkersResident is the resident memory of Djinn's running workers, in bytes (Monitor.SetWorkerMemory): memory
	// available already leaves it out, so what Djinn may commit counts it back in (CommitMemory); 0 when unknown.
	WorkersResident uint64
}

Snapshot is the machine as read at one time. What the system does not give stays unknown.

func Calm added in v0.2.0

func Calm() (Snapshot, error)

Calm reads this machine as a Djinn under test sees it: its cores and memory, none of the memory taken, no load and no pressure. Its fake workers start whatever else the machine runs: other workers' builds and tests would hold them back past a test's wait (a macOS runner of the CI reads a load of 21 on 3 cores; this machine reached 42 on 16 while the e2e suite ran, W181). The pressure has its own tests (internal/machine, internal/gate).

func Read

func Read() (Snapshot, error)

Read reads this machine: /proc for the memory, the load and the pressure.

func ReadProc

func ReadProc(fsys fs.FS) (Snapshot, error)

ReadProc reads the memory, the load and the pressure from a Linux /proc, fsys being the root of the file system. The pressure files are optional: a kernel without PSI leaves the pressure unknown. The cores are not read here.

func (Snapshot) ByPressure added in v0.5.0

func (s Snapshot) ByPressure() bool

ByPressure says whether the system's own memory pressure level judges the memory instead of the memory available: on macOS, which compresses then swaps rather than refuse, and always shows little free (L30, option 2). The memory available then holds no worker back (Slots, Monitor.Available) and no gate (Room): the level does (Pressure, GatePressure, Warned). The memory available stays what the window shows.

type Work added in v0.2.0

type Work struct {
	// Cgroups is the CPU time of each cgroup that holds Djinn's work alone, by folder: its workers' and its own
	// commands' scopes (djinn-*.scope), and its own cgroup when nothing else runs in it. A cgroup counts the
	// processes it held that ended too: a test binary that exits leaves its time behind.
	Cgroups map[string]time.Duration
	// Procs is the CPU time of each process of Djinn's work in none of those cgroups, its own alone: its tree where
	// its cgroup is shared, and what its work started that moved to a cgroup of its own (a headless browser, W253).
	Procs map[int]time.Duration
	// Memory is the resident memory of Djinn's tree, of the processes in its scopes and of what they started.
	Memory uint64
}

Work is what Djinn's work used, read at once (ReadWork): counters that only grow while what they count lives, so that a process or a scope that ends never takes back what it used (W347: when a test run ended, the sum of Djinn's processes fell under its last reading, the Djinn line read 0 % and the next one too little).

func ReadWork added in v0.2.0

func ReadWork(pid int, slice string, cgroups []string) (Work, error)

ReadWork reads what Djinn's work uses, pid being Djinn's process: the cgroups (v2) that hold it alone, every djinn-*.scope under slice (Scopes.Slice: any Djinn's workers and commands, an end-to-end test's too), the scopes of the containers of every task's slice (ContainersSlice) and in cgroups (the scopes of its running workers, Scope.Cgroup), and the processes of its work out of them; from the same listing as ReadWorker. Without cgroups, its tree's processes alone.

type WorkerMemoryFunc added in v0.1.1

type WorkerMemoryFunc func(ctx context.Context, p Policy) (engaged, actual uint64, err error)

WorkerMemoryFunc returns the engaged memory (sum of peak forecasts) and actual resident memory of running workers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL