Skip to main content

nmbrs_host/
category.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The host's subsystems by name (SRD-118 §3), and what each needs of
5//! this host. The sampler's `sysmon=` and the host op's `read:` name
6//! categories from this one list.
7
8/// The category names, in the order they are listed to a user.
9pub const CATEGORY_NAMES: &[&str] = &[
10    "cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc", "cgroup",
11];
12
13/// A set of categories.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub struct Categories {
16    pub cpu: bool,
17    pub io: bool,
18    pub ram: bool,
19    pub rambw: bool,
20    pub storage: bool,
21    pub net: bool,
22    pub pressure: bool,
23    pub proc: bool,
24    pub cgroup: bool,
25}
26
27impl Categories {
28    pub const ALL: Categories = Categories {
29        cpu: true,
30        io: true,
31        ram: true,
32        rambw: true,
33        storage: true,
34        net: true,
35        pressure: true,
36        proc: true,
37        cgroup: true,
38    };
39
40    /// True when any category is in the set.
41    pub fn any(&self) -> bool {
42        *self != Categories::default()
43    }
44
45    /// The flag a category name stands for.
46    fn flag(&mut self, name: &str) -> Option<&mut bool> {
47        Some(match name {
48            "cpu" => &mut self.cpu,
49            "io" => &mut self.io,
50            "ram" => &mut self.ram,
51            "rambw" => &mut self.rambw,
52            "storage" => &mut self.storage,
53            "net" => &mut self.net,
54            "pressure" => &mut self.pressure,
55            "proc" => &mut self.proc,
56            "cgroup" => &mut self.cgroup,
57            _ => return None,
58        })
59    }
60
61    /// True when the category `name` is in the set.
62    pub fn has(&self, name: &str) -> bool {
63        let mut copy = *self;
64        copy.flag(name).is_some_and(|on| *on)
65    }
66
67    /// Put the category `name` in the set. `Err` holds the name when
68    /// it is not a category.
69    pub fn add(&mut self, name: &str) -> Result<(), String> {
70        match self.flag(name) {
71            Some(flag) => {
72                *flag = true;
73                Ok(())
74            }
75            None => Err(name.to_string()),
76        }
77    }
78
79    /// The categories' names, in listing order.
80    pub fn list(&self) -> Vec<&'static str> {
81        CATEGORY_NAMES
82            .iter()
83            .filter(|name| self.has(name))
84            .copied()
85            .collect()
86    }
87
88    /// The categories' names, comma separated.
89    pub fn names(&self) -> String {
90        self.list().join(",")
91    }
92}
93
94/// The readings come from `/proc` and `/sys`, which only Linux has.
95pub const fn platform_supported() -> bool {
96    cfg!(target_os = "linux")
97}
98
99/// Why this host cannot supply the category `name`, or `None` when it
100/// can. The reason is a sentence that follows "…, but": it does not
101/// say who asked.
102///
103/// `cpu`, `io`, `ram`, `storage`, `net` and `proc` need only `/proc`.
104/// `rambw` needs resctrl, `pressure` the kernel's stall accounting,
105/// and `cgroup` the unified hierarchy.
106pub fn unavailable(name: &str) -> Option<String> {
107    if !platform_supported() {
108        return Some(
109            "the host's readings come from /proc and are available on Linux only".to_string(),
110        );
111    }
112    match name {
113        "rambw" if crate::mem::read_membw_bytes().is_none() => Some(
114            "\
115the kernel resctrl interface is not available at /sys/fs/resctrl/mon_data.
116
117To enable memory-bandwidth monitoring:
118  1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
119     check for the `cqm_mbm_total` flag:  grep -m1 cqm_mbm_total /proc/cpuinfo
120  2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
121     mainstream distro kernels).
122  3. Mount the interface:  sudo mount -t resctrl resctrl /sys/fs/resctrl
123
124Most virtual machines cannot support it."
125                .to_string(),
126        ),
127        "pressure" if crate::pressure::read_pressure().is_none() => Some(
128            "the kernel's pressure stall information is not readable at /proc/pressure. \
129             It needs a kernel built with CONFIG_PSI (4.20 or later) that was not booted \
130             with `psi=0`, and a container must be given the host's /proc/pressure."
131                .to_string(),
132        ),
133        "cgroup" if !crate::cgroup::hierarchy_available() => Some(format!(
134            "the unified control group hierarchy (cgroup v2) is not mounted at {}.",
135            crate::cgroup::ROOT
136        )),
137        _ => None,
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn a_set_is_built_by_name_and_listed_in_order() {
147        let mut cats = Categories::default();
148        assert!(!cats.any());
149        for name in ["proc", "cpu", "cgroup"] {
150            cats.add(name).unwrap();
151        }
152        assert_eq!(cats.names(), "cpu,proc,cgroup");
153        assert!(cats.has("proc") && !cats.has("io") && !cats.has("disk"));
154        assert_eq!(cats.add("disk"), Err("disk".to_string()));
155    }
156
157    #[test]
158    fn every_name_is_a_category() {
159        let mut all = Categories::default();
160        for name in CATEGORY_NAMES {
161            all.add(name).unwrap();
162        }
163        assert_eq!(all, Categories::ALL);
164    }
165
166    /// The categories that read only /proc are there on any Linux.
167    #[cfg(target_os = "linux")]
168    #[test]
169    fn the_proc_categories_need_nothing_more() {
170        for name in ["cpu", "io", "ram", "storage", "net", "proc"] {
171            assert_eq!(unavailable(name), None, "{name}");
172        }
173    }
174}