use std::ffi::OsString; use std::path::PathBuf; use std::process::ExitCode; use std::sync::Arc; use std::time::Duration; use clap::{CommandFactory, Parser, Subcommand}; use forge_ci::proto::RegisterRequest; use tokio_util::sync::CancellationToken; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, Layer as _}; use crate::cache::CacheStore; use crate::client::ForgeClient; use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; use crate::oci::ImageStore; use crate::runner::{RunEnd, RunOptions, Runner}; use crate::sandbox::idmap::IdMap; use crate::selflog; use crate::update; const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); #[derive(Parser)] #[command( name = "forge-runner", version = forge_ci::build::display(), about = "Runs forge CI jobs in a rootless sandbox (builtin) or rootless podman" )] struct Cli { #[command(subcommand)] command: Command, } #[derive(Subcommand)] enum Command { Register { #[arg(long)] url: String, #[arg(long)] token: String, #[arg(long)] name: String, #[arg(long, value_delimiter = ',')] labels: Vec, #[arg(long)] config: Option, #[arg(long)] work_dir: Option, }, Run { #[arg(long)] config: Option, }, Unregister { #[arg(long)] config: Option, }, Check { #[arg(long)] work_dir: Option, #[arg(long)] config: Option, }, } pub fn main_with_args(bin_name: &str, args: I) -> ExitCode where I: IntoIterator, T: Into, { let args: Vec = args.into_iter().map(Into::into).collect(); if args.first().is_some_and(is_sandbox_arg) { std::process::exit(hidden_dispatch(&args)); } let runtime = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() { Ok(runtime) => runtime, Err(e) => { eprintln!("{bin_name}: cannot start the runtime: {e}"); return ExitCode::FAILURE; } }; let _ = tracing_subscriber::registry() .with( tracing_subscriber::fmt::layer() .with_writer(std::io::stderr) .with_filter( EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), ), ) .with(selflog::layer()) .try_init(); let argv = std::iter::once(OsString::from(bin_name)).chain(args); let cli = match Cli::command() .bin_name(bin_name) .try_get_matches_from(argv) .and_then(|matches| ::from_arg_matches(&matches)) { Ok(cli) => cli, Err(e) => { let code = e.exit_code(); let _ = e.print(); return ExitCode::from(code as u8); } }; runtime.block_on(async { match run(cli).await { Ok(code) => code, Err(e) => { eprintln!("{bin_name}: {e}"); ExitCode::FAILURE } } }) } pub fn is_sandbox_invocation() -> bool { std::env::args_os() .nth(1) .is_some_and(|arg| is_sandbox_arg(&arg)) } pub fn hidden_main() -> i32 { let args: Vec = std::env::args_os().skip(1).collect(); hidden_dispatch(&args) } fn is_sandbox_arg(arg: &OsString) -> bool { arg.as_encoded_bytes().starts_with(b"__sandbox") } fn hidden_dispatch(args: &[OsString]) -> i32 { match args.first().map(|arg| arg.as_encoded_bytes()) { Some(b"__sandbox") => crate::sandbox::helper_main(), Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]), Some(b"__sandbox-net") => crate::sandbox::net::net_helper_main(&args[1..]), Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]), Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(), _ => { crate::sandbox::report("unknown helper command"); 125 } } } async fn run(cli: Cli) -> Result> { match cli.command { Command::Register { url, token, name, labels, config: path, work_dir, } => { let path = path.map_or_else(config::default_config_path, Ok)?; let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; let client = ForgeClient::new(&url)?; let resp = client .register(&RegisterRequest { token, name: name.clone(), labels: labels.clone(), }) .await?; let cfg = RunnerConfig { url, runner_id: resp.runner_id.clone(), runner_secret: resp.runner_secret, name, labels, work_dir, concurrency: 1, limits: Limits::default(), executor: ExecutorKind::default(), images: ImagesConfig::default(), sandbox: config::SandboxConfig::default(), registries: Vec::new(), auto_update: true, cache_max_gib: config::default_cache_max_gib(), }; config::save(&path, &cfg)?; println!( "registered runner {} and wrote {}", resp.runner_id, path.display() ); Ok(ExitCode::SUCCESS) } Command::Unregister { config: path } => { let path = path.map_or_else(config::default_config_path, Ok)?; let cfg = config::load(&path)?; ForgeClient::new(&cfg.url)? .unregister(&cfg.runner_secret) .await?; println!("runner {} removed from {}", cfg.name, cfg.url); Ok(ExitCode::SUCCESS) } Command::Run { config: path } => { let path = path.map_or_else(config::default_config_path, Ok)?; let mut cfg = config::load(&path)?; sync_config_with_forge(&mut cfg).await; let shutdown = CancellationToken::new(); if let ExecutorKind::Builtin = cfg.executor && let Err(e) = crate::pressure::start_box(crate::memory::box_size(&cfg.limits)) { tracing::warn!("no memory box, builtin jobs run without one: {e}"); } let cache_root = cfg.work_dir.join(".cache"); let cache_cap = cfg.cache_max_gib; let (executor, map): (Arc, IdMap) = match cfg.executor { ExecutorKind::Podman => ( Arc::new(PodmanExecutor::new(cfg.limits.clone())), IdMap::single(), ), ExecutorKind::Builtin => { let map = IdMap::resolve(cfg.sandbox.userns)?; tracing::info!("sandbox ids: {}", map.describe()); let helper = std::env::current_exe()?; let root = cfg.work_dir.join("oci"); spawn_image_gc( root.clone(), cfg.images.keep_days, map.clone(), helper.clone(), shutdown.clone(), ); let images = ImageStore::new(root) .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) .with_idmap(map.clone(), helper.clone()); crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; let jobs_dir = cfg.work_dir.join("jobs"); let executor = BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir) .with_idmap(map.clone()) .with_registries(&cfg.registries); (Arc::new(executor), map) } }; let stop_url = cfg.url.clone(); let stop_secret = cfg.runner_secret.clone(); let mut runner = Runner::new(cfg, executor, RunOptions::default())?; if cache_cap > 0 { let cache = CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); if let Err(e) = cache.sweep_stale().await { tracing::warn!(error = %e, "cannot remove stale cache dirs"); } runner = runner.with_cache(cache); } let stop = shutdown.clone(); tokio::spawn(async move { let Ok(mut term) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) else { return; }; tokio::select! { _ = tokio::signal::ctrl_c() => {} _ = term.recv() => {} } tracing::info!("stop signal received, cancelling running jobs"); stop.cancel(); }); match runner.run(shutdown).await { RunEnd::Stopped => { if let Err(e) = ForgeClient::new(&stop_url)?.stopped(&stop_secret).await { tracing::warn!(error = %e, "could not tell the forge the runner stopped"); } Ok(ExitCode::SUCCESS) } RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), } } Command::Check { work_dir, config: config_path, } => { let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; let mode = check_userns_mode(config_path)?; let helper = std::env::current_exe()?; if crate::check::run(&helper, &work_dir, mode).await { Ok(ExitCode::SUCCESS) } else { Err("some host checks failed, see the report above".into()) } } } } fn check_userns_mode(config_path: Option) -> Result { if let Some(path) = config_path { return Ok(config::load(&path)?.sandbox.userns); } match config::default_config_path() { Ok(path) if path.exists() => Ok(config::load(&path)?.sandbox.userns), _ => Ok(UsernsMode::Auto), } } fn spawn_image_gc( root: PathBuf, keep_days: u32, map: IdMap, helper: PathBuf, shutdown: CancellationToken, ) { tokio::spawn(async move { loop { let (root, map, helper) = (root.clone(), map.clone(), helper.clone()); let result = tokio::task::spawn_blocking(move || { ImageStore::new(root).with_idmap(map, helper).gc(keep_days) }) .await; match result { Ok(Ok(stats)) => tracing::info!(?stats, "image garbage collection finished"), Ok(Err(e)) => tracing::warn!("image garbage collection failed: {e}"), Err(e) => tracing::warn!("image garbage collection task failed: {e}"), } tokio::select! { _ = tokio::time::sleep(GC_INTERVAL) => {} _ = shutdown.cancelled() => break, } } }); } fn gib(gb: u64) -> u64 { gb.saturating_mul(1024 * 1024 * 1024) } async fn sync_config_with_forge(cfg: &mut RunnerConfig) { let client = match crate::client::ForgeClient::new(&cfg.url) { Ok(client) => client, Err(e) => { tracing::warn!(error = %e, "cannot sync config with the forge"); return; } }; match client.get_config(&cfg.runner_secret).await { Ok(reply) => { for line in cfg.apply_overrides(&reply.overrides) { tracing::info!("{line}"); } } Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"), } let report = forge_ci::proto::RunnerConfigReport { config: cfg.report(), }; if let Err(e) = client.put_config(&cfg.runner_secret, &report).await { tracing::warn!(error = %e, "cannot report config to the forge"); } }