| e0918b88 Andy McCall |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
mod cpio; |
| 5 |
mod home; |
| 6 |
mod microvm; |
| a67b97e9 Andy McCall ↶ |
7 |
mod outputs; |
| e0918b88 Andy McCall |
8 |
mod runner; |
| 9e8f4a56 Andy McCall ↶ |
9 |
mod wait; |
| e0918b88 Andy McCall |
10 |
mod workspace; |
| 11 |
|
| 12 |
use anyhow::{bail, Context, Result}; |
| 13 |
use clap::{Parser, Subcommand}; |
| 14 |
use flow_core::api::Record; |
| 15 |
use flow_core::{Pipeline, Runtime, PIPELINE_PATH}; |
| 16 |
use home::Home; |
| 17 |
use std::collections::BTreeSet; |
| 18 |
use std::path::{Path, PathBuf}; |
| 19 |
use std::time::Duration; |
| 20 |
|
| 21 |
#[derive(Parser)] |
| 2d025bbf Andy McCall ↶ |
22 |
#[command(name = "flow", version = env!("OXY_VERSION_LONG"), about = "OxygenFlow: hermetic pipelines for Oxygen repositories")] |
| e0918b88 Andy McCall |
23 |
struct Cli { |
| 24 |
|
| 25 |
#[arg(long, global = true)] |
| 26 |
home: Option<PathBuf>, |
| 27 |
#[command(subcommand)] |
| 28 |
cmd: Cmd, |
| 29 |
} |
| 30 |
|
| 31 |
#[derive(Subcommand)] |
| f98a8f78 Andy McCall ↶ |
32 |
enum RunnerCmd { |
| 33 |
|
| 34 |
Register { |
| 35 |
|
| 36 |
hub: String, |
| 37 |
|
| 38 |
#[arg(long)] |
| 39 |
token: Option<String>, |
| 40 |
|
| 41 |
#[arg(long)] |
| 42 |
name: Option<String>, |
| 43 |
|
| 44 |
#[arg(long)] |
| 45 |
ca: Option<PathBuf>, |
| 46 |
|
| 47 |
#[arg(long)] |
| 48 |
label: Vec<String>, |
| 49 |
}, |
| 50 |
} |
| 51 |
|
| 52 |
#[derive(Subcommand)] |
| e0918b88 Andy McCall |
53 |
enum Cmd { |
| 54 |
|
| 55 |
Check { |
| 56 |
|
| 57 |
file: Option<PathBuf>, |
| 58 |
}, |
| 59 |
|
| 60 |
Hash { file: PathBuf }, |
| 61 |
|
| 62 |
Rootfs { |
| 63 |
#[command(subcommand)] |
| 64 |
cmd: RootfsCmd, |
| 65 |
}, |
| 66 |
|
| 67 |
Run { |
| 68 |
|
| 69 |
jobs: Vec<String>, |
| 70 |
|
| 71 |
#[arg(long, default_value = ".")] |
| 72 |
dir: PathBuf, |
| 73 |
|
| 74 |
#[arg(long, default_value_t = 60)] |
| 75 |
timeout: u64, |
| c58efc6a Andy McCall ↶ |
76 |
|
| 77 |
|
| 78 |
#[arg(long = "var", value_name = "NAME=VALUE")] |
| 79 |
vars: Vec<String>, |
| f98a8f78 Andy McCall ↶ |
80 |
}, |
| 81 |
|
| 82 |
|
| 83 |
Runner { |
| 84 |
#[command(subcommand)] |
| 85 |
cmd: Option<RunnerCmd>, |
| e0918b88 Andy McCall |
86 |
}, |
| 9e8f4a56 Andy McCall ↶ |
87 |
|
| 88 |
|
| 89 |
|
| 90 |
Wait { |
| 91 |
|
| 92 |
url: String, |
| 93 |
|
| 94 |
state: String, |
| 95 |
|
| 96 |
#[arg(long, default_value_t = 60)] |
| 97 |
timeout: u64, |
| 98 |
}, |
| e0918b88 Andy McCall |
99 |
} |
| 100 |
|
| 101 |
#[derive(Subcommand)] |
| 102 |
enum RootfsCmd { |
| 103 |
|
| 104 |
Import { |
| 105 |
tarball: PathBuf, |
| 106 |
|
| 107 |
#[arg(long)] |
| 108 |
sha256: Option<String>, |
| a72abeee Andy McCall ↶ |
109 |
|
| 110 |
|
| 111 |
|
| 112 |
#[arg(long = "env", value_name = "NAME=VALUE")] |
| 113 |
env: Vec<String>, |
| e0918b88 Andy McCall |
114 |
}, |
| 115 |
|
| 116 |
List, |
| 117 |
} |
| 118 |
|
| 119 |
fn main() { |
| 120 |
let cli = Cli::parse(); |
| 121 |
if let Err(e) = run(cli) { |
| 122 |
eprintln!("flow: {e:#}"); |
| 123 |
std::process::exit(1); |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
fn run(cli: Cli) -> Result<()> { |
| 128 |
match cli.cmd { |
| 129 |
Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))), |
| 130 |
Cmd::Hash { file } => { |
| 131 |
println!("{}", home::hash_file(&file)?); |
| 132 |
Ok(()) |
| 133 |
} |
| 134 |
Cmd::Rootfs { cmd } => { |
| 135 |
let home = Home::locate(cli.home.as_deref())?; |
| 136 |
match cmd { |
| a72abeee Andy McCall ↶ |
137 |
RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env), |
| e0918b88 Andy McCall |
138 |
RootfsCmd::List => { |
| 139 |
for e in std::fs::read_dir(home.root.join("cas"))?.flatten() { |
| 140 |
let size = e.metadata().map(|m| m.len()).unwrap_or(0); |
| 141 |
if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") { |
| 142 |
println!("cas://blob/{h} {} MiB", size >> 20); |
| 143 |
} |
| 144 |
} |
| 145 |
Ok(()) |
| 146 |
} |
| 147 |
} |
| 148 |
} |
| c58efc6a Andy McCall ↶ |
149 |
Cmd::Run { jobs, dir, timeout, vars } => { |
| e0918b88 Andy McCall |
150 |
let home = Home::locate(cli.home.as_deref())?; |
| c58efc6a Andy McCall ↶ |
151 |
let vars = vars |
| 152 |
.iter() |
| 153 |
.map(|e| { |
| 154 |
e.split_once('=') |
| 155 |
.map(|(k, v)| (k.to_string(), v.to_string())) |
| 156 |
.ok_or_else(|| anyhow::anyhow!("--var {e:?}: expected NAME=VALUE")) |
| 157 |
}) |
| 158 |
.collect::<Result<Vec<_>>>()?; |
| 159 |
run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars) |
| f98a8f78 Andy McCall ↶ |
160 |
} |
| 161 |
Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => { |
| 162 |
let home = Home::locate(cli.home.as_deref())?; |
| 163 |
if std::env::var_os("OXY_HOME").is_none() { |
| 164 |
std::env::set_var("OXY_HOME", home.root.join("oxy")); |
| 165 |
} |
| 166 |
let name = name.unwrap_or_else(|| { |
| 167 |
std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into()) |
| 168 |
}); |
| 169 |
let token = match token { |
| 170 |
Some(t) => t, |
| 171 |
None => { |
| 172 |
eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:"); |
| 173 |
let mut line = String::new(); |
| 174 |
std::io::stdin().read_line(&mut line)?; |
| 175 |
line.trim().to_string() |
| 176 |
} |
| 177 |
}; |
| 178 |
let got = runner::register(&home, &hub, &token, &name, ca, label)?; |
| 179 |
println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id); |
| 180 |
Ok(()) |
| e0918b88 Andy McCall |
181 |
} |
| f98a8f78 Andy McCall ↶ |
182 |
Cmd::Runner { cmd: None } => { |
| e0918b88 Andy McCall |
183 |
let home = Home::locate(cli.home.as_deref())?; |
| 184 |
|
| 185 |
if std::env::var_os("OXY_HOME").is_none() { |
| 186 |
std::env::set_var("OXY_HOME", home.root.join("oxy")); |
| 187 |
} |
| 188 |
runner::serve(&home) |
| 9e8f4a56 Andy McCall ↶ |
189 |
} |
| 190 |
Cmd::Wait { url, state, timeout } => { |
| 191 |
let token = std::env::var("OXY_TOKEN").ok(); |
| 192 |
let ca = std::env::var_os("OXY_CA").map(PathBuf::from); |
| 193 |
let code = |
| 194 |
wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?; |
| 195 |
std::process::exit(code); |
| e0918b88 Andy McCall |
196 |
} |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
fn load(file: &Path) -> Result<Pipeline> { |
| 201 |
let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?; |
| 202 |
Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display())) |
| 203 |
} |
| 204 |
|
| 205 |
fn check(file: &Path) -> Result<()> { |
| 206 |
let p = load(file)?; |
| 207 |
let depths = p.depths(); |
| 208 |
for j in p.order() { |
| 209 |
let sb = &p.sandboxes[&j.sandbox]; |
| 210 |
let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) }; |
| 211 |
println!("{}{} {} [{}]{after}", " ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str()); |
| 212 |
} |
| 213 |
println!("pipeline {}", hex::encode(p.hash())); |
| 214 |
Ok(()) |
| 215 |
} |
| 216 |
|
| a72abeee Andy McCall ↶ |
217 |
|
| 218 |
|
| 219 |
fn image_env_file(env: &[String]) -> Result<String> { |
| 220 |
let mut out = String::new(); |
| 221 |
for e in env { |
| 222 |
let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") }; |
| 223 |
let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'); |
| 224 |
if !ok || v.contains('\n') || v.contains('\0') { |
| 225 |
bail!("--env {e:?}: a name is letters, digits and _, and a value is one line"); |
| 226 |
} |
| 227 |
out.push_str(&format!("{k}={v}\n")); |
| 228 |
} |
| 229 |
Ok(out) |
| 230 |
} |
| 231 |
|
| 232 |
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> { |
| 233 |
let env_file = image_env_file(env)?; |
| e0918b88 Andy McCall |
234 |
if let Some(want) = sha256 { |
| 235 |
let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?; |
| 236 |
let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string(); |
| 237 |
if got != want.to_lowercase() { |
| 238 |
bail!("{} has SHA-256 {got}, expected {want}", tarball.display()); |
| 239 |
} |
| 240 |
} |
| 241 |
let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id())); |
| 242 |
let _ = std::fs::remove_dir_all(&tmp); |
| 243 |
let tree = tmp.join("tree"); |
| 244 |
std::fs::create_dir_all(&tree)?; |
| 245 |
let result = (|| -> Result<String> { |
| 246 |
let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?; |
| 247 |
if !status.success() { |
| 248 |
bail!("tar could not unpack {}", tarball.display()); |
| 249 |
} |
| 250 |
|
| 251 |
for d in ["src", "tmp", "proc", "dev", "run"] { |
| 252 |
std::fs::create_dir_all(tree.join(d))?; |
| a72abeee Andy McCall ↶ |
253 |
} |
| 254 |
if !env_file.is_empty() { |
| 255 |
std::fs::create_dir_all(tree.join("etc/flow"))?; |
| 256 |
std::fs::write(tree.join("etc/flow/env"), &env_file)?; |
| e0918b88 Andy McCall |
257 |
} |
| 258 |
let used: u64 = ignore::WalkBuilder::new(&tree) |
| 259 |
.hidden(false) |
| 260 |
.ignore(false) |
| 261 |
.git_ignore(false) |
| 262 |
.build() |
| 263 |
.flatten() |
| 264 |
.filter_map(|e| e.metadata().ok()) |
| 265 |
.map(|m| m.len().max(4096)) |
| 266 |
.sum(); |
| 267 |
let mib = used * 13 / 10 / (1 << 20) + 64; |
| 268 |
let img = tmp.join("rootfs.ext4"); |
| 269 |
let status = std::process::Command::new("mkfs.ext4") |
| 270 |
.args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"]) |
| 271 |
.arg(&tree) |
| 272 |
.arg(&img) |
| 273 |
.arg(format!("{mib}M")) |
| 274 |
.status() |
| 275 |
.context("run mkfs.ext4")?; |
| 276 |
if !status.success() { |
| 277 |
bail!("mkfs.ext4 failed"); |
| 278 |
} |
| 279 |
let hash = home::hash_file(&img)?; |
| 280 |
std::fs::rename(&img, home.rootfs(&hash))?; |
| 281 |
Ok(hash) |
| 282 |
})(); |
| 283 |
let _ = std::fs::remove_dir_all(&tmp); |
| 284 |
let hash = result?; |
| 285 |
println!("rootfs \"cas://blob/{hash}\""); |
| 286 |
Ok(()) |
| 287 |
} |
| 288 |
|
| c58efc6a Andy McCall ↶ |
289 |
fn run_local(home: &Home, dir: &Path, only: &[String], timeout: Duration, vars: &[(String, String)]) -> Result<()> { |
| e0918b88 Andy McCall |
290 |
let p = load(&dir.join(PIPELINE_PATH))?; |
| 291 |
|
| 292 |
let mut wanted: BTreeSet<String> = only.iter().cloned().collect(); |
| 293 |
for name in only { |
| 294 |
if !p.jobs.contains_key(name) { |
| 295 |
bail!("no job {name:?} in the pipeline"); |
| 296 |
} |
| 297 |
} |
| 298 |
if !only.is_empty() { |
| 299 |
loop { |
| 300 |
let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect(); |
| 301 |
if more.is_empty() { |
| 302 |
break; |
| 303 |
} |
| 304 |
wanted.extend(more); |
| 305 |
} |
| 306 |
} |
| 307 |
let scratch = home.root.join("work").join(format!("local-{}", std::process::id())); |
| 308 |
let _ = std::fs::remove_dir_all(&scratch); |
| 309 |
std::fs::create_dir_all(scratch.join("tree"))?; |
| 310 |
workspace::copy_tree(dir, &scratch.join("tree"))?; |
| 311 |
let mut failed: BTreeSet<String> = BTreeSet::new(); |
| 312 |
let mut worst = 0; |
| 313 |
for job in p.order() { |
| 314 |
if !only.is_empty() && !wanted.contains(&job.name) { |
| 315 |
continue; |
| 316 |
} |
| 317 |
if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) { |
| 318 |
println!("── {} skipped: {d} failed", job.name); |
| 319 |
failed.insert(job.name.clone()); |
| 320 |
continue; |
| 321 |
} |
| 322 |
let sb = &p.sandboxes[&job.sandbox]; |
| 323 |
if sb.runtime != Runtime::Microvm { |
| 324 |
bail!("job {}: runtime {} is not available in this build yet", job.name, sb.runtime.as_str()); |
| 325 |
} |
| 326 |
println!("── {} ({})", job.name, job.exec.join(" ")); |
| 327 |
let js = scratch.join(&job.name); |
| 328 |
std::fs::create_dir_all(&js)?; |
| 329 |
|
| 330 |
workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?; |
| c58efc6a Andy McCall ↶ |
331 |
let job = &job |
| 332 |
.in_sandbox(sb) |
| 333 |
.with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())]) |
| 334 |
.with_flow_env(vars); |
| e0918b88 Andy McCall |
335 |
let out = microvm::run(home, sb, job, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?; |
| 336 |
let _ = std::fs::remove_dir_all(&js); |
| 337 |
match out.exit_code { |
| 338 |
Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms), |
| 339 |
other => { |
| 340 |
println!( |
| 341 |
"── {} failed ({}) in {} ms", |
| 342 |
job.name, |
| 343 |
other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()), |
| 344 |
out.duration_ms |
| 345 |
); |
| 346 |
failed.insert(job.name.clone()); |
| 347 |
worst = 1; |
| 348 |
} |
| 349 |
} |
| 350 |
} |
| 351 |
let _ = std::fs::remove_dir_all(&scratch); |
| 352 |
if worst != 0 { |
| 353 |
std::process::exit(worst); |
| 354 |
} |
| 355 |
Ok(()) |
| 356 |
} |
| 357 |
|
| 358 |
fn print_record(r: &Record) { |
| 359 |
match r.stream.as_str() { |
| 360 |
"out" => println!(" {}", r.text), |
| 361 |
"err" => eprintln!(" {}", r.text), |
| 362 |
s => eprintln!(" [{s}] {}", r.text), |
| a72abeee Andy McCall ↶ |
363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
#[cfg(test)] |
| 367 |
mod tests { |
| 368 |
use super::image_env_file; |
| 369 |
|
| 370 |
#[test] |
| 371 |
fn image_environments_are_checked_lines() { |
| 372 |
let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap(); |
| 373 |
assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n"); |
| 374 |
assert!(image_env_file(&["NOEQUALS".into()]).is_err()); |
| 375 |
assert!(image_env_file(&["1X=y".into()]).is_err()); |
| 376 |
assert!(image_env_file(&["X=two\nlines".into()]).is_err()); |
| 377 |
assert_eq!(image_env_file(&[]).unwrap(), ""); |
| e0918b88 Andy McCall |
378 |
} |
| 379 |
} |