Skip to main content

optimization_job_api/
process.rs

1//! Shell-free process groups and bounded I/O, extracted/adapted from route_agent.
2use std::{
3    io::{self, Read, Write},
4    process::{Child, Command, ExitStatus, Stdio},
5    thread,
6    time::{Duration, Instant},
7};
8/// Puts the command in a process group of its own, so that
9/// [`terminate_process_group`] also reaches its descendants.
10pub fn group(command: &mut Command) {
11    #[cfg(unix)]
12    {
13        use std::os::unix::process::CommandExt;
14        command.process_group(0);
15    }
16}
17/// Kills the child's process group with SIGKILL, then the child itself.
18pub fn terminate_process_group(child: &mut Child) {
19    #[cfg(unix)]
20    {
21        if let Ok(pid) = i32::try_from(child.id()) {
22            unsafe {
23                libc::kill(-pid, libc::SIGKILL);
24            }
25        }
26    }
27    let _ = child.kill();
28}
29/// Keep draining beyond the limit to avoid pipe deadlocks; never retain excess bytes.
30pub fn drain(mut reader: impl Read, maximum: usize) -> io::Result<(Vec<u8>, bool)> {
31    let mut out = Vec::new();
32    let mut overflow = false;
33    let mut buf = [0u8; 8192];
34    loop {
35        let n = reader.read(&mut buf)?;
36        if n == 0 {
37            break;
38        }
39        let keep = n.min(maximum.saturating_sub(out.len()));
40        out.extend_from_slice(&buf[..keep]);
41        overflow |= keep < n;
42    }
43    Ok((out, overflow))
44}
45/// Runs `argv` without a shell in its own process group, writes `input` to its
46/// standard input, and returns its exit status, standard output and standard
47/// error. Fails with `TimedOut` after `timeout`, and when either stream
48/// exceeds `maximum` bytes. The group is killed when the command ends.
49pub fn bounded_command(
50    argv: &[String],
51    input: Vec<u8>,
52    timeout: Duration,
53    maximum: usize,
54) -> io::Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
55    bounded_command_until(argv, input, timeout, maximum, &|| false)
56}
57/// [`bounded_command`] that also stops the command's process group, with an
58/// `Interrupted` error, as soon as `abort` returns true. The command runs in
59/// its own group, so a terminal's SIGINT to the caller does not reach it.
60pub fn bounded_command_until(
61    argv: &[String],
62    input: Vec<u8>,
63    timeout: Duration,
64    maximum: usize,
65    abort: &dyn Fn() -> bool,
66) -> io::Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
67    let exe = argv.first().ok_or_else(|| io::Error::other("empty argv"))?;
68    let mut command = Command::new(exe);
69    command
70        .args(&argv[1..])
71        .stdin(Stdio::piped())
72        .stdout(Stdio::piped())
73        .stderr(Stdio::piped());
74    group(&mut command);
75    let mut child = command.spawn()?;
76    let mut stdin = child.stdin.take().unwrap();
77    let writer = thread::spawn(move || stdin.write_all(&input));
78    let stdout = child.stdout.take().unwrap();
79    let stderr = child.stderr.take().unwrap();
80    let a = thread::spawn(move || drain(stdout, maximum));
81    let b = thread::spawn(move || drain(stderr, maximum));
82    let start = Instant::now();
83    let mut aborted = false;
84    let finished = loop {
85        if exited(&mut child)? {
86            break true;
87        }
88        if abort() {
89            aborted = true;
90            break false;
91        }
92        if start.elapsed() >= timeout {
93            break false;
94        }
95        thread::sleep(Duration::from_millis(10));
96    };
97    // A parent may exit leaving descendants holding the pipes. Clean the group
98    // even on success before joining bounded pipe readers. The exited leader
99    // is not reaped yet, so its PID, which names the group, cannot have been
100    // reused by another process group.
101    terminate_process_group(&mut child);
102    let status = child.wait();
103    let write_result = writer
104        .join()
105        .map_err(|_| io::Error::other("stdin thread panicked"))?;
106    let (out, oa) = a
107        .join()
108        .map_err(|_| io::Error::other("stdout thread panicked"))??;
109    let (err, ob) = b
110        .join()
111        .map_err(|_| io::Error::other("stderr thread panicked"))??;
112    if aborted {
113        return Err(io::Error::new(
114            io::ErrorKind::Interrupted,
115            "command interrupted",
116        ));
117    }
118    let status = finished
119        .then_some(status?)
120        .ok_or_else(|| io::Error::new(io::ErrorKind::TimedOut, "command deadline exceeded"))?;
121    write_result?;
122    if oa || ob {
123        return Err(io::Error::other("command stream exceeds configured cap"));
124    }
125    Ok((status, out, err))
126}
127/// True once the child has exited, without reaping it: while the child is a
128/// zombie, its PID cannot be reused.
129#[cfg(target_os = "linux")]
130fn exited(child: &mut Child) -> io::Result<bool> {
131    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
132    let rc = unsafe {
133        libc::waitid(
134            libc::P_PID,
135            child.id() as libc::id_t,
136            &mut info,
137            libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
138        )
139    };
140    if rc < 0 {
141        return Err(io::Error::last_os_error());
142    }
143    Ok(unsafe { info.si_pid() } != 0)
144}
145#[cfg(not(target_os = "linux"))]
146fn exited(child: &mut Child) -> io::Result<bool> {
147    Ok(child.try_wait()?.is_some())
148}
149/// Bounded on-disk diagnostics, with pipes drained after cap is reached.
150pub fn drain_file(
151    mut reader: impl Read,
152    mut file: std::fs::File,
153    maximum: usize,
154) -> io::Result<()> {
155    let mut kept = 0;
156    let mut buf = [0u8; 8192];
157    loop {
158        let n = reader.read(&mut buf)?;
159        if n == 0 {
160            break;
161        }
162        let k = n.min(maximum.saturating_sub(kept));
163        file.write_all(&buf[..k])?;
164        kept += k;
165    }
166    file.sync_data()
167}
168/// Check Linux process-group membership, counting zombies as already stopped.
169/// Returns an error when liveness cannot be established. Escaped sessions are
170/// outside the foreground backend's contract; use systemd for containment.
171#[cfg(target_os = "linux")]
172pub fn group_stopped(pgid: u32) -> io::Result<bool> {
173    // kill(0) uses the caller's PID namespace and avoids unrelated /proc access.
174    let rc = unsafe { libc::kill(-(pgid as i32), 0) };
175    if rc < 0 {
176        let e = io::Error::last_os_error();
177        return if e.raw_os_error() == Some(libc::ESRCH) {
178            Ok(true)
179        } else {
180            Err(e)
181        };
182    }
183    let namespace = std::fs::read_link("/proc/self/ns/pid")?;
184    let own_status = std::fs::read_to_string("/proc/self/status")?;
185    let depth = own_status
186        .lines()
187        .find_map(|l| l.strip_prefix("NSpgid:"))
188        .ok_or_else(|| io::Error::other("NSpgid unavailable"))?
189        .split_whitespace()
190        .count();
191    for entry in std::fs::read_dir("/proc")? {
192        let entry = entry?;
193        if entry.file_name().to_string_lossy().parse::<u32>().is_err() {
194            continue;
195        }
196        // A process that exits during the scan is gone, not unknown.
197        let vanished = |e: &io::Error| {
198            e.kind() == io::ErrorKind::NotFound || e.raw_os_error() == Some(libc::ESRCH)
199        };
200        let status = match std::fs::read_to_string(entry.path().join("status")) {
201            Ok(s) => s,
202            Err(e) if vanished(&e) => continue,
203            Err(e) => return Err(e),
204        };
205        let groups: Vec<_> = status
206            .lines()
207            .find_map(|l| l.strip_prefix("NSpgid:"))
208            .unwrap_or("")
209            .split_whitespace()
210            .collect();
211        if groups.len() != depth || groups.last().and_then(|s| s.parse::<u32>().ok()) != Some(pgid)
212        {
213            continue;
214        }
215        let other = match std::fs::read_link(entry.path().join("ns/pid")) {
216            Ok(n) => n,
217            Err(e) if vanished(&e) => continue,
218            Err(e) => return Err(e),
219        };
220        if other != namespace {
221            continue;
222        }
223        let state = status
224            .lines()
225            .find_map(|l| l.strip_prefix("State:"))
226            .and_then(|s| s.split_whitespace().next());
227        if state.is_none() {
228            return Err(io::Error::other("process state unavailable"));
229        }
230        if !matches!(state, Some("Z" | "X")) {
231            return Ok(false);
232        }
233    }
234    Ok(true)
235}
236#[cfg(not(target_os = "linux"))]
237pub fn group_stopped(_: u32) -> io::Result<bool> {
238    Err(io::Error::other("Linux process verification required"))
239}