forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiB51b2bbfTahinli1 month ago19 commits

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