Skip to main content

nmbrs_host/
pressure.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pressure stall information from `/proc/pressure` (SRD-118 ยง3.7):
5//! the share of time tasks were stalled for want of CPU, memory or
6//! I/O.
7//!
8//! Utilization says how much of a resource is in use; pressure says
9//! whether work is waiting for it. A host at 100% CPU with no pressure
10//! is busy, and one with pressure is short.
11
12/// Cumulative stall time for one resource, in microseconds.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub struct StallTotals {
15    /// Time in which at least one task was stalled.
16    pub some_us: u64,
17    /// Time in which every runnable task was stalled. The kernel
18    /// reports none for CPU at the system level.
19    pub full_us: Option<u64>,
20}
21
22/// The `total=` of the `some` and `full` lines of one
23/// `/proc/pressure/<resource>` file. `None` without a `some` line.
24pub fn parse_pressure(text: &str) -> Option<StallTotals> {
25    let total = |kind: &str| -> Option<u64> {
26        text.lines()
27            .find(|line| line.split_whitespace().next() == Some(kind))?
28            .split_whitespace()
29            .find_map(|field| field.strip_prefix("total="))?
30            .parse()
31            .ok()
32    };
33    Some(StallTotals {
34        some_us: total("some")?,
35        full_us: total("full"),
36    })
37}
38
39/// The stalled share of a sample window, for the three resources.
40/// Each is a fraction of the window, 0 to 1.
41#[derive(Debug, Clone, Copy, PartialEq, Default)]
42pub struct PressureReading {
43    pub cpu: f64,
44    pub mem: f64,
45    pub mem_full: f64,
46    pub io: f64,
47    pub io_full: f64,
48}
49
50/// The three resources' cumulative stall times.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub struct PressureTotals {
53    pub cpu: StallTotals,
54    pub mem: StallTotals,
55    pub io: StallTotals,
56}
57
58/// The stalled share of the window between two readings `dt_s` apart.
59pub fn pressure_between(prev: PressureTotals, cur: PressureTotals, dt_s: f64) -> PressureReading {
60    let share = |before: u64, now: u64| -> f64 {
61        if dt_s <= 0.0 {
62            return 0.0;
63        }
64        (now.saturating_sub(before) as f64 / 1e6 / dt_s).clamp(0.0, 1.0)
65    };
66    let full = |before: StallTotals, now: StallTotals| match (before.full_us, now.full_us) {
67        (Some(before), Some(now)) => share(before, now),
68        _ => 0.0,
69    };
70    PressureReading {
71        cpu: share(prev.cpu.some_us, cur.cpu.some_us),
72        mem: share(prev.mem.some_us, cur.mem.some_us),
73        mem_full: full(prev.mem, cur.mem),
74        io: share(prev.io.some_us, cur.io.some_us),
75        io_full: full(prev.io, cur.io),
76    }
77}
78
79/// Read the three pressure files. `None` when any is missing: the
80/// kernel was built without PSI, or it is turned off (`psi=0`), or a
81/// container hides it.
82pub fn read_pressure() -> Option<PressureTotals> {
83    let read = |resource: &str| -> Option<StallTotals> {
84        parse_pressure(&std::fs::read_to_string(format!("/proc/pressure/{resource}")).ok()?)
85    };
86    Some(PressureTotals {
87        cpu: read("cpu")?,
88        mem: read("memory")?,
89        io: read("io")?,
90    })
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn totals_are_read_from_both_lines() {
99        let text = "\
100some avg10=0.00 avg60=0.12 avg300=0.05 total=2500000
101full avg10=0.00 avg60=0.00 avg300=0.00 total=500000";
102        assert_eq!(
103            parse_pressure(text),
104            Some(StallTotals {
105                some_us: 2_500_000,
106                full_us: Some(500_000)
107            })
108        );
109        assert_eq!(
110            parse_pressure("some avg10=0.00 avg60=0.00 avg300=0.00 total=7"),
111            Some(StallTotals {
112                some_us: 7,
113                full_us: None
114            })
115        );
116        assert_eq!(parse_pressure(""), None);
117    }
118
119    /// Half a second stalled in a two second window is a quarter.
120    #[test]
121    fn pressure_is_the_stalled_share_of_the_window() {
122        let at = |some_us, full_us| StallTotals { some_us, full_us };
123        let prev = PressureTotals {
124            cpu: at(0, None),
125            mem: at(100, Some(100)),
126            io: at(0, Some(0)),
127        };
128        let cur = PressureTotals {
129            cpu: at(500_000, None),
130            mem: at(100, Some(100)),
131            io: at(2_000_000, Some(1_000_000)),
132        };
133        assert_eq!(
134            pressure_between(prev, cur, 2.0),
135            PressureReading {
136                cpu: 0.25,
137                mem: 0.0,
138                mem_full: 0.0,
139                io: 1.0,
140                io_full: 0.5,
141            }
142        );
143    }
144}