diff --git a/Cargo.lock b/Cargo.lock index 91404ab..05df56d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2048,6 +2048,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "signal-hook", "tar", "tempfile", "thiserror 2.0.21", @@ -6635,6 +6636,16 @@ dependencies = [ "tracing", ] +[[package]] +name = "signal-hook" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" diff --git a/Cargo.toml b/Cargo.toml index f04c116..88a209f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -102,6 +102,8 @@ libcontainer = { version = "0.7.0", default-features = false, features = ["v2"] seccompiler = { version = "0.5.0", features = ["json"] } oci-spec = "0.10.0" nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify", "poll"] } +# sandbox helper: signal delivery through a self-pipe, so the helper needs no unsafe sigaction +signal-hook = "0.4.5" # build and test grass = "0.13.4" diff --git a/crates/forge-runner/Cargo.toml b/crates/forge-runner/Cargo.toml index 424d922..5109c23 100644 --- a/crates/forge-runner/Cargo.toml +++ b/crates/forge-runner/Cargo.toml @@ -34,6 +34,7 @@ serde_json = { workspace = true } libcontainer = { workspace = true } oci-spec = { workspace = true } nix = { workspace = true } +signal-hook = { workspace = true } seccompiler = { workspace = true } [dev-dependencies] diff --git a/crates/forge-runner/src/sandbox/helper.rs b/crates/forge-runner/src/sandbox/helper.rs index d8ee730..821527a 100644 --- a/crates/forge-runner/src/sandbox/helper.rs +++ b/crates/forge-runner/src/sandbox/helper.rs @@ -13,30 +13,34 @@ //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the //! container from it. The file is deleted right after `build()`, since libcontainer has //! read it by then. -//! 4. The container starts and the helper waits, polling so that SIGTERM is never missed. On -//! SIGTERM the container is killed and deleted. The exit code is the job's. +//! 4. The container starts and the helper waits. It sleeps in `poll` on a self-pipe that SIGTERM, +//! SIGINT and SIGCHLD write to, so it wakes as soon as one arrives. On SIGTERM or SIGINT the +//! container is killed and deleted. The exit code is the job's. //! //! Exit codes: the job's code, 128 + signal if the job was signalled, or 125 for a sandbox setup //! failure. A setup failure prints `forge-sandbox: ` on stderr. use std::fs::{self, OpenOptions}; -use std::io::{self, Write}; +use std::io::{self, Read, Write}; use std::os::fd::AsFd; use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, lchown}; +use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; use libcontainer::container::Container; use libcontainer::container::builder::ContainerBuilder; use libcontainer::syscall::syscall::SyscallType; use nix::errno::Errno; use nix::mount::{MntFlags, MsFlags, mount, umount2}; -use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}; +use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid}; use nix::unistd::Pid; use oci_spec::runtime::Spec; +use signal_hook::consts::{SIGCHLD, SIGINT, SIGTERM}; +use signal_hook::low_level::pipe; use super::exec::FilteredExecutor; use super::idmap::enter_mapped_userns; @@ -47,18 +51,8 @@ use crate::workspace::validate_job_id; /// Exit code for a sandbox setup failure. The runner maps it to a sandbox error. pub const EXIT_SETUP_FAILED: i32 = 125; -/// How often the wait loop checks for SIGTERM and polls the child. -const POLL: Duration = Duration::from_millis(50); const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n"; -/// Set by the SIGTERM and SIGINT handler. The wait loop reads it. -static TERMINATE: AtomicBool = AtomicBool::new(false); - -extern "C" fn on_terminate(_signal: i32) { - // Only an atomic store here, which is async-signal-safe. - TERMINATE.store(true, Ordering::SeqCst); -} - /// Entry point for `forge-runner __sandbox`. Returns the process exit code. pub fn helper_main() -> i32 { // libcontainer logs through tracing. Its logs appear only when the operator sets RUST_LOG. @@ -107,7 +101,7 @@ fn run() -> Result { let req: SandboxRequest = serde_json::from_reader(io::stdin().lock()) .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?; validate_request(&req)?; - install_signal_handlers()?; + let signals = install_signal_handlers()?; let layout = Layout::new(&req.job_dir); prepare_dirs(&layout)?; @@ -117,7 +111,7 @@ fn run() -> Result { let rootfs = mount_rootfs(&req, &layout)?; // Clean up on failure too: the state dir holds the job env. - let result = run_job(&req, &layout, &rootfs); + let result = run_job(&req, &layout, &rootfs, &signals); // The container is gone, so nothing writes to the workspace now. In subuid mode the job may // have left files owned by subordinate ids, which the runner can't remove, so they go back // to the runner. @@ -186,20 +180,38 @@ fn validate_request(req: &SandboxRequest) -> Result<(), SandboxError> { Ok(()) } -/// Installs the SIGTERM and SIGINT handler. It does not set SA_RESTART. The wait loop polls, -/// so the handler only sets a flag. -fn install_signal_handlers() -> Result<(), SandboxError> { - let action = SigAction::new( - SigHandler::Handler(on_terminate), - SaFlags::empty(), - SigSet::empty(), - ); - for sig in [Signal::SIGTERM, Signal::SIGINT] { - // SAFETY: the handler only performs an atomic store, which is async-signal-safe. - unsafe { sigaction(sig, &action) } - .map_err(|e| SandboxError::Setup(format!("cannot install signal handler: {e}")))?; +/// The signal state the wait loop reads. See [`install_signal_handlers`]. +struct Signals { + /// The read end of the self-pipe. SIGTERM, SIGINT and SIGCHLD each write one byte to it, so it + /// becomes readable. The byte does not say which signal it was. + wake: UnixStream, + /// Set by SIGTERM and SIGINT. + terminate: Arc, +} + +/// Routes SIGTERM, SIGINT and SIGCHLD to a self-pipe, so the wait loop can block in `poll`. SIGTERM +/// and SIGINT also set a flag, since the pipe byte doesn't say which signal it was. The handlers +/// are installed by `signal-hook`, which does the low-level work, so this file needs none. +fn install_signal_handlers() -> Result { + let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}")); + let (wake, write_end) = + UnixStream::pair().map_err(SandboxError::io("cannot create the signal pipe"))?; + // Both ends are non-blocking. A signal handler must never block on a full pipe. + wake.set_nonblocking(true) + .map_err(SandboxError::io("cannot configure the signal pipe"))?; + write_end + .set_nonblocking(true) + .map_err(SandboxError::io("cannot configure the signal pipe"))?; + let terminate = Arc::new(AtomicBool::new(false)); + for sig in [SIGTERM, SIGINT] { + signal_hook::flag::register(sig, Arc::clone(&terminate)).map_err(setup)?; + let pipe_end = write_end + .try_clone() + .map_err(SandboxError::io("cannot duplicate the signal pipe"))?; + pipe::register(sig, pipe_end).map_err(setup)?; } - Ok(()) + pipe::register(SIGCHLD, write_end).map_err(setup)?; + Ok(Signals { wake, terminate }) } fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> { @@ -305,18 +317,23 @@ fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> { /// libcontainer 0.7 cannot run a container in a user namespace without a cgroup manager, and it /// only avoids systemd when the cgroup path is absolute. So "run without cgroups" is not /// available. If the job cgroup can't be created at all, the job fails with exit 125. -fn run_job(req: &SandboxRequest, layout: &Layout, rootfs: &Path) -> Result { +fn run_job( + req: &SandboxRequest, + layout: &Layout, + rootfs: &Path, + signals: &Signals, +) -> Result { let cgroup = job_cgroup_path(&req.job_id, std::process::id())?; let mut spec = build_spec(req, rootfs)?; set_cgroup_path(&mut spec, &cgroup); - match launch_and_wait(layout, &req.job_id, &spec) { + match launch_and_wait(layout, &req.job_id, &spec, signals) { Ok(code) => Ok(code), Err(SandboxError::Setup(reason)) if reason.starts_with("container: ") => { warn(format!("resource limits unavailable: {reason}")); strip_limits(&mut spec); let retry_id = format!("{}-nolimits", req.job_id); - launch_and_wait(layout, &retry_id, &spec) + launch_and_wait(layout, &retry_id, &spec, signals) } Err(e) => Err(e), } @@ -398,7 +415,12 @@ fn strip_limits(spec: &mut Spec) { /// Writes the bundle, builds, starts, and waits. Build and start errors are returned as /// `Setup("container: …")` so the caller can tell them apart from setup errors. -fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result { +fn launch_and_wait( + layout: &Layout, + id: &str, + spec: &Spec, + signals: &Signals, +) -> Result { // Start each attempt with an empty state dir, so a failed attempt leaves no state behind. // The dir may not exist yet on the first attempt, so a failure here is not an error. let _ = fs::remove_dir_all(&layout.state); @@ -430,7 +452,7 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result Result<(), String> { container.kill(sigkill, true).map_err(|e| e.to_string()) } -/// Waits for the init process. On SIGTERM the container is killed. The child is then reaped, -/// and `delete` removes the container's state. Returns the job's exit code. +/// Waits for the init process. On SIGTERM or SIGINT the container is killed. The child is then +/// reaped, and `delete` removes the container's state. Returns the job's exit code. fn wait_for_init( container: &mut Container, pid: Pid, cgroup: Option<&Path>, + signals: &Signals, ) -> Result { let mut killed = false; loop { - if !killed && TERMINATE.load(Ordering::SeqCst) { + if !killed && signals.terminate.load(Ordering::SeqCst) { killed = true; if let Err(e) = kill_container(container) { warn(format!("cannot kill container: {e}")); } } match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { - Ok(WaitStatus::StillAlive) => std::thread::sleep(POLL), + Ok(WaitStatus::StillAlive) => { + // A signal that arrived since the checks above has already written to the pipe, + // so this returns at once and nothing is missed. + if let Err(e) = wait_for_signal(&signals.wake) { + let _ = kill_container(container); + delete_container(container); + return Err(SandboxError::Setup(format!("waiting for the job: {e}"))); + } + } Ok(WaitStatus::Exited(_, code)) => { report_oom(cgroup); delete_container(container); @@ -539,6 +570,28 @@ fn wait_for_init( } } +/// Blocks until the self-pipe is readable, then empties it. The pipe is only written by signal +/// handlers, so this wakes on any of SIGTERM, SIGINT or SIGCHLD. Returns an error only if `poll` +/// itself fails. +fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { + let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)]; + match poll(&mut fds, PollTimeout::NONE) { + // EINTR means a handler ran, and it wrote to the pipe. The drain below picks that up. + Ok(_) | Err(Errno::EINTR) => {} + Err(e) => return Err(e), + } + let mut buf = [0u8; 64]; + loop { + match (&*wake).read(&mut buf) { + Ok(0) => return Ok(()), + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + // WouldBlock means the pipe is empty. Any other read error can't be acted on either. + Err(_) => return Ok(()), + } + } +} + /// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs /// after the init exited and before the cgroup is deleted, the only time the file still exists. fn report_oom(cgroup: Option<&Path>) {