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

//! A control group's CPU, memory and storage I/O, from the unified
//! (version 2) hierarchy (SRD-118 ยง3.9).
//!
//! A control group is the kernel's account of a service: every process
//! in it, across restarts, with its I/O divided by device. Its files
//! are readable without privilege.

use std::path::{Path, PathBuf};

/// Where the unified hierarchy is mounted.
pub const ROOT: &str = "/sys/fs/cgroup";

/// True when the unified hierarchy is mounted at [`ROOT`].
pub fn hierarchy_available() -> bool {
    Path::new(ROOT).join("cgroup.controllers").exists()
}

/// One control group to watch, and the name its series carry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupTarget {
    pub name: String,
    /// The group's directory.
    pub dir: PathBuf,
}

/// The directory of the group written as `path`: `path` itself when
/// it is under [`ROOT`], and otherwise `path` under [`ROOT`].
fn group_dir(path: &str) -> PathBuf {
    if Path::new(path).starts_with(ROOT) {
        PathBuf::from(path)
    } else {
        Path::new(ROOT).join(path.trim_start_matches('/'))
    }
}

/// Parse a list of control groups: a comma list of `name:path`. A
/// name is letters, digits, `_` and `-`, and is given once. An error
/// does not name the setting it was read from; the caller does.
pub fn parse_cgroups(value: &str) -> Result<Vec<CgroupTarget>, String> {
    let mut targets: Vec<CgroupTarget> = Vec::new();
    for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
        let Some((name, path)) = item.split_once(':') else {
            return Err(format!("'{item}' is not `name:path`"));
        };
        let (name, path) = (name.trim(), path.trim());
        if !crate::is_subject_name(name) {
            return Err(format!(
                "'{name}' is not a name; a name is letters, digits, `_` and `-`"
            ));
        }
        if targets.iter().any(|t| t.name == name) {
            return Err(format!("the name '{name}' is given twice"));
        }
        if path.is_empty() {
            return Err(format!("'{name}' has no control group path"));
        }
        targets.push(CgroupTarget {
            name: name.to_string(),
            dir: group_dir(path),
        });
    }
    Ok(targets)
}

/// One device's cumulative I/O by a control group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupIo {
    /// The device as `/proc/diskstats` names it, or `major:minor` when
    /// it is not listed there.
    pub device: String,
    pub read_bytes: u64,
    pub write_bytes: u64,
    pub reads: u64,
    pub writes: u64,
}

/// A control group's cumulative counters and current memory. A member
/// is `None`, or the list empty, when the group's controller for it is
/// not enabled.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CgroupCounters {
    /// CPU time taken, in microseconds.
    pub cpu_usec: Option<u64>,
    pub mem_bytes: Option<u64>,
    pub io: Vec<CgroupIo>,
}

/// `usage_usec` of `cpu.stat`.
pub fn parse_cpu_stat(text: &str) -> Option<u64> {
    text.lines()
        .find_map(|line| line.strip_prefix("usage_usec "))?
        .trim()
        .parse()
        .ok()
}

/// The devices of `io.stat`. A line is `major:minor key=value โ€ฆ`; one
/// without all four of `rbytes`, `wbytes`, `rios` and `wios` is left
/// out. `devices` names a device by its number.
pub fn parse_io_stat(text: &str, devices: &[((u32, u32), String)]) -> Vec<CgroupIo> {
    text.lines()
        .filter_map(|line| {
            let mut tokens = line.split_whitespace();
            let number = tokens.next()?;
            let (major, minor) = number.split_once(':')?;
            let number_pair: (u32, u32) = (major.parse().ok()?, minor.parse().ok()?);
            let pairs: Vec<(&str, u64)> = tokens
                .filter_map(|t| {
                    let (key, value) = t.split_once('=')?;
                    Some((key, value.parse().ok()?))
                })
                .collect();
            let value = |key: &str| pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| *v);
            Some(CgroupIo {
                device: devices
                    .iter()
                    .find(|(n, _)| *n == number_pair)
                    .map(|(_, name)| name.clone())
                    .unwrap_or_else(|| number.to_string()),
                read_bytes: value("rbytes")?,
                write_bytes: value("wbytes")?,
                reads: value("rios")?,
                writes: value("wios")?,
            })
        })
        .collect()
}

