forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBdcdcd27Tahinli1 month ago240 commits

executor.rs1170 lines, 42.1 KiBHistoryRawDownload
1//! Running a job's `run` script.
2//!
3//! `BuiltinExecutor` is the default: the image is prepared by an [`ImageSource`] (the
4//! [`ImageStore`] in production), and the script runs in a sandbox started by a helper process
5//! (`forge-runner __sandbox`). No external tool is needed.
6//!
7//! `PodmanExecutor` is the optional path: a rootless podman container with the workspace
8//! mounted at `/workspace`. Secret values and job env travel in the child process environment,
9//! and podman receives only `-e NAME`, so no value ever appears in argv.
10//!
11//! `HostExecutor` runs the script directly on the host. It exists only for tests and is compiled
12//! only under `cfg(test)` or the `test-host-executor` feature.
13
14use std::fs;
15use std::future::Future;
16use std::path::{Path, PathBuf};
17use std::pin::Pin;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::process::{ExitStatus, Stdio};
21use std::time::Duration;
22
23use forge_ci::proto::{JobAssignment, Outcome};
24use nix::sys::signal::{Signal, kill};
25use nix::unistd::Pid;
26use oci_client::Reference;
27use tokio::io::AsyncWriteExt;
28use tokio::process::{Child, Command};
29use tokio::sync::mpsc;
30use tokio::task::JoinHandle;
31use tokio_util::sync::CancellationToken;
32
33use crate::config::{Limits, RegistryConfig};
34use crate::logs::forward_lines;
35use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth};
36use crate::oom::{OomEvents, OomSink};
37use crate::sandbox::helper::EXIT_SETUP_FAILED;
38use crate::sandbox::idmap::{IdMap, remove_tree};
39use crate::sandbox::{SandboxRequest, job_cgroup_path};
40use crate::workspace::validate_job_id;
41
42/// The prefix of the sandbox helper's own error lines on stderr.
43const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: ";
44
45/// How long to wait for the output readers to drain after the child has exited.
46const READER_GRACE: Duration = Duration::from_secs(10);
47/// How long to wait for the child to exit after it has been told to stop.
48const STOP_GRACE: Duration = Duration::from_secs(30);
49
50/// Everything an executor needs to run one job.
51pub struct ExecRequest<'a> {
52 pub job: &'a JobAssignment,
53 /// The checked-out source tree. The script runs with it as `/workspace` or as its cwd.
54 pub workspace: &'a Path,
55 /// Where merged stdout and stderr go, one line per message.
56 pub logs: mpsc::Sender<Vec<u8>>,
57 /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`.
58 pub cancel: CancellationToken,
59 /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see
60 /// them leave it alone.
61 pub oom: OomSink,
62 /// The runner's memory budget now. The builtin executor gives a job without `memory` this as
63 /// its cgroup limit; `None` keeps the configured `limits.memory`.
64 pub memory_budget: Option<u64>,
65}
66
67/// The executor's answer. The runner adds timeouts and artifact results on top of it.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct ExecResult {
70 pub outcome: Outcome,
71 pub exit_code: Option<i32>,
72 pub message: Option<String>,
73}
74
75/// The boxed future an executor returns. Written out so `Executor` stays object safe.
76pub type ExecFuture<'a> = Pin<Box<dyn Future<Output = ExecResult> + Send + 'a>>;
77
78/// Runs jobs. The runner holds one as `Arc<dyn Executor>`.
79pub trait Executor: Send + Sync {
80 fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>;
81}
82
83/// An executor failure, reported as `Outcome::Error`.
84#[derive(Debug, thiserror::Error)]
85pub enum ExecError {
86 #[error("invalid job: {0}")]
87 Invalid(String),
88}
89
90/// Env names go to podman as `-e NAME`, so they must be plain identifiers. A name with `=` in it
91/// would carry a value into argv.
92pub fn validate_env_name(name: &str) -> Result<(), ExecError> {
93 let mut chars = name.chars();
94 let first_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_');
95 let rest_ok = chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
96 if first_ok && rest_ok && name.len() <= 256 {
97 Ok(())
98 } else {
99 Err(ExecError::Invalid(format!("bad env name {name:?}")))
100 }
101}
102
103/// The job's env and secrets as name/value pairs. Secrets win over plain env on a clash.
104pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError> {
105 let mut pairs: Vec<(String, String)> = Vec::new();
106 for (k, v) in job.env.iter().chain(job.secrets.iter()) {
107 validate_env_name(k)?;
108 pairs.retain(|(name, _)| name != k);
109 pairs.push((k.clone(), v.clone()));
110 }
111 Ok(pairs)
112}
113
114/// How many things a job should build at once: its CPU limit rounded up, at least 1 and at most
115/// the host's CPUs. The runner decides this, not the workflow, since only it knows the machine.
116pub fn job_parallelism(limits: &Limits) -> u32 {
117 let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
118 let cpus = limits
119 .cpus
120 .trim()
121 .parse::<f64>()
122 .ok()
123 .filter(|c| c.is_finite() && *c > 0.0)
124 .map_or(host, |c| c.ceil() as u32);
125 cpus.clamp(1, host.max(1))
126}
127
128/// The job's env with the runner's defaults under it: `FORGE_CPUS`, `FORGE_MEMORY_BYTES` (the job's
129/// memory limit) and the parallelism knobs common build tools read (cargo, make, cmake). A job that
130/// sets one of them itself keeps its own value.
131pub fn job_env_with_defaults(
132 job: &JobAssignment,
133 limits: &Limits,
134) -> Result<Vec<(String, String)>, ExecError> {
135 let n = job_parallelism(limits);
136 let mut pairs: Vec<(String, String)> = [
137 ("FORGE_CPUS", n.to_string()),
138 ("FORGE_MEMORY_BYTES", crate::sandbox::spec::parse_bytes(&limits.memory).map_or_else(|_| "0".to_owned(), |b| b.to_string())),
139 ("CARGO_BUILD_JOBS", n.to_string()),
140 ("MAKEFLAGS", format!("-j{n}")),
141 ("CMAKE_BUILD_PARALLEL_LEVEL", n.to_string()),
142 ]
143 .into_iter()
144 .map(|(k, v)| (k.to_owned(), v))
145 .collect();
146 for (k, v) in job_env(job)? {
147 pairs.retain(|(name, _)| *name != k);
148 pairs.push((k, v));
149 }
150 Ok(pairs)
151}
152
153/// The podman invocation for a job: argv (no values in it) and the env the child needs.
154#[derive(Debug, PartialEq, Eq)]
155pub struct PodmanInvocation {
156 pub args: Vec<String>,
157 pub env: Vec<(String, String)>,
158 pub container: String,
159}
160
161fn check_image(image: &str) -> Result<(), ExecError> {
162 // Podman would read a leading `-` as an option, and whitespace is never valid in a reference.
163 if image.is_empty() || image.starts_with('-') || image.contains(char::is_whitespace) {
164 return Err(ExecError::Invalid(format!("bad image {image:?}")));
165 }
166 Ok(())
167}
168
169fn check_limit(value: &str, what: &str) -> Result<(), ExecError> {
170 let ok = !value.is_empty()
171 && !value.starts_with('-')
172 && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '.');
173 if ok {
174 Ok(())
175 } else {
176 Err(ExecError::Invalid(format!("bad {what} limit {value:?}")))
177 }
178}
179
180/// Builds the podman invocation for `job`. Pure, so the argv can be tested.
181pub fn podman_invocation(
182 job: &JobAssignment,
183 workspace: &Path,
184 limits: &Limits,
185) -> Result<PodmanInvocation, ExecError> {
186 validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?;
187 check_image(&job.image)?;
188 let limits = &limits.for_job(job.memory_bytes);
189 check_limit(&limits.memory, "memory")?;
190 check_limit(&limits.cpus, "cpus")?;
191 let ws = workspace
192 .to_str()
193 .filter(|s| !s.contains(':') && !s.contains(','))
194 .ok_or_else(|| ExecError::Invalid("workspace path has a ':' or ','".into()))?;
195
196 let env = job_env_with_defaults(job, limits)?;
197 let container = format!("forge-job-{}", job.job_id);
198 let network = if job.network { "slirp4netns" } else { "none" };
199
200 let mut args: Vec<String> = [
201 "run",
202 "--rm",
203 "--name",
204 &container,
205 "--pull=newer",
206 &format!("--network={network}"),
207 "--memory",
208 &limits.memory,
209 "--memory-swap",
210 &limits.memory,
211 "--cpus",
212 &limits.cpus,
213 "--pids-limit",
214 ]
215 .iter()
216 .map(|s| (*s).to_owned())
217 .collect();
218 args.push(limits.pids.to_string());
219 for flag in [
220 "--security-opt",
221 "no-new-privileges",
222 "--cap-drop",
223 "ALL",
224 "-v",
225 ] {
226 args.push(flag.to_owned());
227 }
228 args.push(format!("{ws}:/workspace:Z"));
229 args.extend(["-w".to_owned(), "/workspace".to_owned()]);
230 for (name, _) in &env {
231 args.push("-e".to_owned());
232 args.push(name.clone());
233 }
234 args.push(job.image.clone());
235 args.extend([
236 "sh".to_owned(),
237 "-eu".to_owned(),
238 "-c".to_owned(),
239 job.run.clone(),
240 ]);
241
242 Ok(PodmanInvocation {
243 args,
244 env,
245 container,
246 })
247}
248
249/// How a finished child maps to a job result.
250fn classify(status: ExitStatus) -> ExecResult {
251 match status.code() {
252 Some(0) => ExecResult {
253 outcome: Outcome::Success,
254 exit_code: Some(0),
255 message: None,
256 },
257 // podman itself exits 125 when it cannot run the container (no image, no storage, ...).
258 Some(125) => ExecResult {
259 outcome: Outcome::Error,
260 exit_code: Some(125),
261 message: Some("podman failed to run the container (exit 125)".to_owned()),
262 },
263 Some(code) => ExecResult {
264 outcome: Outcome::Failure,
265 exit_code: Some(code),
266 message: None,
267 },
268 None => ExecResult {
269 outcome: Outcome::Failure,
270 exit_code: None,
271 message: Some("job was terminated by a signal".to_owned()),
272 },
273 }
274}
275
276fn error_result(message: impl Into<String>) -> ExecResult {
277 ExecResult {
278 outcome: Outcome::Error,
279 exit_code: None,
280 message: Some(message.into()),
281 }
282}
283
284/// How to stop a job when it is cancelled.
285enum Stopper {
286 Podman {
287 container: String,
288 },
289 #[cfg(any(test, feature = "test-host-executor"))]
290 ProcessGroup {
291 pid: u32,
292 },
293 /// The sandbox helper. It is sent SIGTERM and stops its own container, see [`stop_child`].
294 Helper {
295 pid: u32,
296 },
297}
298
299impl Stopper {
300 async fn stop(&self) {
301 match self {
302 Stopper::Podman { container } => {
303 let quiet = |cmd: &mut Command| {
304 cmd.stdin(Stdio::null())
305 .stdout(Stdio::null())
306 .stderr(Stdio::null());
307 };
308 let mut kill = Command::new("podman");
309 kill.args(["kill", container.as_str()]);
310 quiet(&mut kill);
311 let _ = kill.status().await;
312 let mut rm = Command::new("podman");
313 rm.args(["rm", "-f", container.as_str()]);
314 quiet(&mut rm);
315 let _ = rm.status().await;
316 }
317 #[cfg(any(test, feature = "test-host-executor"))]
318 Stopper::ProcessGroup { pid } => {
319 let mut kill = Command::new("kill");
320 kill.args(["-KILL", "--", &format!("-{pid}")])
321 .stdin(Stdio::null())
322 .stdout(Stdio::null())
323 .stderr(Stdio::null());
324 let _ = kill.status().await;
325 }
326 Stopper::Helper { .. } => {}
327 }
328 }
329}
330
331/// Stops the child on cancellation and returns its exit status.
332///
333/// The sandbox helper gets SIGTERM and gets to kill and delete its container itself. SIGKILL
334/// follows only if it does not exit within [`STOP_GRACE`]. Other children are killed at once.
335async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result<ExitStatus> {
336 if let Stopper::Helper { pid } = stopper {
337 let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM);
338 return match tokio::time::timeout(STOP_GRACE, child.wait()).await {
339 Ok(status) => status,
340 Err(_) => {
341 let _ = child.start_kill();
342 child.wait().await
343 }
344 };
345 }
346 stopper.stop().await;
347 let _ = child.start_kill();
348 tokio::time::timeout(STOP_GRACE, child.wait())
349 .await
350 .unwrap_or_else(|_| Err(std::io::Error::other("child did not stop")))
351}
352
353/// What [`supervise`] saw when the child finished.
354struct Supervised {
355 cancelled: bool,
356 status: std::io::Result<ExitStatus>,
357 /// The sandbox helper's last `forge-sandbox: <reason>` line on stderr, when it printed one.
358 sandbox_error: Option<String>,
359 /// The OOM counters the helper printed, when something in the job was OOM-killed.
360 oom: Option<OomEvents>,
361}
362
363/// Copies stderr lines to the log and remembers the last sandbox error line.
364async fn tap_sandbox_errors(
365 mut lines: mpsc::Receiver<Vec<u8>>,
366 logs: mpsc::Sender<Vec<u8>>,
367) -> (Option<String>, Option<OomEvents>) {
368 let mut found = None;
369 let mut oom = None;
370 while let Some(chunk) = lines.recv().await {
371 // The OOM line is for the runner, not for the job log.
372 if chunk.starts_with(SANDBOX_PREFIX)
373 && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk))
374 {
375 oom = Some(events);
376 continue;
377 }
378 let is_error = chunk.starts_with(SANDBOX_PREFIX)
379 && !chunk[SANDBOX_PREFIX.len()..].starts_with(b"warning:");
380 if is_error {
381 found = Some(String::from_utf8_lossy(&chunk).trim_end().to_owned());
382 }
383 if logs.send(chunk).await.is_err() {
384 break;
385 }
386 }
387 (found, oom)
388}
389
390/// Forwards the child's output, waits for it, and reports how it ended. On cancellation the
391/// child is stopped first. `cleanup` runs as soon as the child has exited, before the output is
392/// drained: a container keeps the output pipes open until it is killed.
393async fn supervise(
394 mut child: Child,
395 logs: mpsc::Sender<Vec<u8>>,
396 cancel: CancellationToken,
397 stopper: Stopper,
398 cleanup: Option<JobCleanup>,
399) -> Supervised {
400 let mut readers: Vec<JoinHandle<()>> = Vec::new();
401 if let Some(out) = child.stdout.take() {
402 readers.push(tokio::spawn(forward_lines(out, logs.clone())));
403 }
404 let mut tap = None;
405 if let Some(err) = child.stderr.take() {
406 let (tx, rx) = mpsc::channel(64);
407 readers.push(tokio::spawn(forward_lines(err, tx)));
408 tap = Some(tokio::spawn(tap_sandbox_errors(rx, logs.clone())));
409 }
410 drop(logs);
411
412 // The wait future must be dropped before the stop path borrows the child again.
413 let early = tokio::select! {
414 status = child.wait() => Some(status),
415 _ = cancel.cancelled() => None,
416 };
417 let (status, cancelled) = match early {
418 Some(status) => (status, false),
419 None => (stop_child(&mut child, stopper).await, true),
420 };
421 if let Some(job) = cleanup {
422 reap_job(&job).await;
423 }
424
425 let drain = async {
426 for reader in readers.iter_mut() {
427 let _ = reader.await;
428 }
429 };
430 if tokio::time::timeout(READER_GRACE, drain).await.is_err() {
431 // A grandchild still holds the pipe. Stop reading rather than hang the job.
432 for reader in &readers {
433 reader.abort();
434 }
435 }
436 let (sandbox_error, oom) = match tap {
437 Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await {
438 Ok(Ok(found)) => found,
439 _ => (None, None),
440 },
441 None => (None, None),
442 };
443
444 Supervised {
445 cancelled,
446 status,
447 sandbox_error,
448 oom,
449 }
450}
451
452/// The result for a child that was supervised with the podman or host rules.
453fn finish(supervised: Supervised) -> ExecResult {
454 if supervised.cancelled {
455 return cancelled_result();
456 }
457 match supervised.status {
458 Ok(status) => classify(status),
459 Err(e) => error_result(format!("waiting for the job failed: {e}")),
460 }
461}
462
463fn cancelled_result() -> ExecResult {
464 ExecResult {
465 outcome: Outcome::Cancelled,
466 exit_code: None,
467 message: Some("job was cancelled".to_owned()),
468 }
469}
470
471/// Runs jobs in rootless podman.
472#[derive(Clone, Debug)]
473pub struct PodmanExecutor {
474 limits: Limits,
475}
476
477impl PodmanExecutor {
478 pub fn new(limits: Limits) -> Self {
479 Self { limits }
480 }
481}
482
483impl Executor for PodmanExecutor {
484 fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> {
485 Box::pin(async move {
486 let inv = match podman_invocation(req.job, req.workspace, &self.limits) {
487 Ok(inv) => inv,
488 Err(e) => return error_result(e.to_string()),
489 };
490 let mut cmd = Command::new("podman");
491 cmd.args(&inv.args)
492 .envs(inv.env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
493 .stdin(Stdio::null())
494 .stdout(Stdio::piped())
495 .stderr(Stdio::piped())
496 .kill_on_drop(true);
497 let child = match cmd.spawn() {
498 Ok(child) => child,
499 Err(e) => return error_result(format!("cannot start podman: {e}")),
500 };
501 finish(
502 supervise(
503 child,
504 req.logs,
505 req.cancel,
506 Stopper::Podman {
507 container: inv.container,
508 },
509 None,
510 )
511 .await,
512 )
513 })
514 }
515}
516
517/// Runs the script on the host with no isolation. Tests only.
518#[cfg(any(test, feature = "test-host-executor"))]
519#[derive(Clone, Copy, Debug, Default)]
520pub struct HostExecutor;
521
522#[cfg(any(test, feature = "test-host-executor"))]
523impl Executor for HostExecutor {
524 fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> {
525 Box::pin(async move {
526 let env = match job_env(req.job) {
527 Ok(env) => env,
528 Err(e) => return error_result(e.to_string()),
529 };
530 let mut cmd = Command::new("sh");
531 cmd.args(["-eu", "-c", req.job.run.as_str()])
532 .current_dir(req.workspace)
533 .envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
534 .stdin(Stdio::null())
535 .stdout(Stdio::piped())
536 .stderr(Stdio::piped())
537 .process_group(0)
538 .kill_on_drop(true);
539 let child = match cmd.spawn() {
540 Ok(child) => child,
541 Err(e) => return error_result(format!("cannot start sh: {e}")),
542 };
543 let Some(pid) = child.id() else {
544 return error_result("child exited before its pid was read");
545 };
546 finish(
547 supervise(
548 child,
549 req.logs,
550 req.cancel,
551 Stopper::ProcessGroup { pid },
552 None,
553 )
554 .await,
555 )
556 })
557 }
558}
559
560/// Where the builtin executor gets its rootfs. [`ImageStore`] pulls and unpacks images. Tests
561/// supply a local rootfs directory instead.
562pub trait ImageSource: Send + Sync {
563 /// Makes `image` available and returns its rootfs and config. Progress lines go to `log`.
564 fn prepare<'a>(
565 &'a self,
566 image: &'a str,
567 auth: Option<&'a RegistryAuth>,
568 log: &'a mpsc::Sender<Vec<u8>>,
569 ) -> impl Future<Output = Result<PreparedImage, ImageError>> + Send + 'a;
570}
571
572impl ImageSource for ImageStore {
573 fn prepare<'a>(
574 &'a self,
575 image: &'a str,
576 auth: Option<&'a RegistryAuth>,
577 log: &'a mpsc::Sender<Vec<u8>>,
578 ) -> impl Future<Output = Result<PreparedImage, ImageError>> + Send + 'a {
579 self.ensure(image, auth, log)
580 }
581}
582
583/// Runs jobs in a libcontainer sandbox, started as `helper` (`forge-runner __sandbox`). It needs
584/// no external container tool. See `docs/ci.md`.
585pub struct BuiltinExecutor<I = ImageStore> {
586 images: I,
587 limits: Limits,
588 helper: PathBuf,
589 /// Holds one `<job id>` directory per running job, for the overlay and container state.
590 jobs_dir: PathBuf,
591 /// `[[registry]]` logins, as (host, login).
592 registries: Vec<(String, RegistryAuth)>,
593 /// The id map jobs run under. Single unless set by [`BuiltinExecutor::with_idmap`].
594 idmap: IdMap,
595}
596
597impl<I: ImageSource> BuiltinExecutor<I> {
598 pub fn new(images: I, limits: Limits, helper: PathBuf, jobs_dir: PathBuf) -> Self {
599 Self {
600 images,
601 limits,
602 helper,
603 jobs_dir,
604 registries: Vec::new(),
605 idmap: IdMap::single(),
606 }
607 }
608
609 /// Sets the id map that jobs run under. Job dirs are removed under it too.
610 pub fn with_idmap(mut self, map: IdMap) -> Self {
611 self.idmap = map;
612 self
613 }
614
615 /// Sets the `[[registry]]` logins. Each one is used for images on its host.
616 pub fn with_registries(mut self, registries: &[RegistryConfig]) -> Self {
617 self.registries = registries
618 .iter()
619 .map(|r| {
620 (
621 r.host.clone(),
622 RegistryAuth {
623 username: r.username.clone(),
624 password: r.password.clone(),
625 },
626 )
627 })
628 .collect();
629 self
630 }
631
632 /// The login for `image`, matched by its registry host. Docker Hub is `docker.io`.
633 fn auth_for(&self, image: &str) -> Option<&RegistryAuth> {
634 let reference: Reference = image.parse().ok()?;
635 let host = reference.registry();
636 self.registries
637 .iter()
638 .find(|(registry, _)| registry == host)
639 .map(|(_, auth)| auth)
640 }
641
642 async fn run_job(&self, req: ExecRequest<'_>) -> ExecResult {
643 let ExecRequest {
644 job,
645 workspace,
646 logs,
647 cancel,
648 oom: oom_sink,
649 memory_budget,
650 } = req;
651 let limits = self.limits.for_builtin_job(job.memory_bytes, memory_budget);
652 let disk_gb = limits.job_disk_gb;
653 if let Err(e) = validate_job_id(&job.job_id) {
654 return error_result(e.to_string());
655 }
656 if let Err(e) = check_image(&job.image) {
657 return error_result(e.to_string());
658 }
659 let env = match job_env_with_defaults(job, &limits) {
660 Ok(env) => env,
661 Err(e) => return error_result(e.to_string()),
662 };
663
664 let auth = self.auth_for(&job.image);
665 let prepared = tokio::select! {
666 prepared = self.images.prepare(&job.image, auth, &logs) => prepared,
667 _ = cancel.cancelled() => return cancelled_result(),
668 };
669 let image = match prepared {
670 Ok(image) => image,
671 Err(e) => return error_result(format!("cannot prepare image {}: {e}", job.image)),
672 };
673 let _ = logs
674 .send(format!("image {}\n", image.digest).into_bytes())
675 .await;
676
677 let job_dir = self.jobs_dir.join(&job.job_id);
678 // A leftover from an earlier run of this job id would hold stale overlay state, and maybe
679 // the pid of a pasta that outlived its helper.
680 crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir));
681 if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await {
682 tracing::warn!("cannot remove stale {}: {e}", job_dir.display());
683 }
684 let pasta = if job.network {
685 let pasta = crate::sandbox::net::find_pasta();
686 if pasta.is_none() {
687 let _ = logs
688 .send(
689 b"runner: pasta is not installed, so this job shares the runner's network; \
690 install passt to isolate it\n"
691 .to_vec(),
692 )
693 .await;
694 }
695 pasta
696 } else {
697 None
698 };
699 let request = SandboxRequest {
700 job_id: job.job_id.clone(),
701 rootfs: image.rootfs,
702 job_dir,
703 workspace: workspace.to_owned(),
704 image_env: image.env,
705 env,
706 run: job.run.clone(),
707 network: job.network,
708 pasta,
709 limits,
710 idmap: self.idmap.clone(),
711 };
712 // The request holds the secrets. It goes to the helper's stdin and nowhere else.
713 let json = match serde_json::to_vec(&request) {
714 Ok(json) => json,
715 Err(e) => return error_result(format!("cannot encode the sandbox request: {e}")),
716 };
717 drop(request);
718
719 let mut cmd = Command::new(&self.helper);
720 cmd.arg("__sandbox")
721 .stdin(Stdio::piped())
722 .stdout(Stdio::piped())
723 .stderr(Stdio::piped())
724 .kill_on_drop(true);
725 let mut child = match cmd.spawn() {
726 Ok(child) => child,
727 Err(e) => return error_result(format!("cannot start the sandbox helper: {e}")),
728 };
729 let Some(pid) = child.id() else {
730 return error_result("sandbox helper exited before its pid was read");
731 };
732 if let Some(mut stdin) = child.stdin.take() {
733 // The helper reads the whole request before it does anything else.
734 if let Err(e) = stdin.write_all(&json).await {
735 return error_result(format!("cannot send the job to the sandbox helper: {e}"));
736 }
737 }
738 drop(json);
739
740 // The disk cap stops the job through its own token, so a stop for disk can be told apart
741 // from a cancel.
742 let job_cancel = cancel.child_token();
743 let over_disk = Arc::new(AtomicBool::new(false));
744 let disk_cap = disk_gb.saturating_mul(1 << 30);
745 let watcher = (disk_cap > 0).then(|| {
746 let job_dir = self.jobs_dir.join(&job.job_id);
747 let roots = vec![
748 workspace.to_owned(),
749 job_dir.join("tmp"),
750 job_dir.join("overlay/upper"),
751 ];
752 tokio::spawn(crate::disk::watch(
753 roots,
754 disk_cap,
755 job_cancel.clone(),
756 Arc::clone(&over_disk),
757 ))
758 });
759 let Supervised {
760 cancelled,
761 status,
762 sandbox_error,
763 oom,
764 } = supervise(
765 child,
766 logs,
767 job_cancel,
768 Stopper::Helper { pid },
769 Some(JobCleanup {
770 helper_pid: pid,
771 job_id: job.job_id.clone(),
772 job_dir: self.jobs_dir.join(&job.job_id),
773 idmap: self.idmap.clone(),
774 helper: self.helper.clone(),
775 }),
776 )
777 .await;
778 if let Some(watcher) = watcher {
779 watcher.abort();
780 }
781 if let Some(events) = oom {
782 oom_sink.record(events);
783 }
784 if over_disk.load(Ordering::SeqCst) && !cancel.is_cancelled() {
785 return ExecResult {
786 outcome: Outcome::Failure,
787 exit_code: None,
788 message: Some(format!(
789 "job was stopped: it filled more than {disk_gb} GB of disk (workspace, /tmp \
790 and writes over the image)"
791 )),
792 };
793 }
794 if cancelled {
795 return cancelled_result();
796 }
797 match status {
798 Err(e) => error_result(format!("waiting for the sandbox failed: {e}")),
799 Ok(status) => match status.code() {
800 Some(0) => ExecResult {
801 outcome: Outcome::Success,
802 exit_code: Some(0),
803 message: None,
804 },
805 // The helper's own setup failure. A job that exits 125 by itself is a failure.
806 Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => {
807 let line = sandbox_error.unwrap_or_default();
808 let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line);
809 ExecResult {
810 outcome: Outcome::Error,
811 exit_code: Some(EXIT_SETUP_FAILED),
812 message: Some(format!("sandbox setup failed: {reason}")),
813 }
814 }
815 Some(code) => ExecResult {
816 outcome: Outcome::Failure,
817 exit_code: Some(code),
818 message: None,
819 },
820 None => ExecResult {
821 outcome: Outcome::Failure,
822 exit_code: None,
823 message: Some("job was terminated by a signal".to_owned()),
824 },
825 },
826 }
827 }
828}
829
830/// Where cgroup2 is mounted. Job cgroup paths are relative to it.
831const CGROUP_ROOT: &str = "/sys/fs/cgroup";
832/// How often, and how many times, to retry removing a job cgroup while its processes exit.
833const REAP_POLL: Duration = Duration::from_millis(100);
834const REAP_POLLS: u32 = 50;
835
836/// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up).
837/// Older kernels get a SIGKILL to each pid in `cgroup.procs`.
838pub(crate) fn kill_cgroup(dir: &Path) {
839 if fs::write(dir.join("cgroup.kill"), "1").is_ok() {
840 return;
841 }
842 let Ok(procs) = fs::read_to_string(dir.join("cgroup.procs")) else {
843 return;
844 };
845 for pid in procs
846 .lines()
847 .filter_map(|line| line.trim().parse::<i32>().ok())
848 {
849 let _ = kill(Pid::from_raw(pid), Signal::SIGKILL);
850 }
851}
852
853/// What to clean up once a job's sandbox helper has exited. See [`reap_job`].
854struct JobCleanup {
855 helper_pid: u32,
856 job_id: String,
857 job_dir: PathBuf,
858 idmap: IdMap,
859 helper: PathBuf,
860}
861
862/// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL
863/// cannot delete its container, so the container could otherwise keep running. This kills what is
864/// left in the job cgroup, removes the cgroup, stops a leftover pasta, and removes the job dir.
865async fn reap_job(job: &JobCleanup) {
866 if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) {
867 let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative));
868 if dir.exists() {
869 kill_cgroup(&dir);
870 // rmdir fails while processes remain, so retry until they have exited.
871 for _ in 0..REAP_POLLS {
872 if fs::remove_dir(&dir).is_ok() || !dir.exists() {
873 break;
874 }
875 tokio::time::sleep(REAP_POLL).await;
876 }
877 }
878 }
879 // A helper killed with SIGKILL could not stop its pasta either.
880 crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir));
881 if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await {
882 tracing::warn!("cannot remove {}: {e}", job.job_dir.display());
883 }
884}
885
886/// Cleans up after an earlier run of the runner that did not get to (a crash, a SIGKILL, a power
887/// cut): for every leftover `work_dir/jobs/<id>` it stops a pasta, kills the job's cgroups and
888/// removes the dir, and it removes leftover workspaces `work_dir/<id>`. Call it at startup,
889/// before any job runs. Only job ids found in this runner's own dirs are touched, so another
890/// runner's jobs in a shared cgroup are left alone.
891pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) {
892 let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned());
893 let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await;
894 if let Err(e) = swept {
895 tracing::warn!("cannot sweep leftover jobs: {e}");
896 }
897}
898
899fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) {
900 let jobs_dir = work_dir.join("jobs");
901 let cgroup_bases: Vec<PathBuf> = crate::sandbox::helper::job_cgroup_base()
902 .map(|base| {
903 let base = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base));
904 vec![base.join(crate::sandbox::helper::BOX_NAME), base]
905 })
906 .unwrap_or_default();
907 for job_id in job_ids_in(&jobs_dir) {
908 let job_dir = jobs_dir.join(&job_id);
909 tracing::info!("removing leftover job {job_id}");
910 crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir));
911 let prefix = format!("forge-job-{job_id}-");
912 for base in &cgroup_bases {
913 let Ok(entries) = fs::read_dir(base) else {
914 continue;
915 };
916 for entry in entries.flatten() {
917 let name = entry.file_name();
918 let Some(pid) = name.to_str().and_then(|n| n.strip_prefix(&prefix)) else {
919 continue;
920 };
921 if pid.parse::<u32>().is_err() {
922 continue;
923 }
924 let dir = entry.path();
925 kill_cgroup(&dir);
926 for _ in 0..REAP_POLLS {
927 if fs::remove_dir(&dir).is_ok() || !dir.exists() {
928 break;
929 }
930 std::thread::sleep(REAP_POLL);
931 }
932 }
933 }
934 if let Err(e) = remove_tree(map, &job_dir, helper) {
935 tracing::warn!("cannot remove {}: {e}", job_dir.display());
936 }
937 }
938 // `work_dir` may be shared with other files (an operator could point it at a home dir), so
939 // only names shaped like the forge's job ids (ULIDs) count as workspaces.
940 for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) {
941 let workspace = work_dir.join(&job_id);
942 tracing::info!("removing leftover workspace {job_id}");
943 if let Err(e) = remove_tree(map, &workspace, helper) {
944 tracing::warn!("cannot remove {}: {e}", workspace.display());
945 }
946 }
947}
948
949/// 26 Crockford base32 digits, the shape of every job id the forge hands out.
950fn is_ulid(name: &str) -> bool {
951 name.len() == 26
952 && name
953 .bytes()
954 .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b)))
955}
956
957/// The names of the dirs in `dir` that are valid job ids. Symlinks are skipped.
958fn job_ids_in(dir: &Path) -> Vec<String> {
959 let Ok(entries) = fs::read_dir(dir) else {
960 return Vec::new();
961 };
962 entries
963 .flatten()
964 .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir()))
965 .filter_map(|entry| entry.file_name().into_string().ok())
966 .filter(|name| validate_job_id(name).is_ok())
967 .collect()
968}
969
970/// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through
971/// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async
972/// runtime.
973async fn remove_job_dir(map: &IdMap, helper: &Path, job_dir: &Path) -> std::io::Result<()> {
974 let (map, helper, job_dir) = (map.clone(), helper.to_owned(), job_dir.to_owned());
975 tokio::task::spawn_blocking(move || remove_tree(&map, &job_dir, &helper))
976 .await
977 .map_err(std::io::Error::other)?
978}
979
980impl<I: ImageSource> Executor for BuiltinExecutor<I> {
981 fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> {
982 Box::pin(self.run_job(req))
983 }
984}
985
986#[cfg(test)]
987mod tests {
988 use super::*;
989 use std::collections::BTreeMap;
990
991 #[test]
992 fn sweep_removes_only_leftover_jobs_and_ulid_workspaces() {
993 let dir = tempfile::tempdir().unwrap();
994 let work = dir.path();
995 for d in ["jobs/job_01/overlay", "01JD6Z8Q4XW3N5R7T9V2B4C6E8/src", "oci", "notes", "check-7"] {
996 fs::create_dir_all(work.join(d)).unwrap();
997 }
998 fs::create_dir_all(work.join(".cache")).unwrap();
999 sweep_blocking(work, &IdMap::single(), Path::new("/nonexistent"));
1000 assert!(!work.join("jobs/job_01").exists());
1001 assert!(!work.join("01JD6Z8Q4XW3N5R7T9V2B4C6E8").exists());
1002 for kept in ["jobs", "oci", "notes", "check-7", ".cache"] {
1003 assert!(work.join(kept).exists(), "{kept} was removed");
1004 }
1005 }
1006
1007 const SECRET: &str = "hunter2-SUPER-SECRET-value";
1008
1009 pub(crate) fn fixture_job(run: &str) -> JobAssignment {
1010 JobAssignment {
1011 job_id: "job_01".to_owned(),
1012 job_token: "tok_01_secret_token".to_owned(),
1013 repo: "owner/name".to_owned(),
1014 clone_url: "https://forge.example/owner/name.git".to_owned(),
1015 commit: "a".repeat(40),
1016 git_ref: "refs/heads/main".to_owned(),
1017 job_name: "build".to_owned(),
1018 image: "docker.io/library/alpine:3".to_owned(),
1019 run: run.to_owned(),
1020 env: BTreeMap::from([("PLAIN".to_owned(), "visible".to_owned())]),
1021 secrets: BTreeMap::from([("MY_TOKEN".to_owned(), SECRET.to_owned())]),
1022 artifacts: Vec::new(),
1023 timeout_minutes: 5,
1024 network: false,
1025 cache: Vec::new(),
1026 cache_key: String::new(),
1027 cache_restore_keys: Vec::new(),
1028 memory_bytes: None,
1029 }
1030 }
1031
1032 #[test]
1033 fn podman_argv_never_contains_a_secret_value() {
1034 let job = fixture_job("echo $MY_TOKEN");
1035 let inv = podman_invocation(&job, Path::new("/work/job_01"), &Limits::default())
1036 .expect("invocation");
1037 assert!(inv.args.iter().all(|a| !a.contains(SECRET)));
1038 assert!(inv.args.iter().all(|a| !a.contains("visible")));
1039 // The values travel in the child env, by name.
1040 assert!(
1041 inv.env
1042 .contains(&("MY_TOKEN".to_owned(), SECRET.to_owned()))
1043 );
1044 assert!(
1045 inv.env
1046 .contains(&("PLAIN".to_owned(), "visible".to_owned()))
1047 );
1048 let names: Vec<&str> = inv
1049 .args
1050 .windows(2)
1051 .filter(|w| w[0] == "-e")
1052 .map(|w| w[1].as_str())
1053 .collect();
1054 assert_eq!(
1055 names,
1056 vec!["FORGE_CPUS", "FORGE_MEMORY_BYTES", "CARGO_BUILD_JOBS", "MAKEFLAGS", "CMAKE_BUILD_PARALLEL_LEVEL", "PLAIN", "MY_TOKEN"]
1057 );
1058 }
1059
1060 #[test]
1061 fn podman_argv_has_the_isolation_flags() {
1062 let job = fixture_job("true");
1063 let inv = podman_invocation(&job, Path::new("/work/job_01"), &Limits::default())
1064 .expect("invocation");
1065 let joined = inv.args.join(" ");
1066 assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer"));
1067 assert!(joined.contains("--network=none"));
1068 assert!(joined.contains("--memory 4g --memory-swap 4g --cpus 2 --pids-limit 4096"));
1069 assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL"));
1070 assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace"));
1071 assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true"));
1072 }
1073
1074 #[test]
1075 fn network_true_selects_slirp() {
1076 let mut job = fixture_job("true");
1077 job.network = true;
1078 let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv");
1079 assert!(inv.args.contains(&"--network=slirp4netns".to_owned()));
1080 }
1081
1082 #[test]
1083 fn a_declared_memory_sets_the_podman_limit() {
1084 let mut job = fixture_job("true");
1085 job.memory_bytes = Some(4 << 30);
1086 let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv");
1087 let joined = inv.args.join(" ");
1088 // 4 GiB plus the 256 MiB slack, and no swap on top.
1089 let limit = (4u64 << 30) + (256 << 20);
1090 assert!(
1091 joined.contains(&format!("--memory {limit} --memory-swap {limit}")),
1092 "{joined}"
1093 );
1094 }
1095
1096 #[test]
1097 fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() {
1098 let mut job = fixture_job("true");
1099 let limits = Limits { cpus: "0.5".to_owned(), ..Limits::default() };
1100 let env = job_env_with_defaults(&job, &limits).expect("env");
1101 assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned())));
1102 job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned());
1103 let env = job_env_with_defaults(&job, &limits).expect("env");
1104 let jobs: Vec<_> = env.iter().filter(|(k, _)| k == "CARGO_BUILD_JOBS").collect();
1105 assert_eq!(jobs, [&("CARGO_BUILD_JOBS".to_owned(), "7".to_owned())]);
1106 }
1107
1108 #[test]
1109 fn hostile_values_are_refused() {
1110 let ws = Path::new("/w");
1111 let mut job = fixture_job("true");
1112 job.image = "--privileged".to_owned();
1113 assert!(podman_invocation(&job, ws, &Limits::default()).is_err());
1114
1115 let mut job = fixture_job("true");
1116 job.env.insert("A=B".to_owned(), "x".to_owned());
1117 assert!(podman_invocation(&job, ws, &Limits::default()).is_err());
1118
1119 let mut job = fixture_job("true");
1120 job.job_id = "../escape".to_owned();
1121 assert!(podman_invocation(&job, ws, &Limits::default()).is_err());
1122
1123 let job = fixture_job("true");
1124 assert!(podman_invocation(&job, Path::new("/w:evil"), &Limits::default()).is_err());
1125 }
1126
1127 #[test]
1128 fn exit_codes_map_to_outcomes() {
1129 use std::os::unix::process::ExitStatusExt;
1130 let ok = classify(ExitStatus::from_raw(0));
1131 assert_eq!(ok.outcome, Outcome::Success);
1132 let fail = classify(ExitStatus::from_raw(3 << 8));
1133 assert_eq!(fail.outcome, Outcome::Failure);
1134 assert_eq!(fail.exit_code, Some(3));
1135 let podman = classify(ExitStatus::from_raw(125 << 8));
1136 assert_eq!(podman.outcome, Outcome::Error);
1137 }
1138
1139 /// Needs rootless podman and network access to pull the image.
1140 #[tokio::test]
1141 #[ignore = "requires rootless podman and registry access"]
1142 async fn podman_runs_a_real_container() {
1143 let dir = tempfile::tempdir().expect("tempdir");
1144 let ws = dir.path().join("ws");
1145 std::fs::create_dir_all(&ws).expect("mkdir");
1146 let job = fixture_job(
1147 "echo hi-from-container; echo \"s=$MY_TOKEN\" >&2; touch /workspace/out.txt",
1148 );
1149 let (tx, mut rx) = mpsc::channel(64);
1150 let exec = PodmanExecutor::new(Limits::default());
1151 let result = exec
1152 .run(ExecRequest {
1153 job: &job,
1154 workspace: &ws,
1155 logs: tx,
1156 cancel: CancellationToken::new(),
1157 oom: OomSink::default(),
1158 memory_budget: None,
1159 })
1160 .await;
1161 assert_eq!(result.outcome, Outcome::Success, "{result:?}");
1162 let mut all = Vec::new();
1163 while let Some(chunk) = rx.recv().await {
1164 all.extend_from_slice(&chunk);
1165 }
1166 let text = String::from_utf8_lossy(&all).into_owned();
1167 assert!(text.contains("hi-from-container"));
1168 assert!(ws.join("out.txt").exists());
1169 }
1170}