1use std::collections::HashSet;
7use std::io::Read;
8use std::os::fd::AsFd;
9use std::process::{Command, Output, Stdio};
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::thread;
13use std::time::{Duration, Instant};
14
15use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
16
17use crate::types::{Pid as StacklessPid, ProcessStartTime};
18
19#[derive(Debug)]
21pub enum TimedCommand {
22 Finished(Output),
23 LockFailed {
24 path: std::path::PathBuf,
25 detail: String,
26 },
27 TimedOut {
28 pid: u32,
29 },
30 Spawn(std::io::Error),
31 CaptureFailed(CaptureFailure),
32 CleanupFailed {
33 pid: u32,
34 },
35}
36
37pub const COMMAND_STDOUT_LIMIT: usize = 4 * 1024 * 1024;
39pub const COMMAND_STDERR_LIMIT: usize = 256 * 1024;
40const DRAIN_JOIN: Duration = Duration::from_secs(2);
41
42#[derive(Debug, thiserror::Error)]
43pub enum CaptureFailure {
44 #[error("{stream} exceeded {limit} bytes")]
45 Limit { stream: &'static str, limit: usize },
46 #[error("{stream} remained open after command cleanup")]
47 Incomplete { stream: &'static str },
48 #[error("could not capture {stream}: {source}")]
49 Read {
50 stream: &'static str,
51 source: std::io::Error,
52 },
53}
54
55pub fn real_user_id() -> u32 {
56 rustix::process::getuid().as_raw()
57}
58
59pub fn effective_user_id() -> u32 {
60 rustix::process::geteuid().as_raw()
61}
62
63pub fn run_with_timeout(cmd: &mut Command, budget: Duration) -> TimedCommand {
67 cmd.stdout(Stdio::piped())
68 .stderr(Stdio::piped())
69 .stdin(Stdio::null());
70 #[cfg(unix)]
71 {
72 use std::os::unix::process::CommandExt;
73 cmd.process_group(0);
74 }
75 let cookie = uuid::Uuid::new_v4().to_string();
76 cmd.env("STACKLESS_SPAWN", &cookie);
77 let child = match cmd.spawn() {
78 Ok(child) => child,
79 Err(err) => return TimedCommand::Spawn(err),
80 };
81 collect_child(
82 child,
83 &cookie,
84 budget,
85 COMMAND_STDOUT_LIMIT,
86 COMMAND_STDERR_LIMIT,
87 )
88}
89
90pub(crate) fn collect_child(
91 mut child: std::process::Child,
92 cookie: &str,
93 budget: Duration,
94 stdout_limit: usize,
95 stderr_limit: usize,
96) -> TimedCommand {
97 let pid = child.id();
98 let root = ProcessStamp::of(pid);
99 let stdout = drain_read(child.stdout.take(), "stdout", stdout_limit);
100 let stderr = drain_read(child.stderr.take(), "stderr", stderr_limit);
101 let deadline = Instant::now() + budget;
102 let stop = Arc::new(AtomicBool::new(false));
103 let seen = Arc::new(std::sync::Mutex::new(HashSet::new()));
104 let watcher = {
105 let stop = stop.clone();
106 let seen = seen.clone();
107 thread::spawn(move || {
108 while !stop.load(Ordering::Relaxed) {
109 if let Some(root) = root {
110 seen.lock()
111 .unwrap_or_else(|e| e.into_inner())
112 .extend(descendants(root));
113 }
114 thread::sleep(Duration::from_millis(1));
115 }
116 })
117 };
118 let outcome = loop {
119 if stdout.failed.load(Ordering::Acquire) || stderr.failed.load(Ordering::Acquire) {
120 break TimedCommand::CaptureFailed(CaptureFailure::Incomplete { stream: "output" });
121 }
122 match child.try_wait() {
123 Ok(Some(status)) => {
124 break TimedCommand::Finished(Output {
125 status,
126 stdout: Vec::new(),
127 stderr: Vec::new(),
128 });
129 }
130 Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(20)),
131 Ok(None) => break TimedCommand::TimedOut { pid },
132 Err(err) => break TimedCommand::Spawn(err),
133 }
134 };
135 stop.store(true, Ordering::Relaxed);
136 let _ = watcher.join();
137 let mut processes = seen.lock().unwrap_or_else(|e| e.into_inner()).clone();
138 if let Some(root) = root {
139 processes.extend(descendants(root));
140 }
141 processes.extend(cookie_processes(cookie));
142 let cleanup_deadline = Instant::now() + Duration::from_secs(3);
143 let cleaned = loop {
144 kill_observed(&processes);
145 processes.retain(ProcessStamp::is_alive);
146 processes.extend(cookie_processes(cookie));
147 if processes.is_empty() {
148 break true;
149 }
150 if Instant::now() >= cleanup_deadline {
151 break false;
152 }
153 thread::sleep(Duration::from_millis(10));
154 };
155 if !matches!(outcome, TimedCommand::Finished(_)) {
156 let _ = child.kill();
157 let _ = child.wait();
158 }
159 let drain_deadline = Instant::now() + DRAIN_JOIN;
160 let out = take_drain(stdout, drain_deadline);
161 let err = take_drain(stderr, drain_deadline);
162 if !cleaned {
163 return TimedCommand::CleanupFailed { pid };
164 }
165 match outcome {
166 TimedCommand::Finished(mut output) => match (out, err) {
167 (Ok(stdout), Ok(stderr)) => {
168 output.stdout = stdout;
169 output.stderr = stderr;
170 TimedCommand::Finished(output)
171 }
172 (Err(error), _) | (_, Err(error)) => TimedCommand::CaptureFailed(error),
173 },
174 TimedCommand::CaptureFailed(fallback) => {
175 TimedCommand::CaptureFailed(out.err().or_else(|| err.err()).unwrap_or(fallback))
176 }
177 other => other,
178 }
179}
180
181struct Drain {
182 failed: Arc<AtomicBool>,
183 stop: Arc<AtomicBool>,
184 handle: thread::JoinHandle<Result<Vec<u8>, CaptureFailure>>,
185 stream: &'static str,
186}
187
188fn drain_read<R: Read + AsFd + Send + 'static>(
189 pipe: Option<R>,
190 stream: &'static str,
191 limit: usize,
192) -> Drain {
193 let failed = Arc::new(AtomicBool::new(false));
194 let stop = Arc::new(AtomicBool::new(false));
195 let reader_failed = failed.clone();
196 let reader_stop = stop.clone();
197 let handle = thread::spawn(move || {
198 let result = capture(pipe, stream, limit, &reader_stop, &reader_failed);
199 if result.is_err() {
200 reader_failed.store(true, Ordering::Release);
201 }
202 result
203 });
204 Drain {
205 failed,
206 stop,
207 handle,
208 stream,
209 }
210}
211
212fn capture<R: Read + AsFd>(
213 pipe: Option<R>,
214 stream: &'static str,
215 limit: usize,
216 stop: &AtomicBool,
217 failed: &AtomicBool,
218) -> Result<Vec<u8>, CaptureFailure> {
219 let mut pipe = pipe.ok_or_else(|| CaptureFailure::Read {
220 stream,
221 source: std::io::Error::other("command pipe missing"),
222 })?;
223 let flags = rustix::fs::fcntl_getfl(&pipe).map_err(|error| CaptureFailure::Read {
224 stream,
225 source: error.into(),
226 })?;
227 rustix::fs::fcntl_setfl(&pipe, flags | rustix::fs::OFlags::NONBLOCK).map_err(|error| {
228 CaptureFailure::Read {
229 stream,
230 source: error.into(),
231 }
232 })?;
233 let mut bytes = Vec::with_capacity(limit);
234 let mut exceeded = false;
235 let mut complete = false;
236 let mut chunk = [0u8; 8192];
237 while !stop.load(Ordering::Acquire) {
238 match pipe.read(&mut chunk) {
239 Ok(0) => {
240 complete = true;
241 break;
242 }
243 Ok(count) => {
244 let retained = count.min(limit.saturating_sub(bytes.len()));
245 bytes.extend_from_slice(&chunk[..retained]);
246 if retained != count {
247 exceeded = true;
248 failed.store(true, Ordering::Release);
249 }
250 }
251 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
252 thread::sleep(Duration::from_millis(5))
253 }
254 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => (),
255 Err(source) => return Err(CaptureFailure::Read { stream, source }),
256 }
257 }
258 if exceeded {
259 return Err(CaptureFailure::Limit { stream, limit });
260 }
261 if !complete {
262 return Err(CaptureFailure::Incomplete { stream });
263 }
264 Ok(bytes)
265}
266
267fn take_drain(drain: Drain, deadline: Instant) -> Result<Vec<u8>, CaptureFailure> {
268 while !drain.handle.is_finished() && Instant::now() < deadline {
269 thread::sleep(Duration::from_millis(5));
270 }
271 drain.stop.store(true, Ordering::Release);
272 drain.handle.join().unwrap_or_else(|_| {
273 Err(CaptureFailure::Read {
274 stream: drain.stream,
275 source: std::io::Error::other("command reader panicked"),
276 })
277 })
278}
279
280pub fn kill_process_tree(root: u32) {
283 if let Some(root) = ProcessStamp::of(root) {
284 kill_process_tree_stamped(root);
285 }
286}
287
288pub fn kill_process_tree_stamped(root: ProcessStamp) {
290 kill_owned_processes(root, []);
291}
292
293pub(crate) fn kill_owned_processes(
294 root: ProcessStamp,
295 members: impl IntoIterator<Item = ProcessStamp>,
296) {
297 let mut processes = descendants(root);
298 processes.extend(members);
299 kill_observed(&processes);
300}
301
302fn process_stamp(pid: Pid, process: &sysinfo::Process) -> ProcessStamp {
303 ProcessStamp {
304 pid: StacklessPid::from_os(pid.as_u32()),
305 start_time: ProcessStartTime::from_os(process.start_time()),
306 }
307}
308
309fn descendants(root: ProcessStamp) -> HashSet<ProcessStamp> {
310 let mut system = System::new();
311 system.refresh_processes(ProcessesToUpdate::All, true);
312 if system
313 .process(Pid::from_u32(root.pid.get()))
314 .is_none_or(|process| process.start_time() != root.start_time.get())
315 {
316 return HashSet::new();
317 }
318 let mut stack = vec![root.pid.get()];
319 let mut visited = HashSet::new();
320 let mut observed = HashSet::new();
321 while let Some(pid) = stack.pop() {
322 if !visited.insert(pid) {
323 continue;
324 }
325 if let Some(process) = system.process(Pid::from_u32(pid))
326 && process.status() != sysinfo::ProcessStatus::Zombie
327 {
328 observed.insert(process_stamp(Pid::from_u32(pid), process));
329 }
330 for (child, process) in system.processes() {
331 if process.parent() == Some(Pid::from_u32(pid)) {
332 stack.push(child.as_u32());
333 }
334 }
335 }
336 observed
337}
338
339fn cookie_processes(cookie: &str) -> HashSet<ProcessStamp> {
340 let mut system = System::new();
341 system.refresh_processes_specifics(
342 ProcessesToUpdate::All,
343 true,
344 ProcessRefreshKind::nothing().with_environ(UpdateKind::Always),
345 );
346 let expected = format!("STACKLESS_SPAWN={cookie}");
347 system
348 .processes()
349 .iter()
350 .filter_map(|(pid, process)| {
351 (process.status() != sysinfo::ProcessStatus::Zombie
352 && process
353 .environ()
354 .iter()
355 .any(|value| value == std::ffi::OsStr::new(&expected)))
356 .then_some(process_stamp(*pid, process))
357 })
358 .collect()
359}
360
361fn kill_observed(processes: &HashSet<ProcessStamp>) {
362 let mut system = System::new();
363 system.refresh_processes(ProcessesToUpdate::All, true);
364 let owned: std::collections::HashMap<_, _> = processes
365 .iter()
366 .filter(|stamp| {
367 system
368 .process(Pid::from_u32(stamp.pid.get()))
369 .is_some_and(|process| process.start_time() == stamp.start_time.get())
370 })
371 .map(|stamp| (stamp.pid.get(), *stamp))
372 .collect();
373 let mut ordered: Vec<_> = owned.values().copied().collect();
374 ordered.sort_by_key(|stamp| {
375 let mut depth = 0;
376 let mut cursor = stamp.pid.get();
377 let mut visited = HashSet::new();
378 while visited.insert(cursor) {
379 let Some(parent) = system
380 .process(Pid::from_u32(cursor))
381 .and_then(|process| process.parent())
382 else {
383 break;
384 };
385 if !owned.contains_key(&parent.as_u32()) {
386 break;
387 }
388 depth += 1;
389 cursor = parent.as_u32();
390 }
391 (depth, stamp.pid.get())
392 });
393 for process in &ordered {
396 if process.is_alive()
397 && let Ok(raw) = i32::try_from(process.pid.get())
398 && let Some(pid) = rustix::process::Pid::from_raw(raw)
399 {
400 let _ = rustix::process::kill_process(pid, rustix::process::Signal::STOP);
401 }
402 }
403 for process in ordered {
404 if !process.is_alive() {
405 continue;
406 }
407 if is_process_group_leader(process.pid.get()) {
408 kill_process_group(process.pid.get());
409 }
410 if process.is_alive() {
411 kill_one(process.pid.get());
412 }
413 }
414}
415
416fn is_process_group_leader(pid: u32) -> bool {
417 #[cfg(unix)]
418 {
419 let Ok(raw) = i32::try_from(pid) else {
420 return false;
421 };
422 let Some(pid) = rustix::process::Pid::from_raw(raw) else {
423 return false;
424 };
425 rustix::process::getpgid(Some(pid)).ok() == Some(pid)
426 }
427 #[cfg(not(unix))]
428 {
429 let _ = pid;
430 false
431 }
432}
433
434pub fn kill_process_group(pid: u32) {
436 #[cfg(unix)]
437 if let Ok(raw) = i32::try_from(pid)
438 && let Some(pgid) = rustix::process::Pid::from_raw(raw)
439 {
440 let _ = rustix::process::kill_process_group(pgid, rustix::process::Signal::KILL);
441 }
442 #[cfg(not(unix))]
443 let _ = pid;
444}
445
446fn kill_one(pid: u32) {
447 #[cfg(unix)]
448 if let Ok(raw) = i32::try_from(pid)
449 && let Some(pid) = rustix::process::Pid::from_raw(raw)
450 {
451 let _ = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
452 }
453 #[cfg(not(unix))]
454 let _ = pid;
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
459pub struct ProcessStamp {
460 pub pid: StacklessPid,
461 pub start_time: ProcessStartTime,
463}
464
465impl ProcessStamp {
466 pub fn current() -> Self {
468 let pid = StacklessPid::from_os(std::process::id());
469 Self {
470 pid,
471 start_time: start_time_of(pid).unwrap_or(ProcessStartTime::from_os(0)),
472 }
473 }
474
475 pub fn of(pid: u32) -> Option<Self> {
477 let pid = StacklessPid::from_os(pid);
478 start_time_of(pid).map(|start_time| Self { pid, start_time })
479 }
480
481 pub fn is_alive(&self) -> bool {
484 start_time_of(self.pid).is_some_and(|start| start == self.start_time)
485 }
486}
487
488fn start_time_of(pid: StacklessPid) -> Option<ProcessStartTime> {
489 let raw = pid.get();
490 let mut system = System::new();
491 system.refresh_processes_specifics(
492 ProcessesToUpdate::Some(&[Pid::from_u32(raw)]),
493 false,
494 ProcessRefreshKind::nothing(),
495 );
496 system
497 .process(Pid::from_u32(raw))
498 .filter(|process| process.status() != sysinfo::ProcessStatus::Zombie)
499 .map(sysinfo::Process::start_time)
500 .map(ProcessStartTime::from_os)
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506
507 #[test]
508 fn current_process_is_alive() {
509 let stamp = ProcessStamp::current();
510 assert!(stamp.start_time.get() > 0);
511 assert!(stamp.is_alive());
512 }
513
514 #[test]
515 fn wrong_start_time_is_not_alive() {
516 let stamp = ProcessStamp {
517 pid: StacklessPid::from_os(std::process::id()),
518 start_time: ProcessStartTime::from_os(1),
519 };
520 assert!(!stamp.is_alive());
521 }
522
523 #[test]
524 fn bogus_pid_is_not_alive() {
525 let stamp = ProcessStamp {
526 pid: StacklessPid::from_os(u32::MAX - 1),
527 start_time: ProcessStartTime::from_os(1),
528 };
529 assert!(!stamp.is_alive());
530 }
531
532 #[test]
533 fn an_unreaped_exit_is_not_a_live_process() {
534 let mut child = Command::new("/bin/sh")
535 .args(["-c", "read stackless_gate; exit 0"])
536 .stdin(Stdio::piped())
537 .spawn()
538 .unwrap();
539 let stamp = ProcessStamp::of(child.id()).unwrap();
540 drop(child.stdin.take());
541 let deadline = Instant::now() + Duration::from_secs(3);
542 while stamp.is_alive() && Instant::now() < deadline {
543 thread::sleep(Duration::from_millis(10));
544 }
545 let stopped = !stamp.is_alive();
546 child.wait().unwrap();
547 assert!(
548 stopped,
549 "an exited child was treated as alive until its parent reaped it"
550 );
551 }
552
553 #[test]
554 fn run_with_timeout_finishes_a_quick_command() {
555 let mut cmd = Command::new("echo");
556 cmd.arg("stackless-timeout-ok");
557 match run_with_timeout(&mut cmd, Duration::from_secs(5)) {
558 TimedCommand::Finished(out) => {
559 assert!(out.status.success());
560 assert!(String::from_utf8_lossy(&out.stdout).contains("stackless-timeout-ok"));
561 }
562 other => panic!("expected finish, got {other:?}"),
563 }
564 }
565
566 #[test]
567 fn run_with_timeout_kills_a_sleeper() {
568 let mut cmd = Command::new("sleep");
569 cmd.arg("30");
570 let started = Instant::now();
571 match run_with_timeout(&mut cmd, Duration::from_millis(250)) {
572 TimedCommand::TimedOut { pid } => {
573 assert!(pid > 0);
574 assert!(started.elapsed() < Duration::from_secs(3));
575 assert!(
576 ProcessStamp::of(pid).is_none_or(|stamp| !stamp.is_alive()),
577 "sleeper pid {pid} still alive after timeout kill"
578 );
579 }
580 other => panic!("expected timeout, got {other:?}"),
581 }
582 }
583
584 #[test]
585 fn run_with_timeout_drains_stdout_larger_than_a_pipe() {
586 let mut cmd = Command::new("python3");
587 cmd.args(["-c", "print('x' * 200_000, end='')"]);
588 match run_with_timeout(&mut cmd, Duration::from_secs(5)) {
589 TimedCommand::Finished(out) => {
590 assert!(out.status.success());
591 assert_eq!(out.stdout.len(), 200_000);
592 }
593 other => panic!("expected finish, got {other:?}"),
594 }
595 }
596
597 #[test]
598 fn capture_rejects_overflow_even_when_the_child_exits_zero() {
599 for (stream, limit) in [
600 ("stdout", COMMAND_STDOUT_LIMIT),
601 ("stderr", COMMAND_STDERR_LIMIT),
602 ] {
603 for excess in [0, 1] {
604 let mut command = Command::new("python3");
605 command.args([
606 "-c",
607 &format!(
608 "import sys; sys.{stream}.buffer.write(b'x' * {}); sys.{stream}.flush()",
609 limit + excess
610 ),
611 ]);
612 match run_with_timeout(&mut command, Duration::from_secs(5)) {
613 TimedCommand::Finished(output) if excess == 0 => {
614 assert!(output.status.success());
615 assert_eq!(
616 if stream == "stdout" {
617 output.stdout.len()
618 } else {
619 output.stderr.len()
620 },
621 limit
622 );
623 }
624 TimedCommand::CaptureFailed(CaptureFailure::Limit {
625 stream: actual,
626 limit: actual_limit,
627 }) if excess == 1 => {
628 assert_eq!(actual, stream);
629 assert_eq!(actual_limit, limit);
630 }
631 other => panic!("unexpected capture result: {other:?}"),
632 }
633 }
634 }
635 }
636
637 #[test]
638 fn capture_overflow_stops_the_process_before_its_time_budget() {
639 let root = tempfile::tempdir().unwrap();
640 let mut command = Command::new("python3");
641 command.current_dir(root.path()).args([
642 "-c",
643 &format!(
644 r#"
645import os, pathlib, sys, time
646pathlib.Path('pid').write_text(str(os.getpid()))
647sys.stdout.buffer.write(b'x' * {})
648sys.stdout.flush()
649time.sleep(30)
650pathlib.Path('late').touch()
651"#,
652 COMMAND_STDOUT_LIMIT * 2
653 ),
654 ]);
655 let started = Instant::now();
656 assert!(matches!(
657 run_with_timeout(&mut command, Duration::from_secs(30)),
658 TimedCommand::CaptureFailed(CaptureFailure::Limit {
659 stream: "stdout",
660 ..
661 })
662 ));
663 assert!(started.elapsed() < Duration::from_secs(5));
664 let pid = std::fs::read_to_string(root.path().join("pid"))
665 .unwrap()
666 .parse::<u32>()
667 .unwrap();
668 assert!(ProcessStamp::of(pid).is_none());
669 assert!(!root.path().join("late").exists());
670 }
671
672 #[test]
673 fn capture_stops_and_joins_a_reader_whose_writer_never_closes() {
674 use std::io::Write;
675 let (reader, mut writer) = std::os::unix::net::UnixStream::pair().unwrap();
676 writer.write_all(br#"{"ok":true}"#).unwrap();
677 let drain = drain_read(Some(reader), "stdout", 1024);
678 let started = Instant::now();
679 assert!(matches!(
680 take_drain(drain, Instant::now() + Duration::from_millis(50)),
681 Err(CaptureFailure::Incomplete { stream: "stdout" })
682 ));
683 assert!(started.elapsed() < Duration::from_secs(1));
684 assert!(writer.write_all(b"still open").is_err());
686 }
687
688 #[test]
689 fn capture_cleanup_requires_an_exact_cookie_environment_entry() {
690 let root = tempfile::tempdir().unwrap();
691 let directory = root.path().to_path_buf();
692 let worker = thread::spawn(move || {
693 let mut command = Command::new("python3");
694 command.current_dir(directory).args([
695 "-c",
696 r#"
697import os, pathlib, time
698pathlib.Path('cookie').write_text(os.environ['STACKLESS_SPAWN'])
699while not pathlib.Path('finish').exists(): time.sleep(0.01)
700"#,
701 ]);
702 run_with_timeout(&mut command, Duration::from_secs(10))
703 });
704 let deadline = Instant::now() + Duration::from_secs(5);
705 let cookie = loop {
706 if let Ok(cookie) = std::fs::read_to_string(root.path().join("cookie"))
707 && uuid::Uuid::parse_str(&cookie).is_ok()
708 {
709 break cookie;
710 }
711 assert!(Instant::now() < deadline);
712 thread::sleep(Duration::from_millis(10));
713 };
714 let mut unrelated = Command::new("/bin/sleep")
715 .arg("30")
716 .env("UNRELATED", &cookie)
717 .spawn()
718 .unwrap();
719 let mut substring = Command::new("/bin/sleep")
720 .arg("30")
721 .env("STACKLESS_SPAWN", format!("prefix-{cookie}"))
722 .spawn()
723 .unwrap();
724 std::fs::write(root.path().join("finish"), "done").unwrap();
725 let result = worker.join();
726 let unrelated_alive = unrelated.try_wait().unwrap().is_none();
727 let substring_alive = substring.try_wait().unwrap().is_none();
728 let _ = unrelated.kill();
729 let _ = unrelated.wait();
730 let _ = substring.kill();
731 let _ = substring.wait();
732 assert!(matches!(result.unwrap(), TimedCommand::Finished(_)));
733 assert!(unrelated_alive && substring_alive);
734 }
735
736 #[test]
737 fn capture_cleanup_rejects_a_stale_process_incarnation() {
738 use std::os::unix::process::CommandExt;
739 let mut child = Command::new("/bin/sleep")
740 .arg("30")
741 .process_group(0)
742 .spawn()
743 .unwrap();
744 let actual = ProcessStamp::of(child.id()).unwrap();
745 let stale = ProcessStamp {
746 start_time: ProcessStartTime::from_os(1),
747 ..actual
748 };
749 kill_observed(&HashSet::from([stale]));
750 kill_process_tree_stamped(stale);
751 let alive = actual.is_alive();
752 kill_process_tree_stamped(actual);
753 child.wait().unwrap();
754 assert!(alive);
755 assert!(!actual.is_alive());
756 }
757
758 #[test]
759 fn run_with_timeout_keeps_stdout_when_helper_holds_the_pipe() {
760 let marker = "stackless-bound-helper-marker";
761 let mut cmd = Command::new("python3");
762 cmd.args([
763 "-c",
764 &format!(
765 r#"
766import os, sys
767sys.stdout.write('{{"ok":true}}')
768sys.stdout.flush()
769if os.fork() == 0:
770 os.setsid()
771 import time
772 time.sleep(30) # {marker}
773os._exit(0)
774"#
775 ),
776 ]);
777 match run_with_timeout(&mut cmd, Duration::from_secs(8)) {
778 TimedCommand::Finished(out) => {
779 assert!(out.status.success());
780 assert!(
781 String::from_utf8_lossy(&out.stdout).contains(r#"{"ok":true}"#),
782 "stdout was {:?}",
783 String::from_utf8_lossy(&out.stdout)
784 );
785 }
786 other => panic!("expected finish, got {other:?}"),
787 }
788 let leftover = Command::new("pgrep")
789 .args(["-f", &format!("python3.*{marker}")])
790 .output()
791 .expect("pgrep");
792 assert!(
793 leftover.stdout.is_empty(),
794 "setsid helper still alive: {}",
795 String::from_utf8_lossy(&leftover.stdout)
796 );
797 }
798
799 #[test]
800 fn run_with_timeout_reaps_setsid_helper_that_closes_stdio() {
801 let marker = "stackless-closed-stdio-helper-marker";
802 let mut cmd = Command::new("python3");
803 cmd.args([
804 "-c",
805 &format!(
806 r#"
807import os, sys
808sys.stdout.write('{{"ok":true}}')
809sys.stdout.flush()
810if os.fork() == 0:
811 os.setsid()
812 os.close(1)
813 os.close(2)
814 import time
815 time.sleep(30) # {marker}
816os._exit(0)
817"#
818 ),
819 ]);
820 match run_with_timeout(&mut cmd, Duration::from_secs(8)) {
821 TimedCommand::Finished(out) => {
822 assert!(out.status.success());
823 assert!(
824 String::from_utf8_lossy(&out.stdout).contains(r#"{"ok":true}"#),
825 "stdout was {:?}",
826 String::from_utf8_lossy(&out.stdout)
827 );
828 }
829 other => panic!("expected finish, got {other:?}"),
830 }
831 let leftover = Command::new("pgrep")
832 .args(["-f", &format!("python3.*{marker}")])
833 .output()
834 .expect("pgrep");
835 assert!(
836 leftover.stdout.is_empty(),
837 "closed-stdio helper still alive: {}",
838 String::from_utf8_lossy(&leftover.stdout)
839 );
840 }
841
842 #[test]
843 fn run_with_timeout_reaps_setsid_helper_grandchildren() {
844 let marker = "stackless-setsid-grandchild-marker";
845 let mut cmd = Command::new("python3");
846 cmd.args([
847 "-c",
848 &format!(
849 r#"
850import os, sys, time
851sys.stdout.write('{{"ok":true}}')
852sys.stdout.flush()
853if os.fork() == 0:
854 os.setsid()
855 if os.fork() == 0:
856 time.sleep(30) # {marker}
857 os._exit(0)
858 time.sleep(30)
859os._exit(0)
860"#
861 ),
862 ]);
863 match run_with_timeout(&mut cmd, Duration::from_secs(8)) {
864 TimedCommand::Finished(out) => {
865 assert!(out.status.success());
866 assert!(
867 String::from_utf8_lossy(&out.stdout).contains(r#"{"ok":true}"#),
868 "stdout was {:?}",
869 String::from_utf8_lossy(&out.stdout)
870 );
871 }
872 other => panic!("expected finish, got {other:?}"),
873 }
874 let leftover = Command::new("pgrep")
875 .args(["-f", &format!("python3.*{marker}")])
876 .output()
877 .expect("pgrep");
878 assert!(
879 leftover.stdout.is_empty(),
880 "setsid grandchild still alive: {}",
881 String::from_utf8_lossy(&leftover.stdout)
882 );
883 }
884
885 #[test]
886 fn run_with_timeout_does_not_kill_unrelated_stripe_named_process() {
887 let decoy = std::env::temp_dir().join(format!(
888 "stripe-cli-projects-unrelated-{}",
889 std::process::id()
890 ));
891 std::fs::write(&decoy, b"#!/bin/sh\nexec sleep 60\n").expect("write decoy");
892 #[cfg(unix)]
893 {
894 use std::os::unix::fs::PermissionsExt;
895 let mut perms = std::fs::metadata(&decoy).expect("meta").permissions();
896 perms.set_mode(0o755);
897 std::fs::set_permissions(&decoy, perms).expect("chmod");
898 }
899 let mut decoy_child = Command::new(&decoy)
900 .stdin(Stdio::null())
901 .stdout(Stdio::null())
902 .stderr(Stdio::null())
903 .spawn()
904 .expect("spawn decoy");
905 let decoy_pid = decoy_child.id();
906 let mut cmd = Command::new("sleep");
907 cmd.arg("30");
908 let timed = run_with_timeout(&mut cmd, Duration::from_millis(250));
909 let decoy_alive = ProcessStamp::of(decoy_pid).is_some_and(|s| s.is_alive());
910 let _ = decoy_child.kill();
911 let _ = decoy_child.wait();
912 let _ = std::fs::remove_file(&decoy);
913 match timed {
914 TimedCommand::TimedOut { .. } => {}
915 other => panic!("expected timeout, got {other:?}"),
916 }
917 assert!(
918 decoy_alive,
919 "unrelated stripe-cli-projects decoy {decoy_pid} was killed"
920 );
921 }
922 #[test]
923 fn cleanup_cannot_wake_a_waiting_parent_into_its_next_action() {
924 use std::os::unix::process::CommandExt;
925 let root = tempfile::tempdir().unwrap();
926 for iteration in 0..12 {
927 let directory = root.path().join(iteration.to_string());
928 std::fs::create_dir(&directory).unwrap();
929 let mut child = Command::new("python3")
930 .current_dir(&directory)
931 .args([
932 "-c",
933 r#"
934import os, pathlib, time
935child = os.fork()
936if child == 0:
937 time.sleep(30)
938 os._exit(0)
939pathlib.Path('child.tmp').write_text(str(child))
940os.replace('child.tmp', 'child')
941os.waitpid(child, 0)
942pathlib.Path('escaped').touch()
943"#,
944 ])
945 .stdin(Stdio::null())
946 .stdout(Stdio::null())
947 .stderr(Stdio::null())
948 .process_group(0)
949 .spawn()
950 .unwrap();
951 let parent = ProcessStamp::of(child.id()).unwrap();
952 let deadline = Instant::now() + Duration::from_secs(2);
953 let sleeper = loop {
954 if let Ok(pid) = std::fs::read_to_string(directory.join("child")) {
955 break ProcessStamp::of(pid.parse().unwrap()).unwrap();
956 }
957 assert!(Instant::now() < deadline, "waiting parent did not start");
958 thread::sleep(Duration::from_millis(5));
959 };
960 let processes = (0..64)
962 .map(|_| HashSet::from([sleeper, parent]))
963 .find(|processes| processes.iter().next() == Some(&sleeper))
964 .unwrap();
965 kill_observed(&processes);
966 child.wait().unwrap();
967 let deadline = Instant::now() + Duration::from_secs(3);
969 while (parent.is_alive() || sleeper.is_alive()) && Instant::now() < deadline {
970 thread::sleep(Duration::from_millis(5));
971 }
972 assert!(
973 !parent.is_alive() && !sleeper.is_alive(),
974 "cleanup left a live process: parent={parent:?}, child={sleeper:?}"
975 );
976 assert!(!directory.join("escaped").exists());
977 }
978 }
979}