Skip to main content

platform/
usage.rs

1//! The host's CPU, memory, load, and uptime, read from the system itself
2//! (`/proc` on Linux, the kernel's own calls on macOS): no program is
3//! started for a sample.
4//!
5//! CPU time is cumulative since boot, in the system's own ticks, so a
6//! caller works out a share from two readings ([`cpu_shares`]).
7
8/// One reading.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Reading {
11    /// Per core: ticks spent busy, and ticks in all, since boot.
12    pub cores: Vec<Ticks>,
13    pub memory_used: u64,
14    pub memory_total: u64,
15    /// The load averages over 1, 5, and 15 minutes.
16    pub load: [f64; 3],
17    pub uptime_s: u64,
18}
19
20/// A core's CPU time since boot.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub struct Ticks {
23    pub busy: u64,
24    pub total: u64,
25}
26
27/// The share of time each core was busy between two readings (0 to 1),
28/// and the share over all of them. A core with no ticks between the two
29/// counts as idle; readings with different core counts give nothing.
30pub fn cpu_shares(earlier: &[Ticks], later: &[Ticks]) -> Option<(f64, Vec<f64>)> {
31    if earlier.len() != later.len() || later.is_empty() {
32        return None;
33    }
34    let (mut busy, mut total) = (0u64, 0u64);
35    let cores = earlier
36        .iter()
37        .zip(later)
38        .map(|(a, b)| {
39            let (db, dt) = (
40                b.busy.saturating_sub(a.busy),
41                b.total.saturating_sub(a.total),
42            );
43            busy += db;
44            total += dt;
45            if dt == 0 {
46                0.0
47            } else {
48                (db as f64 / dt as f64).clamp(0.0, 1.0)
49            }
50        })
51        .collect();
52    let all = if total == 0 {
53        0.0
54    } else {
55        (busy as f64 / total as f64).clamp(0.0, 1.0)
56    };
57    Some((all, cores))
58}
59
60/// Read the host now. `None` where this system is not supported, or a
61/// source could not be read.
62pub fn read() -> Option<Reading> {
63    imp::read()
64}
65
66/// `/proc/stat`'s per-core lines as ticks: busy is everything but idle
67/// and waiting for I/O.
68#[cfg(any(target_os = "linux", test))]
69fn proc_stat(text: &str) -> Vec<Ticks> {
70    text.lines()
71        .filter(|l| {
72            l.strip_prefix("cpu")
73                .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()))
74        })
75        .map(|l| {
76            let n: Vec<u64> = l
77                .split_whitespace()
78                .skip(1)
79                .filter_map(|v| v.parse().ok())
80                .collect();
81            // user nice system idle iowait irq softirq steal (guest time is
82            // already in user).
83            let total: u64 = n.iter().take(8).sum();
84            let idle = n.get(3).copied().unwrap_or(0) + n.get(4).copied().unwrap_or(0);
85            Ticks {
86                busy: total.saturating_sub(idle),
87                total,
88            }
89        })
90        .collect()
91}
92
93/// `/proc/meminfo`: used (total less what is available) and total, in
94/// bytes.
95#[cfg(any(target_os = "linux", test))]
96fn proc_meminfo(text: &str) -> Option<(u64, u64)> {
97    let kb = |key: &str| -> Option<u64> {
98        text.lines()
99            .find_map(|l| l.strip_prefix(key)?.strip_prefix(':'))
100            .and_then(|v| v.split_whitespace().next()?.parse().ok())
101    };
102    let total = kb("MemTotal")?;
103    let available = kb("MemAvailable").or_else(|| kb("MemFree"))?;
104    Some((total.saturating_sub(available) * 1024, total * 1024))
105}
106
107#[cfg(target_os = "linux")]
108mod imp {
109    use super::{Reading, proc_meminfo, proc_stat};
110
111    pub fn read() -> Option<Reading> {
112        let file = |p: &str| std::fs::read_to_string(p).ok();
113        let cores = proc_stat(&file("/proc/stat")?);
114        if cores.is_empty() {
115            return None;
116        }
117        let (memory_used, memory_total) = proc_meminfo(&file("/proc/meminfo")?)?;
118        let mut load = [0.0; 3];
119        for (slot, v) in load
120            .iter_mut()
121            .zip(file("/proc/loadavg")?.split_whitespace())
122        {
123            *slot = v.parse().ok()?;
124        }
125        let uptime_s = file("/proc/uptime")?
126            .split_whitespace()
127            .next()?
128            .parse::<f64>()
129            .ok()? as u64;
130        Some(Reading {
131            cores,
132            memory_used,
133            memory_total,
134            load,
135            uptime_s,
136        })
137    }
138}
139
140#[cfg(target_os = "macos")]
141#[allow(unsafe_code)]
142mod imp {
143    use std::ffi::{c_char, c_int, c_void};
144
145    use super::{Reading, Ticks};
146
147    // Mach's host statistics, and sysctl: the kernel's own interfaces.
148    // There is no file to read these from on macOS.
149    unsafe extern "C" {
150        fn mach_host_self() -> u32;
151        static mach_task_self_: u32;
152        fn host_processor_info(
153            host: u32,
154            flavor: c_int,
155            out_count: *mut u32,
156            out_info: *mut *mut c_int,
157            out_info_count: *mut u32,
158        ) -> c_int;
159        fn host_statistics64(host: u32, flavor: c_int, info: *mut c_int, count: *mut u32) -> c_int;
160        fn vm_deallocate(task: u32, address: usize, size: usize) -> c_int;
161        fn sysctlbyname(
162            name: *const c_char,
163            old: *mut c_void,
164            old_len: *mut usize,
165            new: *mut c_void,
166            new_len: usize,
167        ) -> c_int;
168        fn getloadavg(averages: *mut f64, n: c_int) -> c_int;
169    }
170
171    const PROCESSOR_CPU_LOAD_INFO: c_int = 2;
172    const HOST_VM_INFO64: c_int = 4;
173    /// `vm_statistics64` in 32-bit words.
174    const VM_INFO64_WORDS: usize = 38;
175
176    /// A fixed-size value by sysctl name (`name` ends with a NUL).
177    fn sysctl<const N: usize>(name: &'static [u8]) -> Option<[u8; N]> {
178        debug_assert!(name.ends_with(&[0]));
179        let mut out = [0u8; N];
180        let mut len = N;
181        // SAFETY: `name` is NUL-terminated; `out` is `len` bytes, and the
182        // kernel writes at most `len` and says how many it wrote.
183        let r = unsafe {
184            sysctlbyname(
185                name.as_ptr().cast(),
186                out.as_mut_ptr().cast(),
187                &mut len,
188                std::ptr::null_mut(),
189                0,
190            )
191        };
192        (r == 0 && len == N).then_some(out)
193    }
194
195    fn cores() -> Option<Vec<Ticks>> {
196        let (mut count, mut words) = (0u32, 0u32);
197        let mut info: *mut c_int = std::ptr::null_mut();
198        // SAFETY: the out pointers are valid for writes; on success the
199        // kernel gives an array of `words` 32-bit values that this
200        // process owns until it is deallocated below.
201        let r = unsafe {
202            host_processor_info(
203                mach_host_self(),
204                PROCESSOR_CPU_LOAD_INFO,
205                &mut count,
206                &mut info,
207                &mut words,
208            )
209        };
210        if r != 0 || info.is_null() {
211            return None;
212        }
213        // SAFETY: `info` points to `words` initialized values, as above.
214        let ticks = unsafe { std::slice::from_raw_parts(info.cast::<u32>(), words as usize) };
215        // Per core: user, system, idle, nice.
216        let cores: Vec<Ticks> = ticks
217            .as_chunks::<4>()
218            .0
219            .iter()
220            .take(count as usize)
221            .map(|c| {
222                let total: u64 = c.iter().map(|v| u64::from(*v)).sum();
223                Ticks {
224                    busy: total - u64::from(c[2]),
225                    total,
226                }
227            })
228            .collect();
229        // SAFETY: the array came from the call above and is not used
230        // after this; its size is `words` 32-bit values.
231        unsafe {
232            vm_deallocate(mach_task_self_, info as usize, words as usize * 4);
233        }
234        (!cores.is_empty()).then_some(cores)
235    }
236
237    /// Memory in use, as Activity Monitor counts it: what apps hold
238    /// (less what can be purged), what is wired, and what is compressed.
239    fn memory_used(page: u64) -> Option<u64> {
240        let mut words = [0u32; VM_INFO64_WORDS];
241        let mut count = VM_INFO64_WORDS as u32;
242        // SAFETY: `words` holds `count` 32-bit values, the size of
243        // `vm_statistics64`; the kernel writes at most that many.
244        let r = unsafe {
245            host_statistics64(
246                mach_host_self(),
247                HOST_VM_INFO64,
248                words.as_mut_ptr().cast(),
249                &mut count,
250            )
251        };
252        if r != 0 || (count as usize) < VM_INFO64_WORDS {
253            return None;
254        }
255        // Words of `vm_statistics64`: wire_count 3, purgeable_count 22,
256        // compressor_page_count 32, internal_page_count 35.
257        let (wired, purgeable, compressed, internal) = (
258            u64::from(words[3]),
259            u64::from(words[22]),
260            u64::from(words[32]),
261            u64::from(words[35]),
262        );
263        Some((internal.saturating_sub(purgeable) + wired + compressed) * page)
264    }
265
266    pub fn read() -> Option<Reading> {
267        let memory_total = u64::from_ne_bytes(sysctl::<8>(b"hw.memsize\0")?);
268        let page = u64::from_ne_bytes(sysctl::<8>(b"hw.pagesize\0")?);
269        // `struct timeval`: seconds, then microseconds.
270        let boot = sysctl::<16>(b"kern.boottime\0")?;
271        let booted = i64::from_ne_bytes(boot[..8].try_into().ok()?);
272        let now = std::time::SystemTime::now()
273            .duration_since(std::time::UNIX_EPOCH)
274            .ok()?
275            .as_secs() as i64;
276        let mut load = [0.0f64; 3];
277        // SAFETY: `load` has room for the three values asked for.
278        if unsafe { getloadavg(load.as_mut_ptr(), 3) } != 3 {
279            return None;
280        }
281        Some(Reading {
282            cores: cores()?,
283            memory_used: memory_used(page)?.min(memory_total),
284            memory_total,
285            load,
286            uptime_s: (now - booted).max(0) as u64,
287        })
288    }
289}
290
291#[cfg(not(any(target_os = "linux", target_os = "macos")))]
292mod imp {
293    pub fn read() -> Option<super::Reading> {
294        None
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn proc_files_are_read_as_ticks_and_bytes() {
304        let stat = "cpu  100 0 50 800 50 0 0 0 0 0\ncpu0 60 0 30 400 10 0 0 0 0 0\ncpu1 40 0 20 400 40 0 0 0 0 0\nintr 1 2\n";
305        let cores = proc_stat(stat);
306        assert_eq!(
307            cores,
308            [
309                Ticks {
310                    busy: 90,
311                    total: 500
312                },
313                Ticks {
314                    busy: 60,
315                    total: 500
316                }
317            ]
318        );
319        let mem = "MemTotal:       16000 kB\nMemFree:         1000 kB\nMemAvailable:    6000 kB\n";
320        assert_eq!(proc_meminfo(mem), Some((10_000 * 1024, 16_000 * 1024)));
321    }
322
323    #[test]
324    fn cpu_shares_come_from_two_readings() {
325        let a = [
326            Ticks {
327                busy: 100,
328                total: 1000,
329            },
330            Ticks {
331                busy: 0,
332                total: 1000,
333            },
334        ];
335        let b = [
336            Ticks {
337                busy: 150,
338                total: 1100,
339            },
340            Ticks {
341                busy: 0,
342                total: 1100,
343            },
344        ];
345        let (all, cores) = cpu_shares(&a, &b).expect("shares");
346        assert_eq!(cores, [0.5, 0.0]);
347        assert_eq!(all, 0.25);
348        assert!(cpu_shares(&a, &b[..1]).is_none());
349    }
350
351    /// On the systems Dreamer runs on, a reading is there and plausible.
352    #[cfg(any(target_os = "linux", target_os = "macos"))]
353    #[test]
354    fn this_host_reads_plausibly() {
355        let r = read().expect("a reading");
356        assert!(!r.cores.is_empty());
357        assert!(r.memory_total >= 256 * 1024 * 1024, "{}", r.memory_total);
358        assert!(r.memory_used > 0 && r.memory_used <= r.memory_total);
359        assert!(r.load.iter().all(|l| l.is_finite() && *l >= 0.0));
360        assert!(r.uptime_s > 0);
361    }
362}