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
- Variables
- func Add(c *machinev1.CommandCost, run *machinev1.CommandServiceRecordRequest)
- func AgentPath(goos, path, home, shell string) string
- func AskLoginShell() error
- func BaseSlots(s Snapshot) int
- func CgroupPIDs(dir string) ([]int, error)
- func CostsHandler(db *store.Store) (string, http.Handler)
- func ExtendPath()
- func FreezeCgroup(dir string, frozen bool) error
- func GroupPIDs(procs []proc, pid int) []int
- func Handler(m *Monitor, running func() int, uses func() []*machinev1.WorkerUse, ...) (string, http.Handler)
- func KillCgroup(dir string) error
- func LoadHandler(home string, m *Monitor, setPolicy func(Policy), ...) (string, http.Handler)
- func LookPath(name, path string) (string, error)
- func LowPriority(notch djinnv1.LoadNotch) bool
- func NotchIndex(n djinnv1.LoadNotch) int
- func NotchName(notch djinnv1.LoadNotch) string
- func NotchTitle(notch djinnv1.LoadNotch) string
- func ParseNotch(s string) (djinnv1.LoadNotch, error)
- func Project(ctx context.Context, db *store.Store, taskID, dir string) (id, name string, err error)
- func ReadIfritIdle(home string) uint32
- func ReadLeadDriven(home string) bool
- func ReadNotch(home string) djinnv1.LoadNotch
- func Reader(dir string) func() (Snapshot, error)
- func SetCgroupWeight(dir string, weight int) error
- func SetWatchInterval(d time.Duration) func()
- func WorkerPIDs(pid int, cgroup string) ([]int, error)
- func WriteNotch(home string, notch djinnv1.LoadNotch) error
- type AutoController
- func (c *AutoController) Chosen() djinnv1.LoadNotch
- func (c *AutoController) Effective() djinnv1.LoadNotch
- func (c *AutoController) IsAuto() bool
- func (c *AutoController) Reason() *djinnv1.LoadAutoReason
- func (c *AutoController) SetNotch(notch djinnv1.LoadNotch) (effective djinnv1.LoadNotch, changed bool)
- func (c *AutoController) Tick() (bool, djinnv1.LoadNotch)
- type AutoMarks
- type AutoOption
- type Disk
- type GPU
- type Group
- type HandlerOption
- func WithDiskFolders(fn func() []*machinev1.DiskFolder) HandlerOption
- func WithDiskItems(fn func() []*machinev1.DiskItem) HandlerOption
- func WithHistory(h *History) HandlerOption
- func WithNetwork(fn func() *timestamppb.Timestamp) HandlerOption
- func WithSeriesIntervals(fn func(cutoff time.Time) []*machinev1.GateInterval) HandlerOption
- func WithSeriesRecorder(rec *SeriesRecorder) HandlerOption
- func WithSeriesWorkers(...) HandlerOption
- type History
- func (h *History) Flush(ctx context.Context)
- func (h *History) Machine(p *machinev1.MachinePoint)
- func (h *History) MachinePoints(ctx context.Context, from, to time.Time) []*machinev1.MachinePoint
- func (h *History) Worker(taskID string, p *machinev1.WorkerPoint)
- func (h *History) WorkerPoints(ctx context.Context, taskID string, from, to time.Time) []*machinev1.WorkerPoint
- type LoadOption
- func WithLoadAutoController(ac *AutoController) LoadOption
- func WithLoadClock(clock func() time.Time) LoadOption
- func WithLoadForcedWorkers(forced func() int) LoadOption
- func WithLoadLowerPauses(pauses func() bool) LoadOption
- func WithLoadOutside(source OutsideSource) LoadOption
- func WithLoadPausedWorkers(paused func() int) LoadOption
- func WithLoadRunningWorkers(running func() int) LoadOption
- func WithLoadStreamer(attach func(...)) LoadOption
- func WithLoadTickInterval(d time.Duration) LoadOption
- func WithLoadWorkerForecast(forecast func() uint64) LoadOption
- type Monitor
- func (m *Monitor) Available() uint64
- func (m *Monitor) BarSlots(n djinnv1.LoadNotch) int
- func (m *Monitor) Capacity() (slots int, rule, pressure string)
- func (m *Monitor) NotchSlots() []NotchSlots
- func (m *Monitor) Policy() Policy
- func (m *Monitor) Pressure() string
- func (m *Monitor) SetPolicy(p Policy)
- func (m *Monitor) SetWorkerMemory(resident func() uint64)
- func (m *Monitor) Snapshot() Snapshot
- func (m *Monitor) Total() uint64
- type NotchSlots
- type Outside
- type OutsideSource
- type Peaks
- type Policy
- func (p Policy) AvailableMemory(s Snapshot) uint64
- func (p Policy) BarSlots(s Snapshot) int
- func (p Policy) BaseSlots(s Snapshot, peaks ...uint64) (int, string)
- func (p Policy) BindingResource(s Snapshot, peaks ...uint64) string
- func (p Policy) CPUSlots(s Snapshot) int
- func (p Policy) CommitMemory(s Snapshot) uint64
- func (p Policy) CommittableLimit(available uint64) uint64
- func (p Policy) EngagedAt() string
- func (p Policy) LocalModel(s Snapshot) (bool, string)
- func (p Policy) LowPriority() bool
- func (p Policy) MemoryPercentile() int
- func (p Policy) MemorySlots(s Snapshot, peaks ...uint64) int
- func (p Policy) NotchName() string
- func (p Policy) NotchTitle() string
- func (p Policy) Pressure(s Snapshot) string
- func (p Policy) Room(s Snapshot, command string, peak, held uint64) string
- func (p Policy) RuleMemory(total uint64) uint64
- func (p Policy) Slots(s Snapshot, peaks ...uint64) (int, string)
- func (p Policy) Typical(peaks []uint64) (uint64, int)
- func (p Policy) UsableMemory(s Snapshot) uint64
- func (p Policy) WorkerForecast(peaks ...uint64) uint64
- func (p Policy) WorkerMemoryCeiling(peak uint64, measured int) uint64
- func (p Policy) WorkerMemoryMax(factor float64, peak uint64, measured int) uint64
- func (p Policy) WorkerRoom(total, available, resident, held, engaged uint64, provider string, peak uint64, ...) string
- type Pressure
- type Scope
- type Scopes
- type SeriesRecorder
- func (r *SeriesRecorder) AddPoint(p *machinev1.MachinePoint)
- func (r *SeriesRecorder) Keep(h *History)
- func (r *SeriesRecorder) Outside(since time.Time) (Outside, bool)
- func (r *SeriesRecorder) Points(cutoff time.Time) []*machinev1.MachinePoint
- func (r *SeriesRecorder) ReadSelf(read func() (Group, error))
- func (r *SeriesRecorder) ReadWork(read func() (Work, error))
- func (r *SeriesRecorder) Sample()
- func (r *SeriesRecorder) SetFS(fsys fs.FS)
- type Snapshot
- type Work
- type WorkerMemoryFunc
Constants ¶
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.
const ( MiB = 1 << 20 GiB = 1 << 30 )
MiB is a mebibyte; GiB is a gibibyte.
const ( MemoryWarning = 2 MemoryCritical = 4 )
macOS's memory pressure levels that may hold new workers: warning at the Minimal notch, critical from Medium up.
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.
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.
const NotMeasured = ""
NotMeasured is why the workers' CPU and memory are not measured here; empty: they are.
Variables ¶
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.
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.
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.
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.
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.
var ManualNotches = []djinnv1.LoadNotch{ djinnv1.LoadNotch_LOAD_NOTCH_MINIMAL, djinnv1.LoadNotch_LOAD_NOTCH_MEDIUM, djinnv1.LoadNotch_LOAD_NOTCH_HIGH, djinnv1.LoadNotch_LOAD_NOTCH_MAX, djinnv1.LoadNotch_LOAD_NOTCH_OVERCLOCK, }
ManualNotches is the ordered list of 5 manual operating load notches.
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.
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.
var SeriesMinutes = []int32{10, 30, 120, 24 * 60, 7 * 24 * 60}
SeriesMinutes are the ranges a series may be asked for: 10 and 30 minutes, 2 hours, a day, a week.
Functions ¶
func Add ¶
func Add(c *machinev1.CommandCost, run *machinev1.CommandServiceRecordRequest)
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
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
BaseSlots returns the number of slots given by the current machine rule without notch scaling.
func CgroupPIDs ¶
CgroupPIDs lists the processes in the cgroup folder dir; an error when it does not exist (yet, or any more).
func CostsHandler ¶
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 FreezeCgroup ¶
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
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 KillCgroup ¶
KillCgroup kills every process in the cgroup folder dir, at once (cgroup.kill, since Linux 5.14).
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
LookPath finds name in the folders of path, as exec.LookPath does for a worker: only absolute folders count.
func LowPriority ¶ added in v0.1.1
LowPriority reports whether the load notch runs workers with low CPU priority. Minimal and medium notches run with low CPU priority to yield CPU to developer applications; high, max, and overclock run with standard priority.
func NotchIndex ¶ added in v0.1.1
NotchIndex returns the index of a notch among the manual notches (0 to 4), mapping LIGHT to MEDIUM (1).
func NotchTitle ¶ added in v0.1.1
NotchTitle returns the title-case name of a notch (e.g. "Minimal", "Medium", "High", "Max", "Overclock", "Auto").
func ParseNotch ¶ added in v0.1.1
ParseNotch parses a string into a LoadNotch.
func Project ¶ added in v0.1.1
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 ReadIfritIdle ¶ added in v0.2.0
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
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
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 ¶
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 SetCgroupWeight ¶ added in v0.1.1
SetCgroupWeight sets the CPU weight of the cgroup folder dir (1 to 10000, 100 is default, 10 for low priority).
func SetWatchInterval ¶ added in v0.1.1
SetWatchInterval sets the minimum interval between Watch stream messages for tests.
func WorkerPIDs ¶ added in v0.1.1
WorkerPIDs returns the list of process IDs belonging to a worker (from its cgroup if available, or process tree).
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
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 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 ¶
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 ¶
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. 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 ¶
ParsePS reads, from the output of ps with PSArgs, what the worker whose process leads group pid uses.
func ReadCgroup ¶
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 ¶
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
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 ReadWorker ¶
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 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 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) []*machinev1.GateInterval) HandlerOption
WithSeriesIntervals sets the function returning gate intervals.
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 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
NewHistory keeps the series in db.
func (*History) Flush ¶ added in v0.1.1
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) 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
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 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 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 ¶
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 ¶
Available is the memory available to new programs now, in bytes; 0 when unknown.
func (*Monitor) BarSlots ¶ added in v0.1.2
BarSlots is the most workers the notch n itself lets run now (Policy.BarSlots), djinn up --workers holding.
func (*Monitor) Capacity ¶
Capacity is the most workers the machine runs at once and its rule, 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) SetWorkerMemory ¶ added in v0.1.1
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.
type NotchSlots ¶ added in v0.1.2
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
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 the highest peak memory measured of each command, for the gates.
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, instead of MemoryFree, the system's own memory pressure level at MemoryLevel
// or above: warning (MemoryWarning) at Minimal only, since warning is frequent and passing on a busy Mac;
// critical (MemoryCritical, also what 0 means) from Medium up.
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 highest peak plus CommandMargin; 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 float64
// 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
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
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
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
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
BindingResource reports which resource limits worker capacity: "memory" or "cpu".
func (Policy) CPUSlots ¶ added in v0.1.1
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
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
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
EngagedAt says at which percentile of its memory a worker is engaged, and why: "engaged at p50 (overclock)".
func (Policy) LocalModel ¶
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) LowPriority ¶ added in v0.1.1
LowPriority reports whether the policy runs workers with low CPU priority.
func (Policy) MemoryPercentile ¶ added in v0.1.1
MemoryPercentile is the percentile a worker is engaged at (Percentile): 95 when unset.
func (Policy) MemorySlots ¶ added in v0.1.1
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 returns MaxWorkers.
func (Policy) NotchTitle ¶ added in v0.1.1
NotchTitle returns the title-case name of the policy's load notch.
func (Policy) Pressure ¶
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 ¶
Room says why the machine cannot hold the command yet, its highest 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. A command never measured (peak 0), or a machine whose memory is unknown, has room.
func (Policy) RuleMemory ¶ added in v0.1.1
RuleMemory returns the memory the rule would engage on a machine with total RAM.
func (Policy) Slots ¶
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.
func (Policy) Typical ¶
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
UsableMemory returns the memory Djinn could use beyond the reserve, its running workers' included: max(0, CommitMemory - MemoryReserve).
func (Policy) WorkerForecast ¶ added in v0.1.1
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
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
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 ¶
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
// 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 ¶
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 ¶
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
NewWithMemory is the scope of a process of the worker name with an explicit memory ceiling in bytes (0: no ceiling).
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.
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
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).
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
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) 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.