1#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct DiskCounters {
11 pub name: String,
12 pub reads: u64,
14 pub read_sectors: u64,
16 pub writes: u64,
18 pub write_sectors: u64,
20 pub io_ticks: u64,
22}
23
24const SECTOR_BYTES: f64 = 512.0;
26
27pub 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
49pub 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#[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
83pub 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
114pub 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
124pub 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
131pub 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 mounts.push(mount.replace("\\040", " "));
161 }
162 mounts
163}
164
165#[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
182pub 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 #[cfg(not(unix))]
197 {
198 None
199 }
200}
201
202pub fn parse_device_numbers(text: &str) -> Vec<((u32, u32), String)> {
206 text.lines()
207 .filter_map(|line| {
208 let mut t = line.split_whitespace();
209 Some((
210 (t.next()?.parse().ok()?, t.next()?.parse().ok()?),
211 t.next()?.to_string(),
212 ))
213 })
214 .collect()
215}
216
217pub fn read_device_numbers() -> Vec<((u32, u32), String)> {
220 std::fs::read_to_string("/proc/diskstats")
221 .map(|t| parse_device_numbers(&t))
222 .unwrap_or_default()
223}
224
225pub fn read_mount_sizes() -> Vec<(String, u64, u64)> {
229 std::fs::read_to_string("/proc/mounts")
230 .map(|t| parse_dev_mounts(&t))
231 .unwrap_or_default()
232 .into_iter()
233 .filter_map(|mount| {
234 let (total, available) = crate::du::filesystem(std::path::Path::new(&mount))?;
235 (total > 0).then_some((mount, total, available))
236 })
237 .collect()
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn devices_are_named_by_number() {
246 let text = " 259 0 nvme0n1 1 2 3\n 8 16 sdb 1 2 3\n";
247 assert_eq!(
248 parse_device_numbers(text),
249 vec![
250 ((259, 0), "nvme0n1".to_string()),
251 ((8, 16), "sdb".to_string())
252 ]
253 );
254 }
255
256 fn ticks(name: &str, io_ticks: u64) -> DiskCounters {
258 DiskCounters {
259 name: name.into(),
260 reads: 0,
261 read_sectors: 0,
262 writes: 0,
263 write_sectors: 0,
264 io_ticks,
265 }
266 }
267
268 #[test]
271 fn rates_are_per_second_and_partitions_are_not_counted_twice() {
272 let at = |name: &str, reads, read_sectors, writes, write_sectors| DiskCounters {
273 name: name.into(),
274 reads,
275 read_sectors,
276 writes,
277 write_sectors,
278 io_ticks: 0,
279 };
280 let prev = vec![
281 at("sda", 10, 1000, 20, 2000),
282 at("sda1", 10, 1000, 20, 2000),
283 ];
284 let cur = vec![
285 at("sda", 30, 5000, 60, 4000),
286 at("sda1", 30, 5000, 60, 4000),
287 ];
288 let rates = disk_rates(&prev, &cur, 2.0, &|name| name == "sda");
289 assert_eq!(
290 rates,
291 vec![DiskRate {
292 device: "sda".into(),
293 read_bytes_per_s: 2000.0 * 512.0,
294 write_bytes_per_s: 1000.0 * 512.0,
295 read_ops_per_s: 10.0,
296 write_ops_per_s: 20.0,
297 }]
298 );
299 assert!(disk_rates(&prev, &cur, 0.0, &|_| true).is_empty());
300 }
301
302 #[test]
304 fn diskstats_reads_io_ticks_from_the_tenth_stat_field() {
305 let text = "\
306 259 0 nvme0n1 1083809 77036 79071293 1310486 4905083 3299234 633830668 26973654 0 3344862 28284141 0 0 0 0 0 0
307 259 5 nvme1n1 16478852962 684755 139660303464 4041025697 191545776 3994164 30038357911 3695409309 0 588447592 3442404703 29888 5913 38808742648 936992 0 0";
308 let parsed = parse_diskstats(text);
309 assert_eq!(
310 parsed[0],
311 DiskCounters {
312 name: "nvme0n1".into(),
313 reads: 1_083_809,
314 read_sectors: 79_071_293,
315 writes: 4_905_083,
316 write_sectors: 633_830_668,
317 io_ticks: 3_344_862,
318 }
319 );
320 assert_eq!(parsed[1].name, "nvme1n1");
321 assert_eq!(parsed[1].io_ticks, 588_447_592);
322 }
323
324 #[test]
327 fn disk_util_is_the_max_across_devices() {
328 let prev = vec![ticks("a", 1000), ticks("b", 5000)];
329 let cur = vec![ticks("a", 1400), ticks("b", 6000)];
330 let (name, util) = max_disk_util(&prev, &cur, 2000.0).unwrap();
331 assert_eq!(name, "b");
332 assert!((util - 0.5).abs() < 1e-9);
333 }
334 #[test]
337 fn degenerate_windows_yield_none() {
338 let d = vec![ticks("a", 5)];
339 assert!(max_disk_util(&d, &d, 0.0).is_none());
340 assert!(max_disk_util(&[], &d, 1000.0).is_none());
341 }
342
343 #[test]
347 fn dev_mounts_are_filtered_and_deduplicated() {
348 let mounts = "\
349proc /proc proc rw 0 0
350/dev/nvme0n1p1 / ext4 rw 0 0
351tmpfs /tmp tmpfs rw 0 0
352/dev/loop0 /snap/core22/2045 squashfs ro,nodev 0 0
353/dev/nvme1n1 /mnt/nvme xfs rw 0 0
354/dev/nvme1n1 /mnt/alias xfs rw 0 0
355/dev/mapper/vg-data /data\\040dir ext4 rw 0 0";
356 assert_eq!(
357 parse_dev_mounts(mounts),
358 vec![
359 "/".to_string(),
360 "/mnt/nvme".to_string(),
361 "/data dir".to_string(),
362 ]
363 );
364 }
365}