The sandbox helper waits on a signal pipe instead of an unsafe sigaction handler
Browse files at this commit843ec873f2863c3eaf0f554fb468242e7dd24225Parent: 3b06bab- refactor
- the sandbox helper waits on a signal pipe instead of an unsafe sigaction handler
4 changed files +106 -39
- Cargo.lock +11 -0
- Cargo.toml +2 -0
- crates/forge-runner/Cargo.toml +1 -0
- crates/forge-runner/src/sandbox/helper.rs +92 -39
Cargo.lockmodified+11 -0
| @@ -2048,6 +2048,7 @@ dependencies = [ | ||
| 2048 | 2048 | "serde", |
| 2049 | 2049 | "serde_json", |
| 2050 | 2050 | "sha2 0.11.1", |
| 2051 | + "signal-hook", | |
| 2051 | 2052 | "tar", |
| 2052 | 2053 | "tempfile", |
| 2053 | 2054 | "thiserror 2.0.21", |
| @@ -6635,6 +6636,16 @@ dependencies = [ | ||
| 6635 | 6636 | "tracing", |
| 6636 | 6637 | ] |
| 6637 | 6638 | |
| 6639 | +[[package]] | |
| 6640 | +name = "signal-hook" | |
| 6641 | +version = "0.4.5" | |
| 6642 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 6643 | +checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e" | |
| 6644 | +dependencies = [ | |
| 6645 | + "libc", | |
| 6646 | + "signal-hook-registry", | |
| 6647 | +] | |
| 6648 | + | |
| 6638 | 6649 | [[package]] |
| 6639 | 6650 | name = "signal-hook-registry" |
| 6640 | 6651 | version = "1.4.8" |
Cargo.tomlmodified+2 -0
| @@ -102,6 +102,8 @@ libcontainer = { version = "0.7.0", default-features = false, features = ["v2"] | ||
| 102 | 102 | seccompiler = { version = "0.5.0", features = ["json"] } |
| 103 | 103 | oci-spec = "0.10.0" |
| 104 | 104 | nix = { version = "0.31.3", features = ["signal", "process", "mount", "sched", "user", "resource", "fs", "inotify", "poll"] } |
| 105 | +# sandbox helper: signal delivery through a self-pipe, so the helper needs no unsafe sigaction | |
| 106 | +signal-hook = "0.4.5" | |
| 105 | 107 | |
| 106 | 108 | # build and test |
| 107 | 109 | grass = "0.13.4" |
crates/forge-runner/Cargo.tomlmodified+1 -0
| @@ -34,6 +34,7 @@ serde_json = { workspace = true } | ||
| 34 | 34 | libcontainer = { workspace = true } |
| 35 | 35 | oci-spec = { workspace = true } |
| 36 | 36 | nix = { workspace = true } |
| 37 | +signal-hook = { workspace = true } | |
| 37 | 38 | seccompiler = { workspace = true } |
| 38 | 39 | |
| 39 | 40 | [dev-dependencies] |
crates/forge-runner/src/sandbox/helper.rsmodified+92 -39
| @@ -13,30 +13,34 @@ | ||
| 13 | 13 | //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the |
| 14 | 14 | //! container from it. The file is deleted right after `build()`, since libcontainer has |
| 15 | 15 | //! read it by then. |
| 16 | -//! 4. The container starts and the helper waits, polling so that SIGTERM is never missed. On | |
| 17 | -//! SIGTERM the container is killed and deleted. The exit code is the job's. | |
| 16 | +//! 4. The container starts and the helper waits. It sleeps in `poll` on a self-pipe that SIGTERM, | |
| 17 | +//! SIGINT and SIGCHLD write to, so it wakes as soon as one arrives. On SIGTERM or SIGINT the | |
| 18 | +//! container is killed and deleted. The exit code is the job's. | |
| 18 | 19 | //! |
| 19 | 20 | //! Exit codes: the job's code, 128 + signal if the job was signalled, or 125 for a sandbox setup |
| 20 | 21 | //! failure. A setup failure prints `forge-sandbox: <reason>` on stderr. |
| 21 | 22 | |
| 22 | 23 | use std::fs::{self, OpenOptions}; |
| 23 | -use std::io::{self, Write}; | |
| 24 | +use std::io::{self, Read, Write}; | |
| 24 | 25 | use std::os::fd::AsFd; |
| 25 | 26 | use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, lchown}; |
| 27 | +use std::os::unix::net::UnixStream; | |
| 26 | 28 | use std::path::{Path, PathBuf}; |
| 27 | 29 | use std::process::Command; |
| 30 | +use std::sync::Arc; | |
| 28 | 31 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 29 | -use std::time::Duration; | |
| 30 | 32 | |
| 31 | 33 | use libcontainer::container::Container; |
| 32 | 34 | use libcontainer::container::builder::ContainerBuilder; |
| 33 | 35 | use libcontainer::syscall::syscall::SyscallType; |
| 34 | 36 | use nix::errno::Errno; |
| 35 | 37 | use nix::mount::{MntFlags, MsFlags, mount, umount2}; |
| 36 | -use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}; | |
| 38 | +use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; | |
| 37 | 39 | use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid}; |
| 38 | 40 | use nix::unistd::Pid; |
| 39 | 41 | use oci_spec::runtime::Spec; |
| 42 | +use signal_hook::consts::{SIGCHLD, SIGINT, SIGTERM}; | |
| 43 | +use signal_hook::low_level::pipe; | |
| 40 | 44 | |
| 41 | 45 | use super::exec::FilteredExecutor; |
| 42 | 46 | use super::idmap::enter_mapped_userns; |
| @@ -47,18 +51,8 @@ use crate::workspace::validate_job_id; | ||
| 47 | 51 | |
| 48 | 52 | /// Exit code for a sandbox setup failure. The runner maps it to a sandbox error. |
| 49 | 53 | pub const EXIT_SETUP_FAILED: i32 = 125; |
| 50 | -/// How often the wait loop checks for SIGTERM and polls the child. | |
| 51 | -const POLL: Duration = Duration::from_millis(50); | |
| 52 | 54 | const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n"; |
| 53 | 55 | |
| 54 | -/// Set by the SIGTERM and SIGINT handler. The wait loop reads it. | |
| 55 | -static TERMINATE: AtomicBool = AtomicBool::new(false); | |
| 56 | - | |
| 57 | -extern "C" fn on_terminate(_signal: i32) { | |
| 58 | - // Only an atomic store here, which is async-signal-safe. | |
| 59 | - TERMINATE.store(true, Ordering::SeqCst); | |
| 60 | -} | |
| 61 | - | |
| 62 | 56 | /// Entry point for `forge-runner __sandbox`. Returns the process exit code. |
| 63 | 57 | pub fn helper_main() -> i32 { |
| 64 | 58 | // libcontainer logs through tracing. Its logs appear only when the operator sets RUST_LOG. |
| @@ -107,7 +101,7 @@ fn run() -> Result<i32, SandboxError> { | ||
| 107 | 101 | let req: SandboxRequest = serde_json::from_reader(io::stdin().lock()) |
| 108 | 102 | .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?; |
| 109 | 103 | validate_request(&req)?; |
| 110 | - install_signal_handlers()?; | |
| 104 | + let signals = install_signal_handlers()?; | |
| 111 | 105 | |
| 112 | 106 | let layout = Layout::new(&req.job_dir); |
| 113 | 107 | prepare_dirs(&layout)?; |
| @@ -117,7 +111,7 @@ fn run() -> Result<i32, SandboxError> { | ||
| 117 | 111 | let rootfs = mount_rootfs(&req, &layout)?; |
| 118 | 112 | |
| 119 | 113 | // Clean up on failure too: the state dir holds the job env. |
| 120 | - let result = run_job(&req, &layout, &rootfs); | |
| 114 | + let result = run_job(&req, &layout, &rootfs, &signals); | |
| 121 | 115 | // The container is gone, so nothing writes to the workspace now. In subuid mode the job may |
| 122 | 116 | // have left files owned by subordinate ids, which the runner can't remove, so they go back |
| 123 | 117 | // to the runner. |
| @@ -186,20 +180,38 @@ fn validate_request(req: &SandboxRequest) -> Result<(), SandboxError> { | ||
| 186 | 180 | Ok(()) |
| 187 | 181 | } |
| 188 | 182 | |
| 189 | -/// Installs the SIGTERM and SIGINT handler. It does not set SA_RESTART. The wait loop polls, | |
| 190 | -/// so the handler only sets a flag. | |
| 191 | -fn install_signal_handlers() -> Result<(), SandboxError> { | |
| 192 | - let action = SigAction::new( | |
| 193 | - SigHandler::Handler(on_terminate), | |
| 194 | - SaFlags::empty(), | |
| 195 | - SigSet::empty(), | |
| 196 | - ); | |
| 197 | - for sig in [Signal::SIGTERM, Signal::SIGINT] { | |
| 198 | - // SAFETY: the handler only performs an atomic store, which is async-signal-safe. | |
| 199 | - unsafe { sigaction(sig, &action) } | |
| 200 | - .map_err(|e| SandboxError::Setup(format!("cannot install signal handler: {e}")))?; | |
| 183 | +/// The signal state the wait loop reads. See [`install_signal_handlers`]. | |
| 184 | +struct Signals { | |
| 185 | + /// The read end of the self-pipe. SIGTERM, SIGINT and SIGCHLD each write one byte to it, so it | |
| 186 | + /// becomes readable. The byte does not say which signal it was. | |
| 187 | + wake: UnixStream, | |
| 188 | + /// Set by SIGTERM and SIGINT. | |
| 189 | + terminate: Arc<AtomicBool>, | |
| 190 | +} | |
| 191 | + | |
| 192 | +/// Routes SIGTERM, SIGINT and SIGCHLD to a self-pipe, so the wait loop can block in `poll`. SIGTERM | |
| 193 | +/// and SIGINT also set a flag, since the pipe byte doesn't say which signal it was. The handlers | |
| 194 | +/// are installed by `signal-hook`, which does the low-level work, so this file needs none. | |
| 195 | +fn install_signal_handlers() -> Result<Signals, SandboxError> { | |
| 196 | + let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}")); | |
| 197 | + let (wake, write_end) = | |
| 198 | + UnixStream::pair().map_err(SandboxError::io("cannot create the signal pipe"))?; | |
| 199 | + // Both ends are non-blocking. A signal handler must never block on a full pipe. | |
| 200 | + wake.set_nonblocking(true) | |
| 201 | + .map_err(SandboxError::io("cannot configure the signal pipe"))?; | |
| 202 | + write_end | |
| 203 | + .set_nonblocking(true) | |
| 204 | + .map_err(SandboxError::io("cannot configure the signal pipe"))?; | |
| 205 | + let terminate = Arc::new(AtomicBool::new(false)); | |
| 206 | + for sig in [SIGTERM, SIGINT] { | |
| 207 | + signal_hook::flag::register(sig, Arc::clone(&terminate)).map_err(setup)?; | |
| 208 | + let pipe_end = write_end | |
| 209 | + .try_clone() | |
| 210 | + .map_err(SandboxError::io("cannot duplicate the signal pipe"))?; | |
| 211 | + pipe::register(sig, pipe_end).map_err(setup)?; | |
| 201 | 212 | } |
| 202 | - Ok(()) | |
| 213 | + pipe::register(SIGCHLD, write_end).map_err(setup)?; | |
| 214 | + Ok(Signals { wake, terminate }) | |
| 203 | 215 | } |
| 204 | 216 | |
| 205 | 217 | fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> { |
| @@ -305,18 +317,23 @@ fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> { | ||
| 305 | 317 | /// libcontainer 0.7 cannot run a container in a user namespace without a cgroup manager, and it |
| 306 | 318 | /// only avoids systemd when the cgroup path is absolute. So "run without cgroups" is not |
| 307 | 319 | /// available. If the job cgroup can't be created at all, the job fails with exit 125. |
| 308 | -fn run_job(req: &SandboxRequest, layout: &Layout, rootfs: &Path) -> Result<i32, SandboxError> { | |
| 320 | +fn run_job( | |
| 321 | + req: &SandboxRequest, | |
| 322 | + layout: &Layout, | |
| 323 | + rootfs: &Path, | |
| 324 | + signals: &Signals, | |
| 325 | +) -> Result<i32, SandboxError> { | |
| 309 | 326 | let cgroup = job_cgroup_path(&req.job_id, std::process::id())?; |
| 310 | 327 | let mut spec = build_spec(req, rootfs)?; |
| 311 | 328 | set_cgroup_path(&mut spec, &cgroup); |
| 312 | 329 | |
| 313 | - match launch_and_wait(layout, &req.job_id, &spec) { | |
| 330 | + match launch_and_wait(layout, &req.job_id, &spec, signals) { | |
| 314 | 331 | Ok(code) => Ok(code), |
| 315 | 332 | Err(SandboxError::Setup(reason)) if reason.starts_with("container: ") => { |
| 316 | 333 | warn(format!("resource limits unavailable: {reason}")); |
| 317 | 334 | strip_limits(&mut spec); |
| 318 | 335 | let retry_id = format!("{}-nolimits", req.job_id); |
| 319 | - launch_and_wait(layout, &retry_id, &spec) | |
| 336 | + launch_and_wait(layout, &retry_id, &spec, signals) | |
| 320 | 337 | } |
| 321 | 338 | Err(e) => Err(e), |
| 322 | 339 | } |
| @@ -398,7 +415,12 @@ fn strip_limits(spec: &mut Spec) { | ||
| 398 | 415 | |
| 399 | 416 | /// Writes the bundle, builds, starts, and waits. Build and start errors are returned as |
| 400 | 417 | /// `Setup("container: …")` so the caller can tell them apart from setup errors. |
| 401 | -fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result<i32, SandboxError> { | |
| 418 | +fn launch_and_wait( | |
| 419 | + layout: &Layout, | |
| 420 | + id: &str, | |
| 421 | + spec: &Spec, | |
| 422 | + signals: &Signals, | |
| 423 | +) -> Result<i32, SandboxError> { | |
| 402 | 424 | // Start each attempt with an empty state dir, so a failed attempt leaves no state behind. |
| 403 | 425 | // The dir may not exist yet on the first attempt, so a failure here is not an error. |
| 404 | 426 | let _ = fs::remove_dir_all(&layout.state); |
| @@ -430,7 +452,7 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result<i32, Sandbo | ||
| 430 | 452 | .linux() |
| 431 | 453 | .as_ref() |
| 432 | 454 | .and_then(|linux| linux.cgroups_path().clone()); |
| 433 | - wait_for_init(&mut container, pid, cgroup.as_deref()) | |
| 455 | + wait_for_init(&mut container, pid, cgroup.as_deref(), signals) | |
| 434 | 456 | } |
| 435 | 457 | |
| 436 | 458 | /// Writes `bundle/config.json` (0600). It holds the job env and secrets, so it is removed right |
| @@ -501,23 +523,32 @@ fn kill_container(container: &mut Container) -> Result<(), String> { | ||
| 501 | 523 | container.kill(sigkill, true).map_err(|e| e.to_string()) |
| 502 | 524 | } |
| 503 | 525 | |
| 504 | -/// Waits for the init process. On SIGTERM the container is killed. The child is then reaped, | |
| 505 | -/// and `delete` removes the container's state. Returns the job's exit code. | |
| 526 | +/// Waits for the init process. On SIGTERM or SIGINT the container is killed. The child is then | |
| 527 | +/// reaped, and `delete` removes the container's state. Returns the job's exit code. | |
| 506 | 528 | fn wait_for_init( |
| 507 | 529 | container: &mut Container, |
| 508 | 530 | pid: Pid, |
| 509 | 531 | cgroup: Option<&Path>, |
| 532 | + signals: &Signals, | |
| 510 | 533 | ) -> Result<i32, SandboxError> { |
| 511 | 534 | let mut killed = false; |
| 512 | 535 | loop { |
| 513 | - if !killed && TERMINATE.load(Ordering::SeqCst) { | |
| 536 | + if !killed && signals.terminate.load(Ordering::SeqCst) { | |
| 514 | 537 | killed = true; |
| 515 | 538 | if let Err(e) = kill_container(container) { |
| 516 | 539 | warn(format!("cannot kill container: {e}")); |
| 517 | 540 | } |
| 518 | 541 | } |
| 519 | 542 | match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { |
| 520 | - Ok(WaitStatus::StillAlive) => std::thread::sleep(POLL), | |
| 543 | + Ok(WaitStatus::StillAlive) => { | |
| 544 | + // A signal that arrived since the checks above has already written to the pipe, | |
| 545 | + // so this returns at once and nothing is missed. | |
| 546 | + if let Err(e) = wait_for_signal(&signals.wake) { | |
| 547 | + let _ = kill_container(container); | |
| 548 | + delete_container(container); | |
| 549 | + return Err(SandboxError::Setup(format!("waiting for the job: {e}"))); | |
| 550 | + } | |
| 551 | + } | |
| 521 | 552 | Ok(WaitStatus::Exited(_, code)) => { |
| 522 | 553 | report_oom(cgroup); |
| 523 | 554 | delete_container(container); |
| @@ -539,6 +570,28 @@ fn wait_for_init( | ||
| 539 | 570 | } |
| 540 | 571 | } |
| 541 | 572 | |
| 573 | +/// Blocks until the self-pipe is readable, then empties it. The pipe is only written by signal | |
| 574 | +/// handlers, so this wakes on any of SIGTERM, SIGINT or SIGCHLD. Returns an error only if `poll` | |
| 575 | +/// itself fails. | |
| 576 | +fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { | |
| 577 | + let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)]; | |
| 578 | + match poll(&mut fds, PollTimeout::NONE) { | |
| 579 | + // EINTR means a handler ran, and it wrote to the pipe. The drain below picks that up. | |
| 580 | + Ok(_) | Err(Errno::EINTR) => {} | |
| 581 | + Err(e) => return Err(e), | |
| 582 | + } | |
| 583 | + let mut buf = [0u8; 64]; | |
| 584 | + loop { | |
| 585 | + match (&*wake).read(&mut buf) { | |
| 586 | + Ok(0) => return Ok(()), | |
| 587 | + Ok(_) => {} | |
| 588 | + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} | |
| 589 | + // WouldBlock means the pipe is empty. Any other read error can't be acted on either. | |
| 590 | + Err(_) => return Ok(()), | |
| 591 | + } | |
| 592 | + } | |
| 593 | +} | |
| 594 | + | |
| 542 | 595 | /// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs |
| 543 | 596 | /// after the init exited and before the cgroup is deleted, the only time the file still exists. |
| 544 | 597 | fn report_oom(cgroup: Option<&Path>) { |