ultron-kernel 1.0.0

Supervisor for Ultron's persistent Python kernel (runtime.py): process, wire protocol, host requests
Documentation
//! Linux process inspection and the kernel's process-tree kill (tree-memory.ts `killProcessTree`, `descendantPids`).

use rustix::process::{Pid, Signal, kill_process, kill_process_group};
use std::collections::HashMap;
use std::time::Duration;

pub(crate) struct ProcStat {
    pub state: String,
    pub ppid: i32,
    /// Start time in clock ticks since boot: tells a live process apart from a later one reusing its pid.
    pub start_time: u64,
}

/// Fields after the parenthesized command name of /proc/<pid>/stat: state(3), ppid(4), ...
fn stat_fields(pid: i32) -> Option<Vec<String>> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let rest = stat.get(stat.rfind(')')? + 2..)?;
    Some(rest.split(' ').map(str::to_string).collect())
}

/// Parent, state and start time of one process (`processStat`), or none when it is gone.
pub(crate) fn process_stat(pid: i32) -> Option<ProcStat> {
    let fields = stat_fields(pid)?;
    Some(ProcStat {
        state: fields.first()?.clone(),
        ppid: fields.get(1)?.parse().ok()?,
        start_time: fields.get(19)?.parse().ok()?,
    })
}

/// CPU seconds (user + system) of one Linux process, or None when unavailable.
pub(crate) fn process_cpu_seconds(pid: i32) -> Option<f64> {
    let fields = stat_fields(pid)?;
    let user: f64 = fields.get(11)?.parse().ok()?;
    let system: f64 = fields.get(12)?.parse().ok()?;
    Some((user + system) / 100.0)
}

/// Live descendants of `root`, breadth first (zombies are skipped: they cannot be signalled).
pub(crate) fn descendant_pids(root: i32) -> Vec<i32> {
    let Ok(entries) = std::fs::read_dir("/proc") else {
        return Vec::new();
    };
    let mut children: HashMap<i32, Vec<i32>> = HashMap::new();
    for entry in entries.flatten() {
        let Some(pid) = entry.file_name().to_str().and_then(|name| name.parse::<i32>().ok()) else {
            continue;
        };
        let Some(stat) = process_stat(pid) else {
            continue;
        };
        if stat.state == "Z" || stat.state == "X" {
            continue;
        }
        children.entry(stat.ppid).or_default().push(pid);
    }
    let mut result = Vec::new();
    let mut queue = std::collections::VecDeque::from([root]);
    while let Some(parent) = queue.pop_front() {
        for &child in children.get(&parent).map(Vec::as_slice).unwrap_or_default() {
            result.push(child);
            queue.push_back(child);
        }
    }
    result
}

/// The process group a host may signal for a command it started in a group of its own: `pgid` itself, when it is
/// a real positive group id (never 0, -1 or another negative value, never init's 1) and neither this process's pid
/// nor this process's own group. Pure, so the guard is tested without sending any signal.
fn command_group_target(pgid: i32, own_pid: i32, own_group: i32) -> Option<Pid> {
    if pgid <= 1 || pgid == own_pid || pgid == own_group {
        return None;
    }
    Pid::from_raw(pgid)
}

/// The process a host may signal: a positive pid other than init and this process (pure, as above).
pub(crate) fn process_target(pid: i32, own_pid: i32) -> Option<Pid> {
    if pid <= 1 || pid == own_pid {
        return None;
    }
    Pid::from_raw(pid)
}

/// SIGKILLs the process group the host created for one command (its leader's `pgid`), through
/// [`command_group_target`]; whether a signal was sent.
pub fn kill_command_group(pgid: i32) -> bool {
    let own_pid = rustix::process::getpid().as_raw_nonzero().get();
    let own_group = rustix::process::getpgrp().as_raw_nonzero().get();
    match command_group_target(pgid, own_pid, own_group) {
        Some(group) => kill_process_group(group, Signal::KILL).is_ok(),
        None => false,
    }
}

fn signal(pid: i32, signal: Signal) {
    let own = rustix::process::getpid().as_raw_nonzero().get();
    if let Some(pid) = process_target(pid, own) {
        let _ = kill_process(pid, signal);
    }
}

/// What else a tree kill reaches (`KillTreeOptions` of tree-memory.ts).
#[derive(Default)]
pub(crate) struct KillExtras<'a> {
    /// Processes seen in the tree earlier (pid to start time), killed when still the same process.
    pub known: Option<&'a HashMap<i32, u64>>,
    /// The kernel's cgroup scope: every process still in it is killed.
    pub cgroup_dir: Option<&'a std::path::Path>,
}

/// SIGKILLs `root` and every process in its tree. The root is stopped first so it can neither start new processes
/// nor exit while its descendants are killed; as a child subreaper it adopts their orphans, which later sweeps kill.
/// `root_alive`: the root is still the host's unreaped child, so its pid cannot belong to another process. Processes
/// seen in earlier watchdog scans and the members of the kernel's scope are killed too.
pub(crate) fn kill_process_tree(root: i32, owns_process_group: bool, root_alive: bool, extras: KillExtras<'_>) {
    if root_alive {
        signal(root, Signal::STOP);
        for sweep in 0..20 {
            let pids = descendant_pids(root);
            if pids.is_empty() {
                break;
            }
            for pid in pids {
                signal(pid, Signal::KILL);
            }
            std::thread::sleep(Duration::from_millis(if sweep < 5 { 2 } else { 10 }));
        }
    }
    if owns_process_group {
        kill_command_group(root);
    }
    if root_alive {
        signal(root, Signal::KILL);
    }
    for (&pid, &start_time) in extras.known.into_iter().flatten() {
        if process_stat(pid).is_some_and(|stat| stat.start_time == start_time && stat.state != "Z") {
            signal(pid, Signal::KILL);
        }
    }
    // Only a scope of the kernel's own: never the host's cgroup or an ancestor of it (see `is_foreign_scope`).
    if let Some(dir) = extras
        .cgroup_dir
        .filter(|dir| crate::tree_memory::is_foreign_scope(dir))
    {
        let own = std::process::id() as i32;
        for pid in crate::tree_memory::cgroup_pids(dir) {
            if pid != own {
                signal(pid, Signal::KILL);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::command_group_target;

    /// The process-group kill guard, tested as a pure function only: no signal is ever sent here.
    #[test]
    fn kernel_w16f_only_a_real_command_group_other_than_the_hosts_own_may_be_signalled() {
        let (own_pid, own_group) = (4242, 4000);
        for refused in [0, -1, -4242, 1, own_pid, own_group, i32::MIN] {
            assert_eq!(command_group_target(refused, own_pid, own_group), None, "{refused}");
        }
        for allowed in [2, 4001, 4243, i32::MAX] {
            assert_eq!(
                command_group_target(allowed, own_pid, own_group).map(|pid| pid.as_raw_nonzero().get()),
                Some(allowed)
            );
        }
    }
}