Skip to main content

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