/// Read one control group. `None` when its directory is not there.
pub fn read_counters(dir: &Path, devices: &[((u32, u32), String)]) -> Option<CgroupCounters> {
    if !dir.is_dir() {
        return None;
    }
    let read = |file: &str| std::fs::read_to_string(dir.join(file)).ok();
    Some(CgroupCounters {
        cpu_usec: read("cpu.stat").and_then(|t| parse_cpu_stat(&t)),
        mem_bytes: read("memory.current").and_then(|t| t.trim().parse().ok()),
        io: read("io.stat")
            .map(|t| parse_io_stat(&t, devices))
            .unwrap_or_default(),
    })
}

/// What a control group read and wrote on one device over a window.
#[derive(Debug, Clone, PartialEq)]
pub struct CgroupIoRate {
    pub device: String,
    pub read_bytes_per_s: f64,
    pub write_bytes_per_s: f64,
    pub read_ops_per_s: f64,
    pub write_ops_per_s: f64,
}

/// What one control group did over a sample window.
#[derive(Debug, Clone, PartialEq)]
pub struct CgroupReading {
    pub name: String,
    /// CPU time over wall time: 1.0 is one core kept busy.
    pub cpu_cores: Option<f64>,
    pub mem_bytes: Option<f64>,
    /// Each device that is in both readings.
    pub io: Vec<CgroupIoRate>,
}

/// One control group's reading between two sets of counters `dt_s`
/// apart.
pub fn reading(
    name: &str,
    prev: &CgroupCounters,
    cur: &CgroupCounters,
    dt_s: f64,
) -> CgroupReading {
    let per_s = |before: u64, now: u64| -> f64 {
        if dt_s <= 0.0 {
            0.0
        } else {
            now.saturating_sub(before) as f64 / dt_s
        }
    };
    CgroupReading {
        name: name.to_string(),
        cpu_cores: match (prev.cpu_usec, cur.cpu_usec) {
            (Some(before), Some(now)) => Some(per_s(before, now) / 1e6),
            _ => None,
        },
        mem_bytes: cur.mem_bytes.map(|b| b as f64),
        io: cur
            .io
            .iter()
            .filter_map(|now| {
                let before = prev.io.iter().find(|d| d.device == now.device)?;
                Some(CgroupIoRate {
                    device: now.device.clone(),
                    read_bytes_per_s: per_s(before.read_bytes, now.read_bytes),
                    write_bytes_per_s: per_s(before.write_bytes, now.write_bytes),
                    read_ops_per_s: per_s(before.reads, now.reads),
                    write_ops_per_s: per_s(before.writes, now.writes),
                })
            })
            .collect(),
    }
}

