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