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