nmbrs-runtime 0.7.2

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Session-level system-performance sampler (SRD-118).
//!
//! Enabled per session with `sysmon=<categories>`: `sysmon=all`,
//! `sysmon=any`, or a comma list of category names. `all` and `any`
//! differ in exactly one way: `all` ABORTS when a subsystem is
//! unavailable, `any` enables what the host supports and NAMES what it
//! skipped. Reads `/proc` (and statvfs) on a fixed interval (default
//! 5 s, `sysmon_interval=<seconds>`) and publishes host-side measures
//! as session-scoped gauges plus a live observer callback for display
//! surfaces: measurement of the machine under the workload, not of the
//! workload.
//!
//! The categories, each in its own module:
//!
//! - **cpu** ([`cpu`]): mean utilization, the hottest core, and the
//!   quartiles of the per-core distribution.
//! - **io** ([`disk`]): how busy the busiest device is, and each whole
//!   device's read and write throughput.
//! - **ram** ([`mem`]): memory committed, and memory touched (page
//!   cache included).
//! - **rambw** ([`mem`]): memory bandwidth against a stated peak, from
//!   resctrl.
//! - **storage** ([`disk`]): how full the fullest writable filesystem
//!   is.
//! - **net** ([`net`]): each interface's receive and transmit
//!   throughput.
//! - **pressure** ([`pressure`]): the share of time tasks were stalled
//!   for want of CPU, memory or I/O.
//! - **proc** ([`process`]): CPU, memory, threads and storage I/O of
//!   nmbrs itself and of each process `sysmon_procs=` names.
//!
//! Counters are cumulative, so every rate here is a pairwise delta
//! over the sample window; the published gauge is the latest window's
//! value and any windowing beyond that belongs to MetricsQL at query
//! time.
//!
//! The parsers read strings, so the arithmetic is tested on fixtures;
//! only the sampler and the `read_*` functions touch the filesystem.

pub mod cpu;
pub mod disk;
pub mod gauges;
pub mod mem;
pub mod net;
pub mod pressure;
pub mod process;
mod sampler;

use std::time::Duration;

pub use cpu::CpuReading;
pub use sampler::spawn;

/// The category names, in the order they are listed to a user.
pub const CATEGORY_NAMES: &[&str] = &[
    "cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc",
];

/// Which categories a `sysmon=` setting enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Categories {
    pub cpu: bool,
    pub io: bool,
    pub ram: bool,
    pub rambw: bool,
    pub storage: bool,
    pub net: bool,
    pub pressure: bool,
    pub proc: bool,
}

impl Categories {
    pub const ALL: Categories = Categories {
        cpu: true,
        io: true,
        ram: true,
        rambw: true,
        storage: true,
        net: true,
        pressure: true,
        proc: true,
    };

    pub fn any(&self) -> bool {
        *self != Categories::default()
    }

    /// The flag a category name stands for.
    fn flag(&mut self, name: &str) -> Option<&mut bool> {
        Some(match name {
            "cpu" => &mut self.cpu,
            "io" => &mut self.io,
            "ram" => &mut self.ram,
            "rambw" => &mut self.rambw,
            "storage" => &mut self.storage,
            "net" => &mut self.net,
            "pressure" => &mut self.pressure,
            "proc" => &mut self.proc,
            _ => return None,
        })
    }

    /// The enabled categories' names, comma separated.
    pub fn names(&self) -> String {
        let mut copy = *self;
        CATEGORY_NAMES
            .iter()
            .filter(|name| copy.flag(name).is_some_and(|on| *on))
            .copied()
            .collect::<Vec<_>>()
            .join(",")
    }
}

/// What a `sysmon=` value asked for: a fixed category set, or "whatever
/// this host supports".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Selection {
    /// Named categories (including `all`): every one is REQUIRED, and an
    /// unavailable subsystem aborts the session with instructions.
    Cats(Categories),
    /// `sysmon=any`: enable every available subsystem, skip-and-announce
    /// the rest. The stated opt-in is what makes the skip acceptable.
    Any,
}

