Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

perf(guest): skip SIGTERM wait when container init ignores it (#3258)

lfld287ca53a8d2c31b
diff --git a/src/guest/README.md b/src/guest/README.md
index 96993df36..16d094dcd 100644
--- a/src/guest/README.md
+++ b/src/guest/README.md
@@ -139,6 +139,18 @@ The zygote resets its inherited panic hook before creating container PID namespa
Failed fatal diagnostics do not abort the reset path; a rejected reset parks init for host cleanup.
Successful container exit and host-driven Shutdown keep their existing exit-record and RPC ordering.
+## Container shutdown
+
+`Container::shutdown` inspects the container init process's `/proc/<pid>/status` signal masks before waiting on `SIGTERM`:
+
+- `SIGTERM` (signal 15, bit 14 / `0x4000`) is delivered to container PID 1 (`SIGNAL_UNKILLABLE` in its PID namespace) only when `SigCgt` or `SigBlk` has bit 14 set.
+- When neither `SigCgt` nor `SigBlk` handles `SIGTERM` (for example `SIG_DFL` or `SIG_IGN`), or when `timeout_ms == 0`, `Container::shutdown` skips `SIGTERM` and its polling loop and sends `SIGKILL` immediately.
+- `LibContainer::load` marks containers without a PID as `Stopped` (`!container.can_kill()`), so `Container::shutdown` returns `Ok(())` without signaling; if `/proc/<pid>/status` cannot be read or parsed for a running init, shutdown falls back conservatively to sending `SIGTERM` and waiting up to `timeout_ms`.
+- This check is based on container PID 1's signal disposition (after `ExecutionRegistry::shutdown_all` has already stopped managed exec processes); when `SIGTERM` is skipped, `Container::shutdown` sends `SIGKILL` directly to the container cgroup, so unmanaged descendants under a non-`exec` shell wrapper do not receive `SIGTERM`.
+- Guest `Shutdown` Step 2b (`exit_slot` -> `exit_file`, yielding exit code `137` on `SIGKILL`) and Step 3 (`sync()`) remain unchanged.
+
+Run `make test:unit:guest FILTER=container::lifecycle::shutdown_tests` on Linux to verify `/proc/<pid>/status` parsing and real-process shutdown behavior.
+
## Native qualification
```sh
diff --git a/src/guest/src/container/lifecycle.rs b/src/guest/src/container/lifecycle.rs
index 7c8852001..0624c06ff 100644
--- a/src/guest/src/container/lifecycle.rs
+++ b/src/guest/src/container/lifecycle.rs
@@ -34,10 +34,18 @@ const DEFAULT_INIT_PTY: PtyConfig = PtyConfig {
modes: Vec::new(),
};
+/// Bit mask for SIGTERM (15) in `/proc/<pid>/status` hex signal masks.
+/// Linux signal masks are 0-indexed (`bit = signo - 1`, so SIGTERM = 15 -> bit 14 = `0x4000`).
+const SIGTERM_MASK: u64 = 1u64 << (nix::libc::SIGTERM as u32 - 1);
+
#[cfg(test)]
#[path = "tests/pty_init.rs"]
mod pty_init_tests;
+#[cfg(test)]
+#[path = "tests/shutdown.rs"]
+mod shutdown_tests;
+
/// OCI container
///
/// Manages the lifecycle of an OCI-compliant container using libcontainer.
@@ -621,19 +629,26 @@ impl Container {
result
}
- /// Gracefully shutdown the container.
+ /// Shutdown the container, using SIGTERM when init handles it or SIGKILL directly otherwise.
///
- /// Sends SIGTERM first, waits for exit with timeout, then SIGKILL if needed.
- /// Sets the `shutdown_called` flag to prevent double-kill in Drop.
+ /// Checks `/proc/<pid>/status` (`SigCgt` and `SigBlk`) for init: when `timeout_ms > 0`
+ /// and init catches or blocks `SIGTERM` (or `/proc/<pid>/status` cannot be read/parsed),
+ /// sends `SIGTERM`, polls up to `timeout_ms`, then sends `SIGKILL` if still running.
+ /// Otherwise skips `SIGTERM` and sends `SIGKILL` immediately.
+ /// Sets the `is_shutdown` flag to prevent double-kill in `Drop`.
///
/// # Arguments
///
- /// - `timeout_ms`: Maximum time to wait for graceful exit before SIGKILL
+ /// - `timeout_ms`: Maximum time to wait for graceful exit before `SIGKILL`
///
/// # Returns
///
- /// Ok(()) on successful shutdown, or if container was already stopped.
+ /// `Ok(())` on successful shutdown, or if the container was already stopped.
pub fn shutdown(&self, timeout_ms: u64) -> BoxliteResult<()> {
+ self.shutdown_with(timeout_ms, true)
+ }
+
+ fn shutdown_with(&self, timeout_ms: u64, kill_all: bool) -> BoxliteResult<()> {
self.is_shutdown
.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -651,25 +666,37 @@ impl Container {
return Ok(());
}
- // Step 1: Send SIGTERM
- tracing::info!(container_id = %self.id, "Sending SIGTERM to container");
- let sigterm = Signal::try_from(15).expect("SIGTERM (15) is a valid signal");
- let _ = container.kill(sigterm, true);
+ let should_try_sigterm = timeout_ms > 0 && container.pid().is_none_or(pid_handles_sigterm);
- // Step 2: Wait for graceful exit with timeout
- let start = std::time::Instant::now();
- while start.elapsed().as_millis() < timeout_ms as u128 {
- if !self.is_running() {
- tracing::info!(container_id = %self.id, "Container exited gracefully");
- return Ok(());
+ if should_try_sigterm {
+ // Step 1: Send SIGTERM
+ tracing::info!(container_id = %self.id, "Sending SIGTERM to container");
+ let sigterm = Signal::try_from(15).expect("SIGTERM (15) is a valid signal");
+ let _ = container.kill(sigterm, kill_all);
+
+ // Step 2: Wait for graceful exit with timeout
+ let start = std::time::Instant::now();
+ while start.elapsed().as_millis() < timeout_ms as u128 {
+ if !self.is_running() {
+ tracing::info!(container_id = %self.id, "Container exited gracefully");
+ return Ok(());
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
}
- std::thread::sleep(std::time::Duration::from_millis(100));
+
+ // Step 3: SIGKILL if still running
+ tracing::warn!(container_id = %self.id, "Container didn't exit gracefully, sending SIGKILL");
+ } else {
+ tracing::info!(
+ container_id = %self.id,
+ timeout_ms,
+ init_pid = ?container.pid(),
+ "Skipping SIGTERM wait: init does not handle SIGTERM or timeout is 0, sending SIGKILL"
+ );
}
- // Step 3: SIGKILL if still running
- tracing::warn!(container_id = %self.id, "Container didn't exit gracefully, sending SIGKILL");
let sigkill = Signal::try_from(9).expect("SIGKILL (9) is a valid signal");
- let _ = container.kill(sigkill, true);
+ let _ = container.kill(sigkill, kill_all);
Ok(())
}
@@ -679,6 +706,58 @@ impl Container {
}
}
+/// Parse `/proc/<pid>/status` text and return whether SIGTERM is caught (`SigCgt`)
+/// or blocked (`SigBlk`). Returns `None` if either field is missing or invalid hex.
+fn parse_sigterm_handled(status: &str) -> Option<bool> {
+ let mut sigcgt: Option<u64> = None;
+ let mut sigblk: Option<u64> = None;
+
+ for line in status.lines() {
+ let Some((key, val)) = line.split_once(':') else {
+ continue;
+ };
+ match key {
+ "SigCgt" => {
+ sigcgt = Some(u64::from_str_radix(val.trim(), 16).ok()?);
+ }
+ "SigBlk" => {
+ sigblk = Some(u64::from_str_radix(val.trim(), 16).ok()?);
+ }
+ _ => continue,
+ }
+ if sigcgt.is_some() && sigblk.is_some() {
+ break;
+ }
+ }
+
+ Some(((sigcgt? | sigblk?) & SIGTERM_MASK) != 0)
+}
+
+/// Read a `/proc/<pid>/status`-formatted file; returns `true` (conservative fallback)
+/// on I/O or parse failure so graceful SIGTERM shutdown is preserved when uncertain.
+fn pid_handles_sigterm_at(status_path: &Path) -> bool {
+ let content = match std::fs::read_to_string(status_path) {
+ Ok(c) => c,
+ Err(error) => {
+ tracing::debug!(path = %status_path.display(), %error, "Failed to read proc status, assuming SIGTERM is handled");
+ return true;
+ }
+ };
+
+ match parse_sigterm_handled(&content) {
+ Some(handled) => handled,
+ None => {
+ tracing::debug!(path = %status_path.display(), "Failed to parse SigCgt/SigBlk, assuming SIGTERM is handled");
+ true
+ }
+ }
+}
+
+/// Thin wrapper over `pid_handles_sigterm_at` for `/proc/{pid}/status`.
+fn pid_handles_sigterm(pid: nix::unistd::Pid) -> bool {
+ pid_handles_sigterm_at(&PathBuf::from(format!("/proc/{pid}/status")))
+}
+
fn init_pipe_handle(
pid: nix::unistd::Pid,
stdin: std::os::fd::OwnedFd,
diff --git a/src/guest/src/container/tests/shutdown.rs b/src/guest/src/container/tests/shutdown.rs
new file mode 100644
index 000000000..2dbd353d7
--- /dev/null
+++ b/src/guest/src/container/tests/shutdown.rs
@@ -0,0 +1,376 @@
+//! Unit and Linux process-behavior tests for `Container::shutdown` and `/proc/<pid>/status` parsing.
+
+use super::*;
+use libcontainer::container::{ContainerStatus, State};
+use nix::sys::signal::{killpg, Signal as NixSignal};
+use nix::unistd::Pid;
+use std::io::Read;
+use std::os::unix::process::{CommandExt, ExitStatusExt};
+use std::process::{Child, Command, ExitStatus, Stdio};
+use std::time::Instant;
+
+struct ChildGuard {
+ child: Option<Child>,
+ kill_process_group: bool,
+}
+
+impl ChildGuard {
+ fn new(child: Child) -> Self {
+ Self {
+ child: Some(child),
+ kill_process_group: false,
+ }
+ }
+
+ fn with_process_group(child: Child) -> Self {
+ Self {
+ child: Some(child),
+ kill_process_group: true,
+ }
+ }
+
+ fn pid(&self) -> i32 {
+ self.child.as_ref().expect("child not yet reaped").id() as i32
+ }
+
+ fn wait(&mut self) -> ExitStatus {
+ let mut child = self.child.take().expect("child already reaped");
+ let pgid = Pid::from_raw(child.id() as i32);
+ let status = child.wait().expect("wait child");
+ if self.kill_process_group {
+ // Best-effort cleanup of any background descendants (e.g. `sleep 30`) in the group.
+ let _ = killpg(pgid, NixSignal::SIGKILL);
+ }
+ status
+ }
+}
+
+impl Drop for ChildGuard {
+ fn drop(&mut self) {
+ if let Some(mut child) = self.child.take() {
+ if self.kill_process_group {
+ let _ = killpg(Pid::from_raw(child.id() as i32), NixSignal::SIGKILL);
+ } else {
+ let _ = child.kill();
+ }
+ let _ = child.wait();
+ }
+ }
+}
+
+fn setup_container(dir: &Path, id: &str, pid: Option<i32>, status: ContainerStatus) -> Container {
+ let state_root = dir.to_path_buf();
+ let state_dir = state_root.join(id);
+ std::fs::create_dir_all(&state_dir).unwrap();
+ let bundle = dir.join("bundle");
+ std::fs::create_dir_all(&bundle).unwrap();
+
+ State::new(id, status, pid, bundle.clone())
+ .save(&state_dir)
+ .unwrap();
+
+ let container = Container::for_unit_test(id, state_root, bundle);
+ container
+ .is_shutdown
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ container
+}
+
+/// Spawn `sleep 30` with explicit `SIGTERM` disposition (`SIG_IGN` or `SIG_DFL`) and mask
+/// (`SIG_UNBLOCK` or `SIG_BLOCK`) applied in `pre_exec` before `exec`.
+fn spawn_sleep_with_sigterm(ignore: bool, block: bool) -> ChildGuard {
+ let mut cmd = Command::new("sleep");
+ cmd.arg("30")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+
+ // SAFETY: `pre_exec` only calls async-signal-safe libc signal functions.
+ unsafe {
+ cmd.pre_exec(move || {
+ let handler = if ignore {
+ nix::libc::SIG_IGN
+ } else {
+ nix::libc::SIG_DFL
+ };
+ if nix::libc::signal(nix::libc::SIGTERM, handler) == nix::libc::SIG_ERR {
+ return Err(std::io::Error::last_os_error());
+ }
+
+ let mut set: nix::libc::sigset_t = std::mem::zeroed();
+ nix::libc::sigemptyset(&mut set);
+ nix::libc::sigaddset(&mut set, nix::libc::SIGTERM);
+ let how = if block {
+ nix::libc::SIG_BLOCK
+ } else {
+ nix::libc::SIG_UNBLOCK
+ };
+ if nix::libc::sigprocmask(how, &set, std::ptr::null_mut()) != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+ });
+ }
+
+ ChildGuard::new(cmd.spawn().expect("spawn sleep"))
+}
+
+// ============================================================================
+// /proc/<pid>/status parsing matrix
+// ============================================================================
+
+#[test]
+fn parse_sigterm_handled_caught_only() {
+ let status = "SigCgt:\t0000000000004000\nSigBlk:\t0000000000000000\n";
+ assert_eq!(parse_sigterm_handled(status), Some(true));
+}
+
+#[test]
+fn parse_sigterm_handled_blocked_only() {
+ let status = "SigCgt:\t0000000000000000\nSigBlk:\t0000000000004000\n";
+ assert_eq!(parse_sigterm_handled(status), Some(true));
+}
+
+#[test]
+fn parse_sigterm_handled_both_caught_and_blocked() {
+ let status = "SigCgt:\t0000000000004000\nSigBlk:\t0000000000004000\n";
+ assert_eq!(parse_sigterm_handled(status), Some(true));
+}
+
+#[test]
+fn parse_sigterm_handled_ignored_only_is_false() {
+ let status = "\
+SigIgn:\t0000000000004000
+SigCgt:\t0000000000000000
+SigBlk:\t0000000000000000
+";
+ assert_eq!(parse_sigterm_handled(status), Some(false));
+}
+
+#[test]
+fn parse_sigterm_handled_all_zero_is_false() {
+ let status = "SigCgt:\t0000000000000000\nSigBlk:\t0000000000000000\n";
+ assert_eq!(parse_sigterm_handled(status), Some(false));
+}
+
+#[test]
+fn parse_sigterm_handled_adjacent_bits_without_bit14_is_false() {
+ // All 64 bits set except bit 14 (0x4000).
+ let status = "SigCgt:\tffffffffffffbfff\nSigBlk:\tffffffffffffbfff\n";
+ assert_eq!(parse_sigterm_handled(status), Some(false));
+}
+
+#[test]
+fn parse_sigterm_handled_missing_fields_returns_none() {
+ assert_eq!(parse_sigterm_handled(""), None);
+ assert_eq!(parse_sigterm_handled("SigCgt:\t0000000000004000\n"), None);
+ assert_eq!(parse_sigterm_handled("SigBlk:\t0000000000004000\n"), None);
+}
+
+#[test]
+fn parse_sigterm_handled_invalid_hex_returns_none() {
+ assert_eq!(
+ parse_sigterm_handled("SigCgt:\tnot_hex\nSigBlk:\t0000000000000000\n"),
+ None
+ );
+ assert_eq!(
+ parse_sigterm_handled("SigCgt:\t0x4000\nSigBlk:\t0000000000000000\n"),
+ None
+ );
+ assert_eq!(
+ parse_sigterm_handled("SigCgt:\t10000000000000000\nSigBlk:\t0000000000000000\n"),
+ None
+ );
+ assert_eq!(
+ parse_sigterm_handled("SigCgt:\t\nSigBlk:\t0000000000000000\n"),
+ None
+ );
+}
+
+#[test]
+fn parse_sigterm_handled_realistic_status_formatting() {
+ let status = "\
+Name:\tmy:proc:name\r
+Umask:\t0022\r
+State:\tS (sleeping)\r
+Tgid:\t1\r
+SigBlk: 0000000000000000\r
+SigIgn:\t0000000000004000\r
+SigCgt:\t0000000000004ABC\r
+";
+ assert_eq!(parse_sigterm_handled(status), Some(true));
+}
+
+#[test]
+fn pid_handles_sigterm_at_falls_back_conservatively() {
+ let dir = tempfile::tempdir().unwrap();
+
+ // Missing / unreadable path -> true.
+ assert!(pid_handles_sigterm_at(&dir.path().join("missing/status")));
+
+ // Malformed file -> true.
+ let malformed = dir.path().join("malformed");
+ std::fs::write(&malformed, "Name:\tinit\nSigCgt:\tinvalid\n").unwrap();
+ assert!(pid_handles_sigterm_at(&malformed));
+
+ // Valid file with unhandled SIGTERM -> false.
+ let unhandled = dir.path().join("unhandled");
+ std::fs::write(&unhandled, "SigCgt:\t0\nSigBlk:\t0\n").unwrap();
+ assert!(!pid_handles_sigterm_at(&unhandled));
+
+ // Valid file with handled SIGTERM -> true.
+ let handled = dir.path().join("handled");
+ std::fs::write(&handled, "SigCgt:\t4000\nSigBlk:\t0\n").unwrap();
+ assert!(pid_handles_sigterm_at(&handled));
+}
+
+// ============================================================================
+// Real Linux process shutdown behavior
+// ============================================================================
+
+#[test]
+fn shutdown_skips_sigterm_wait_when_init_ignores_sigterm() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut child = spawn_sleep_with_sigterm(true, false);
+ let container = setup_container(
+ dir.path(),
+ "sigign-container",
+ Some(child.pid()),
+ ContainerStatus::Running,
+ );
+
+ let start = Instant::now();
+ container.shutdown_with(1000, false).unwrap();
+ let elapsed = start.elapsed();
+
+ assert!(
+ elapsed.as_millis() < 400,
+ "expected fast SIGKILL skip, took {}ms",
+ elapsed.as_millis()
+ );
+ let status = child.wait();
+ assert_eq!(status.signal(), Some(NixSignal::SIGKILL as i32));
+}
+
+#[test]
+fn shutdown_sends_sigkill_directly_for_default_disposition() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut child = spawn_sleep_with_sigterm(false, false);
+ let container = setup_container(
+ dir.path(),
+ "sigdfl-container",
+ Some(child.pid()),
+ ContainerStatus::Running,
+ );
+
+ container.shutdown_with(1000, false).unwrap();
+
+ // `sleep` has SIG_DFL for SIGTERM: if SIGTERM had been sent, it would have died with SIGTERM.
+ // Receiving SIGKILL proves SIGTERM was skipped.
+ let status = child.wait();
+ assert_eq!(status.signal(), Some(NixSignal::SIGKILL as i32));
+}
+
+fn spawn_trapping_shell() -> ChildGuard {
+ let mut cmd = Command::new("/bin/sh");
+ cmd.args([
+ "-c",
+ "trap 'kill $child 2>/dev/null; exit 42' TERM; sleep 30 & child=$!; printf x; wait $child",
+ ])
+ .process_group(0)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+
+ let mut guard = ChildGuard::with_process_group(cmd.spawn().expect("spawn sh"));
+
+ // Wait until the shell has installed its `trap` and emitted the ready byte.
+ let mut ready = [0u8; 1];
+ guard
+ .child
+ .as_mut()
+ .unwrap()
+ .stdout
+ .as_mut()
+ .unwrap()
+ .read_exact(&mut ready)
+ .expect("read ready byte");
+
+ guard
+}
+
+#[test]
+fn shutdown_waits_for_graceful_exit_when_init_catches_sigterm() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut child = spawn_trapping_shell();
+
+ let container = setup_container(
+ dir.path(),
+ "sigcgt-container",
+ Some(child.pid()),
+ ContainerStatus::Running,
+ );
+
+ let start = Instant::now();
+ container.shutdown_with(2000, false).unwrap();
+ let elapsed = start.elapsed();
+
+ let status = child.wait();
+ assert!(
+ elapsed.as_millis() < 1000,
+ "expected graceful exit well before timeout, took {}ms",
+ elapsed.as_millis()
+ );
+ assert_eq!(status.code(), Some(42));
+}
+
+#[test]
+fn shutdown_waits_grace_period_when_init_blocks_sigterm() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut child = spawn_sleep_with_sigterm(false, true);
+ let container = setup_container(
+ dir.path(),
+ "sigblk-container",
+ Some(child.pid()),
+ ContainerStatus::Running,
+ );
+
+ let start = Instant::now();
+ container.shutdown_with(400, false).unwrap();
+ let elapsed = start.elapsed();
+
+ let status = child.wait();
+ assert!(
+ elapsed.as_millis() >= 350,
+ "expected grace wait when SIGTERM is blocked, took {}ms",
+ elapsed.as_millis()
+ );
+ assert_eq!(status.signal(), Some(NixSignal::SIGKILL as i32));
+}
+
+#[test]
+fn shutdown_zero_timeout_skips_sigterm_and_stopped_container_is_noop() {
+ let dir = tempfile::tempdir().unwrap();
+
+ // Case 1: Caught SIGTERM with timeout_ms == 0 skips SIGTERM and sends SIGKILL immediately.
+ let mut child = spawn_trapping_shell();
+
+ let running_container = setup_container(
+ dir.path(),
+ "zero-timeout-container",
+ Some(child.pid()),
+ ContainerStatus::Running,
+ );
+ running_container.shutdown_with(0, false).unwrap();
+ let status = child.wait();
+ assert_eq!(status.signal(), Some(NixSignal::SIGKILL as i32));
+
+ // Case 2: Stopped container with pid == None is a clean no-op.
+ let stopped_container = setup_container(
+ dir.path(),
+ "stopped-container",
+ None,
+ ContainerStatus::Stopped,
+ );
+ assert!(stopped_container.shutdown_with(1000, false).is_ok());
+}