Coverage / crates/flow/src/main.rs 31.3%
126 of 402 lines run, 14 of 108 functions · run #216 on main · run missed
| 1 | //! `flow`: check pipelines, run them locally, and run jobs for OxygenHub | |
| 2 | //! (docs/spec.md, docs/m0.md). | |
| 3 | | |
| 4 | use flow::{facts, home, images, microvm, runner, syscall, wait, wasm, workspace}; | |
| 5 | ||
| 6 | use anyhow::{bail, Context, Result}; | |
| 7 | use clap::{Parser, Subcommand}; | |
| 8 | use flow_core::api::Record; | |
| 9 | use flow_core::{Pipeline, Runtime, PIPELINE_PATH}; | |
| 10 | use home::Home; | |
| 11 | use std::collections::BTreeSet; | |
| 12 | use std::path::{Path, PathBuf}; | |
| 13 | use std::time::Duration; | |
| 14 | ||
| 15 | #[derive(Parser)] | |
| 16 | #[command(name = "flow", version = env!("OXY_VERSION_LONG"), about = "OxygenFlow: hermetic pipelines for Oxygen repositories")] | |
| 17 | struct Cli { | |
| 18 | /// The Flow home (default $FLOW_HOME, else ~/.local/share/flow). | |
| 19 | #[arg(long, global = true)] | |
| 20 | home: Option<PathBuf>, | |
| 21 | #[command(subcommand)] | |
| 22 | cmd: Cmd, | |
| 23 | } | |
| 24 | ||
| 25 | #[derive(Subcommand)] | |
| 26 | enum RunnerCmd { | |
| 27 | /// Register this runner with a hub using a one-time token from its Admin → Runners page | |
| 28 | Register { | |
| 29 | /// The hub, e.g. https://earth.example:7343 | |
| 30 | hub: String, | |
| 31 | /// The registration token (read from stdin when not given) | |
| 32 | #[arg(long)] | |
| 33 | token: Option<String>, | |
| 34 | /// The runner's name (default: the host name) | |
| 35 | #[arg(long)] | |
| 36 | name: Option<String>, | |
| 37 | /// The hub's CA certificate, when self-signed | |
| 38 | #[arg(long)] | |
| 39 | ca: Option<PathBuf>, | |
| 40 | /// A label the runner offers (repeatable) | |
| 41 | #[arg(long)] | |
| 42 | label: Vec<String>, | |
| 43 | }, | |
| 44 | /// Measure this machine as a runner does: its speed score (100 on the | |
| 45 | /// reference machine) and class, free disk and load (spec §11.1) | |
| 46 | Bench, | |
| 47 | /// Ask this home's running runner to drain: claim nothing more, finish | |
| 48 | /// and report what it holds, then stop (as SIGTERM does on Linux; on | |
| 49 | /// Windows, the way to stop a runner without losing its job) | |
| 50 | Drain, | |
| 51 | /// Install a new flow build in place of this one (docs/jetstream.md | |
| 52 | /// §8.2): check it, keep this one as flow.prev, and have the running | |
| 53 | /// runner leave with notice so its unit starts the new build. A build | |
| 54 | /// that does not reach the hub goes back to flow.prev by itself | |
| 55 | Update { | |
| 56 | /// The new flow binary | |
| 57 | #[arg(long)] | |
| 58 | from: PathBuf, | |
| 59 | /// Seconds the running runner has to finish what it holds; jobs | |
| 60 | /// that will not finish in time are handed back with their checkpoints | |
| 61 | #[arg(long, default_value_t = 600)] | |
| 62 | notice: u64, | |
| 63 | /// Check the build and say what would happen, changing nothing | |
| 64 | #[arg(long)] | |
| 65 | dry_run: bool, | |
| 66 | /// Install a build older than this one | |
| 67 | #[arg(long)] | |
| 68 | allow_older: bool, | |
| 69 | /// The installed binary to replace (default: this one) | |
| 70 | #[arg(long)] | |
| 71 | exe: Option<PathBuf>, | |
| 72 | }, | |
| 73 | } | |
| 74 | ||
| 75 | #[derive(Subcommand)] | |
| 76 | enum Cmd { | |
| 77 | /// Validate a pipeline and print its jobs and hash | |
| 78 | Check { | |
| 79 | /// The pipeline file (default: .flow/pipeline.kdl) | |
| 80 | file: Option<PathBuf>, | |
| 81 | }, | |
| 82 | /// Print a file's BLAKE3, for pinning in flow.toml | |
| 83 | Hash { file: PathBuf }, | |
| 84 | /// Rootfs images for sandboxes | |
| 85 | Rootfs { | |
| 86 | #[command(subcommand)] | |
| 87 | cmd: RootfsCmd, | |
| 88 | }, | |
| 89 | /// Run the pipeline on this directory's files, locally | |
| 90 | Run { | |
| 91 | /// Only these jobs (and what they depend on) | |
| 92 | jobs: Vec<String>, | |
| 93 | /// The directory to build (default: the current one) | |
| 94 | #[arg(long, default_value = ".")] | |
| 95 | dir: PathBuf, | |
| 96 | /// Minutes before a job is stopped | |
| 97 | #[arg(long, default_value_t = 60)] | |
| 98 | timeout: u64, | |
| 99 | /// A variable for every job, as the hub's settings would give it; | |
| 100 | /// the pipeline's own `env` wins | |
| 101 | #[arg(long = "var", value_name = "NAME=VALUE")] | |
| 102 | vars: Vec<String>, | |
| 103 | /// A secret a job's `secret` block names, as the hub would supply | |
| 104 | /// it; mounted as a file, never in the environment | |
| 105 | #[arg(long = "secret", value_name = "NAME=VALUE")] | |
| 106 | secrets: Vec<String>, | |
| 107 | }, | |
| 108 | /// Claim and run jobs for the hub in flow.toml's [runner] (or the | |
| 109 | /// runner.toml `flow runner register` wrote) | |
| 110 | Runner { | |
| 111 | #[command(subcommand)] | |
| 112 | cmd: Option<RunnerCmd>, | |
| 113 | }, | |
| 114 | /// Follow the checks of a pushed state on OxygenHub until they finish: | |
| 115 | /// exit 0 when all passed, 1 when one failed, 2 at the time limit. | |
| 116 | /// Uses $OXY_TOKEN and $OXY_CA as oxy does. | |
| 117 | Wait { | |
| 118 | /// The repository's URL on the hub (https://hub/owner/name) | |
| 119 | url: String, | |
| 120 | /// The state hash the push moved the bookmark to (`oxy push --json` prints it) | |
| 121 | state: String, | |
| 122 | /// Minutes to wait at most | |
| 123 | #[arg(long, default_value_t = 60)] | |
| 124 | timeout: u64, | |
| 125 | }, | |
| 126 | /// Show which isolation tiers this machine can run jobs in, and why | |
| 127 | /// the others cannot | |
| 128 | Tiers, | |
| 129 | /// The syscall tier's sandbox helper, started by the runner for each job | |
| 130 | #[command(name = "__sandbox", hide = true)] | |
| 131 | Sandbox { spec: PathBuf }, | |
| 132 | /// Check that this machine can run the syscall tier | |
| 133 | #[command(name = "__sandbox-probe", hide = true)] | |
| 134 | SandboxProbe, | |
| 135 | /// Rename a program that cannot rename its own file (Windows; #83) | |
| 136 | #[command(name = "__rename", hide = true)] | |
| 137 | Rename { from: PathBuf, to: PathBuf }, | |
| 138 | /// The WASM tier's helper, started by the runner for each job | |
| 139 | #[command(name = "__wasm", hide = true)] | |
| 140 | Wasm { spec: PathBuf }, | |
| 141 | } | |
| 142 | ||
| 143 | #[derive(Subcommand)] | |
| 144 | enum RootfsCmd { | |
| 145 | /// Make an ext4 rootfs image from a root file system tarball and store it by hash | |
| 146 | Import { | |
| 147 | tarball: PathBuf, | |
| 148 | /// Refuse the tarball unless its SHA-256 matches (as its publisher states it) | |
| 149 | #[arg(long)] | |
| 150 | sha256: Option<String>, | |
| 151 | /// The image's own environment, NAME=value (repeatable): what a | |
| 152 | /// Dockerfile's ENV sets and `docker export` loses. Jobs start from | |
| 153 | /// it; their sandbox's and their own `env` override it | |
| 154 | #[arg(long = "env", value_name = "NAME=VALUE")] | |
| 155 | env: Vec<String>, | |
| 156 | }, | |
| 157 | /// List the images this home holds | |
| 158 | List, | |
| 159 | /// Send an image to a hub, so its runners fetch it instead of having it | |
| 160 | /// copied to them: only the chunks the hub lacks travel. Signs in as | |
| 161 | /// `oh` is signed in to that hub, or with $OXY_TOKEN and $OXY_CA | |
| 162 | Push { | |
| 163 | /// The image's hash, as pipelines pin it (cas://blob/HASH) | |
| 164 | hash: String, | |
| 165 | /// The hub (default: $OH_HUB, else the runner's, from runner.toml or flow.toml) | |
| 166 | #[arg(long)] | |
| 167 | hub: Option<String>, | |
| 168 | }, | |
| 169 | /// Fetch an image a hub holds into this home, as a runner does for a | |
| 170 | /// job whose image it lacks. Signs in as `oh` is, or with $OXY_TOKEN | |
| 171 | Pull { | |
| 172 | hash: String, | |
| 173 | #[arg(long)] | |
| 174 | hub: Option<String>, | |
| 175 | }, | |
| 176 | } | |
| 177 | ||
| 178 | 5× | fn main() { |
| 179 | 5× | let cli = Cli::parse(); |
| 180 | 5× | if let Err(e) = run(cli) { |
| 181 | 2× | eprintln!("flow: {e:#}"); |
| 182 | 2× | std::process::exit(1); |
| 183 | 3× | } |
| 184 | 3× | } |
| 185 | ||
| 186 | 5× | fn run(cli: Cli) -> Result<()> { |
| 187 | 0× | match cli.cmd { |
| 188 | 0× | Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)), |
| 189 | 0× | Cmd::SandboxProbe => std::process::exit(syscall::probe_main()), |
| 190 | 0× | Cmd::Rename { from, to } => { |
| 191 | 0× | flow::portable::rename(&from, &to).with_context(|| format!("renaming {} to {}", from.display(), to.display()))?; |
| 192 | 0× | Ok(()) |
| 193 | } | |
| 194 | 0× | Cmd::Wasm { spec } => std::process::exit(wasm::wasm_main(&spec)), |
| 195 | 0× | Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))), |
| 196 | 0× | Cmd::Hash { file } => { |
| 197 | 0× | println!("{}", home::hash_file(&file)?); |
| 198 | 0× | Ok(()) |
| 199 | } | |
| 200 | 0× | Cmd::Rootfs { cmd } => { |
| 201 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 202 | 0× | match cmd { |
| 203 | 0× | RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env), |
| 204 | 0× | RootfsCmd::Push { hash, hub } => { |
| 205 | 0× | let client = image_client(&home, hub)?; |
| 206 | 0× | eprintln!("Sending image {} …", &hash[..12.min(hash.len())]); |
| 207 | 0× | let m = client.push(&home, &hash)?; |
| 208 | 0× | println!( |
| 209 | "Sent image {}: {} chunks the hub lacked, {} in {:.1} s", | |
| 210 | 0× | &hash[..12], |
| 211 | m.chunks, | |
| 212 | 0× | images::human(m.bytes), |
| 213 | 0× | m.elapsed.as_secs_f64() |
| 214 | ); | |
| 215 | 0× | Ok(()) |
| 216 | } | |
| 217 | 0× | RootfsCmd::Pull { hash, hub } => { |
| 218 | 0× | let client = image_client(&home, hub)?; |
| 219 | 0× | match client.fetch(&home, &hash)? { |
| 220 | 0× | Some(m) => { |
| 221 | 0× | println!( |
| 222 | "Fetched image {}: {} chunks, {} in {:.1} s", | |
| 223 | 0× | &hash[..12], |
| 224 | m.chunks, | |
| 225 | 0× | images::human(m.bytes), |
| 226 | 0× | m.elapsed.as_secs_f64() |
| 227 | ); | |
| 228 | 0× | Ok(()) |
| 229 | } | |
| 230 | 0× | None => anyhow::bail!("the hub does not hold image {}; send it with flow rootfs push", &hash[..12.min(hash.len())]), |
| 231 | } | |
| 232 | } | |
| 233 | RootfsCmd::List => { | |
| 234 | 0× | for e in std::fs::read_dir(home.root.join("cas"))?.flatten() { |
| 235 | 0× | let size = e.metadata().map(|m| m.len()).unwrap_or(0); |
| 236 | 0× | if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") { |
| 237 | 0× | println!("cas://blob/{h} {} MiB", size >> 20); |
| 238 | 0× | } |
| 239 | } | |
| 240 | 0× | Ok(()) |
| 241 | } | |
| 242 | } | |
| 243 | } | |
| 244 | 2× | Cmd::Run { jobs, dir, timeout, vars, secrets } => { |
| 245 | 2× | let home = Home::locate(cli.home.as_deref())?; |
| 246 | 4× | let pairs = |what: &str, list: &[String]| { |
| 247 | 4× | list.iter() |
| 248 | 4× | .map(|e| { |
| 249 | 0× | e.split_once('=') |
| 250 | 0× | .map(|(k, v)| (k.to_string(), v.to_string())) |
| 251 | 0× | .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE")) |
| 252 | 0× | }) |
| 253 | 4× | .collect::<Result<Vec<_>>>() |
| 254 | 4× | }; |
| 255 | 2× | let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?); |
| 256 | 2× | run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets) |
| 257 | } | |
| 258 | Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => { | |
| 259 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 260 | 0× | let (speed, ms) = facts::bench(); |
| 261 | 0× | let f = facts::now(&home, Some(speed)); |
| 262 | 0× | println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed)); |
| 263 | 0× | println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display()); |
| 264 | 0× | match f.load_x100 { |
| 265 | 0× | Some(l) => println!("load {:.2}", l as f64 / 100.0), |
| 266 | 0× | None => println!("load not measured here"), |
| 267 | } | |
| 268 | 0× | if let Some(k) = f.kernel { |
| 269 | 0× | println!("kernel {k}"); |
| 270 | 0× | } |
| 271 | 0× | Ok(()) |
| 272 | } | |
| 273 | 0× | Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => { |
| 274 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 275 | 0× | if std::env::var_os("OXY_HOME").is_none() { |
| 276 | 0× | std::env::set_var("OXY_HOME", home.root.join("oxy")); |
| 277 | 0× | } |
| 278 | 0× | let name = name.unwrap_or_else(|| { |
| 279 | 0× | std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into()) |
| 280 | 0× | }); |
| 281 | 0× | let token = match token { |
| 282 | 0× | Some(t) => t, |
| 283 | None => { | |
| 284 | 0× | eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:"); |
| 285 | 0× | let mut line = String::new(); |
| 286 | 0× | std::io::stdin().read_line(&mut line)?; |
| 287 | 0× | line.trim().to_string() |
| 288 | } | |
| 289 | }; | |
| 290 | 0× | let got = runner::register(&home, &hub, &token, &name, ca, label)?; |
| 291 | 0× | println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id); |
| 292 | 0× | Ok(()) |
| 293 | } | |
| 294 | Cmd::Runner { cmd: Some(RunnerCmd::Drain) } => { | |
| 295 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 296 | 0× | if flow::update::ask_to_drain(&home.root)? { |
| 297 | 0× | println!("asked the runner to drain: it claims nothing more and stops once its jobs are done and reported"); |
| 298 | 0× | } else { |
| 299 | 0× | println!("no runner of this home is running; the next one starts afresh"); |
| 300 | 0× | } |
| 301 | 0× | Ok(()) |
| 302 | } | |
| 303 | 0× | Cmd::Runner { cmd: Some(RunnerCmd::Update { from, notice, dry_run, allow_older, exe }) } => { |
| 304 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 305 | 0× | let exe = match exe { |
| 306 | 0× | Some(e) => e, |
| 307 | 0× | None => std::env::current_exe().context("finding this flow binary")?, |
| 308 | }; | |
| 309 | 0× | let done = flow::update::install(&home, &exe, &from, Duration::from_secs(notice), dry_run, allow_older)?; |
| 310 | 0× | if dry_run { |
| 311 | 0× | println!( |
| 312 | "flow {} checks out: it would replace flow {} at {} (dry run: nothing changed)", | |
| 313 | done.to, | |
| 314 | done.from, | |
| 315 | 0× | done.exe.display() |
| 316 | ); | |
| 317 | 0× | return Ok(()); |
| 318 | 0× | } |
| 319 | 0× | println!("flow {} installed at {}; flow {} kept as {}", done.to, done.exe.display(), done.from, flow::update::PREV); |
| 320 | 0× | match done.told { |
| 321 | 0× | Some(pid) => println!("the runner (pid {pid}) leaves within {notice} s, then its unit starts flow {}", done.to), |
| 322 | 0× | None => println!( |
| 323 | "no runner of this home was told (none runs, or one from before runner updates, which does not listen): \ | |
| 324 | restart its unit, e.g. `systemctl restart --no-block flow-runner`; it drains and starts flow {}", | |
| 325 | done.to | |
| 326 | ), | |
| 327 | } | |
| 328 | 0× | Ok(()) |
| 329 | } | |
| 330 | Cmd::Runner { cmd: None } => { | |
| 331 | 0× | let home = Home::locate(cli.home.as_deref())?; |
| 332 | // A new build on trial that keeps failing to start goes back to | |
| 333 | // the one before, which then runs in its place (#85). | |
| 334 | 0× | if let flow::update::Start::RolledBack(p) = flow::update::on_start(&home.root)? { |
| 335 | #[cfg(unix)] | |
| 336 | { | |
| 337 | use std::os::unix::process::CommandExt; | |
| 338 | 0× | let err = std::process::Command::new(&p.exe).args(std::env::args_os().skip(1)).exec(); |
| 339 | 0× | bail!("starting flow {} again after the rollback: {err}", p.from); |
| 340 | } | |
| 341 | // Windows has no exec: run the restored build and end with it. | |
| 342 | #[cfg(not(unix))] | |
| 343 | { | |
| 344 | let status = std::process::Command::new(&p.exe) | |
| 345 | .args(std::env::args_os().skip(1)) | |
| 346 | .status() | |
| 347 | .with_context(|| format!("starting flow {} again after the rollback", p.from))?; | |
| 348 | std::process::exit(status.code().unwrap_or(1)); | |
| 349 | } | |
| 350 | 0× | } |
| 351 | // The runner's oxy state (identity, user config) stays in its home. | |
| 352 | 0× | if std::env::var_os("OXY_HOME").is_none() { |
| 353 | 0× | std::env::set_var("OXY_HOME", home.root.join("oxy")); |
| 354 | 0× | } |
| 355 | 0× | runner::serve(&home) |
| 356 | } | |
| 357 | Cmd::Tiers => { | |
| 358 | 3× | let home = Home::locate(cli.home.as_deref())?; |
| 359 | 3× | match runner::tiers(&home) { |
| 360 | 3× | Ok((have, missing)) => { |
| 361 | 3× | for t in have { |
| 362 | 3× | println!("{t}: available"); |
| 363 | 3× | } |
| 364 | 6× | for why in missing { |
| 365 | 6× | println!("{}", why.replacen(": ", ": unavailable: ", 1)); |
| 366 | 6× | } |
| 367 | } | |
| 368 | 0× | Err(why) => println!("{why}"), |
| 369 | } | |
| 370 | 3× | Ok(()) |
| 371 | } | |
| 372 | 0× | Cmd::Wait { url, state, timeout } => { |
| 373 | 0× | let token = std::env::var("OXY_TOKEN").ok(); |
| 374 | 0× | let ca = std::env::var_os("OXY_CA").map(PathBuf::from); |
| 375 | 0× | let code = |
| 376 | 0× | wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?; |
| 377 | 0× | std::process::exit(code); |
| 378 | } | |
| 379 | } | |
| 380 | 5× | } |
| 381 | ||
| 382 | /// The hub image commands talk to: `--hub`, else $OH_HUB, else the | |
| 383 | /// runner's. The token: $OXY_TOKEN, else the login `oh auth login` (or | |
| 384 | /// `oxy auth login`) saved for that hub in Oxygen's credential store | |
| 385 | /// (oxygenflow#44), else the runner's own. | |
| 386 | 0× | fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> { |
| 387 | 0× | let runner = home.config.runner.clone(); |
| 388 | 0× | let hub = hub |
| 389 | 0× | .or_else(|| std::env::var("OH_HUB").ok().filter(|h| !h.is_empty())) |
| 390 | 0× | .or_else(|| runner.as_ref().map(|r| r.hub.clone())) |
| 391 | 0× | .context("name the hub with --hub https://HUB (or set OH_HUB)")?; |
| 392 | 0× | let (saved_token, saved_ca) = oxy_core::credentials::Credentials::user().lookup(&hub); |
| 393 | 0× | let token = std::env::var("OXY_TOKEN") |
| 394 | 0× | .ok() |
| 395 | 0× | .filter(|t| !t.is_empty()) |
| 396 | 0× | .or(saved_token) |
| 397 | 0× | .or_else(|| runner.as_ref().map(|r| r.token.clone())) |
| 398 | 0× | .with_context(|| format!("no token for {hub}: sign in with `oh auth login --hub {hub}`, or set OXY_TOKEN"))?; |
| 399 | 0× | let ca = std::env::var_os("OXY_CA").map(PathBuf::from).or(saved_ca).or_else(|| runner.as_ref().and_then(|r| r.ca.clone())); |
| 400 | 0× | images::Client::new(&hub, &token, ca.as_deref()) |
| 401 | 0× | } |
| 402 | ||
| 403 | 2× | fn load(file: &Path) -> Result<Pipeline> { |
| 404 | 2× | let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?; |
| 405 | 2× | Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{}", not_valid(file, &p.to_string()))) |
| 406 | 2× | } |
| 407 | ||
| 408 | /// Why a pipeline did not parse. When it names something this flow does | |
| 409 | /// not know (a node, an output, an event), the pipeline may simply be | |
| 410 | /// newer than this flow (oxygenflow#43): say so, with this flow's version. | |
| 411 | 2× | fn not_valid(file: &Path, problems: &str) -> String { |
| 412 | 2× | if problems.contains("unknown ") { |
| 413 | 1× | format!( |
| 414 | "{} uses something this flow ({}) does not know:\n{problems}\n\ | |
| 415 | If the pipeline was written for a newer OxygenFlow, update flow (build it from oxygenflow main); \ | |
| 416 | otherwise fix the lines named.", | |
| 417 | 1× | file.display(), |
| 418 | env!("OXY_VERSION_LONG") | |
| 419 | ) | |
| 420 | } else { | |
| 421 | 1× | format!("{} is not valid:\n{problems}", file.display()) |
| 422 | } | |
| 423 | 2× | } |
| 424 | ||
| 425 | 0× | fn check(file: &Path) -> Result<()> { |
| 426 | 0× | let p = load(file)?; |
| 427 | 0× | let depths = p.depths(); |
| 428 | 0× | for j in p.order() { |
| 429 | 0× | let sb = &p.sandboxes[&j.sandbox]; |
| 430 | 0× | let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) }; |
| 431 | 0× | println!("{}{} {} [{}]{after}", " ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str()); |
| 432 | } | |
| 433 | 0× | println!("pipeline {}", hex::encode(p.hash())); |
| 434 | 0× | Ok(()) |
| 435 | 0× | } |
| 436 | ||
| 437 | /// The image environment file flow-init reads (`/etc/flow/env`): one | |
| 438 | /// `NAME=value` per line, names checked as a pipeline's are. | |
| 439 | 5× | fn image_env_file(env: &[String]) -> Result<String> { |
| 440 | 5× | let mut out = String::new(); |
| 441 | 6× | for e in env { |
| 442 | 6× | let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") }; |
| 443 | 16× | let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'); |
| 444 | 5× | if !ok || v.contains('\n') || v.contains('\0') { |
| 445 | 2× | bail!("--env {e:?}: a name is letters, digits and _, and a value is one line"); |
| 446 | 3× | } |
| 447 | 3× | out.push_str(&format!("{k}={v}\n")); |
| 448 | } | |
| 449 | 2× | Ok(out) |
| 450 | 5× | } |
| 451 | ||
| 452 | /// The architecture an ELF file was built for, by its header. | |
| 453 | 0× | fn elf_arch(path: &Path) -> Option<&'static str> { |
| 454 | 0× | let mut head = [0u8; 20]; |
| 455 | 0× | std::io::Read::read_exact(&mut std::fs::File::open(path).ok()?, &mut head).ok()?; |
| 456 | 0× | jet::rootfs::elf_arch(&head) |
| 457 | 0× | } |
| 458 | ||
| 459 | /// The architecture of an unpacked rootfs: its shell's, or the first | |
| 460 | /// program's found under bin. | |
| 461 | 0× | fn tree_arch(tree: &Path) -> Option<&'static str> { |
| 462 | 0× | for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] { |
| 463 | 0× | let p = tree.join(rel); |
| 464 | 0× | let p = std::fs::canonicalize(&p).unwrap_or(p); |
| 465 | 0× | if let Some(a) = elf_arch(&p) { |
| 466 | 0× | return Some(a); |
| 467 | 0× | } |
| 468 | } | |
| 469 | 0× | None |
| 470 | 0× | } |
| 471 | ||
| 472 | 0× | fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> { |
| 473 | 0× | let env_file = image_env_file(env)?; |
| 474 | 0× | if let Some(want) = sha256 { |
| 475 | 0× | let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?; |
| 476 | 0× | let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string(); |
| 477 | 0× | if got != want.to_lowercase() { |
| 478 | 0× | bail!("{} has SHA-256 {got}, expected {want}", tarball.display()); |
| 479 | 0× | } |
| 480 | 0× | } |
| 481 | 0× | let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id())); |
| 482 | 0× | let _ = std::fs::remove_dir_all(&tmp); |
| 483 | 0× | let tree = tmp.join("tree"); |
| 484 | 0× | std::fs::create_dir_all(&tree)?; |
| 485 | 0× | let result = (|| -> Result<String> { |
| 486 | 0× | let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?; |
| 487 | 0× | if !status.success() { |
| 488 | 0× | bail!("tar could not unpack {}", tarball.display()); |
| 489 | 0× | } |
| 490 | // The image's architecture must be this machine's: there is no | |
| 491 | // emulation tier (spec §11.2). | |
| 492 | 0× | let arch = tree_arch(&tree).unwrap_or("unknown"); |
| 493 | 0× | if arch != "unknown" && arch != std::env::consts::ARCH { |
| 494 | 0× | bail!( |
| 495 | "{} is a {arch} image; this runner is {}, and jobs here run no other architecture", | |
| 496 | 0× | tarball.display(), |
| 497 | std::env::consts::ARCH | |
| 498 | ); | |
| 499 | 0× | } |
| 500 | // Mount points flow-init needs (docs/m0.md §2). | |
| 501 | 0× | for d in ["src", "tmp", "proc", "dev", "run"] { |
| 502 | 0× | std::fs::create_dir_all(tree.join(d))?; |
| 503 | } | |
| 504 | 0× | if !env_file.is_empty() { |
| 505 | 0× | std::fs::create_dir_all(tree.join("etc/flow"))?; |
| 506 | 0× | std::fs::write(tree.join("etc/flow/env"), &env_file)?; |
| 507 | 0× | } |
| 508 | 0× | let used: u64 = ignore::WalkBuilder::new(&tree) |
| 509 | 0× | .hidden(false) |
| 510 | 0× | .ignore(false) |
| 511 | 0× | .git_ignore(false) |
| 512 | 0× | .build() |
| 513 | 0× | .flatten() |
| 514 | 0× | .filter_map(|e| e.metadata().ok()) |
| 515 | 0× | .map(|m| m.len().max(4096)) |
| 516 | 0× | .sum(); |
| 517 | 0× | let mib = used * 13 / 10 / (1 << 20) + 64; |
| 518 | 0× | let img = tmp.join("rootfs.ext4"); |
| 519 | 0× | let status = std::process::Command::new("mkfs.ext4") |
| 520 | 0× | .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"]) |
| 521 | 0× | .arg(&tree) |
| 522 | 0× | .arg(&img) |
| 523 | 0× | .arg(format!("{mib}M")) |
| 524 | 0× | .status() |
| 525 | 0× | .context("run mkfs.ext4")?; |
| 526 | 0× | if !status.success() { |
| 527 | 0× | bail!("mkfs.ext4 failed"); |
| 528 | 0× | } |
| 529 | 0× | let hash = home::hash_file(&img)?; |
| 530 | 0× | std::fs::rename(&img, home.rootfs(&hash))?; |
| 531 | 0× | let manifest = serde_json::json!({ "arch": if arch == "unknown" { std::env::consts::ARCH } else { arch }, "imported_ms": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) }); |
| 532 | 0× | std::fs::write(home.image_manifest(&hash), manifest.to_string())?; |
| 533 | 0× | Ok(hash) |
| 534 | })(); | |
| 535 | 0× | let _ = std::fs::remove_dir_all(&tmp); |
| 536 | 0× | let hash = result?; |
| 537 | 0× | println!("rootfs \"cas://blob/{hash}\""); |
| 538 | 0× | Ok(()) |
| 539 | 0× | } |
| 540 | ||
| 541 | 2× | fn run_local( |
| 542 | 2× | home: &Home, |
| 543 | 2× | dir: &Path, |
| 544 | 2× | only: &[String], |
| 545 | 2× | timeout: Duration, |
| 546 | 2× | vars: &[(String, String)], |
| 547 | 2× | secrets: &[(String, String)], |
| 548 | 2× | ) -> Result<()> { |
| 549 | 2× | let p = load(&dir.join(PIPELINE_PATH))?; |
| 550 | // The named jobs and everything they depend on. | |
| 551 | 2× | let mut wanted: BTreeSet<String> = only.iter().cloned().collect(); |
| 552 | 2× | for name in only { |
| 553 | 0× | if !p.jobs.contains_key(name) { |
| 554 | 0× | bail!("no job {name:?} in the pipeline"); |
| 555 | 0× | } |
| 556 | } | |
| 557 | 2× | if !only.is_empty() { |
| 558 | loop { | |
| 559 | 0× | let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect(); |
| 560 | 0× | if more.is_empty() { |
| 561 | 0× | break; |
| 562 | 0× | } |
| 563 | 0× | wanted.extend(more); |
| 564 | } | |
| 565 | 2× | } |
| 566 | 2× | let scratch = home.root.join("work").join(format!("local-{}", std::process::id())); |
| 567 | 2× | let _ = std::fs::remove_dir_all(&scratch); |
| 568 | 2× | std::fs::create_dir_all(scratch.join("tree"))?; |
| 569 | 2× | workspace::copy_tree(dir, &scratch.join("tree"))?; |
| 570 | 2× | let mut failed: BTreeSet<String> = BTreeSet::new(); |
| 571 | 2× | let mut worst = 0; |
| 572 | 12× | for job in p.order() { |
| 573 | 12× | if !only.is_empty() && !wanted.contains(&job.name) { |
| 574 | 0× | continue; |
| 575 | 12× | } |
| 576 | 12× | if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) { |
| 577 | 0× | println!("── {} skipped: {d} failed", job.name); |
| 578 | 0× | failed.insert(job.name.clone()); |
| 579 | 0× | continue; |
| 580 | 12× | } |
| 581 | 12× | let sb = &p.sandboxes[&job.sandbox]; |
| 582 | 12× | println!("── {} ({})", job.name, job.exec.join(" ")); |
| 583 | 12× | let js = scratch.join(&job.name); |
| 584 | 12× | std::fs::create_dir_all(&js)?; |
| 585 | 12× | let job = &job |
| 586 | 12× | .in_sandbox(sb) |
| 587 | 12× | .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())]) |
| 588 | 12× | .with_flow_env(vars); |
| 589 | // Identities come from a hub: a local run has none. | |
| 590 | 12× | for i in &job.identities { |
| 591 | 0× | println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path); |
| 592 | 0× | } |
| 593 | // Each secret the job declares must be given, as the hub would. | |
| 594 | 12× | let inputs = job |
| 595 | 12× | .secrets |
| 596 | 12× | .iter() |
| 597 | 12× | .map(|s| { |
| 598 | 0× | let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone()); |
| 599 | 0× | value |
| 600 | 0× | .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value }) |
| 601 | 0× | .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name)) |
| 602 | 0× | }) |
| 603 | 12× | .collect::<Result<Vec<_>>>()?; |
| 604 | // Each job starts from the same files: jobs do not share writes. | |
| 605 | 12× | let out = if sb.runtime == Runtime::Wasm { |
| 606 | 12× | workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?; |
| 607 | 17× | wasm::run(sb, job, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r))? |
| 608 | 0× | } else if sb.runtime == Runtime::Syscall { |
| 609 | 0× | workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?; |
| 610 | 0× | let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy()); |
| 611 | 0× | syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)? |
| 612 | } else { | |
| 613 | 0× | workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?; |
| 614 | 0× | microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))? |
| 615 | }; | |
| 616 | 12× | let _ = workspace::remove_tree(&js); |
| 617 | 12× | match out.exit_code { |
| 618 | 8× | Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms), |
| 619 | 4× | other => { |
| 620 | 4× | println!( |
| 621 | "── {} failed ({}) in {} ms", | |
| 622 | job.name, | |
| 623 | 4× | other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()), |
| 624 | out.duration_ms | |
| 625 | ); | |
| 626 | 4× | failed.insert(job.name.clone()); |
| 627 | 4× | worst = 1; |
| 628 | } | |
| 629 | } | |
| 630 | } | |
| 631 | 2× | let _ = workspace::remove_tree(&scratch); |
| 632 | 2× | if worst != 0 { |
| 633 | 2× | std::process::exit(worst); |
| 634 | 0× | } |
| 635 | 0× | Ok(()) |
| 636 | 0× | } |
| 637 | ||
| 638 | 17× | fn print_record(r: &Record) { |
| 639 | 17× | match r.stream.as_str() { |
| 640 | 17× | "out" => println!(" {}", r.text), |
| 641 | 13× | "err" => eprintln!(" {}", r.text), |
| 642 | 10× | s => eprintln!(" [{s}] {}", r.text), |
| 643 | } | |
| 644 | 17× | } |
| 645 | ||
| 646 | #[cfg(test)] | |
| 647 | mod tests { | |
| 648 | #[test] | |
| 649 | 1× | fn a_pipeline_newer_than_flow_is_named_as_such() { |
| 650 | 1× | let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 92: unknown output `sbom`; outputs are …"); |
| 651 | 1× | assert!(m.contains("does not know") && m.contains(env!("OXY_VERSION_LONG")) && m.contains("newer OxygenFlow"), "{m}"); |
| 652 | 1× | let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 3: a job needs a sandbox"); |
| 653 | 1× | assert!(m.contains("is not valid") && !m.contains("newer"), "{m}"); |
| 654 | 1× | } |
| 655 | | |
| 656 | use super::image_env_file; | |
| 657 | | |
| 658 | #[test] | |
| 659 | 1× | fn image_environments_are_checked_lines() { |
| 660 | 1× | let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap(); |
| 661 | 1× | assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n"); |
| 662 | 1× | assert!(image_env_file(&["NOEQUALS".into()]).is_err()); |
| 663 | 1× | assert!(image_env_file(&["1X=y".into()]).is_err()); |
| 664 | 1× | assert!(image_env_file(&["X=two\nlines".into()]).is_err()); |
| 665 | 1× | assert_eq!(image_env_file(&[]).unwrap(), ""); |
| 666 | 1× | } |
| 667 | } |