Skip to main content

sys_lib/
pressure.rs

1//! [`Pressure`]: how much work is stalled waiting for a resource.
2
3use core::time::Duration;
4
5use crate::Percent;
6
7/// How much work is stalled waiting for a resource (CPU, memory, or I/O).
8///
9/// The best single sign that a machine, or a container, is overloaded: it
10/// measures waiting rather than busyness. A CPU at 100% with nothing stalled is
11/// doing its job; with 30% of the time stalled it is turning work away.
12/// [`cpu::pressure`](crate::cpu::pressure), [`mem::pressure`](crate::mem::pressure),
13/// and [`disk::pressure`](crate::disk::pressure) return it.
14///
15/// On Linux it is the kernel's pressure-stall information (PSI, kernel 4.20 and
16/// later), read from the process's own cgroup when it has one, so a container
17/// sees its own pressure, and from `/proc/pressure/` otherwise. Where an OS
18/// reports only a level (macOS and Windows memory), the stall shares are zero
19/// and `total` is `None`.
20///
21/// ```
22/// use sys_lib::{self as sys, PressureLevel};
23///
24/// if let Some(p) = sys::cpu::pressure()? {
25///     if p.level >= PressureLevel::Warning {
26///         println!("tasks waited for a CPU {} of the last 10 s", p.some.avg10);
27///     }
28/// }
29/// # Ok::<(), sys_lib::Error>(())
30/// ```
31#[derive(Clone, Copy, PartialEq, Debug)]
32#[non_exhaustive]
33pub struct Pressure {
34    /// The level the stall shares amount to (see the thresholds).
35    pub level: PressureLevel,
36    /// The share of time at least one task was stalled.
37    pub some: Stall,
38    /// The share of time every non-idle task was stalled at once (`None` for
39    /// CPU at the host level, where the kernel does not report it).
40    pub full: Option<Stall>,
41    /// The cumulative time tasks were stalled (`some`), when reported.
42    pub total: Option<Duration>,
43}
44
45impl Pressure {
46    /// `some.avg10` at or above this is [`PressureLevel::Warning`].
47    pub const WARNING_SOME_AVG10: f32 = 10.0;
48    /// `some.avg10` at or above this is [`PressureLevel::Critical`].
49    pub const CRITICAL_SOME_AVG10: f32 = 40.0;
50    /// `full.avg10` above this is [`PressureLevel::Critical`].
51    pub const CRITICAL_FULL_AVG10: f32 = 10.0;
52
53    /// A pressure reading from its stall shares, with the level they amount to.
54    #[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))] // Linux PSI
55    pub(crate) fn from_stalls(
56        some: Stall,
57        full: Option<Stall>,
58        total: Option<Duration>,
59    ) -> Pressure {
60        let full_critical = full.is_some_and(|f| f.avg10.value() > Self::CRITICAL_FULL_AVG10);
61        let level = if full_critical || some.avg10.value() >= Self::CRITICAL_SOME_AVG10 {
62            PressureLevel::Critical
63        } else if some.avg10.value() >= Self::WARNING_SOME_AVG10 {
64            PressureLevel::Warning
65        } else {
66            PressureLevel::Normal
67        };
68        Pressure {
69            level,
70            some,
71            full,
72            total,
73        }
74    }
75
76    /// A level-only reading, for an OS that reports no stall shares.
77    #[allow(dead_code)] // the macOS and Windows memory readings
78    pub(crate) fn from_level(level: PressureLevel) -> Pressure {
79        Pressure {
80            level,
81            some: Stall::ZERO,
82            full: None,
83            total: None,
84        }
85    }
86}
87
88/// The share of time tasks were stalled, averaged over the last 10, 60, and
89/// 300 seconds.
90#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
91#[non_exhaustive]
92pub struct Stall {
93    /// Over the last 10 seconds.
94    pub avg10: Percent,
95    /// Over the last 60 seconds.
96    pub avg60: Percent,
97    /// Over the last 300 seconds.
98    pub avg300: Percent,
99}
100
101impl Stall {
102    pub(crate) const ZERO: Stall = Stall {
103        avg10: Percent::ZERO,
104        avg60: Percent::ZERO,
105        avg300: Percent::ZERO,
106    };
107
108    #[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))] // Linux PSI
109    pub(crate) fn new(avg10: Percent, avg60: Percent, avg300: Percent) -> Stall {
110        Stall {
111            avg10,
112            avg60,
113            avg300,
114        }
115    }
116}
117
118/// How serious a [`Pressure`] reading is. Ordered: `Normal < Warning < Critical`.
119#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
120#[non_exhaustive]
121pub enum PressureLevel {
122    /// Little or no stall.
123    Normal,
124    /// Work is waiting often enough to notice: trim caches, postpone batch work.
125    Warning,
126    /// Work is waiting most of the time: shed load.
127    Critical,
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    fn stall(avg10: f32) -> Stall {
135        Stall::new(Percent::from_value(avg10), Percent::ZERO, Percent::ZERO)
136    }
137
138    #[test]
139    fn test_pressure_level_thresholds() {
140        let level = |some: f32, full: Option<f32>| {
141            Pressure::from_stalls(stall(some), full.map(stall), None).level
142        };
143        assert_eq!(level(0.0, None), PressureLevel::Normal);
144        assert_eq!(level(9.99, Some(10.0)), PressureLevel::Normal);
145        assert_eq!(level(10.0, None), PressureLevel::Warning);
146        assert_eq!(level(39.9, Some(5.0)), PressureLevel::Warning);
147        assert_eq!(level(40.0, None), PressureLevel::Critical);
148        assert_eq!(level(1.0, Some(10.01)), PressureLevel::Critical);
149        assert!(
150            PressureLevel::Normal < PressureLevel::Warning
151                && PressureLevel::Warning < PressureLevel::Critical
152        );
153    }
154
155    #[test]
156    fn test_pressure_from_level_has_no_shares() {
157        let p = Pressure::from_level(PressureLevel::Critical);
158        assert_eq!(p.level, PressureLevel::Critical);
159        assert_eq!(p.some, Stall::ZERO);
160        assert_eq!((p.full, p.total), (None, None));
161    }
162}