forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

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