diff --git a/src/sandbox/get_or_create.rs b/src/sandbox/get_or_create.rs index d25a586..683cba0 100644 --- a/src/sandbox/get_or_create.rs +++ b/src/sandbox/get_or_create.rs @@ -1037,11 +1037,12 @@ impl Sandbox { close(std::io::stdin().as_raw_fd()) .context(format!("failed to close stdin"))?; + /* Exit on SIGTERM, with the signal number as our exit status. libc's + * exit has the C calling convention a signal handler needs, which + * std::process::exit doesn't. */ + let exit: unsafe extern "C" fn(libc::c_int) -> ! = libc::exit; unsafe { - libc::signal( - libc::SIGTERM, - std::process::exit as libc::sighandler_t, - ); + libc::signal(libc::SIGTERM, exit as libc::sighandler_t); } // sleep forever, this process hangs around only to host the namespaces so other processes diff --git a/tests/ai_test_sigterm.rs b/tests/ai_test_sigterm.rs new file mode 100644 index 0000000..e5f877d --- /dev/null +++ b/tests/ai_test_sigterm.rs @@ -0,0 +1,34 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::Path; +use std::time::{Duration, Instant}; + +#[rstest] +fn ai_test_sigterm_stops_sandbox(mut sandbox: SandboxManager) -> Result<()> { + sandbox.run(&["true"])?; + + sandbox.run(&["config", "sandbox_dir"])?; + let pid_file = format!("{}.pid", sandbox.last_stdout.trim()); + let pid = std::fs::read_to_string(&pid_file)?.trim().to_string(); + let proc_dir = format!("/proc/{}", pid); + assert!(Path::new(&proc_dir).exists()); + + // The sandbox's PID 1 exits when asked to terminate + let status = std::process::Command::new("sudo") + .args(["kill", "-TERM", &pid]) + .status()?; + assert!(status.success()); + let deadline = Instant::now() + Duration::from_secs(5); + while Path::new(&proc_dir).exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!Path::new(&proc_dir).exists()); + + // and the sandbox starts again the next time it's used + sandbox.run(&["echo", "restarted"])?; + assert_eq!(sandbox.last_stdout.trim(), "restarted"); + Ok(()) +}