Repository navigation
feat(sbx): a host resource sampler, one JSON line every 15 s (#857 R2) - #904
Conversation
…l#857 R2) Nothing sampled a sandbox-service KVM host's CPU, memory, pressure or disk I/O, so "how loaded was the host?" had no answer after the fact. deploy/sbx/sampler.sh, run by sbx-sampler.timer (OnUnitActiveSec=15s, AccuracySec=1s), writes one JSON line per sample to the journal: load, memory and swap, PSI (cpu/memory/io), workspace bytes and inodes, the sbx.slice cgroup's cpu.stat, memory.current/peak and io.stat, and per worker its VMs (populated vmpool cgroups), slice memory, budget and, with SH_DIAG_STATS_ADDR, committedBytes/standbyCommittedBytes/refusals from /stats. It reads /proc and cgroup files with builtins, starts only df and curl, needs no jq, and always exits 0. A failure kind is one error line when it starts and one recovered line when it ends (state in the unit's preserved RuntimeDirectory); every sample names the kinds failing in it. The unit logs at notice with LogLevelMax=notice, so systemd's per-run lines stay out of the journal. install-host.sh installs it with every worker install (no bundle or secret, so no flag of its own) as the shared manifest kind `sampler`: --keep-shared keeps it, the last plain --uninstall removes it, and SBX_SAMPLER_INTERVAL_S (5-3600, 0 = none) sets the interval. status.sh --host prints the same line once, from the same script. Docs: README, the runbook's new "The host sampler" section and step 4 of "Reproducing a member's issue", configuration.md. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Review follow-up: stats() curled whatever host SH_DIAG_STATS_ADDR named and only mapped the wildcard addresses to loopback. It now reads a wildcard on loopback and refuses any address that is neither loopback (127.*, [::1], localhost) nor a wildcard, with one error line, so the sampler only ever reads this host's own workers. Tested; the header and the RUNBOOK say so. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Review follow-up: `127.*` was a glob and the host may hold letters, so a name like 127.example.com matched and would have been resolved through DNS. 127.0.0.0/8 is now matched as four numeric octets; tests refuse 127.example.com and read 127.0.0.2. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Measured on a KVM host: the timer's AccuracySec=1s lets systemd defer each elapse up to 1 s, so the default 15 s series runs every 15-16 s (38 samples in 600 s). The RUNBOOK and the timer's comment say so; the interval itself is unchanged. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
A well-scoped sampler. It reads only /proc and cgroup files, validates every value as a number, escapes strings, and caps errors at one line per kind. The install and uninstall paths follow the read-ahead and janitor patterns (manifest kind, --keep-shared, interval validation, plain-path check before the unit sed), and the /stats fetch is loopback-only with --noproxy. No blocking issues; the three inline comments are non-blocking.
Author: webchang (MEMBER). Commits: 4, all signed off. CI: all checks passing. No .claude/.vscode changes.
| df_line() { | ||
| local -a t=() | ||
| command -v timeout >/dev/null && t=(timeout 5) | ||
| printf -v "$1" '%s' "$("${t[@]}" df -P "$2" -- "$SBX_SRV/workspaces" 2>/dev/null | { read -r _; read -r l; printf '%s' "${l:-}"; })" |
There was a problem hiding this comment.
suggestion: the worst case of the two timeout 5 df calls is 10 s, which equals TimeoutStartSec=10s. On a hung workspace filesystem systemd kills the unit, so there is no sample, and it logs a failure at warning level every 15 s. That is the journal flood the header says this script avoids ("always exits 0"). Consider timeout 3 for each df, or skip the inode df when the byte df timed out, so a hang still ends in a sample with workspaces null plus an error line.
There was a problem hiding this comment.
Fixed in bf0cfc9: each df runs under timeout -k 1 3, and the inode call is skipped after a byte call that did not answer, so a hung filesystem costs one 3-4 s bound and still ends in a sample with workspaces null and one error line. sampler.test.sh covers it with a df that never answers under the real timeout (about 3 s, one call; the previous version took the full 10 s).
| systemctl daemon-reload | ||
| # enable, then restart rather than enable --now: a re-install with another interval must re-arm | ||
| # a timer that is already running. | ||
| systemctl enable sbx-sampler.timer |
There was a problem hiding this comment.
suggestion: the PR text and the install_sampler comment say a sampler problem is "never a failed worker install". Only the precondition checks warn and return. install -d, install -m, systemctl daemon-reload, systemctl enable and systemctl restart run under set -e, so a failure aborts before install_worker. install_read_ahead behaves the same way. Either guard these with || { echo WARNING...; return 0; } or soften the wording.
There was a problem hiding this comment.
Fixed in c324259: every step of the sampler's install is now checked, and the first one that fails is a WARNING naming it while the worker install goes on; the files are recorded in the manifest first, so an uninstall cleans up after a partial install. Tested with a failing enable, a failing restart and an unwritable unit file. install_read_ahead is unchanged here, and the comment no longer claims the sampler behaves the same way.
| # (SH_DIAG_STATS_ADDR is set in one, as the env file is rewritten by every install). Its main | ||
| # process is the first in the unit's cgroup (Type=simple: microvm-worker itself). | ||
| pid='' | ||
| read1 pid "$CG/sbx.slice/sbx-$id.slice/sbx-worker@$id.service/cgroup.procs" || pid='' |
There was a problem hiding this comment.
nit: the kernel doesn't guarantee that the first line of cgroup.procs is the unit's main process (pid wraparound, for example). A child such as the jailer could then supply /proc/<pid>/environ, and budget_mb and stats would silently fall back to the env file. Children mostly inherit the worker's env, so the impact is small. A softer comment, or a check that /proc/<pid>/comm is microvm-worker, would be more honest.
There was a problem hiding this comment.
Fixed in bf0cfc9: the worker is now the pid in its unit's cgroup.procs whose /proc/<pid>/comm is microvm-worker (no fork per worker, unlike systemctl show -p MainPID), falling back to the env file alone. Tested with a jailer listed first and with no such process.
The comment and the PR said so, but only the precondition checks warned: install -d, install -m, the unit file writes, daemon-reload, enable and restart ran under set -e, so any of them aborted the install before the worker started (review on rossoctl#904). install_sampler_steps checks each step and returns at the first that fails, naming it; install_sampler turns that into a WARNING and the worker install goes on. The three files are recorded in the manifest first, so an uninstall removes whatever a failed step left. Tested: a failing enable or restart of the timer, and a unit file it cannot write, warn with the step, the worker still starts and attaches, and the uninstall leaves no sampler file or line. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
…m; the worker pid by comm Two review points on rossoctl#904: - Two `timeout 5 df` calls could take 10 s, the unit's whole TimeoutStartSec, so a hung workspace filesystem got the unit killed every 15 s with a warning-level failure and no sample. Each df now runs under `timeout -k 1 3`, and the inode call is skipped after a byte call that did not answer: a hang costs one 3-4 s bound and ends in a sample with workspaces null and one error line. Tested with a df that never answers under the real timeout (about 3 s, one call); the previous version took 10 s on it. - The kernel does not order cgroup.procs, so its first line could be a helper whose environment would stand in for the worker's. The worker is now the pid there whose /proc/<pid>/comm is microvm-worker (no fork, unlike systemctl show -p MainPID), else the env file alone. Tested with a helper listed first, and with no such process. Part of rossoctl#857 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Brings 15 upstream merges since 2eb0219, among them the R2 host sampler in its reviewed form (rossoctl#904), the workspace-reset marker (rossoctl#895), turn budgets and cancel (rossoctl#856), the egress allow-all option (rossoctl#886), the sbx installer token (rossoctl#888), and the docs site with the product-name prose (rossoctl#884, rossoctl#885, rossoctl#899). One conflict, deploy/sbx/template-onboarding/README.md: upstream's product-name wording for the deploy/sbx table, keeping the fork's mint-login.sh row. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Rong Chang <[email protected]>
Part of #857 (R2): a host resource sampler for sandbox-service KVM hosts, one JSON line in the journal every 15 s, and the same fields in
status.sh --hostWhat changed and why
R2 asks that an operator can answer "how loaded was the host?" for any time in the retention window with one query. Until now nothing sampled a KVM host's CPU, memory, pressure or disk I/O, and the worker's
/stats(opt-in viaSH_DIAG_STATS_ADDR) was read by nothing.deploy/sbx/sampler.sh(installed as/usr/local/libexec/sbx-sampler.sh) prints one{"sampler":"sample",…}line per run, in the janitor summary's style:load(1/5/15 min),mem_kb(MemTotal, MemAvailable, SwapTotal, SwapFree, swap used),psi(cpu,memory,io:someandfull, avg10 and avg60),workspaces(bytes and inodes of the filesystem holding$SBX_SRV/workspaces);slice: thesbx.slicecgroup'scpu.stat(usage_usec,nr_throttled,throttled_usec),memory.current,memory.peak(null before Linux 5.19) andio.statsummed over devices;workers, one per installed worker:vms, the VM cgroups in its slice that hold a process (the namesvmpoolmakes:pool-<n>,vm-<n>,vm-vm-<n>.scope; the unit's own cgroup never counts), the slice'smemory_current,budget_mbandreserve_mb(SH_MAX_COMMITTED_MB,SH_MEMORY_RESERVE_MB), andstats:committedBytes,standbyCommittedBytesandrefusalsfrom the worker's/stats, or null withoutSH_DIAG_STATS_ADDR. Those settings come from the running worker's/proc/<pid>/environ(so a drop-in'sSH_DIAG_STATS_ADDRcounts, and an install rewrites the env file anyway), else from its env file./procand cgroup files with bash builtins. The only programs it starts aredftwice (undertimeout 5) and onecurl --max-time 1per worker with/stats. It needs nojq, so a worker host needs nothing new. Every value is checked as a number and is null when it cannot be read. It always exits 0.loadavg,meminfo,psi,workspaces,slice,workers,curl,worker:<id>,stats:<id>) gets at most one{"sampler":"error","kind","why"}line per run. With the unit's preservedRuntimeDirectory, it gets only one when it starts failing, and one{"sampler":"recovered","kind"}line when it reads again. Every sample'serrorsnames the kinds failing in it, so a lasting failure, for example a kernel without PSI, is one line rather than one every 15 s.sbx-sampler.service+sbx-sampler.timer. The service is a oneshot withTimeoutStartSec=10s,Nice=10,ProtectSystem=strictand read-only kernel tunables and cgroups. It setsSyslogLevel=noticewithLogLevelMax=notice, so systemd's own info lines about each run (started, finished, CPU consumed) stay out of the journal. The timer usesOnUnitActiveSec=15swithAccuracySec=1s(the default accuracy is a minute).install-host.shinstalls the sampler with every worker install, not behind a flag of its own like--janitor. The sampler needs no bundle and no secret, and it measures the workers, so every host that has a worker samples from its first install on, with no extra step to forget. Its three files are their own manifest kind,sampler <path>, and are shared like the template unit: one of two uninstalls keeps them,--keep-sharedkeeps them (so a host agent's retire of a build never stops the sampling), and the last plain--uninstalldisables the timer, cleans the runtime directory and removes them.SBX_SAMPLER_INTERVAL_S(default 15, 5-3600) sets the interval;0installs none and removes an installed one. A bad value is refused before anything is touched. As with the read-ahead, a problem installing the sampler is a warning, never a failed worker install.status.sh --hostaddsunit sbx-sampler.timer: …andhost sample: <the sampler's line>, with ahost sample error: …line before it for each failing kind. It runs the installed sampler, or elsesampler.shbeside the script in a checkout, without the state directory. The one-shot view and the journal series come from one code path, and the host side piped over ssh still needs no checkout. The existing lines are unchanged.deploy/sbxREADME covers the sampler beside the read-ahead, and the last uninstall now removes it. The runbook gets a new section, "The host sampler": the fields, how errors are reported,journalctl -u sbx-sampler -o cat … | jqqueries (a point in time, andsbx.sliceCPU in cores between samples), how to turn onSH_DIAG_STATS_ADDRfor one worker with a drop-in, and how to measure its cost. The runbook also gets the sampler in §8's host output and in §12, its journal volume under "What is kept", and step 4 of "Reproducing a member's issue" now pulls the window's samples.docs/reference/configuration.mdlistsSBX_SAMPLER_INTERVAL_S.Tests
deploy/sbx/tests/sampler.test.shruns on a fake/procand cgroup tree (SBX_SYS_ROOT, the host agent's seam), withdf,curlandtimeoutmocked andPATHholding only the mocks, so it also proves the sampler runs nothing else. It checks:cgroup.eventsby itscgroup.procs;/statsaddresses read on loopback, and a running worker's environment winning over its env file;psiline), named in the sample'serrors;recoveredline; without a usable state directory, every run reports;install-host.test.sh:SBX_SAMPLER_INTERVAL_Svalues before systemd or any file is touched;samplerlines (notunitlines), and enables and restarts the timer before the worker restart;--keep-sharedkeep the sampler, and the plain last uninstall disables, cleans and removes it, leaving the manifest empty;0removes an installed sampler and on a clean host never touches its units.status.test.sh:host sampleline with the fixture's fields and the timer's unit state;bash -s), the installed sampler runs.bash deploy/sbx/tests/*.test.sh(all pass),shellcheck -x -S warningoverdeploy/andscripts/,prettier --checkon the changed Markdown,python3 scripts/check-doc-links.pyandscripts/check-docs-publish.sh.Overhead
The epic's target is under 1% of one core. Local numbers, on a developer machine (macOS, where fork and exec cost more than on Linux) with a fake tree of 4 workers with 8 VM cgroups each, 200 runs, CPU time of the runs (user + sys):
/stats: about 35 ms of CPU per run, so 0.23% of one core at the 15 s interval;/statson all 4 workers (a local HTTP server standing in for each worker): about 66 ms per run, 0.44% of one core.On a KVM host (one template worker installed, idle; the installed script under its own unit,
systemd-run --wait -p CPUAccounting=yesfive times and GNUtime -vthree times): 11.5-14 ms CPU per run, 0.08-0.09 % of one core at the 15 s interval, about 3.2 MB peak RSS, about 954 bytes per sample in the journal, and no error or per-run systemd lines over 600 s. Under load (one sandbox created, one command run, then deleted), every sample stayed valid,workers[].vmsfollowed the run's standby pool (0 before the run's first Exec, 2 between Execs, 0 again about 107 s after the delete), and the command showed as about 1 s ofsbx.sliceCPU between two samples.The cadence is every 15-16 s in practice (38 samples in 600 s), since
AccuracySec=1slets systemd defer each elapse up to 1 s; the docs say so (2c22a56).Out of scope
SH_DIAG_STATS_ADDRby default: it stays the operator's opt-in; the runbook shows the drop-in.memory.currentand the worker's/statscover budget use. A per-VM breakdown would read every VM cgroup every 15 s.Every commit is signed off (DCO).
Assisted-By: Claude Code