/// A watched control group between samples: its counters when it was
/// last read.
pub struct WatchedCgroup {
    pub target: CgroupTarget,
    last: Option<CgroupCounters>,
    /// True once the group was reported missing, so it is said once
    /// per absence and not once per window.
    missing_reported: bool,
}

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

    /// Read the group now and return its reading for the window since
    /// the last read. `None` for the first window, which has nothing
    /// to take a difference against, and while the group is not there;
    /// `missing` is called once each time it goes missing.
    pub fn sample(
        &mut self,
        dt_s: f64,
        devices: &[((u32, u32), String)],
        missing: &mut dyn FnMut(&str),
    ) -> Option<CgroupReading> {
        let Some(cur) = read_counters(&self.target.dir, devices) 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(cur.clone())?;
        Some(reading(&self.target.name, &prev, &cur, dt_s))
    }
}

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

    #[test]
    fn groups_are_names_with_a_path_under_the_hierarchy() {
        assert_eq!(
            parse_cgroups("node:system.slice/db.service, me:/sys/fs/cgroup/user.slice").unwrap(),
            vec![
                CgroupTarget {
                    name: "node".into(),
                    dir: "/sys/fs/cgroup/system.slice/db.service".into()
                },
                CgroupTarget {
                    name: "me".into(),
                    dir: "/sys/fs/cgroup/user.slice".into()
                },
            ]
        );
        // A path as /proc/<pid>/cgroup writes it, from the root.
        assert_eq!(
            parse_cgroups("a:/system.slice").unwrap()[0].dir,
            PathBuf::from("/sys/fs/cgroup/system.slice")
        );
        for (value, says) in [
            ("node", "is not `name:path`"),
            ("a b:x", "is not a name"),
            ("a:x,a:y", "given twice"),
            ("a:", "no control group path"),
        ] {
            let err = parse_cgroups(value).unwrap_err();
            assert!(err.contains(says), "{value}: {err}");
        }
    }

    #[test]
    fn cpu_stat_gives_the_time_taken() {
        let text = "usage_usec 2500000\nuser_usec 2000000\nsystem_usec 500000\n";
        assert_eq!(parse_cpu_stat(text), Some(2_500_000));
        assert_eq!(parse_cpu_stat("user_usec 1\n"), None);
    }

    /// A device is named as diskstats names it, by number when it is
    /// not listed, and a line with no counters is left out.
    #[test]
    fn io_stat_is_read_per_device() {
        let devices = vec![((259, 0), "nvme0n1".to_string())];
        let text = "\
259:0 rbytes=4096 wbytes=8192 rios=1 wios=2 dbytes=0 dios=0
9:127 rbytes=10 wbytes=20 rios=3 wios=4 dbytes=0 dios=0
8:0
";
        assert_eq!(
            parse_io_stat(text, &devices),
            vec![
                CgroupIo {
                    device: "nvme0n1".into(),
                    read_bytes: 4096,
                    write_bytes: 8192,
                    reads: 1,
                    writes: 2,
                },
                CgroupIo {
                    device: "9:127".into(),
                    read_bytes: 10,
                    write_bytes: 20,
                    reads: 3,
                    writes: 4,
                },
            ]
        );
    }

    /// Two seconds of CPU time in two seconds is one core; a device in
    /// only one reading has no rate; a controller that is off is absent.
    #[test]
    fn a_reading_is_the_difference_over_the_window() {
        let io = |device: &str, write_bytes| CgroupIo {
            device: device.into(),
            read_bytes: 0,
            write_bytes,
            reads: 0,
            writes: 0,
        };
        let prev = CgroupCounters {
            cpu_usec: Some(1_000_000),
            mem_bytes: Some(10),
            io: vec![io("sda", 1000)],
        };
        let cur = CgroupCounters {
            cpu_usec: Some(3_000_000),
            mem_bytes: Some(4096),
            io: vec![io("sda", 5000), io("sdb", 7)],
        };
        let got = reading("node", &prev, &cur, 2.0);
        assert_eq!(got.cpu_cores, Some(1.0));
        assert_eq!(got.mem_bytes, Some(4096.0));
        assert_eq!(got.io.len(), 1);
        assert_eq!(got.io[0].write_bytes_per_s, 2000.0);

        let off = reading(
            "node",
            &CgroupCounters::default(),
            &CgroupCounters::default(),
            2.0,
        );
        assert_eq!(
            (off.cpu_cores, off.mem_bytes, off.io.len()),
            (None, None, 0)
        );
    }

    /// A group that is not there is reported once, and has no reading.
    #[test]
    fn a_missing_group_is_said_once() {
        let mut watched = WatchedCgroup::new(CgroupTarget {
            name: "gone".into(),
            dir: "/sys/fs/cgroup/no-such-group-for-this-test".into(),
        });
        let mut said = 0;
        for _ in 0..3 {
            assert!(watched.sample(1.0, &[], &mut |_| said += 1).is_none());
        }
        assert_eq!(said, 1);
    }

    /// This process's own group is there to read, and its second
    /// window has a reading.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_own_group_is_read() {
        if !hierarchy_available() {
            return;
        }
        let own = std::fs::read_to_string("/proc/self/cgroup").unwrap();
        let Some(path) = own.lines().find_map(|line| line.strip_prefix("0::")) else {
            return;
        };
        let mut watched =
            WatchedCgroup::new(parse_cgroups(&format!("me:{path}")).unwrap().remove(0));
        let mut missing = |name: &str| panic!("{name} reported missing");
        assert!(watched.sample(1.0, &[], &mut missing).is_none());
        assert_eq!(watched.sample(1.0, &[], &mut missing).unwrap().name, "me");
    }
}