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