use core::time::Duration;
use std::time::Instant;
use crate::{Error, Percent, Result, origin::Origin};
pub const DEFAULT_WINDOW: Duration = Duration::from_millis(100);
const MIN_WINDOW: Duration = Duration::from_millis(10);
const MAX_WINDOW: Duration = Duration::from_secs(10);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Times {
pub user: Duration,
pub nice: Duration,
pub system: Duration,
pub idle: Duration,
pub iowait: Duration,
pub irq: Duration,
pub softirq: Duration,
pub steal: Duration,
}
impl Times {
fn total(&self) -> Duration {
self.busy() + self.idle + self.iowait
}
fn busy(&self) -> Duration {
self.user + self.nice + self.system + self.irq + self.softirq + self.steal
}
fn since(&self, earlier: &Times) -> Option<Times> {
Some(Times {
user: self.user.checked_sub(earlier.user)?,
nice: self.nice.checked_sub(earlier.nice)?,
system: self.system.checked_sub(earlier.system)?,
idle: self.idle.checked_sub(earlier.idle)?,
iowait: self.iowait.checked_sub(earlier.iowait)?,
irq: self.irq.checked_sub(earlier.irq)?,
softirq: self.softirq.checked_sub(earlier.softirq)?,
steal: self.steal.checked_sub(earlier.steal)?,
})
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct States {
pub(crate) iowait: bool,
pub(crate) steal: bool,
pub(crate) irq: bool,
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Usage {
pub user: Percent,
pub system: Percent,
pub idle: Percent,
pub iowait: Option<Percent>,
pub steal: Option<Percent>,
pub irq: Option<Percent>,
pub interval: Duration,
}
impl Usage {
#[must_use]
pub fn used(&self) -> Percent {
self.free().complement()
}
#[must_use]
pub fn free(&self) -> Percent {
let iowait = self.iowait.map_or(0.0, Percent::value);
Percent::from_value(self.idle.value() + iowait)
}
fn from_delta(d: &Times, states: States, interval: Duration) -> Option<Usage> {
let total = d.total().as_nanos();
if total == 0 {
return None;
}
let share = |part: Duration| Percent::from_ratio_u128(part.as_nanos(), total);
Some(Usage {
user: share(d.user + d.nice),
system: share(d.system),
idle: share(d.idle),
iowait: states.iowait.then(|| share(d.iowait)),
steal: states.steal.then(|| share(d.steal)),
irq: states.irq.then(|| share(d.irq + d.softirq)),
interval,
})
}
}
pub fn times() -> Result<Times> {
crate::sys::cpu_times()
}
pub fn usage() -> Result<Usage> {
usage_over(DEFAULT_WINDOW)
}
pub fn usage_over(window: Duration) -> Result<Usage> {
let mut sampler = Sampler::total_only()?;
std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
sampler.sample()
}
pub fn used() -> Result<Percent> {
usage().map(|u| u.used())
}
pub fn free() -> Result<Percent> {
usage().map(|u| u.free())
}
#[derive(Debug)]
pub struct Sampler {
total: Times,
at: Instant,
cores_total: Times,
cores: Vec<Times>,
scratch: Vec<Times>,
cores_at: Instant,
origin: Origin,
}
impl Sampler {
pub fn new() -> Result<Sampler> {
Self::from(Origin::local())
}
pub(crate) fn from(origin: Origin) -> Result<Sampler> {
let total = origin.cpu_times()?;
let mut cores = vec![Times::default(); super::logical()];
let (cores_total, n) = match read_cores(&origin, &mut cores) {
Ok(r) => r,
Err(Error::Unsupported { .. }) => (total, 0),
Err(e) => return Err(e),
};
cores.truncate(n);
let now = Instant::now();
Ok(Sampler {
total,
at: now,
cores_total,
scratch: vec![Times::default(); cores.len()],
cores,
cores_at: now,
origin,
})
}
fn total_only() -> Result<Sampler> {
let now = Instant::now();
let total = times()?;
Ok(Sampler {
total,
at: now,
cores_total: total,
cores: Vec::new(),
scratch: Vec::new(),
cores_at: now,
origin: Origin::local(),
})
}
pub fn sample(&mut self) -> Result<Usage> {
let now = self.origin.cpu_times()?;
let at = Instant::now();
let usage = between(&now, &self.total, at.duration_since(self.at));
self.total = now;
self.at = at;
usage
}
pub fn sample_per_core(&mut self) -> Result<(Usage, Vec<Percent>)> {
let mut out = vec![Percent::ZERO; self.scratch.len().max(super::logical())];
let usage = self.sample_per_core_into(&mut out)?;
out.truncate(self.cores.len());
Ok((usage, out))
}
pub fn sample_per_core_into(&mut self, out: &mut [Percent]) -> Result<Usage> {
let (total, n) = read_cores(&self.origin, &mut self.scratch)?;
let at = Instant::now();
if out.len() < n {
return Err(Error::TooLarge {
what: "per-core CPU usage",
limit: out.len() as u64,
});
}
let interval = at.duration_since(self.cores_at);
let usage = between(&total, &self.cores_total, interval);
for (i, now) in self.scratch[..n].iter().enumerate() {
out[i] = self
.cores
.get(i)
.and_then(|old| now.since(old))
.and_then(|d| Usage::from_delta(&d, crate::sys::CPU_STATES, interval))
.map_or(Percent::ZERO, |u| u.used());
}
self.cores.resize(n, Times::default());
self.cores.copy_from_slice(&self.scratch[..n]);
self.cores_at = at;
self.cores_total = total;
usage
}
}
fn between(now: &Times, then: &Times, interval: Duration) -> Result<Usage> {
let too_soon = || Error::TooSoon {
elapsed: interval,
minimum: crate::sys::CPU_TICK,
};
let delta = now.since(then).ok_or_else(too_soon)?;
Usage::from_delta(&delta, crate::sys::CPU_STATES, interval).ok_or_else(too_soon)
}
const MAX_CORES: usize = 16_384;
fn read_cores(origin: &Origin, buf: &mut Vec<Times>) -> Result<(Times, usize)> {
loop {
match origin.cpu_times_per_core(buf) {
Err(Error::TooLarge { .. }) if buf.len() < MAX_CORES => {
let len = (buf.len() * 2 + super::logical()).min(MAX_CORES);
buf.resize(len, Times::default());
}
r => {
let (total, n) = r?;
return Ok((total, n.min(buf.len())));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "linux")]
#[test]
fn test_read_cores_grows_for_a_larger_probed_host() {
let host = crate::origin::Host {
root: crate::linux::fixtures::root("wsl2"),
net_dev: "/proc/net/dev",
};
let origin = Origin::host(std::sync::Arc::new(host));
let mut buf = vec![Times::default(); 1];
let (_, n) = read_cores(&origin, &mut buf).unwrap();
assert_eq!(n, 32);
assert!(buf.len() >= 32);
}
const ALL: States = States {
iowait: true,
steal: true,
irq: true,
};
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
fn times(user: u64, system: u64, idle: u64, iowait: u64, steal: u64) -> Times {
Times {
user: ms(user),
system: ms(system),
idle: ms(idle),
iowait: ms(iowait),
steal: ms(steal),
..Times::default()
}
}
#[test]
fn test_cpu_usage_steal_busy_iowait_idle() {
let d = times(300, 100, 400, 100, 100);
let u = Usage::from_delta(&d, ALL, ms(1000)).unwrap();
assert_eq!(u.user.to_string(), "30.0%");
assert_eq!(u.idle.to_string(), "40.0%");
assert_eq!(u.iowait.unwrap().to_string(), "10.0%");
assert_eq!(u.steal.unwrap().to_string(), "10.0%");
assert_eq!(u.free().to_string(), "50.0%");
assert_eq!(u.used().to_string(), "50.0%");
}
#[test]
fn test_cpu_usage_states_a_platform_lacks_are_none() {
let u = Usage::from_delta(
×(1, 1, 2, 0, 0),
States {
iowait: false,
steal: false,
irq: false,
},
ms(4),
)
.unwrap();
assert_eq!((u.iowait, u.steal, u.irq), (None, None, None));
assert_eq!(u.used().to_string(), "50.0%");
}
#[test]
fn test_cpu_usage_no_time_and_backwards_counters() {
assert!(Usage::from_delta(&Times::default(), ALL, ms(5)).is_none());
assert!(times(5, 0, 0, 0, 0).since(×(6, 0, 0, 0, 0)).is_none());
let d = times(7, 1, 2, 0, 0).since(×(5, 1, 1, 0, 0)).unwrap();
assert_eq!((d.user, d.idle), (ms(2), ms(1)));
}
#[test]
fn test_cpu_sampler_live_never_out_of_range() {
let mut s = Sampler::new().unwrap();
let mut out = vec![Percent::FULL; crate::cpu::logical() + 4];
std::thread::sleep(ms(30));
match s.sample_per_core_into(&mut out) {
Ok(u) => {
assert!(u.used() <= Percent::FULL && u.interval >= ms(25));
assert_eq!(
out[crate::cpu::logical() + 3],
Percent::FULL,
"past the cores is untouched"
);
}
Err(Error::TooSoon { .. } | Error::Unsupported { .. }) => {}
Err(e) => panic!("{e}"),
}
let mut short = [Percent::ZERO; 0];
if crate::cpu::logical() > 0 {
assert!(matches!(
s.sample_per_core_into(&mut short),
Err(Error::TooLarge { .. }) | Err(Error::Unsupported { .. })
));
}
std::thread::sleep(ms(30));
if let Ok(u) = s.sample() {
assert!(u.used() <= Percent::FULL);
}
let u = usage_over(ms(30)).unwrap();
assert!(u.used() <= Percent::FULL);
}
}