Skip to main content

subc_os/
host.rs

1//! Facts about the machine as a whole: its memory, its load and the space on a
2//! filesystem, read now, for reporting only.
3//!
4//! Each reader returns `None` when the platform has no source for the value or
5//! the read failed, never a zero in its place: a dashboard that shows "0 GB
6//! free" for a failed read is making a claim the machine never made.
7//!
8//! Sources, per platform:
9//!
10//! - Linux: memory from `/proc/meminfo` (`MemTotal`, `MemAvailable`), load
11//!   from `getloadavg`, filesystem space from `statvfs`.
12//! - macOS: total memory from `sysctl` `hw.memsize`; available memory is the
13//!   free plus inactive pages `host_statistics64` reports (the pages the kernel
14//!   can hand out without paging anything to disk), times the page size. Load
15//!   from `getloadavg`, filesystem space from `statvfs`.
16//! - Windows: memory from `GlobalMemoryStatusEx`, filesystem space from
17//!   `GetDiskFreeSpaceExW`. Windows keeps no load average, so
18//!   [`load_average`] is always `None` there.
19
20use std::path::Path;
21
22/// The machine's physical memory, in bytes.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct MemoryInfo {
25    pub total_bytes: u64,
26    /// Memory that can be given to programs without swapping: free memory
27    /// plus caches the kernel can drop. Not the same as "unused".
28    pub available_bytes: u64,
29}
30
31/// Space on one filesystem, in bytes.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct DiskSpace {
34    pub total_bytes: u64,
35    /// Bytes an unprivileged program may still write. On Unix this leaves out
36    /// the blocks reserved for the superuser, so `total - free` can exceed
37    /// what `df` lists as used.
38    pub free_bytes: u64,
39}
40
41/// The machine's physical memory, read now.
42pub fn memory() -> Option<MemoryInfo> {
43    platform_memory()
44}
45
46/// The 1, 5 and 15 minute load averages: the average number of runnable (and,
47/// on Linux, uninterruptible) threads over each span. `None` on Windows, which
48/// keeps no such figure.
49pub fn load_average() -> Option<[f64; 3]> {
50    #[cfg(unix)]
51    {
52        let mut loads = [0f64; 3];
53        // SAFETY: `getloadavg` writes at most `nelem` doubles into the buffer
54        // it is given; the buffer holds exactly three and we pass three.
55        #[allow(unsafe_code)]
56        let n = unsafe { libc::getloadavg(loads.as_mut_ptr(), 3) };
57        (n == 3).then_some(loads)
58    }
59    #[cfg(not(unix))]
60    {
61        None
62    }
63}
64
65/// Total and free space of the filesystem holding `path`, read now.
66pub fn disk_space(path: &Path) -> Option<DiskSpace> {
67    platform_disk_space(path)
68}
69
70#[cfg(target_os = "linux")]
71fn platform_memory() -> Option<MemoryInfo> {
72    let text = std::fs::read_to_string("/proc/meminfo").ok()?;
73    parse_meminfo(&text)
74}
75
76/// Reads `MemTotal` and `MemAvailable` (kibibytes) from `/proc/meminfo` text.
77#[cfg(any(target_os = "linux", test))]
78fn parse_meminfo(text: &str) -> Option<MemoryInfo> {
79    let field = |name: &str| -> Option<u64> {
80        let line = text.lines().find(|l| l.starts_with(name))?;
81        let rest = line[name.len()..].trim_start_matches(':').trim();
82        let kib: u64 = rest.split_whitespace().next()?.parse().ok()?;
83        kib.checked_mul(1024)
84    };
85    Some(MemoryInfo {
86        total_bytes: field("MemTotal")?,
87        available_bytes: field("MemAvailable")?,
88    })
89}
90
91#[cfg(target_os = "macos")]
92fn platform_memory() -> Option<MemoryInfo> {
93    let total_bytes = macos_memsize()?;
94    let page_size = macos_page_size()?;
95    let (free, inactive) = macos_free_and_inactive_pages()?;
96    Some(MemoryInfo {
97        total_bytes,
98        available_bytes: (free + inactive).saturating_mul(page_size).min(total_bytes),
99    })
100}
101
102#[cfg(target_os = "macos")]
103fn macos_memsize() -> Option<u64> {
104    let mut value: u64 = 0;
105    let mut len: libc::size_t = std::mem::size_of::<u64>();
106    // SAFETY: the name is a NUL-terminated C string; `value` is a writable
107    // u64 and `len` says exactly its size, which `hw.memsize` (a 64-bit
108    // integer) fills completely.
109    #[allow(unsafe_code)]
110    let result = unsafe {
111        libc::sysctlbyname(
112            c"hw.memsize".as_ptr(),
113            (&mut value as *mut u64).cast(),
114            &mut len,
115            std::ptr::null_mut(),
116            0,
117        )
118    };
119    (result == 0 && len == std::mem::size_of::<u64>() && value > 0).then_some(value)
120}
121
122#[cfg(target_os = "macos")]
123fn macos_page_size() -> Option<u64> {
124    // SAFETY: `sysconf` only reads a configuration value.
125    #[allow(unsafe_code)]
126    let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
127    u64::try_from(size).ok().filter(|s| *s > 0)
128}
129
130#[cfg(target_os = "macos")]
131#[allow(deprecated)] // libc points Mach users at the mach2 crate; these calls are stable.
132fn macos_free_and_inactive_pages() -> Option<(u64, u64)> {
133    // SAFETY: `vm_statistics64` is a plain C struct of integers, so all-zero
134    // bytes are a valid value.
135    #[allow(unsafe_code)]
136    let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
137    let mut count = libc::HOST_VM_INFO64_COUNT;
138    // `mach_host_self` adds a reference to the task's send right for the host
139    // port on every call. Asking once and keeping the right for the life of
140    // the process bounds that to one reference instead of one per reading.
141    static HOST_PORT: std::sync::OnceLock<libc::mach_port_t> = std::sync::OnceLock::new();
142    // SAFETY: `mach_host_self` takes no arguments and only returns a port name.
143    #[allow(unsafe_code)]
144    let host = *HOST_PORT.get_or_init(|| unsafe { libc::mach_host_self() });
145    // SAFETY: `stats` is a writable vm_statistics64 and `count` is its size in
146    // natural-width integers, as HOST_VM_INFO64 requires; the kernel writes at
147    // most `count` of them. `host` is a send right this process holds.
148    #[allow(unsafe_code)]
149    let result = unsafe {
150        libc::host_statistics64(
151            host,
152            libc::HOST_VM_INFO64,
153            (&mut stats as *mut libc::vm_statistics64).cast(),
154            &mut count,
155        )
156    };
157    (result == libc::KERN_SUCCESS)
158        .then(|| (u64::from(stats.free_count), u64::from(stats.inactive_count)))
159}
160
161#[cfg(windows)]
162fn platform_memory() -> Option<MemoryInfo> {
163    use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
164    // SAFETY: MEMORYSTATUSEX is a plain struct of integers; zero is valid.
165    #[allow(unsafe_code)]
166    let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
167    status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
168    // SAFETY: `status` is writable and its `dwLength` names its size, as the
169    // call requires.
170    #[allow(unsafe_code)]
171    let ok = unsafe { GlobalMemoryStatusEx(&mut status) };
172    (ok != 0 && status.ullTotalPhys > 0).then_some(MemoryInfo {
173        total_bytes: status.ullTotalPhys,
174        available_bytes: status.ullAvailPhys,
175    })
176}
177
178#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
179fn platform_memory() -> Option<MemoryInfo> {
180    None
181}
182
183#[cfg(unix)]
184fn platform_disk_space(path: &Path) -> Option<DiskSpace> {
185    use std::os::unix::ffi::OsStrExt;
186    let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
187    // SAFETY: `statvfs` is a plain C struct of integers; zero is valid.
188    #[allow(unsafe_code)]
189    let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
190    // SAFETY: `c_path` is NUL-terminated and outlives the call; `st` is a
191    // writable statvfs.
192    #[allow(unsafe_code)]
193    let result = unsafe { libc::statvfs(c_path.as_ptr(), &mut st) };
194    if result != 0 {
195        return None;
196    }
197    // Block counts are in units of the fragment size, `f_frsize`.
198    #[allow(clippy::unnecessary_cast)] // the field widths differ by platform
199    let unit = st.f_frsize as u64;
200    #[allow(clippy::unnecessary_cast)]
201    let (blocks, avail) = (st.f_blocks as u64, st.f_bavail as u64);
202    let total_bytes = blocks.checked_mul(unit)?;
203    (total_bytes > 0).then(|| DiskSpace {
204        total_bytes,
205        free_bytes: avail.saturating_mul(unit),
206    })
207}
208
209#[cfg(windows)]
210fn platform_disk_space(path: &Path) -> Option<DiskSpace> {
211    use std::os::windows::ffi::OsStrExt;
212    use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
213    let wide: Vec<u16> = path
214        .as_os_str()
215        .encode_wide()
216        .chain(std::iter::once(0))
217        .collect();
218    let (mut free_to_caller, mut total, mut _free_total) = (0u64, 0u64, 0u64);
219    // SAFETY: `wide` is NUL-terminated and outlives the call; the three
220    // out-pointers are writable u64s.
221    #[allow(unsafe_code)]
222    let ok = unsafe {
223        GetDiskFreeSpaceExW(
224            wide.as_ptr(),
225            &mut free_to_caller,
226            &mut total,
227            &mut _free_total,
228        )
229    };
230    (ok != 0 && total > 0).then_some(DiskSpace {
231        total_bytes: total,
232        free_bytes: free_to_caller,
233    })
234}
235
236#[cfg(not(any(unix, windows)))]
237fn platform_disk_space(_path: &Path) -> Option<DiskSpace> {
238    None
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn meminfo_text_parses_to_bytes() {
247        let text = "MemTotal:       16314952 kB\nMemFree:  1000 kB\nMemAvailable:   12002000 kB\n";
248        assert_eq!(
249            parse_meminfo(text),
250            Some(MemoryInfo {
251                total_bytes: 16_314_952 * 1024,
252                available_bytes: 12_002_000 * 1024,
253            })
254        );
255        assert_eq!(parse_meminfo("MemTotal: 5 kB\n"), None);
256    }
257
258    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
259    #[test]
260    fn memory_is_plausible() {
261        let m = memory().expect("this platform reports memory");
262        // At least 64 MiB and at most 64 TiB of RAM, and available within it.
263        assert!(m.total_bytes >= 64 << 20, "{m:?}");
264        assert!(m.total_bytes <= 64 << 40, "{m:?}");
265        assert!(m.available_bytes > 0, "{m:?}");
266        assert!(m.available_bytes <= m.total_bytes, "{m:?}");
267    }
268
269    #[cfg(unix)]
270    #[test]
271    fn load_average_is_plausible() {
272        let [one, five, fifteen] = load_average().expect("unix reports load");
273        for l in [one, five, fifteen] {
274            assert!(l.is_finite() && l >= 0.0, "{one} {five} {fifteen}");
275            // No test machine runs a hundred thousand runnable threads.
276            assert!(l < 100_000.0, "{one} {five} {fifteen}");
277        }
278    }
279
280    #[cfg(windows)]
281    #[test]
282    fn windows_has_no_load_average() {
283        assert_eq!(load_average(), None);
284    }
285
286    #[cfg(any(unix, windows))]
287    #[test]
288    fn disk_space_is_plausible() {
289        let dir = std::env::temp_dir();
290        let d = disk_space(&dir).expect("the temp directory's filesystem reports space");
291        assert!(d.total_bytes >= 1 << 20, "{d:?}");
292        assert!(d.free_bytes <= d.total_bytes, "{d:?}");
293    }
294
295    #[test]
296    fn a_missing_path_has_no_disk_space() {
297        assert_eq!(
298            disk_space(Path::new("/definitely/not/a/real/path/for/subc-os")),
299            None
300        );
301    }
302}