use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::Instant;
use crate::proc_table::read_pids;
fn wall_clock_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since_epoch| since_epoch.as_secs())
}
fn start_epoch_secs(pid: u32) -> Option<u64> {
read_pids(&[pid]).get(&pid)?.started_secs
}
fn age_from_epoch(started_secs: u64, now_secs: u64) -> Duration {
Duration::from_secs(now_secs.saturating_sub(started_secs))
}
#[must_use]
pub(crate) fn started_at_of(pid: u32) -> Instant {
let now = Instant::now();
let Some(started_secs) = start_epoch_secs(pid) else {
return now;
};
let age = age_from_epoch(started_secs, wall_clock_secs());
now.checked_sub(age).unwrap_or(now)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_age_is_the_gap_between_the_two_readings() {
assert_eq!(age_from_epoch(100, 400), Duration::from_secs(300));
}
#[test]
fn a_clock_that_moved_backwards_gives_an_age_of_zero() {
assert_eq!(age_from_epoch(400, 100), Duration::ZERO);
}
#[test]
fn a_process_that_started_this_second_has_no_age_yet() {
assert_eq!(age_from_epoch(1_700_000_000, 1_700_000_000), Duration::ZERO);
}
#[test]
fn a_pid_the_table_does_not_know_reads_as_unknown() {
assert_eq!(start_epoch_secs(0), None);
}
mod slow {
use std::process::Command;
use super::*;
const ALIVE_FOR: Duration = Duration::from_secs(3);
const AT_LEAST: Duration = Duration::from_secs(2);
const AT_MOST: Duration = Duration::from_secs(3_600);
#[test]
fn an_adopted_child_that_has_been_alive_for_seconds_is_that_old() {
let mut child = Command::new("/bin/sh")
.arg("-c")
.arg("sleep 30")
.spawn()
.expect("/bin/sh is present on every platform this module compiles for");
let pid = child.id();
std::thread::sleep(ALIVE_FOR);
let derived = started_at_of(pid);
let uptime = Instant::now().saturating_duration_since(derived);
let _ = child.kill();
let _ = child.wait();
assert!(
uptime >= AT_LEAST,
"a child alive for {ALIVE_FOR:?} derived an uptime of {uptime:?}; \
a `started_at` stamped at the handover reads as ~0 here"
);
assert!(
uptime <= AT_MOST,
"a child alive for {ALIVE_FOR:?} derived an uptime of {uptime:?}, \
which is not an age but an arithmetic error"
);
}
}
}