OXYGENHUB
# 6a2d31568cf2 oxygenflow / crates / flow / src / main.rs
22.6 KiB · Rust · last changed A runner's own metrics (refs #35) 15 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
d60aac6c Andy McCall ↶ 4
mod cache;
e0918b88 Andy McCall 5
mod cpio;
ea81796b Andy McCall ↶ 6
mod egress;
62829d15 Andy McCall ↶ 7
mod facts;
ea56c56e Andy McCall ↶ 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;
e0918b88 Andy McCall 12
mod home;
4cf0c99a Andy McCall ↶ 13
mod images;
4be5e4cd Andy McCall ↶ 14
mod metrics;
e0918b88 Andy McCall 15
mod microvm;
a67b97e9 Andy McCall ↶ 16
mod outputs;
e0918b88 Andy McCall 17
mod runner;
b14aeaae Andy McCall ↶ 18
mod swarm;
ea56c56e Andy McCall ↶ 19
mod syscall;
9e8f4a56 Andy McCall ↶ 20
mod wait;
e0918b88 Andy McCall 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)]
2d025bbf Andy McCall ↶ 33
#[command(name = "flow", version = env!("OXY_VERSION_LONG"), about = "OxygenFlow: hermetic pipelines for Oxygen repositories")]
e0918b88 Andy McCall 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)]
f98a8f78 Andy McCall ↶ 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
    },
62829d15 Andy McCall ↶ 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,
f98a8f78 Andy McCall ↶ 64
}
65
66
#[derive(Subcommand)]
e0918b88 Andy McCall 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,
c58efc6a Andy McCall ↶ 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>,
e2c12561 Andy McCall ↶ 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>,
f98a8f78 Andy McCall ↶ 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>,
e0918b88 Andy McCall 104
    },
9e8f4a56 Andy McCall ↶ 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
    },
ea56c56e Andy McCall ↶ 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,
e0918b88 Andy McCall 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>,
a72abeee Andy McCall ↶ 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>,
e0918b88 Andy McCall 141
    },
142
    /// List the images this home holds
143
    List,
4cf0c99a Andy McCall ↶ 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. Uses
146
    /// $OXY_TOKEN (a token that may write repositories) and $OXY_CA
147
    Push {
148
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
149
        hash: String,
150
        /// The hub (default: 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. Uses $OXY_TOKEN and $OXY_CA
156
    Pull {
157
        hash: String,
158
        #[arg(long)]
159
        hub: Option<String>,
160
    },
e0918b88 Andy McCall 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 {
ea56c56e Andy McCall ↶ 173
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
174
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
e0918b88 Andy McCall 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 {
a72abeee Andy McCall ↶ 183
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
4cf0c99a Andy McCall ↶ 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
                }
e0918b88 Andy McCall 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
        }
e2c12561 Andy McCall ↶ 224
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
e0918b88 Andy McCall 225
            let home = Home::locate(cli.home.as_deref())?;
e2c12561 Andy McCall ↶ 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)
f98a8f78 Andy McCall ↶ 237
        }
62829d15 Andy McCall ↶ 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
        }
f98a8f78 Andy McCall ↶ 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(())
e0918b88 Andy McCall 270
        }
f98a8f78 Andy McCall ↶ 271
        Cmd::Runner { cmd: None } => {
e0918b88 Andy McCall 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)
9e8f4a56 Andy McCall ↶ 278
        }
ea56c56e Andy McCall ↶ 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
        }
9e8f4a56 Andy McCall ↶ 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);
e0918b88 Andy McCall 300
        }
301
    }
4cf0c99a Andy McCall ↶ 302
}
303
304
/// The hub image commands talk to: `--hub`, else the runner's; with
305
/// $OXY_TOKEN, else the runner's own token.
306
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
307
    let runner = home.config.runner.clone();
308
    let hub = hub.or_else(|| runner.as_ref().map(|r| r.hub.clone())).context("name the hub with --hub https://HUB")?;
309
    let token = std::env::var("OXY_TOKEN")
310
        .ok()
311
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
312
        .context("set OXY_TOKEN to a token of yours on the hub")?;
313
    let ca = std::env::var_os("OXY_CA").map(PathBuf::from).or_else(|| runner.as_ref().and_then(|r| r.ca.clone()));
314
    images::Client::new(&hub, &token, ca.as_deref())
