1use std::path::Path;
4use std::sync::Once;
5
6use tracing::warn;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct DiskUsage {
11 pub total_bytes: u64,
13
14 pub available_bytes: u64,
16}
17
18impl DiskUsage {
19 #[allow(clippy::useless_conversion)]
24 pub fn from_path(path: &Path) -> Option<Self> {
25 match nix::sys::statvfs::statvfs(path) {
26 Ok(stat) => {
27 let block_bytes = u64::from(stat.fragment_size());
30 let total_bytes = block_bytes.checked_mul(u64::from(stat.blocks()))?;
31 let available_bytes =
32 block_bytes.checked_mul(u64::from(stat.blocks_available()))?;
33 (total_bytes > 0).then_some(Self {
35 total_bytes,
36 available_bytes,
37 })
38 }
39 Err(errno) => {
40 static ONCE: Once = Once::new();
41 ONCE.call_once(|| {
42 warn!(
43 "Failed to read disk usage for {}, reporting it as unknown: {errno}",
44 path.display()
45 )
46 });
47 None
48 }
49 }
50 }
51}
52
53#[cfg(test)]
54mod test {
55 use std::path::Path;
56
57 use super::DiskUsage;
58
59 #[test]
60 fn reports_disk_usage_for_an_existing_directory() {
61 let temp_dir = std::env::temp_dir();
62 let usage = DiskUsage::from_path(&temp_dir)
63 .unwrap_or_else(|| panic!("a disk must hold {}", temp_dir.display()));
64 assert!(usage.total_bytes > 0, "{usage:?}");
65 assert!(usage.available_bytes <= usage.total_bytes, "{usage:?}");
66 }
67
68 #[test]
69 fn reports_no_disk_usage_for_a_missing_path() {
70 assert_eq!(
72 DiskUsage::from_path(Path::new("/nonexistent-feldera-storage-path")),
73 None
74 );
75 }
76}