nmbrs-host 0.7.3

Host readings for nmbrs: CPU, memory, disks, network, pressure, processes, control groups and directory sizes
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Per-process measures from `/proc/<pid>` (SRD-118 ยง3.8): CPU in
//! cores, resident memory, threads, and bytes read from and written to
//! storage.
//!
//! nmbrs itself is always one of the processes, named `nmbrs`: how
//! much of the host the load generator takes is part of reading any
//! result. The sampler's `sysmon_procs=` and the host op's `procs:`
//! name others, such as a server under test on the same host.

use std::path::PathBuf;

/// The name nmbrs's own process is reported under.
pub const OWN_NAME: &str = "nmbrs";

/// How a watched process is found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcSource {
    /// nmbrs itself.
    Own,
    /// A fixed process id.
    Pid(u32),
    /// A file holding the process id. Read again every sample window,
    /// so a restarted process is followed.
    PidFile(PathBuf),
}

/// One process to watch, and the name its series carry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcTarget {
    pub name: String,
    pub source: ProcSource,
}

/// Parse a list of processes: a comma list of `name:pid` or
/// `name:/path/to/pidfile`. A name is letters, digits, `_` and `-`,
/// is given once, and is not `nmbrs`. An error does not name the
/// setting it was read from; the caller does.
pub fn parse_procs(value: &str) -> Result<Vec<ProcTarget>, String> {
    let mut targets: Vec<ProcTarget> = Vec::new();
    for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
        let Some((name, source)) = item.split_once(':') else {
            return Err(format!(
                "'{item}' is not `name:pid` or `name:/path/to/pidfile`"
            ));
        };
        let (name, source) = (name.trim(), source.trim());
        if !crate::is_subject_name(name) {
            return Err(format!(
                "'{name}' is not a name; a name is letters, digits, `_` and `-`"
            ));
        }
        if name == OWN_NAME {
            return Err(format!(
                "`{OWN_NAME}` names nmbrs's own process, which is always watched"
            ));
        }
        if targets.iter().any(|t| t.name == name) {
            return Err(format!("the name '{name}' is given twice"));
        }
        let source = if source.is_empty() {
            return Err(format!("'{name}' has no pid or pidfile"));
        } else if let Ok(pid) = source.parse::<u32>() {
            ProcSource::Pid(pid)
        } else if source.starts_with('/') {
            ProcSource::PidFile(PathBuf::from(source))
        } else {
            return Err(format!(
                "'{source}' (for '{name}') is neither a process id nor an \
                 absolute path to a pidfile"
            ));
        };
        targets.push(ProcTarget {
            name: name.to_string(),
            source,
        });
    }
    Ok(targets)
}

/// The cumulative counters and current sizes of one process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ProcCounters {
    /// User plus system CPU time, in clock ticks.
    pub cpu_ticks: u64,
    pub threads: u64,
    /// Resident set size, in pages.
    pub rss_pages: u64,
    /// Bytes fetched from and sent to storage. `None` when
    /// `/proc/<pid>/io` cannot be read, as for another user's process.
    pub io: Option<(u64, u64)>,
}

/// The fields of `/proc/<pid>/stat` the measures need. The command
/// name is in parentheses and may hold spaces and parentheses, so the
/// fields are counted from the last `)`: state is the first after it,
/// which makes utime the 12th, stime the 13th, num_threads the 18th
/// and rss the 22nd.
pub fn parse_stat(text: &str) -> Option<(u64, u64, u64)> {
    let after = &text[text.rfind(')')? + 1..];
    let fields: Vec<&str> = after.split_whitespace().collect();
    let field = |at: usize| -> Option<u64> { fields.get(at)?.parse().ok() };
    Some((field(11)? + field(12)?, field(17)?, field(21)?))
}