/// Parse a `sysmon=` value: `all`, `any`, or a comma list of category
/// names. Unknown names are errors that NAME the valid set — a typo
/// silently monitoring nothing would be the failure mode this surface
/// exists to avoid.
pub fn parse_selection(value: &str) -> Result<Selection, String> {
    let trimmed = value.trim();
    if trimmed.eq_ignore_ascii_case("any") {
        return Ok(Selection::Any);
    }
    if trimmed
        .to_ascii_lowercase()
        .split(',')
        .any(|t| t.trim() == "any")
    {
        return Err("sysmon: `any` stands alone (it means \"every available \
             subsystem\") — combining it with named categories is \
             ambiguous. Use `sysmon=any`, or name the categories."
            .to_string());
    }
    parse_categories(trimmed).map(Selection::Cats)
}

/// Parse a fixed category list (`all` or comma names). See
/// [`parse_selection`] for the `any` form.
pub fn parse_categories(value: &str) -> Result<Categories, String> {
    if value.trim().eq_ignore_ascii_case("all") {
        return Ok(Categories::ALL);
    }
    let valid = CATEGORY_NAMES.join(", ");
    let mut cats = Categories::default();
    for token in value.split(',') {
        let name = token.trim().to_ascii_lowercase();
        if name.is_empty() {
            continue;
        }
        match cats.flag(&name) {
            Some(flag) => *flag = true,
            None => {
                return Err(format!(
                    "sysmon: unknown category '{name}'. Valid: all, any, or a \
                     comma list of {valid}"
                ));
            }
        }
    }
    if !cats.any() {
        return Err(format!(
            "sysmon: no categories enabled. Use `sysmon=all`, `sysmon=any` or a comma \
             list of {valid}"
        ));
    }
    Ok(cats)
}

/// One completed sample window. A field is `Some`, or a list is
/// filled, exactly when its category was enabled and had a reading —
/// a disabled category is absent, not zero.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SysmonSample {
    pub cpu: Option<CpuReading>,
    /// (device, utilization) — the busiest device this window.
    pub io: Option<(String, f64)>,
    /// Each whole device's throughput this window.
    pub io_rates: Vec<disk::DiskRate>,
    /// (committed, everything-including-page-cache).
    pub ram: Option<(f64, f64)>,
    /// Memory-bandwidth utilization against the configured peak.
    pub rambw: Option<f64>,
    /// (mount point, space utilization) — the fullest filesystem.
    pub storage: Option<(String, f64)>,
    /// Each interface's throughput this window.
    pub net: Vec<net::NetRate>,
    /// The stalled share of this window, by resource.
    pub pressure: Option<pressure::PressureReading>,
    /// Each watched process this window.
    pub procs: Vec<process::ProcReading>,
}

/// Sampler configuration, resolved by the runner from session params.
#[derive(Debug, Clone)]
pub struct SysmonConfig {
    pub cats: Categories,
    /// Sample window. Default 5 s (`sysmon_interval=<seconds>`).
    pub interval: Duration,
    /// Peak memory bandwidth in bytes/s — the reference that turns rambw
    /// bytes/s into a utilization. Required when `rambw` is enabled.
    pub membw_peak_bytes_per_s: Option<f64>,
    /// The processes `sysmon_procs=` names, besides nmbrs itself.
    pub procs: Vec<process::ProcTarget>,
}

/// The sampler reads `/proc`, which only Linux has.
pub const fn platform_supported() -> bool {
    cfg!(target_os = "linux")
}

/// What the platform check says when it fails.
pub const UNSUPPORTED_PLATFORM: &str = "sysmon: the sampler reads /proc and is available on \
     Linux only; run without `sysmon=` on this host";

