Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions crates/sendbox-runtime/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,13 +497,15 @@ impl RunningProcess {
.child
.as_mut()
.ok_or_else(|| RuntimeError::Provider("process was already reaped".to_owned()))?;
tokio::select! {
result = child.wait() => result.map_err(RuntimeError::Wait),
let status = tokio::select! {
result = child.wait() => result.map_err(RuntimeError::Wait)?,
() = tokio::time::sleep(grace) => {
force_kill_process(Some(child), self.process_group)?;
child.wait().await.map_err(RuntimeError::Wait)
child.wait().await.map_err(RuntimeError::Wait)?
}
}
};
kill_surviving_group_members(self.process_group)?;
Ok(status)
}
}

Expand Down Expand Up @@ -860,6 +862,30 @@ fn force_kill_process(
.map_err(RuntimeError::Wait)
}

/// A descendant forked while the group SIGTERM is in flight can miss it, outlive the
/// leader, and keep the output pipes open. macOS reports EPERM when only exiting
/// members remain, so that is treated like an already empty group.
#[cfg(unix)]
fn kill_surviving_group_members(process_group: Option<i32>) -> Result<(), RuntimeError> {
match send_process_group_signal(process_group, ProcessSignal::Kill) {
Err(RuntimeError::Signal { source, .. })
if matches!(
source.raw_os_error(),
Some(code) if code == nix::errno::Errno::ESRCH as i32
|| code == nix::errno::Errno::EPERM as i32
) =>
{
Ok(())
}
other => other,
}
}

#[cfg(not(unix))]
fn kill_surviving_group_members(_process_group: Option<i32>) -> Result<(), RuntimeError> {
Ok(())
}

