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