#[derive(Debug, Clone, PartialEq)]
pub struct Reading {
pub cores: Vec<Ticks>,
pub memory_used: u64,
pub memory_total: u64,
pub load: [f64; 3],
pub uptime_s: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Ticks {
pub busy: u64,
pub total: u64,
}
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))
}
pub fn read() -> Option<Reading> {
imp::read()
}
#[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();
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()
}
#[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};
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;
const VM_INFO64_WORDS: usize = 38;
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;
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();
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;
}
let ticks = unsafe { std::slice::from_raw_parts(info.cast::<u32>(), words as usize) };
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();
unsafe {
vm_deallocate(mach_task_self_, info as usize, words as usize * 4);
}
(!cores.is_empty()).then_some(cores)
}
fn memory_used(page: u64) -> Option<u64> {
let mut words = [0u32; VM_INFO64_WORDS];
let mut count = VM_INFO64_WORDS as u32;
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;
}
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")?);
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];
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());
}
#[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);
}
}