Skip to main content

nmbrs_runtime/sysmon/
process.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-process measures from `/proc/<pid>` (SRD-118 ยง3.8): CPU in
5//! cores, resident memory, threads, and bytes read from and written to
6//! storage.
7//!
8//! nmbrs itself is always one of the processes, named `nmbrs`: how
9//! much of the host the load generator takes is part of reading any
10//! result. `sysmon_procs=` names others, such as a server under test
11//! on the same host.
12
13use std::path::PathBuf;
14
15/// The name nmbrs's own process is reported under.
16pub const OWN_NAME: &str = "nmbrs";
17
18/// How a watched process is found.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ProcSource {
21    /// nmbrs itself.
22    Own,
23    /// A fixed process id.
24    Pid(u32),
25    /// A file holding the process id. Read again every sample window,
26    /// so a restarted process is followed.
27    PidFile(PathBuf),
28}
29
30/// One process to watch, and the name its series carry.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct ProcTarget {
33    pub name: String,
34    pub source: ProcSource,
35}
36
37/// Parse `sysmon_procs=`: a comma list of `name:pid` or
38/// `name:/path/to/pidfile`. A name is letters, digits, `_` and `-`,
39/// is given once, and is not `nmbrs`.
40pub fn parse_procs(value: &str) -> Result<Vec<ProcTarget>, String> {
41    let mut targets: Vec<ProcTarget> = Vec::new();
42    for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
43        let Some((name, source)) = item.split_once(':') else {
44            return Err(format!(
45                "sysmon_procs: '{item}' is not `name:pid` or `name:/path/to/pidfile`"
46            ));
47        };
48        let (name, source) = (name.trim(), source.trim());
49        if name.is_empty()
50            || !name
51                .chars()
52                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
53        {
54            return Err(format!(
55                "sysmon_procs: '{name}' is not a name; a name is letters, digits, `_` and `-`"
56            ));
57        }
58        if name == OWN_NAME {
59            return Err(format!(
60                "sysmon_procs: `{OWN_NAME}` names nmbrs's own process, which is always watched"
61            ));
62        }
63        if targets.iter().any(|t| t.name == name) {
64            return Err(format!("sysmon_procs: the name '{name}' is given twice"));
65        }
66        let source = if source.is_empty() {
67            return Err(format!("sysmon_procs: '{name}' has no pid or pidfile"));
68        } else if let Ok(pid) = source.parse::<u32>() {
69            ProcSource::Pid(pid)
70        } else if source.starts_with('/') {
71            ProcSource::PidFile(PathBuf::from(source))
72        } else {
73            return Err(format!(
74                "sysmon_procs: '{source}' (for '{name}') is neither a process id nor an \
75                 absolute path to a pidfile"
76            ));
77        };
78        targets.push(ProcTarget {
79            name: name.to_string(),
80            source,
81        });
82    }
83    Ok(targets)
84}
85
86/// The cumulative counters and current sizes of one process.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub struct ProcCounters {
89    /// User plus system CPU time, in clock ticks.
90    pub cpu_ticks: u64,
91    pub threads: u64,
92    /// Resident set size, in pages.
93    pub rss_pages: u64,
94    /// Bytes fetched from and sent to storage. `None` when
95    /// `/proc/<pid>/io` cannot be read, as for another user's process.
96    pub io: Option<(u64, u64)>,
97}
98
99/// The fields of `/proc/<pid>/stat` the measures need. The command
100/// name is in parentheses and may hold spaces and parentheses, so the
101/// fields are counted from the last `)`: state is the first after it,
102/// which makes utime the 12th, stime the 13th, num_threads the 18th
103/// and rss the 22nd.
104pub fn parse_stat(text: &str) -> Option<(u64, u64, u64)> {
105    let after = &text[text.rfind(')')? + 1..];
106    let fields: Vec<&str> = after.split_whitespace().collect();
107    let field = |at: usize| -> Option<u64> { fields.get(at)?.parse().ok() };
108    Some((field(11)? + field(12)?, field(17)?, field(21)?))
109}
110
111/// `read_bytes` and `write_bytes` of `/proc/<pid>/io`.
112pub fn parse_io(text: &str) -> Option<(u64, u64)> {
113    let value = |key: &str| -> Option<u64> {
114        text.lines()
115            .find_map(|line| line.strip_prefix(key))?
116            .trim()
117            .parse()
118            .ok()
119    };
120    Some((value("read_bytes:")?, value("write_bytes:")?))
121}
122
123/// What one process did over a sample window.
124#[derive(Debug, Clone, PartialEq)]
125pub struct ProcReading {
126    pub name: String,
127    /// CPU time over wall time: 1.0 is one core kept busy.
128    pub cpu_cores: f64,
129    pub rss_bytes: f64,
130    pub threads: f64,
131    /// (read, write) bytes per second, when `/proc/<pid>/io` is readable.
132    pub io_bytes_per_s: Option<(f64, f64)>,
133}
134
135/// One process's reading between two sets of counters `dt_s` apart.
136pub fn reading(
137    name: &str,
138    prev: ProcCounters,
139    cur: ProcCounters,
140    dt_s: f64,
141    ticks_per_s: f64,
142    page_bytes: f64,
143) -> ProcReading {
144    let per_s = |before: u64, now: u64| -> f64 {
145        if dt_s <= 0.0 {
146            0.0
147        } else {
148            now.saturating_sub(before) as f64 / dt_s
149        }
150    };
151    ProcReading {
152        name: name.to_string(),
153        cpu_cores: per_s(prev.cpu_ticks, cur.cpu_ticks) / ticks_per_s.max(1.0),
154        rss_bytes: cur.rss_pages as f64 * page_bytes,
155        threads: cur.threads as f64,
156        io_bytes_per_s: match (prev.io, cur.io) {
157            (Some((r0, w0)), Some((r1, w1))) => Some((per_s(r0, r1), per_s(w0, w1))),
158            _ => None,
159        },
160    }
161}
162
163/// A watched process between samples: the process it was last found
164/// as, and that process's counters then.
165pub(super) struct Watched {
166    pub target: ProcTarget,
167    last: Option<(u32, ProcCounters)>,
168    /// True once the process was reported missing, so it is said once
169    /// per absence and not once per window.
170    missing_reported: bool,
171}
172
173/// `sysconf` for a value that is positive on every supported host.
174#[cfg(unix)]
175fn sysconf(name: libc::c_int, fallback: f64) -> f64 {
176    let value = unsafe { libc::sysconf(name) };
177    if value > 0 { value as f64 } else { fallback }
178}
179
180/// Clock ticks per second and bytes per page.
181pub(super) fn units() -> (f64, f64) {
182    #[cfg(unix)]
183    {
184        (
185            sysconf(libc::_SC_CLK_TCK, 100.0),
186            sysconf(libc::_SC_PAGESIZE, 4096.0),
187        )
188    }
189    #[cfg(not(unix))]
190    {
191        (100.0, 4096.0)
192    }
193}
194
195impl Watched {
196    pub fn new(target: ProcTarget) -> Self {
197        Self {
198            target,
199            last: None,
200            missing_reported: false,
201        }
202    }
203
204    fn pid(&self) -> Option<u32> {
205        match &self.target.source {
206            ProcSource::Own => Some(std::process::id()),
207            ProcSource::Pid(pid) => Some(*pid),
208            ProcSource::PidFile(path) => std::fs::read_to_string(path).ok()?.trim().parse().ok(),
209        }
210    }
211
212    fn counters(pid: u32) -> Option<ProcCounters> {
213        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
214        let (cpu_ticks, threads, rss_pages) = parse_stat(&stat)?;
215        let io = std::fs::read_to_string(format!("/proc/{pid}/io"))
216            .ok()
217            .and_then(|text| parse_io(&text));
218        Some(ProcCounters {
219            cpu_ticks,
220            threads,
221            rss_pages,
222            io,
223        })
224    }
225
226    /// Read the process now and return its reading for the window
227    /// since the last read. `None` for the first window of a process,
228    /// which has nothing to take a difference against, and while the
229    /// process is not there; `missing` is called once each time it
230    /// goes missing.
231    pub fn sample(
232        &mut self,
233        dt_s: f64,
234        units: (f64, f64),
235        missing: &mut dyn FnMut(&str),
236    ) -> Option<ProcReading> {
237        let found = self.pid().and_then(|pid| Some((pid, Self::counters(pid)?)));
238        let Some((pid, cur)) = found else {
239            if !self.missing_reported {
240                self.missing_reported = true;
241                missing(&self.target.name);
242            }
243            self.last = None;
244            return None;
245        };
246        self.missing_reported = false;
247        let prev = self.last.replace((pid, cur));
248        match prev {
249            // A different process under the same name starts over.
250            Some((prev_pid, prev)) if prev_pid == pid => Some(reading(
251                &self.target.name,
252                prev,
253                cur,
254                dt_s,
255                units.0,
256                units.1,
257            )),
258            _ => None,
259        }
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn procs_are_names_with_a_pid_or_a_pidfile() {
269        assert_eq!(
270            parse_procs("server:1234, db:/run/db.pid").unwrap(),
271            vec![
272                ProcTarget {
273                    name: "server".into(),
274                    source: ProcSource::Pid(1234)
275                },
276                ProcTarget {
277                    name: "db".into(),
278                    source: ProcSource::PidFile("/run/db.pid".into())
279                },
280            ]
281        );
282        for (value, says) in [
283            ("server", "is not `name:pid`"),
284            ("a b:1", "is not a name"),
285            ("nmbrs:1", "always watched"),
286            ("a:1,a:2", "given twice"),
287            ("a:", "no pid or pidfile"),
288            ("a:run/x.pid", "neither a process id nor an absolute path"),
289        ] {
290            let err = parse_procs(value).unwrap_err();
291            assert!(err.contains(says), "{value}: {err}");
292        }
293    }
294
295    /// A command name may hold spaces and parentheses; the fields are
296    /// counted from the last `)`.
297    #[test]
298    fn stat_fields_are_counted_after_the_command_name() {
299        let stat = "4242 (my (odd) cmd) S 1 4242 4242 0 -1 4194560 100 0 0 0 \
300                    700 300 0 0 20 0 17 0 12345 1000000 2500 18446744073709551615 1 1";
301        assert_eq!(parse_stat(stat), Some((1000, 17, 2500)));
302        assert_eq!(parse_stat("no parenthesis"), None);
303    }
304
305    #[test]
306    fn io_reads_the_storage_byte_counts() {
307        let io = "rchar: 9\nwchar: 9\nsyscr: 1\nsyscw: 1\nread_bytes: 4096\nwrite_bytes: 8192\ncancelled_write_bytes: 0\n";
308        assert_eq!(parse_io(io), Some((4096, 8192)));
309        assert_eq!(parse_io("rchar: 9\n"), None);
310    }
311
312    /// 200 ticks at 100 per second over two seconds is one core.
313    #[test]
314    fn a_reading_is_the_difference_over_the_window() {
315        let prev = ProcCounters {
316            cpu_ticks: 1000,
317            threads: 4,
318            rss_pages: 10,
319            io: Some((0, 1000)),
320        };
321        let cur = ProcCounters {
322            cpu_ticks: 1200,
323            threads: 6,
324            rss_pages: 20,
325            io: Some((4000, 1000)),
326        };
327        assert_eq!(
328            reading("p", prev, cur, 2.0, 100.0, 4096.0),
329            ProcReading {
330                name: "p".into(),
331                cpu_cores: 1.0,
332                rss_bytes: 81920.0,
333                threads: 6.0,
334                io_bytes_per_s: Some((2000.0, 0.0)),
335            }
336        );
337    }
338
339    /// nmbrs's own process is there to read, and its second window has
340    /// a reading.
341    #[cfg(target_os = "linux")]
342    #[test]
343    fn the_own_process_is_read() {
344        let mut own = Watched::new(ProcTarget {
345            name: OWN_NAME.into(),
346            source: ProcSource::Own,
347        });
348        let mut missing = |name: &str| panic!("{name} reported missing");
349        assert!(own.sample(1.0, units(), &mut missing).is_none());
350        let reading = own.sample(1.0, units(), &mut missing).unwrap();
351        assert!(reading.rss_bytes > 0.0 && reading.threads >= 1.0);
352    }
353}