forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB41ee476Tahinli29 days ago283 commits

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