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

//! Pressure stall information from `/proc/pressure` (SRD-118 ยง3.7):
//! the share of time tasks were stalled for want of CPU, memory or
//! I/O.
//!
//! Utilization says how much of a resource is in use; pressure says
//! whether work is waiting for it. A host at 100% CPU with no pressure
//! is busy, and one with pressure is short.

/// Cumulative stall time for one resource, in microseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StallTotals {
    /// Time in which at least one task was stalled.
    pub some_us: u64,
    /// Time in which every runnable task was stalled. The kernel
    /// reports none for CPU at the system level.
    pub full_us: Option<u64>,
}

/// The `total=` of the `some` and `full` lines of one
/// `/proc/pressure/<resource>` file. `None` without a `some` line.
pub fn parse_pressure(text: &str) -> Option<StallTotals> {
    let total = |kind: &str| -> Option<u64> {
        text.lines()
            .find(|line| line.split_whitespace().next() == Some(kind))?
            .split_whitespace()
            .find_map(|field| field.strip_prefix("total="))?
            .parse()
            .ok()
    };
    Some(StallTotals {
        some_us: total("some")?,
        full_us: total("full"),
    })
}

/// The stalled share of a sample window, for the three resources.
/// Each is a fraction of the window, 0 to 1.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct PressureReading {
    pub cpu: f64,
    pub mem: f64,
    pub mem_full: f64,
    pub io: f64,
    pub io_full: f64,
}

/// The three resources' cumulative stall times.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PressureTotals {
    pub cpu: StallTotals,
    pub mem: StallTotals,
    pub io: StallTotals,
}

/// The stalled share of the window between two readings `dt_s` apart.
pub fn pressure_between(prev: PressureTotals, cur: PressureTotals, dt_s: f64) -> PressureReading {
    let share = |before: u64, now: u64| -> f64 {
        if dt_s <= 0.0 {
            return 0.0;
        }
        (now.saturating_sub(before) as f64 / 1e6 / dt_s).clamp(0.0, 1.0)
    };
    let full = |before: StallTotals, now: StallTotals| match (before.full_us, now.full_us) {
        (Some(before), Some(now)) => share(before, now),
        _ => 0.0,
    };
    PressureReading {
        cpu: share(prev.cpu.some_us, cur.cpu.some_us),
        mem: share(prev.mem.some_us, cur.mem.some_us),
        mem_full: full(prev.mem, cur.mem),
        io: share(prev.io.some_us, cur.io.some_us),
        io_full: full(prev.io, cur.io),
    }
}

/// Read the three pressure files. `None` when any is missing: the
/// kernel was built without PSI, or it is turned off (`psi=0`), or a
/// container hides it.
pub fn read_pressure() -> Option<PressureTotals> {
    let read = |resource: &str| -> Option<StallTotals> {
        parse_pressure(&std::fs::read_to_string(format!("/proc/pressure/{resource}")).ok()?)
    };
    Some(PressureTotals {
        cpu: read("cpu")?,
        mem: read("memory")?,
        io: read("io")?,
    })
}

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

    #[test]
    fn totals_are_read_from_both_lines() {
        let text = "\
some avg10=0.00 avg60=0.12 avg300=0.05 total=2500000
full avg10=0.00 avg60=0.00 avg300=0.00 total=500000";
        assert_eq!(
            parse_pressure(text),
            Some(StallTotals {
                some_us: 2_500_000,
                full_us: Some(500_000)
            })
        );
        assert_eq!(
            parse_pressure("some avg10=0.00 avg60=0.00 avg300=0.00 total=7"),
            Some(StallTotals {
                some_us: 7,
                full_us: None
            })
        );
        assert_eq!(parse_pressure(""), None);
    }

    /// Half a second stalled in a two second window is a quarter.
    #[test]
    fn pressure_is_the_stalled_share_of_the_window() {
        let at = |some_us, full_us| StallTotals { some_us, full_us };
        let prev = PressureTotals {
            cpu: at(0, None),
            mem: at(100, Some(100)),
            io: at(0, Some(0)),
        };
        let cur = PressureTotals {
            cpu: at(500_000, None),
            mem: at(100, Some(100)),
            io: at(2_000_000, Some(1_000_000)),
        };
        assert_eq!(
            pressure_between(prev, cur, 2.0),
            PressureReading {
                cpu: 0.25,
                mem: 0.0,
                mem_full: 0.0,
                io: 1.0,
                io_full: 0.5,
            }
        );
    }
}