git clone https://garage44.eu/jeroen/midas.git.. /src/procs.rs
//! The processes on this machine, on Linux (from `/proc`) and on macOS (from
//! `ps`), for the node's handover, its count of open ssh sessions, and the
//! stall watch on a command (`node::watch`).
pub struct Proc {
pub pid: u32,
pub ppid: u32,
pub uid: u32,
/// Its process group: a command and everything it started, even what was
/// orphaned to init on the way, unless that left the group on purpose.
pub pgid: u32,
/// CPU time used so far, user and system, in milliseconds.
pub cpu_ms: u64,
/// The full command line, arguments joined by spaces.
pub cmd: String,
}
#[cfg(target_os = "linux")]
pub fn all() -> Vec<Proc> {
use std::fs;
// SAFETY: sysconf has no preconditions.
let tick = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }.max(1) as u64;
let mut out = Vec::new();
let Ok(rd) = fs::read_dir("/proc") else { return out };
for e in rd.flatten() {
let Ok(pid) = e.file_name().to_string_lossy().parse::<u32>() else { continue };
let Ok(status) = fs::read_to_string(format!("/proc/{pid}/status")) else { continue };
let field = |k: &str| status.lines().find_map(|l| l.strip_prefix(k).and_then(|v| v.split_whitespace().next()?.parse::<u32>().ok()));
let cmd = fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default()
.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).to_string())
.collect::<Vec<_>>().join(" ");
let (pgid, ticks) = fs::read_to_string(format!("/proc/{pid}/stat")).ok().and_then(|s| stat_fields(&s)).unwrap_or((0, 0));
out.push(Proc {
pid, ppid: field("PPid:").unwrap_or(0), uid: field("Uid:").unwrap_or(u32::MAX),
pgid, cpu_ms: ticks * 1000 / tick, cmd,
});
}
out
}
/// `/proc/<pid>/stat`'s process group and CPU ticks (utime + stime). The
/// fields are counted after the command's closing parenthesis, since the
/// command itself may hold spaces and parentheses.
#[cfg(any(target_os = "linux", test))]
fn stat_fields(stat: &str) -> Option<(u32, u64)> {
let rest = &stat[stat.rfind(')')? + 1..];
let f: Vec<&str> = rest.split_whitespace().collect();
// After the command: state(0) ppid(1) pgrp(2) … utime(11) stime(12).
Some((f.get(2)?.parse().ok()?, f.get(11)?.parse::<u64>().ok()? + f.get(12)?.parse::<u64>().ok()?))
}
#[cfg(not(target_os = "linux"))]
pub fn all() -> Vec<Proc> {
let Ok(out) = std::process::Command::new("ps").args(["-axo", "pid=,ppid=,uid=,pgid=,time=,command="]).output() else {
return vec![];
};
String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| {
let mut w = l.split_whitespace();
let (pid, ppid, uid, pgid) = (w.next()?.parse().ok()?, w.next()?.parse().ok()?, w.next()?.parse().ok()?, w.next()?.parse().ok()?);
let cpu_ms = cpu_time_ms(w.next()?).unwrap_or(0);
Some(Proc { pid, ppid, uid, pgid, cpu_ms, cmd: w.collect::<Vec<_>>().join(" ") })
}).collect()
}
/// `ps`'s `time`, `[[dd-]hh:]mm:ss[.cc]` (macOS: `2369:57.86`, minutes past
/// sixty), in milliseconds.
#[cfg(any(not(target_os = "linux"), test))]
fn cpu_time_ms(t: &str) -> Option<u64> {
let (days, clock) = match t.split_once('-') {
Some((d, c)) => (d.parse::<u64>().ok()?, c),
None => (0, t),
};
let mut parts: Vec<&str> = clock.split(':').collect();
let secs: f64 = parts.pop()?.parse().ok()?;
let mut whole = 0u64;
for p in parts {
whole = whole * 60 + p.parse::<u64>().ok()?;
}
Some(((days * 86400 + whole * 60) as f64 * 1000.0 + secs * 1000.0).round() as u64)
}
/// The CPU time, in milliseconds, used so far by the processes in group
/// `pgid`, but not by `except` (the watcher itself, should it be in it).
pub fn group_cpu_ms(all: &[Proc], pgid: u32, except: u32) -> u64 {
all.iter().filter(|p| p.pgid == pgid && p.pid != except).map(|p| p.cpu_ms).sum()
}
/// This process and its ancestors.
pub fn ancestry(all: &[Proc]) -> std::collections::HashSet<u32> {
let mut seen = std::collections::HashSet::new();
let mut pid = std::process::id();
while pid > 1 && seen.insert(pid) {
pid = all.iter().find(|p| p.pid == pid).map(|p| p.ppid).unwrap_or(1);
}
seen
}
/// Open ssh sessions for `user`: what runs under sshd's per-connection
/// process, `sshd: build@…` (or `sshd-session: build@…` in newer OpenSSH), not
/// its privileged half. Its children, not the process itself: an agent's ssh
/// keeps its connection open for later commands (`ControlPersist`), and such a
/// connection with nothing running in it is not a session — counted, it kept
/// an idle node from going back to the pool. One connection carries several
/// sessions at once, each its own child.
pub fn ssh_sessions(all: &[Proc], user: &str) -> usize {
let a = format!("sshd: {user}@");
let b = format!("sshd-session: {user}@");
let conns: std::collections::HashSet<u32> = all.iter()
.filter(|p| (p.cmd.starts_with(&a) || p.cmd.starts_with(&b)) && !p.cmd.contains("[priv]"))
.map(|p| p.pid).collect();
all.iter().filter(|p| conns.contains(&p.ppid)).count()
}
#[cfg(test)]
mod tests {
use super::*;
fn p(pid: u32, ppid: u32, cmd: &str) -> Proc {
Proc { pid, ppid, uid: 1000, pgid: pid, cpu_ms: 0, cmd: cmd.into() }
}
#[test]
fn cpu_time_reads_both_platforms_forms() {
assert_eq!(cpu_time_ms("0:00.01"), Some(10));
assert_eq!(cpu_time_ms("2369:57.86"), Some(142_197_860)); // mac-2's configd
assert_eq!(cpu_time_ms("01:02:03"), Some(3_723_000));
assert_eq!(cpu_time_ms("1-00:00:01"), Some(86_401_000));
assert_eq!(cpu_time_ms("bad"), None);
// A command whose name has a space and a parenthesis in it.
let stat = "37664 (qemu (x) y) S 1 37603 37603 0 -1 4194560 1 0 0 0 1234 66 0 0 20 0";
assert_eq!(stat_fields(stat), Some((37603, 1300)));
}
#[test]
fn a_kept_open_connection_with_nothing_in_it_is_no_session() {
let idle = vec![p(10, 1, "sshd-session: build [priv]"), p(11, 10, "sshd-session: build@notty")];
assert_eq!(ssh_sessions(&idle, "build"), 0);
let mut busy = idle;
busy.push(p(12, 11, "/usr/local/bin/midas node session"));
busy.push(p(13, 11, "/usr/local/bin/midas node session"));
busy.push(p(14, 12, "cargo test"));
busy.push(p(20, 1, "sshd: build@notty"));
busy.push(p(21, 20, "/usr/local/bin/midas node session"));
assert_eq!(ssh_sessions(&busy, "build"), 3);
}
}