nmbrs-runtime 0.7.3

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

//! The sampler's session params (SRD-118 §2): `sysmon`,
//! `sysmon_interval`, `sysmon_membw_gbps`, `sysmon_procs` and
//! `sysmon_cgroups`, read from the session's params whether they came
//! from the command line or from the workload's `params:`.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use nmbrs_metrics::component::Component;

use nmbrs_host::category::Categories;

use crate::sysmon::{self, Selection, SysmonConfig};

/// The sampler's params.
pub const PARAMS: &[&str] = &[
    "sysmon",
    "sysmon_interval",
    "sysmon_membw_gbps",
    "sysmon_procs",
    "sysmon_cgroups",
];

/// The default sample window.
const DEFAULT_INTERVAL: Duration = Duration::from_secs(5);

/// A spelling these params had before they were given names a
/// workload's `params:` can hold, and the name to write.
const RETIRED: &[(&str, &str)] = &[
    ("sysmon-interval", "sysmon_interval"),
    ("sysmon-membw-gbps", "sysmon_membw_gbps"),
];

/// Read the sampler's params. `Ok(None)` when `sysmon` is not set.
///
/// Fails on a retired spelling, on a sampler param given without
/// `sysmon`, and on a value that does not parse; each error names the
/// param and what to write.
pub fn read(params: &HashMap<String, String>) -> Result<Option<(Selection, SysmonConfig)>, String> {
    for (retired, name) in RETIRED {
        if params.contains_key(*retired) {
            return Err(format!("`{retired}` is now `{name}`; write `{name}=…`"));
        }
    }
    let Some(setting) = params.get("sysmon") else {
        if let Some(orphan) = PARAMS[1..].iter().find(|p| params.contains_key(**p)) {
            return Err(format!(
                "`{orphan}` is set and `sysmon` is not, so nothing would be sampled; \
                 add `sysmon=any` or name the categories"
            ));
        }
        return Ok(None);
    };
    let selection = sysmon::parse_selection(setting)?;
    let interval = match params.get("sysmon_interval") {
        None => DEFAULT_INTERVAL,
        Some(v) => match v.trim_end_matches('s').parse::<f64>() {
            Ok(secs) if secs > 0.0 => Duration::from_secs_f64(secs),
            _ => {
                return Err(format!(
                    "sysmon_interval: expected seconds (e.g. `sysmon_interval=5`), got '{v}'"
                ));
            }
        },
    };
    let membw_peak_bytes_per_s = match params.get("sysmon_membw_gbps") {
        None => None,
        Some(v) => match v.parse::<f64>() {
            Ok(gbps) if gbps > 0.0 => Some(gbps * 1e9),
            _ => {
                return Err(format!(
                    "sysmon_membw_gbps: expected the host's peak memory bandwidth \
                     in GB/s, got '{v}'"
                ));
            }
        },
    };
    let procs = match params.get("sysmon_procs") {
        None => Vec::new(),
        Some(v) => nmbrs_host::process::parse_procs(v).map_err(|e| format!("sysmon_procs: {e}"))?,
    };
    let cgroups = match params.get("sysmon_cgroups") {
        None => Vec::new(),
        Some(v) => {
            nmbrs_host::cgroup::parse_cgroups(v).map_err(|e| format!("sysmon_cgroups: {e}"))?
        }
    };
    // `cgroup` asked for by name has to have something to watch. Under
    // `all` and `any` it is on with the rest, and `start` says when it
    // watches nothing.
    let named_cgroup = setting
        .split(',')
        .any(|token| token.trim().eq_ignore_ascii_case("cgroup"));
    if named_cgroup && cgroups.is_empty() {
        return Err(
            "sysmon: the `cgroup` category watches the control groups `sysmon_cgroups=` \
             names, and none is named; write `sysmon_cgroups=<name>:<path>` (the path of \
             a group under /sys/fs/cgroup)"
                .to_string(),
        );
    }
    let cats = match selection {
        Selection::Cats(cats) => cats,
        // Decided against the host by `start`.
        Selection::Any => Categories::ALL,
    };
    Ok(Some((
        selection,
        SysmonConfig {
            cats,
            interval,
            membw_peak_bytes_per_s,
            procs,
            cgroups,
        },
    )))
}

