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