dreamer-platform 0.16.1

Per-user paths and small OS helpers shared by Dreamer's executables
Documentation
//! The host's CPU, memory, load, and uptime, read from the system itself
//! (`/proc` on Linux, the kernel's own calls on macOS): no program is
//! started for a sample.
//!
//! CPU time is cumulative since boot, in the system's own ticks, so a
//! caller works out a share from two readings ([`cpu_shares`]).

/// One reading.
#[derive(Debug, Clone, PartialEq)]
pub struct Reading {
    /// Per core: ticks spent busy, and ticks in all, since boot.
    pub cores: Vec<Ticks>,
    pub memory_used: u64,
    pub memory_total: u64,
    /// The load averages over 1, 5, and 15 minutes.
    pub load: [f64; 3],
    pub uptime_s: u64,
}

/// A core's CPU time since boot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Ticks {
    pub busy: u64,
    pub total: u64,
}

/// The share of time each core was busy between two readings (0 to 1),
/// and the share over all of them. A core with no ticks between the two
/// counts as idle; readings with different core counts give nothing.
pub fn cpu_shares(earlier: &[Ticks], later: &[Ticks]) -> Option<(f64, Vec<f64>)> {
    if earlier.len() != later.len() || later.is_empty() {
        return None;
    }
    let (mut busy, mut total) = (0u64, 0u64);
    let cores = earlier
        .iter()
        .zip(later)
        .map(|(a, b)| {
            let (db, dt) = (
                b.busy.saturating_sub(a.busy),
                b.total.saturating_sub(a.total),
            );
            busy += db;
            total += dt;
            if dt == 0 {
                0.0
            } else {
                (db as f64 / dt as f64).clamp(0.0, 1.0)
            }
        })
        .collect();
    let all = if total == 0 {
        0.0
    } else {
        (busy as f64 / total as f64).clamp(0.0, 1.0)
    };
    Some((all, cores))
}

/// Read the host now. `None` where this system is not supported, or a
/// source could not be read.
pub fn read() -> Option<Reading> {
    imp::read()
}

/// `/proc/stat`'s per-core lines as ticks: busy is everything but idle
/// and waiting for I/O.
#[cfg(any(target_os = "linux", test))]
fn proc_stat(text: &str) -> Vec<Ticks> {
    text.lines()
        .filter(|l| {
            l.strip_prefix("cpu")
                .is_some_and(|r| r.starts_with(|c: char| c.is_ascii_digit()))
        })
        .map(|l| {
            let n: Vec<u64> = l
                .split_whitespace()
                .skip(1)
                .filter_map(|v| v.parse().ok())
                .collect();
            // user nice system idle iowait irq softirq steal (guest time is
            // already in user).
            let total: u64 = n.iter().take(8).sum();
            let idle = n.get(3).copied().unwrap_or(0) + n.get(4).copied().unwrap_or(0);
            Ticks {
                busy: total.saturating_sub(idle),
                total,
            }
        })
        .collect()
}

/// `/proc/meminfo`: used (total less what is available) and total, in
/// bytes.
#[cfg(any(target_os = "linux", test))]
fn proc_meminfo(text: &str) -> Option<(u64, u64)> {
    let kb = |key: &str| -> Option<u64> {
        text.lines()
            .find_map(|l| l.strip_prefix(key)?.strip_prefix(':'))
            .and_then(|v| v.split_whitespace().next()?.parse().ok())
    };
    let total = kb("MemTotal")?;
    let available = kb("MemAvailable").or_else(|| kb("MemFree"))?;
    Some((total.saturating_sub(available) * 1024, total * 1024))
}

#[cfg(target_os = "linux")]
mod imp {
    use super::{Reading, proc_meminfo, proc_stat};

