forge
Explore
Log in

Don't you dare go Hollow

The sandbox helper waits on a signal pipe instead of an unsafe sigaction handler

Browse files at this commit

843ec873f2863c3eaf0f554fb468242e7dd24225Ahmet Kaan GümüşParent: 3b06bab
  • refactor
    • the sandbox helper waits on a signal pipe instead of an unsafe sigaction handler
Show full message
♻️ refactor: the sandbox helper waits on a signal pipe instead of an unsafe sigaction handler

SIGTERM, SIGINT and SIGCHLD now go through signal-hook: a self-pipe wakes the
wait loop, and SIGTERM and SIGINT also set a flag. The loop blocks in poll
instead of sleeping every 50 ms. The helper has no unsafe code of its own.
Cargo.lockmodified+11 -0
@@ -2048,6 +2048,7 @@ dependencies = [
20482048 "serde",
20492049 "serde_json",
20502050 "sha2 0.11.1",
2051+ "signal-hook",
20512052 "tar",
20522053 "tempfile",
20532054 "thiserror 2.0.21",
@@ -6635,6 +6636,16 @@ dependencies = [
66356636 "tracing",
66366637 ]
66376638
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+
66386649 [[package]]
66396650 name = "signal-hook-registry"
66406651 version = "1.4.8"
Cargo.tomlmodified+2 -0
@@ -102,6 +102,8 @@ libcontainer = { version = "0.7.0", default-features = false, features = ["v2"]
102102 seccompiler = { version = "0.5.0", features = ["json"] }
103103 oci-spec = "0.10.0"
104104 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"
105107
106108 # build and test
107109 grass = "0.13.4"
crates/forge-runner/Cargo.tomlmodified+1 -0
@@ -34,6 +34,7 @@ serde_json = { workspace = true }
3434 libcontainer = { workspace = true }
3535 oci-spec = { workspace = true }
3636 nix = { workspace = true }
37+signal-hook = { workspace = true }
3738 seccompiler = { workspace = true }
3839
3940 [dev-dependencies]
crates/forge-runner/src/sandbox/helper.rsmodified+92 -39
@@ -13,30 +13,34 @@
1313 //! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the
1414 //! container from it. The file is deleted right after `build()`, since libcontainer has
1515 //! 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.
1819 //!
1920 //! Exit codes: the job's code, 128 + signal if the job was signalled, or 125 for a sandbox setup
2021 //! failure. A setup failure prints `forge-sandbox: <reason>` on stderr.
2122
2223 use std::fs::{self, OpenOptions};
23-use std::io::{self, Write};
24+use std::io::{self, Read, Write};
2425 use std::os::fd::AsFd;
2526 use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, lchown};
27+use std::os::unix::net::UnixStream;
2628 use std::path::{Path, PathBuf};
2729 use std::process::Command;
30+use std::sync::Arc;
2831 use std::sync::atomic::{AtomicBool, Ordering};
29-use std::time::Duration;
3032
3133 use libcontainer::container::Container;
3234 use libcontainer::container::builder::ContainerBuilder;
3335 use libcontainer::syscall::syscall::SyscallType;
3436 use nix::errno::Errno;
3537 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};
3739 use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
3840 use nix::unistd::Pid;
3941 use oci_spec::runtime::Spec;
42+use signal_hook::consts::{SIGCHLD, SIGINT, SIGTERM};
43+use signal_hook::low_level::pipe;
4044
4145 use super::exec::FilteredExecutor;
4246 use super::idmap::enter_mapped_userns;
@@ -47,18 +51,8 @@ use crate::workspace::validate_job_id;
4751
4852 /// Exit code for a sandbox setup failure. The runner maps it to a sandbox error.
4953 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);
5254 const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n";
5355
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-
6256 /// Entry point for `forge-runner __sandbox`. Returns the process exit code.
6357 pub fn helper_main() -> i32 {
6458 // libcontainer logs through tracing. Its logs appear only when the operator sets RUST_LOG.
@@ -107,7 +101,7 @@ fn run() -> Result<i32, SandboxError> {
107101 let req: SandboxRequest = serde_json::from_reader(io::stdin().lock())
108102 .map_err(|e| SandboxError::Invalid(format!("cannot read request: {e}")))?;
109103 validate_request(&req)?;
110- install_signal_handlers()?;
104+ let signals = install_signal_handlers()?;
111105
112106 let layout = Layout::new(&req.job_dir);
113107 prepare_dirs(&layout)?;
@@ -117,7 +111,7 @@ fn run() -> Result<i32, SandboxError> {
117111 let rootfs = mount_rootfs(&req, &layout)?;
118112
119113 // 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);
121115 // The container is gone, so nothing writes to the workspace now. In subuid mode the job may
122116 // have left files owned by subordinate ids, which the runner can't remove, so they go back
123117 // to the runner.
@@ -186,20 +180,38 @@ fn validate_request(req: &SandboxRequest) -> Result<(), SandboxError> {
186180 Ok(())
187181 }
188182
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)?;
201212 }
202- Ok(())
213+ pipe::register(SIGCHLD, write_end).map_err(setup)?;
214+ Ok(Signals { wake, terminate })
203215 }
204216
205217 fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> {
@@ -305,18 +317,23 @@ fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> {
305317 /// libcontainer 0.7 cannot run a container in a user namespace without a cgroup manager, and it
306318 /// only avoids systemd when the cgroup path is absolute. So "run without cgroups" is not
307319 /// 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> {
309326 let cgroup = job_cgroup_path(&req.job_id, std::process::id())?;
310327 let mut spec = build_spec(req, rootfs)?;
311328 set_cgroup_path(&mut spec, &cgroup);
312329
313- match launch_and_wait(layout, &req.job_id, &spec) {
330+ match launch_and_wait(layout, &req.job_id, &spec, signals) {
314331 Ok(code) => Ok(code),
315332 Err(SandboxError::Setup(reason)) if reason.starts_with("container: ") => {
316333 warn(format!("resource limits unavailable: {reason}"));
317334 strip_limits(&mut spec);
318335 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)
320337 }
321338 Err(e) => Err(e),
322339 }
@@ -398,7 +415,12 @@ fn strip_limits(spec: &mut Spec) {
398415
399416 /// Writes the bundle, builds, starts, and waits. Build and start errors are returned as
400417 /// `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> {
402424 // Start each attempt with an empty state dir, so a failed attempt leaves no state behind.
403425 // The dir may not exist yet on the first attempt, so a failure here is not an error.
404426 let _ = fs::remove_dir_all(&layout.state);
@@ -430,7 +452,7 @@ fn launch_and_wait(layout: &Layout, id: &str, spec: &Spec) -> Result<i32, Sandbo
430452 .linux()
431453 .as_ref()
432454 .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)
434456 }
435457
436458 /// 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> {
501523 container.kill(sigkill, true).map_err(|e| e.to_string())
502524 }
503525
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.
506528 fn wait_for_init(
507529 container: &mut Container,
508530 pid: Pid,
509531 cgroup: Option<&Path>,
532+ signals: &Signals,
510533 ) -> Result<i32, SandboxError> {
511534 let mut killed = false;
512535 loop {
513- if !killed && TERMINATE.load(Ordering::SeqCst) {
536+ if !killed && signals.terminate.load(Ordering::SeqCst) {
514537 killed = true;
515538 if let Err(e) = kill_container(container) {
516539 warn(format!("cannot kill container: {e}"));
517540 }
518541 }
519542 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+ }
521552 Ok(WaitStatus::Exited(_, code)) => {
522553 report_oom(cgroup);
523554 delete_container(container);
@@ -539,6 +570,28 @@ fn wait_for_init(
539570 }
540571 }
541572
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+
542595 /// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs
543596 /// after the init exited and before the cgroup is deleted, the only time the file still exists.
544597 fn report_oom(cgroup: Option<&Path>) {