Skip to main content

nmbrs_runtime/
sysmon.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Session-level system-performance sampler (SRD-118).
5//!
6//! Enabled per session with `sysmon=<categories>`: `sysmon=all`,
7//! `sysmon=any`, or a comma list of category names. `all` and `any`
8//! differ in exactly one way: `all` ABORTS when a subsystem is
9//! unavailable, `any` enables what the host supports and NAMES what it
10//! skipped. Reads `/proc` (and statvfs) on a fixed interval (default
11//! 5 s, `sysmon_interval=<seconds>`) and publishes host-side measures
12//! as session-scoped gauges plus a live observer callback for display
13//! surfaces: measurement of the machine under the workload, not of the
14//! workload.
15//!
16//! The host is read through `nmbrs-host` (SRD-118 §9), which holds
17//! each category's counters, parser and arithmetic. This module holds
18//! what makes those readings a session's sampler: the `sysmon=`
19//! setting, what it requires of the session, the sample a window
20//! yields, the gauges and the task.
21//!
22//! Counters are cumulative, so every rate here is a pairwise delta
23//! over the sample window; the published gauge is the latest window's
24//! value and any windowing beyond that belongs to MetricsQL at query
25//! time.
26
27pub mod gauges;
28mod sampler;
29
30use std::time::Duration;
31
32use nmbrs_host::category::{CATEGORY_NAMES, Categories, platform_supported, unavailable};
33use nmbrs_host::{cgroup, cpu, disk, net, pressure, process};
34
35pub use sampler::spawn;
36
37/// What a `sysmon=` value asked for: a fixed category set, or "whatever
38/// this host supports".
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Selection {
41    /// Named categories (including `all`): every one is REQUIRED, and an
42    /// unavailable subsystem aborts the session with instructions.
43    Cats(Categories),
44    /// `sysmon=any`: enable every available subsystem, skip-and-announce
45    /// the rest. The stated opt-in is what makes the skip acceptable.
46    Any,
47}
48
49/// Parse a `sysmon=` value: `all`, `any`, or a comma list of category
50/// names. Unknown names are errors that NAME the valid set — a typo
51/// silently monitoring nothing would be the failure mode this surface
52/// exists to avoid.
53pub fn parse_selection(value: &str) -> Result<Selection, String> {
54    let trimmed = value.trim();
55    if trimmed.eq_ignore_ascii_case("any") {
56        return Ok(Selection::Any);
57    }
58    if trimmed
59        .to_ascii_lowercase()
60        .split(',')
61        .any(|t| t.trim() == "any")
62    {
63        return Err("sysmon: `any` stands alone (it means \"every available \
64             subsystem\") — combining it with named categories is \
65             ambiguous. Use `sysmon=any`, or name the categories."
66            .to_string());
67    }
68    parse_categories(trimmed).map(Selection::Cats)
69}
70
71/// Parse a fixed category list (`all` or comma names). See
72/// [`parse_selection`] for the `any` form.
73pub fn parse_categories(value: &str) -> Result<Categories, String> {
74    if value.trim().eq_ignore_ascii_case("all") {
75        return Ok(Categories::ALL);
76    }
77    let valid = CATEGORY_NAMES.join(", ");
78    let mut cats = Categories::default();
79    for token in value.split(',') {
80        let name = token.trim().to_ascii_lowercase();
81        if name.is_empty() {
82            continue;
83        }
84        cats.add(&name).map_err(|name| {
85            format!(
86                "sysmon: unknown category '{name}'. Valid: all, any, or a \
87                 comma list of {valid}"
88            )
89        })?;
90    }
91    if !cats.any() {
92        return Err(format!(
93            "sysmon: no categories enabled. Use `sysmon=all`, `sysmon=any` or a comma \
94             list of {valid}"
95        ));
96    }
97    Ok(cats)
98}
99
100/// One completed sample window. A field is `Some`, or a list is
101/// filled, exactly when its category was enabled and had a reading —
102/// a disabled category is absent, not zero.
103#[derive(Debug, Clone, PartialEq, Default)]
104pub struct SysmonSample {
105    pub cpu: Option<cpu::CpuReading>,
106    /// (device, utilization) — the busiest device this window.
107    pub io: Option<(String, f64)>,
108    /// Each whole device's throughput this window.
109    pub io_rates: Vec<disk::DiskRate>,
110    /// (committed, everything-including-page-cache).
111    pub ram: Option<(f64, f64)>,
112    /// Memory-bandwidth utilization against the configured peak.
113    pub rambw: Option<f64>,
114    /// (mount point, space utilization) — the fullest filesystem.
115    pub storage: Option<(String, f64)>,
116    /// Each interface's throughput this window.
117    pub net: Vec<net::NetRate>,
118    /// The stalled share of this window, by resource.
119    pub pressure: Option<pressure::PressureReading>,
120    /// Each watched process this window.
121    pub procs: Vec<process::ProcReading>,
122    /// Each watched control group this window.
123    pub cgroups: Vec<cgroup::CgroupReading>,
124}
125
126/// Sampler configuration, resolved by the runner from session params.
127#[derive(Debug, Clone)]
128pub struct SysmonConfig {
129    pub cats: Categories,
130    /// Sample window. Default 5 s (`sysmon_interval=<seconds>`).
131    pub interval: Duration,
132    /// Peak memory bandwidth in bytes/s — the reference that turns rambw
133    /// bytes/s into a utilization. Required when `rambw` is enabled.
134    pub membw_peak_bytes_per_s: Option<f64>,
135    /// The processes `sysmon_procs=` names, besides nmbrs itself.
136    pub procs: Vec<process::ProcTarget>,
137    /// The control groups `sysmon_cgroups=` names.
138    pub cgroups: Vec<cgroup::CgroupTarget>,
139}
140
141/// What the platform check says when it fails.
142pub const UNSUPPORTED_PLATFORM: &str = "sysmon: the sampler reads /proc and is available on \
143     Linux only; run without `sysmon=` on this host";
144
145/// What a category that was asked for by name says when this host
146/// cannot supply it: the host's reason, and how to run without it.
147fn required(category: &str, reason: String) -> String {
148    format!(
149        "sysmon: {category} was requested, but {reason}\n\n\
150         Name the categories without {category}, or use  sysmon=any  to enable \
151         every subsystem this host supports."
152    )
153}
154
155/// The rambw prerequisites, checked BEFORE the session starts so an
156/// unsupported host aborts with instructions instead of silently monitoring
157/// less than was asked for.
158pub fn check_rambw_requirements(config: &SysmonConfig) -> Result<(), String> {
159    if !config.cats.rambw {
160        return Ok(());
161    }
162    if let Some(reason) = unavailable("rambw") {
163        return Err(required("rambw", reason));
164    }
165    if config.membw_peak_bytes_per_s.is_none() {
166        return Err("\
167sysmon: rambw needs a peak-bandwidth reference to turn bytes/s into a \
168utilization. Set it with  sysmon_membw_gbps=<peak>  (the host's rated \
169memory bandwidth in GB/s), name the categories without rambw, or use  \
170sysmon=any"
171            .to_string());
172    }
173    Ok(())
174}
175
176/// A category whose only prerequisite is the host's: `pressure` and
177/// `cgroup`.
178fn check_host_requirement(config: &SysmonConfig, category: &str) -> Result<(), String> {
179    if !config.cats.has(category) {
180        return Ok(());
181    }
182    match unavailable(category) {
183        Some(reason) => Err(required(category, reason)),
184        None => Ok(()),
185    }
186}
187
188/// Everything a named category needs of this host, checked before the
189/// session starts. `sysmon_procs=` without the `proc` category, and
190/// `sysmon_cgroups=` without `cgroup`, are refused here too: each
191/// would otherwise name something nothing watches.
192pub fn check_requirements(config: &SysmonConfig) -> Result<(), String> {
193    if !platform_supported() {
194        return Err(UNSUPPORTED_PLATFORM.to_string());
195    }
196    if !config.procs.is_empty() && !config.cats.proc {
197        return Err(
198            "sysmon: `sysmon_procs=` names processes to watch, and the `proc` \
199             category is not enabled; add `proc` to `sysmon=`"
200                .to_string(),
201        );
202    }
203    if !config.cgroups.is_empty() && !config.cats.cgroup {
204        return Err(
205            "sysmon: `sysmon_cgroups=` names control groups to watch, and the \
206             `cgroup` category is not enabled; add `cgroup` to `sysmon=`"
207                .to_string(),
208        );
209    }
210    check_rambw_requirements(config)?;
211    check_host_requirement(config, "pressure")?;
212    check_host_requirement(config, "cgroup")
213}
214
215/// Resolve `sysmon=any` against THIS host: every category the host
216/// supports, plus one human-readable line per category that had to be
217/// skipped and why. The /proc-backed categories are always available
218/// on Linux; rambw, pressure and cgroup carry real prerequisites.
219///
220/// The skip lines exist because `any` is best-effort, not silent-effort:
221/// the runner logs each one, so a session that monitored six of nine
222/// categories says so.
223pub fn resolve_any(config: &SysmonConfig) -> (Categories, Vec<String>) {
224    if !platform_supported() {
225        return (
226            Categories::default(),
227            vec![UNSUPPORTED_PLATFORM.to_string()],
228        );
229    }
230    let mut cats = Categories::ALL;
231    let mut skipped = Vec::new();
232    let probe = SysmonConfig {
233        cats,
234        ..config.clone()
235    };
236    // First line of the full instructions — the one that names the
237    // missing prerequisite. Naming the category gets the complete text.
238    let first = |reason: String| reason.lines().next().unwrap_or("unavailable").to_string();
239    if let Err(reason) = check_rambw_requirements(&probe) {
240        cats.rambw = false;
241        skipped.push(format!(
242            "{} (run `sysmon=rambw` for the enable steps)",
243            first(reason)
244        ));
245    }
246    for (category, on) in [
247        ("pressure", &mut cats.pressure),
248        ("cgroup", &mut cats.cgroup),
249    ] {
250        if let Err(reason) = check_host_requirement(&probe, category) {
251            *on = false;
252            skipped.push(format!(
253                "{} (run `sysmon={category}` for the details)",
254                first(reason)
255            ));
256        }
257    }
258    (cats, skipped)
259}
260
261#[cfg(test)]
262mod tests;