e0918b88 Andy McCall 315
}
316
317
fn load(file: &Path) -> Result<Pipeline> {
318
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
319
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display()))
320
}
321
322
fn check(file: &Path) -> Result<()> {
323
    let p = load(file)?;
324
    let depths = p.depths();
325
    for j in p.order() {
326
        let sb = &p.sandboxes[&j.sandbox];
327
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
328
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
329
    }
330
    println!("pipeline {}", hex::encode(p.hash()));
331
    Ok(())
332
}
333
a72abeee Andy McCall ↶ 334
/// The image environment file flow-init reads (`/etc/flow/env`): one
335
/// `NAME=value` per line, names checked as a pipeline's are.
336
fn image_env_file(env: &[String]) -> Result<String> {
337
    let mut out = String::new();
338
    for e in env {
339
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
340
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
341
        if !ok || v.contains('\n') || v.contains('\0') {
342
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
343
        }
344
        out.push_str(&format!("{k}={v}\n"));
345
    }
346
    Ok(out)
347
}
348
1abadd4a Andy McCall ↶ 349
/// The architecture an ELF file was built for, by its header.
350
fn elf_arch(path: &Path) -> Option<&'static str> {
351
    let bytes = std::fs::read(path).ok()?;
352
    if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" {
353
        return None;
354
    }
355
    let little = bytes[5] == 1;
356
    let machine = if little { u16::from_le_bytes([bytes[18], bytes[19]]) } else { u16::from_be_bytes([bytes[18], bytes[19]]) };
357
    Some(match machine {
358
        0x3E => "x86_64",
359
        0xB7 => "aarch64",
360
        0xF3 => "riscv64",
361
        0x03 => "x86",
362
        0x28 => "arm",
363
        0x15 => "powerpc64",
364
        0x16 => "s390x",
365
        _ => return None,
366
    })
367
}
368
369
/// The architecture of an unpacked rootfs: its shell's, or the first
370
/// program's found under bin.
371
fn tree_arch(tree: &Path) -> Option<&'static str> {
372
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
373
        let p = tree.join(rel);
374
        let p = std::fs::canonicalize(&p).unwrap_or(p);
375
        if let Some(a) = elf_arch(&p) {
376
            return Some(a);
377
        }
378
    }
379
    None
380
}
381
a72abeee Andy McCall ↶ 382
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
383
    let env_file = image_env_file(env)?;
e0918b88 Andy McCall 384
    if let Some(want) = sha256 {
385
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
386
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
387
        if got != want.to_lowercase() {
388
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
389
        }
390
    }
391
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
392
    let _ = std::fs::remove_dir_all(&tmp);
393
    let tree = tmp.join("tree");
394
    std::fs::create_dir_all(&tree)?;
395
    let result = (|| -> Result<String> {
396
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
397
        if !status.success() {
398
            bail!("tar could not unpack {}", tarball.display());
1abadd4a Andy McCall ↶ 399
        }
400
        // The image's architecture must be this machine's: there is no
401
        // emulation tier (spec §11.2).
402
        let arch = tree_arch(&tree).unwrap_or("unknown");
403
        if arch != "unknown" && arch != std::env::consts::ARCH {
404
            bail!(
405
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
406
                tarball.display(),
407
                std::env::consts::ARCH
408
            );
e0918b88 Andy McCall 409
        }
410
        // Mount points flow-init needs (docs/m0.md §2).
411
        for d in ["src", "tmp", "proc", "dev", "run"] {
412
            std::fs::create_dir_all(tree.join(d))?;
a72abeee Andy McCall ↶ 413
        }
414
        if !env_file.is_empty() {
415
            std::fs::create_dir_all(tree.join("etc/flow"))?;
416
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
e0918b88 Andy McCall 417
        }
418
        let used: u64 = ignore::WalkBuilder::new(&tree)
419
            .hidden(false)
420
            .ignore(false)
421
            .git_ignore(false)
422
            .build()
423
            .flatten()
424
            .filter_map(|e| e.metadata().ok())
425
            .map(|m| m.len().max(4096))
426
            .sum();
427
        let mib = used * 13 / 10 / (1 << 20) + 64;
428
        let img = tmp.join("rootfs.ext4");
429
        let status = std::process::Command::new("mkfs.ext4")
430
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
431
            .arg(&tree)
432
            .arg(&img)
433
            .arg(format!("{mib}M"))
434
            .status()
435
            .context("run mkfs.ext4")?;
436
        if !status.success() {
437
            bail!("mkfs.ext4 failed");
438
        }
439
        let hash = home::hash_file(&img)?;
440
        std::fs::rename(&img, home.rootfs(&hash))?;
1abadd4a Andy McCall ↶ 441
        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) });
