Skip to main content

nmbrs_host/
snapshot.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! One reading of chosen categories, as named measures (SRD-118
5//! ยง6.6).
6//!
7//! Where the sampler turns two readings into a rate, this reads once
8//! and gives the kernel's counters as they stand, with the levels
9//! beside them. A measure whose name ends in `_total` is a counter,
10//! counted from boot (for a process or a control group, from its
11//! start); two readings of it are subtracted to get what happened
12//! between them.
13
14use crate::category::Categories;
15use crate::cgroup::CgroupTarget;
16use crate::process::{OWN_NAME, ProcSource, ProcTarget};
17
18/// One measure of one reading.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Measure {
21    /// The measure's name, such as `io_write_bytes_total`.
22    pub name: &'static str,
23    /// What the measure is of, outermost first: `[("device", "sda")]`,
24    /// or `[("cgroup", "node"), ("device", "sda")]`. Empty for a
25    /// measure of the host as a whole.
26    pub subject: Vec<(&'static str, String)>,
27    pub value: f64,
28}
29
30/// One reading.
31#[derive(Debug, Clone, PartialEq, Default)]
32pub struct Snapshot {
33    pub measures: Vec<Measure>,
34    /// What was asked for and could not be read, each as a sentence.
35    pub absent: Vec<String>,
36}
37
38impl Snapshot {
39    fn host(&mut self, name: &'static str, value: f64) {
40        self.measures.push(Measure {
41            name,
42            subject: Vec::new(),
43            value,
44        });
45    }
46
47    fn of(&mut self, name: &'static str, subject: &[(&'static str, &str)], value: f64) {
48        self.measures.push(Measure {
49            name,
50            subject: subject.iter().map(|(k, v)| (*k, v.to_string())).collect(),
51            value,
52        });
53    }
54}
55
56/// The size `/proc/diskstats` counts sectors in.
57const SECTOR_BYTES: f64 = 512.0;
58
59/// Read the categories in `cats` once. `procs` are read besides nmbrs
60/// itself under `proc`, and `cgroups` under `cgroup`.
61///
62/// Reads `/proc` and `/sys`, and asks each mounted filesystem under
63/// `storage`: call it from a thread that may block.
64pub fn read(cats: Categories, procs: &[ProcTarget], cgroups: &[CgroupTarget]) -> Snapshot {
65    let mut out = Snapshot::default();
66    let (ticks_per_s, page_bytes) = crate::process::units();
67
68    if cats.cpu {
69        match crate::cpu::read_proc_stat() {
70            Some((all, _)) => {
71                out.host("cpu_busy_seconds_total", all.busy as f64 / ticks_per_s);
72                out.host("cpu_seconds_total", all.total as f64 / ticks_per_s);
73            }
74            None => out.absent.push("/proc/stat could not be read".into()),
75        }
76    }
77    if cats.io {
78        for disk in crate::disk::read_diskstats()
79            .iter()
80            .filter(|d| crate::disk::is_whole_device(&d.name))
81        {
82            let device = [("device", disk.name.as_str())];
83            out.of(
84                "io_read_bytes_total",
85                &device,
86                disk.read_sectors as f64 * SECTOR_BYTES,
87            );
88            out.of(
89                "io_write_bytes_total",
90                &device,
91                disk.write_sectors as f64 * SECTOR_BYTES,
92            );
93            out.of("io_read_ops_total", &device, disk.reads as f64);
94            out.of("io_write_ops_total", &device, disk.writes as f64);
95            out.of(
96                "io_busy_seconds_total",
97                &device,
98                disk.io_ticks as f64 / 1000.0,
99            );
100        }
101    }
102    if cats.ram {
103        match std::fs::read_to_string("/proc/meminfo")
104            .ok()
105            .and_then(|t| crate::mem::parse_meminfo(&t))
106        {
107            Some(mem) => {
108                out.host("ram_total_bytes", mem.total_kb as f64 * 1024.0);
109                out.host("ram_available_bytes", mem.available_kb as f64 * 1024.0);
110                out.host("ram_free_bytes", mem.free_kb as f64 * 1024.0);
111            }
112            None => out.absent.push("/proc/meminfo could not be read".into()),
113        }
114    }
115    if cats.rambw {
116        match crate::mem::read_membw_bytes() {
117            Some(bytes) => out.host("rambw_bytes_total", bytes as f64),
118            None => out
119                .absent
120                .push("the resctrl memory-bandwidth counters could not be read".into()),
121        }
122    }
123    if cats.storage {
124        for (mount, total, available) in crate::disk::read_mount_sizes() {
125            let mount = [("mount", mount.as_str())];
126            out.of("storage_total_bytes", &mount, total as f64);
127            out.of("storage_available_bytes", &mount, available as f64);
128        }
129    }
130    if cats.net {
131        for iface in crate::net::read_net_dev() {
132            let subject = [("iface", iface.iface.as_str())];
133            out.of("net_rx_bytes_total", &subject, iface.rx_bytes as f64);
134            out.of("net_tx_bytes_total", &subject, iface.tx_bytes as f64);
135        }
136    }
137    if cats.pressure {
138        match crate::pressure::read_pressure() {
139            Some(p) => {
140                let seconds = |us: u64| us as f64 / 1e6;
141                out.host("pressure_cpu_seconds_total", seconds(p.cpu.some_us));
142                out.host("pressure_mem_seconds_total", seconds(p.mem.some_us));
143                out.host("pressure_io_seconds_total", seconds(p.io.some_us));
144                if let Some(full) = p.mem.full_us {
145                    out.host("pressure_mem_full_seconds_total", seconds(full));
146                }
147                if let Some(full) = p.io.full_us {
148                    out.host("pressure_io_full_seconds_total", seconds(full));
149                }
150            }
151            None => out.absent.push("/proc/pressure could not be read".into()),
152        }
153    }
154    if cats.proc {
155        let own = ProcTarget {
156            name: OWN_NAME.to_string(),
157            source: ProcSource::Own,
158        };
159        for target in std::iter::once(&own).chain(procs) {
160            let found = crate::process::resolve_pid(&target.source)
161                .and_then(|pid| Some((pid, crate::process::read_counters(pid)?)));
162            let Some((pid, counters)) = found else {
163                out.absent.push(format!(
164                    "process '{}' is not running (or its pidfile is unreadable)",
165                    target.name
166                ));
167                continue;
168            };
169            let subject = [("proc", target.name.as_str())];
170            out.of(
171                "proc_cpu_seconds_total",
172                &subject,
173                counters.cpu_ticks as f64 / ticks_per_s,
174            );
175            out.of(
176                "proc_rss_bytes",
177                &subject,
178                counters.rss_pages as f64 * page_bytes,
179            );
180            out.of("proc_threads", &subject, counters.threads as f64);
181            out.of("proc_pid", &subject, pid as f64);
182            match counters.io {
183                Some((read, write)) => {
184                    out.of("proc_read_bytes_total", &subject, read as f64);
185                    out.of("proc_write_bytes_total", &subject, write as f64);
186                }
187                None => out.absent.push(format!(
188                    "the storage I/O of process '{}' may not be read (it belongs to \
189                     another user)",
190                    target.name
191                )),
192            }
193        }
194    }
195    if cats.cgroup {
196        let devices = crate::disk::read_device_numbers();
197        for target in cgroups {
198            let Some(counters) = crate::cgroup::read_counters(&target.dir, &devices) else {
199                out.absent.push(format!(
200                    "control group '{}' is not there ({})",
201                    target.name,
202                    target.dir.display()
203                ));
204                continue;
205            };
206            let group = target.name.as_str();
207            if let Some(usec) = counters.cpu_usec {
208                out.of(
209                    "cgroup_cpu_seconds_total",
210                    &[("cgroup", group)],
211                    usec as f64 / 1e6,
212                );
213            }
214            if let Some(bytes) = counters.mem_bytes {
215                out.of("cgroup_mem_bytes", &[("cgroup", group)], bytes as f64);
216            }
217            for io in &counters.io {
218                let subject = [("cgroup", group), ("device", io.device.as_str())];
219                out.of("cgroup_io_read_bytes_total", &subject, io.read_bytes as f64);
220                out.of(
221                    "cgroup_io_write_bytes_total",
222                    &subject,
223                    io.write_bytes as f64,
224                );
225                out.of("cgroup_io_read_ops_total", &subject, io.reads as f64);
226                out.of("cgroup_io_write_ops_total", &subject, io.writes as f64);
227            }
228        }
229    }
230    out
231}
232
233#[cfg(all(test, target_os = "linux"))]
234mod tests {
235    use super::*;
236
237    fn value(snapshot: &Snapshot, name: &str) -> Option<f64> {
238        snapshot
239            .measures
240            .iter()
241            .find(|m| m.name == name)
242            .map(|m| m.value)
243    }
244
245    /// Only what was asked for is read.
246    #[test]
247    fn only_the_named_categories_are_read() {
248        let cats = Categories {
249            ram: true,
250            ..Categories::default()
251        };
252        let snapshot = read(cats, &[], &[]);
253        assert!(snapshot.measures.iter().all(|m| m.name.starts_with("ram_")));
254        let total = value(&snapshot, "ram_total_bytes").unwrap();
255        assert!(total > 0.0 && value(&snapshot, "ram_available_bytes").unwrap() <= total);
256    }
257
258    /// nmbrs's own process is always read under `proc`, and a counter
259    /// read twice does not go down.
260    #[test]
261    fn counters_do_not_go_down_between_two_readings() {
262        let cats = Categories {
263            cpu: true,
264            proc: true,
265            ..Categories::default()
266        };
267        let first = read(cats, &[], &[]);
268        let second = read(cats, &[], &[]);
269        for name in ["cpu_seconds_total", "proc_cpu_seconds_total"] {
270            assert!(value(&second, name).unwrap() >= value(&first, name).unwrap());
271        }
272        let own = first
273            .measures
274            .iter()
275            .find(|m| m.name == "proc_pid")
276            .unwrap();
277        assert_eq!(own.subject, vec![("proc", OWN_NAME.to_string())]);
278        assert_eq!(own.value, std::process::id() as f64);
279    }
280
281    /// What is not there is said, and has no measure.
282    #[test]
283    fn what_is_not_there_is_named() {
284        let cats = Categories {
285            proc: true,
286            cgroup: true,
287            ..Categories::default()
288        };
289        let procs = vec![ProcTarget {
290            name: "gone".into(),
291            source: ProcSource::PidFile("/nonexistent/gone.pid".into()),
292        }];
293        let cgroups = crate::cgroup::parse_cgroups("lost:no-such-group-for-this-test").unwrap();
294        let snapshot = read(cats, &procs, &cgroups);
295        assert!(snapshot.absent.iter().any(|a| a.contains("'gone'")));
296        assert!(snapshot.absent.iter().any(|a| a.contains("'lost'")));
297        assert!(
298            snapshot
299                .measures
300                .iter()
301                .all(|m| m.subject.iter().all(|(_, v)| v != "gone" && v != "lost"))
302        );
303    }
304}