Skip to main content

nmbrs_host/
du.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The disk space a directory takes (SRD-118 ยง6.2): a walk of
5//! everything under it, counted as `du` counts.
6//!
7//! - **bytes** is the space allocated on disk: each file's block count
8//!   times 512. It is what filling the disk is measured in, and it is
9//!   less than the apparent size for a sparse file and more for a
10//!   small one.
11//! - **apparent_bytes** is the sum of the files' lengths.
12//! - A file with several hard links under the directory is counted
13//!   once.
14//! - A symbolic link is counted as the link, and is never followed.
15//! - The directory itself and every directory under it are counted.
16//!
17//! A database rewrites its files while it runs, so an entry that is
18//! gone by the time it is examined is skipped without comment: it was
19//! deleted during the walk and takes no space now.
20
21use std::collections::HashSet;
22use std::io;
23use std::path::{Path, PathBuf};
24
25/// What a directory holds.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub struct Usage {
28    /// Space allocated on disk.
29    pub bytes: u64,
30    /// The sum of the entries' lengths.
31    pub apparent_bytes: u64,
32    /// Entries that are not directories.
33    pub files: u64,
34    /// Directories, the measured one included.
35    pub dirs: u64,
36    /// Entries that could not be examined, when those are skipped.
37    pub unreadable: u64,
38}
39
40/// An entry the walk could not examine.
41#[derive(Debug)]
42pub struct Unreadable {
43    pub path: PathBuf,
44    pub error: io::Error,
45}
46
47/// The allocated size, length and identity of one entry.
48#[cfg(unix)]
49fn sizes(meta: &std::fs::Metadata) -> (u64, u64, Option<(u64, u64)>) {
50    use std::os::unix::fs::MetadataExt;
51    let identity = (meta.nlink() > 1 && !meta.is_dir()).then(|| (meta.dev(), meta.ino()));
52    (meta.blocks() * 512, meta.len(), identity)
53}
54
55/// Where the platform reports no block count, the length stands for
56/// the allocated size.
57#[cfg(not(unix))]
58fn sizes(meta: &std::fs::Metadata) -> (u64, u64, Option<(u64, u64)>) {
59    (meta.len(), meta.len(), None)
60}
61
62/// Measure `root`.
63///
64/// `Err` when `root` itself cannot be read (it is missing, is not a
65/// directory, or may not be listed), and for the first entry under it
66/// that cannot be examined unless `skip_unreadable`, in which case
67/// such entries are counted in [`Usage::unreadable`].
68pub fn measure(root: &Path, skip_unreadable: bool) -> Result<Usage, Unreadable> {
69    let fail = |path: &Path, error: io::Error| Unreadable {
70        path: path.to_path_buf(),
71        error,
72    };
73    let meta = std::fs::symlink_metadata(root).map_err(|e| fail(root, e))?;
74    if !meta.is_dir() {
75        return Err(fail(
76            root,
77            io::Error::new(io::ErrorKind::NotADirectory, "not a directory"),
78        ));
79    }
80    let mut usage = Usage::default();
81    let (bytes, apparent, _) = sizes(&meta);
82    usage.bytes += bytes;
83    usage.apparent_bytes += apparent;
84    usage.dirs += 1;
85
86    let mut linked: HashSet<(u64, u64)> = HashSet::new();
87    let mut pending = vec![root.to_path_buf()];
88    let mut is_root = true;
89    while let Some(dir) = pending.pop() {
90        let entries = match std::fs::read_dir(&dir) {
91            Ok(entries) => entries,
92            // The measured directory must be listable. One under it
93            // that is not is an unreadable entry like any other.
94            Err(error) if is_root => return Err(fail(&dir, error)),
95            Err(error) => {
96                examine_failed(&mut usage, error, skip_unreadable).map_err(|e| fail(&dir, e))?;
97                continue;
98            }
99        };
100        is_root = false;
101        for entry in entries {
102            let entry = match entry {
103                Ok(entry) => entry,
104                Err(error) => {
105                    examine_failed(&mut usage, error, skip_unreadable)
106                        .map_err(|e| fail(&dir, e))?;
107                    continue;
108                }
109            };
110            let path = entry.path();
111            let meta = match std::fs::symlink_metadata(&path) {
112                Ok(meta) => meta,
113                Err(error) => {
114                    examine_failed(&mut usage, error, skip_unreadable)
115                        .map_err(|e| fail(&path, e))?;
116                    continue;
117                }
118            };
119            let (bytes, apparent, identity) = sizes(&meta);
120            if let Some(identity) = identity
121                && !linked.insert(identity)
122            {
123                continue;
124            }
125            usage.bytes += bytes;
126            usage.apparent_bytes += apparent;
127            if meta.is_dir() {
128                usage.dirs += 1;
129                pending.push(path);
130            } else {
131                usage.files += 1;
132            }
133        }
134    }
135    Ok(usage)
136}
137
138/// What to do about an entry under the measured directory that could
139/// not be examined: nothing when it is gone, count it when unreadable
140/// entries are skipped, and otherwise fail with its error.
141fn examine_failed(
142    usage: &mut Usage,
143    error: io::Error,
144    skip_unreadable: bool,
145) -> Result<(), io::Error> {
146    if error.kind() == io::ErrorKind::NotFound {
147        return Ok(());
148    }
149    if skip_unreadable {
150        usage.unreadable += 1;
151        return Ok(());
152    }
153    Err(error)
154}
155
156/// The size of the filesystem `path` is on and the space on it a
157/// process without privilege may still take: `(total, available)` in
158/// bytes. `None` when statvfs fails or the platform has none.
159pub fn filesystem(path: &Path) -> Option<(u64, u64)> {
160    #[cfg(unix)]
161    {
162        use std::os::unix::ffi::OsStrExt;
163        let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
164        let mut vfs: libc::statvfs = unsafe { std::mem::zeroed() };
165        if unsafe { libc::statvfs(c_path.as_ptr(), &mut vfs) } != 0 {
166            return None;
167        }
168        let unit = vfs.f_frsize as u64;
169        Some((vfs.f_blocks as u64 * unit, vfs.f_bavail as u64 * unit))
170    }
171    #[cfg(not(unix))]
172    {
173        let _ = path;
174        None
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    /// A fresh directory under the test tmp dir.
183    fn sandbox(label: &str) -> PathBuf {
184        let dir = std::env::temp_dir().join(format!(
185            "nmbrs-host-du-{label}-{}-{}",
186            std::process::id(),
187            std::time::SystemTime::now()
188                .duration_since(std::time::UNIX_EPOCH)
189                .unwrap()
190                .as_nanos(),
191        ));
192        std::fs::create_dir_all(&dir).unwrap();
193        dir
194    }
195
196    #[test]
197    fn files_and_directories_are_counted_through_the_tree() {
198        let dir = sandbox("tree");
199        std::fs::create_dir_all(dir.join("a/b")).unwrap();
200        std::fs::write(dir.join("one"), vec![1u8; 10_000]).unwrap();
201        std::fs::write(dir.join("a/two"), vec![2u8; 20_000]).unwrap();
202        std::fs::write(dir.join("a/b/three"), b"").unwrap();
203        let usage = measure(&dir, false).unwrap();
204        assert_eq!((usage.files, usage.dirs, usage.unreadable), (3, 3, 0));
205        // Lengths: the files', plus whatever the three directories report.
206        assert!(usage.apparent_bytes >= 30_000, "{usage:?}");
207        // Allocation is in whole blocks, so it is at least the data.
208        #[cfg(unix)]
209        assert!(usage.bytes >= 30_000, "{usage:?}");
210    }
211
212    #[cfg(unix)]
213    #[test]
214    fn a_hard_link_is_counted_once_and_a_symlink_is_not_followed() {
215        let dir = sandbox("links");
216        let outside = sandbox("links-outside");
217        std::fs::write(outside.join("big"), vec![0u8; 500_000]).unwrap();
218        std::fs::write(dir.join("data"), vec![7u8; 50_000]).unwrap();
219        let before = measure(&dir, false).unwrap();
220
221        std::fs::hard_link(dir.join("data"), dir.join("again")).unwrap();
222        std::os::unix::fs::symlink(&outside, dir.join("elsewhere")).unwrap();
223        let after = measure(&dir, false).unwrap();
224        // The second name of `data` adds no file; the link adds one.
225        assert_eq!(after.files, before.files + 1);
226        assert!(
227            after.apparent_bytes < before.apparent_bytes + 50_000,
228            "the link's target is not part of the directory: {before:?} {after:?}"
229        );
230    }
231
232    #[cfg(unix)]
233    #[test]
234    fn a_sparse_file_takes_less_than_its_length() {
235        use std::io::{Seek, SeekFrom, Write};
236        let dir = sandbox("sparse");
237        let mut file = std::fs::File::create(dir.join("holes")).unwrap();
238        file.seek(SeekFrom::Start(64 * 1024 * 1024)).unwrap();
239        file.write_all(b"end").unwrap();
240        drop(file);
241        let usage = measure(&dir, false).unwrap();
242        assert!(usage.apparent_bytes > 64 * 1024 * 1024);
243        // Not every filesystem keeps holes; where it does, the
244        // allocation is far below the length.
245        if usage.bytes < usage.apparent_bytes {
246            assert!(usage.bytes < 1024 * 1024, "{usage:?}");
247        }
248    }
249
250    #[test]
251    fn a_missing_directory_and_a_file_are_refused() {
252        let dir = sandbox("missing");
253        let err = measure(&dir.join("nope"), true).unwrap_err();
254        assert_eq!(err.error.kind(), io::ErrorKind::NotFound);
255        std::fs::write(dir.join("file"), b"x").unwrap();
256        let err = measure(&dir.join("file"), true).unwrap_err();
257        assert_eq!(err.error.kind(), io::ErrorKind::NotADirectory);
258    }
259
260    #[cfg(unix)]
261    #[test]
262    fn an_unreadable_directory_fails_or_is_counted() {
263        use std::os::unix::fs::PermissionsExt;
264        let dir = sandbox("locked");
265        std::fs::create_dir(dir.join("locked")).unwrap();
266        std::fs::write(dir.join("locked/inside"), b"x").unwrap();
267        let lock = |mode| {
268            std::fs::set_permissions(dir.join("locked"), std::fs::Permissions::from_mode(mode))
269                .unwrap()
270        };
271        lock(0o000);
272        // A privileged user reads it anyway; there is nothing to test.
273        if std::fs::read_dir(dir.join("locked")).is_ok() {
274            lock(0o755);
275            return;
276        }
277        let err = measure(&dir, false).unwrap_err();
278        assert!(err.path.ends_with("locked"), "{err:?}");
279        let usage = measure(&dir, true).unwrap();
280        assert_eq!((usage.unreadable, usage.dirs), (1, 2));
281        lock(0o755);
282    }
283
284    #[cfg(unix)]
285    #[test]
286    fn the_filesystem_reports_its_size() {
287        let (total, available) = filesystem(&sandbox("fs")).unwrap();
288        assert!(total > 0 && available <= total);
289    }
290}