nmbrs-host 0.7.3

Host readings for nmbrs: CPU, memory, disks, network, pressure, processes, control groups and directory sizes
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Disks: how busy the busiest device is and how much each device
//! reads and writes, from `/proc/diskstats`; and how full the fullest
//! filesystem is, from statvfs (SRD-118 §3.2, §3.5).

/// One device's cumulative counters from `/proc/diskstats`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiskCounters {
    pub name: String,
    /// Reads completed.
    pub reads: u64,
    /// Sectors read. A sector here is 512 bytes whatever the device's.
    pub read_sectors: u64,
    /// Writes completed.
    pub writes: u64,
    /// Sectors written.
    pub write_sectors: u64,
    /// Milliseconds the device had I/O in flight.
    pub io_ticks: u64,
}

/// The size `/proc/diskstats` counts sectors in.
const SECTOR_BYTES: f64 = 512.0;

/// Every device's cumulative counters. Field layout per the kernel's
/// Documentation/iostats: `major minor name <stat fields>`, where
/// reads completed is stat field 1, sectors read 3, writes completed
/// 5, sectors written 7 and io_ticks 10 (whitespace tokens 3, 5, 7, 9
/// and 12).
pub fn parse_diskstats(text: &str) -> Vec<DiskCounters> {
    text.lines()
        .filter_map(|line| {
            let t: Vec<&str> = line.split_whitespace().collect();
            let field = |at: usize| -> Option<u64> { t.get(at)?.parse().ok() };
            Some(DiskCounters {
                name: t.get(2)?.to_string(),
                reads: field(3)?,
                read_sectors: field(5)?,
                writes: field(7)?,
                write_sectors: field(9)?,
                io_ticks: field(12)?,
            })
        })
        .collect()
}

/// The highest per-device utilization between two diskstats snapshots taken
/// `dt_ms` apart. Devices present in only one snapshot are skipped (hotplug
/// between samples); an empty intersection yields `None`.
pub fn max_disk_util(
    prev: &[DiskCounters],
    cur: &[DiskCounters],
    dt_ms: f64,
) -> Option<(String, f64)> {
    if dt_ms <= 0.0 {
        return None;
    }
    let mut best: Option<(String, f64)> = None;
    for now in cur {
        let Some(before) = prev.iter().find(|d| d.name == now.name) else {
            continue;
        };
        let util = (now.io_ticks.saturating_sub(before.io_ticks) as f64 / dt_ms).clamp(0.0, 1.0);
        if best.as_ref().is_none_or(|(_, b)| util > *b) {
            best = Some((now.name.clone(), util));
        }
    }
    best
}

/// What one device read and wrote over a sample window.
#[derive(Debug, Clone, PartialEq)]
pub struct DiskRate {
    pub device: String,
    pub read_bytes_per_s: f64,
    pub write_bytes_per_s: f64,
    pub read_ops_per_s: f64,
    pub write_ops_per_s: f64,
}

/// Each device's throughput between two snapshots `dt_s` apart, for the
/// devices `counted` accepts and that are in both snapshots.
///
/// `/proc/diskstats` lists a device and each of its partitions, and the
/// partitions' counters are part of the device's. `counted` is what
/// keeps a byte from being reported twice ([`is_whole_device`]).
pub fn disk_rates(
    prev: &[DiskCounters],
    cur: &[DiskCounters],
    dt_s: f64,
    counted: &dyn Fn(&str) -> bool,
) -> Vec<DiskRate> {
    if dt_s <= 0.0 {
        return Vec::new();
    }
    cur.iter()
        .filter(|now| counted(&now.name))
        .filter_map(|now| {
            let before = prev.iter().find(|d| d.name == now.name)?;
            let per_s = |now: u64, before: u64| now.saturating_sub(before) as f64 / dt_s;
            Some(DiskRate {
                device: now.name.clone(),
                read_bytes_per_s: per_s(now.read_sectors, before.read_sectors) * SECTOR_BYTES,
                write_bytes_per_s: per_s(now.write_sectors, before.write_sectors) * SECTOR_BYTES,
                read_ops_per_s: per_s(now.reads, before.reads),
                write_ops_per_s: per_s(now.writes, before.writes),
            })
        })
        .collect()
}

/// True for a device whose throughput is reported: a whole block
/// device (it has a directory in `/sys/block`; a partition does not)
/// that is not a loop, RAM or compressed-RAM device.
pub fn is_whole_device(name: &str) -> bool {
    if ["loop", "ram", "zram"].iter().any(|p| name.starts_with(p)) {
        return false;
    }
    std::path::Path::new("/sys/block").join(name).exists()
}