/// `read_bytes` and `write_bytes` of `/proc/<pid>/io`.
pub fn parse_io(text: &str) -> Option<(u64, u64)> {
    let value = |key: &str| -> Option<u64> {
        text.lines()
            .find_map(|line| line.strip_prefix(key))?
            .trim()
            .parse()
            .ok()
    };
    Some((value("read_bytes:")?, value("write_bytes:")?))
}

/// What one process did over a sample window.
#[derive(Debug, Clone, PartialEq)]
pub struct ProcReading {
    pub name: String,
    /// CPU time over wall time: 1.0 is one core kept busy.
    pub cpu_cores: f64,
    pub rss_bytes: f64,
    pub threads: f64,
    /// (read, write) bytes per second, when `/proc/<pid>/io` is readable.
    pub io_bytes_per_s: Option<(f64, f64)>,
}

/// One process's reading between two sets of counters `dt_s` apart.
pub fn reading(
    name: &str,
    prev: ProcCounters,
    cur: ProcCounters,
    dt_s: f64,
    ticks_per_s: f64,
    page_bytes: f64,
) -> ProcReading {
    let per_s = |before: u64, now: u64| -> f64 {
        if dt_s <= 0.0 {
            0.0
        } else {
            now.saturating_sub(before) as f64 / dt_s
        }
    };
    ProcReading {
        name: name.to_string(),
        cpu_cores: per_s(prev.cpu_ticks, cur.cpu_ticks) / ticks_per_s.max(1.0),
        rss_bytes: cur.rss_pages as f64 * page_bytes,
        threads: cur.threads as f64,
        io_bytes_per_s: match (prev.io, cur.io) {
            (Some((r0, w0)), Some((r1, w1))) => Some((per_s(r0, r1), per_s(w0, w1))),
            _ => None,
        },
    }
}

/// A watched process between samples: the process it was last found
/// as, and that process's counters then.
pub struct Watched {
    pub target: ProcTarget,
    last: Option<(u32, ProcCounters)>,
    /// True once the process was reported missing, so it is said once
    /// per absence and not once per window.
    missing_reported: bool,
}

/// `sysconf` for a value that is positive on every supported host.
#[cfg(unix)]
fn sysconf(name: libc::c_int, fallback: f64) -> f64 {
    let value = unsafe { libc::sysconf(name) };
    if value > 0 { value as f64 } else { fallback }
}

/// Clock ticks per second and bytes per page.
pub fn units() -> (f64, f64) {
    #[cfg(unix)]
    {
        (
            sysconf(libc::_SC_CLK_TCK, 100.0),
            sysconf(libc::_SC_PAGESIZE, 4096.0),
        )
    }
    #[cfg(not(unix))]
    {
        (100.0, 4096.0)
    }
}

/// The process id a source stands for now. `None` when a pidfile
/// cannot be read or does not hold a number.
pub fn resolve_pid(source: &ProcSource) -> Option<u32> {
    match source {
        ProcSource::Own => Some(std::process::id()),
        ProcSource::Pid(pid) => Some(*pid),
        ProcSource::PidFile(path) => std::fs::read_to_string(path).ok()?.trim().parse().ok(),
    }
}

/// Read one process's counters. `None` when the process is not there.
pub fn read_counters(pid: u32) -> Option<ProcCounters> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let (cpu_ticks, threads, rss_pages) = parse_stat(&stat)?;
    let io = std::fs::read_to_string(format!("/proc/{pid}/io"))
        .ok()
        .and_then(|text| parse_io(&text));
    Some(ProcCounters {
        cpu_ticks,
        threads,
        rss_pages,
        io,
    })
}

impl Watched {
    pub fn new(target: ProcTarget) -> Self {
        Self {
            target,
            last: None,
            missing_reported: false,
        }
    }