    pub fn read() -> Option<Reading> {
        let file = |p: &str| std::fs::read_to_string(p).ok();
        let cores = proc_stat(&file("/proc/stat")?);
        if cores.is_empty() {
            return None;
        }
        let (memory_used, memory_total) = proc_meminfo(&file("/proc/meminfo")?)?;
        let mut load = [0.0; 3];
        for (slot, v) in load
            .iter_mut()
            .zip(file("/proc/loadavg")?.split_whitespace())
        {
            *slot = v.parse().ok()?;
        }
        let uptime_s = file("/proc/uptime")?
            .split_whitespace()
            .next()?
            .parse::<f64>()
            .ok()? as u64;
        Some(Reading {
            cores,
            memory_used,
            memory_total,
            load,
            uptime_s,
        })
    }
}

#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
mod imp {
    use std::ffi::{c_char, c_int, c_void};

    use super::{Reading, Ticks};

    // Mach's host statistics, and sysctl: the kernel's own interfaces.
    // There is no file to read these from on macOS.
    unsafe extern "C" {
        fn mach_host_self() -> u32;
        static mach_task_self_: u32;
        fn host_processor_info(
            host: u32,
            flavor: c_int,
            out_count: *mut u32,
            out_info: *mut *mut c_int,
            out_info_count: *mut u32,
        ) -> c_int;
        fn host_statistics64(host: u32, flavor: c_int, info: *mut c_int, count: *mut u32) -> c_int;
        fn vm_deallocate(task: u32, address: usize, size: usize) -> c_int;
        fn sysctlbyname(
            name: *const c_char,
            old: *mut c_void,
            old_len: *mut usize,
            new: *mut c_void,
            new_len: usize,
        ) -> c_int;
        fn getloadavg(averages: *mut f64, n: c_int) -> c_int;
    }

    const PROCESSOR_CPU_LOAD_INFO: c_int = 2;
    const HOST_VM_INFO64: c_int = 4;
    /// `vm_statistics64` in 32-bit words.
    const VM_INFO64_WORDS: usize = 38;

    /// A fixed-size value by sysctl name (`name` ends with a NUL).
    fn sysctl<const N: usize>(name: &'static [u8]) -> Option<[u8; N]> {
        debug_assert!(name.ends_with(&[0]));
        let mut out = [0u8; N];
        let mut len = N;
        // SAFETY: `name` is NUL-terminated; `out` is `len` bytes, and the
        // kernel writes at most `len` and says how many it wrote.
        let r = unsafe {
            sysctlbyname(
                name.as_ptr().cast(),
                out.as_mut_ptr().cast(),
                &mut len,
                std::ptr::null_mut(),
                0,
            )
        };
        (r == 0 && len == N).then_some(out)
    }

    fn cores() -> Option<Vec<Ticks>> {
        let (mut count, mut words) = (0u32, 0u32);
        let mut info: *mut c_int = std::ptr::null_mut();
        // SAFETY: the out pointers are valid for writes; on success the
        // kernel gives an array of `words` 32-bit values that this
        // process owns until it is deallocated below.
        let r = unsafe {
            host_processor_info(
                mach_host_self(),
                PROCESSOR_CPU_LOAD_INFO,
                &mut count,
                &mut info,
                &mut words,
            )
        };
        if r != 0 || info.is_null() {
            return None;
        }
        // SAFETY: `info` points to `words` initialized values, as above.
        let ticks = unsafe { std::slice::from_raw_parts(info.cast::<u32>(), words as usize) };
        // Per core: user, system, idle, nice.
        let cores: Vec<Ticks> = ticks
            .as_chunks::<4>()
            .0
            .iter()
            .take(count as usize)
            .map(|c| {
                let total: u64 = c.iter().map(|v| u64::from(*v)).sum();
                Ticks {
                    busy: total - u64::from(c[2]),
                    total,
                }
            })
            .collect();
        // SAFETY: the array came from the call above and is not used
        // after this; its size is `words` 32-bit values.
        unsafe {
            vm_deallocate(mach_task_self_, info as usize, words as usize * 4);
        }
        (!cores.is_empty()).then_some(cores)
    }

