use core::time::Duration;
use std::{
path::{Path, PathBuf},
time::Instant,
};
use crate::{Bytes, Error, Percent, Pressure, Rate, Result, origin::Origin};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Space {
pub total: Bytes,
pub free: Bytes,
pub available: Bytes,
}
impl Space {
#[allow(dead_code)]
pub(crate) fn new(total: u64, free: u64, available: u64) -> Space {
let free = free.min(total);
Space {
total: Bytes::new(total),
free: Bytes::new(free),
available: Bytes::new(available.min(free)),
}
}
#[must_use]
pub fn used(&self) -> Bytes {
self.total.saturating_sub(self.free)
}
#[must_use]
pub fn used_percent(&self) -> Percent {
self.used().percent_of(self.total)
}
}
pub fn space(path: impl AsRef<Path>) -> Result<Space> {
crate::sys::disk_space(path.as_ref())
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Disk {
pub mount_point: PathBuf,
pub device: String,
pub label: Option<String>,
pub filesystem: String,
pub kind: DiskKind,
pub space: Option<Space>,
pub read_only: bool,
pub removable: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum DiskKind {
Ssd,
Hdd,
Removable,
Network,
Optical,
Ram,
Virtual,
Unknown,
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ListOptions {
pub include_network: bool,
pub include_pseudo: bool,
pub include_duplicates: bool,
pub max_mounts: usize,
}
impl Default for ListOptions {
fn default() -> Self {
ListOptions {
include_network: false,
include_pseudo: false,
include_duplicates: false,
max_mounts: 4_096,
}
}
}
pub fn list() -> Result<Vec<Disk>> {
list_with(ListOptions::default())
}
pub fn list_with(options: ListOptions) -> Result<Vec<Disk>> {
let mut disks = crate::sys::disks(&options)?;
disks.sort_by(|a, b| a.mount_point.cmp(&b.mount_point));
Ok(disks)
}
pub fn of(path: impl AsRef<Path>) -> Result<Disk> {
crate::sys::disk_of(path.as_ref())
}
pub const DEFAULT_WINDOW: Duration = Duration::from_secs(1);
const MIN_WINDOW: Duration = Duration::from_millis(100);
const MAX_WINDOW: Duration = Duration::from_secs(60);
#[derive(Clone, Copy, PartialEq, Debug)]
#[non_exhaustive]
pub struct DiskIo {
pub read: Rate,
pub write: Rate,
pub reads_per_sec: f64,
pub writes_per_sec: f64,
pub busy: Option<Percent>,
pub average_latency: Option<Duration>,
pub interval: Duration,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct IoTotals {
pub read: Bytes,
pub written: Bytes,
pub reads: u64,
pub writes: u64,
pub io_time: Option<Duration>,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct DeviceIo {
pub device: String,
pub io: DiskIo,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct IoCounters {
pub device: String,
pub totals: IoTotals,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(crate) struct DiskRaw {
pub(crate) read: u64,
pub(crate) written: u64,
pub(crate) reads: u64,
pub(crate) writes: u64,
pub(crate) busy: Option<Duration>,
pub(crate) op_time: Option<Duration>,
pub(crate) disks: u32,
}
impl DiskRaw {
#[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))] pub(crate) fn add(&mut self, other: &DiskRaw) {
self.read = self.read.saturating_add(other.read);
self.written = self.written.saturating_add(other.written);
self.reads = self.reads.saturating_add(other.reads);
self.writes = self.writes.saturating_add(other.writes);
self.busy = add_opt(self.busy, other.busy);
self.op_time = add_opt(self.op_time, other.op_time);
self.disks = self.disks.saturating_add(other.disks);
}
fn totals(&self) -> IoTotals {
IoTotals {
read: Bytes::new(self.read),
written: Bytes::new(self.written),
reads: self.reads,
writes: self.writes,
io_time: self.busy,
}
}
fn rates_since(&self, earlier: &DiskRaw, interval: Duration) -> DiskIo {
let d = |new: u64, old: u64| new.saturating_sub(old);
let secs = interval.as_secs_f64();
let ops = d(self.reads, earlier.reads).saturating_add(d(self.writes, earlier.writes));
let per_sec = |n: u64| if secs > 0.0 { n as f64 / secs } else { 0.0 };
DiskIo {
read: Rate::from_delta(d(self.read, earlier.read), interval),
write: Rate::from_delta(d(self.written, earlier.written), interval),
reads_per_sec: per_sec(d(self.reads, earlier.reads)),
writes_per_sec: per_sec(d(self.writes, earlier.writes)),
busy: match (self.busy, earlier.busy) {
(Some(n), Some(o)) if !interval.is_zero() => Some(Percent::from_ratio_u128(
n.checked_sub(o).unwrap_or_default().as_nanos(),
interval.as_nanos() * u128::from(self.disks.max(1)),
)),
_ => None,
},
average_latency: match (self.op_time, earlier.op_time) {
(Some(n), Some(o)) if ops > 0 => {
let spent = n.checked_sub(o).unwrap_or_default();
Some(spent / u32::try_from(ops).unwrap_or(u32::MAX))
}
_ => None,
},
interval,
}
}
}
#[cfg_attr(not(any(target_os = "linux", target_os = "android")), allow(dead_code))]
fn add_opt(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> {
match (a, b) {
(Some(a), Some(b)) => Some(a.saturating_add(b)),
(a, None) => a,
(None, b) => b,
}
}
pub fn io() -> Result<DiskIo> {
io_over(DEFAULT_WINDOW)
}
pub fn io_over(window: Duration) -> Result<DiskIo> {
let mut sampler = IoSampler::totals_only()?;
std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
sampler.sample()
}
pub fn io_totals() -> Result<IoTotals> {
crate::sys::disk_io_totals().map(|r| r.totals())
}
pub fn io_counters() -> Result<Vec<IoCounters>> {
Ok(crate::sys::disk_io_counters()?
.into_iter()
.map(|(device, raw)| IoCounters {
device,
totals: raw.totals(),
})
.collect())
}
pub fn pressure() -> Result<Option<Pressure>> {
crate::sys::disk_pressure()
}
#[derive(Debug)]
pub struct IoSampler {
total: DiskRaw,
at: Instant,
devices: Vec<(String, DiskRaw)>,
devices_at: Instant,
origin: Origin,
}
impl IoSampler {
pub fn new() -> Result<IoSampler> {
Self::from(Origin::local())
}
pub(crate) fn from(origin: Origin) -> Result<IoSampler> {
let now = Instant::now();
Ok(IoSampler {
total: origin.disk_io_totals()?,
at: now,
devices: origin.disk_io_counters()?,
devices_at: now,
origin,
})
}
fn totals_only() -> Result<IoSampler> {
let now = Instant::now();
Ok(IoSampler {
total: crate::sys::disk_io_totals()?,
at: now,
devices: Vec::new(),
devices_at: now,
origin: Origin::local(),
})
}
pub fn sample(&mut self) -> Result<DiskIo> {
let now = self.origin.disk_io_totals()?;
let at = Instant::now();
let interval = at.duration_since(self.at);
if interval.is_zero() {
return Err(too_soon(interval));
}
let io = now.rates_since(&self.total, interval);
self.total = now;
self.at = at;
Ok(io)
}
pub fn sample_per_disk(&mut self) -> Result<Vec<DeviceIo>> {
let now = self.origin.disk_io_counters()?;
let at = Instant::now();
let interval = at.duration_since(self.devices_at);
if interval.is_zero() {
return Err(too_soon(interval));
}
let out = now
.iter()
.map(|(device, raw)| {
let earlier = self
.devices
.iter()
.find(|(d, _)| d == device)
.map_or(*raw, |(_, r)| *r);
DeviceIo {
device: device.clone(),
io: raw.rates_since(&earlier, interval),
}
})
.collect();
self.devices = now;
self.devices_at = at;
Ok(out)
}
}
fn too_soon(elapsed: Duration) -> Error {
Error::TooSoon {
elapsed,
minimum: Duration::from_millis(1),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_disk_busy_across_two_disks_is_the_mean() {
let one = |busy_ms: u64| DiskRaw {
busy: Some(Duration::from_millis(busy_ms)),
disks: 1,
..DiskRaw::default()
};
let (mut before, mut after) = (one(0), one(600));
before.add(&one(0));
after.add(&one(600));
let io = after.rates_since(&before, Duration::from_secs(1));
assert_eq!(io.busy.unwrap().to_string(), "60.0%");
}
#[test]
fn test_disk_space_invariants() {
let s = Space::new(100, 150, 200);
assert_eq!(
(s.total.raw(), s.free.raw(), s.available.raw()),
(100, 100, 100)
);
let s = Space::new(1000, 400, 300);
assert_eq!(s.used().raw(), 600);
assert_eq!(s.used_percent().to_string(), "60.0%");
assert_eq!(Space::new(0, 0, 0).used_percent(), Percent::ZERO);
}
#[test]
fn test_disk_rates_and_backwards_counters() {
let a = DiskRaw {
read: 1 << 20,
written: 0,
reads: 10,
writes: 0,
busy: Some(Duration::from_millis(100)),
op_time: Some(Duration::from_millis(20)),
disks: 1,
};
let b = DiskRaw {
read: 3 << 20,
written: 1 << 20,
reads: 30,
writes: 10,
busy: Some(Duration::from_millis(600)),
op_time: Some(Duration::from_millis(80)),
disks: 1,
};
let io = b.rates_since(&a, Duration::from_secs(1));
assert_eq!(io.read.to_string(), "2 MiB/s");
assert_eq!(io.write.to_string(), "1 MiB/s");
assert!((io.reads_per_sec - 20.0).abs() < 1e-9 && (io.writes_per_sec - 10.0).abs() < 1e-9);
assert_eq!(io.busy.unwrap().to_string(), "50.0%");
assert_eq!(io.average_latency, Some(Duration::from_millis(2)));
let back = a.rates_since(&b, Duration::from_secs(1));
assert_eq!((back.read, back.write), (Rate::ZERO, Rate::ZERO));
assert_eq!(back.busy.unwrap(), Percent::ZERO);
assert_eq!(back.average_latency, None);
}
#[test]
fn test_disk_live_space_and_list() {
let s = space(".").unwrap();
assert!(s.total.raw() > 0 && s.available <= s.free && s.free <= s.total);
let disks = list().unwrap();
assert!(
disks
.windows(2)
.all(|w| w[0].mount_point <= w[1].mount_point)
);
for d in &disks {
assert!(!d.filesystem.is_empty(), "{d:?}");
}
assert!(matches!(space("/definitely/not/here/sys-lib"), Err(e) if e.is_unavailable()));
}
}