442
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
e0918b88 Andy McCall 443
        Ok(hash)
444
    })();
445
    let _ = std::fs::remove_dir_all(&tmp);
446
    let hash = result?;
447
    println!("rootfs \"cas://blob/{hash}\"");
448
    Ok(())
449
}
450
e2c12561 Andy McCall ↶ 451
fn run_local(
452
    home: &Home,
453
    dir: &Path,
454
    only: &[String],
455
    timeout: Duration,
456
    vars: &[(String, String)],
457
    secrets: &[(String, String)],
458
) -> Result<()> {
e0918b88 Andy McCall 459
    let p = load(&dir.join(PIPELINE_PATH))?;
460
    // The named jobs and everything they depend on.
461
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
462
    for name in only {
463
        if !p.jobs.contains_key(name) {
464
            bail!("no job {name:?} in the pipeline");
465
        }
466
    }
467
    if !only.is_empty() {
468
        loop {
469
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
470
            if more.is_empty() {
471
                break;
472
            }
473
            wanted.extend(more);
474
        }
475
    }
476
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
477
    let _ = std::fs::remove_dir_all(&scratch);
478
    std::fs::create_dir_all(scratch.join("tree"))?;
479
    workspace::copy_tree(dir, &scratch.join("tree"))?;
480
    let mut failed: BTreeSet<String> = BTreeSet::new();
481
    let mut worst = 0;
482
    for job in p.order() {
483
        if !only.is_empty() && !wanted.contains(&job.name) {
484
            continue;
485
        }
486
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
487
            println!("── {} skipped: {d} failed", job.name);
488
            failed.insert(job.name.clone());
489
            continue;
490
        }
491
        let sb = &p.sandboxes[&job.sandbox];
ea56c56e Andy McCall ↶ 492
        if sb.runtime == Runtime::Wasm {
e0918b88 Andy McCall 493
            bail!("job {}: runtime {} is not available in this build yet", job.name, sb.runtime.as_str());
494
        }
495
        println!("── {} ({})", job.name, job.exec.join(" "));
496
        let js = scratch.join(&job.name);
497
        std::fs::create_dir_all(&js)?;
c58efc6a Andy McCall ↶ 498
        let job = &job
499
            .in_sandbox(sb)
500
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
501
            .with_flow_env(vars);
720eb819 Andy McCall ↶ 502
        // Identities come from a hub: a local run has none.
503
        for i in &job.identities {
504
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
505
        }
e2c12561 Andy McCall ↶ 506
        // Each secret the job declares must be given, as the hub would.
507
        let inputs = job
508
            .secrets
509
            .iter()
510
            .map(|s| {
511
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
512
                value
513
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
514
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
515
            })
516
            .collect::<Result<Vec<_>>>()?;
ea56c56e Andy McCall ↶ 517
        // Each job starts from the same files: jobs do not share writes.
518
        let out = if sb.runtime == Runtime::Syscall {
519
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
520
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
521
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
522
        } else {
523
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
524
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
525
        };
526
        let _ = workspace::remove_tree(&js);
e0918b88 Andy McCall 527
        match out.exit_code {
528
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
529
            other => {
530
                println!(
531
                    "── {} failed ({}) in {} ms",
532
                    job.name,
533
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
534
                    out.duration_ms
535
                );
536
                failed.insert(job.name.clone());
537
                worst = 1;
538
            }
539
        }
540
    }
ea56c56e Andy McCall ↶ 541
    let _ = workspace::remove_tree(&scratch);
e0918b88 Andy McCall 542
    if worst != 0 {
543
        std::process::exit(worst);
544
    }
545
    Ok(())
546
}
547
548
fn print_record(r: &Record) {
549
    match r.stream.as_str() {
550
        "out" => println!("   {}", r.text),
551
        "err" => eprintln!("   {}", r.text),
552
        s => eprintln!("   [{s}] {}", r.text),
a72abeee Andy McCall ↶ 553
    }
554
}
555
556
#[cfg(test)]
557
mod tests {
558
    use super::image_env_file;
559
560
    #[test]
561
    fn image_environments_are_checked_lines() {
562
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
563
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
564
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
565
        assert!(image_env_file(&["1X=y".into()]).is_err());
566
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
567
        assert_eq!(image_env_file(&[]).unwrap(), "");
e0918b88 Andy McCall 568
    }
569
}