    /// Memory in use, as Activity Monitor counts it: what apps hold
    /// (less what can be purged), what is wired, and what is compressed.
    fn memory_used(page: u64) -> Option<u64> {
        let mut words = [0u32; VM_INFO64_WORDS];
        let mut count = VM_INFO64_WORDS as u32;
        // SAFETY: `words` holds `count` 32-bit values, the size of
        // `vm_statistics64`; the kernel writes at most that many.
        let r = unsafe {
            host_statistics64(
                mach_host_self(),
                HOST_VM_INFO64,
                words.as_mut_ptr().cast(),
                &mut count,
            )
        };
        if r != 0 || (count as usize) < VM_INFO64_WORDS {
            return None;
        }
        // Words of `vm_statistics64`: wire_count 3, purgeable_count 22,
        // compressor_page_count 32, internal_page_count 35.
        let (wired, purgeable, compressed, internal) = (
            u64::from(words[3]),
            u64::from(words[22]),
            u64::from(words[32]),
            u64::from(words[35]),
        );
        Some((internal.saturating_sub(purgeable) + wired + compressed) * page)
    }

    pub fn read() -> Option<Reading> {
        let memory_total = u64::from_ne_bytes(sysctl::<8>(b"hw.memsize\0")?);
        let page = u64::from_ne_bytes(sysctl::<8>(b"hw.pagesize\0")?);
        // `struct timeval`: seconds, then microseconds.
        let boot = sysctl::<16>(b"kern.boottime\0")?;
        let booted = i64::from_ne_bytes(boot[..8].try_into().ok()?);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_secs() as i64;
        let mut load = [0.0f64; 3];
        // SAFETY: `load` has room for the three values asked for.
        if unsafe { getloadavg(load.as_mut_ptr(), 3) } != 3 {
            return None;
        }
        Some(Reading {
            cores: cores()?,
            memory_used: memory_used(page)?.min(memory_total),
            memory_total,
            load,
            uptime_s: (now - booted).max(0) as u64,
        })
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
mod imp {
    pub fn read() -> Option<super::Reading> {
        None
    }
}

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

    #[test]
    fn proc_files_are_read_as_ticks_and_bytes() {
        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";
        let cores = proc_stat(stat);
        assert_eq!(
            cores,
            [
                Ticks {
                    busy: 90,
                    total: 500
                },
                Ticks {
                    busy: 60,
                    total: 500
                }
            ]
        );
        let mem = "MemTotal:       16000 kB\nMemFree:         1000 kB\nMemAvailable:    6000 kB\n";
        assert_eq!(proc_meminfo(mem), Some((10_000 * 1024, 16_000 * 1024)));
    }

    #[test]
    fn cpu_shares_come_from_two_readings() {
        let a = [
            Ticks {
                busy: 100,
                total: 1000,
            },
            Ticks {
                busy: 0,
                total: 1000,
            },
        ];
        let b = [
            Ticks {
                busy: 150,
                total: 1100,
            },
            Ticks {
                busy: 0,
                total: 1100,
            },
        ];
        let (all, cores) = cpu_shares(&a, &b).expect("shares");
        assert_eq!(cores, [0.5, 0.0]);
        assert_eq!(all, 0.25);
        assert!(cpu_shares(&a, &b[..1]).is_none());
    }

    /// On the systems Dreamer runs on, a reading is there and plausible.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn this_host_reads_plausibly() {
        let r = read().expect("a reading");
        assert!(!r.cores.is_empty());
        assert!(r.memory_total >= 256 * 1024 * 1024, "{}", r.memory_total);
        assert!(r.memory_used > 0 && r.memory_used <= r.memory_total);
        assert!(r.load.iter().all(|l| l.is_finite() && *l >= 0.0));
        assert!(r.uptime_s > 0);
    }
}