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

//! The disk space a directory takes (SRD-118 ยง6.2): a walk of
//! everything under it, counted as `du` counts.
//!
//! - **bytes** is the space allocated on disk: each file's block count
//!   times 512. It is what filling the disk is measured in, and it is
//!   less than the apparent size for a sparse file and more for a
//!   small one.
//! - **apparent_bytes** is the sum of the files' lengths.
//! - A file with several hard links under the directory is counted
//!   once.
//! - A symbolic link is counted as the link, and is never followed.
//! - The directory itself and every directory under it are counted.
//!
//! A database rewrites its files while it runs, so an entry that is
//! gone by the time it is examined is skipped without comment: it was
//! deleted during the walk and takes no space now.

use std::collections::HashSet;
use std::io;
use std::path::{Path, PathBuf};

/// What a directory holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Usage {
    /// Space allocated on disk.
    pub bytes: u64,
    /// The sum of the entries' lengths.
    pub apparent_bytes: u64,
    /// Entries that are not directories.
    pub files: u64,
    /// Directories, the measured one included.
    pub dirs: u64,
    /// Entries that could not be examined, when those are skipped.
    pub unreadable: u64,
}

/// An entry the walk could not examine.
#[derive(Debug)]
pub struct Unreadable {
    pub path: PathBuf,
    pub error: io::Error,
}

/// The allocated size, length and identity of one entry.
#[cfg(unix)]
fn sizes(meta: &std::fs::Metadata) -> (u64, u64, Option<(u64, u64)>) {
    use std::os::unix::fs::MetadataExt;
    let identity = (meta.nlink() > 1 && !meta.is_dir()).then(|| (meta.dev(), meta.ino()));
    (meta.blocks() * 512, meta.len(), identity)
}

/// Where the platform reports no block count, the length stands for
/// the allocated size.
#[cfg(not(unix))]
fn sizes(meta: &std::fs::Metadata) -> (u64, u64, Option<(u64, u64)>) {
    (meta.len(), meta.len(), None)
}

/// Measure `root`.
///
/// `Err` when `root` itself cannot be read (it is missing, is not a
/// directory, or may not be listed), and for the first entry under it
/// that cannot be examined unless `skip_unreadable`, in which case
/// such entries are counted in [`Usage::unreadable`].
pub fn measure(root: &Path, skip_unreadable: bool) -> Result<Usage, Unreadable> {
    let fail = |path: &Path, error: io::Error| Unreadable {
        path: path.to_path_buf(),
        error,
    };
    let meta = std::fs::symlink_metadata(root).map_err(|e| fail(root, e))?;
    if !meta.is_dir() {
        return Err(fail(
            root,
            io::Error::new(io::ErrorKind::NotADirectory, "not a directory"),
        ));
    }
    let mut usage = Usage::default();
    let (bytes, apparent, _) = sizes(&meta);
    usage.bytes += bytes;
    usage.apparent_bytes += apparent;
    usage.dirs += 1;

    let mut linked: HashSet<(u64, u64)> = HashSet::new();
    let mut pending = vec![root.to_path_buf()];
    let mut is_root = true;
    while let Some(dir) = pending.pop() {
        let entries = match std::fs::read_dir(&dir) {
            Ok(entries) => entries,
            // The measured directory must be listable. One under it
            // that is not is an unreadable entry like any other.
            Err(error) if is_root => return Err(fail(&dir, error)),
            Err(error) => {
                examine_failed(&mut usage, error, skip_unreadable).map_err(|e| fail(&dir, e))?;
                continue;
            }
        };
        is_root = false;
        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) => {
                    examine_failed(&mut usage, error, skip_unreadable)
                        .map_err(|e| fail(&dir, e))?;
                    continue;
                }
            };
            let path = entry.path();
            let meta = match std::fs::symlink_metadata(&path) {
                Ok(meta) => meta,
                Err(error) => {
                    examine_failed(&mut usage, error, skip_unreadable)
                        .map_err(|e| fail(&path, e))?;
                    continue;
                }
            };
            let (bytes, apparent, identity) = sizes(&meta);
            if let Some(identity) = identity
                && !linked.insert(identity)
            {
                continue;
            }
            usage.bytes += bytes;
            usage.apparent_bytes += apparent;
            if meta.is_dir() {
                usage.dirs += 1;
                pending.push(path);
            } else {
                usage.files += 1;
            }
        }
    }
    Ok(usage)
}

/// What to do about an entry under the measured directory that could
/// not be examined: nothing when it is gone, count it when unreadable
/// entries are skipped, and otherwise fail with its error.
fn examine_failed(
    usage: &mut Usage,
    error: io::Error,
    skip_unreadable: bool,
) -> Result<(), io::Error> {
    if error.kind() == io::ErrorKind::NotFound {
        return Ok(());
    }
    if skip_unreadable {
        usage.unreadable += 1;
        return Ok(());
    }
    Err(error)
}