/// Read `/proc/diskstats`. Empty when it cannot be read.
pub fn read_diskstats() -> Vec<DiskCounters> {
    std::fs::read_to_string("/proc/diskstats")
        .map(|t| parse_diskstats(&t))
        .unwrap_or_default()
}

/// WRITABLE `/dev/`-backed mount points from `/proc/mounts`, deduplicated by
/// source device (bind mounts and btrfs subvolumes re-list one device many
/// times; space is a per-DEVICE fact).
///
/// Read-only mounts are excluded, and it matters: snap images are
/// `/dev/loop*` squashfs mounts that are 100% full BY CONSTRUCTION, so one
/// installed snap would pin the storage item at bright-orange forever.
/// Verified on this host — `/dev/loop0 /snap/... ro,...` at 100% while the
/// fullest writable filesystem sat at 40%. A read-only filesystem cannot
/// fill up, so its fullness is not a utilization.
pub fn parse_dev_mounts(text: &str) -> Vec<String> {
    let mut seen_sources: Vec<&str> = Vec::new();
    let mut mounts = Vec::new();
    for line in text.lines() {
        let mut t = line.split_whitespace();
        let (Some(source), Some(mount), _fstype, Some(options)) =
            (t.next(), t.next(), t.next(), t.next())
        else {
            continue;
        };
        if !source.starts_with("/dev/") || seen_sources.contains(&source) {
            continue;
        }
        let read_only = options.split(',').any(|o| o == "ro");
        if read_only {
            continue;
        }
        seen_sources.push(source);
        // /proc/mounts octal-escapes spaces in mount points (\040).
        mounts.push(mount.replace("\\040", " "));
    }
    mounts
}

/// Space utilization of one filesystem: `1 − available/total`, matching what
/// `df` calls Use%. `None` on statvfs failure or a zero-block pseudo-fs.
/// Unix-only, like its caller [`max_storage_util`] (which walks
/// `/proc/mounts` and therefore never yields a mount elsewhere).
#[cfg(unix)]
fn statvfs_util(mount: &str) -> Option<f64> {
    let c_mount = std::ffi::CString::new(mount).ok()?;
    let mut vfs: libc::statvfs = unsafe { std::mem::zeroed() };
    if unsafe { libc::statvfs(c_mount.as_ptr(), &mut vfs) } != 0 {
        return None;
    }
    if vfs.f_blocks == 0 {
        return None;
    }
    Some((1.0 - vfs.f_bavail as f64 / vfs.f_blocks as f64).clamp(0.0, 1.0))
}

/// The fullest `/dev/`-backed filesystem right now: (mount point, util).
pub fn max_storage_util() -> Option<(String, f64)> {
    #[cfg(unix)]
    {
        let mounts = std::fs::read_to_string("/proc/mounts")
            .map(|t| parse_dev_mounts(&t))
            .unwrap_or_default();
        mounts
            .into_iter()
            .filter_map(|m| statvfs_util(&m).map(|u| (m, u)))
            .max_by(|a, b| a.1.total_cmp(&b.1))
    }
    // No `/proc/mounts` off Unix — storage-utilization sampling
    // is simply unavailable there.
    #[cfg(not(unix))]
    {
        None
    }
}

/// Each block device's name by its `(major, minor)` number, from the
/// text of `/proc/diskstats`. A control group's `io.stat` names a
/// device by number.
pub fn parse_device_numbers(text: &str) -> Vec<((u32, u32), String)> {
    text.lines()
        .filter_map(|line| {
            let mut t = line.split_whitespace();
            Some((
                (t.next()?.parse().ok()?, t.next()?.parse().ok()?),
                t.next()?.to_string(),
            ))
        })
        .collect()
}

/// [`parse_device_numbers`] of this host. Empty when `/proc/diskstats`
/// cannot be read.
pub fn read_device_numbers() -> Vec<((u32, u32), String)> {
    std::fs::read_to_string("/proc/diskstats")
        .map(|t| parse_device_numbers(&t))
        .unwrap_or_default()
}

