#[cfg(unix)]
use std::collections::HashMap;
#[cfg(unix)]
use sysinfo::{Pid, ProcessRefreshKind, ProcessStatus, ProcessesToUpdate, System};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct ProcInstant(u64);
impl ProcInstant {
pub(crate) fn now() -> Self {
#[cfg(target_os = "linux")]
let now = linux::ticks_now().unwrap_or(0);
#[cfg(not(target_os = "linux"))]
let now = crate::now_ms() / 1000;
Self(now)
}
#[cfg(unix)]
pub(crate) fn earliest_start() -> Self {
#[cfg(target_os = "linux")]
{
Self(0)
}
#[cfg(not(target_os = "linux"))]
{
Self::after_boot((crate::now_ms() / 1000).saturating_sub(System::uptime()))
}
}
#[cfg(any(test, all(unix, not(target_os = "linux"))))]
pub(crate) fn after_boot(booted_secs: u64) -> Self {
Self(booted_secs.saturating_sub(BOOT_SLACK_SECS))
}
#[cfg(test)]
pub(crate) const fn from_raw(raw: u64) -> Self {
Self(raw)
}
#[cfg(test)]
pub(crate) const fn raw(self) -> u64 {
self.0
}
}
#[cfg(any(test, all(unix, not(target_os = "linux"))))]
pub(crate) const BOOT_SLACK_SECS: u64 = 2;
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PidReading {
pub started_secs: Option<u64>,
pub started: Option<ProcInstant>,
pub zombie: bool,
}
#[cfg(unix)]
fn refresh_kind() -> ProcessRefreshKind {
ProcessRefreshKind::nothing().without_tasks()
}
#[cfg(unix)]
pub(crate) fn read_pids(pids: &[u32]) -> HashMap<u32, PidReading> {
let wanted: Vec<Pid> = pids.iter().copied().map(Pid::from_u32).collect();
let mut system = System::new();
system.refresh_processes_specifics(ProcessesToUpdate::Some(&wanted), true, refresh_kind());
system
.processes()
.values()
.map(|process| {
let pid = process.pid().as_u32();
let started = process.start_time();
let started_secs = (started != 0).then_some(started);
let reading = PidReading {
started_secs,
started: start_instant(pid, started_secs),
zombie: matches!(
process.status(),
ProcessStatus::Zombie | ProcessStatus::Dead
),
};
(pid, reading)
})
.collect()
}
#[cfg(target_os = "linux")]
fn start_instant(pid: u32, _started_secs: Option<u64>) -> Option<ProcInstant> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
parse_start_ticks(&stat).map(ProcInstant)
}
#[cfg(all(unix, not(target_os = "linux")))]
fn start_instant(_pid: u32, started_secs: Option<u64>) -> Option<ProcInstant> {
started_secs.map(ProcInstant)
}
#[cfg(any(test, target_os = "linux"))]
fn parse_start_ticks(stat: &str) -> Option<u64> {
let (_, after_comm) = stat.rsplit_once(')')?;
after_comm.split_ascii_whitespace().nth(19)?.parse().ok()
}
#[cfg(any(test, target_os = "linux"))]
fn ticks_at(secs: u64, nanos: u64, hz: u64) -> Option<u64> {
secs.checked_mul(hz)?
.checked_add(nanos.checked_mul(hz)? / 1_000_000_000)
}
#[cfg(target_os = "linux")]
mod linux {
use nix::time::{ClockId, clock_gettime};
use nix::unistd::{SysconfVar, sysconf};
pub(super) fn ticks_per_second() -> Option<u64> {
let hz = sysconf(SysconfVar::CLK_TCK).ok()??;
u64::try_from(hz).ok().filter(|&hz| hz > 0)
}
pub(super) fn ticks_now() -> Option<u64> {
let hz = ticks_per_second()?;
let now = clock_gettime(ClockId::CLOCK_BOOTTIME).ok()?;
super::ticks_at(
u64::try_from(now.tv_sec()).ok()?,
u64::try_from(now.tv_nsec()).ok()?,
hz,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stat_line(comm: &str) -> String {
format!(
"1234 ({comm}) S 1 1234 1234 0 -1 4194560 100 0 0 0 0 0 0 0 20 0 1 0 98765 \
5636096 200 18446744073709551615"
)
}
#[test]
fn the_start_is_field_twenty_two_of_a_stat_line() {
assert_eq!(parse_start_ticks(&stat_line("sleep")), Some(98765));
}
#[test]
fn a_comm_holding_parens_and_spaces_does_not_shift_the_fields() {
assert_eq!(parse_start_ticks(&stat_line("a) (b")), Some(98765));
assert_eq!(parse_start_ticks(&stat_line("x) 1 2 3 (y")), Some(98765));
}
#[test]
fn a_stat_line_that_is_cut_short_or_garbled_has_no_start() {
assert_eq!(parse_start_ticks(""), None);
assert_eq!(parse_start_ticks("1234 sleep S 1 2 3"), None, "no `)`");
assert_eq!(parse_start_ticks("1234 (sleep) S 1 1234"), None);
let garbled = stat_line("sleep").replace(" 98765 ", " 98x65 ");
assert_eq!(parse_start_ticks(&garbled), None);
}
#[test]
fn a_clock_reading_floors_to_the_tick() {
assert_eq!(ticks_at(5, 0, 100), Some(500));
assert_eq!(ticks_at(5, 9_999_999, 100), Some(500));
assert_eq!(ticks_at(5, 10_000_000, 100), Some(501));
assert_eq!(ticks_at(5, 999_999_999, 100), Some(599));
assert_eq!(ticks_at(u64::MAX, 0, 100), None);
}
#[test]
fn the_earliest_start_after_a_boot_allows_the_floored_seconds_slack() {
assert_eq!(
ProcInstant::after_boot(1_000).raw(),
1_000 - BOOT_SLACK_SECS
);
assert_eq!(ProcInstant::after_boot(1).raw(), 0);
}
#[cfg(unix)]
mod unix {
use std::process::Command;
use super::*;
struct Child(std::process::Child);
impl Child {
fn sleeping() -> Self {
let child = Command::new("/bin/sh")
.arg("-c")
.arg("sleep 30")
.spawn()
.expect("/bin/sh is present on every platform this module compiles for");
Self(child)
}
}
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[test]
fn a_pid_the_table_does_not_know_is_absent() {
assert!(read_pids(&[0]).is_empty());
}
#[test]
fn the_refresh_kind_asks_for_nothing_the_start_time_does_not_need() {
let kind = refresh_kind();
assert!(!kind.memory(), "the start time is not a memory reading");
assert!(!kind.cpu(), "the start time is not a CPU reading");
assert!(!kind.tasks(), "nothing here reads a thread");
}
#[test]
fn a_running_child_reads_as_live_with_a_start_time() {
let child = Child::sleeping();
let pid = child.0.id();
let readings = read_pids(&[pid]);
let reading = readings.get(&pid).expect("a running child is in the table");
assert!(!reading.zombie, "{reading:?}");
assert!(reading.started_secs.is_some(), "{reading:?}");
assert_eq!(readings.len(), 1, "only the named pid is read");
}
#[test]
fn a_fresh_childs_start_lies_between_the_clock_before_and_after_it() {
let before = ProcInstant::now();
let child = Child::sleeping();
let readings = read_pids(&[child.0.id()]);
let after = ProcInstant::now();
let started = readings
.get(&child.0.id())
.and_then(|reading| reading.started)
.expect("a running child has a start");
assert!(
before <= started && started <= after,
"{before:?} <= {started:?} <= {after:?}"
);
}
#[test]
fn the_earliest_start_is_no_later_than_a_running_childs() {
let child = Child::sleeping();
let started = read_pids(&[child.0.id()])
.get(&child.0.id())
.and_then(|reading| reading.started)
.expect("a running child has a start");
assert!(ProcInstant::earliest_start() <= started);
}
}
#[cfg(target_os = "linux")]
mod linux {
use super::super::linux::ticks_per_second;
use super::*;
#[test]
fn a_fresh_childs_start_is_within_a_second_of_now_in_ticks() {
let hz = ticks_per_second().expect("every Linux has a USER_HZ");
let mut child = std::process::Command::new("/bin/sh")
.arg("-c")
.arg("sleep 30")
.spawn()
.expect("/bin/sh is present on Linux");
let pid = child.id();
let started = read_pids(&[pid]).get(&pid).and_then(|r| r.started);
let now = ProcInstant::now();
let _ = child.kill();
let _ = child.wait();
let started = started.expect("a running child has a start").raw();
assert!(
now.raw().saturating_sub(hz) <= started && started <= now.raw(),
"start {started} ticks against now {now:?} at {hz} Hz"
);
}
}
}