Skip to main content

nmbrs_runtime/
sysmon_params.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sampler's session params (SRD-118 §2): `sysmon`,
5//! `sysmon_interval`, `sysmon_membw_gbps` and `sysmon_procs`, read
6//! from the session's params whether they came from the command line
7//! or from the workload's `params:`.
8
9use std::collections::HashMap;
10use std::sync::{Arc, RwLock};
11use std::time::Duration;
12
13use nmbrs_metrics::component::Component;
14
15use crate::sysmon::{self, Selection, SysmonConfig};
16
17/// The sampler's params.
18pub const PARAMS: &[&str] = &[
19    "sysmon",
20    "sysmon_interval",
21    "sysmon_membw_gbps",
22    "sysmon_procs",
23];
24
25/// The default sample window.
26const DEFAULT_INTERVAL: Duration = Duration::from_secs(5);
27
28/// A spelling these params had before they were given names a
29/// workload's `params:` can hold, and the name to write.
30const RETIRED: &[(&str, &str)] = &[
31    ("sysmon-interval", "sysmon_interval"),
32    ("sysmon-membw-gbps", "sysmon_membw_gbps"),
33];
34
35/// Read the sampler's params. `Ok(None)` when `sysmon` is not set.
36///
37/// Fails on a retired spelling, on a sampler param given without
38/// `sysmon`, and on a value that does not parse; each error names the
39/// param and what to write.
40pub fn read(params: &HashMap<String, String>) -> Result<Option<(Selection, SysmonConfig)>, String> {
41    for (retired, name) in RETIRED {
42        if params.contains_key(*retired) {
43            return Err(format!("`{retired}` is now `{name}`; write `{name}=…`"));
44        }
45    }
46    let Some(setting) = params.get("sysmon") else {
47        if let Some(orphan) = PARAMS[1..].iter().find(|p| params.contains_key(**p)) {
48            return Err(format!(
49                "`{orphan}` is set and `sysmon` is not, so nothing would be sampled; \
50                 add `sysmon=any` or name the categories"
51            ));
52        }
53        return Ok(None);
54    };
55    let selection = sysmon::parse_selection(setting)?;
56    let interval = match params.get("sysmon_interval") {
57        None => DEFAULT_INTERVAL,
58        Some(v) => match v.trim_end_matches('s').parse::<f64>() {
59            Ok(secs) if secs > 0.0 => Duration::from_secs_f64(secs),
60            _ => {
61                return Err(format!(
62                    "sysmon_interval: expected seconds (e.g. `sysmon_interval=5`), got '{v}'"
63                ));
64            }
65        },
66    };
67    let membw_peak_bytes_per_s = match params.get("sysmon_membw_gbps") {
68        None => None,
69        Some(v) => match v.parse::<f64>() {
70            Ok(gbps) if gbps > 0.0 => Some(gbps * 1e9),
71            _ => {
72                return Err(format!(
73                    "sysmon_membw_gbps: expected the host's peak memory bandwidth \
74                     in GB/s, got '{v}'"
75                ));
76            }
77        },
78    };
79    let procs = match params.get("sysmon_procs") {
80        None => Vec::new(),
81        Some(v) => sysmon::process::parse_procs(v)?,
82    };
83    let cats = match selection {
84        Selection::Cats(cats) => cats,
85        // Decided against the host by `start`.
86        Selection::Any => sysmon::Categories::ALL,
87    };
88    Ok(Some((
89        selection,
90        SysmonConfig {
91            cats,
92            interval,
93            membw_peak_bytes_per_s,
94            procs,
95        },
96    )))
97}
98
99/// Start the sampler the session's params ask for, if they ask for
100/// one. Must be called inside the session's runtime.
101pub fn start(
102    params: &HashMap<String, String>,
103    component: &Arc<RwLock<Component>>,
104    observer: &Arc<dyn crate::observer::RunObserver>,
105) -> Result<(), String> {
106    let Some((selection, mut config)) = read(params)? else {
107        return Ok(());
108    };
109    match selection {
110        // `any` — best-effort by stated request: enable what the host
111        // supports and ANNOUNCE each skip, one line per subsystem.
112        Selection::Any => {
113            let (cats, skipped) = sysmon::resolve_any(&config);
114            config.cats = cats;
115            for reason in skipped {
116                crate::diag!(
117                    crate::observer::LogLevel::Warn,
118                    "sysmon: skipping a subsystem: {reason}"
119                );
120            }
121            if !cats.any() {
122                return Ok(());
123            }
124        }
125        // Named categories are REQUIRED: the gate runs before spawn so
126        // an unsupported host is a clean session abort with
127        // instructions. The session directory already exists at this
128        // point — the same is true of every config error raised from
129        // here, and the next run gets its own directory.
130        Selection::Cats(_) => sysmon::check_requirements(&config)?,
131    }
132    let (names, interval) = (config.cats.names(), config.interval);
133    sysmon::spawn(config, component.clone(), observer.clone())?;
134    crate::diag!(
135        crate::observer::LogLevel::Info,
136        "sysmon: sampling {names} every {interval:?}"
137    );
138    Ok(())
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    fn params(pairs: &[(&str, &str)]) -> HashMap<String, String> {
146        pairs
147            .iter()
148            .map(|(k, v)| (k.to_string(), v.to_string()))
149            .collect()
150    }
151
152    #[test]
153    fn no_sysmon_param_is_no_sampler() {
154        assert!(read(&params(&[("cycles", "10")])).unwrap().is_none());
155    }
156
157    #[test]
158    fn the_params_are_read_with_their_defaults() {
159        let (selection, config) = read(&params(&[("sysmon", "cpu,proc")])).unwrap().unwrap();
160        assert!(matches!(selection, Selection::Cats(c) if c.cpu && c.proc && !c.io));
161        assert_eq!(config.interval, DEFAULT_INTERVAL);
162        assert!(config.procs.is_empty() && config.membw_peak_bytes_per_s.is_none());
163
164        let (_, config) = read(&params(&[
165            ("sysmon", "any"),
166            ("sysmon_interval", "0.5"),
167            ("sysmon_membw_gbps", "80"),
168            ("sysmon_procs", "server:42"),
169        ]))
170        .unwrap()
171        .unwrap();
172        assert_eq!(config.interval, Duration::from_millis(500));
173        assert_eq!(config.membw_peak_bytes_per_s, Some(80e9));
174        assert_eq!(config.procs.len(), 1);
175    }
176
177    #[test]
178    fn a_retired_spelling_is_refused_with_the_name_to_write() {
179        let err = read(&params(&[("sysmon", "cpu"), ("sysmon-interval", "1")])).unwrap_err();
180        assert_eq!(
181            err,
182            "`sysmon-interval` is now `sysmon_interval`; write `sysmon_interval=…`"
183        );
184        let err = read(&params(&[("sysmon-membw-gbps", "80")])).unwrap_err();
185        assert!(err.contains("`sysmon_membw_gbps`"), "{err}");
186    }
187
188    #[test]
189    fn a_sampler_param_without_sysmon_is_refused() {
190        let err = read(&params(&[("sysmon_interval", "1")])).unwrap_err();
191        assert!(
192            err.contains("`sysmon_interval` is set and `sysmon` is not"),
193            "{err}"
194        );
195    }
196
197    #[test]
198    fn a_value_that_does_not_parse_names_its_param() {
199        for (key, value) in [
200            ("sysmon_interval", "soon"),
201            ("sysmon_interval", "0"),
202            ("sysmon_membw_gbps", "fast"),
203            ("sysmon_procs", "server"),
204        ] {
205            let err = read(&params(&[("sysmon", "cpu"), (key, value)])).unwrap_err();
206            assert!(err.contains(key), "{key}={value}: {err}");
207        }
208    }
209}