/// Every writable `/dev/`-backed filesystem with its size and the
/// space a process without privilege may still take:
/// `(mount point, total bytes, available bytes)`.
pub fn read_mount_sizes() -> Vec<(String, u64, u64)> {
    std::fs::read_to_string("/proc/mounts")
        .map(|t| parse_dev_mounts(&t))
        .unwrap_or_default()
        .into_iter()
        .filter_map(|mount| {
            let (total, available) = crate::du::filesystem(std::path::Path::new(&mount))?;
            (total > 0).then_some((mount, total, available))
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn devices_are_named_by_number() {
        let text = " 259       0 nvme0n1 1 2 3\n   8      16 sdb 1 2 3\n";
        assert_eq!(
            parse_device_numbers(text),
            vec![
                ((259, 0), "nvme0n1".to_string()),
                ((8, 16), "sdb".to_string())
            ]
        );
    }

    /// A device with only its busy time set.
    fn ticks(name: &str, io_ticks: u64) -> DiskCounters {
        DiskCounters {
            name: name.into(),
            reads: 0,
            read_sectors: 0,
            writes: 0,
            write_sectors: 0,
            io_ticks,
        }
    }

    /// Throughput is the counters' difference over the window, in
    /// bytes for sectors, and a partition is left to its device.
    #[test]
    fn rates_are_per_second_and_partitions_are_not_counted_twice() {
        let at = |name: &str, reads, read_sectors, writes, write_sectors| DiskCounters {
            name: name.into(),
            reads,
            read_sectors,
            writes,
            write_sectors,
            io_ticks: 0,
        };
        let prev = vec![
            at("sda", 10, 1000, 20, 2000),
            at("sda1", 10, 1000, 20, 2000),
        ];
        let cur = vec![
            at("sda", 30, 5000, 60, 4000),
            at("sda1", 30, 5000, 60, 4000),
        ];
        let rates = disk_rates(&prev, &cur, 2.0, &|name| name == "sda");
        assert_eq!(
            rates,
            vec![DiskRate {
                device: "sda".into(),
                read_bytes_per_s: 2000.0 * 512.0,
                write_bytes_per_s: 1000.0 * 512.0,
                read_ops_per_s: 10.0,
                write_ops_per_s: 20.0,
            }]
        );
        assert!(disk_rates(&prev, &cur, 0.0, &|_| true).is_empty());
    }

    /// Real lines from this host's /proc/diskstats — io_ticks is token 12.
    #[test]
    fn diskstats_reads_io_ticks_from_the_tenth_stat_field() {
        let text = "\
 259       0 nvme0n1 1083809 77036 79071293 1310486 4905083 3299234 633830668 26973654 0 3344862 28284141 0 0 0 0 0 0
 259       5 nvme1n1 16478852962 684755 139660303464 4041025697 191545776 3994164 30038357911 3695409309 0 588447592 3442404703 29888 5913 38808742648 936992 0 0";
        let parsed = parse_diskstats(text);
        assert_eq!(
            parsed[0],
            DiskCounters {
                name: "nvme0n1".into(),
                reads: 1_083_809,
                read_sectors: 79_071_293,
                writes: 4_905_083,
                write_sectors: 633_830_668,
                io_ticks: 3_344_862,
            }
        );
        assert_eq!(parsed[1].name, "nvme1n1");
        assert_eq!(parsed[1].io_ticks, 588_447_592);
    }

    /// Highest utilization wins and is named; a device busy 1000ms of a
    /// 2000ms window is 50%.
    #[test]
    fn disk_util_is_the_max_across_devices() {
        let prev = vec![ticks("a", 1000), ticks("b", 5000)];
        let cur = vec![ticks("a", 1400), ticks("b", 6000)];
        let (name, util) = max_disk_util(&prev, &cur, 2000.0).unwrap();
        assert_eq!(name, "b");
        assert!((util - 0.5).abs() < 1e-9);
    }
    /// A window with no elapsed time or no shared devices yields nothing
    /// rather than a fabricated zero.
    #[test]
    fn degenerate_windows_yield_none() {
        let d = vec![ticks("a", 5)];
        assert!(max_disk_util(&d, &d, 0.0).is_none());
        assert!(max_disk_util(&[], &d, 1000.0).is_none());
    }

    /// Only WRITABLE /dev/-backed mounts count for storage, deduplicated by
    /// source. Pseudo-filesystems are not disks; a read-only squashfs snap
    /// image is 100% full by construction and would pin the item forever.
    #[test]
    fn dev_mounts_are_filtered_and_deduplicated() {
        let mounts = "\
proc /proc proc rw 0 0
/dev/nvme0n1p1 / ext4 rw 0 0
tmpfs /tmp tmpfs rw 0 0
/dev/loop0 /snap/core22/2045 squashfs ro,nodev 0 0
/dev/nvme1n1 /mnt/nvme xfs rw 0 0
/dev/nvme1n1 /mnt/alias xfs rw 0 0
/dev/mapper/vg-data /data\\040dir ext4 rw 0 0";
        assert_eq!(
            parse_dev_mounts(mounts),
            vec![
                "/".to_string(),
                "/mnt/nvme".to_string(),
                "/data dir".to_string(),
            ]
        );
    }
}