/// The rambw prerequisites, checked BEFORE the session starts so an
/// unsupported host aborts with instructions instead of silently monitoring
/// less than was asked for.
pub fn check_rambw_requirements(config: &SysmonConfig) -> Result<(), String> {
    if !config.cats.rambw {
        return Ok(());
    }
    if mem::read_membw_bytes().is_none() {
        return Err("\
sysmon: rambw was requested, but the kernel resctrl interface is not \
available at /sys/fs/resctrl/mon_data.

To enable memory-bandwidth monitoring:
  1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
     check for the `cqm_mbm_total` flag:  grep -m1 cqm_mbm_total /proc/cpuinfo
  2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
     mainstream distro kernels).
  3. Mount the interface:  sudo mount -t resctrl resctrl /sys/fs/resctrl

If this host cannot support it (most VMs cannot), name the categories \
without rambw, or use  sysmon=any  to enable every subsystem this host \
supports."
            .to_string());
    }
    if config.membw_peak_bytes_per_s.is_none() {
        return Err("\
sysmon: rambw needs a peak-bandwidth reference to turn bytes/s into a \
utilization. Set it with  sysmon_membw_gbps=<peak>  (the host's rated \
memory bandwidth in GB/s), name the categories without rambw, or use  \
sysmon=any"
            .to_string());
    }
    Ok(())
}

/// The pressure prerequisite: the kernel's pressure stall files.
pub fn check_pressure_requirements(config: &SysmonConfig) -> Result<(), String> {
    if !config.cats.pressure || pressure::read_pressure().is_some() {
        return Ok(());
    }
    Err("\
sysmon: pressure was requested, but the kernel's pressure stall \
information is not readable at /proc/pressure. It needs a kernel built \
with CONFIG_PSI (4.20 or later) that was not booted with `psi=0`, and a \
container must be given the host's /proc/pressure. Name the categories \
without pressure, or use  sysmon=any  to enable every subsystem this \
host supports."
        .to_string())
}

/// Everything a named category needs of this host, checked before the
/// session starts. `sysmon_procs=` without the `proc` category is
/// refused here too: it would otherwise name processes nothing watches.
pub fn check_requirements(config: &SysmonConfig) -> Result<(), String> {
    if !platform_supported() {
        return Err(UNSUPPORTED_PLATFORM.to_string());
    }
    if !config.procs.is_empty() && !config.cats.proc {
        return Err(
            "sysmon: `sysmon_procs=` names processes to watch, and the `proc` \
             category is not enabled; add `proc` to `sysmon=`"
                .to_string(),
        );
    }
    check_rambw_requirements(config)?;
    check_pressure_requirements(config)
}

/// Resolve `sysmon=any` against THIS host: every category the host
/// supports, plus one human-readable line per category that had to be
/// skipped and why. The /proc-backed categories are always available
/// on Linux; rambw and pressure carry real prerequisites.
///
/// The skip lines exist because `any` is best-effort, not silent-effort:
/// the runner logs each one, so a session that monitored six of eight
/// categories says so.
pub fn resolve_any(config: &SysmonConfig) -> (Categories, Vec<String>) {
    if !platform_supported() {
        return (
            Categories::default(),
            vec![UNSUPPORTED_PLATFORM.to_string()],
        );
    }
    let mut cats = Categories::ALL;
    let mut skipped = Vec::new();
    let probe = SysmonConfig {
        cats,
        ..config.clone()
    };
    // First line of the full instructions — the one that names the
    // missing prerequisite. Naming the category gets the complete text.
    let first = |reason: String| reason.lines().next().unwrap_or("unavailable").to_string();
    if let Err(reason) = check_rambw_requirements(&probe) {
        cats.rambw = false;
        skipped.push(format!(
            "{} (run `sysmon=rambw` for the enable steps)",
            first(reason)
        ));
    }
    if let Err(reason) = check_pressure_requirements(&probe) {
        cats.pressure = false;
        skipped.push(format!(
            "{} (run `sysmon=pressure` for the details)",
            first(reason)
        ));
    }
    (cats, skipped)
}

#[cfg(test)]
mod tests;