use super::{HostReader, MachineLoad, MemoryPressure, ReadError};
#[cfg(target_vendor = "apple")]
use apple as platform;
#[cfg(any(target_os = "linux", target_os = "android"))]
use linux as platform;
#[cfg(not(any(
target_vendor = "apple",
target_os = "linux",
target_os = "android",
windows
)))]
use unsupported as platform;
#[cfg(windows)]
use windows as platform;
#[derive(Debug)]
pub struct SystemReader(platform::State);
impl SystemReader {
pub const DEFAULT_LOAD_THRESHOLD: f64 = platform::DEFAULT_LOAD_THRESHOLD;
pub fn new() -> Result<Self, ReadError> {
let mut state = platform::State::new()?;
platform::memory_pressure(&state)?;
platform::machine_load(&mut state)?;
Ok(Self(state))
}
}
impl HostReader for SystemReader {
fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError> {
platform::memory_pressure(&self.0)
}
fn machine_load(&mut self) -> Result<MachineLoad, ReadError> {
platform::machine_load(&mut self.0)
}
}
fn psi_avg10(content: &str, kind: &str) -> Option<f64> {
content
.lines()
.find_map(|line| line.strip_prefix(kind)?.strip_prefix(' '))?
.split_whitespace()
.find_map(|field| field.strip_prefix("avg10="))?
.parse()
.ok()
}
const PSI_WARNING_PERCENT: f64 = 10.0;
const PSI_CRITICAL_PERCENT: f64 = 10.0;
pub fn psi_memory_pressure(content: &str) -> Option<MemoryPressure> {
Some(if psi_avg10(content, "full")? >= PSI_CRITICAL_PERCENT {
MemoryPressure::Critical
} else if psi_avg10(content, "some")? >= PSI_WARNING_PERCENT {
MemoryPressure::Warning
} else {
MemoryPressure::Normal
})
}
#[cfg(target_vendor = "apple")]
mod apple {
use std::ffi::{CStr, c_int, c_void};
use std::io;
use super::{MachineLoad, MemoryPressure, ReadError};
pub const DEFAULT_LOAD_THRESHOLD: f64 = 1.0;
const PRESSURE_LEVEL: &CStr = c"kern.memorystatus_vm_pressure_level";
#[derive(Debug)]
pub struct State {
cores: f64,
}
impl State {
#[allow(clippy::unnecessary_wraps)]
pub fn new() -> Result<Self, ReadError> {
let cores = std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
#[allow(clippy::cast_precision_loss)]
Ok(Self {
cores: cores as f64,
})
}
}
pub fn memory_pressure(_: &State) -> Result<MemoryPressure, ReadError> {
let mut level: c_int = 0;
let mut size = size_of::<c_int>();
let status = unsafe {
libc::sysctlbyname(
PRESSURE_LEVEL.as_ptr(),
(&raw mut level).cast::<c_void>(),
&raw mut size,
std::ptr::null_mut(),
0,
)
};
if status != 0 {
return Err(ReadError::Io {
what: "kern.memorystatus_vm_pressure_level",
source: io::Error::last_os_error(),
});
}
match level {
1 => Ok(MemoryPressure::Normal),
2 => Ok(MemoryPressure::Warning),
4 => Ok(MemoryPressure::Critical),
other => Err(ReadError::Malformed {
what: "kern.memorystatus_vm_pressure_level",
content: other.to_string(),
}),
}
}
#[allow(clippy::needless_pass_by_ref_mut)]
pub fn machine_load(state: &mut State) -> Result<MachineLoad, ReadError> {
let mut average = 0.0_f64;
let samples = unsafe { libc::getloadavg(&raw mut average, 1) };
if samples != 1 {
return Err(ReadError::Io {
what: "the load average",
source: io::Error::other("getloadavg returned no sample"),
});
}
Ok(MachineLoad(average / state.cores))
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux {
use std::fs;
use super::{MachineLoad, MemoryPressure, ReadError, psi_avg10, psi_memory_pressure};
pub const DEFAULT_LOAD_THRESHOLD: f64 = 0.3;
const MEMORY: &str = "/proc/pressure/memory";
const CPU: &str = "/proc/pressure/cpu";
#[derive(Debug)]
pub struct State;
impl State {
#[allow(clippy::unnecessary_wraps)]
pub const fn new() -> Result<Self, ReadError> {
Ok(Self)
}
}
fn read(path: &'static str) -> Result<String, ReadError> {
fs::read_to_string(path).map_err(|source| ReadError::Io { what: path, source })
}
fn avg10(path: &'static str, content: &str, kind: &str) -> Result<f64, ReadError> {
psi_avg10(content, kind).ok_or_else(|| ReadError::Malformed {
what: path,
content: content.to_owned(),
})
}
pub fn memory_pressure(_: &State) -> Result<MemoryPressure, ReadError> {
let content = read(MEMORY)?;
psi_memory_pressure(&content).ok_or(ReadError::Malformed {
what: MEMORY,
content,
})
}
pub fn machine_load(_: &mut State) -> Result<MachineLoad, ReadError> {
let content = read(CPU)?;
Ok(MachineLoad(avg10(CPU, &content, "some")? / 100.0))
}
}
#[cfg(windows)]
mod windows {
use std::io;
use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
use windows_sys::Win32::System::Memory::{
CreateMemoryResourceNotification, LowMemoryResourceNotification,
QueryMemoryResourceNotification,
};
use windows_sys::Win32::System::Threading::GetSystemTimes;
use super::{MachineLoad, MemoryPressure, ReadError};
pub const DEFAULT_LOAD_THRESHOLD: f64 = 0.9;
#[derive(Debug, Clone, Copy)]
struct Times {
idle: u64,
total: u64,
}
#[derive(Debug)]
pub struct State {
previous: Times,
}
fn ticks(time: FILETIME) -> u64 {
(u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime)
}
fn times() -> Result<Times, ReadError> {
let (mut idle, mut kernel, mut user) = (
FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
},
FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
},
FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
},
);
let ok = unsafe { GetSystemTimes(&raw mut idle, &raw mut kernel, &raw mut user) };
if ok == 0 {
return Err(ReadError::Io {
what: "GetSystemTimes",
source: io::Error::last_os_error(),
});
}
Ok(Times {
idle: ticks(idle),
total: ticks(kernel) + ticks(user),
})
}
impl State {
pub fn new() -> Result<Self, ReadError> {
Ok(Self { previous: times()? })
}
}
pub fn memory_pressure(_: &State) -> Result<MemoryPressure, ReadError> {
let handle = unsafe { CreateMemoryResourceNotification(LowMemoryResourceNotification) };
if handle.is_null() {
return Err(ReadError::Io {
what: "the low-memory resource notification",
source: io::Error::last_os_error(),
});
}
let mut low = 0;
let queried = unsafe { QueryMemoryResourceNotification(handle, &raw mut low) };
let queried_error = io::Error::last_os_error();
unsafe { CloseHandle(handle) };
if queried == 0 {
return Err(ReadError::Io {
what: "the low-memory resource notification",
source: queried_error,
});
}
Ok(if low == 0 {
MemoryPressure::Normal
} else {
MemoryPressure::Warning
})
}
pub fn machine_load(state: &mut State) -> Result<MachineLoad, ReadError> {
let now = times()?;
let total = now.total.saturating_sub(state.previous.total);
let idle = now.idle.saturating_sub(state.previous.idle);
state.previous = now;
if total == 0 {
return Ok(MachineLoad(0.0));
}
#[allow(clippy::cast_precision_loss)]
let busy = 1.0 - idle as f64 / total as f64;
Ok(MachineLoad(busy))
}
}
#[cfg(not(any(
target_vendor = "apple",
target_os = "linux",
target_os = "android",
windows
)))]
mod unsupported {
use super::{MachineLoad, MemoryPressure, ReadError};
pub const DEFAULT_LOAD_THRESHOLD: f64 = 1.0;
#[derive(Debug)]
pub struct State;
impl State {
pub const fn new() -> Result<Self, ReadError> {
Err(ReadError::Unsupported {
what: "host memory pressure and load",
})
}
}
pub fn memory_pressure(_: &State) -> Result<MemoryPressure, ReadError> {
unreachable!("an unsupported host has no reader")
}
pub fn machine_load(_: &mut State) -> Result<MachineLoad, ReadError> {
unreachable!("an unsupported host has no reader")
}
}
#[cfg(test)]
mod tests {
use super::*;
const PSI_MEMORY: &str = "some avg10=12.50 avg60=3.00 avg300=1.00 total=123456\nfull avg10=0.40 avg60=0.10 avg300=0.00 total=789\n";
#[test]
fn psi_lines_are_read_by_kind() {
assert_eq!(psi_avg10(PSI_MEMORY, "some"), Some(12.5));
assert_eq!(psi_avg10(PSI_MEMORY, "full"), Some(0.4));
assert_eq!(psi_avg10("some avg60=1.0", "some"), None);
assert_eq!(psi_avg10("", "full"), None);
}
#[test]
fn psi_text_states_a_memory_pressure_level() {
let stall = |some, full| {
format!(
"some avg10={some} avg60=0.00 avg300=0.00 total=1\nfull avg10={full} avg60=0.00 avg300=0.00 total=1\n"
)
};
assert_eq!(
psi_memory_pressure(&stall("0.00", "0.00")),
Some(MemoryPressure::Normal)
);
assert_eq!(
psi_memory_pressure(&stall("12.00", "0.00")),
Some(MemoryPressure::Warning)
);
assert_eq!(
psi_memory_pressure(&stall("30.00", "10.00")),
Some(MemoryPressure::Critical)
);
assert_eq!(psi_memory_pressure("not pressure"), None);
}
#[cfg(any(target_vendor = "apple", windows))]
#[test]
fn the_host_reader_reads_this_host() {
let mut reader = SystemReader::new().expect("this host offers both readings");
reader.memory_pressure().expect("memory pressure reads");
let load = reader.machine_load().expect("machine load reads");
assert!(load.0 >= 0.0, "load is not negative: {load:?}");
}
}