forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

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