Repository navigation
Expand file tree
/
Copy pathprocess.rs
More file actions
1398 lines (1318 loc) · 50 KB
/
Copy pathprocess.rs
File metadata and controls
1398 lines (1318 loc) · 50 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! Bounded probe output capture with OS-scoped descendant ownership.
mod tree;
use tree::ProcessTree;
mod supervisor;
use supervisor::{Admission, Supervisor};
use std::{
fmt,
io::{self, Read},
process::{Child, Command, ExitStatus, Output, Stdio},
thread,
time::{Duration, Instant},
};
const CAPTURE_LIMIT: usize = 4 * 1024 * 1024;
/// Shared execution budget after synchronous OS process creation returns.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15);
const POLL_INTERVAL: Duration = Duration::from_millis(5);
const CLEANUP_TIMEOUT: Duration = Duration::from_secs(2);
static SUPERVISOR: Supervisor = Supervisor::new();
#[derive(Debug)]
pub enum ProcessError {
Spawn(io::Error),
Ownership(io::Error),
Io(io::Error),
Cancelled,
Timeout(Duration),
OutputLimit(usize),
IncompleteOutput(ExitStatus),
Cleanup {
primary: Box<ProcessError>,
source: io::Error,
},
}
impl ProcessError {
fn with_cleanup(self, cleanup: io::Result<()>) -> Self {
match cleanup {
Ok(()) => self,
Err(source) => Self::Cleanup {
primary: Box::new(self),
source,
},
}
}
}
impl fmt::Display for ProcessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spawn(error) => write!(f, "failed to spawn subprocess: {error}"),
Self::Ownership(error) => write!(f, "subprocess ownership failed: {error}"),
Self::Io(error) => write!(f, "subprocess I/O failed: {error}"),
Self::Cancelled => write!(f, "subprocess cancelled for process shutdown"),
Self::Timeout(timeout) => write!(f, "subprocess timed out after {timeout:?}"),
Self::OutputLimit(limit) => {
write!(f, "subprocess output exceeded {limit} captured bytes")
}
Self::IncompleteOutput(status) => write!(
f,
"subprocess exited with {status} but output did not reach EOF before the deadline"
),
Self::Cleanup { primary, source } => {
write!(f, "{primary}; subprocess cleanup failed: {source}")
}
}
}
}
impl std::error::Error for ProcessError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Spawn(error) | Self::Ownership(error) | Self::Io(error) => Some(error),
Self::Cleanup { primary, .. } => Some(primary.as_ref()),
Self::Cancelled
| Self::Timeout(_)
| Self::OutputLimit(_)
| Self::IncompleteOutput(_) => None,
}
}
}
impl From<io::Error> for ProcessError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
/// Drain both pipes while an owned subprocess runs, without reader threads.
///
/// The execution clock starts when synchronous OS spawn returns. At direct-child
/// exit, remaining members of its Unix process group or Windows job are killed
/// before reaping the child. Draining continues within the original deadline.
/// Escaped Unix descendants are not owned and cannot extend that deadline.
/// This is a discovery-probe API, not a general replacement for Command::output.
/// On Windows it **replaces any caller-supplied creation flags** with
/// CREATE_NO_WINDOW | CREATE_SUSPENDED for safe job assignment. Callers must not
/// depend on additional creation flags. Arguments, cwd, and environment are kept.
/// Retained bytes are bounded; an extra byte detects overflow and is not retained.
pub fn output(command: &mut Command, timeout: Duration) -> Result<Output, ProcessError> {
output_with_supervisor(command, timeout, CAPTURE_LIMIT, &SUPERVISOR)
}
/// Permanently closes discovery-probe admission for this process, cancels all
/// admitted probes, and waits up to `timeout` for their ownership cleanup.
///
/// A successful return guarantees that every probe accepted before closure has
/// completed cleanup successfully. The first cleanup failure is retained and
/// returned after all admitted probes finish, including from repeated calls. A
/// timeout leaves admission closed and cancellation active; callers may invoke
/// this again to continue waiting. Synchronous OS process creation and OS I/O
/// calls cannot be interrupted by this API, so shutdown can time out while an
/// admitted thread is inside one of those calls.
pub fn shutdown(timeout: Duration) -> io::Result<()> {
SUPERVISOR.shutdown(timeout)
}
/// Returns whether process-wide probe shutdown has begun.
pub fn is_shutting_down() -> bool {
SUPERVISOR.is_shutting_down()
}
#[cfg(test)]
fn output_with_limit(
command: &mut Command,
timeout: Duration,
limit: usize,
) -> Result<Output, ProcessError> {
output_with_supervisor(command, timeout, limit, &SUPERVISOR)
}
fn output_with_supervisor(
command: &mut Command,
timeout: Duration,
limit: usize,
supervisor: &Supervisor,
) -> Result<Output, ProcessError> {
output_with_supervisor_setup(command, timeout, limit, supervisor, |tree, child| {
tree.attach(child)
})
}
#[cfg(test)]
fn output_with_setup(
command: &mut Command,
timeout: Duration,
limit: usize,
setup: impl FnOnce(&mut ProcessTree, &Child) -> io::Result<()>,
) -> Result<Output, ProcessError> {
output_with_supervisor_setup(command, timeout, limit, &SUPERVISOR, setup)
}
fn output_with_supervisor_setup(
command: &mut Command,
timeout: Duration,
limit: usize,
supervisor: &Supervisor,
setup: impl FnOnce(&mut ProcessTree, &Child) -> io::Result<()>,
) -> Result<Output, ProcessError> {
let admission = supervisor.admit()?;
let mut tree = ProcessTree::prepare(command).map_err(ProcessError::Ownership)?;
let mut child = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(ProcessError::Spawn)?;
let started = Instant::now();
let mut stdout = child
.stdout
.take()
.expect("stdout was configured as a pipe");
let mut stderr = child
.stderr
.take()
.expect("stderr was configured as a pipe");
let result = (|| {
setup(&mut tree, &child).map_err(ProcessError::Ownership)?;
configure_pipe(&stdout)?;
configure_pipe(&stderr)?;
capture(
&mut || tree.poll(&mut child).map_err(ProcessError::Ownership),
&mut stdout,
&mut stderr,
started,
timeout,
limit,
&admission,
)
})();
drop(stdout);
drop(stderr);
let cleanup = cleanup(child, &mut tree);
let shutdown_won = admission.finish(&cleanup);
match result {
Err(primary) => Err(primary.with_cleanup(cleanup)),
Ok(_) if shutdown_won => Err(ProcessError::Cancelled.with_cleanup(cleanup)),
Ok(output) => cleanup.map(|()| output).map_err(ProcessError::Ownership),
}
}
fn capture(
poll: &mut impl FnMut() -> Result<Option<ExitStatus>, ProcessError>,
stdout: &mut impl Pipe,
stderr: &mut impl Pipe,
started: Instant,
timeout: Duration,
limit: usize,
admission: &Admission<'_>,
) -> Result<Output, ProcessError> {
let mut captured_stdout = Vec::new();
let mut captured_stderr = Vec::new();
let mut stdout_eof = false;
let mut stderr_eof = false;
let mut status = None;
let mut scratch = [0; 8192];
loop {
if admission.is_cancelled() {
return Err(ProcessError::Cancelled);
}
if status.is_none() {
status = poll()?;
}
let mut progressed = false;
if !stdout_eof {
progressed |= drain(
stdout,
&mut captured_stdout,
captured_stderr.len(),
&mut stdout_eof,
&mut scratch,
limit,
)?;
}
if !stderr_eof {
progressed |= drain(
stderr,
&mut captured_stderr,
captured_stdout.len(),
&mut stderr_eof,
&mut scratch,
limit,
)?;
}
if let Some(status) = status {
if stdout_eof && stderr_eof {
return Ok(Output {
status,
stdout: captured_stdout,
stderr: captured_stderr,
});
}
}
if started.elapsed() >= timeout {
return Err(match status {
Some(status) => ProcessError::IncompleteOutput(status),
None => ProcessError::Timeout(timeout),
});
}
if !progressed {
thread::sleep(POLL_INTERVAL.min(timeout.saturating_sub(started.elapsed())));
}
}
}
fn drain(
pipe: &mut (impl Pipe + ?Sized),
captured: &mut Vec<u8>,
other_len: usize,
eof: &mut bool,
scratch: &mut [u8],
limit: usize,
) -> Result<bool, ProcessError> {
let remaining = limit
.saturating_sub(captured.len())
.saturating_sub(other_len);
let maximum = scratch.len().min(remaining.saturating_add(1));
match pipe.read_available(&mut scratch[..maximum])? {
PipeRead::Pending => Ok(false),
PipeRead::Eof => {
*eof = true;
Ok(true)
}
PipeRead::Data(count) => {
if count > remaining {
return Err(ProcessError::OutputLimit(limit));
}
captured.extend_from_slice(&scratch[..count]);
Ok(true)
}
}
}
enum PipeRead {
Data(usize),
Pending,
Eof,
}
trait Pipe {
fn read_available(&mut self, buffer: &mut [u8]) -> io::Result<PipeRead>;
}
macro_rules! impl_pipe {
($($pipe:ty),+) => {$(
impl Pipe for $pipe {
fn read_available(&mut self, buffer: &mut [u8]) -> io::Result<PipeRead> {
read_available(self, buffer)
}
}
)+};
}
impl_pipe!(std::process::ChildStdout, std::process::ChildStderr);
#[cfg(unix)]
fn configure_pipe(pipe: &impl std::os::fd::AsRawFd) -> io::Result<()> {
let fd = pipe.as_raw_fd();
// SAFETY: the descriptor is live, and both fcntl operations use integer flags.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(windows)]
fn configure_pipe(_pipe: &impl std::os::windows::io::AsRawHandle) -> io::Result<()> {
Ok(())
}
#[cfg(unix)]
fn read_available(pipe: &mut impl Read, buffer: &mut [u8]) -> io::Result<PipeRead> {
match pipe.read(buffer) {
Ok(0) => Ok(PipeRead::Eof),
Ok(count) => Ok(PipeRead::Data(count)),
Err(error)
if matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
) =>
{
Ok(PipeRead::Pending)
}
Err(error) => Err(error),
}
}
#[cfg(windows)]
fn read_available(
pipe: &mut (impl Read + std::os::windows::io::AsRawHandle),
buffer: &mut [u8],
) -> io::Result<PipeRead> {
use std::ptr;
use windows_sys::Win32::{
Foundation::{ERROR_BROKEN_PIPE, ERROR_HANDLE_EOF},
System::Pipes::PeekNamedPipe,
};
let mut available = 0;
// SAFETY: this is a live pipe; only the available-byte count is requested.
if unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
ptr::null_mut(),
0,
ptr::null_mut(),
&mut available,
ptr::null_mut(),
)
} == 0
{
let error = io::Error::last_os_error();
return match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_BROKEN_PIPE | ERROR_HANDLE_EOF) => Ok(PipeRead::Eof),
_ => Err(error),
};
}
if available == 0 {
return Ok(PipeRead::Pending);
}
let maximum = buffer.len().min(available as usize);
match pipe.read(&mut buffer[..maximum]) {
Ok(0) => Ok(PipeRead::Eof),
Ok(count) => Ok(PipeRead::Data(count)),
Err(error) if error.kind() == io::ErrorKind::Interrupted => Ok(PipeRead::Pending),
Err(error) => Err(error),
}
}
fn poll_child(child: &mut Child) -> io::Result<Option<ExitStatus>> {
match child.try_wait() {
Err(error) if error.kind() == io::ErrorKind::Interrupted => Ok(None),
result => result,
}
}
fn cleanup(child: Child, tree: &mut ProcessTree) -> io::Result<()> {
let started = Instant::now();
let termination = tree.terminate();
let reaping = terminate_and_reap(child, started);
let descendants = tree.finish(started);
// Always attempt reaping even when group/job termination failed.
termination.and(reaping).and(descendants)
}
fn terminate_and_reap(mut child: Child, started: Instant) -> io::Result<()> {
match poll_child(&mut child) {
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(error) => {
if let Err(kill_error) = child.kill() {
log::error!("Failed to kill probe child after wait failure: {kill_error}");
}
reap_later(child);
return Err(error);
}
}
let kill_error = child.kill().err();
loop {
match poll_child(&mut child) {
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(error) => {
reap_later(child);
return Err(error);
}
}
if started.elapsed() >= CLEANUP_TIMEOUT {
reap_later(child);
return Err(kill_error.unwrap_or_else(|| {
io::Error::new(
io::ErrorKind::TimedOut,
"direct child did not exit within cleanup allowance",
)
}));
}
thread::sleep(POLL_INTERVAL);
}
}
fn reap_later(mut child: Child) {
let pid = child.id();
// Only exceptional OS cleanup failures use a waiter; it owns no output pipes.
if let Err(error) = thread::Builder::new()
.name("pet-child-reaper".into())
.spawn(move || {
if let Err(error) = child.wait() {
log::error!("Failed to reap probe child: {error}");
}
})
{
log::error!("Failed to start probe child reaper for PID {pid}; reaping cannot be guaranteed: {error}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{fs, io::Write, path::Path, sync::Mutex};
const FIXTURE_ENV: &str = "PET_CAPTURE_FIXTURE";
const LARGE_OUTPUT: usize = 128 * 1024;
static FIXTURES: Mutex<()> = Mutex::new(());
fn fixture_command(mode: &str) -> Command {
let mut command = crate::executable::new_silent_command(std::env::current_exe().unwrap());
command.args([
"--exact",
"process::tests::subprocess_fixture",
"--nocapture",
]);
command.env(FIXTURE_ENV, mode);
command
}
#[test]
fn subprocess_fixture() {
let Ok(mode) = std::env::var(FIXTURE_ENV) else {
return;
};
match mode.as_str() {
"quiet" => std::process::exit(0),
"stdout" | "stderr" | "both" | "nonzero" => {
if let Some(pid_file) = std::env::var_os("PET_CAPTURE_PID") {
fs::write(pid_file, std::process::id().to_string()).unwrap();
}
if mode != "stderr" {
io::stdout().write_all(&vec![0xfe; LARGE_OUTPUT]).unwrap();
}
if mode != "stdout" {
io::stderr().write_all(&vec![0xff; LARGE_OUTPUT]).unwrap();
}
std::process::exit(if mode == "nonzero" { 23 } else { 0 });
}
"hang" | "noisy-hang" => {
fs::write(
std::env::var_os("PET_CAPTURE_PID").unwrap(),
std::process::id().to_string(),
)
.unwrap();
let started = Instant::now();
while started.elapsed() < Duration::from_secs(30) {
if mode == "noisy-hang" {
io::stdout().write_all(&[0xfe; 1024]).unwrap();
io::stdout().flush().unwrap();
}
thread::sleep(Duration::from_millis(10));
}
}
"inherit" | "tree-hang" | "tree-limit" | "tree-nonzero" | "tree-no-pipes"
| "escape" => {
if let Some(pid_file) = std::env::var_os("PET_CAPTURE_PID") {
fs::write(pid_file, std::process::id().to_string()).unwrap();
}
let mut command = fixture_command("descendant");
if mode == "tree-no-pipes" {
command.stdout(Stdio::null()).stderr(Stdio::null());
} else {
command.stdout(Stdio::inherit()).stderr(Stdio::inherit());
}
if mode == "escape" {
command.env("PET_CAPTURE_ESCAPE", "1");
}
let mut descendant = command.spawn().unwrap();
let directory = std::env::var_os("PET_CAPTURE_DIRECTORY").unwrap();
let ready = Path::new(&directory).join("ready");
let started = Instant::now();
while !ready.exists() {
if started.elapsed() > Duration::from_secs(10) {
descendant.kill().unwrap();
descendant.wait().unwrap();
panic!("descendant fixture did not start");
}
thread::sleep(POLL_INTERVAL);
}
if mode == "tree-hang" {
thread::sleep(Duration::from_secs(30));
}
if mode == "tree-limit" {
io::stdout().write_all(&vec![0xfe; LARGE_OUTPUT]).unwrap();
}
std::process::exit(if mode == "tree-nonzero" { 23 } else { 0 });
}
"nested" => {
let result =
output(&mut fixture_command("inherit"), Duration::from_secs(5)).unwrap();
assert!(result.status.success());
std::process::exit(0);
}
"descendant" => {
let directory = std::env::var_os("PET_CAPTURE_DIRECTORY").unwrap();
let directory = Path::new(&directory);
#[cfg(unix)]
if std::env::var_os("PET_CAPTURE_ESCAPE").is_some() {
// SAFETY: this deliberately escaped, single fixture process
// is cleaned up by the release handshake, not by PET.
assert_ne!(unsafe { libc::setsid() }, -1);
}
let lease = fs::File::create(directory.join("lease")).unwrap();
lease.lock().unwrap();
fs::write(directory.join("ready"), b"ready").unwrap();
let started = Instant::now();
while !directory.join("release").exists()
&& started.elapsed() < Duration::from_secs(10)
{
thread::sleep(POLL_INTERVAL);
}
fs::write(directory.join("done"), b"done").unwrap();
std::process::exit(0);
}
_ => panic!("unknown fixture mode: {mode}"),
}
std::process::exit(0);
}
#[test]
fn drains_more_than_pipe_capacity_on_either_or_both_streams() {
let _guard = FIXTURES.lock().unwrap();
for mode in ["stdout", "stderr", "both", "nonzero"] {
let started = Instant::now();
let result = output(&mut fixture_command(mode), Duration::from_secs(10)).unwrap();
assert!(started.elapsed() < Duration::from_secs(10), "{mode}");
assert_eq!(
result.status.code(),
Some(if mode == "nonzero" { 23 } else { 0 })
);
let expected_stdout = if mode == "stderr" { 0 } else { LARGE_OUTPUT };
let expected_stderr = if mode == "stdout" { 0 } else { LARGE_OUTPUT };
// libtest emits a small ASCII preamble before the fixture starts.
let binary_start = result
.stdout
.iter()
.position(|b| *b == 0xfe)
.unwrap_or(result.stdout.len());
assert!(result.stdout[..binary_start].is_ascii());
assert_eq!(&result.stdout[binary_start..], vec![0xfe; expected_stdout]);
assert_eq!(result.stderr, vec![0xff; expected_stderr]);
}
}
#[test]
fn timeout_and_capture_limit_reap_direct_child() {
let _guard = FIXTURES.lock().unwrap();
let directory = tempfile::tempdir().unwrap();
let pid = directory.path().join("pid");
let mut command = fixture_command("hang");
command.env("PET_CAPTURE_PID", &pid);
let started = Instant::now();
let error = output(&mut command, Duration::from_secs(2)).unwrap_err();
assert!(matches!(error, ProcessError::Timeout(_)), "{error}");
assert!(started.elapsed() < Duration::from_secs(5));
let pid: u32 = fs::read_to_string(pid)
.expect("fixture must reach its hang")
.parse()
.unwrap();
assert_child_reaped(pid);
let limit_pid = directory.path().join("limit-pid");
let mut command = fixture_command("both");
command.env("PET_CAPTURE_PID", &limit_pid);
assert!(matches!(
output_with_limit(&mut command, Duration::from_secs(10), 100),
Err(ProcessError::OutputLimit(100))
));
let pid = fs::read_to_string(limit_pid).unwrap().parse().unwrap();
assert_child_reaped(pid);
}
#[cfg(unix)]
fn assert_child_reaped(pid: u32) {
let mut status = 0;
// SAFETY: waitpid targets only our already-reaped fixture child.
assert_eq!(
unsafe { libc::waitpid(pid as libc::pid_t, &mut status, libc::WNOHANG) },
-1
);
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(libc::ECHILD)
);
}
#[cfg(windows)]
fn assert_child_reaped(pid: u32) {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use windows_sys::Win32::{
Foundation::{ERROR_INVALID_PARAMETER, WAIT_OBJECT_0},
System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE},
};
// SAFETY: OpenProcess returns either a uniquely owned handle or null.
let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
if handle.is_null() {
assert_eq!(
io::Error::last_os_error().raw_os_error(),
Some(ERROR_INVALID_PARAMETER as i32)
);
return;
}
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
// SAFETY: the process handle stays alive through this nonblocking wait.
assert_eq!(
unsafe { WaitForSingleObject(handle.as_raw_handle(), 0) },
WAIT_OBJECT_0
);
}
struct ReleaseDescendant(tempfile::TempDir);
impl ReleaseDescendant {
fn assert_terminated(&self, mut waiting: Option<std::sync::mpsc::SyncSender<()>>) {
assert!(
self.0.path().join("ready").exists(),
"descendant never started"
);
let lease = fs::File::open(self.0.path().join("lease")).unwrap();
let started = Instant::now();
loop {
match lease.try_lock() {
Ok(()) => break,
Err(fs::TryLockError::WouldBlock) => {
if let Some(waiting) = waiting.take() {
waiting.send(()).expect("lease wait observer dropped");
}
assert!(
started.elapsed() < CLEANUP_TIMEOUT,
"descendant still holds its lease"
);
thread::sleep(POLL_INTERVAL);
}
Err(error) => panic!("failed to inspect descendant lease: {error}"),
}
}
assert!(
!self.0.path().join("done").exists(),
"descendant exited on its own instead of being terminated"
);
}
}
#[test]
fn termination_check_waits_for_the_descendant_lease() {
use std::sync::{mpsc, Arc};
let directory = Arc::new(ReleaseDescendant(tempfile::tempdir().unwrap()));
let lease = fs::File::create(directory.0.path().join("lease")).unwrap();
lease.lock().unwrap();
fs::write(directory.0.path().join("ready"), b"ready").unwrap();
let (waiting_tx, waiting_rx) = mpsc::sync_channel(1);
let waiting_directory = directory.clone();
let waiter = thread::spawn(move || waiting_directory.assert_terminated(Some(waiting_tx)));
waiting_rx
.recv_timeout(CLEANUP_TIMEOUT)
.expect("termination check did not observe the held lease");
assert!(!waiter.is_finished());
lease.unlock().unwrap();
waiter.join().unwrap();
}
impl ReleaseDescendant {
fn release(&self) -> io::Result<()> {
fs::write(self.0.path().join("release"), b"release")?;
if !self.0.path().join("ready").exists() {
return Ok(());
}
let lease = fs::File::open(self.0.path().join("lease"))?;
let started = Instant::now();
loop {
match lease.try_lock() {
Ok(()) => return Ok(()),
Err(fs::TryLockError::WouldBlock) => {
if started.elapsed() >= Duration::from_secs(12) {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"descendant did not acknowledge cleanup",
));
}
thread::sleep(POLL_INTERVAL);
}
Err(fs::TryLockError::Error(error)) => return Err(error),
}
}
}
}
impl Drop for ReleaseDescendant {
fn drop(&mut self) {
if let Err(error) = self.release() {
eprintln!("Failed to clean up descendant fixture: {error}");
}
}
}
#[test]
fn root_exit_terminates_descendants_with_or_without_inherited_pipes() {
let _guard = FIXTURES.lock().unwrap();
for mode in ["inherit", "tree-no-pipes", "tree-nonzero"] {
let directory = ReleaseDescendant(tempfile::tempdir().unwrap());
let pid = directory.0.path().join("root-pid");
let mut command = fixture_command(mode);
command
.env("PET_CAPTURE_DIRECTORY", directory.0.path())
.env("PET_CAPTURE_PID", &pid);
let started = Instant::now();
let result = output(&mut command, Duration::from_secs(5)).unwrap();
assert_eq!(
result.status.code(),
Some(if mode == "tree-nonzero" { 23 } else { 0 })
);
assert!(started.elapsed() < Duration::from_secs(5));
directory.assert_terminated(None);
assert_child_reaped(fs::read_to_string(pid).unwrap().parse().unwrap());
}
}
#[test]
fn timeout_and_output_limit_terminate_descendants() {
let _guard = FIXTURES.lock().unwrap();
for mode in ["tree-hang", "tree-limit"] {
let directory = ReleaseDescendant(tempfile::tempdir().unwrap());
let mut command = fixture_command(mode);
command.env("PET_CAPTURE_DIRECTORY", directory.0.path());
let started = Instant::now();
let error = output_with_limit(&mut command, Duration::from_secs(2), 4096).unwrap_err();
if mode == "tree-hang" {
assert!(matches!(error, ProcessError::Timeout(_)), "{error}");
} else {
assert!(matches!(error, ProcessError::OutputLimit(4096)), "{error}");
}
assert!(started.elapsed() < Duration::from_secs(5));
directory.assert_terminated(None);
}
}
#[cfg(unix)]
#[test]
fn escaped_descendant_cannot_extend_capture_deadline() {
let _guard = FIXTURES.lock().unwrap();
let directory = ReleaseDescendant(tempfile::tempdir().unwrap());
let mut command = fixture_command("escape");
command.env("PET_CAPTURE_DIRECTORY", directory.0.path());
let started = Instant::now();
let error = output(&mut command, Duration::from_secs(2)).unwrap_err();
assert!(
matches!(error, ProcessError::IncompleteOutput(status) if status.success()),
"{error}"
);
assert!(started.elapsed() < Duration::from_secs(5));
assert!(!directory.0.path().join("done").exists());
directory.release().unwrap();
assert!(directory.0.path().join("done").exists());
}
#[cfg(windows)]
#[test]
fn nested_job_ownership_terminates_descendants() {
let _guard = FIXTURES.lock().unwrap();
let directory = ReleaseDescendant(tempfile::tempdir().unwrap());
let mut command = fixture_command("nested");
command.env("PET_CAPTURE_DIRECTORY", directory.0.path());
assert!(output(&mut command, Duration::from_secs(10))
.unwrap()
.status
.success());
directory.assert_terminated(None);
}
#[cfg(windows)]
#[test]
fn failure_after_job_assignment_reaps_suspended_child() {
let _guard = FIXTURES.lock().unwrap();
let directory = tempfile::tempdir().unwrap();
let pid_file = directory.path().join("pid");
let mut command = fixture_command("hang");
command.env("PET_CAPTURE_PID", &pid_file);
let mut pid = 0;
let error = output_with_setup(&mut command, Duration::from_secs(2), 100, |tree, child| {
tree.assign(child)?;
pid = child.id();
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"injected resume failure",
))
})
.unwrap_err();
assert!(matches!(error, ProcessError::Ownership(_)), "{error}");
assert!(error.to_string().contains("injected resume failure"));
assert!(
!pid_file.exists(),
"suspended fixture executed before resume"
);
assert_child_reaped(pid);
}
#[cfg(windows)]
#[test]
fn runner_explicitly_replaces_windows_creation_flags() {
use std::os::windows::{io::AsRawHandle, process::CommandExt};
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, GetPriorityClass, BELOW_NORMAL_PRIORITY_CLASS, IDLE_PRIORITY_CLASS,
NORMAL_PRIORITY_CLASS,
};
let _guard = FIXTURES.lock().unwrap();
// SAFETY: the pseudo-handle is valid for querying our process priority.
let parent_priority = unsafe { GetPriorityClass(GetCurrentProcess()) };
assert_ne!(parent_priority, 0);
let expected = match parent_priority {
IDLE_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS => parent_priority,
_ => NORMAL_PRIORITY_CLASS,
};
let requested = if expected == IDLE_PRIORITY_CLASS {
BELOW_NORMAL_PRIORITY_CLASS
} else {
IDLE_PRIORITY_CLASS
};
let mut command = fixture_command("quiet");
command.creation_flags(requested);
let mut actual_priority = 0;
let result =
output_with_setup(&mut command, Duration::from_secs(2), 1024, |tree, child| {
// SAFETY: the still-suspended child handle is live.
actual_priority = unsafe { GetPriorityClass(child.as_raw_handle()) };
tree.attach(child)
})
.unwrap();
assert!(result.status.success());
assert_eq!(actual_priority, expected);
}
struct FixtureChild(Child);
impl Drop for FixtureChild {
fn drop(&mut self) {
if self.0.try_wait().unwrap().is_none() {
self.0.kill().unwrap();
}
self.0.wait().unwrap();
}
}
#[test]
fn cleanup_does_not_terminate_an_unrelated_process() {
let _guard = FIXTURES.lock().unwrap();
let directory = tempfile::tempdir().unwrap();
let mut unrelated = FixtureChild(
fixture_command("descendant")
.env("PET_CAPTURE_DIRECTORY", directory.path())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let started = Instant::now();
while !directory.path().join("ready").exists() {
assert!(
started.elapsed() < Duration::from_secs(5),
"unrelated fixture did not start"
);
assert!(unrelated.0.try_wait().unwrap().is_none());
thread::sleep(POLL_INTERVAL);
}
let owned = ReleaseDescendant(tempfile::tempdir().unwrap());
let mut command = fixture_command("inherit");
command.env("PET_CAPTURE_DIRECTORY", owned.0.path());
assert!(output(&mut command, Duration::from_secs(5))
.unwrap()
.status
.success());
owned.assert_terminated(None);
assert!(unrelated.0.try_wait().unwrap().is_none());
let lease = fs::File::open(directory.path().join("lease")).unwrap();
assert!(matches!(
lease.try_lock(),
Err(fs::TryLockError::WouldBlock)
));
// FixtureChild is dropped before its directory and reaps this control process.
}
#[test]
fn setup_failure_reaps_child_and_preserves_error() {
let _guard = FIXTURES.lock().unwrap();
let mut pid = 0;
let error = output_with_setup(
&mut fixture_command("quiet"),
Duration::from_secs(2),
100,
|tree, child| {
// Unix ownership is established before exec; Windows assignment
// and resume normally happen here. Exercise an early setup error.
#[cfg(unix)]
tree.attach(child)?;
#[cfg(windows)]
let _ = tree;
pid = child.id();
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"injected ownership failure",
))
},
)
.unwrap_err();
assert!(matches!(error, ProcessError::Ownership(_)), "{error}");
assert!(error.to_string().contains("injected ownership failure"));
assert_child_reaped(pid);
}
#[test]
fn setup_failure_remains_primary_when_shutdown_wins_completion() {
let _guard = FIXTURES.lock().unwrap();
let supervisor = Supervisor::new();
let mut pid = 0;
let error = output_with_supervisor_setup(
&mut fixture_command("quiet"),
Duration::from_secs(2),
100,
&supervisor,
|tree, child| {
#[cfg(unix)]
tree.attach(child)?;
#[cfg(windows)]
let _ = tree;
pid = child.id();
let shutdown = supervisor.shutdown(Duration::ZERO).unwrap_err();
assert_eq!(shutdown.kind(), io::ErrorKind::TimedOut);
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"injected ownership failure after shutdown",
))
},
)
.unwrap_err();
assert!(matches!(error, ProcessError::Ownership(_)), "{error}");
assert!(error
.to_string()
.contains("injected ownership failure after shutdown"));
assert_child_reaped(pid);