forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBe587be7Tahinli15 hours ago323 commits

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