    /// Read the process now and return its reading for the window
    /// since the last read. `None` for the first window of a process,
    /// which has nothing to take a difference against, and while the
    /// process is not there; `missing` is called once each time it
    /// goes missing.
    pub fn sample(
        &mut self,
        dt_s: f64,
        units: (f64, f64),
        missing: &mut dyn FnMut(&str),
    ) -> Option<ProcReading> {
        let found =
            resolve_pid(&self.target.source).and_then(|pid| Some((pid, read_counters(pid)?)));
        let Some((pid, cur)) = found else {
            if !self.missing_reported {
                self.missing_reported = true;
                missing(&self.target.name);
            }
            self.last = None;
            return None;
        };
        self.missing_reported = false;
        let prev = self.last.replace((pid, cur));
        match prev {
            // A different process under the same name starts over.
            Some((prev_pid, prev)) if prev_pid == pid => Some(reading(
                &self.target.name,
                prev,
                cur,
                dt_s,
                units.0,
                units.1,
            )),
            _ => None,
        }
    }
}

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

    #[test]
    fn procs_are_names_with_a_pid_or_a_pidfile() {
        assert_eq!(
            parse_procs("server:1234, db:/run/db.pid").unwrap(),
            vec![
                ProcTarget {
                    name: "server".into(),
                    source: ProcSource::Pid(1234)
                },
                ProcTarget {
                    name: "db".into(),
                    source: ProcSource::PidFile("/run/db.pid".into())
                },
            ]
        );
        for (value, says) in [
            ("server", "is not `name:pid`"),
            ("a b:1", "is not a name"),
            ("nmbrs:1", "always watched"),
            ("a:1,a:2", "given twice"),
            ("a:", "no pid or pidfile"),
            ("a:run/x.pid", "neither a process id nor an absolute path"),
        ] {
            let err = parse_procs(value).unwrap_err();
            assert!(err.contains(says), "{value}: {err}");
        }
    }

    /// A command name may hold spaces and parentheses; the fields are
    /// counted from the last `)`.
    #[test]
    fn stat_fields_are_counted_after_the_command_name() {
        let stat = "4242 (my (odd) cmd) S 1 4242 4242 0 -1 4194560 100 0 0 0 \
                    700 300 0 0 20 0 17 0 12345 1000000 2500 18446744073709551615 1 1";
        assert_eq!(parse_stat(stat), Some((1000, 17, 2500)));
        assert_eq!(parse_stat("no parenthesis"), None);
    }

    #[test]
    fn io_reads_the_storage_byte_counts() {
        let io = "rchar: 9\nwchar: 9\nsyscr: 1\nsyscw: 1\nread_bytes: 4096\nwrite_bytes: 8192\ncancelled_write_bytes: 0\n";
        assert_eq!(parse_io(io), Some((4096, 8192)));
        assert_eq!(parse_io("rchar: 9\n"), None);
    }

    /// 200 ticks at 100 per second over two seconds is one core.
    #[test]
    fn a_reading_is_the_difference_over_the_window() {
        let prev = ProcCounters {
            cpu_ticks: 1000,
            threads: 4,
            rss_pages: 10,
            io: Some((0, 1000)),
        };
        let cur = ProcCounters {
            cpu_ticks: 1200,
            threads: 6,
            rss_pages: 20,
            io: Some((4000, 1000)),
        };
        assert_eq!(
            reading("p", prev, cur, 2.0, 100.0, 4096.0),
            ProcReading {
                name: "p".into(),
                cpu_cores: 1.0,
                rss_bytes: 81920.0,
                threads: 6.0,
                io_bytes_per_s: Some((2000.0, 0.0)),
            }
        );
    }

    /// nmbrs's own process is there to read, and its second window has
    /// a reading.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_own_process_is_read() {
        let mut own = Watched::new(ProcTarget {
            name: OWN_NAME.into(),
            source: ProcSource::Own,
        });
        let mut missing = |name: &str| panic!("{name} reported missing");
        assert!(own.sample(1.0, units(), &mut missing).is_none());
        let reading = own.sample(1.0, units(), &mut missing).unwrap();
        assert!(reading.rss_bytes > 0.0 && reading.threads >= 1.0);
    }
}