use std::time::Duration;
const CLOCK_TICKS: u64 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Process {
pub(crate) cpu: Duration,
pub(crate) started_at: u64,
pub(crate) threads: Option<u64>,
pub(crate) open_fds: Option<u64>,
pub(crate) max_fds: Option<u64>,
}
impl Process {
pub(crate) fn read() -> Option<Self> {
let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
let (user, system, started) = parse_stat(&stat)?;
let stat_all = std::fs::read_to_string("/proc/stat").ok()?;
let boot = boot_time(&stat_all)?;
let ticks = user.checked_add(system)?;
let threads = std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|status| parse_threads(&status));
let max_fds = std::fs::read_to_string("/proc/self/limits")
.ok()
.and_then(|limits| parse_max_fds(&limits));
Some(Self {
cpu: Duration::from_secs_f64(ticks as f64 / CLOCK_TICKS as f64),
started_at: boot.checked_add(started / CLOCK_TICKS)?,
threads,
open_fds: open_fds(),
max_fds,
})
}
}
fn open_fds() -> Option<u64> {
let count = std::fs::read_dir("/proc/self/fd")
.ok()?
.filter_map(Result::ok)
.count();
u64::try_from(count.saturating_sub(1)).ok()
}
pub(crate) fn parse_threads(status: &str) -> Option<u64> {
status
.lines()
.find_map(|line| line.strip_prefix("Threads:")?.trim().parse().ok())
}
pub(crate) fn parse_max_fds(limits: &str) -> Option<u64> {
let line = limits
.lines()
.find(|line| line.starts_with("Max open files"))?;
line.split_whitespace().nth(3)?.parse().ok()
}
pub(crate) fn parse_stat(text: &str) -> Option<(u64, u64, u64)> {
let rest = text.rsplit_once(')')?.1;
let fields = rest.split_whitespace();
let nth = |distance: usize| fields.clone().nth(distance)?.parse::<u64>().ok();
let user = nth(11)?;
let system = nth(12)?;
let started = nth(19)?;
Some((user, system, started))
}
pub(crate) fn boot_time(text: &str) -> Option<u64> {
text.lines()
.find(|line| line.starts_with("btime "))
.and_then(|line| line["btime".len()..].trim().parse().ok())
}
#[cfg(test)]
mod tests {
use super::{Process, boot_time, parse_max_fds, parse_stat, parse_threads};
const STAT: &str = "4242 (trial worker) S 1 4242 4242 0 -1 4194304 1234 0 0 0 150 40 0 0 20 0 3 0 987654 120000 5000 18446744073709551615 \n";
#[test]
fn cpu_time_and_start_are_read_from_stat() {
assert_eq!(parse_stat(STAT), Some((150, 40, 987654)));
}
#[test]
fn stat_without_parentheses_is_rejected() {
assert_eq!(parse_stat("4242 trial S 1"), None);
}
#[test]
fn boot_time_is_read_from_proc_stat() {
const TEXT: &str = "cpu 10 0 5 1000 0 0 0 0 0 0\ncpu0 5 0 2 500 0 0 0 0 0 0\nbtime 1795815300\nprocesses 1234\n";
assert_eq!(boot_time(TEXT), Some(1_795_815_300));
assert_eq!(boot_time("cpu 1 1 1 1"), None);
}
#[test]
fn threads_are_read_from_status() {
const STATUS: &str = "Name:\ttrial\nVmRSS:\t 12345 kB\nThreads:\t12\n";
assert_eq!(parse_threads(STATUS), Some(12));
assert_eq!(parse_threads("Name:\ttrial\n"), None);
}
#[test]
fn soft_limit_of_descriptors_is_read_from_limits() {
const LIMITS: &str = "Limit Soft Limit Hard Limit Units\nMax open files 1048576 1048576 files\n";
assert_eq!(parse_max_fds(LIMITS), Some(1_048_576));
const UNLIMITED: &str =
"Max open files unlimited unlimited files\n";
assert_eq!(parse_max_fds(UNLIMITED), None);
assert_eq!(parse_max_fds("Max processes 1 2 processes"), None);
}
#[test]
fn process_read_is_consistent_with_the_clock() {
let first = Process::read().expect("the process statistics are readable");
let busy: u64 = (0u64..2_000_000).map(|value| value.wrapping_mul(3)).sum();
let second = Process::read().expect("the process statistics are readable");
assert!(busy > 0);
assert!(second.cpu >= first.cpu);
assert_eq!(second.started_at, first.started_at);
assert!(second.started_at > 1_700_000_000);
assert!(first.threads.is_some_and(|threads| threads >= 1));
assert!(first.open_fds.is_some_and(|fds| fds >= 1));
assert!(first.max_fds.is_some_and(|fds| fds > 0));
}
}