1use core::time::Duration;
13use std::{
14 path::{Path, PathBuf},
15 time::Instant,
16};
17
18use crate::{Bytes, Error, Percent, Pressure, Rate, Result};
19
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
22#[non_exhaustive]
23pub struct Space {
24 pub total: Bytes,
26 pub free: Bytes,
28 pub available: Bytes,
30}
31
32impl Space {
33 #[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))] pub(crate) fn new(total: u64, free: u64, available: u64) -> Space {
36 let free = free.min(total);
37 Space {
38 total: Bytes::new(total),
39 free: Bytes::new(free),
40 available: Bytes::new(available.min(free)),
41 }
42 }
43
44 #[must_use]
46 pub fn used(&self) -> Bytes {
47 self.total.saturating_sub(self.free)
48 }
49
50 #[must_use]
52 pub fn used_percent(&self) -> Percent {
53 self.used().percent_of(self.total)
54 }
55}
56
57pub fn space(path: impl AsRef<Path>) -> Result<Space> {
76 crate::sys::disk_space(path.as_ref())
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct Disk {
83 pub mount_point: PathBuf,
85 pub device: String,
87 pub label: Option<String>,
89 pub filesystem: String,
91 pub kind: DiskKind,
93 pub space: Option<Space>,
96 pub read_only: bool,
98 pub removable: bool,
100}
101
102#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
105#[non_exhaustive]
106pub enum DiskKind {
107 Ssd,
109 Hdd,
111 Removable,
113 Network,
115 Optical,
117 Ram,
119 Virtual,
121 Unknown,
123}
124
125#[derive(Clone, Copy, Debug)]
127#[non_exhaustive]
128pub struct ListOptions {
129 pub include_network: bool,
132 pub include_pseudo: bool,
135 pub include_duplicates: bool,
138 pub max_mounts: usize,
140}
141
142impl Default for ListOptions {
143 fn default() -> Self {
144 ListOptions {
145 include_network: false,
146 include_pseudo: false,
147 include_duplicates: false,
148 max_mounts: 4_096,
149 }
150 }
151}
152
153pub fn list() -> Result<Vec<Disk>> {
171 list_with(ListOptions::default())
172}
173
174pub fn list_with(options: ListOptions) -> Result<Vec<Disk>> {
189 let mut disks = crate::sys::disks(&options)?;
190 disks.sort_by(|a, b| a.mount_point.cmp(&b.mount_point));
191 Ok(disks)
192}
193
194pub const DEFAULT_WINDOW: Duration = Duration::from_secs(1);
196
197const MIN_WINDOW: Duration = Duration::from_millis(100);
198const MAX_WINDOW: Duration = Duration::from_secs(60);
199
200#[derive(Clone, Copy, PartialEq, Debug)]
202#[non_exhaustive]
203pub struct DiskIo {
204 pub read: Rate,
206 pub write: Rate,
208 pub reads_per_sec: f64,
210 pub writes_per_sec: f64,
212 pub busy: Option<Percent>,
214 pub average_latency: Option<Duration>,
216 pub interval: Duration,
218}
219
220#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
222#[non_exhaustive]
223pub struct IoTotals {
224 pub read: Bytes,
226 pub written: Bytes,
228 pub reads: u64,
230 pub writes: u64,
232 pub io_time: Option<Duration>,
234}
235
236#[derive(Clone, Debug, PartialEq)]
238#[non_exhaustive]
239pub struct DeviceIo {
240 pub device: String,
242 pub io: DiskIo,
244}
245
246#[derive(Clone, Debug, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct IoCounters {
250 pub device: String,
252 pub totals: IoTotals,
254}
255
256#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
258pub(crate) struct DiskRaw {
259 pub(crate) read: u64,
260 pub(crate) written: u64,
261 pub(crate) reads: u64,
262 pub(crate) writes: u64,
263 pub(crate) busy: Option<Duration>,
265 pub(crate) op_time: Option<Duration>,
267 pub(crate) disks: u32,
270}
271
272impl DiskRaw {
273 #[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))] pub(crate) fn add(&mut self, other: &DiskRaw) {
275 self.read = self.read.saturating_add(other.read);
276 self.written = self.written.saturating_add(other.written);
277 self.reads = self.reads.saturating_add(other.reads);
278 self.writes = self.writes.saturating_add(other.writes);
279 self.busy = add_opt(self.busy, other.busy);
280 self.op_time = add_opt(self.op_time, other.op_time);
281 self.disks = self.disks.saturating_add(other.disks);
282 }
283
284 fn totals(&self) -> IoTotals {
285 IoTotals {
286 read: Bytes::new(self.read),
287 written: Bytes::new(self.written),
288 reads: self.reads,
289 writes: self.writes,
290 io_time: self.busy,
291 }
292 }
293
294 fn rates_since(&self, earlier: &DiskRaw, interval: Duration) -> DiskIo {
298 let d = |new: u64, old: u64| new.saturating_sub(old);
299 let secs = interval.as_secs_f64();
300 let ops = d(self.reads, earlier.reads).saturating_add(d(self.writes, earlier.writes));
301 let per_sec = |n: u64| if secs > 0.0 { n as f64 / secs } else { 0.0 };
302 DiskIo {
303 read: Rate::from_delta(d(self.read, earlier.read), interval),
304 write: Rate::from_delta(d(self.written, earlier.written), interval),
305 reads_per_sec: per_sec(d(self.reads, earlier.reads)),
306 writes_per_sec: per_sec(d(self.writes, earlier.writes)),
307 busy: match (self.busy, earlier.busy) {
309 (Some(n), Some(o)) if !interval.is_zero() => Some(Percent::from_ratio_u128(
310 n.checked_sub(o).unwrap_or_default().as_nanos(),
311 interval.as_nanos() * u128::from(self.disks.max(1)),
312 )),
313 _ => None,
314 },
315 average_latency: match (self.op_time, earlier.op_time) {
316 (Some(n), Some(o)) if ops > 0 => {
317 let spent = n.checked_sub(o).unwrap_or_default();
318 Some(spent / u32::try_from(ops).unwrap_or(u32::MAX))
319 }
320 _ => None,
321 },
322 interval,
323 }
324 }
325}
326
327#[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))]
328fn add_opt(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> {
329 match (a, b) {
330 (Some(a), Some(b)) => Some(a.saturating_add(b)),
331 (a, None) => a,
332 (None, b) => b,
333 }
334}
335
336pub fn io() -> Result<DiskIo> {
354 io_over(DEFAULT_WINDOW)
355}
356
357pub fn io_over(window: Duration) -> Result<DiskIo> {
364 let mut sampler = IoSampler::totals_only()?;
365 std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
366 sampler.sample()
367}
368
369pub fn io_totals() -> Result<IoTotals> {
377 crate::sys::disk_io_totals().map(|r| r.totals())
378}
379
380pub fn io_counters() -> Result<Vec<IoCounters>> {
386 Ok(crate::sys::disk_io_counters()?
387 .into_iter()
388 .map(|(device, raw)| IoCounters {
389 device,
390 totals: raw.totals(),
391 })
392 .collect())
393}
394
395pub fn pressure() -> Result<Option<Pressure>> {
411 crate::sys::disk_pressure()
412}
413
414#[derive(Debug)]
430pub struct IoSampler {
431 total: DiskRaw,
432 at: Instant,
433 devices: Vec<(String, DiskRaw)>,
434 devices_at: Instant,
435}
436
437impl IoSampler {
438 pub fn new() -> Result<IoSampler> {
444 let now = Instant::now();
445 Ok(IoSampler {
446 total: crate::sys::disk_io_totals()?,
447 at: now,
448 devices: crate::sys::disk_io_counters()?,
449 devices_at: now,
450 })
451 }
452
453 fn totals_only() -> Result<IoSampler> {
454 let now = Instant::now();
455 Ok(IoSampler {
456 total: crate::sys::disk_io_totals()?,
457 at: now,
458 devices: Vec::new(),
459 devices_at: now,
460 })
461 }
462
463 pub fn sample(&mut self) -> Result<DiskIo> {
471 let now = crate::sys::disk_io_totals()?;
472 let at = Instant::now();
473 let interval = at.duration_since(self.at);
474 if interval.is_zero() {
475 return Err(too_soon(interval));
476 }
477 let io = now.rates_since(&self.total, interval);
478 self.total = now;
479 self.at = at;
480 Ok(io)
481 }
482
483 pub fn sample_per_disk(&mut self) -> Result<Vec<DeviceIo>> {
490 let now = crate::sys::disk_io_counters()?;
491 let at = Instant::now();
492 let interval = at.duration_since(self.devices_at);
493 if interval.is_zero() {
494 return Err(too_soon(interval));
495 }
496 let out = now
497 .iter()
498 .map(|(device, raw)| {
499 let earlier = self
500 .devices
501 .iter()
502 .find(|(d, _)| d == device)
503 .map_or(*raw, |(_, r)| *r);
504 DeviceIo {
505 device: device.clone(),
506 io: raw.rates_since(&earlier, interval),
507 }
508 })
509 .collect();
510 self.devices = now;
511 self.devices_at = at;
512 Ok(out)
513 }
514}
515
516fn too_soon(elapsed: Duration) -> Error {
517 Error::TooSoon {
518 elapsed,
519 minimum: Duration::from_millis(1),
520 }
521}
522
523#[cfg(test)]
524mod tests {
525 use super::*;
526
527 #[test]
528 fn test_disk_busy_across_two_disks_is_the_mean() {
529 let one = |busy_ms: u64| DiskRaw {
530 busy: Some(Duration::from_millis(busy_ms)),
531 disks: 1,
532 ..DiskRaw::default()
533 };
534 let (mut before, mut after) = (one(0), one(600));
535 before.add(&one(0));
536 after.add(&one(600));
537 let io = after.rates_since(&before, Duration::from_secs(1));
538 assert_eq!(io.busy.unwrap().to_string(), "60.0%");
539 }
540
541 #[test]
542 fn test_disk_space_invariants() {
543 let s = Space::new(100, 150, 200);
544 assert_eq!(
545 (s.total.raw(), s.free.raw(), s.available.raw()),
546 (100, 100, 100)
547 );
548 let s = Space::new(1000, 400, 300);
549 assert_eq!(s.used().raw(), 600);
550 assert_eq!(s.used_percent().to_string(), "60.0%");
551 assert_eq!(Space::new(0, 0, 0).used_percent(), Percent::ZERO);
552 }
553
554 #[test]
555 fn test_disk_rates_and_backwards_counters() {
556 let a = DiskRaw {
557 read: 1 << 20,
558 written: 0,
559 reads: 10,
560 writes: 0,
561 busy: Some(Duration::from_millis(100)),
562 op_time: Some(Duration::from_millis(20)),
563 disks: 1,
564 };
565 let b = DiskRaw {
566 read: 3 << 20,
567 written: 1 << 20,
568 reads: 30,
569 writes: 10,
570 busy: Some(Duration::from_millis(600)),
571 op_time: Some(Duration::from_millis(80)),
572 disks: 1,
573 };
574 let io = b.rates_since(&a, Duration::from_secs(1));
575 assert_eq!(io.read.to_string(), "2 MiB/s");
576 assert_eq!(io.write.to_string(), "1 MiB/s");
577 assert!((io.reads_per_sec - 20.0).abs() < 1e-9 && (io.writes_per_sec - 10.0).abs() < 1e-9);
578 assert_eq!(io.busy.unwrap().to_string(), "50.0%");
579 assert_eq!(io.average_latency, Some(Duration::from_millis(2)));
580 let back = a.rates_since(&b, Duration::from_secs(1));
582 assert_eq!((back.read, back.write), (Rate::ZERO, Rate::ZERO));
583 assert_eq!(back.busy.unwrap(), Percent::ZERO);
584 assert_eq!(back.average_latency, None);
585 }
586
587 #[test]
588 fn test_disk_live_space_and_list() {
589 let s = space(".").unwrap();
590 assert!(s.total.raw() > 0 && s.available <= s.free && s.free <= s.total);
591 let disks = list().unwrap();
592 assert!(
593 disks
594 .windows(2)
595 .all(|w| w[0].mount_point <= w[1].mount_point)
596 );
597 for d in &disks {
598 assert!(!d.filesystem.is_empty(), "{d:?}");
599 }
600 assert!(matches!(space("/definitely/not/here/sys-lib"), Err(e) if e.is_unavailable()));
601 }
602}