#[cfg(unix)]
fn ignore_missing_group(result: Result<(), RuntimeError>) -> Result<(), RuntimeError> {
match result {
Expand Down
14 changes: 14 additions & 0 deletions crates/sendbox-testkit/src/bin/process_fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,20 @@ fn run() -> Result<(), String> {
io::stdout().flush().map_err(|error| error.to_string())?;
thread::sleep(Duration::from_millis(milliseconds));
}
"spawn-term-ignoring-child" => {
let milliseconds = parse_u64(arguments.next(), "milliseconds")?;
// The child inherits stdout and stderr and reports its PID only after it ignores
// SIGTERM, so it outlives the leader while holding the output pipes open.
Command::new("/bin/sh")
.arg("-c")
.arg(r#"trap '' TERM; echo "$$"; exec "$0" sleep "$1""#)
.arg(env::current_exe().map_err(|error| error.to_string())?)
.arg(milliseconds.to_string())
.stdin(Stdio::null())
.spawn()
.map_err(|error| error.to_string())?;
thread::sleep(Duration::from_millis(milliseconds));
}
other => return Err(format!("unknown mode `{other}`")),
}
Ok(())
Expand Down
134 changes: 70 additions & 64 deletions crates/sendbox-testkit/tests/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,29 +445,16 @@ async fn named_program_resolver_must_return_an_absolute_path() {
}

#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_child_processes_in_the_same_group() {
use nix::{errno::Errno, sys::signal::kill, unistd::Pid};

let cancellation = CancellationToken::new();
let mut process = runner()
.spawn(
fixture_command("spawn-child", ["5000".to_owned()]),
ProcessOptions {
termination_grace: Duration::from_millis(25),
output_channel_capacity: 4,
..ProcessOptions::default()
},
&cancellation,
)
.await
.expect("spawn process group");
async fn read_child_pid(
process: &mut sendbox_runtime::RunningProcess,
cancellation: &CancellationToken,
) -> i32 {
let mut subscription = process
.take_output_subscription()
.expect("output subscription");
let mut child_pid_bytes = Vec::new();
while !child_pid_bytes.contains(&b'\n') {
let event = tokio::time::timeout(Duration::from_secs(5), subscription.next(&cancellation))
let event = tokio::time::timeout(Duration::from_secs(5), subscription.next(cancellation))
.await
.expect("child pid output timeout")
.expect("child pid output")
Expand All @@ -481,35 +468,86 @@ async fn cancellation_kills_child_processes_in_the_same_group() {
child_pid_bytes.extend(bytes);
}
}
let child_pid = String::from_utf8(child_pid_bytes)
String::from_utf8(child_pid_bytes)
.expect("child pid UTF-8")
.trim()
.parse::<i32>()
.expect("child pid");
cancellation.cancel();
let outcome = process
.wait(&cancellation)
.await
.expect("cancel process group");
assert_eq!(outcome.termination, TerminationReason::Cancelled);
.expect("child pid")
}

#[cfg(unix)]
async fn assert_process_exits(pid: i32) {
use nix::{errno::Errno, sys::signal::kill, unistd::Pid};

let deadline = Instant::now() + Duration::from_secs(2);
loop {
match kill(Pid::from_raw(child_pid), None) {
match kill(Pid::from_raw(pid), None) {
Err(Errno::ESRCH) => break,
Ok(()) | Err(Errno::EPERM) if Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(20)).await;
}
result => panic!("child process {child_pid} survived group cleanup: {result:?}"),
result => panic!("process {pid} survived process group cleanup: {result:?}"),
}
}
}

#[cfg(unix)]
#[tokio::test]
async fn dropping_running_process_synchronously_kills_its_process_group() {
use nix::{errno::Errno, sys::signal::kill, unistd::Pid};
async fn cancellation_kills_child_processes_in_the_same_group() {
let cancellation = CancellationToken::new();
let mut process = runner()
.spawn(
fixture_command("spawn-child", ["5000".to_owned()]),
ProcessOptions {
termination_grace: Duration::from_millis(25),
output_channel_capacity: 4,
..ProcessOptions::default()
},
&cancellation,
)
.await
.expect("spawn process group");
let child_pid = read_child_pid(&mut process, &cancellation).await;
cancellation.cancel();
let outcome = process
.wait(&cancellation)
.await
.expect("cancel process group");
assert_eq!(outcome.termination, TerminationReason::Cancelled);

assert_process_exits(child_pid).await;
}

#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_group_members_that_outlive_the_leader() {
let cancellation = CancellationToken::new();
let mut process = runner()
.spawn(
fixture_command("spawn-term-ignoring-child", ["5000".to_owned()]),
ProcessOptions {
termination_grace: Duration::from_secs(2),
output_channel_capacity: 4,
..ProcessOptions::default()
},
&cancellation,
)
.await
.expect("spawn process group");
let child_pid = read_child_pid(&mut process, &cancellation).await;
cancellation.cancel();
let outcome = tokio::time::timeout(Duration::from_secs(3), process.wait(&cancellation))
.await
.expect("a surviving group member must not hold the output pipes open")
.expect("cancel process group");
assert_eq!(outcome.termination, TerminationReason::Cancelled);

assert_process_exits(child_pid).await;
}

#[cfg(unix)]
#[tokio::test]
async fn dropping_running_process_synchronously_kills_its_process_group() {
let cancellation = CancellationToken::new();
let mut process = runner()
.spawn(
Expand All @@ -523,43 +561,11 @@ async fn dropping_running_process_synchronously_kills_its_process_group() {
.await
.expect("spawn process group");
let parent_pid = i32::try_from(process.pid()).expect("parent pid");
let mut subscription = process
.take_output_subscription()
.expect("output subscription");
let mut child_pid_bytes = Vec::new();
while !child_pid_bytes.contains(&b'\n') {
let event = tokio::time::timeout(Duration::from_secs(5), subscription.next(&cancellation))
.await
.expect("child pid output timeout")
.expect("child pid output")
.expect("child pid event");
if let OutputEvent::Data {
stream: OutputStream::Stdout,
bytes,
..
} = event
{
child_pid_bytes.extend(bytes);
}
}
let child_pid = String::from_utf8(child_pid_bytes)
.expect("child pid UTF-8")
.trim()
.parse::<i32>()
.expect("child pid");
let child_pid = read_child_pid(&mut process, &cancellation).await;

drop(process);

for pid in [parent_pid, child_pid] {
let deadline = Instant::now() + Duration::from_secs(2);
loop {
match kill(Pid::from_raw(pid), None) {
Err(Errno::ESRCH) => break,
Ok(()) | Err(Errno::EPERM) if Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(20)).await;
}
result => panic!("process {pid} survived RunningProcess drop: {result:?}"),
}
}
assert_process_exits(pid).await;
}
}
7 changes: 6 additions & 1 deletion docs/architecture/runtime-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,12 @@ pipe reads. Captures report total and truncated bytes.
Unix children start in a new process group using the standard library
`process_group(0)` configuration. Signals use the safe `nix::killpg` API.
Cancellation and timeout send `SIGTERM`, wait the configured grace period, then
send `SIGKILL` and reap. `RunningProcess::drop` directly sends `SIGKILL` to the
send `SIGKILL` and reap. Once the leader is reaped, the runner sends `SIGKILL`
to the group again, so a descendant that missed `SIGTERM` (for example one
forked while the signal was in flight, which macOS can leave alive) cannot keep
the output pipes open and stall the drain. `ESRCH` and macOS's `EPERM` for a
group with only exiting members mean nothing is left to kill.
`RunningProcess::drop` directly sends `SIGKILL` to the
group synchronously as a last-resort fallback; it does not depend on an async
command channel.

Expand Down
Loading