Skip to main content

nmbrs_runtime/sysmon/
disk.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Disks: how busy the busiest device is and how much each device
5//! reads and writes, from `/proc/diskstats`; and how full the fullest
6//! filesystem is, from statvfs (SRD-118 §3.2, §3.5).
7
8/// One device's cumulative counters from `/proc/diskstats`.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct DiskCounters {
11    pub name: String,
12    /// Reads completed.
13    pub reads: u64,
14    /// Sectors read. A sector here is 512 bytes whatever the device's.
15    pub read_sectors: u64,
16    /// Writes completed.
17    pub writes: u64,
18    /// Sectors written.
19    pub write_sectors: u64,
20    /// Milliseconds the device had I/O in flight.
21    pub io_ticks: u64,
22}
23
24/// The size `/proc/diskstats` counts sectors in.
25const SECTOR_BYTES: f64 = 512.0;
26
27/// Every device's cumulative counters. Field layout per the kernel's
28/// Documentation/iostats: `major minor name <stat fields>`, where
29/// reads completed is stat field 1, sectors read 3, writes completed
30/// 5, sectors written 7 and io_ticks 10 (whitespace tokens 3, 5, 7, 9
31/// and 12).
32pub fn parse_diskstats(text: &str) -> Vec<DiskCounters> {
33    text.lines()
34        .filter_map(|line| {
35            let t: Vec<&str> = line.split_whitespace().collect();
36            let field = |at: usize| -> Option<u64> { t.get(at)?.parse().ok() };
37            Some(DiskCounters {
38                name: t.get(2)?.to_string(),
39                reads: field(3)?,
40                read_sectors: field(5)?,
41                writes: field(7)?,
42                write_sectors: field(9)?,
43                io_ticks: field(12)?,
44            })
45        })
46        .collect()
47}
48
49/// The highest per-device utilization between two diskstats snapshots taken
50/// `dt_ms` apart. Devices present in only one snapshot are skipped (hotplug
51/// between samples); an empty intersection yields `None`.
52pub fn max_disk_util(
53    prev: &[DiskCounters],
54    cur: &[DiskCounters],
55    dt_ms: f64,
56) -> Option<(String, f64)> {
57    if dt_ms <= 0.0 {
58        return None;
59    }
60    let mut best: Option<(String, f64)> = None;
61    for now in cur {
62        let Some(before) = prev.iter().find(|d| d.name == now.name) else {
63            continue;
64        };
65        let util = (now.io_ticks.saturating_sub(before.io_ticks) as f64 / dt_ms).clamp(0.0, 1.0);
66        if best.as_ref().is_none_or(|(_, b)| util > *b) {
67            best = Some((now.name.clone(), util));
68        }
69    }
70    best
71}
72
73/// What one device read and wrote over a sample window.
74#[derive(Debug, Clone, PartialEq)]
75pub struct DiskRate {
76    pub device: String,
77    pub read_bytes_per_s: f64,
78    pub write_bytes_per_s: f64,
79    pub read_ops_per_s: f64,
80    pub write_ops_per_s: f64,
81}
82
83/// Each device's throughput between two snapshots `dt_s` apart, for the
84/// devices `counted` accepts and that are in both snapshots.
85///
86/// `/proc/diskstats` lists a device and each of its partitions, and the
87/// partitions' counters are part of the device's. `counted` is what
88/// keeps a byte from being reported twice ([`is_whole_device`]).
89pub fn disk_rates(
90    prev: &[DiskCounters],
91    cur: &[DiskCounters],
92    dt_s: f64,
93    counted: &dyn Fn(&str) -> bool,
94) -> Vec<DiskRate> {
95    if dt_s <= 0.0 {
96        return Vec::new();
97    }
98    cur.iter()
99        .filter(|now| counted(&now.name))
100        .filter_map(|now| {
101            let before = prev.iter().find(|d| d.name == now.name)?;
102            let per_s = |now: u64, before: u64| now.saturating_sub(before) as f64 / dt_s;
103            Some(DiskRate {
104                device: now.name.clone(),
105                read_bytes_per_s: per_s(now.read_sectors, before.read_sectors) * SECTOR_BYTES,
106                write_bytes_per_s: per_s(now.write_sectors, before.write_sectors) * SECTOR_BYTES,
107                read_ops_per_s: per_s(now.reads, before.reads),
108                write_ops_per_s: per_s(now.writes, before.writes),
109            })
110        })
111        .collect()
112}
113
114/// True for a device whose throughput is reported: a whole block
115/// device (it has a directory in `/sys/block`; a partition does not)
116/// that is not a loop, RAM or compressed-RAM device.
117pub fn is_whole_device(name: &str) -> bool {
118    if ["loop", "ram", "zram"].iter().any(|p| name.starts_with(p)) {
119        return false;
120    }
121    std::path::Path::new("/sys/block").join(name).exists()
122}
123
124/// Read `/proc/diskstats`. Empty when it cannot be read.
125pub(super) fn read_diskstats() -> Vec<DiskCounters> {
126    std::fs::read_to_string("/proc/diskstats")
127        .map(|t| parse_diskstats(&t))
128        .unwrap_or_default()
129}
130
131/// WRITABLE `/dev/`-backed mount points from `/proc/mounts`, deduplicated by
132/// source device (bind mounts and btrfs subvolumes re-list one device many
133/// times; space is a per-DEVICE fact).
134///
135/// Read-only mounts are excluded, and it matters: snap images are
136/// `/dev/loop*` squashfs mounts that are 100% full BY CONSTRUCTION, so one
137/// installed snap would pin the storage item at bright-orange forever.
138/// Verified on this host — `/dev/loop0 /snap/... ro,...` at 100% while the
139/// fullest writable filesystem sat at 40%. A read-only filesystem cannot
140/// fill up, so its fullness is not a utilization.
141pub fn parse_dev_mounts(text: &str) -> Vec<String> {
142    let mut seen_sources: Vec<&str> = Vec::new();
143    let mut mounts = Vec::new();
144    for line in text.lines() {
145        let mut t = line.split_whitespace();
146        let (Some(source), Some(mount), _fstype, Some(options)) =
147            (t.next(), t.next(), t.next(), t.next())
148        else {
149            continue;
150        };
151        if !source.starts_with("/dev/") || seen_sources.contains(&source) {
152            continue;
153        }
154        let read_only = options.split(',').any(|o| o == "ro");
155        if read_only {
156            continue;
157        }
158        seen_sources.push(source);
159        // /proc/mounts octal-escapes spaces in mount points (\040).
160        mounts.push(mount.replace("\\040", " "));
161    }
162    mounts
163}
164
165/// Space utilization of one filesystem: `1 − available/total`, matching what
166/// `df` calls Use%. `None` on statvfs failure or a zero-block pseudo-fs.
167/// Unix-only, like its caller [`max_storage_util`] (which walks
168/// `/proc/mounts` and therefore never yields a mount elsewhere).
169#[cfg(unix)]
170fn statvfs_util(mount: &str) -> Option<f64> {
171    let c_mount = std::ffi::CString::new(mount).ok()?;
172    let mut vfs: libc::statvfs = unsafe { std::mem::zeroed() };
173    if unsafe { libc::statvfs(c_mount.as_ptr(), &mut vfs) } != 0 {
174        return None;
175    }
176    if vfs.f_blocks == 0 {
177        return None;
178    }
179    Some((1.0 - vfs.f_bavail as f64 / vfs.f_blocks as f64).clamp(0.0, 1.0))
180}
181
182/// The fullest `/dev/`-backed filesystem right now: (mount point, util).
183pub(super) fn max_storage_util() -> Option<(String, f64)> {
184    #[cfg(unix)]
185    {
186        let mounts = std::fs::read_to_string("/proc/mounts")
187            .map(|t| parse_dev_mounts(&t))
188            .unwrap_or_default();
189        mounts
190            .into_iter()
191            .filter_map(|m| statvfs_util(&m).map(|u| (m, u)))
192            .max_by(|a, b| a.1.total_cmp(&b.1))
193    }
194    // No `/proc/mounts` off Unix — storage-utilization sampling
195    // is simply unavailable there.
196    #[cfg(not(unix))]
197    {
198        None
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    /// A device with only its busy time set.
207    fn ticks(name: &str, io_ticks: u64) -> DiskCounters {
208        DiskCounters {
209            name: name.into(),
210            reads: 0,
211            read_sectors: 0,
212            writes: 0,
213            write_sectors: 0,
214            io_ticks,
215        }
216    }
217
218    /// Throughput is the counters' difference over the window, in
219    /// bytes for sectors, and a partition is left to its device.
220    #[test]
221    fn rates_are_per_second_and_partitions_are_not_counted_twice() {
222        let at = |name: &str, reads, read_sectors, writes, write_sectors| DiskCounters {
223            name: name.into(),
224            reads,
225            read_sectors,
226            writes,
227            write_sectors,
228            io_ticks: 0,
229        };
230        let prev = vec![
231            at("sda", 10, 1000, 20, 2000),
232            at("sda1", 10, 1000, 20, 2000),
233        ];
234        let cur = vec![
235            at("sda", 30, 5000, 60, 4000),
236            at("sda1", 30, 5000, 60, 4000),
237        ];
238        let rates = disk_rates(&prev, &cur, 2.0, &|name| name == "sda");
239        assert_eq!(
240            rates,
241            vec![DiskRate {
242                device: "sda".into(),
243                read_bytes_per_s: 2000.0 * 512.0,
244                write_bytes_per_s: 1000.0 * 512.0,
245                read_ops_per_s: 10.0,
246                write_ops_per_s: 20.0,
247            }]
248        );
249        assert!(disk_rates(&prev, &cur, 0.0, &|_| true).is_empty());
250    }
251
252    /// Real lines from this host's /proc/diskstats — io_ticks is token 12.
253    #[test]
254    fn diskstats_reads_io_ticks_from_the_tenth_stat_field() {
255        let text = "\
256 259       0 nvme0n1 1083809 77036 79071293 1310486 4905083 3299234 633830668 26973654 0 3344862 28284141 0 0 0 0 0 0
257 259       5 nvme1n1 16478852962 684755 139660303464 4041025697 191545776 3994164 30038357911 3695409309 0 588447592 3442404703 29888 5913 38808742648 936992 0 0";
258        let parsed = parse_diskstats(text);
259        assert_eq!(
260            parsed[0],
261            DiskCounters {
262                name: "nvme0n1".into(),
263                reads: 1_083_809,
264                read_sectors: 79_071_293,
265                writes: 4_905_083,
266                write_sectors: 633_830_668,
267                io_ticks: 3_344_862,
268            }
269        );
270        assert_eq!(parsed[1].name, "nvme1n1");
271        assert_eq!(parsed[1].io_ticks, 588_447_592);
272    }
273
274    /// Highest utilization wins and is named; a device busy 1000ms of a
275    /// 2000ms window is 50%.
276    #[test]
277    fn disk_util_is_the_max_across_devices() {
278        let prev = vec![ticks("a", 1000), ticks("b", 5000)];
279        let cur = vec![ticks("a", 1400), ticks("b", 6000)];
280        let (name, util) = max_disk_util(&prev, &cur, 2000.0).unwrap();
281        assert_eq!(name, "b");
282        assert!((util - 0.5).abs() < 1e-9);
283    }
284    /// A window with no elapsed time or no shared devices yields nothing
285    /// rather than a fabricated zero.
286    #[test]
287    fn degenerate_windows_yield_none() {
288        let d = vec![ticks("a", 5)];
289        assert!(max_disk_util(&d, &d, 0.0).is_none());
290        assert!(max_disk_util(&[], &d, 1000.0).is_none());
291    }
292
293    /// Only WRITABLE /dev/-backed mounts count for storage, deduplicated by
294    /// source. Pseudo-filesystems are not disks; a read-only squashfs snap
295    /// image is 100% full by construction and would pin the item forever.
296    #[test]
297    fn dev_mounts_are_filtered_and_deduplicated() {
298        let mounts = "\
299proc /proc proc rw 0 0
300/dev/nvme0n1p1 / ext4 rw 0 0
301tmpfs /tmp tmpfs rw 0 0
302/dev/loop0 /snap/core22/2045 squashfs ro,nodev 0 0
303/dev/nvme1n1 /mnt/nvme xfs rw 0 0
304/dev/nvme1n1 /mnt/alias xfs rw 0 0
305/dev/mapper/vg-data /data\\040dir ext4 rw 0 0";
306        assert_eq!(
307            parse_dev_mounts(mounts),
308            vec![
309                "/".to_string(),
310                "/mnt/nvme".to_string(),
311                "/data dir".to_string(),
312            ]
313        );
314    }
315}