/// The size of the filesystem `path` is on and the space on it a
/// process without privilege may still take: `(total, available)` in
/// bytes. `None` when statvfs fails or the platform has none.
pub fn filesystem(path: &Path) -> Option<(u64, u64)> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
        let mut vfs: libc::statvfs = unsafe { std::mem::zeroed() };
        if unsafe { libc::statvfs(c_path.as_ptr(), &mut vfs) } != 0 {
            return None;
        }
        let unit = vfs.f_frsize as u64;
        Some((vfs.f_blocks as u64 * unit, vfs.f_bavail as u64 * unit))
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        None
    }
}

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

    /// A fresh directory under the test tmp dir.
    fn sandbox(label: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "nmbrs-host-du-{label}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn files_and_directories_are_counted_through_the_tree() {
        let dir = sandbox("tree");
        std::fs::create_dir_all(dir.join("a/b")).unwrap();
        std::fs::write(dir.join("one"), vec![1u8; 10_000]).unwrap();
        std::fs::write(dir.join("a/two"), vec![2u8; 20_000]).unwrap();
        std::fs::write(dir.join("a/b/three"), b"").unwrap();
        let usage = measure(&dir, false).unwrap();
        assert_eq!((usage.files, usage.dirs, usage.unreadable), (3, 3, 0));
        // Lengths: the files', plus whatever the three directories report.
        assert!(usage.apparent_bytes >= 30_000, "{usage:?}");
        // Allocation is in whole blocks, so it is at least the data.
        #[cfg(unix)]
        assert!(usage.bytes >= 30_000, "{usage:?}");
    }

    #[cfg(unix)]
    #[test]
    fn a_hard_link_is_counted_once_and_a_symlink_is_not_followed() {
        let dir = sandbox("links");
        let outside = sandbox("links-outside");
        std::fs::write(outside.join("big"), vec![0u8; 500_000]).unwrap();
        std::fs::write(dir.join("data"), vec![7u8; 50_000]).unwrap();
        let before = measure(&dir, false).unwrap();

        std::fs::hard_link(dir.join("data"), dir.join("again")).unwrap();
        std::os::unix::fs::symlink(&outside, dir.join("elsewhere")).unwrap();
        let after = measure(&dir, false).unwrap();
        // The second name of `data` adds no file; the link adds one.
        assert_eq!(after.files, before.files + 1);
        assert!(
            after.apparent_bytes < before.apparent_bytes + 50_000,
            "the link's target is not part of the directory: {before:?} {after:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_sparse_file_takes_less_than_its_length() {
        use std::io::{Seek, SeekFrom, Write};
        let dir = sandbox("sparse");
        let mut file = std::fs::File::create(dir.join("holes")).unwrap();
        file.seek(SeekFrom::Start(64 * 1024 * 1024)).unwrap();
        file.write_all(b"end").unwrap();
        drop(file);
        let usage = measure(&dir, false).unwrap();
        assert!(usage.apparent_bytes > 64 * 1024 * 1024);
        // Not every filesystem keeps holes; where it does, the
        // allocation is far below the length.
        if usage.bytes < usage.apparent_bytes {
            assert!(usage.bytes < 1024 * 1024, "{usage:?}");
        }
    }

    #[test]
    fn a_missing_directory_and_a_file_are_refused() {
        let dir = sandbox("missing");
        let err = measure(&dir.join("nope"), true).unwrap_err();
        assert_eq!(err.error.kind(), io::ErrorKind::NotFound);
        std::fs::write(dir.join("file"), b"x").unwrap();
        let err = measure(&dir.join("file"), true).unwrap_err();
        assert_eq!(err.error.kind(), io::ErrorKind::NotADirectory);
    }

    #[cfg(unix)]
    #[test]
    fn an_unreadable_directory_fails_or_is_counted() {
        use std::os::unix::fs::PermissionsExt;
        let dir = sandbox("locked");
        std::fs::create_dir(dir.join("locked")).unwrap();
        std::fs::write(dir.join("locked/inside"), b"x").unwrap();
        let lock = |mode| {
            std::fs::set_permissions(dir.join("locked"), std::fs::Permissions::from_mode(mode))
                .unwrap()
        };
        lock(0o000);
        // A privileged user reads it anyway; there is nothing to test.
        if std::fs::read_dir(dir.join("locked")).is_ok() {
            lock(0o755);
            return;
        }
        let err = measure(&dir, false).unwrap_err();
        assert!(err.path.ends_with("locked"), "{err:?}");
        let usage = measure(&dir, true).unwrap();
        assert_eq!((usage.unreadable, usage.dirs), (1, 2));
        lock(0o755);
    }

    #[cfg(unix)]
    #[test]
    fn the_filesystem_reports_its_size() {
        let (total, available) = filesystem(&sandbox("fs")).unwrap();
        assert!(total > 0 && available <= total);
    }
}