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

//! The host's subsystems by name (SRD-118 §3), and what each needs of
//! this host. The sampler's `sysmon=` and the host op's `read:` name
//! categories from this one list.

/// The category names, in the order they are listed to a user.
pub const CATEGORY_NAMES: &[&str] = &[
    "cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc", "cgroup",
];

/// A set of categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Categories {
    pub cpu: bool,
    pub io: bool,
    pub ram: bool,
    pub rambw: bool,
    pub storage: bool,
    pub net: bool,
    pub pressure: bool,
    pub proc: bool,
    pub cgroup: bool,
}

impl Categories {
    pub const ALL: Categories = Categories {
        cpu: true,
        io: true,
        ram: true,
        rambw: true,
        storage: true,
        net: true,
        pressure: true,
        proc: true,
        cgroup: true,
    };

    /// True when any category is in the set.
    pub fn any(&self) -> bool {
        *self != Categories::default()
    }

    /// The flag a category name stands for.
    fn flag(&mut self, name: &str) -> Option<&mut bool> {
        Some(match name {
            "cpu" => &mut self.cpu,
            "io" => &mut self.io,
            "ram" => &mut self.ram,
            "rambw" => &mut self.rambw,
            "storage" => &mut self.storage,
            "net" => &mut self.net,
            "pressure" => &mut self.pressure,
            "proc" => &mut self.proc,
            "cgroup" => &mut self.cgroup,
            _ => return None,
        })
    }

    /// True when the category `name` is in the set.
    pub fn has(&self, name: &str) -> bool {
        let mut copy = *self;
        copy.flag(name).is_some_and(|on| *on)
    }

    /// Put the category `name` in the set. `Err` holds the name when
    /// it is not a category.
    pub fn add(&mut self, name: &str) -> Result<(), String> {
        match self.flag(name) {
            Some(flag) => {
                *flag = true;
                Ok(())
            }
            None => Err(name.to_string()),
        }
    }

    /// The categories' names, in listing order.
    pub fn list(&self) -> Vec<&'static str> {
        CATEGORY_NAMES
            .iter()
            .filter(|name| self.has(name))
            .copied()
            .collect()
    }

    /// The categories' names, comma separated.
    pub fn names(&self) -> String {
        self.list().join(",")
    }
}

/// The readings come from `/proc` and `/sys`, which only Linux has.
pub const fn platform_supported() -> bool {
    cfg!(target_os = "linux")
}

/// Why this host cannot supply the category `name`, or `None` when it
/// can. The reason is a sentence that follows "…, but": it does not
/// say who asked.
///
/// `cpu`, `io`, `ram`, `storage`, `net` and `proc` need only `/proc`.
/// `rambw` needs resctrl, `pressure` the kernel's stall accounting,
/// and `cgroup` the unified hierarchy.
pub fn unavailable(name: &str) -> Option<String> {
    if !platform_supported() {
        return Some(
            "the host's readings come from /proc and are available on Linux only".to_string(),
        );
    }
    match name {
        "rambw" if crate::mem::read_membw_bytes().is_none() => Some(
            "\
the kernel resctrl interface is not available at /sys/fs/resctrl/mon_data.

To enable memory-bandwidth monitoring:
  1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
     check for the `cqm_mbm_total` flag:  grep -m1 cqm_mbm_total /proc/cpuinfo
  2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
     mainstream distro kernels).
  3. Mount the interface:  sudo mount -t resctrl resctrl /sys/fs/resctrl

Most virtual machines cannot support it."
                .to_string(),
        ),
        "pressure" if crate::pressure::read_pressure().is_none() => Some(
            "the kernel's pressure stall information is not readable at /proc/pressure. \
             It needs a kernel built with CONFIG_PSI (4.20 or later) that was not booted \
             with `psi=0`, and a container must be given the host's /proc/pressure."
                .to_string(),
        ),
        "cgroup" if !crate::cgroup::hierarchy_available() => Some(format!(
            "the unified control group hierarchy (cgroup v2) is not mounted at {}.",
            crate::cgroup::ROOT
        )),
        _ => None,
    }
}

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

    #[test]
    fn a_set_is_built_by_name_and_listed_in_order() {
        let mut cats = Categories::default();
        assert!(!cats.any());
        for name in ["proc", "cpu", "cgroup"] {
            cats.add(name).unwrap();
        }
        assert_eq!(cats.names(), "cpu,proc,cgroup");
        assert!(cats.has("proc") && !cats.has("io") && !cats.has("disk"));
        assert_eq!(cats.add("disk"), Err("disk".to_string()));
    }

    #[test]
    fn every_name_is_a_category() {
        let mut all = Categories::default();
        for name in CATEGORY_NAMES {
            all.add(name).unwrap();
        }
        assert_eq!(all, Categories::ALL);
    }

    /// The categories that read only /proc are there on any Linux.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_proc_categories_need_nothing_more() {
        for name in ["cpu", "io", "ram", "storage", "net", "proc"] {
            assert_eq!(unavailable(name), None, "{name}");
        }
    }
}