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