schedr_agent/usage.rs
1//! What a spawned process used, read from its zombie before it is reaped (decision 18A, see
2//! archive/PROJECT.md, How Python tasks are started: the fork server).
3//!
4//! The workspace forbids `unsafe`, and no safe call returns a child's `rusage`; but between
5//! its exit and its reaping a process is a zombie whose `/proc/<pid>/stat` still holds its
6//! CPU time (with the children it reaped) and its faults. Its memory is gone, so the peak RSS
7//! isn't known, and its `status` has its leader thread's context switches only, so those
8//! aren't reported either. The agent waits for the exit without reaping (`waitid` with
9//! `WNOWAIT`), reads them, then reaps. A forked process's usage comes from its shim instead
10//! (the parent's `rusage`, all of it).
11
12use std::io;
13use std::path::Path;
14
15use rustix::process::{Pid, WaitId, WaitIdOptions, waitid};
16use schedr_model::runner::ProcessUsage;
17
18#[cfg(test)]
19mod tests;
20
21/// How a process ended, besides its exit status: what it used and whether it dumped core.
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
23pub struct Ended {
24 /// What it used; `None` if it couldn't be read.
25 pub usage: Option<ProcessUsage>,
26 /// Whether it dumped core.
27 pub core_dumped: bool,
28}
29
30/// The usage of zombie `pid` from `proc_root` (`/proc`): CPU time with its reaped children's,
31/// in microseconds of `ticks` per second, and major faults (its own and its reaped
32/// children's); no peak RSS and no context switches. `None` if it can't be read or isn't a zombie (a process
33/// still running would give a partial answer).
34#[must_use]
35pub fn zombie_usage(proc_root: &Path, pid: i32, ticks: u64) -> Option<ProcessUsage> {
36 let dir = proc_root.join(pid.to_string());
37 let stat = std::fs::read_to_string(dir.join("stat")).ok()?;
38 let fields: Vec<&str> = stat[stat.rfind(')')? + 1..].split_whitespace().collect();
39 // After the command: field 3 (state) is [0], so field n is [n - 3].
40 if *fields.first()? != "Z" {
41 return None;
42 }
43 let field = |n: usize| fields.get(n - 3)?.parse::<u64>().ok();
44 let micros = |t: u64| t.saturating_mul(1_000_000) / ticks.max(1);
45 Some(ProcessUsage {
46 user_cpu_micros: micros(field(14)? + field(16)?),
47 system_cpu_micros: micros(field(15)? + field(17)?),
48 peak_rss_bytes: None,
49 major_faults: field(12)? + field(13)?,
50 // Not the context switches: a zombie's `status` has its leader thread's only, not
51 // its other threads' or its reaped children's (`rusage` has them; no safe call
52 // returns a child's).
53 voluntary_context_switches: None,
54 involuntary_context_switches: None,
55 })
56}
57
58/// Waits until child `pid` has exited, without reaping it (`waitid` with `WNOWAIT`, on the
59/// blocking pool: one parked thread per running process), so its zombie can be read first.
60///
61/// # Errors
62///
63/// The operating system's error (e.g. `ECHILD` for a process that isn't an unreaped child).
64pub async fn exited(pid: Pid) -> io::Result<()> {
65 tokio::task::spawn_blocking(move || {
66 let options = WaitIdOptions::EXITED | WaitIdOptions::NOWAIT;
67 loop {
68 match waitid(WaitId::Pid(pid), options) {
69 Ok(_) => return Ok(()),
70 Err(rustix::io::Errno::INTR) => {}
71 Err(error) => return Err(io::Error::from(error)),
72 }
73 }
74 })
75 .await
76 .map_err(io::Error::other)?
77}
78
79/// The clock ticks per second of `/proc`'s times.
80#[must_use]
81pub fn clock_ticks() -> u64 {
82 rustix::param::clock_ticks_per_second()
83}