use core::{ops::Sub, time::Duration};
use std::time::{Instant, SystemTime};
use super::{Limit, User};
use crate::{Bytes, Error, Percent, Result};
#[must_use]
pub fn parent_id() -> Option<u32> {
crate::sys::parent_id()
}
pub fn memory() -> Result<Bytes> {
crate::sys::process_memory()
}
pub fn peak_memory() -> Result<Bytes> {
crate::sys::peak_memory()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct ProcessMemory {
pub resident: Bytes,
pub peak_resident: Bytes,
pub virtual_size: Bytes,
pub private: Option<Bytes>,
pub shared: Option<Bytes>,
pub swapped: Option<Bytes>,
}
pub fn memory_detail() -> Result<ProcessMemory> {
crate::sys::memory_detail()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct CpuTime {
pub user: Duration,
pub system: Duration,
}
impl CpuTime {
#[must_use]
pub fn total(&self) -> Duration {
self.user.saturating_add(self.system)
}
}
pub fn cpu_time() -> Result<CpuTime> {
crate::sys::cpu_time()
}
pub fn threads() -> Result<usize> {
crate::sys::threads()
}
pub fn open_files() -> Result<usize> {
crate::sys::open_files()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Limits {
pub open_files: Limit,
pub processes: Limit,
pub address_space: Limit,
pub core_dump: Limit,
pub stack: Limit,
}
pub fn limits() -> Result<Limits> {
crate::sys::limits()
}
pub fn started_at() -> Result<SystemTime> {
crate::sys::started_at()
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ProcessInfo {
pub id: u32,
pub parent_id: Option<u32>,
pub memory: ProcessMemory,
pub cpu_time: CpuTime,
pub threads: Option<usize>,
pub open_files: Option<usize>,
pub limits: Limits,
pub started_at: Option<SystemTime>,
pub user: Option<User>,
pub is_elevated: Option<bool>,
}
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub struct InfoOptions {
pub with_threads: bool,
}
pub fn info() -> Result<ProcessInfo> {
info_with(InfoOptions::default())
}
pub fn info_with(options: InfoOptions) -> Result<ProcessInfo> {
let threads = if cfg!(windows) && !options.with_threads {
None
} else {
threads().ok()
};
Ok(ProcessInfo {
id: super::id(),
parent_id: parent_id(),
memory: memory_detail()?,
cpu_time: cpu_time()?,
threads,
open_files: open_files().ok(),
limits: limits()?,
started_at: started_at().ok(),
user: super::user().ok(),
is_elevated: super::is_elevated().ok(),
})
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct ProcessIo {
pub read: Bytes,
pub written: Bytes,
pub read_ops: Option<u64>,
pub write_ops: Option<u64>,
pub storage_only: bool,
}
impl Sub for ProcessIo {
type Output = ProcessIo;
fn sub(self, earlier: ProcessIo) -> ProcessIo {
let ops = |a: Option<u64>, b: Option<u64>| Some(a?.saturating_sub(b?));
ProcessIo {
read: self.read.saturating_sub(earlier.read),
written: self.written.saturating_sub(earlier.written),
read_ops: ops(self.read_ops, earlier.read_ops),
write_ops: ops(self.write_ops, earlier.write_ops),
storage_only: self.storage_only,
}
}
}
pub fn io() -> Result<ProcessIo> {
crate::sys::process_io()
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ProcessUsage {
pub of_one_core: f32,
pub of_machine: Percent,
pub interval: Duration,
}
#[derive(Debug)]
pub struct CpuSampler {
previous: CpuTime,
at: Instant,
}
impl CpuSampler {
pub fn new() -> Result<CpuSampler> {
Ok(CpuSampler {
previous: cpu_time()?,
at: Instant::now(),
})
}
pub fn sample(&mut self) -> Result<ProcessUsage> {
let now = cpu_time()?;
let at = Instant::now();
let interval = at.duration_since(self.at);
if interval.is_zero() {
return Err(Error::TooSoon {
elapsed: interval,
minimum: Duration::from_millis(1),
});
}
let used = now.total().saturating_sub(self.previous.total());
let cpus = crate::cpu::logical() as f32;
let of_one_core = (used.as_secs_f64() / interval.as_secs_f64() * 100.0) as f32;
let of_one_core = of_one_core.clamp(0.0, 100.0 * cpus);
self.previous = now;
self.at = at;
Ok(ProcessUsage {
of_one_core,
of_machine: Percent::from_value(of_one_core / cpus),
interval,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_process_readings_live() {
let rss = memory().unwrap();
assert!(rss.raw() > 0);
assert!(peak_memory().unwrap() >= rss || cfg!(windows));
let d = memory_detail().unwrap();
assert!(d.virtual_size >= d.resident || d.virtual_size.raw() == 0);
let t = cpu_time().unwrap();
assert!(t.total() >= t.user);
assert!(threads().unwrap() >= 1);
assert!(open_files().unwrap() >= 1);
let l = limits().unwrap();
if let (Some(s), Some(h)) = (l.open_files.soft, l.open_files.hard) {
assert!(s <= h);
}
let started = started_at().unwrap();
assert!(started <= SystemTime::now());
let info = info().unwrap();
assert_eq!(info.id, super::super::id());
let io = io().unwrap();
assert_eq!((io - io).read, Bytes::ZERO);
}
#[test]
fn test_process_cpu_sampler_bounded() {
let mut s = CpuSampler::new().unwrap();
let mut x = 0u64;
let start = Instant::now();
while start.elapsed() < Duration::from_millis(30) {
x = x.wrapping_mul(31).wrapping_add(7);
}
std::hint::black_box(x);
let u = s.sample().unwrap();
assert!(u.of_one_core >= 0.0 && u.of_one_core <= 100.0 * crate::cpu::logical() as f32);
assert!(u.of_machine <= Percent::FULL);
}
#[test]
fn test_process_io_subtracts_saturating() {
let a = ProcessIo {
read: Bytes::new(10),
written: Bytes::new(20),
read_ops: Some(3),
write_ops: None,
storage_only: true,
};
let b = ProcessIo {
read: Bytes::new(15),
written: Bytes::new(5),
read_ops: Some(5),
write_ops: Some(1),
storage_only: true,
};
let d = b - a;
assert_eq!(
(d.read.raw(), d.written.raw(), d.read_ops, d.write_ops),
(5, 0, Some(2), None)
);
}
}