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