| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::fs; |
| 15 | use std::future::Future; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::pin::Pin; |
| 18 | use std::process::{ExitStatus, Stdio}; |
| 19 | use std::time::Duration; |
| 20 | |
| 21 | use forge_ci::proto::{JobAssignment, Outcome}; |
| 22 | use nix::sys::signal::{Signal, kill}; |
| 23 | use nix::unistd::Pid; |
| 24 | use oci_client::Reference; |
| 25 | use tokio::io::AsyncWriteExt; |
| 26 | use tokio::process::{Child, Command}; |
| 27 | use tokio::sync::mpsc; |
| 28 | use tokio::task::JoinHandle; |
| 29 | use tokio_util::sync::CancellationToken; |
| 30 | |
| 31 | use crate::config::{Limits, RegistryConfig}; |
| 32 | use crate::logs::forward_lines; |
| 33 | use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; |
| 34 | use crate::oom::{OomEvents, OomSink}; |
| 35 | use crate::sandbox::helper::EXIT_SETUP_FAILED; |
| 36 | use crate::sandbox::idmap::{IdMap, remove_tree}; |
| 37 | use crate::sandbox::{SandboxRequest, job_cgroup_path}; |
| 38 | use crate::workspace::validate_job_id; |
| 39 | |
| 40 | |
| 41 | const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: "; |
| 42 | |
| 43 | |
| 44 | const READER_GRACE: Duration = Duration::from_secs(10); |
| 45 | |
| 46 | const STOP_GRACE: Duration = Duration::from_secs(30); |
| 47 | |
| 48 | |
| 49 | pub struct ExecRequest<'a> { |
| 50 | pub job: &'a JobAssignment, |
| 51 | |
| 52 | pub workspace: &'a Path, |
| 53 | |
| 54 | pub logs: mpsc::Sender<Vec<u8>>, |
| 55 | |
| 56 | pub cancel: CancellationToken, |
| 57 | |
| 58 | |
| 59 | pub oom: OomSink, |
| 60 | } |
| 61 | |
| 62 | |
| 63 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 64 | pub struct ExecResult { |
| 65 | pub outcome: Outcome, |
| 66 | pub exit_code: Option<i32>, |
| 67 | pub message: Option<String>, |
| 68 | } |
| 69 | |
| 70 | |
| 71 | pub type ExecFuture<'a> = Pin<Box<dyn Future<Output = ExecResult> + Send + 'a>>; |
| 72 | |
| 73 | |
| 74 | pub trait Executor: Send + Sync { |
| 75 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>; |
| 76 | } |
| 77 | |
| 78 | |
| 79 | #[derive(Debug, thiserror::Error)] |
| 80 | pub enum ExecError { |
| 81 | #[error("invalid job: {0}")] |
| 82 | Invalid(String), |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | pub 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 | |
| 99 | pub 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 | |
| 110 | #[derive(Debug, PartialEq, Eq)] |
| 111 | pub struct PodmanInvocation { |
| 112 | pub args: Vec<String>, |
| 113 | pub env: Vec<(String, String)>, |
| 114 | pub container: String, |
| 115 | } |
| 116 | |
| 117 | fn check_image(image: &str) -> Result<(), ExecError> { |
| 118 | |
| 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 | |
| 125 | fn 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 | |
| 137 | pub 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 | |
| 206 | fn 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 | |
| 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 | |
| 232 | fn 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 | |
| 241 | enum Stopper { |
| 242 | Podman { |
| 243 | container: String, |
| 244 | }, |
| 245 | #[cfg(any(test, feature = "test-host-executor"))] |
| 246 | ProcessGroup { |
| 247 | pid: u32, |
| 248 | }, |
| 249 | |
| 250 | Helper { |
| 251 | pid: u32, |
| 252 | }, |
| 253 | } |
| 254 | |
| 255 | impl 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 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | async 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 | |
| 310 | struct Supervised { |
| 311 | cancelled: bool, |
| 312 | status: std::io::Result<ExitStatus>, |
| 313 | |
| 314 | sandbox_error: Option<String>, |
| 315 | |
| 316 | oom: Option<OomEvents>, |
| 317 | } |
| 318 | |
| 319 | |
| 320 | async 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 | |
| 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 | |
| 347 | |
| 348 | |
| 349 | async 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 | |
| 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 | |
| 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 | |
| 409 | fn 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 | |
| 419 | fn 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 | |
| 428 | #[derive(Clone, Debug)] |
| 429 | pub struct PodmanExecutor { |
| 430 | limits: Limits, |
| 431 | } |
| 432 | |
| 433 | impl PodmanExecutor { |
| 434 | pub fn new(limits: Limits) -> Self { |
| 435 | Self { limits } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | impl 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 | |
| 474 | #[cfg(any(test, feature = "test-host-executor"))] |
| 475 | #[derive(Clone, Copy, Debug, Default)] |
| 476 | pub struct HostExecutor; |
| 477 | |
| 478 | #[cfg(any(test, feature = "test-host-executor"))] |
| 479 | impl 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 | |
| 517 | |
| 518 | pub trait ImageSource: Send + Sync { |
| 519 | |
| 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 | |
| 528 | impl 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 | |
| 540 | |
| 541 | pub struct BuiltinExecutor<I = ImageStore> { |
| 542 | images: I, |
| 543 | limits: Limits, |
| 544 | helper: PathBuf, |
| 545 | |
| 546 | jobs_dir: PathBuf, |
| 547 | |
| 548 | registries: Vec<(String, RegistryAuth)>, |
| 549 | |
| 550 | idmap: IdMap, |
| 551 | } |
| 552 | |
| 553 | impl<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 | |
| 566 | pub fn with_idmap(mut self, map: IdMap) -> Self { |
| 567 | self.idmap = map; |
| 568 | self |
| 569 | } |
| 570 | |
| 571 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 734 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; |
| 735 | |
| 736 | const REAP_POLL: Duration = Duration::from_millis(100); |
| 737 | const REAP_POLLS: u32 = 50; |
| 738 | |
| 739 | |
| 740 | |
| 741 | pub(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 | |
| 757 | struct JobCleanup { |
| 758 | helper_pid: u32, |
| 759 | job_id: String, |
| 760 | job_dir: PathBuf, |
| 761 | idmap: IdMap, |
| 762 | helper: PathBuf, |
| 763 | } |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | async 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 | |
| 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 | |
| 788 | |
| 789 | |
| 790 | async 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 | |
| 797 | impl<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)] |
| 804 | mod 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 | |
| 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 | |
| 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 | |
| 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 | } |