forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·9.3 MiB·e910f7e·Tahinli·2 hours ago·361 commits
| 1 | use std::fs; |
| 2 | use std::future::Future; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::pin::Pin; |
| 5 | use std::process::{ExitStatus, Stdio}; |
| 6 | use std::sync::Arc; |
| 7 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 8 | use std::time::Duration; |
| 9 | |
| 10 | use forge_ci::proto::{JobAssignment, Outcome}; |
| 11 | use nix::sys::signal::{Signal, kill}; |
| 12 | use nix::unistd::Pid; |
| 13 | use oci_client::Reference; |
| 14 | use tokio::io::AsyncWriteExt; |
| 15 | use tokio::process::{Child, Command}; |
| 16 | use tokio::sync::mpsc; |
| 17 | use tokio::task::JoinHandle; |
| 18 | use tokio_util::sync::CancellationToken; |
| 19 | |
| 20 | use crate::config::{Limits, RegistryConfig}; |
| 21 | use crate::logs::forward_lines; |
| 22 | use crate::oci::{ImageError, ImageStore, PreparedImage, RegistryAuth}; |
| 23 | use crate::oom::{OomEvents, OomSink}; |
| 24 | use crate::sandbox::helper::EXIT_SETUP_FAILED; |
| 25 | use crate::sandbox::idmap::{IdMap, remove_tree}; |
| 26 | use crate::sandbox::{SandboxRequest, job_cgroup_path, new_token, strip_line}; |
| 27 | use crate::workspace::validate_job_id; |
| 28 | |
| 29 | const READER_GRACE: Duration = Duration::from_secs(10); |
| 30 | const STOP_GRACE: Duration = Duration::from_secs(30); |
| 31 | |
| 32 | pub struct ExecRequest<'a> { |
| 33 | pub job: &'a JobAssignment, |
| 34 | pub workspace: &'a Path, |
| 35 | pub logs: mpsc::Sender<Vec<u8>>, |
| 36 | pub cancel: CancellationToken, |
| 37 | pub oom: OomSink, |
| 38 | } |
| 39 | |
| 40 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 41 | pub struct ExecResult { |
| 42 | pub outcome: Outcome, |
| 43 | pub exit_code: Option<i32>, |
| 44 | pub message: Option<String>, |
| 45 | } |
| 46 | |
| 47 | pub type ExecFuture<'a> = Pin<Box<dyn Future<Output = ExecResult> + Send + 'a>>; |
| 48 | |
| 49 | pub trait Executor: Send + Sync { |
| 50 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>; |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, thiserror::Error)] |
| 54 | pub enum ExecError { |
| 55 | #[error("invalid job: {0}")] |
| 56 | Invalid(String), |
| 57 | } |
| 58 | |
| 59 | pub fn validate_env_name(name: &str) -> Result<(), ExecError> { |
| 60 | let mut chars = name.chars(); |
| 61 | let first_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_'); |
| 62 | let rest_ok = chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); |
| 63 | if first_ok && rest_ok && name.len() <= 256 { |
| 64 | Ok(()) |
| 65 | } else { |
| 66 | Err(ExecError::Invalid(format!("bad env name {name:?}"))) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError> { |
| 71 | let mut pairs: Vec<(String, String)> = Vec::new(); |
| 72 | for (k, v) in job.env.iter().chain(job.secrets.iter()) { |
| 73 | validate_env_name(k)?; |
| 74 | pairs.retain(|(name, _)| name != k); |
| 75 | pairs.push((k.clone(), v.clone())); |
| 76 | } |
| 77 | Ok(pairs) |
| 78 | } |
| 79 | |
| 80 | pub fn job_parallelism(limits: &Limits) -> u32 { |
| 81 | let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); |
| 82 | let cpus = limits |
| 83 | .cpus |
| 84 | .trim() |
| 85 | .parse::<f64>() |
| 86 | .ok() |
| 87 | .filter(|c| c.is_finite() && *c > 0.0) |
| 88 | .map_or(host, |c| c.ceil() as u32); |
| 89 | cpus.clamp(1, host.max(1)) |
| 90 | } |
| 91 | |
| 92 | pub fn job_env_with_defaults( |
| 93 | job: &JobAssignment, |
| 94 | limits: &Limits, |
| 95 | ) -> Result<Vec<(String, String)>, ExecError> { |
| 96 | let n = job_parallelism(limits); |
| 97 | let mut pairs: Vec<(String, String)> = [ |
| 98 | ("FORGE_CPUS", n.to_string()), |
| 99 | ( |
| 100 | "FORGE_MEMORY_BYTES", |
| 101 | crate::memory::box_size(limits).to_string(), |
| 102 | ), |
| 103 | ("CARGO_BUILD_JOBS", n.to_string()), |
| 104 | ("MAKEFLAGS", format!("-j{n}")), |
| 105 | ("CMAKE_BUILD_PARALLEL_LEVEL", n.to_string()), |
| 106 | ] |
| 107 | .into_iter() |
| 108 | .map(|(k, v)| (k.to_owned(), v)) |
| 109 | .collect(); |
| 110 | for (k, v) in job_env(job)? { |
| 111 | pairs.retain(|(name, _)| *name != k); |
| 112 | pairs.push((k, v)); |
| 113 | } |
| 114 | Ok(pairs) |
| 115 | } |
| 116 | |
| 117 | #[derive(Debug, PartialEq, Eq)] |
| 118 | pub struct PodmanInvocation { |
| 119 | pub args: Vec<String>, |
| 120 | pub env: Vec<(String, String)>, |
| 121 | pub container: String, |
| 122 | } |
| 123 | |
| 124 | fn check_image(image: &str) -> Result<(), ExecError> { |
| 125 | if image.is_empty() || image.starts_with('-') || image.contains(char::is_whitespace) { |
| 126 | return Err(ExecError::Invalid(format!("bad image {image:?}"))); |
| 127 | } |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | fn check_limit(value: &str, what: &str) -> Result<(), ExecError> { |
| 132 | let ok = !value.is_empty() |
| 133 | && !value.starts_with('-') |
| 134 | && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '.'); |
| 135 | if ok { |
| 136 | Ok(()) |
| 137 | } else { |
| 138 | Err(ExecError::Invalid(format!("bad {what} limit {value:?}"))) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | pub fn podman_invocation( |
| 143 | job: &JobAssignment, |
| 144 | workspace: &Path, |
| 145 | limits: &Limits, |
| 146 | ) -> Result<PodmanInvocation, ExecError> { |
| 147 | validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?; |
| 148 | check_image(&job.image)?; |
| 149 | check_limit(&limits.cpus, "cpus")?; |
| 150 | let memory = crate::memory::box_size(limits).to_string(); |
| 151 | let ws = workspace |
| 152 | .to_str() |
| 153 | .filter(|s| !s.contains(':') && !s.contains(',')) |
| 154 | .ok_or_else(|| ExecError::Invalid("workspace path has a ':' or ','".into()))?; |
| 155 | |
| 156 | let env = job_env_with_defaults(job, limits)?; |
| 157 | let container = format!("forge-job-{}", job.job_id); |
| 158 | let network = if job.network { "slirp4netns" } else { "none" }; |
| 159 | |
| 160 | let mut args: Vec<String> = [ |
| 161 | "run", |
| 162 | "--rm", |
| 163 | "--name", |
| 164 | &container, |
| 165 | "--pull=newer", |
| 166 | &format!("--network={network}"), |
| 167 | "--memory", |
| 168 | &memory, |
| 169 | "--cpus", |
| 170 | &limits.cpus, |
| 171 | "--pids-limit", |
| 172 | ] |
| 173 | .iter() |
| 174 | .map(|s| (*s).to_owned()) |
| 175 | .collect(); |
| 176 | args.push(limits.pids.to_string()); |
| 177 | for flag in [ |
| 178 | "--security-opt", |
| 179 | "no-new-privileges", |
| 180 | "--cap-drop", |
| 181 | "ALL", |
| 182 | "-v", |
| 183 | ] { |
| 184 | args.push(flag.to_owned()); |
| 185 | } |
| 186 | args.push(format!("{ws}:/workspace:Z")); |
| 187 | args.extend(["-w".to_owned(), "/workspace".to_owned()]); |
| 188 | for (name, _) in &env { |
| 189 | args.push("-e".to_owned()); |
| 190 | args.push(name.clone()); |
| 191 | } |
| 192 | args.push(job.image.clone()); |
| 193 | args.extend([ |
| 194 | "sh".to_owned(), |
| 195 | "-eu".to_owned(), |
| 196 | "-c".to_owned(), |
| 197 | job.run.clone(), |
| 198 | ]); |
| 199 | |
| 200 | Ok(PodmanInvocation { |
| 201 | args, |
| 202 | env, |
| 203 | container, |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | fn classify(status: ExitStatus) -> ExecResult { |
| 208 | match status.code() { |
| 209 | Some(0) => ExecResult { |
| 210 | outcome: Outcome::Success, |
| 211 | exit_code: Some(0), |
| 212 | message: None, |
| 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 | enum Stopper { |
| 241 | Podman { |
| 242 | container: String, |
| 243 | }, |
| 244 | #[cfg(any(test, feature = "test-host-executor"))] |
| 245 | ProcessGroup { |
| 246 | pid: u32, |
| 247 | }, |
| 248 | Helper { |
| 249 | pid: u32, |
| 250 | }, |
| 251 | } |
| 252 | |
| 253 | impl Stopper { |
| 254 | async fn stop(&self) { |
| 255 | match self { |
| 256 | Stopper::Podman { container } => { |
| 257 | let quiet = |cmd: &mut Command| { |
| 258 | cmd.stdin(Stdio::null()) |
| 259 | .stdout(Stdio::null()) |
| 260 | .stderr(Stdio::null()); |
| 261 | }; |
| 262 | let mut kill = Command::new("podman"); |
| 263 | kill.args(["kill", container.as_str()]); |
| 264 | quiet(&mut kill); |
| 265 | let _ = kill.status().await; |
| 266 | let mut rm = Command::new("podman"); |
| 267 | rm.args(["rm", "-f", container.as_str()]); |
| 268 | quiet(&mut rm); |
| 269 | let _ = rm.status().await; |
| 270 | } |
| 271 | #[cfg(any(test, feature = "test-host-executor"))] |
| 272 | Stopper::ProcessGroup { pid } => { |
| 273 | let mut kill = Command::new("kill"); |
| 274 | kill.args(["-KILL", "--", &format!("-{pid}")]) |
| 275 | .stdin(Stdio::null()) |
| 276 | .stdout(Stdio::null()) |
| 277 | .stderr(Stdio::null()); |
| 278 | let _ = kill.status().await; |
| 279 | } |
| 280 | Stopper::Helper { .. } => {} |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result<ExitStatus> { |
| 286 | if let Stopper::Helper { pid } = stopper { |
| 287 | let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM); |
| 288 | return match tokio::time::timeout(STOP_GRACE, child.wait()).await { |
| 289 | Ok(status) => status, |
| 290 | Err(_) => { |
| 291 | let _ = child.start_kill(); |
| 292 | child.wait().await |
| 293 | } |
| 294 | }; |
| 295 | } |
| 296 | stopper.stop().await; |
| 297 | let _ = child.start_kill(); |
| 298 | tokio::time::timeout(STOP_GRACE, child.wait()) |
| 299 | .await |
| 300 | .unwrap_or_else(|_| Err(std::io::Error::other("child did not stop"))) |
| 301 | } |
| 302 | |
| 303 | struct Supervised { |
| 304 | cancelled: bool, |
| 305 | status: std::io::Result<ExitStatus>, |
| 306 | sandbox_error: Option<String>, |
| 307 | oom: Option<OomEvents>, |
| 308 | } |
| 309 | |
| 310 | async fn tap_sandbox_errors( |
| 311 | mut lines: mpsc::Receiver<Vec<u8>>, |
| 312 | logs: mpsc::Sender<Vec<u8>>, |
| 313 | token: String, |
| 314 | ) -> (Option<String>, Option<OomEvents>) { |
| 315 | let mut found = None; |
| 316 | let mut oom = None; |
| 317 | while let Some(chunk) = lines.recv().await { |
| 318 | let text = String::from_utf8_lossy(&chunk).into_owned(); |
| 319 | if let Some(message) = strip_line(&text, &token) { |
| 320 | if let Some(events) = OomEvents::from_line(message) { |
| 321 | oom = Some(events); |
| 322 | continue; |
| 323 | } |
| 324 | if !message.starts_with("warning:") { |
| 325 | found = Some(message.trim_end().to_owned()); |
| 326 | } |
| 327 | } |
| 328 | if logs.send(chunk).await.is_err() { |
| 329 | break; |
| 330 | } |
| 331 | } |
| 332 | (found, oom) |
| 333 | } |
| 334 | |
| 335 | async fn supervise( |
| 336 | mut child: Child, |
| 337 | logs: mpsc::Sender<Vec<u8>>, |
| 338 | cancel: CancellationToken, |
| 339 | stopper: Stopper, |
| 340 | cleanup: Option<JobCleanup>, |
| 341 | token: String, |
| 342 | ) -> Supervised { |
| 343 | let mut readers: Vec<JoinHandle<()>> = Vec::new(); |
| 344 | if let Some(out) = child.stdout.take() { |
| 345 | readers.push(tokio::spawn(forward_lines(out, logs.clone()))); |
| 346 | } |
| 347 | let mut tap = None; |
| 348 | if let Some(err) = child.stderr.take() { |
| 349 | let (tx, rx) = mpsc::channel(64); |
| 350 | readers.push(tokio::spawn(forward_lines(err, tx))); |
| 351 | tap = Some(tokio::spawn(tap_sandbox_errors(rx, logs.clone(), token))); |
| 352 | } |
| 353 | drop(logs); |
| 354 | |
| 355 | let early = tokio::select! { |
| 356 | status = child.wait() => Some(status), |
| 357 | _ = cancel.cancelled() => None, |
| 358 | }; |
| 359 | let (status, cancelled) = match early { |
| 360 | Some(status) => (status, false), |
| 361 | None => (stop_child(&mut child, stopper).await, true), |
| 362 | }; |
| 363 | if let Some(job) = cleanup { |
| 364 | reap_job(&job).await; |
| 365 | } |
| 366 | |
| 367 | let drain = async { |
| 368 | for reader in readers.iter_mut() { |
| 369 | let _ = reader.await; |
| 370 | } |
| 371 | }; |
| 372 | if tokio::time::timeout(READER_GRACE, drain).await.is_err() { |
| 373 | for reader in &readers { |
| 374 | reader.abort(); |
| 375 | } |
| 376 | } |
| 377 | let (sandbox_error, oom) = match tap { |
| 378 | Some(tap) => match tokio::time::timeout(READER_GRACE, tap).await { |
| 379 | Ok(Ok(found)) => found, |
| 380 | _ => (None, None), |
| 381 | }, |
| 382 | None => (None, None), |
| 383 | }; |
| 384 | |
| 385 | Supervised { |
| 386 | cancelled, |
| 387 | status, |
| 388 | sandbox_error, |
| 389 | oom, |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | fn finish(supervised: Supervised) -> ExecResult { |
| 394 | if supervised.cancelled { |
| 395 | return cancelled_result(); |
| 396 | } |
| 397 | match supervised.status { |
| 398 | Ok(status) => classify(status), |
| 399 | Err(e) => error_result(format!("waiting for the job failed: {e}")), |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | fn cancelled_result() -> ExecResult { |
| 404 | ExecResult { |
| 405 | outcome: Outcome::Cancelled, |
| 406 | exit_code: None, |
| 407 | message: Some("job was cancelled".to_owned()), |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | #[derive(Clone, Debug)] |
| 412 | pub struct PodmanExecutor { |
| 413 | limits: Limits, |
| 414 | } |
| 415 | |
| 416 | impl PodmanExecutor { |
| 417 | pub fn new(limits: Limits) -> Self { |
| 418 | Self { limits } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | impl Executor for PodmanExecutor { |
| 423 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> { |
| 424 | Box::pin(async move { |
| 425 | let inv = match podman_invocation(req.job, req.workspace, &self.limits) { |
| 426 | Ok(inv) => inv, |
| 427 | Err(e) => return error_result(e.to_string()), |
| 428 | }; |
| 429 | let mut cmd = Command::new("podman"); |
| 430 | cmd.args(&inv.args) |
| 431 | .envs(inv.env.iter().map(|(k, v)| (k.as_str(), v.as_str()))) |
| 432 | .stdin(Stdio::null()) |
| 433 | .stdout(Stdio::piped()) |
| 434 | .stderr(Stdio::piped()) |
| 435 | .kill_on_drop(true); |
| 436 | let child = match cmd.spawn() { |
| 437 | Ok(child) => child, |
| 438 | Err(e) => return error_result(format!("cannot start podman: {e}")), |
| 439 | }; |
| 440 | finish( |
| 441 | supervise( |
| 442 | child, |
| 443 | req.logs, |
| 444 | req.cancel, |
| 445 | Stopper::Podman { |
| 446 | container: inv.container, |
| 447 | }, |
| 448 | None, |
| 449 | new_token(), |
| 450 | ) |
| 451 | .await, |
| 452 | ) |
| 453 | }) |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | #[cfg(any(test, feature = "test-host-executor"))] |
| 458 | #[derive(Clone, Copy, Debug, Default)] |
| 459 | pub struct HostExecutor; |
| 460 | |
| 461 | #[cfg(any(test, feature = "test-host-executor"))] |
| 462 | impl Executor for HostExecutor { |
| 463 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> { |
| 464 | Box::pin(async move { |
| 465 | let env = match job_env(req.job) { |
| 466 | Ok(env) => env, |
| 467 | Err(e) => return error_result(e.to_string()), |
| 468 | }; |
| 469 | let mut cmd = Command::new("sh"); |
| 470 | cmd.args(["-eu", "-c", req.job.run.as_str()]) |
| 471 | .current_dir(req.workspace) |
| 472 | .envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str()))) |
| 473 | .stdin(Stdio::null()) |
| 474 | .stdout(Stdio::piped()) |
| 475 | .stderr(Stdio::piped()) |
| 476 | .process_group(0) |
| 477 | .kill_on_drop(true); |
| 478 | let child = match cmd.spawn() { |
| 479 | Ok(child) => child, |
| 480 | Err(e) => return error_result(format!("cannot start sh: {e}")), |
| 481 | }; |
| 482 | let Some(pid) = child.id() else { |
| 483 | return error_result("child exited before its pid was read"); |
| 484 | }; |
| 485 | finish( |
| 486 | supervise( |
| 487 | child, |
| 488 | req.logs, |
| 489 | req.cancel, |
| 490 | Stopper::ProcessGroup { pid }, |
| 491 | None, |
| 492 | new_token(), |
| 493 | ) |
| 494 | .await, |
| 495 | ) |
| 496 | }) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | pub trait ImageSource: Send + Sync { |
| 501 | fn prepare<'a>( |
| 502 | &'a self, |
| 503 | image: &'a str, |
| 504 | auth: Option<&'a RegistryAuth>, |
| 505 | log: &'a mpsc::Sender<Vec<u8>>, |
| 506 | ) -> impl Future<Output = Result<PreparedImage, ImageError>> + Send + 'a; |
| 507 | } |
| 508 | |
| 509 | impl ImageSource for ImageStore { |
| 510 | fn prepare<'a>( |
| 511 | &'a self, |
| 512 | image: &'a str, |
| 513 | auth: Option<&'a RegistryAuth>, |
| 514 | log: &'a mpsc::Sender<Vec<u8>>, |
| 515 | ) -> impl Future<Output = Result<PreparedImage, ImageError>> + Send + 'a { |
| 516 | self.ensure(image, auth, log) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | pub struct BuiltinExecutor<I = ImageStore> { |
| 521 | images: I, |
| 522 | limits: Limits, |
| 523 | helper: PathBuf, |
| 524 | jobs_dir: PathBuf, |
| 525 | registries: Vec<(String, RegistryAuth)>, |
| 526 | idmap: IdMap, |
| 527 | } |
| 528 | |
| 529 | impl<I: ImageSource> BuiltinExecutor<I> { |
| 530 | pub fn new(images: I, limits: Limits, helper: PathBuf, jobs_dir: PathBuf) -> Self { |
| 531 | Self { |
| 532 | images, |
| 533 | limits, |
| 534 | helper, |
| 535 | jobs_dir, |
| 536 | registries: Vec::new(), |
| 537 | idmap: IdMap::single(), |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | pub fn with_idmap(mut self, map: IdMap) -> Self { |
| 542 | self.idmap = map; |
| 543 | self |
| 544 | } |
| 545 | |
| 546 | pub fn with_registries(mut self, registries: &[RegistryConfig]) -> Self { |
| 547 | self.registries = registries |
| 548 | .iter() |
| 549 | .map(|r| { |
| 550 | ( |
| 551 | r.host.clone(), |
| 552 | RegistryAuth { |
| 553 | username: r.username.clone(), |
| 554 | password: r.password.clone(), |
| 555 | }, |
| 556 | ) |
| 557 | }) |
| 558 | .collect(); |
| 559 | self |
| 560 | } |
| 561 | |
| 562 | fn auth_for(&self, image: &str) -> Option<&RegistryAuth> { |
| 563 | let reference: Reference = image.parse().ok()?; |
| 564 | let host = reference.registry(); |
| 565 | self.registries |
| 566 | .iter() |
| 567 | .find(|(registry, _)| registry == host) |
| 568 | .map(|(_, auth)| auth) |
| 569 | } |
| 570 | |
| 571 | async fn run_job(&self, req: ExecRequest<'_>) -> ExecResult { |
| 572 | let ExecRequest { |
| 573 | job, |
| 574 | workspace, |
| 575 | logs, |
| 576 | cancel, |
| 577 | oom: oom_sink, |
| 578 | } = req; |
| 579 | let limits = self.limits.clone(); |
| 580 | let disk_gb = limits.job_disk_gb; |
| 581 | if let Err(e) = validate_job_id(&job.job_id) { |
| 582 | return error_result(e.to_string()); |
| 583 | } |
| 584 | if let Err(e) = check_image(&job.image) { |
| 585 | return error_result(e.to_string()); |
| 586 | } |
| 587 | let env = match job_env_with_defaults(job, &limits) { |
| 588 | Ok(env) => env, |
| 589 | Err(e) => return error_result(e.to_string()), |
| 590 | }; |
| 591 | |
| 592 | let auth = self.auth_for(&job.image); |
| 593 | let prepared = tokio::select! { |
| 594 | prepared = self.images.prepare(&job.image, auth, &logs) => prepared, |
| 595 | _ = cancel.cancelled() => return cancelled_result(), |
| 596 | }; |
| 597 | let image = match prepared { |
| 598 | Ok(image) => image, |
| 599 | Err(e) => return error_result(format!("cannot prepare image {}: {e}", job.image)), |
| 600 | }; |
| 601 | let _ = logs |
| 602 | .send(format!("image {}\n", image.digest).into_bytes()) |
| 603 | .await; |
| 604 | |
| 605 | let job_dir = self.jobs_dir.join(&job.job_id); |
| 606 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); |
| 607 | if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { |
| 608 | tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); |
| 609 | } |
| 610 | let pasta = if job.network { |
| 611 | let pasta = crate::sandbox::net::find_pasta(); |
| 612 | if pasta.is_none() { |
| 613 | let _ = logs |
| 614 | .send( |
| 615 | b"runner: pasta is not installed, so this job shares the runner's network; \ |
| 616 | install passt to isolate it\n" |
| 617 | .to_vec(), |
| 618 | ) |
| 619 | .await; |
| 620 | } |
| 621 | pasta |
| 622 | } else { |
| 623 | None |
| 624 | }; |
| 625 | let token = new_token(); |
| 626 | let request = SandboxRequest { |
| 627 | token: token.clone(), |
| 628 | job_id: job.job_id.clone(), |
| 629 | rootfs: image.rootfs, |
| 630 | job_dir, |
| 631 | workspace: workspace.to_owned(), |
| 632 | image_env: image.env, |
| 633 | env, |
| 634 | run: job.run.clone(), |
| 635 | network: job.network, |
| 636 | pasta, |
| 637 | limits, |
| 638 | idmap: self.idmap.clone(), |
| 639 | }; |
| 640 | let json = match serde_json::to_vec(&request) { |
| 641 | Ok(json) => json, |
| 642 | Err(e) => return error_result(format!("cannot encode the sandbox request: {e}")), |
| 643 | }; |
| 644 | drop(request); |
| 645 | |
| 646 | let mut cmd = Command::new(&self.helper); |
| 647 | cmd.arg("__sandbox") |
| 648 | .stdin(Stdio::piped()) |
| 649 | .stdout(Stdio::piped()) |
| 650 | .stderr(Stdio::piped()) |
| 651 | .kill_on_drop(true); |
| 652 | let mut child = match cmd.spawn() { |
| 653 | Ok(child) => child, |
| 654 | Err(e) => return error_result(format!("cannot start the sandbox helper: {e}")), |
| 655 | }; |
| 656 | let Some(pid) = child.id() else { |
| 657 | return error_result("sandbox helper exited before its pid was read"); |
| 658 | }; |
| 659 | if let Some(mut stdin) = child.stdin.take() { |
| 660 | if let Err(e) = stdin.write_all(&json).await { |
| 661 | return error_result(format!("cannot send the job to the sandbox helper: {e}")); |
| 662 | } |
| 663 | } |
| 664 | drop(json); |
| 665 | |
| 666 | let job_cancel = cancel.child_token(); |
| 667 | let over_disk = Arc::new(AtomicBool::new(false)); |
| 668 | let disk_cap = disk_gb.saturating_mul(1 << 30); |
| 669 | let watcher = (disk_cap > 0).then(|| { |
| 670 | let job_dir = self.jobs_dir.join(&job.job_id); |
| 671 | let roots = vec![ |
| 672 | workspace.to_owned(), |
| 673 | job_dir.join("tmp"), |
| 674 | job_dir.join("overlay/upper"), |
| 675 | ]; |
| 676 | tokio::spawn(crate::disk::watch( |
| 677 | roots, |
| 678 | disk_cap, |
| 679 | job_cancel.clone(), |
| 680 | Arc::clone(&over_disk), |
| 681 | )) |
| 682 | }); |
| 683 | let Supervised { |
| 684 | cancelled, |
| 685 | status, |
| 686 | sandbox_error, |
| 687 | oom, |
| 688 | } = supervise( |
| 689 | child, |
| 690 | logs, |
| 691 | job_cancel, |
| 692 | Stopper::Helper { pid }, |
| 693 | Some(JobCleanup { |
| 694 | helper_pid: pid, |
| 695 | job_id: job.job_id.clone(), |
| 696 | job_dir: self.jobs_dir.join(&job.job_id), |
| 697 | idmap: self.idmap.clone(), |
| 698 | helper: self.helper.clone(), |
| 699 | }), |
| 700 | token, |
| 701 | ) |
| 702 | .await; |
| 703 | if let Some(watcher) = watcher { |
| 704 | watcher.abort(); |
| 705 | } |
| 706 | if let Some(events) = oom { |
| 707 | oom_sink.record(events); |
| 708 | } |
| 709 | if over_disk.load(Ordering::SeqCst) && !cancel.is_cancelled() { |
| 710 | return ExecResult { |
| 711 | outcome: Outcome::Failure, |
| 712 | exit_code: None, |
| 713 | message: Some(format!( |
| 714 | "job was stopped: it filled more than {disk_gb} GB of disk (workspace, /tmp \ |
| 715 | and writes over the image)" |
| 716 | )), |
| 717 | }; |
| 718 | } |
| 719 | if cancelled { |
| 720 | return cancelled_result(); |
| 721 | } |
| 722 | match status { |
| 723 | Err(e) => error_result(format!("waiting for the sandbox failed: {e}")), |
| 724 | Ok(status) => match status.code() { |
| 725 | Some(0) => ExecResult { |
| 726 | outcome: Outcome::Success, |
| 727 | exit_code: Some(0), |
| 728 | message: None, |
| 729 | }, |
| 730 | Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { |
| 731 | let reason = sandbox_error.unwrap_or_default(); |
| 732 | ExecResult { |
| 733 | outcome: Outcome::Error, |
| 734 | exit_code: Some(EXIT_SETUP_FAILED), |
| 735 | message: Some(format!("sandbox setup failed: {reason}")), |
| 736 | } |
| 737 | } |
| 738 | Some(code) => ExecResult { |
| 739 | outcome: Outcome::Failure, |
| 740 | exit_code: Some(code), |
| 741 | message: None, |
| 742 | }, |
| 743 | None => ExecResult { |
| 744 | outcome: Outcome::Failure, |
| 745 | exit_code: None, |
| 746 | message: Some("job was terminated by a signal".to_owned()), |
| 747 | }, |
| 748 | }, |
| 749 | } |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; |
| 754 | const REAP_POLL: Duration = Duration::from_millis(100); |
| 755 | const REAP_POLLS: u32 = 50; |
| 756 | |
| 757 | pub(crate) fn kill_cgroup(dir: &Path) { |
| 758 | if fs::write(dir.join("cgroup.kill"), "1").is_ok() { |
| 759 | return; |
| 760 | } |
| 761 | let Ok(procs) = fs::read_to_string(dir.join("cgroup.procs")) else { |
| 762 | return; |
| 763 | }; |
| 764 | for pid in procs |
| 765 | .lines() |
| 766 | .filter_map(|line| line.trim().parse::<i32>().ok()) |
| 767 | { |
| 768 | let _ = kill(Pid::from_raw(pid), Signal::SIGKILL); |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | struct JobCleanup { |
| 773 | helper_pid: u32, |
| 774 | job_id: String, |
| 775 | job_dir: PathBuf, |
| 776 | idmap: IdMap, |
| 777 | helper: PathBuf, |
| 778 | } |
| 779 | |
| 780 | async fn reap_job(job: &JobCleanup) { |
| 781 | if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { |
| 782 | let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); |
| 783 | if dir.exists() { |
| 784 | kill_cgroup(&dir); |
| 785 | for _ in 0..REAP_POLLS { |
| 786 | if fs::remove_dir(&dir).is_ok() || !dir.exists() { |
| 787 | break; |
| 788 | } |
| 789 | tokio::time::sleep(REAP_POLL).await; |
| 790 | } |
| 791 | } |
| 792 | } |
| 793 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); |
| 794 | if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { |
| 795 | tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { |
| 800 | let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); |
| 801 | let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; |
| 802 | if let Err(e) = swept { |
| 803 | tracing::warn!("cannot sweep leftover jobs: {e}"); |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { |
| 808 | let jobs_dir = work_dir.join("jobs"); |
| 809 | let cgroup_bases: Vec<PathBuf> = crate::sandbox::helper::job_cgroup_base() |
| 810 | .map(|base| { |
| 811 | let base = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); |
| 812 | vec![base.join(crate::sandbox::helper::BOX_NAME), base] |
| 813 | }) |
| 814 | .unwrap_or_default(); |
| 815 | for job_id in job_ids_in(&jobs_dir) { |
| 816 | let job_dir = jobs_dir.join(&job_id); |
| 817 | tracing::info!("removing leftover job {job_id}"); |
| 818 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); |
| 819 | let prefix = format!("forge-job-{job_id}-"); |
| 820 | for base in &cgroup_bases { |
| 821 | let Ok(entries) = fs::read_dir(base) else { |
| 822 | continue; |
| 823 | }; |
| 824 | for entry in entries.flatten() { |
| 825 | let name = entry.file_name(); |
| 826 | let Some(pid) = name.to_str().and_then(|n| n.strip_prefix(&prefix)) else { |
| 827 | continue; |
| 828 | }; |
| 829 | if pid.parse::<u32>().is_err() { |
| 830 | continue; |
| 831 | } |
| 832 | let dir = entry.path(); |
| 833 | kill_cgroup(&dir); |
| 834 | for _ in 0..REAP_POLLS { |
| 835 | if fs::remove_dir(&dir).is_ok() || !dir.exists() { |
| 836 | break; |
| 837 | } |
| 838 | std::thread::sleep(REAP_POLL); |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | if let Err(e) = remove_tree(map, &job_dir, helper) { |
| 843 | tracing::warn!("cannot remove {}: {e}", job_dir.display()); |
| 844 | } |
| 845 | } |
| 846 | for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { |
| 847 | let workspace = work_dir.join(&job_id); |
| 848 | tracing::info!("removing leftover workspace {job_id}"); |
| 849 | if let Err(e) = remove_tree(map, &workspace, helper) { |
| 850 | tracing::warn!("cannot remove {}: {e}", workspace.display()); |
| 851 | } |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | fn is_ulid(name: &str) -> bool { |
| 856 | name.len() == 26 |
| 857 | && name |
| 858 | .bytes() |
| 859 | .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) |
| 860 | } |
| 861 | |
| 862 | fn job_ids_in(dir: &Path) -> Vec<String> { |
| 863 | let Ok(entries) = fs::read_dir(dir) else { |
| 864 | return Vec::new(); |
| 865 | }; |
| 866 | entries |
| 867 | .flatten() |
| 868 | .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir())) |
| 869 | .filter_map(|entry| entry.file_name().into_string().ok()) |
| 870 | .filter(|name| validate_job_id(name).is_ok()) |
| 871 | .collect() |
| 872 | } |
| 873 | |
| 874 | async fn remove_job_dir(map: &IdMap, helper: &Path, job_dir: &Path) -> std::io::Result<()> { |
| 875 | let (map, helper, job_dir) = (map.clone(), helper.to_owned(), job_dir.to_owned()); |
| 876 | tokio::task::spawn_blocking(move || remove_tree(&map, &job_dir, &helper)) |
| 877 | .await |
| 878 | .map_err(std::io::Error::other)? |
| 879 | } |
| 880 | |
| 881 | impl<I: ImageSource> Executor for BuiltinExecutor<I> { |
| 882 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a> { |
| 883 | Box::pin(self.run_job(req)) |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | #[cfg(test)] |
| 888 | mod tests { |
| 889 | use super::*; |
| 890 | use std::collections::BTreeMap; |
| 891 | |
| 892 | #[test] |
| 893 | fn sweep_removes_only_leftover_jobs_and_ulid_workspaces() { |
| 894 | let dir = tempfile::tempdir().unwrap(); |
| 895 | let work = dir.path(); |
| 896 | for d in [ |
| 897 | "jobs/job_01/overlay", |
| 898 | "01JD6Z8Q4XW3N5R7T9V2B4C6E8/src", |
| 899 | "oci", |
| 900 | "notes", |
| 901 | "check-7", |
| 902 | ] { |
| 903 | fs::create_dir_all(work.join(d)).unwrap(); |
| 904 | } |
| 905 | fs::create_dir_all(work.join(".cache")).unwrap(); |
| 906 | sweep_blocking(work, &IdMap::single(), Path::new("/nonexistent")); |
| 907 | assert!(!work.join("jobs/job_01").exists()); |
| 908 | assert!(!work.join("01JD6Z8Q4XW3N5R7T9V2B4C6E8").exists()); |
| 909 | for kept in ["jobs", "oci", "notes", "check-7", ".cache"] { |
| 910 | assert!(work.join(kept).exists(), "{kept} was removed"); |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | const SECRET: &str = "hunter2-SUPER-SECRET-value"; |
| 915 | |
| 916 | pub(crate) fn fixture_job(run: &str) -> JobAssignment { |
| 917 | JobAssignment { |
| 918 | job_id: "job_01".to_owned(), |
| 919 | job_token: "tok_01_secret_token".to_owned(), |
| 920 | repo: "owner/name".to_owned(), |
| 921 | clone_url: "https://forge.example/owner/name.git".to_owned(), |
| 922 | commit: "a".repeat(40), |
| 923 | git_ref: "refs/heads/main".to_owned(), |
| 924 | job_name: "build".to_owned(), |
| 925 | image: "docker.io/library/alpine:3".to_owned(), |
| 926 | run: run.to_owned(), |
| 927 | env: BTreeMap::from([("PLAIN".to_owned(), "visible".to_owned())]), |
| 928 | secrets: BTreeMap::from([("MY_TOKEN".to_owned(), SECRET.to_owned())]), |
| 929 | artifacts: Vec::new(), |
| 930 | timeout_minutes: 5, |
| 931 | network: false, |
| 932 | cache: Vec::new(), |
| 933 | cache_key: String::new(), |
| 934 | cache_restore_keys: Vec::new(), |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn podman_argv_never_contains_a_secret_value() { |
| 940 | let job = fixture_job("echo $MY_TOKEN"); |
| 941 | let inv = podman_invocation(&job, Path::new("/work/job_01"), &Limits::default()) |
| 942 | .expect("invocation"); |
| 943 | assert!(inv.args.iter().all(|a| !a.contains(SECRET))); |
| 944 | assert!(inv.args.iter().all(|a| !a.contains("visible"))); |
| 945 | assert!( |
| 946 | inv.env |
| 947 | .contains(&("MY_TOKEN".to_owned(), SECRET.to_owned())) |
| 948 | ); |
| 949 | assert!( |
| 950 | inv.env |
| 951 | .contains(&("PLAIN".to_owned(), "visible".to_owned())) |
| 952 | ); |
| 953 | let names: Vec<&str> = inv |
| 954 | .args |
| 955 | .windows(2) |
| 956 | .filter(|w| w[0] == "-e") |
| 957 | .map(|w| w[1].as_str()) |
| 958 | .collect(); |
| 959 | assert_eq!( |
| 960 | names, |
| 961 | vec![ |
| 962 | "FORGE_CPUS", |
| 963 | "FORGE_MEMORY_BYTES", |
| 964 | "CARGO_BUILD_JOBS", |
| 965 | "MAKEFLAGS", |
| 966 | "CMAKE_BUILD_PARALLEL_LEVEL", |
| 967 | "PLAIN", |
| 968 | "MY_TOKEN" |
| 969 | ] |
| 970 | ); |
| 971 | } |
| 972 | |
| 973 | #[test] |
| 974 | fn podman_argv_has_the_isolation_flags() { |
| 975 | let job = fixture_job("true"); |
| 976 | let inv = podman_invocation(&job, Path::new("/work/job_01"), &Limits::default()) |
| 977 | .expect("invocation"); |
| 978 | let joined = inv.args.join(" "); |
| 979 | assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer")); |
| 980 | assert!(joined.contains("--network=none")); |
| 981 | let memory = crate::memory::box_size(&Limits::default()); |
| 982 | assert!(joined.contains(&format!("--memory {memory} --cpus 2 --pids-limit 4096"))); |
| 983 | assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL")); |
| 984 | assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace")); |
| 985 | assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true")); |
| 986 | } |
| 987 | |
| 988 | #[test] |
| 989 | fn network_true_selects_slirp() { |
| 990 | let mut job = fixture_job("true"); |
| 991 | job.network = true; |
| 992 | let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); |
| 993 | assert!(inv.args.contains(&"--network=slirp4netns".to_owned())); |
| 994 | } |
| 995 | |
| 996 | #[test] |
| 997 | fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { |
| 998 | let mut job = fixture_job("true"); |
| 999 | let limits = Limits { |
| 1000 | cpus: "0.5".to_owned(), |
| 1001 | ..Limits::default() |
| 1002 | }; |
| 1003 | let env = job_env_with_defaults(&job, &limits).expect("env"); |
| 1004 | assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned()))); |
| 1005 | job.env |
| 1006 | .insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned()); |
| 1007 | let env = job_env_with_defaults(&job, &limits).expect("env"); |
| 1008 | let jobs: Vec<_> = env |
| 1009 | .iter() |
| 1010 | .filter(|(k, _)| k == "CARGO_BUILD_JOBS") |
| 1011 | .collect(); |
| 1012 | assert_eq!(jobs, [&("CARGO_BUILD_JOBS".to_owned(), "7".to_owned())]); |
| 1013 | } |
| 1014 | |
| 1015 | #[test] |
| 1016 | fn hostile_values_are_refused() { |
| 1017 | let ws = Path::new("/w"); |
| 1018 | let mut job = fixture_job("true"); |
| 1019 | job.image = "--privileged".to_owned(); |
| 1020 | assert!(podman_invocation(&job, ws, &Limits::default()).is_err()); |
| 1021 | |
| 1022 | let mut job = fixture_job("true"); |
| 1023 | job.env.insert("A=B".to_owned(), "x".to_owned()); |
| 1024 | assert!(podman_invocation(&job, ws, &Limits::default()).is_err()); |
| 1025 | |
| 1026 | let mut job = fixture_job("true"); |
| 1027 | job.job_id = "../escape".to_owned(); |
| 1028 | assert!(podman_invocation(&job, ws, &Limits::default()).is_err()); |
| 1029 | |
| 1030 | let job = fixture_job("true"); |
| 1031 | assert!(podman_invocation(&job, Path::new("/w:evil"), &Limits::default()).is_err()); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn exit_codes_map_to_outcomes() { |
| 1036 | use std::os::unix::process::ExitStatusExt; |
| 1037 | let ok = classify(ExitStatus::from_raw(0)); |
| 1038 | assert_eq!(ok.outcome, Outcome::Success); |
| 1039 | let fail = classify(ExitStatus::from_raw(3 << 8)); |
| 1040 | assert_eq!(fail.outcome, Outcome::Failure); |
| 1041 | assert_eq!(fail.exit_code, Some(3)); |
| 1042 | let podman = classify(ExitStatus::from_raw(125 << 8)); |
| 1043 | assert_eq!(podman.outcome, Outcome::Error); |
| 1044 | } |
| 1045 | |
| 1046 | #[tokio::test] |
| 1047 | #[ignore = "requires rootless podman and registry access"] |
| 1048 | async fn podman_runs_a_real_container() { |
| 1049 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1050 | let ws = dir.path().join("ws"); |
| 1051 | std::fs::create_dir_all(&ws).expect("mkdir"); |
| 1052 | let job = fixture_job( |
| 1053 | "echo hi-from-container; echo \"s=$MY_TOKEN\" >&2; touch /workspace/out.txt", |
| 1054 | ); |
| 1055 | let (tx, mut rx) = mpsc::channel(64); |
| 1056 | let exec = PodmanExecutor::new(Limits::default()); |
| 1057 | let result = exec |
| 1058 | .run(ExecRequest { |
| 1059 | job: &job, |
| 1060 | workspace: &ws, |
| 1061 | logs: tx, |
| 1062 | cancel: CancellationToken::new(), |
| 1063 | oom: OomSink::default(), |
| 1064 | }) |
| 1065 | .await; |
| 1066 | assert_eq!(result.outcome, Outcome::Success, "{result:?}"); |
| 1067 | let mut all = Vec::new(); |
| 1068 | while let Some(chunk) = rx.recv().await { |
| 1069 | all.extend_from_slice(&chunk); |
| 1070 | } |
| 1071 | let text = String::from_utf8_lossy(&all).into_owned(); |
| 1072 | assert!(text.contains("hi-from-container")); |
| 1073 | assert!(ws.join("out.txt").exists()); |
| 1074 | } |
| 1075 | } |