1use std::time::Duration;
2
3#[cfg(unix)]
6pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
7 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 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#[cfg(unix)]
40pub fn send_sigterm(pid: u32) -> bool {
41 send_signal_to_process_group_or_pid(pid, libc::SIGTERM)
42}
43
44#[cfg(unix)]
46pub fn send_sigkill(pid: u32) -> bool {
47 send_signal_to_process_group_or_pid(pid, libc::SIGKILL)
48}
49
50#[cfg(not(unix))]
52pub fn send_sigterm(pid: u32) -> bool {
53 taskkill(pid, false)
54}
55
56#[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
79pub 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 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#[cfg(any(windows, test))]
114#[allow(dead_code)] mod win32_job {
116 #[repr(C)]
118 #[derive(Debug, Default, Clone, Copy)]
119 pub(super) struct JobObjectBasicLimitInformation {
120 pub per_process_user_time_limit: i64, pub per_job_user_time_limit: i64, pub limit_flags: u32, pub minimum_working_set_size: usize, pub maximum_working_set_size: usize, pub active_process_limit: u32, pub affinity: usize, pub priority_class: u32, pub scheduling_class: u32, }
130
131 #[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 #[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, pub job_memory_limit: usize, pub peak_process_memory_used: usize, pub peak_job_memory_used: usize, }
154
155 pub(super) const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS: i32 = 9;
157 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#[cfg(windows)]
186pub struct JobObject {
187 handle: std::ptr::NonNull<std::ffi::c_void>,
188}
189
190#[cfg(windows)]
193unsafe impl Send for JobObject {}
194#[cfg(windows)]
195unsafe impl Sync for JobObject {}
196
197#[cfg(windows)]
198impl JobObject {
199 pub fn kill_on_close() -> std::io::Result<Self> {
201 use win32_job::*;
202 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 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 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 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 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 unsafe {
247 win32_job::CloseHandle(self.handle.as_ptr());
248 }
249 }
250}
251
252#[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
271pub 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 #[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 #[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}