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(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
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(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 #[cfg(not(unix))]
197 {
198 None
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 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 #[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 #[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 #[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 #[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 #[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}