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