nmbrs-runtime 0.7.3

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 host is read through `nmbrs-host` (SRD-118 ยง9), which holds
//! each category's counters, parser and arithmetic. This module holds
//! what makes those readings a session's sampler: the `sysmon=`
//! setting, what it requires of the session, the sample a window
//! yields, the gauges and the task.
//!
//! 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.

pub mod gauges;
mod sampler;

use std::time::Duration;

use nmbrs_host::category::{CATEGORY_NAMES, Categories, platform_supported, unavailable};
use nmbrs_host::{cgroup, cpu, disk, net, pressure, process};

pub use sampler::spawn;

/// 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;
        }
        cats.add(&name).map_err(|name| {
            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<cpu::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>,
    /// Each watched control group this window.
    pub cgroups: Vec<cgroup::CgroupReading>,
}

/// 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 control groups `sysmon_cgroups=` names.
    pub cgroups: Vec<cgroup::CgroupTarget>,
}

/// 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";

/// What a category that was asked for by name says when this host
/// cannot supply it: the host's reason, and how to run without it.
fn required(category: &str, reason: String) -> String {
    format!(
        "sysmon: {category} was requested, but {reason}\n\n\
         Name the categories without {category}, or use  sysmon=any  to enable \
         every subsystem this host supports."
    )
}

/// 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 let Some(reason) = unavailable("rambw") {
        return Err(required("rambw", reason));
    }
    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(())
}

/// A category whose only prerequisite is the host's: `pressure` and
/// `cgroup`.
fn check_host_requirement(config: &SysmonConfig, category: &str) -> Result<(), String> {
    if !config.cats.has(category) {
        return Ok(());
    }
    match unavailable(category) {
        Some(reason) => Err(required(category, reason)),
        None => Ok(()),
    }
}

/// Everything a named category needs of this host, checked before the
/// session starts. `sysmon_procs=` without the `proc` category, and
/// `sysmon_cgroups=` without `cgroup`, are refused here too: each
/// would otherwise name something 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(),
        );
    }
    if !config.cgroups.is_empty() && !config.cats.cgroup {
        return Err(
            "sysmon: `sysmon_cgroups=` names control groups to watch, and the \
             `cgroup` category is not enabled; add `cgroup` to `sysmon=`"
                .to_string(),
        );
    }
    check_rambw_requirements(config)?;
    check_host_requirement(config, "pressure")?;
    check_host_requirement(config, "cgroup")
}

/// 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, pressure and cgroup 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 nine
/// 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)
        ));
    }
    for (category, on) in [
        ("pressure", &mut cats.pressure),
        ("cgroup", &mut cats.cgroup),
    ] {
        if let Err(reason) = check_host_requirement(&probe, category) {
            *on = false;
            skipped.push(format!(
                "{} (run `sysmon={category}` for the details)",
                first(reason)
            ));
        }
    }
    (cats, skipped)
}

#[cfg(test)]
mod tests;