/// Start the sampler the session's params ask for, if they ask for
/// one. Must be called inside the session's runtime.
pub fn start(
    params: &HashMap<String, String>,
    component: &Arc<RwLock<Component>>,
    observer: &Arc<dyn crate::observer::RunObserver>,
) -> Result<(), String> {
    let Some((selection, mut config)) = read(params)? else {
        return Ok(());
    };
    match selection {
        // `any` — best-effort by stated request: enable what the host
        // supports and ANNOUNCE each skip, one line per subsystem.
        Selection::Any => {
            let (cats, skipped) = sysmon::resolve_any(&config);
            config.cats = cats;
            for reason in skipped {
                crate::diag!(
                    crate::observer::LogLevel::Warn,
                    "sysmon: skipping a subsystem: {reason}"
                );
            }
            if !cats.any() {
                return Ok(());
            }
        }
        // Named categories are REQUIRED: the gate runs before spawn so
        // an unsupported host is a clean session abort with
        // instructions. The session directory already exists at this
        // point — the same is true of every config error raised from
        // here, and the next run gets its own directory.
        Selection::Cats(_) => sysmon::check_requirements(&config)?,
    }
    if config.cats.cgroup && config.cgroups.is_empty() {
        crate::diag!(
            crate::observer::LogLevel::Info,
            "sysmon: the cgroup category has no control group to watch; name them with \
             `sysmon_cgroups=<name>:<path>`"
        );
    }
    let (names, interval) = (config.cats.names(), config.interval);
    sysmon::spawn(config, component.clone(), observer.clone())?;
    crate::diag!(
        crate::observer::LogLevel::Info,
        "sysmon: sampling {names} every {interval:?}"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn params(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn no_sysmon_param_is_no_sampler() {
        assert!(read(&params(&[("cycles", "10")])).unwrap().is_none());
    }

    #[test]
    fn the_params_are_read_with_their_defaults() {
        let (selection, config) = read(&params(&[("sysmon", "cpu,proc")])).unwrap().unwrap();
        assert!(matches!(selection, Selection::Cats(c) if c.cpu && c.proc && !c.io));
        assert_eq!(config.interval, DEFAULT_INTERVAL);
        assert!(config.procs.is_empty() && config.membw_peak_bytes_per_s.is_none());

        let (_, config) = read(&params(&[
            ("sysmon", "any"),
            ("sysmon_interval", "0.5"),
            ("sysmon_membw_gbps", "80"),
            ("sysmon_procs", "server:42"),
            ("sysmon_cgroups", "node:system.slice/db.service"),
        ]))
        .unwrap()
        .unwrap();
        assert_eq!(config.interval, Duration::from_millis(500));
        assert_eq!(config.membw_peak_bytes_per_s, Some(80e9));
        assert_eq!(config.procs.len(), 1);
        assert_eq!(
            config.cgroups[0].dir,
            std::path::PathBuf::from("/sys/fs/cgroup/system.slice/db.service")
        );
    }

    /// `cgroup` named with nothing to watch is refused; under `all` it
    /// is on with the rest.
    #[test]
    fn a_named_cgroup_category_needs_a_group() {
        let err = read(&params(&[("sysmon", "cpu,cgroup")])).unwrap_err();
        assert!(err.contains("sysmon_cgroups=<name>:<path>"), "{err}");
        let (_, config) = read(&params(&[("sysmon", "all")])).unwrap().unwrap();
        assert!(config.cats.cgroup && config.cgroups.is_empty());
    }

    #[test]
    fn a_retired_spelling_is_refused_with_the_name_to_write() {
        let err = read(&params(&[("sysmon", "cpu"), ("sysmon-interval", "1")])).unwrap_err();
        assert_eq!(
            err,
            "`sysmon-interval` is now `sysmon_interval`; write `sysmon_interval=…`"
        );
        let err = read(&params(&[("sysmon-membw-gbps", "80")])).unwrap_err();
        assert!(err.contains("`sysmon_membw_gbps`"), "{err}");
    }

    #[test]
    fn a_sampler_param_without_sysmon_is_refused() {
        let err = read(&params(&[("sysmon_interval", "1")])).unwrap_err();
        assert!(
            err.contains("`sysmon_interval` is set and `sysmon` is not"),
            "{err}"
        );
    }

    #[test]
    fn a_value_that_does_not_parse_names_its_param() {
        for (key, value) in [
            ("sysmon_interval", "soon"),
            ("sysmon_interval", "0"),
            ("sysmon_membw_gbps", "fast"),
            ("sysmon_procs", "server"),
            ("sysmon_cgroups", "node"),
        ] {
            let err = read(&params(&[("sysmon", "cpu"), (key, value)])).unwrap_err();
            assert!(err.contains(key), "{key}={value}: {err}");
        }
    }
}