forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB8e56ffcTahinli1 month ago262 commits

cli.rs403 lines, 15.6 KiBHistoryRawDownload
1//! The `forge-runner` command line: `register`, `run` and `check`.
2//!
3//! The standalone `forge-runner` binary and `forge runner` both call [`main_with_args`], so
4//! the two behave the same way.
5
6use std::ffi::OsString;
7use std::path::PathBuf;
8use std::process::ExitCode;
9use std::sync::Arc;
10use std::time::Duration;
11
12use clap::{CommandFactory, Parser, Subcommand};
13use forge_ci::proto::RegisterRequest;
14use tokio_util::sync::CancellationToken;
15use tracing_subscriber::layer::SubscriberExt;
16use tracing_subscriber::util::SubscriberInitExt;
17use tracing_subscriber::{EnvFilter, Layer as _};
18
19use crate::cache::CacheStore;
20use crate::client::ForgeClient;
21use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode};
22use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor};
23use crate::oci::ImageStore;
24use crate::pressure::Pressure;
25use crate::runner::{RunEnd, RunOptions, Runner};
26use crate::sandbox::idmap::IdMap;
27use crate::selflog;
28use crate::update;
29
30/// How often unused images are garbage collected, after the one at startup.
31const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
32
33#[derive(Parser)]
34#[command(
35 name = "forge-runner",
36 version = forge_ci::build::display(),
37 about = "Runs forge CI jobs in a rootless sandbox (builtin) or rootless podman"
38)]
39struct Cli {
40 #[command(subcommand)]
41 command: Command,
42}
43
44#[derive(Subcommand)]
45enum Command {
46 /// Register this machine with a forge and write the runner config (mode 0600).
47 Register {
48 /// Forge base URL, for example https://forge.example
49 #[arg(long)]
50 url: String,
51 /// Registration token shown by the forge admin page.
52 #[arg(long)]
53 token: String,
54 /// Runner name shown in the forge.
55 #[arg(long)]
56 name: String,
57 /// Comma-separated runner labels, for example linux,x86_64.
58 #[arg(long, value_delimiter = ',')]
59 labels: Vec<String>,
60 /// Where to write the config. Default: ~/.config/forge-runner/runner.toml
61 #[arg(long)]
62 config: Option<PathBuf>,
63 /// Where job workspaces go. Default: ~/.cache/forge-runner/work
64 #[arg(long)]
65 work_dir: Option<PathBuf>,
66 },
67 /// Claim and run jobs until interrupted.
68 Run {
69 /// The config file. Default: ~/.config/forge-runner/runner.toml
70 #[arg(long)]
71 config: Option<PathBuf>,
72 },
73 /// Check that this host can run builtin jobs: user namespaces, overlayfs, cgroup limits,
74 /// seccomp and, in subuid mode, subordinate ids. Runs one trivial job through the real sandbox.
75 Check {
76 /// Where the probe runs. It should be on the filesystem that jobs use.
77 /// Default: ~/.cache/forge-runner/work
78 #[arg(long)]
79 work_dir: Option<PathBuf>,
80 /// The runner config, for its `[sandbox] userns` setting. Default: the default config
81 /// path, if that file exists, otherwise `auto`.
82 #[arg(long)]
83 config: Option<PathBuf>,
84 },
85}
86
87/// Runs the `forge-runner` command line. `args` are the arguments after the program name, so
88/// `register --url ...` and not `forge-runner register --url ...`. `bin_name` is shown in help
89/// and error messages, for example `forge runner`.
90pub fn main_with_args<I, T>(bin_name: &str, args: I) -> ExitCode
91where
92 I: IntoIterator<Item = T>,
93 T: Into<OsString>,
94{
95 let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
96 // The sandbox helper is single-threaded and must not have a tokio runtime, because
97 // libcontainer forks and clones. Dispatch it before anything else starts.
98 if args.first().is_some_and(is_sandbox_arg) {
99 std::process::exit(hidden_dispatch(&args));
100 }
101 let runtime = match tokio::runtime::Builder::new_multi_thread()
102 .enable_all()
103 .build()
104 {
105 Ok(runtime) => runtime,
106 Err(e) => {
107 eprintln!("{bin_name}: cannot start the runtime: {e}");
108 return ExitCode::FAILURE;
109 }
110 };
111 // Another subscriber may already be installed, for example by forge-web. Keep that one.
112 // The env filter applies to the terminal output only. The runner's own log that is shipped to
113 // the forge is always INFO and above, whatever the env filter says, see `selflog`.
114 let _ = tracing_subscriber::registry()
115 .with(
116 tracing_subscriber::fmt::layer()
117 .with_writer(std::io::stderr)
118 .with_filter(
119 EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
120 ),
121 )
122 .with(selflog::layer())
123 .try_init();
124 let argv = std::iter::once(OsString::from(bin_name)).chain(args);
125 let cli = match Cli::command()
126 .bin_name(bin_name)
127 .try_get_matches_from(argv)
128 .and_then(|matches| <Cli as clap::FromArgMatches>::from_arg_matches(&matches))
129 {
130 Ok(cli) => cli,
131 Err(e) => {
132 let code = e.exit_code();
133 let _ = e.print();
134 return ExitCode::from(code as u8);
135 }
136 };
137 runtime.block_on(async {
138 match run(cli).await {
139 Ok(code) => code,
140 Err(e) => {
141 eprintln!("{bin_name}: {e}");
142 ExitCode::FAILURE
143 }
144 }
145 })
146}
147
148/// Whether this process was started as a hidden sandbox helper: argv[1] is `__sandbox`,
149/// `__sandbox-rm`, `__sandbox-map` or `__sandbox-unpack`. Callers that have their own runtime or subscriber check
150/// this first, and then call [`hidden_main`].
151pub fn is_sandbox_invocation() -> bool {
152 std::env::args_os()
153 .nth(1)
154 .is_some_and(|arg| is_sandbox_arg(&arg))
155}
156
157/// Runs the hidden helper named by argv[1]. The helpers are single-threaded and must not start
158/// a tokio runtime. Returns the process exit code.
159pub fn hidden_main() -> i32 {
160 let args: Vec<OsString> = std::env::args_os().skip(1).collect();
161 hidden_dispatch(&args)
162}
163
164fn is_sandbox_arg(arg: &OsString) -> bool {
165 arg.as_encoded_bytes().starts_with(b"__sandbox")
166}
167
168/// Routes a hidden helper command. `args` start with the command name.
169fn hidden_dispatch(args: &[OsString]) -> i32 {
170 match args.first().map(|arg| arg.as_encoded_bytes()) {
171 Some(b"__sandbox") => crate::sandbox::helper_main(),
172 Some(b"__sandbox-rm") => crate::sandbox::idmap::rm_helper_main(&args[1..]),
173 Some(b"__sandbox-net") => crate::sandbox::net::net_helper_main(&args[1..]),
174 Some(b"__sandbox-map") => crate::sandbox::idmap::map_helper_main(&args[1..]),
175 Some(b"__sandbox-unpack") => crate::oci::unpack_helper_main(),
176 _ => {
177 eprintln!("forge-sandbox: unknown helper command");
178 125
179 }
180 }
181}
182
183async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
184 match cli.command {
185 Command::Register {
186 url,
187 token,
188 name,
189 labels,
190 config: path,
191 work_dir,
192 } => {
193 let client = ForgeClient::new(&url)?;
194 let resp = client
195 .register(&RegisterRequest {
196 token,
197 name: name.clone(),
198 labels: labels.clone(),
199 })
200 .await?;
201 let path = match path {
202 Some(p) => p,
203 None => config::default_config_path()?,
204 };
205 let work_dir = match work_dir {
206 Some(w) => w,
207 None => config::default_work_dir()?,
208 };
209 let cfg = RunnerConfig {
210 url,
211 runner_id: resp.runner_id.clone(),
212 runner_secret: resp.runner_secret,
213 name,
214 labels,
215 work_dir,
216 concurrency: 1,
217 limits: Limits::default(),
218 executor: ExecutorKind::default(),
219 images: ImagesConfig::default(),
220 sandbox: config::SandboxConfig::default(),
221 registries: Vec::new(),
222 auto_update: true,
223 cache_max_gib: config::default_cache_max_gib(),
224 };
225 config::save(&path, &cfg)?;
226 println!(
227 "registered runner {} and wrote {}",
228 resp.runner_id,
229 path.display()
230 );
231 Ok(ExitCode::SUCCESS)
232 }
233 Command::Run { config: path } => {
234 let path = match path {
235 Some(p) => p,
236 None => config::default_config_path()?,
237 };
238 let mut cfg = config::load(&path)?;
239 sync_config_with_forge(&mut cfg).await;
240 let shutdown = CancellationToken::new();
241 // Only the builtin executor puts its jobs under the box. With the box, a lone job may
242 // use all of it, so an undeclared job's cgroup limit is the box budget.
243 let pressure = match cfg.executor {
244 ExecutorKind::Builtin => {
245 let budget = crate::memory::MemoryGate::for_host(&cfg.limits).budget();
246 let pressure = Pressure::start(budget, shutdown.clone()).await;
247 if let Some(p) = &pressure {
248 cfg.limits.memory = p.budget().to_string();
249 }
250 pressure
251 }
252 ExecutorKind::Podman => None,
253 };
254 let cache_root = cfg.work_dir.join(".cache");
255 let cache_cap = cfg.cache_max_gib;
256 // The id map is what the executor's jobs run under. The cache removes its dirs with it.
257 let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor {
258 ExecutorKind::Podman => (
259 Arc::new(PodmanExecutor::new(cfg.limits.clone())),
260 IdMap::single(),
261 ),
262 ExecutorKind::Builtin => {
263 // Resolved once. In subuid mode a failure here is a startup error.
264 let map = IdMap::resolve(cfg.sandbox.userns)?;
265 tracing::info!("sandbox ids: {}", map.describe());
266 let helper = std::env::current_exe()?;
267 let root = cfg.work_dir.join("oci");
268 spawn_image_gc(
269 root.clone(),
270 cfg.images.keep_days,
271 map.clone(),
272 helper.clone(),
273 shutdown.clone(),
274 );
275 let images = ImageStore::new(root)
276 .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb))
277 .with_idmap(map.clone(), helper.clone());
278 // Before the first job: what an earlier run left behind.
279 crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await;
280 let jobs_dir = cfg.work_dir.join("jobs");
281 let executor =
282 BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir)
283 .with_idmap(map.clone())
284 .with_registries(&cfg.registries);
285 (Arc::new(executor), map)
286 }
287 };
288 let mut runner =
289 Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure);
290 if cache_cap > 0 {
291 let cache =
292 CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?);
293 if let Err(e) = cache.sweep_stale().await {
294 tracing::warn!(error = %e, "cannot remove stale cache dirs");
295 }
296 runner = runner.with_cache(cache);
297 }
298 let stop = shutdown.clone();
299 tokio::spawn(async move {
300 if tokio::signal::ctrl_c().await.is_ok() {
301 tracing::info!("interrupt received, cancelling running jobs");
302 stop.cancel();
303 }
304 });
305 match runner.run(shutdown).await {
306 RunEnd::Stopped => Ok(ExitCode::SUCCESS),
307 // systemd restarts the runner on this code, and it starts the new binary.
308 RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
309 // An admin asked for a restart. The same exit code, the same systemd restart.
310 RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
311 }
312 }
313 Command::Check {
314 work_dir,
315 config: config_path,
316 } => {
317 let work_dir = match work_dir {
318 Some(w) => w,
319 None => config::default_work_dir()?,
320 };
321 let mode = check_userns_mode(config_path)?;
322 let helper = std::env::current_exe()?;
323 if crate::check::run(&helper, &work_dir, mode).await {
324 Ok(ExitCode::SUCCESS)
325 } else {
326 Err("some host checks failed, see the report above".into())
327 }
328 }
329 }
330}
331
332/// The `[sandbox] userns` setting for `check`. An explicit config must exist. Without one, the
333/// default config is used if it exists, and otherwise the mode is `auto`.
334fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config::ConfigError> {
335 if let Some(path) = config_path {
336 return Ok(config::load(&path)?.sandbox.userns);
337 }
338 match config::default_config_path() {
339 Ok(path) if path.exists() => Ok(config::load(&path)?.sandbox.userns),
340 _ => Ok(UsernsMode::Auto),
341 }
342}
343
344/// Garbage collects unused images now and then once a day, until `shutdown` is cancelled. Images
345/// are removed under `map`, the same as when they were unpacked.
346fn spawn_image_gc(
347 root: PathBuf,
348 keep_days: u32,
349 map: IdMap,
350 helper: PathBuf,
351 shutdown: CancellationToken,
352) {
353 tokio::spawn(async move {
354 loop {
355 let (root, map, helper) = (root.clone(), map.clone(), helper.clone());
356 let result = tokio::task::spawn_blocking(move || {
357 ImageStore::new(root).with_idmap(map, helper).gc(keep_days)
358 })
359 .await;
360 match result {
361 Ok(Ok(stats)) => tracing::info!(?stats, "image garbage collection finished"),
362 Ok(Err(e)) => tracing::warn!("image garbage collection failed: {e}"),
363 Err(e) => tracing::warn!("image garbage collection task failed: {e}"),
364 }
365 tokio::select! {
366 _ = tokio::time::sleep(GC_INTERVAL) => {}
367 _ = shutdown.cancelled() => break,
368 }
369 }
370 });
371}
372
373/// `image_max_gb` as bytes.
374fn gib(gb: u64) -> u64 {
375 gb.saturating_mul(1024 * 1024 * 1024)
376}
377
378/// Applies the admin's startup-time overrides from the forge to `cfg` and reports the effective
379/// config back for the admin page. Best effort: an older forge, or a forge that cannot be reached,
380/// leaves `runner.toml` as it is and the runner starts anyway.
381async fn sync_config_with_forge(cfg: &mut RunnerConfig) {
382 let client = match crate::client::ForgeClient::new(&cfg.url) {
383 Ok(client) => client,
384 Err(e) => {
385 tracing::warn!(error = %e, "cannot sync config with the forge");
386 return;
387 }
388 };
389 match client.get_config(&cfg.runner_secret).await {
390 Ok(reply) => {
391 for line in cfg.apply_overrides(&reply.overrides) {
392 tracing::info!("{line}");
393 }
394 }
395 Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"),
396 }
397 let report = forge_ci::proto::RunnerConfigReport {
398 config: cfg.report(),
399 };
400 if let Err(e) = client.put_config(&cfg.runner_secret, &report).await {
401 tracing::warn!(error = %e, "cannot report config to the forge");
402 }
403}