| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::ffi::OsString; |
| 7 | use std::path::PathBuf; |
| 8 | use std::process::ExitCode; |
| 9 | use std::sync::Arc; |
| 10 | use std::time::Duration; |
| 11 | |
| 12 | use clap::{CommandFactory, Parser, Subcommand}; |
| 13 | use forge_ci::proto::RegisterRequest; |
| 14 | use tokio_util::sync::CancellationToken; |
| 15 | use tracing_subscriber::EnvFilter; |
| 16 | |
| 17 | use crate::cache::CacheStore; |
| 18 | use crate::client::ForgeClient; |
| 19 | use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; |
| 20 | use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; |
| 21 | use crate::oci::ImageStore; |
| 22 | use crate::pressure::Pressure; |
| 23 | use crate::runner::{RunEnd, RunOptions, Runner}; |
| 24 | use crate::sandbox::idmap::IdMap; |
| 25 | use crate::update; |
| 26 | |
| 27 | |
| 28 | const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); |
| 29 | |
| 30 | #[derive(Parser)] |
| 31 | #[command( |
| 32 | name = "forge-runner", |
| 33 | version = forge_ci::build::display(), |
| 34 | about = "Runs forge CI jobs in a rootless sandbox (builtin) or rootless podman" |
| 35 | )] |
| 36 | struct Cli { |
| 37 | #[command(subcommand)] |
| 38 | command: Command, |
| 39 | } |
| 40 | |
| 41 | #[derive(Subcommand)] |
| 42 | enum Command { |
| 43 | |
| 44 | Register { |
| 45 | |
| 46 | #[arg(long)] |
| 47 | url: String, |
| 48 | |
| 49 | #[arg(long)] |
| 50 | token: String, |
| 51 | |
| 52 | #[arg(long)] |
| 53 | name: String, |
| 54 | |
| 55 | #[arg(long, value_delimiter = ',')] |
| 56 | labels: Vec<String>, |
| 57 | |
| 58 | #[arg(long)] |
| 59 | config: Option<PathBuf>, |
| 60 | |
| 61 | #[arg(long)] |
| 62 | work_dir: Option<PathBuf>, |
| 63 | }, |
| 64 | |
| 65 | Run { |
| 66 | |
| 67 | #[arg(long)] |
| 68 | config: Option<PathBuf>, |
| 69 | }, |
| 70 | |
| 71 | |
| 72 | Check { |
| 73 | |
| 74 | |
| 75 | #[arg(long)] |
| 76 | work_dir: Option<PathBuf>, |
| 77 | |
| 78 | |
| 79 | #[arg(long)] |
| 80 | config: Option<PathBuf>, |
| 81 | }, |
| 82 | } |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | pub fn main_with_args<I, T>(bin_name: &str, args: I) -> ExitCode |
| 88 | where |
| 89 | I: IntoIterator<Item = T>, |
| 90 | T: Into<OsString>, |
| 91 | { |
| 92 | let args: Vec<OsString> = args.into_iter().map(Into::into).collect(); |
| 93 | |
| 94 | |
| 95 | if args.first().is_some_and(is_sandbox_arg) { |
| 96 | std::process::exit(hidden_dispatch(&args)); |
| 97 | } |
| 98 | let runtime = match tokio::runtime::Builder::new_multi_thread() |
| 99 | .enable_all() |
| 100 | .build() |
| 101 | { |
| 102 | Ok(runtime) => runtime, |
| 103 | Err(e) => { |
| 104 | eprintln!("{bin_name}: cannot start the runtime: {e}"); |
| 105 | return ExitCode::FAILURE; |
| 106 | } |
| 107 | }; |
| 108 | |
| 109 | let _ = tracing_subscriber::fmt() |
| 110 | .with_env_filter( |
| 111 | EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), |
| 112 | ) |
| 113 | .with_writer(std::io::stderr) |
| 114 | .try_init(); |
| 115 | let argv = std::iter::once(OsString::from(bin_name)).chain(args); |
| 116 | let cli = match Cli::command() |
| 117 | .bin_name(bin_name) |
| 118 | .try_get_matches_from(argv) |
| 119 | .and_then(|matches| <Cli as clap::FromArgMatches>::from_arg_matches(&matches)) |
| 120 | { |
| 121 | Ok(cli) => cli, |
| 122 | Err(e) => { |
| 123 | let code = e.exit_code(); |
| 124 | let _ = e.print(); |
| 125 | return ExitCode::from(code as u8); |
| 126 | } |
| 127 | }; |
| 128 | runtime.block_on(async { |
| 129 | match run(cli).await { |
| 130 | Ok(code) => code, |
| 131 | Err(e) => { |
| 132 | eprintln!("{bin_name}: {e}"); |
| 133 | ExitCode::FAILURE |
| 134 | } |
| 135 | } |
| 136 | }) |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | pub fn is_sandbox_invocation() -> bool { |
| 143 | std::env::args_os() |
| 144 | .nth(1) |
| 145 | .is_some_and(|arg| is_sandbox_arg(&arg)) |
| 146 | } |
| 147 | |
| 148 | |
| 149 | |
| 150 | pub fn hidden_main() -> i32 { |
| 151 | let args: Vec<OsString> = std::env::args_os().skip(1).collect(); |
| 152 | hidden_dispatch(&args) |
| 153 | } |
| 154 | |
| 155 | fn is_sandbox_arg(arg: &OsString) -> bool { |
| 156 | arg.as_encoded_bytes().starts_with(b"__sandbox") |
| 157 | } |
| 158 | |
| 159 | |
| 160 | fn hidden_dispatch(args: &[OsString]) -> i32 { |
| 161 | match args.first().map(|arg| arg.as_encoded_bytes()) { |
| 162 | Some(b"__sandbox") => crate::sandbox::helper_main(), |
| 163 | Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), |
| 164 | Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), |
| 165 | Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), |
| 166 | _ => { |
| 167 | eprintln!("forge-sandbox: unknown helper command"); |
| 168 | 125 |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { |
| 174 | match cli.command { |
| 175 | Command::Register { |
| 176 | url, |
| 177 | token, |
| 178 | name, |
| 179 | labels, |
| 180 | config: path, |
| 181 | work_dir, |
| 182 | } => { |
| 183 | let client = ForgeClient::new(&url)?; |
| 184 | let resp = client |
| 185 | .register(&RegisterRequest { |
| 186 | token, |
| 187 | name: name.clone(), |
| 188 | labels: labels.clone(), |
| 189 | }) |
| 190 | .await?; |
| 191 | let path = match path { |
| 192 | Some(p) => p, |
| 193 | None => config::default_config_path()?, |
| 194 | }; |
| 195 | let work_dir = match work_dir { |
| 196 | Some(w) => w, |
| 197 | None => config::default_work_dir()?, |
| 198 | }; |
| 199 | let cfg = RunnerConfig { |
| 200 | url, |
| 201 | runner_id: resp.runner_id.clone(), |
| 202 | runner_secret: resp.runner_secret, |
| 203 | name, |
| 204 | labels, |
| 205 | work_dir, |
| 206 | concurrency: 1, |
| 207 | limits: Limits::default(), |
| 208 | executor: ExecutorKind::default(), |
| 209 | images: ImagesConfig::default(), |
| 210 | sandbox: config::SandboxConfig::default(), |
| 211 | registries: Vec::new(), |
| 212 | auto_update: true, |
| 213 | cache_max_gib: config::default_cache_max_gib(), |
| 214 | }; |
| 215 | config::save(&path, &cfg)?; |
| 216 | println!( |
| 217 | "registered runner {} and wrote {}", |
| 218 | resp.runner_id, |
| 219 | path.display() |
| 220 | ); |
| 221 | Ok(ExitCode::SUCCESS) |
| 222 | } |
| 223 | Command::Run { config: path } => { |
| 224 | let path = match path { |
| 225 | Some(p) => p, |
| 226 | None => config::default_config_path()?, |
| 227 | }; |
| 228 | let mut cfg = config::load(&path)?; |
| 229 | sync_config_with_forge(&mut cfg).await; |
| 230 | let shutdown = CancellationToken::new(); |
| 231 | |
| 232 | |
| 233 | let pressure = match cfg.executor { |
| 234 | ExecutorKind::Builtin => { |
| 235 | let budget = crate::memory::MemoryGate::for_host(&cfg.limits).budget(); |
| 236 | let pressure = Pressure::start(budget, shutdown.clone()).await; |
| 237 | if let Some(p) = &pressure { |
| 238 | cfg.limits.memory = p.budget().to_string(); |
| 239 | } |
| 240 | pressure |
| 241 | } |
| 242 | ExecutorKind::Podman => None, |
| 243 | }; |
| 244 | let cache_root = cfg.work_dir.join(".cache"); |
| 245 | let cache_cap = cfg.cache_max_gib; |
| 246 | |
| 247 | let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor { |
| 248 | ExecutorKind::Podman => ( |
| 249 | Arc::new(PodmanExecutor::new(cfg.limits.clone())), |
| 250 | IdMap::single(), |
| 251 | ), |
| 252 | ExecutorKind::Builtin => { |
| 253 | |
| 254 | let map = IdMap::resolve(cfg.sandbox.userns)?; |
| 255 | tracing::info!("sandbox ids: {}", map.describe()); |
| 256 | let helper = std::env::current_exe()?; |
| 257 | let root = cfg.work_dir.join("oci"); |
| 258 | spawn_image_gc( |
| 259 | root.clone(), |
| 260 | cfg.images.keep_days, |
| 261 | map.clone(), |
| 262 | helper.clone(), |
| 263 | shutdown.clone(), |
| 264 | ); |
| 265 | let images = ImageStore::new(root) |
| 266 | .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) |
| 267 | .with_idmap(map.clone(), helper.clone()); |
| 268 | let jobs_dir = cfg.work_dir.join("jobs"); |
| 269 | let executor = |
| 270 | BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) |
| 271 | .with_idmap(map.clone()) |
| 272 | .with_registries(&cfg.registries); |
| 273 | (Arc::new(executor), map) |
| 274 | } |
| 275 | }; |
| 276 | let mut runner = |
| 277 | Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); |
| 278 | if cache_cap > 0 { |
| 279 | let cache = |
| 280 | CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); |
| 281 | if let Err(e) = cache.sweep_stale().await { |
| 282 | tracing::warn!(error = %e, "cannot remove stale cache dirs"); |
| 283 | } |
| 284 | runner = runner.with_cache(cache); |
| 285 | } |
| 286 | let stop = shutdown.clone(); |
| 287 | tokio::spawn(async move { |
| 288 | if tokio::signal::ctrl_c().await.is_ok() { |
| 289 | tracing::info!("interrupt received, cancelling running jobs"); |
| 290 | stop.cancel(); |
| 291 | } |
| 292 | }); |
| 293 | match runner.run(shutdown).await { |
| 294 | RunEnd::Stopped => Ok(ExitCode::SUCCESS), |
| 295 | |
| 296 | RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), |
| 297 | |
| 298 | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), |
| 299 | } |
| 300 | } |
| 301 | Command::Check { |
| 302 | work_dir, |
| 303 | config: config_path, |
| 304 | } => { |
| 305 | let work_dir = match work_dir { |
| 306 | Some(w) => w, |
| 307 | None => config::default_work_dir()?, |
| 308 | }; |
| 309 | let mode = check_userns_mode(config_path)?; |
| 310 | let helper = std::env::current_exe()?; |
| 311 | if crate::check::run(&helper, &work_dir, mode).await { |
| 312 | Ok(ExitCode::SUCCESS) |
| 313 | } else { |
| 314 | Err("some host checks failed, see the report above".into()) |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | |
| 321 | |
| 322 | fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config::ConfigError> { |
| 323 | if let Some(path) = config_path { |
| 324 | return Ok(config::load(&path)?.sandbox.userns); |
| 325 | } |
| 326 | match config::default_config_path() { |
| 327 | Ok(path) if path.exists() => Ok(config::load(&path)?.sandbox.userns), |
| 328 | _ => Ok(UsernsMode::Auto), |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | |
| 333 | |
| 334 | fn spawn_image_gc( |
| 335 | root: PathBuf, |
| 336 | keep_days: u32, |
| 337 | map: IdMap, |
| 338 | helper: PathBuf, |
| 339 | shutdown: CancellationToken, |
| 340 | ) { |
| 341 | tokio::spawn(async move { |
| 342 | loop { |
| 343 | let (root, map, helper) = (root.clone(), map.clone(), helper.clone()); |
| 344 | let result = tokio::task::spawn_blocking(move || { |
| 345 | ImageStore::new(root).with_idmap(map, helper).gc(keep_days) |
| 346 | }) |
| 347 | .await; |
| 348 | match result { |
| 349 | Ok(Ok(stats)) => tracing::info!(?stats, "image garbage collection finished"), |
| 350 | Ok(Err(e)) => tracing::warn!("image garbage collection failed: {e}"), |
| 351 | Err(e) => tracing::warn!("image garbage collection task failed: {e}"), |
| 352 | } |
| 353 | tokio::select! { |
| 354 | _ = tokio::time::sleep(GC_INTERVAL) => {} |
| 355 | _ = shutdown.cancelled() => break, |
| 356 | } |
| 357 | } |
| 358 | }); |
| 359 | } |
| 360 | |
| 361 | |
| 362 | fn gib(gb: u64) -> u64 { |
| 363 | gb.saturating_mul(1024 * 1024 * 1024) |
| 364 | } |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | async fn sync_config_with_forge(cfg: &mut RunnerConfig) { |
| 370 | let client = match crate::client::ForgeClient::new(&cfg.url) { |
| 371 | Ok(client) => client, |
| 372 | Err(e) => { |
| 373 | tracing::warn!(error = %e, "cannot sync config with the forge"); |
| 374 | return; |
| 375 | } |
| 376 | }; |
| 377 | match client.get_config(&cfg.runner_secret).await { |
| 378 | Ok(reply) => { |
| 379 | for line in cfg.apply_overrides(&reply.overrides) { |
| 380 | tracing::info!("{line}"); |
| 381 | } |
| 382 | } |
| 383 | Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"), |
| 384 | } |
| 385 | let report = forge_ci::proto::RunnerConfigReport { |
| 386 | config: cfg.report(), |
| 387 | }; |
| 388 | if let Err(e) = client.put_config(&cfg.runner_secret, &report).await { |
| 389 | tracing::warn!(error = %e, "cannot report config to the forge"); |
| 390 | } |
| 391 | } |