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

//! One reading of chosen categories, as named measures (SRD-118
//! ยง6.6).
//!
//! Where the sampler turns two readings into a rate, this reads once
//! and gives the kernel's counters as they stand, with the levels
//! beside them. A measure whose name ends in `_total` is a counter,
//! counted from boot (for a process or a control group, from its
//! start); two readings of it are subtracted to get what happened
//! between them.

use crate::category::Categories;
use crate::cgroup::CgroupTarget;
use crate::process::{OWN_NAME, ProcSource, ProcTarget};

/// One measure of one reading.
#[derive(Debug, Clone, PartialEq)]
pub struct Measure {
    /// The measure's name, such as `io_write_bytes_total`.
    pub name: &'static str,
    /// What the measure is of, outermost first: `[("device", "sda")]`,
    /// or `[("cgroup", "node"), ("device", "sda")]`. Empty for a
    /// measure of the host as a whole.
    pub subject: Vec<(&'static str, String)>,
    pub value: f64,
}

/// One reading.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Snapshot {
    pub measures: Vec<Measure>,
    /// What was asked for and could not be read, each as a sentence.
    pub absent: Vec<String>,
}

impl Snapshot {
    fn host(&mut self, name: &'static str, value: f64) {
        self.measures.push(Measure {
            name,
            subject: Vec::new(),
            value,
        });
    }

    fn of(&mut self, name: &'static str, subject: &[(&'static str, &str)], value: f64) {
        self.measures.push(Measure {
            name,
            subject: subject.iter().map(|(k, v)| (*k, v.to_string())).collect(),
            value,
        });
    }
}

/// The size `/proc/diskstats` counts sectors in.
const SECTOR_BYTES: f64 = 512.0;

