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`, `sysmon_procs` and
6//! `sysmon_cgroups`, read from the session's params whether they came
7//! from the command line 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 nmbrs_host::category::Categories;
16
17use crate::sysmon::{self, Selection, SysmonConfig};
18
19/// The sampler's params.
20pub const PARAMS: &[&str] = &[
21    "sysmon",
22    "sysmon_interval",
23    "sysmon_membw_gbps",
24    "sysmon_procs",
25    "sysmon_cgroups",
26];
27
28/// The default sample window.
29const DEFAULT_INTERVAL: Duration = Duration::from_secs(5);
30
31/// A spelling these params had before they were given names a
32/// workload's `params:` can hold, and the name to write.
33const RETIRED: &[(&str, &str)] = &[
34    ("sysmon-interval", "sysmon_interval"),
35    ("sysmon-membw-gbps", "sysmon_membw_gbps"),
36];
37
38/// Read the sampler's params. `Ok(None)` when `sysmon` is not set.
39///
40/// Fails on a retired spelling, on a sampler param given without
41/// `sysmon`, and on a value that does not parse; each error names the
42/// param and what to write.
43pub fn read(params: &HashMap<String, String>) -> Result<Option<(Selection, SysmonConfig)>, String> {
44    for (retired, name) in RETIRED {
45        if params.contains_key(*retired) {
46            return Err(format!("`{retired}` is now `{name}`; write `{name}=…`"));
47        }
48    }
49    let Some(setting) = params.get("sysmon") else {
50        if let Some(orphan) = PARAMS[1..].iter().find(|p| params.contains_key(**p)) {
51            return Err(format!(
52                "`{orphan}` is set and `sysmon` is not, so nothing would be sampled; \
53                 add `sysmon=any` or name the categories"
54            ));
55        }
56        return Ok(None);
57    };
58    let selection = sysmon::parse_selection(setting)?;
59    let interval = match params.get("sysmon_interval") {
60        None => DEFAULT_INTERVAL,
61        Some(v) => match v.trim_end_matches('s').parse::<f64>() {
62            Ok(secs) if secs > 0.0 => Duration::from_secs_f64(secs),
63            _ => {
64                return Err(format!(
65                    "sysmon_interval: expected seconds (e.g. `sysmon_interval=5`), got '{v}'"
66                ));
67            }
68        },
69    };
70    let membw_peak_bytes_per_s = match params.get("sysmon_membw_gbps") {
71        None => None,
72        Some(v) => match v.parse::<f64>() {
73            Ok(gbps) if gbps > 0.0 => Some(gbps * 1e9),
74            _ => {
75                return Err(format!(
76                    "sysmon_membw_gbps: expected the host's peak memory bandwidth \
77                     in GB/s, got '{v}'"
78                ));
79            }
80        },
81    };
82    let procs = match params.get("sysmon_procs") {
83        None => Vec::new(),
84        Some(v) => nmbrs_host::process::parse_procs(v).map_err(|e| format!("sysmon_procs: {e}"))?,
85    };
86    let cgroups = match params.get("sysmon_cgroups") {
87        None => Vec::new(),
88        Some(v) => {
89            nmbrs_host::cgroup::parse_cgroups(v).map_err(|e| format!("sysmon_cgroups: {e}"))?
90        }
91    };
92    // `cgroup` asked for by name has to have something to watch. Under
93    // `all` and `any` it is on with the rest, and `start` says when it
94    // watches nothing.
95    let named_cgroup = setting
96        .split(',')
97        .any(|token| token.trim().eq_ignore_ascii_case("cgroup"));
98    if named_cgroup && cgroups.is_empty() {
99        return Err(
100            "sysmon: the `cgroup` category watches the control groups `sysmon_cgroups=` \
101             names, and none is named; write `sysmon_cgroups=<name>:<path>` (the path of \
102             a group under /sys/fs/cgroup)"
103                .to_string(),
104        );
105    }
106    let cats = match selection {
107        Selection::Cats(cats) => cats,
108        // Decided against the host by `start`.
109        Selection::Any => Categories::ALL,
110    };
111    Ok(Some((
112        selection,
113        SysmonConfig {
114            cats,
115            interval,
116            membw_peak_bytes_per_s,
117            procs,
118            cgroups,
119        },
120    )))
121}
122
123/// Start the sampler the session's params ask for, if they ask for
124/// one. Must be called inside the session's runtime.
125pub fn start(
126    params: &HashMap<String, String>,
127    component: &Arc<RwLock<Component>>,
128    observer: &Arc<dyn crate::observer::RunObserver>,
129) -> Result<(), String> {
130    let Some((selection, mut config)) = read(params)? else {
131        return Ok(());
132    };
133    match selection {
134        // `any` — best-effort by stated request: enable what the host
135        // supports and ANNOUNCE each skip, one line per subsystem.
136        Selection::Any => {
137            let (cats, skipped) = sysmon::resolve_any(&config);
138            config.cats = cats;
139            for reason in skipped {
140                crate::diag!(
141                    crate::observer::LogLevel::Warn,
142                    "sysmon: skipping a subsystem: {reason}"
143                );
144            }
145            if !cats.any() {
146                return Ok(());
147            }
148        }
149        // Named categories are REQUIRED: the gate runs before spawn so
150        // an unsupported host is a clean session abort with
151        // instructions. The session directory already exists at this
152        // point — the same is true of every config error raised from
153        // here, and the next run gets its own directory.
154        Selection::Cats(_) => sysmon::check_requirements(&config)?,
155    }
156    if config.cats.cgroup && config.cgroups.is_empty() {
157        crate::diag!(
158            crate::observer::LogLevel::Info,
159            "sysmon: the cgroup category has no control group to watch; name them with \
160             `sysmon_cgroups=<name>:<path>`"
161        );
162    }
163    let (names, interval) = (config.cats.names(), config.interval);
164    sysmon::spawn(config, component.clone(), observer.clone())?;
165    crate::diag!(
166        crate::observer::LogLevel::Info,
167        "sysmon: sampling {names} every {interval:?}"
168    );
169    Ok(())
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn params(pairs: &[(&str, &str)]) -> HashMap<String, String> {
177        pairs
178            .iter()
179            .map(|(k, v)| (k.to_string(), v.to_string()))
180            .collect()
181    }
182
183    #[test]
184    fn no_sysmon_param_is_no_sampler() {
185        assert!(read(&params(&[("cycles", "10")])).unwrap().is_none());
186    }
187
188    #[test]
189    fn the_params_are_read_with_their_defaults() {
190        let (selection, config) = read(&params(&[("sysmon", "cpu,proc")])).unwrap().unwrap();
191        assert!(matches!(selection, Selection::Cats(c) if c.cpu && c.proc && !c.io));
192        assert_eq!(config.interval, DEFAULT_INTERVAL);
193        assert!(config.procs.is_empty() && config.membw_peak_bytes_per_s.is_none());
194
195        let (_, config) = read(&params(&[
196            ("sysmon", "any"),
197            ("sysmon_interval", "0.5"),
198            ("sysmon_membw_gbps", "80"),
199            ("sysmon_procs", "server:42"),
200            ("sysmon_cgroups", "node:system.slice/db.service"),
201        ]))
202        .unwrap()
203        .unwrap();
204        assert_eq!(config.interval, Duration::from_millis(500));
205        assert_eq!(config.membw_peak_bytes_per_s, Some(80e9));
206        assert_eq!(config.procs.len(), 1);
207        assert_eq!(
208            config.cgroups[0].dir,
209            std::path::PathBuf::from("/sys/fs/cgroup/system.slice/db.service")
210        );
211    }
212
213    /// `cgroup` named with nothing to watch is refused; under `all` it
214    /// is on with the rest.
215    #[test]
216    fn a_named_cgroup_category_needs_a_group() {
217        let err = read(&params(&[("sysmon", "cpu,cgroup")])).unwrap_err();
218        assert!(err.contains("sysmon_cgroups=<name>:<path>"), "{err}");
219        let (_, config) = read(&params(&[("sysmon", "all")])).unwrap().unwrap();
220        assert!(config.cats.cgroup && config.cgroups.is_empty());
221    }
222
223    #[test]
224    fn a_retired_spelling_is_refused_with_the_name_to_write() {
225        let err = read(&params(&[("sysmon", "cpu"), ("sysmon-interval", "1")])).unwrap_err();
226        assert_eq!(
227            err,
228            "`sysmon-interval` is now `sysmon_interval`; write `sysmon_interval=…`"
229        );
230        let err = read(&params(&[("sysmon-membw-gbps", "80")])).unwrap_err();
231        assert!(err.contains("`sysmon_membw_gbps`"), "{err}");
232    }
233
234    #[test]
235    fn a_sampler_param_without_sysmon_is_refused() {
236        let err = read(&params(&[("sysmon_interval", "1")])).unwrap_err();
237        assert!(
238            err.contains("`sysmon_interval` is set and `sysmon` is not"),
239            "{err}"
240        );
241    }
242
243    #[test]
244    fn a_value_that_does_not_parse_names_its_param() {
245        for (key, value) in [
246            ("sysmon_interval", "soon"),
247            ("sysmon_interval", "0"),
248            ("sysmon_membw_gbps", "fast"),
249            ("sysmon_procs", "server"),
250            ("sysmon_cgroups", "node"),
251        ] {
252            let err = read(&params(&[("sysmon", "cpu"), (key, value)])).unwrap_err();
253            assert!(err.contains(key), "{key}={value}: {err}");
254        }
255    }
256}