forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBdcdcd27Tahinli1 month ago240 commits

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