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