Skip to main content

aidaemon_tools/
process_control.rs

1use std::time::Duration;
2
3/// Configure commands to run in their own process group (Unix).
4/// This allows terminating the full process tree on cancel/timeout.
5#[cfg(unix)]
6pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
7    // SAFETY: pre_exec runs in the child process after fork and before exec.
8    // We only call the async-signal-safe setpgid syscall.
9    unsafe {
10        command.pre_exec(|| {
11            if libc::setpgid(0, 0) != 0 {
12                return Err(std::io::Error::last_os_error());
13            }
14            Ok(())
15        });
16    }
17}
18
19#[cfg(not(unix))]
20pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
21    let _ = command;
22}
23
24#[cfg(unix)]
25fn send_signal_to_process_group_or_pid(pid: u32, signal: i32) -> bool {
26    if pid == 0 {
27        return false;
28    }
29    let raw_pid = pid as libc::pid_t;
30    // Prefer signalling the process group (negative pid), fallback to direct pid.
31    let group_ok = unsafe { libc::kill(-raw_pid, signal) == 0 };
32    if group_ok {
33        return true;
34    }
35    unsafe { libc::kill(raw_pid, signal) == 0 }
36}
37
38/// Send SIGTERM to a process group (or fallback process pid).
39#[cfg(unix)]
40pub fn send_sigterm(pid: u32) -> bool {
41    send_signal_to_process_group_or_pid(pid, libc::SIGTERM)
42}
43
44/// Send SIGKILL to a process group (or fallback process pid).
45#[cfg(unix)]
46pub fn send_sigkill(pid: u32) -> bool {
47    send_signal_to_process_group_or_pid(pid, libc::SIGKILL)
48}
49
50/// Windows has no signals: ask the process tree to close (`taskkill /T`).
51#[cfg(not(unix))]
52pub fn send_sigterm(pid: u32) -> bool {
53    taskkill(pid, false)
54}
55
56/// End the process tree at once (`taskkill /T /F`).
57#[cfg(not(unix))]
58pub fn send_sigkill(pid: u32) -> bool {
59    taskkill(pid, true)
60}
61
62#[cfg(not(unix))]
63fn taskkill(pid: u32, force: bool) -> bool {
64    if pid == 0 {
65        return false;
66    }
67    let mut command = std::process::Command::new("taskkill");
68    command.args(["/PID", &pid.to_string(), "/T"]);
69    if force {
70        command.arg("/F");
71    }
72    command
73        .stdout(std::process::Stdio::null())
74        .stderr(std::process::Stdio::null())
75        .status()
76        .is_ok_and(|status| status.success())
77}
78
79/// Best-effort process tree termination with TERM->KILL escalation.
80pub async fn terminate_process_tree(pid: u32, child: &mut tokio::process::Child, grace: Duration) {
81    #[cfg(unix)]
82    {
83        if !send_sigterm(pid) {
84            let _ = child.start_kill();
85        }
86
87        let exited = tokio::time::timeout(grace, child.wait()).await;
88        if exited.is_err() {
89            let _ = send_sigkill(pid);
90            let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
91        }
92    }
93
94    #[cfg(not(unix))]
95    {
96        // The whole tree, as on Unix: a shell's children too.
97        if !send_sigterm(pid) {
98            let _ = child.start_kill();
99        }
100        if tokio::time::timeout(grace, child.wait()).await.is_err() {
101            if !send_sigkill(pid) {
102                let _ = child.start_kill();
103            }
104            let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
105        }
106    }
107}
108
109/// Win32 job-object FFI: the `winnt.h` layouts and the four `kernel32`
110/// calls this crate needs, declared here so no Windows bindings crate joins
111/// the dependency graph. Compiled for tests on every platform so the layout
112/// checks run in Unix CI too.
113#[cfg(any(windows, test))]
114#[allow(dead_code)] // FFI layouts: fields exist for their size and offset.
115mod win32_job {
116    /// `JOBOBJECT_BASIC_LIMIT_INFORMATION` (`winnt.h`).
117    #[repr(C)]
118    #[derive(Debug, Default, Clone, Copy)]
119    pub(super) struct JobObjectBasicLimitInformation {
120        pub per_process_user_time_limit: i64, // LARGE_INTEGER
121        pub per_job_user_time_limit: i64,     // LARGE_INTEGER
122        pub limit_flags: u32,                 // DWORD
123        pub minimum_working_set_size: usize,  // SIZE_T
124        pub maximum_working_set_size: usize,  // SIZE_T
125        pub active_process_limit: u32,        // DWORD
126        pub affinity: usize,                  // ULONG_PTR
127        pub priority_class: u32,              // DWORD
128        pub scheduling_class: u32,            // DWORD
129    }
130
131    /// `IO_COUNTERS` (`winnt.h`): six `ULONGLONG`s.
132    #[repr(C)]
133    #[derive(Debug, Default, Clone, Copy)]
134    pub(super) struct IoCounters {
135        pub read_operation_count: u64,
136        pub write_operation_count: u64,
137        pub other_operation_count: u64,
138        pub read_transfer_count: u64,
139        pub write_transfer_count: u64,
140        pub other_transfer_count: u64,
141    }
142
143    /// `JOBOBJECT_EXTENDED_LIMIT_INFORMATION` (`winnt.h`).
144    #[repr(C)]
145    #[derive(Debug, Default, Clone, Copy)]
146    pub(super) struct JobObjectExtendedLimitInformation {
147        pub basic_limit_information: JobObjectBasicLimitInformation,
148        pub io_info: IoCounters,
149        pub process_memory_limit: usize,     // SIZE_T
150        pub job_memory_limit: usize,         // SIZE_T
151        pub peak_process_memory_used: usize, // SIZE_T
152        pub peak_job_memory_used: usize,     // SIZE_T
153    }
154
155    /// `JobObjectExtendedLimitInformation` in `JOBOBJECTINFOCLASS`.
156    pub(super) const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS: i32 = 9;
157    /// Close of the job's last handle ends every process in it.
158    pub(super) const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;
159
160    #[cfg(windows)]
161    #[link(name = "kernel32")]
162    unsafe extern "system" {
163        pub(super) fn CreateJobObjectW(
164            job_attributes: *const std::ffi::c_void,
165            name: *const u16,
166        ) -> *mut std::ffi::c_void;
167        pub(super) fn SetInformationJobObject(
168            job: *mut std::ffi::c_void,
169            information_class: i32,
170            information: *const std::ffi::c_void,
171            information_length: u32,
172        ) -> i32;
173        pub(super) fn AssignProcessToJobObject(
174            job: *mut std::ffi::c_void,
175            process: *mut std::ffi::c_void,
176        ) -> i32;
177        pub(super) fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
178    }
179}
180
181/// A Win32 job object whose processes all end when its last handle closes
182/// (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`): on drop, or by the OS when the
183/// owning process exits or crashes. The handle is not inheritable, so a
184/// child never keeps its own job alive.
185#[cfg(windows)]
186pub struct JobObject {
187    handle: std::ptr::NonNull<std::ffi::c_void>,
188}
189
190// SAFETY: a job-object HANDLE is a kernel handle, valid from any thread;
191// the Win32 job calls are thread-safe and `Drop` closes it exactly once.
192#[cfg(windows)]
193unsafe impl Send for JobObject {}
194#[cfg(windows)]
195unsafe impl Sync for JobObject {}
196
197#[cfg(windows)]
198impl JobObject {
199    /// An anonymous job that ends its processes when it is closed.
200    pub fn kill_on_close() -> std::io::Result<Self> {
201        use win32_job::*;
202        // SAFETY: null attributes and name ask for an anonymous job with a
203        // non-inheritable handle; NULL is the only failure value.
204        let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
205        let handle = std::ptr::NonNull::new(raw).ok_or_else(std::io::Error::last_os_error)?;
206        // Owned from here: an early return closes it.
207        let job = Self { handle };
208        let mut info = JobObjectExtendedLimitInformation::default();
209        info.basic_limit_information.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
210        // SAFETY: `info` is the `winnt.h` layout for this class and lives
211        // across the call; the length is its exact size.
212        let ok = unsafe {
213            SetInformationJobObject(
214                job.handle.as_ptr(),
215                JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS,
216                (&raw const info).cast(),
217                std::mem::size_of::<JobObjectExtendedLimitInformation>() as u32,
218            )
219        };
220        if ok == 0 {
221            return Err(std::io::Error::last_os_error());
222        }
223        Ok(job)
224    }
225
226    /// Put a running child (and the processes it starts from now on) in
227    /// this job. A child already reaped has no handle left to assign.
228    pub fn assign(&self, child: &tokio::process::Child) -> std::io::Result<()> {
229        let Some(process) = child.raw_handle() else {
230            return Err(std::io::Error::other("child already reaped"));
231        };
232        // SAFETY: the job handle is live while `self` is, and `process` is
233        // live while `child` (borrowed for the call) holds it.
234        let ok = unsafe { win32_job::AssignProcessToJobObject(self.handle.as_ptr(), process) };
235        if ok == 0 {
236            return Err(std::io::Error::last_os_error());
237        }
238        Ok(())
239    }
240}
241
242#[cfg(windows)]
243impl Drop for JobObject {
244    fn drop(&mut self) {
245        // SAFETY: the handle came from CreateJobObjectW and is closed once.
246        unsafe {
247            win32_job::CloseHandle(self.handle.as_ptr());
248        }
249    }
250}
251
252/// The daemon-wide kill-on-close job, made on first use. It is never
253/// dropped: its handle closes only when the daemon process ends, however it
254/// ends, and Windows then ends every process in it. One job for the whole
255/// process (not one per spawn) because callers turn a `SpawnedProcess` into
256/// its bare `Child` and keep that for the run; a per-spawn job dropped there
257/// would end the child at once.
258#[cfg(windows)]
259fn daemon_job() -> Option<&'static JobObject> {
260    static JOB: std::sync::OnceLock<Option<JobObject>> = std::sync::OnceLock::new();
261    JOB.get_or_init(|| match JobObject::kill_on_close() {
262        Ok(job) => Some(job),
263        Err(error) => {
264            tracing::warn!(%error, "could not create the kill-on-close job object; spawned processes may outlive the daemon");
265            None
266        }
267    })
268    .as_ref()
269}
270
271/// Tie a freshly spawned child (and what it starts afterwards) to the
272/// daemon's life: on Windows it joins the daemon-wide kill-on-close job, so a
273/// killed or crashed daemon takes its process trees with it. Best effort: a
274/// failure (say, a parent job that forbids nesting) is logged and the child
275/// runs on. A no-op elsewhere, where process groups do this job.
276pub fn bind_child_to_daemon_lifetime(child: &tokio::process::Child) {
277    #[cfg(windows)]
278    {
279        let Some(job) = daemon_job() else {
280            return;
281        };
282        if let Err(error) = job.assign(child) {
283            tracing::debug!(%error, pid = child.id(), "could not add child to the kill-on-close job");
284        }
285    }
286    #[cfg(not(windows))]
287    let _ = child;
288}
289
290#[cfg(test)]
291mod tests {
292    use super::win32_job::*;
293    use std::mem::{align_of, offset_of, size_of};
294
295    /// The `winnt.h` layouts, checked on every host: a wrong size makes
296    /// `SetInformationJobObject` fail with ERROR_BAD_LENGTH on Windows.
297    #[test]
298    fn job_limit_structs_match_winnt_layout() {
299        let word = size_of::<usize>();
300        assert_eq!(size_of::<IoCounters>(), 48);
301        assert_eq!(offset_of!(JobObjectBasicLimitInformation, limit_flags), 16);
302        assert_eq!(
303            offset_of!(JobObjectExtendedLimitInformation, io_info),
304            size_of::<JobObjectBasicLimitInformation>()
305        );
306        assert_eq!(
307            offset_of!(JobObjectExtendedLimitInformation, process_memory_limit),
308            size_of::<JobObjectBasicLimitInformation>() + 48
309        );
310        assert_eq!(
311            size_of::<JobObjectExtendedLimitInformation>(),
312            size_of::<JobObjectBasicLimitInformation>() + 48 + 4 * word
313        );
314        assert_eq!(align_of::<JobObjectExtendedLimitInformation>(), 8);
315        assert_eq!(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, 0x2000);
316        assert_eq!(JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS, 9);
317    }
318
319    #[cfg(target_pointer_width = "64")]
320    #[test]
321    fn job_limit_structs_match_winnt_layout_64_bit() {
322        type Basic = JobObjectBasicLimitInformation;
323        assert_eq!(offset_of!(Basic, per_process_user_time_limit), 0);
324        assert_eq!(offset_of!(Basic, per_job_user_time_limit), 8);
325        assert_eq!(offset_of!(Basic, limit_flags), 16);
326        assert_eq!(offset_of!(Basic, minimum_working_set_size), 24);
327        assert_eq!(offset_of!(Basic, maximum_working_set_size), 32);
328        assert_eq!(offset_of!(Basic, active_process_limit), 40);
329        assert_eq!(offset_of!(Basic, affinity), 48);
330        assert_eq!(offset_of!(Basic, priority_class), 56);
331        assert_eq!(offset_of!(Basic, scheduling_class), 60);
332        assert_eq!(size_of::<Basic>(), 64);
333
334        type Extended = JobObjectExtendedLimitInformation;
335        assert_eq!(offset_of!(Extended, io_info), 64);
336        assert_eq!(offset_of!(Extended, process_memory_limit), 112);
337        assert_eq!(offset_of!(Extended, job_memory_limit), 120);
338        assert_eq!(offset_of!(Extended, peak_process_memory_used), 128);
339        assert_eq!(offset_of!(Extended, peak_job_memory_used), 136);
340        assert_eq!(size_of::<Extended>(), 144);
341    }
342
343    /// On Windows, a child in the job is ended when the job closes.
344    #[cfg(windows)]
345    #[tokio::test]
346    async fn closing_the_job_ends_its_process() {
347        let job = super::JobObject::kill_on_close().expect("create job");
348        let mut child = tokio::process::Command::new("cmd")
349            .args(["/C", "ping -n 30 127.0.0.1 >NUL"])
350            .stdout(std::process::Stdio::null())
351            .kill_on_drop(true)
352            .spawn()
353            .expect("spawn");
354        job.assign(&child).expect("assign");
355        drop(job);
356        let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
357            .await
358            .expect("child ended with the job")
359            .expect("wait");
360        assert!(!status.success());
361    }
362}