forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiB197fa34Tahinli1 month ago68 commits

cli.rs390 lines, 14.9 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` 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-unpack") => crate::oci::unpack_helper_main(),
165 _ => {
166 eprintln!("forge-sandbox: unknown helper command");
167 125
168 }
169 }
170}
171
172async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
173 match cli.command {
174 Command::Register {
175 url,
176 token,
177 name,
178 labels,
179 config: path,
180 work_dir,
181 } => {
182 let client = ForgeClient::new(&url)?;
183 let resp = client
184 .register(&RegisterRequest {
185 token,
186 name: name.clone(),
187 labels: labels.clone(),
188 })
189 .await?;
190 let path = match path {
191 Some(p) => p,
192 None => config::default_config_path()?,
193 };
194 let work_dir = match work_dir {
195 Some(w) => w,
196 None => config::default_work_dir()?,
197 };
198 let cfg = RunnerConfig {
199 url,
200 runner_id: resp.runner_id.clone(),
201 runner_secret: resp.runner_secret,
202 name,
203 labels,
204 work_dir,
205 concurrency: 1,
206 limits: Limits::default(),
207 executor: ExecutorKind::default(),
208 images: ImagesConfig::default(),
209 sandbox: config::SandboxConfig::default(),
210 registries: Vec::new(),
211 auto_update: true,
212 cache_max_gib: config::default_cache_max_gib(),
213 };
214 config::save(&path, &cfg)?;
215 println!(
216 "registered runner {} and wrote {}",
217 resp.runner_id,
218 path.display()
219 );
220 Ok(ExitCode::SUCCESS)
221 }
222 Command::Run { config: path } => {
223 let path = match path {
224 Some(p) => p,
225 None => config::default_config_path()?,
226 };
227 let mut cfg = config::load(&path)?;
228 sync_config_with_forge(&mut cfg).await;
229 let shutdown = CancellationToken::new();
230 // Only the builtin executor puts its jobs under the box. With the box, a lone job may
231 // use all of it, so an undeclared job's cgroup limit is the box budget.
232 let pressure = match cfg.executor {
233 ExecutorKind::Builtin => {
234 let budget = crate::memory::MemoryGate::for_host(&cfg.limits).budget();
235 let pressure = Pressure::start(budget, shutdown.clone()).await;
236 if let Some(p) = &pressure {
237 cfg.limits.memory = p.budget().to_string();
238 }
239 pressure
240 }
241 ExecutorKind::Podman => None,
242 };
243 let cache_root = cfg.work_dir.join(".cache");
244 let cache_cap = cfg.cache_max_gib;
245 // The id map is what the executor's jobs run under. The cache removes its dirs with it.
246 let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor {
247 ExecutorKind::Podman => (
248 Arc::new(PodmanExecutor::new(cfg.limits.clone())),
249 IdMap::single(),
250 ),
251 ExecutorKind::Builtin => {
252 // Resolved once. In subuid mode a failure here is a startup error.
253 let map = IdMap::resolve(cfg.sandbox.userns)?;
254 tracing::info!("sandbox ids: {}", map.describe());
255 let helper = std::env::current_exe()?;
256 let root = cfg.work_dir.join("oci");
257 spawn_image_gc(
258 root.clone(),
259 cfg.images.keep_days,
260 map.clone(),
261 helper.clone(),
262 shutdown.clone(),
263 );
264 let images = ImageStore::new(root)
265 .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb))
266 .with_idmap(map.clone(), helper.clone());
267 let jobs_dir = cfg.work_dir.join("jobs");
268 let executor =
269 BuiltinExecutor::new(images, cfg.limits.clone(), helper, jobs_dir)
270 .with_idmap(map.clone())
271 .with_registries(&cfg.registries);
272 (Arc::new(executor), map)
273 }
274 };
275 let mut runner =
276 Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure);
277 if cache_cap > 0 {
278 let cache =
279 CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?);
280 if let Err(e) = cache.sweep_stale().await {
281 tracing::warn!(error = %e, "cannot remove stale cache dirs");
282 }
283 runner = runner.with_cache(cache);
284 }
285 let stop = shutdown.clone();
286 tokio::spawn(async move {
287 if tokio::signal::ctrl_c().await.is_ok() {
288 tracing::info!("interrupt received, cancelling running jobs");
289 stop.cancel();
290 }
291 });
292 match runner.run(shutdown).await {
293 RunEnd::Stopped => Ok(ExitCode::SUCCESS),
294 // systemd restarts the runner on this code, and it starts the new binary.
295 RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
296 // An admin asked for a restart. The same exit code, the same systemd restart.
297 RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)),
298 }
299 }
300 Command::Check {
301 work_dir,
302 config: config_path,
303 } => {
304 let work_dir = match work_dir {
305 Some(w) => w,
306 None => config::default_work_dir()?,
307 };
308 let mode = check_userns_mode(config_path)?;
309 let helper = std::env::current_exe()?;
310 if crate::check::run(&helper, &work_dir, mode).await {
311 Ok(ExitCode::SUCCESS)
312 } else {
313 Err("some host checks failed, see the report above".into())
314 }
315 }
316 }
317}
318
319/// The `[sandbox] userns` setting for `check`. An explicit config must exist. Without one, the
320/// default config is used if it exists, and otherwise the mode is `auto`.
321fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config::ConfigError> {
322 if let Some(path) = config_path {
323 return Ok(config::load(&path)?.sandbox.userns);
324 }
325 match config::default_config_path() {
326 Ok(path) if path.exists() => Ok(config::load(&path)?.sandbox.userns),
327 _ => Ok(UsernsMode::Auto),
328 }
329}
330
331/// Garbage collects unused images now and then once a day, until `shutdown` is cancelled. Images
332/// are removed under `map`, the same as when they were unpacked.
333fn spawn_image_gc(
334 root: PathBuf,
335 keep_days: u32,
336 map: IdMap,
337 helper: PathBuf,
338 shutdown: CancellationToken,
339) {
340 tokio::spawn(async move {
341 loop {
342 let (root, map, helper) = (root.clone(), map.clone(), helper.clone());
343 let result = tokio::task::spawn_blocking(move || {
344 ImageStore::new(root).with_idmap(map, helper).gc(keep_days)
345 })
346 .await;
347 match result {
348 Ok(Ok(stats)) => tracing::info!(?stats, "image garbage collection finished"),
349 Ok(Err(e)) => tracing::warn!("image garbage collection failed: {e}"),
350 Err(e) => tracing::warn!("image garbage collection task failed: {e}"),
351 }
352 tokio::select! {
353 _ = tokio::time::sleep(GC_INTERVAL) => {}
354 _ = shutdown.cancelled() => break,
355 }
356 }
357 });
358}
359
360/// `image_max_gb` as bytes.
361fn gib(gb: u64) -> u64 {
362 gb.saturating_mul(1024 * 1024 * 1024)
363}
364
365/// Applies the admin's startup-time overrides from the forge to `cfg` and reports the effective
366/// config back for the admin page. Best effort: an older forge, or a forge that cannot be reached,
367/// leaves `runner.toml` as it is and the runner starts anyway.
368async fn sync_config_with_forge(cfg: &mut RunnerConfig) {
369 let client = match crate::client::ForgeClient::new(&cfg.url) {
370 Ok(client) => client,
371 Err(e) => {
372 tracing::warn!(error = %e, "cannot sync config with the forge");
373 return;
374 }
375 };
376 match client.get_config(&cfg.runner_secret).await {
377 Ok(reply) => {
378 for line in cfg.apply_overrides(&reply.overrides) {
379 tracing::info!("{line}");
380 }
381 }
382 Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"),
383 }
384 let report = forge_ci::proto::RunnerConfigReport {
385 config: cfg.report(),
386 };
387 if let Err(e) = client.put_config(&cfg.runner_secret, &report).await {
388 tracing::warn!(error = %e, "cannot report config to the forge");
389 }
390}