/// Read the categories in `cats` once. `procs` are read besides nmbrs
/// itself under `proc`, and `cgroups` under `cgroup`.
///
/// Reads `/proc` and `/sys`, and asks each mounted filesystem under
/// `storage`: call it from a thread that may block.
pub fn read(cats: Categories, procs: &[ProcTarget], cgroups: &[CgroupTarget]) -> Snapshot {
    let mut out = Snapshot::default();
    let (ticks_per_s, page_bytes) = crate::process::units();

    if cats.cpu {
        match crate::cpu::read_proc_stat() {
            Some((all, _)) => {
                out.host("cpu_busy_seconds_total", all.busy as f64 / ticks_per_s);
                out.host("cpu_seconds_total", all.total as f64 / ticks_per_s);
            }
            None => out.absent.push("/proc/stat could not be read".into()),
        }
    }
    if cats.io {
        for disk in crate::disk::read_diskstats()
            .iter()
            .filter(|d| crate::disk::is_whole_device(&d.name))
        {
            let device = [("device", disk.name.as_str())];
            out.of(
                "io_read_bytes_total",
                &device,
                disk.read_sectors as f64 * SECTOR_BYTES,
            );
            out.of(
                "io_write_bytes_total",
                &device,
                disk.write_sectors as f64 * SECTOR_BYTES,
            );
            out.of("io_read_ops_total", &device, disk.reads as f64);
            out.of("io_write_ops_total", &device, disk.writes as f64);
            out.of(
                "io_busy_seconds_total",
                &device,
                disk.io_ticks as f64 / 1000.0,
            );
        }
    }
    if cats.ram {
        match std::fs::read_to_string("/proc/meminfo")
            .ok()
            .and_then(|t| crate::mem::parse_meminfo(&t))
        {
            Some(mem) => {
                out.host("ram_total_bytes", mem.total_kb as f64 * 1024.0);
                out.host("ram_available_bytes", mem.available_kb as f64 * 1024.0);
                out.host("ram_free_bytes", mem.free_kb as f64 * 1024.0);
            }
            None => out.absent.push("/proc/meminfo could not be read".into()),
        }
    }
    if cats.rambw {
        match crate::mem::read_membw_bytes() {
            Some(bytes) => out.host("rambw_bytes_total", bytes as f64),
            None => out
                .absent
                .push("the resctrl memory-bandwidth counters could not be read".into()),
        }
    }
    if cats.storage {
        for (mount, total, available) in crate::disk::read_mount_sizes() {
            let mount = [("mount", mount.as_str())];
            out.of("storage_total_bytes", &mount, total as f64);
            out.of("storage_available_bytes", &mount, available as f64);
        }
    }
    if cats.net {
        for iface in crate::net::read_net_dev() {
            let subject = [("iface", iface.iface.as_str())];
            out.of("net_rx_bytes_total", &subject, iface.rx_bytes as f64);
            out.of("net_tx_bytes_total", &subject, iface.tx_bytes as f64);
        }
    }
    if cats.pressure {
        match crate::pressure::read_pressure() {
            Some(p) => {
                let seconds = |us: u64| us as f64 / 1e6;
                out.host("pressure_cpu_seconds_total", seconds(p.cpu.some_us));
                out.host("pressure_mem_seconds_total", seconds(p.mem.some_us));
                out.host("pressure_io_seconds_total", seconds(p.io.some_us));
                if let Some(full) = p.mem.full_us {
                    out.host("pressure_mem_full_seconds_total", seconds(full));
                }
                if let Some(full) = p.io.full_us {
                    out.host("pressure_io_full_seconds_total", seconds(full));
                }
            }
            None => out.absent.push("/proc/pressure could not be read".into()),
        }
    }
    if cats.proc {
        let own = ProcTarget {
            name: OWN_NAME.to_string(),
            source: ProcSource::Own,
        };
        for target in std::iter::once(&own).chain(procs) {
            let found = crate::process::resolve_pid(&target.source)
                .and_then(|pid| Some((pid, crate::process::read_counters(pid)?)));
            let Some((pid, counters)) = found else {
                out.absent.push(format!(
                    "process '{}' is not running (or its pidfile is unreadable)",
                    target.name
                ));
                continue;
            };
            let subject = [("proc", target.name.as_str())];
            out.of(
                "proc_cpu_seconds_total",
                &subject,
                counters.cpu_ticks as f64 / ticks_per_s,
            );
            out.of(
                "proc_rss_bytes",
                &subject,
                counters.rss_pages as f64 * page_bytes,
            );
            out.of("proc_threads", &subject, counters.threads as f64);
            out.of("proc_pid", &subject, pid as f64);
            match counters.io {
                Some((read, write)) => {
                    out.of("proc_read_bytes_total", &subject, read as f64);
                    out.of("proc_write_bytes_total", &subject, write as f64);
                }
                None => out.absent.push(format!(
                    "the storage I/O of process '{}' may not be read (it belongs to \
                     another user)",
                    target.name
                )),
            }
        }
    }
    if cats.cgroup {
        let devices = crate::disk::read_device_numbers();
        for target in cgroups {
            let Some(counters) = crate::cgroup::read_counters(&target.dir, &devices) else {
                out.absent.push(format!(
                    "control group '{}' is not there ({})",
                    target.name,
                    target.dir.display()
                ));
                continue;
            };
            let group = target.name.as_str();
            if let Some(usec) = counters.cpu_usec {
                out.of(
                    "cgroup_cpu_seconds_total",
                    &[("cgroup", group)],
                    usec as f64 / 1e6,
                );
            }
            if let Some(bytes) = counters.mem_bytes {
                out.of("cgroup_mem_bytes", &[("cgroup", group)], bytes as f64);
            }
            for io in &counters.io {
                let subject = [("cgroup", group), ("device", io.device.as_str())];
                out.of("cgroup_io_read_bytes_total", &subject, io.read_bytes as f64);
                out.of(
                    "cgroup_io_write_bytes_total",
                    &subject,
                    io.write_bytes as f64,
                );
                out.of("cgroup_io_read_ops_total", &subject, io.reads as f64);
                out.of("cgroup_io_write_ops_total", &subject, io.writes as f64);
            }
        }
    }
    out
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::*;

    fn value(snapshot: &Snapshot, name: &str) -> Option<f64> {
        snapshot
            .measures
            .iter()
            .find(|m| m.name == name)
            .map(|m| m.value)
    }

    /// Only what was asked for is read.
    #[test]
    fn only_the_named_categories_are_read() {
        let cats = Categories {
            ram: true,
            ..Categories::default()
        };
        let snapshot = read(cats, &[], &[]);
        assert!(snapshot.measures.iter().all(|m| m.name.starts_with("ram_")));
        let total = value(&snapshot, "ram_total_bytes").unwrap();
        assert!(total > 0.0 && value(&snapshot, "ram_available_bytes").unwrap() <= total);
    }

    /// nmbrs's own process is always read under `proc`, and a counter
    /// read twice does not go down.
    #[test]
    fn counters_do_not_go_down_between_two_readings() {
        let cats = Categories {
            cpu: true,
            proc: true,
            ..Categories::default()
        };
        let first = read(cats, &[], &[]);
        let second = read(cats, &[], &[]);
        for name in ["cpu_seconds_total", "proc_cpu_seconds_total"] {
            assert!(value(&second, name).unwrap() >= value(&first, name).unwrap());
        }
        let own = first
            .measures
            .iter()
            .find(|m| m.name == "proc_pid")
            .unwrap();
        assert_eq!(own.subject, vec![("proc", OWN_NAME.to_string())]);
        assert_eq!(own.value, std::process::id() as f64);
    }

    /// What is not there is said, and has no measure.
    #[test]
    fn what_is_not_there_is_named() {
        let cats = Categories {
            proc: true,
            cgroup: true,
            ..Categories::default()
        };
        let procs = vec![ProcTarget {
            name: "gone".into(),
            source: ProcSource::PidFile("/nonexistent/gone.pid".into()),
        }];
        let cgroups = crate::cgroup::parse_cgroups("lost:no-such-group-for-this-test").unwrap();
        let snapshot = read(cats, &procs, &cgroups);
        assert!(snapshot.absent.iter().any(|a| a.contains("'gone'")));
        assert!(snapshot.absent.iter().any(|a| a.contains("'lost'")));
        assert!(
            snapshot
                .measures
                .iter()
                .all(|m| m.subject.iter().all(|(_, v)| v != "gone" && v != "lost"))
        );
    }
}