machine

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 27 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 GiB = 1 << 30

GiB is a gibibyte.

View Source
const NotMeasured = ""

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

Variables

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 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.

Functions

func Add

Add counts a run in what the command costs: the means move, the peak keeps the highest.

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 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 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 Handler

func Handler(m *Monitor, running func() int, uses func() []*machinev1.WorkerUse) (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

func KillCgroup(dir string) error

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

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.

Types

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. 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 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.

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, in bytes; 0 when unknown.

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, and why it is under pressure ("" when it is not).

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) Snapshot

func (m *Monitor) Snapshot() Snapshot

Snapshot is the machine, read at most a second ago. A reading that fails keeps what is known: the cores.

type Peaks

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

Peaks reads the highest peak memory measured of each command, for the gates.

func NewPeaks

func NewPeaks(db *store.Store) *Peaks

NewPeaks reads the peaks in the store.

func (*Peaks) Peak

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

Peak is the highest peak memory, in bytes, of the command in its project: the task's, else the one holding dir. It is 0 when the command was never measured, or outside any project.

type Policy

type Policy struct {
	// 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.
	WorkerMemory uint64
	// 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, the system's own memory pressure level at warning or above.
	LoadPerCore float64
	MemoryFree  float64
	// 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
	// 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. 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 (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) 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 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) Slots

func (p Policy) Slots(s Snapshot) (int, string)

Slots is the most workers the machine runs at once, and the rule that gave it.

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) WorkerRoom

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

WorkerRoom says why the machine cannot hold another worker of provider yet, or "" when it can: the memory available, less held (what the workers running may still take), holds peak, the typical peak 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
	// 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.

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
}

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

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.

Jump to

Keyboard shortcuts

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