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 categories, each in its own module:
17//!
18//! - **cpu** ([`cpu`]): mean utilization, the hottest core, and the
19//!   quartiles of the per-core distribution.
20//! - **io** ([`disk`]): how busy the busiest device is, and each whole
21//!   device's read and write throughput.
22//! - **ram** ([`mem`]): memory committed, and memory touched (page
23//!   cache included).
24//! - **rambw** ([`mem`]): memory bandwidth against a stated peak, from
25//!   resctrl.
26//! - **storage** ([`disk`]): how full the fullest writable filesystem
27//!   is.
28//! - **net** ([`net`]): each interface's receive and transmit
29//!   throughput.
30//! - **pressure** ([`pressure`]): the share of time tasks were stalled
31//!   for want of CPU, memory or I/O.
32//! - **proc** ([`process`]): CPU, memory, threads and storage I/O of
33//!   nmbrs itself and of each process `sysmon_procs=` names.
34//!
35//! Counters are cumulative, so every rate here is a pairwise delta
36//! over the sample window; the published gauge is the latest window's
37//! value and any windowing beyond that belongs to MetricsQL at query
38//! time.
39//!
40//! The parsers read strings, so the arithmetic is tested on fixtures;
41//! only the sampler and the `read_*` functions touch the filesystem.
42
43pub mod cpu;
44pub mod disk;
45pub mod gauges;
46pub mod mem;
47pub mod net;
48pub mod pressure;
49pub mod process;
50mod sampler;
51
52use std::time::Duration;
53
54pub use cpu::CpuReading;
55pub use sampler::spawn;
56
57/// The category names, in the order they are listed to a user.
58pub const CATEGORY_NAMES: &[&str] = &[
59    "cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc",
60];
61
62/// Which categories a `sysmon=` setting enabled.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub struct Categories {
65    pub cpu: bool,
66    pub io: bool,
67    pub ram: bool,
68    pub rambw: bool,
69    pub storage: bool,
70    pub net: bool,
71    pub pressure: bool,
72    pub proc: bool,
73}
74
75impl Categories {
76    pub const ALL: Categories = Categories {
77        cpu: true,
78        io: true,
79        ram: true,
80        rambw: true,
81        storage: true,
82        net: true,
83        pressure: true,
84        proc: true,
85    };
86
87    pub fn any(&self) -> bool {
88        *self != Categories::default()
89    }
90
91    /// The flag a category name stands for.
92    fn flag(&mut self, name: &str) -> Option<&mut bool> {
93        Some(match name {
94            "cpu" => &mut self.cpu,
95            "io" => &mut self.io,
96            "ram" => &mut self.ram,
97            "rambw" => &mut self.rambw,
98            "storage" => &mut self.storage,
99            "net" => &mut self.net,
100            "pressure" => &mut self.pressure,
101            "proc" => &mut self.proc,
102            _ => return None,
103        })
104    }
105
106    /// The enabled categories' names, comma separated.
107    pub fn names(&self) -> String {
108        let mut copy = *self;
109        CATEGORY_NAMES
110            .iter()
111            .filter(|name| copy.flag(name).is_some_and(|on| *on))
112            .copied()
113            .collect::<Vec<_>>()
114            .join(",")
115    }
116}
117
118/// What a `sysmon=` value asked for: a fixed category set, or "whatever
119/// this host supports".
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Selection {
122    /// Named categories (including `all`): every one is REQUIRED, and an
123    /// unavailable subsystem aborts the session with instructions.
124    Cats(Categories),
125    /// `sysmon=any`: enable every available subsystem, skip-and-announce
126    /// the rest. The stated opt-in is what makes the skip acceptable.
127    Any,
128}
129
130/// Parse a `sysmon=` value: `all`, `any`, or a comma list of category
131/// names. Unknown names are errors that NAME the valid set — a typo
132/// silently monitoring nothing would be the failure mode this surface
133/// exists to avoid.
134pub fn parse_selection(value: &str) -> Result<Selection, String> {
135    let trimmed = value.trim();
136    if trimmed.eq_ignore_ascii_case("any") {
137        return Ok(Selection::Any);
138    }
139    if trimmed
140        .to_ascii_lowercase()
141        .split(',')
142        .any(|t| t.trim() == "any")
143    {
144        return Err("sysmon: `any` stands alone (it means \"every available \
145             subsystem\") — combining it with named categories is \
146             ambiguous. Use `sysmon=any`, or name the categories."
147            .to_string());
148    }
149    parse_categories(trimmed).map(Selection::Cats)
150}
151
152/// Parse a fixed category list (`all` or comma names). See
153/// [`parse_selection`] for the `any` form.
154pub fn parse_categories(value: &str) -> Result<Categories, String> {
155    if value.trim().eq_ignore_ascii_case("all") {
156        return Ok(Categories::ALL);
157    }
158    let valid = CATEGORY_NAMES.join(", ");
159    let mut cats = Categories::default();
160    for token in value.split(',') {
161        let name = token.trim().to_ascii_lowercase();
162        if name.is_empty() {
163            continue;
164        }
165        match cats.flag(&name) {
166            Some(flag) => *flag = true,
167            None => {
168                return Err(format!(
169                    "sysmon: unknown category '{name}'. Valid: all, any, or a \
170                     comma list of {valid}"
171                ));
172            }
173        }
174    }
175    if !cats.any() {
176        return Err(format!(
177            "sysmon: no categories enabled. Use `sysmon=all`, `sysmon=any` or a comma \
178             list of {valid}"
179        ));
180    }
181    Ok(cats)
182}
183
184/// One completed sample window. A field is `Some`, or a list is
185/// filled, exactly when its category was enabled and had a reading —
186/// a disabled category is absent, not zero.
187#[derive(Debug, Clone, PartialEq, Default)]
188pub struct SysmonSample {
189    pub cpu: Option<CpuReading>,
190    /// (device, utilization) — the busiest device this window.
191    pub io: Option<(String, f64)>,
192    /// Each whole device's throughput this window.
193    pub io_rates: Vec<disk::DiskRate>,
194    /// (committed, everything-including-page-cache).
195    pub ram: Option<(f64, f64)>,
196    /// Memory-bandwidth utilization against the configured peak.
197    pub rambw: Option<f64>,
198    /// (mount point, space utilization) — the fullest filesystem.
199    pub storage: Option<(String, f64)>,
200    /// Each interface's throughput this window.
201    pub net: Vec<net::NetRate>,
202    /// The stalled share of this window, by resource.
203    pub pressure: Option<pressure::PressureReading>,
204    /// Each watched process this window.
205    pub procs: Vec<process::ProcReading>,
206}
207
208/// Sampler configuration, resolved by the runner from session params.
209#[derive(Debug, Clone)]
210pub struct SysmonConfig {
211    pub cats: Categories,
212    /// Sample window. Default 5 s (`sysmon_interval=<seconds>`).
213    pub interval: Duration,
214    /// Peak memory bandwidth in bytes/s — the reference that turns rambw
215    /// bytes/s into a utilization. Required when `rambw` is enabled.
216    pub membw_peak_bytes_per_s: Option<f64>,
217    /// The processes `sysmon_procs=` names, besides nmbrs itself.
218    pub procs: Vec<process::ProcTarget>,
219}
220
221/// The sampler reads `/proc`, which only Linux has.
222pub const fn platform_supported() -> bool {
223    cfg!(target_os = "linux")
224}
225
226/// What the platform check says when it fails.
227pub const UNSUPPORTED_PLATFORM: &str = "sysmon: the sampler reads /proc and is available on \
228     Linux only; run without `sysmon=` on this host";
229
230/// The rambw prerequisites, checked BEFORE the session starts so an
231/// unsupported host aborts with instructions instead of silently monitoring
232/// less than was asked for.
233pub fn check_rambw_requirements(config: &SysmonConfig) -> Result<(), String> {
234    if !config.cats.rambw {
235        return Ok(());
236    }
237    if mem::read_membw_bytes().is_none() {
238        return Err("\
239sysmon: rambw was requested, but the kernel resctrl interface is not \
240available at /sys/fs/resctrl/mon_data.
241
242To enable memory-bandwidth monitoring:
243  1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
244     check for the `cqm_mbm_total` flag:  grep -m1 cqm_mbm_total /proc/cpuinfo
245  2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
246     mainstream distro kernels).
247  3. Mount the interface:  sudo mount -t resctrl resctrl /sys/fs/resctrl
248
249If this host cannot support it (most VMs cannot), name the categories \
250without rambw, or use  sysmon=any  to enable every subsystem this host \
251supports."
252            .to_string());
253    }
254    if config.membw_peak_bytes_per_s.is_none() {
255        return Err("\
256sysmon: rambw needs a peak-bandwidth reference to turn bytes/s into a \
257utilization. Set it with  sysmon_membw_gbps=<peak>  (the host's rated \
258memory bandwidth in GB/s), name the categories without rambw, or use  \
259sysmon=any"
260            .to_string());
261    }
262    Ok(())
263}
264
265/// The pressure prerequisite: the kernel's pressure stall files.
266pub fn check_pressure_requirements(config: &SysmonConfig) -> Result<(), String> {
267    if !config.cats.pressure || pressure::read_pressure().is_some() {
268        return Ok(());
269    }
270    Err("\
271sysmon: pressure was requested, but the kernel's pressure stall \
272information is not readable at /proc/pressure. It needs a kernel built \
273with CONFIG_PSI (4.20 or later) that was not booted with `psi=0`, and a \
274container must be given the host's /proc/pressure. Name the categories \
275without pressure, or use  sysmon=any  to enable every subsystem this \
276host supports."
277        .to_string())
278}
279
280/// Everything a named category needs of this host, checked before the
281/// session starts. `sysmon_procs=` without the `proc` category is
282/// refused here too: it would otherwise name processes nothing watches.
283pub fn check_requirements(config: &SysmonConfig) -> Result<(), String> {
284    if !platform_supported() {
285        return Err(UNSUPPORTED_PLATFORM.to_string());
286    }
287    if !config.procs.is_empty() && !config.cats.proc {
288        return Err(
289            "sysmon: `sysmon_procs=` names processes to watch, and the `proc` \
290             category is not enabled; add `proc` to `sysmon=`"
291                .to_string(),
292        );
293    }
294    check_rambw_requirements(config)?;
295    check_pressure_requirements(config)
296}
297
298/// Resolve `sysmon=any` against THIS host: every category the host
299/// supports, plus one human-readable line per category that had to be
300/// skipped and why. The /proc-backed categories are always available
301/// on Linux; rambw and pressure carry real prerequisites.
302///
303/// The skip lines exist because `any` is best-effort, not silent-effort:
304/// the runner logs each one, so a session that monitored six of eight
305/// categories says so.
306pub fn resolve_any(config: &SysmonConfig) -> (Categories, Vec<String>) {
307    if !platform_supported() {
308        return (
309            Categories::default(),
310            vec![UNSUPPORTED_PLATFORM.to_string()],
311        );
312    }
313    let mut cats = Categories::ALL;
314    let mut skipped = Vec::new();
315    let probe = SysmonConfig {
316        cats,
317        ..config.clone()
318    };
319    // First line of the full instructions — the one that names the
320    // missing prerequisite. Naming the category gets the complete text.
321    let first = |reason: String| reason.lines().next().unwrap_or("unavailable").to_string();
322    if let Err(reason) = check_rambw_requirements(&probe) {
323        cats.rambw = false;
324        skipped.push(format!(
325            "{} (run `sysmon=rambw` for the enable steps)",
326            first(reason)
327        ));
328    }
329    if let Err(reason) = check_pressure_requirements(&probe) {
330        cats.pressure = false;
331        skipped.push(format!(
332            "{} (run `sysmon=pressure` for the details)",
333            first(reason)
334        ));
335    }
336    (cats, skipped)
337}
338
339#[cfg(test)]
340mod tests;