OXYGENHUB

Coverage / crates/flow/src/main.rs 32.4%

126 of 389 lines run, 14 of 106 functions · run #187 on main · run missed

1
//! `flow`: check pipelines, run them locally, and run jobs for OxygenHub
2
//! (docs/spec.md, docs/m0.md).
3
4
use flow::{facts, home, images, microvm, runner, syscall, wait, wasm, workspace};
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)]
16
#[command(name = "flow", version = env!("OXY_VERSION_LONG"), about = "OxygenFlow: hermetic pipelines for Oxygen repositories")]
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)]
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
    },
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,
47
    /// Install a new flow build in place of this one (docs/jetstream.md
48
    /// §8.2): check it, keep this one as flow.prev, and have the running
49
    /// runner leave with notice so its unit starts the new build. A build
50
    /// that does not reach the hub goes back to flow.prev by itself
51
    Update {
52
        /// The new flow binary
53
        #[arg(long)]
54
        from: PathBuf,
55
        /// Seconds the running runner has to finish what it holds; jobs
56
        /// that will not finish in time are handed back with their checkpoints
57
        #[arg(long, default_value_t = 600)]
58
        notice: u64,
59
        /// Check the build and say what would happen, changing nothing
60
        #[arg(long)]
61
        dry_run: bool,
62
        /// Install a build older than this one
63
        #[arg(long)]
64
        allow_older: bool,
65
        /// The installed binary to replace (default: this one)
66
        #[arg(long)]
67
        exe: Option<PathBuf>,
68
    },
69
}
70
71
#[derive(Subcommand)]
72
enum Cmd {
73
    /// Validate a pipeline and print its jobs and hash
74
    Check {
75
        /// The pipeline file (default: .flow/pipeline.kdl)
76
        file: Option<PathBuf>,
77
    },
78
    /// Print a file's BLAKE3, for pinning in flow.toml
79
    Hash { file: PathBuf },
80
    /// Rootfs images for sandboxes
81
    Rootfs {
82
        #[command(subcommand)]
83
        cmd: RootfsCmd,
84
    },
85
    /// Run the pipeline on this directory's files, locally
86
    Run {
87
        /// Only these jobs (and what they depend on)
88
        jobs: Vec<String>,
89
        /// The directory to build (default: the current one)
90
        #[arg(long, default_value = ".")]
91
        dir: PathBuf,
92
        /// Minutes before a job is stopped
93
        #[arg(long, default_value_t = 60)]
94
        timeout: u64,
95
        /// A variable for every job, as the hub's settings would give it;
96
        /// the pipeline's own `env` wins
97
        #[arg(long = "var", value_name = "NAME=VALUE")]
98
        vars: Vec<String>,
99
        /// A secret a job's `secret` block names, as the hub would supply
100
        /// it; mounted as a file, never in the environment
101
        #[arg(long = "secret", value_name = "NAME=VALUE")]
102
        secrets: Vec<String>,
103
    },
104
    /// Claim and run jobs for the hub in flow.toml's [runner] (or the
105
    /// runner.toml `flow runner register` wrote)
106
    Runner {
107
        #[command(subcommand)]
108
        cmd: Option<RunnerCmd>,
109
    },
110
    /// Follow the checks of a pushed state on OxygenHub until they finish:
111
    /// exit 0 when all passed, 1 when one failed, 2 at the time limit.
112
    /// Uses $OXY_TOKEN and $OXY_CA as oxy does.
113
    Wait {
114
        /// The repository's URL on the hub (https://hub/owner/name)
115
        url: String,
116
        /// The state hash the push moved the bookmark to (`oxy push --json` prints it)
117
        state: String,
118
        /// Minutes to wait at most
119
        #[arg(long, default_value_t = 60)]
120
        timeout: u64,
121
    },
122
    /// Show which isolation tiers this machine can run jobs in, and why
123
    /// the others cannot
124
    Tiers,
125
    /// The syscall tier's sandbox helper, started by the runner for each job
126
    #[command(name = "__sandbox", hide = true)]
127
    Sandbox { spec: PathBuf },
128
    /// Check that this machine can run the syscall tier
129
    #[command(name = "__sandbox-probe", hide = true)]
130
    SandboxProbe,
131
    /// The WASM tier's helper, started by the runner for each job
132
    #[command(name = "__wasm", hide = true)]
133
    Wasm { spec: PathBuf },
134
}
135
136
#[derive(Subcommand)]
137
enum RootfsCmd {
138
    /// Make an ext4 rootfs image from a root file system tarball and store it by hash
139
    Import {
140
        tarball: PathBuf,
141
        /// Refuse the tarball unless its SHA-256 matches (as its publisher states it)
142
        #[arg(long)]
143
        sha256: Option<String>,
144
        /// The image's own environment, NAME=value (repeatable): what a
145
        /// Dockerfile's ENV sets and `docker export` loses. Jobs start from
146
        /// it; their sandbox's and their own `env` override it
147
        #[arg(long = "env", value_name = "NAME=VALUE")]
148
        env: Vec<String>,
149
    },
150
    /// List the images this home holds
151
    List,
152
    /// Send an image to a hub, so its runners fetch it instead of having it
153
    /// copied to them: only the chunks the hub lacks travel. Signs in as
154
    /// `oh` is signed in to that hub, or with $OXY_TOKEN and $OXY_CA
155
    Push {
156
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
157
        hash: String,
158
        /// The hub (default: $OH_HUB, else the runner's, from runner.toml or flow.toml)
159
        #[arg(long)]
160
        hub: Option<String>,
161
    },
162
    /// Fetch an image a hub holds into this home, as a runner does for a
163
    /// job whose image it lacks. Signs in as `oh` is, or with $OXY_TOKEN
164
    Pull {
165
        hash: String,
166
        #[arg(long)]
167
        hub: Option<String>,
168
    },
169
}
170
1715×
fn main() {
1725×
    let cli = Cli::parse();
1735×
    if let Err(e) = run(cli) {
1742×
        eprintln!("flow: {e:#}");
1752×
        std::process::exit(1);
1763×
    }
1773×
}
178
1795×
fn run(cli: Cli) -> Result<()> {
1800×
    match cli.cmd {
1810×
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
1820×
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
1830×
        Cmd::Wasm { spec } => std::process::exit(wasm::wasm_main(&spec)),
1840×
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
1850×
        Cmd::Hash { file } => {
1860×
            println!("{}", home::hash_file(&file)?);
1870×
            Ok(())
188
        }
1890×
        Cmd::Rootfs { cmd } => {
1900×
            let home = Home::locate(cli.home.as_deref())?;
1910×
            match cmd {
1920×
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
1930×
                RootfsCmd::Push { hash, hub } => {
1940×
                    let client = image_client(&home, hub)?;
1950×
                    eprintln!("Sending image {} …", &hash[..12.min(hash.len())]);
1960×
                    let m = client.push(&home, &hash)?;
1970×
                    println!(
198
                        "Sent image {}: {} chunks the hub lacked, {} in {:.1} s",
1990×
                        &hash[..12],
200
                        m.chunks,
2010×
                        images::human(m.bytes),
2020×
                        m.elapsed.as_secs_f64()
203
                    );
2040×
                    Ok(())
205
                }
2060×
                RootfsCmd::Pull { hash, hub } => {
2070×
                    let client = image_client(&home, hub)?;
2080×
                    match client.fetch(&home, &hash)? {
2090×
                        Some(m) => {
2100×
                            println!(
211
                                "Fetched image {}: {} chunks, {} in {:.1} s",
2120×
                                &hash[..12],
213
                                m.chunks,
2140×
                                images::human(m.bytes),
2150×
                                m.elapsed.as_secs_f64()
216
                            );
2170×
                            Ok(())
218
                        }
2190×
                        None => anyhow::bail!("the hub does not hold image {}; send it with flow rootfs push", &hash[..12.min(hash.len())]),
220
                    }
221
                }
222
                RootfsCmd::List => {
2230×
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
2240×
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
2250×
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
2260×
                            println!("cas://blob/{h}  {} MiB", size >> 20);
2270×
                        }
228
                    }
2290×
                    Ok(())
230
                }
231
            }
232
        }
2332×
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
2342×
            let home = Home::locate(cli.home.as_deref())?;
2354×
            let pairs = |what: &str, list: &[String]| {
2364×
                list.iter()
2374×
                    .map(|e| {
2380×
                        e.split_once('=')
2390×
                            .map(|(k, v)| (k.to_string(), v.to_string()))
2400×
                            .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE"))
2410×
                    })
2424×
                    .collect::<Result<Vec<_>>>()
2434×
            };
2442×
            let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?);
2452×
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets)
246
        }
247
        Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => {
2480×
            let home = Home::locate(cli.home.as_deref())?;
2490×
            let (speed, ms) = facts::bench();
2500×
            let f = facts::now(&home, Some(speed));
2510×
            println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
2520×
            println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display());
2530×
            println!("load {:.2}", f.load_x100.unwrap_or(0) as f64 / 100.0);
2540×
            if let Some(k) = f.kernel {
2550×
                println!("kernel {k}");
2560×
            }
2570×
            Ok(())
258
        }
2590×
        Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => {
2600×
            let home = Home::locate(cli.home.as_deref())?;
2610×
            if std::env::var_os("OXY_HOME").is_none() {
2620×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
2630×
            }
2640×
            let name = name.unwrap_or_else(|| {
2650×
                std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into())
2660×
            });
2670×
            let token = match token {
2680×
                Some(t) => t,
269
                None => {
2700×
                    eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:");
2710×
                    let mut line = String::new();
2720×
                    std::io::stdin().read_line(&mut line)?;
2730×
                    line.trim().to_string()
274
                }
275
            };
2760×
            let got = runner::register(&home, &hub, &token, &name, ca, label)?;
2770×
            println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id);
2780×
            Ok(())
279
        }
2800×
        Cmd::Runner { cmd: Some(RunnerCmd::Update { from, notice, dry_run, allow_older, exe }) } => {
2810×
            let home = Home::locate(cli.home.as_deref())?;
2820×
            let exe = match exe {
2830×
                Some(e) => e,
2840×
                None => std::env::current_exe().context("finding this flow binary")?,
285
            };
2860×
            let done = flow::update::install(&home, &exe, &from, Duration::from_secs(notice), dry_run, allow_older)?;
2870×
            if dry_run {
2880×
                println!(
289
                    "flow {} checks out: it would replace flow {} at {} (dry run: nothing changed)",
290
                    done.to,
291
                    done.from,
2920×
                    done.exe.display()
293
                );
2940×
                return Ok(());
2950×
            }
2960×
            println!("flow {} installed at {}; flow {} kept as {}", done.to, done.exe.display(), done.from, flow::update::PREV);
2970×
            match done.told {
2980×
                Some(pid) => println!("the runner (pid {pid}) leaves within {notice} s, then its unit starts flow {}", done.to),
2990×
                None => println!(
300
                    "no runner of this home was told (none runs, or one from before runner updates, which does not listen): \
301
                     restart its unit, e.g. `systemctl restart --no-block flow-runner`; it drains and starts flow {}",
302
                    done.to
303
                ),
304
            }
3050×
            Ok(())
306
        }
307
        Cmd::Runner { cmd: None } => {
3080×
            let home = Home::locate(cli.home.as_deref())?;
309
            // A new build on trial that keeps failing to start goes back to
310
            // the one before, which then runs in its place (#85).
3110×
            if let flow::update::Start::RolledBack(p) = flow::update::on_start(&home.root)? {
312
                #[cfg(unix)]
313
                {
314
                    use std::os::unix::process::CommandExt;
3150×
                    let err = std::process::Command::new(&p.exe).args(std::env::args_os().skip(1)).exec();
3160×
                    bail!("starting flow {} again after the rollback: {err}", p.from);
317
                }
318
                #[cfg(not(unix))]
319
                bail!("rolled back to flow {}; start the runner again", p.from);
3200×
            }
321
            // The runner's oxy state (identity, user config) stays in its home.
3220×
            if std::env::var_os("OXY_HOME").is_none() {
3230×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
3240×
            }
3250×
            runner::serve(&home)
326
        }
327
        Cmd::Tiers => {
3283×
            let home = Home::locate(cli.home.as_deref())?;
3293×
            match runner::tiers(&home) {
3303×
                Ok((have, missing)) => {
3313×
                    for t in have {
3323×
                        println!("{t}: available");
3333×
                    }
3346×
                    for why in missing {
3356×
                        println!("{}", why.replacen(": ", ": unavailable: ", 1));
3366×
                    }
337
                }
3380×
                Err(why) => println!("{why}"),
339
            }
3403×
            Ok(())
341
        }
3420×
        Cmd::Wait { url, state, timeout } => {
3430×
            let token = std::env::var("OXY_TOKEN").ok();
3440×
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
3450×
            let code =
3460×
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
3470×
            std::process::exit(code);
348
        }
349
    }
3505×
}
351
352
/// The hub image commands talk to: `--hub`, else $OH_HUB, else the
353
/// runner's. The token: $OXY_TOKEN, else the login `oh auth login` (or
354
/// `oxy auth login`) saved for that hub in Oxygen's credential store
355
/// (oxygenflow#44), else the runner's own.
3560×
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
3570×
    let runner = home.config.runner.clone();
3580×
    let hub = hub
3590×
        .or_else(|| std::env::var("OH_HUB").ok().filter(|h| !h.is_empty()))
3600×
        .or_else(|| runner.as_ref().map(|r| r.hub.clone()))
3610×
        .context("name the hub with --hub https://HUB (or set OH_HUB)")?;
3620×
    let (saved_token, saved_ca) = oxy_core::credentials::Credentials::user().lookup(&hub);
3630×
    let token = std::env::var("OXY_TOKEN")
3640×
        .ok()
3650×
        .filter(|t| !t.is_empty())
3660×
        .or(saved_token)
3670×
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
3680×
        .with_context(|| format!("no token for {hub}: sign in with `oh auth login --hub {hub}`, or set OXY_TOKEN"))?;
3690×
    let ca = std::env::var_os("OXY_CA").map(PathBuf::from).or(saved_ca).or_else(|| runner.as_ref().and_then(|r| r.ca.clone()));
3700×
    images::Client::new(&hub, &token, ca.as_deref())
3710×
}
372
3732×
fn load(file: &Path) -> Result<Pipeline> {
3742×
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
3752×
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{}", not_valid(file, &p.to_string())))
3762×
}
377
378
/// Why a pipeline did not parse. When it names something this flow does
379
/// not know (a node, an output, an event), the pipeline may simply be
380
/// newer than this flow (oxygenflow#43): say so, with this flow's version.
3812×
fn not_valid(file: &Path, problems: &str) -> String {
3822×
    if problems.contains("unknown ") {
3831×
        format!(
384
            "{} uses something this flow ({}) does not know:\n{problems}\n\
385
             If the pipeline was written for a newer OxygenFlow, update flow (build it from oxygenflow main); \
386
             otherwise fix the lines named.",
3871×
            file.display(),
388
            env!("OXY_VERSION_LONG")
389
        )
390
    } else {
3911×
        format!("{} is not valid:\n{problems}", file.display())
392
    }
3932×
}
394
3950×
fn check(file: &Path) -> Result<()> {
3960×
    let p = load(file)?;
3970×
    let depths = p.depths();
3980×
    for j in p.order() {
3990×
        let sb = &p.sandboxes[&j.sandbox];
4000×
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
4010×
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
402
    }
4030×
    println!("pipeline {}", hex::encode(p.hash()));
4040×
    Ok(())
4050×
}
406
407
/// The image environment file flow-init reads (`/etc/flow/env`): one
408
/// `NAME=value` per line, names checked as a pipeline's are.
4095×
fn image_env_file(env: &[String]) -> Result<String> {
4105×
    let mut out = String::new();
4116×
    for e in env {
4126×
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
41316×
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
4145×
        if !ok || v.contains('\n') || v.contains('\0') {
4152×
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
4163×
        }
4173×
        out.push_str(&format!("{k}={v}\n"));
418
    }
4192×
    Ok(out)
4205×
}
421
422
/// The architecture an ELF file was built for, by its header.
4230×
fn elf_arch(path: &Path) -> Option<&'static str> {
4240×
    let mut head = [0u8; 20];
4250×
    std::io::Read::read_exact(&mut std::fs::File::open(path).ok()?, &mut head).ok()?;
4260×
    jet::rootfs::elf_arch(&head)
4270×
}
428
429
/// The architecture of an unpacked rootfs: its shell's, or the first
430
/// program's found under bin.
4310×
fn tree_arch(tree: &Path) -> Option<&'static str> {
4320×
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
4330×
        let p = tree.join(rel);
4340×
        let p = std::fs::canonicalize(&p).unwrap_or(p);
4350×
        if let Some(a) = elf_arch(&p) {
4360×
            return Some(a);
4370×
        }
438
    }
4390×
    None
4400×
}
441
4420×
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
4430×
    let env_file = image_env_file(env)?;
4440×
    if let Some(want) = sha256 {
4450×
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
4460×
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
4470×
        if got != want.to_lowercase() {
4480×
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
4490×
        }
4500×
    }
4510×
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
4520×
    let _ = std::fs::remove_dir_all(&tmp);
4530×
    let tree = tmp.join("tree");
4540×
    std::fs::create_dir_all(&tree)?;
4550×
    let result = (|| -> Result<String> {
4560×
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
4570×
        if !status.success() {
4580×
            bail!("tar could not unpack {}", tarball.display());
4590×
        }
460
        // The image's architecture must be this machine's: there is no
461
        // emulation tier (spec §11.2).
4620×
        let arch = tree_arch(&tree).unwrap_or("unknown");
4630×
        if arch != "unknown" && arch != std::env::consts::ARCH {
4640×
            bail!(
465
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
4660×
                tarball.display(),
467
                std::env::consts::ARCH
468
            );
4690×
        }
470
        // Mount points flow-init needs (docs/m0.md §2).
4710×
        for d in ["src", "tmp", "proc", "dev", "run"] {
4720×
            std::fs::create_dir_all(tree.join(d))?;
473
        }
4740×
        if !env_file.is_empty() {
4750×
            std::fs::create_dir_all(tree.join("etc/flow"))?;
4760×
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
4770×
        }
4780×
        let used: u64 = ignore::WalkBuilder::new(&tree)
4790×
            .hidden(false)
4800×
            .ignore(false)
4810×
            .git_ignore(false)
4820×
            .build()
4830×
            .flatten()
4840×
            .filter_map(|e| e.metadata().ok())
4850×
            .map(|m| m.len().max(4096))
4860×
            .sum();
4870×
        let mib = used * 13 / 10 / (1 << 20) + 64;
4880×
        let img = tmp.join("rootfs.ext4");
4890×
        let status = std::process::Command::new("mkfs.ext4")
4900×
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
4910×
            .arg(&tree)
4920×
            .arg(&img)
4930×
            .arg(format!("{mib}M"))
4940×
            .status()
4950×
            .context("run mkfs.ext4")?;
4960×
        if !status.success() {
4970×
            bail!("mkfs.ext4 failed");
4980×
        }
4990×
        let hash = home::hash_file(&img)?;
5000×
        std::fs::rename(&img, home.rootfs(&hash))?;
5010×
        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) });
5020×
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
5030×
        Ok(hash)
504
    })();
5050×
    let _ = std::fs::remove_dir_all(&tmp);
5060×
    let hash = result?;
5070×
    println!("rootfs \"cas://blob/{hash}\"");
5080×
    Ok(())
5090×
}
510
5112×
fn run_local(
5122×
    home: &Home,
5132×
    dir: &Path,
5142×
    only: &[String],
5152×
    timeout: Duration,
5162×
    vars: &[(String, String)],
5172×
    secrets: &[(String, String)],
5182×
) -> Result<()> {
5192×
    let p = load(&dir.join(PIPELINE_PATH))?;
520
    // The named jobs and everything they depend on.
5212×
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
5222×
    for name in only {
5230×
        if !p.jobs.contains_key(name) {
5240×
            bail!("no job {name:?} in the pipeline");
5250×
        }
526
    }
5272×
    if !only.is_empty() {
528
        loop {
5290×
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
5300×
            if more.is_empty() {
5310×
                break;
5320×
            }
5330×
            wanted.extend(more);
534
        }
5352×
    }
5362×
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
5372×
    let _ = std::fs::remove_dir_all(&scratch);
5382×
    std::fs::create_dir_all(scratch.join("tree"))?;
5392×
    workspace::copy_tree(dir, &scratch.join("tree"))?;
5402×
    let mut failed: BTreeSet<String> = BTreeSet::new();
5412×
    let mut worst = 0;
54212×
    for job in p.order() {
54312×
        if !only.is_empty() && !wanted.contains(&job.name) {
5440×
            continue;
54512×
        }
54612×
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
5470×
            println!("── {} skipped: {d} failed", job.name);
5480×
            failed.insert(job.name.clone());
5490×
            continue;
55012×
        }
55112×
        let sb = &p.sandboxes[&job.sandbox];
55212×
        println!("── {} ({})", job.name, job.exec.join(" "));
55312×
        let js = scratch.join(&job.name);
55412×
        std::fs::create_dir_all(&js)?;
55512×
        let job = &job
55612×
            .in_sandbox(sb)
55712×
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
55812×
            .with_flow_env(vars);
559
        // Identities come from a hub: a local run has none.
56012×
        for i in &job.identities {
5610×
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
5620×
        }
563
        // Each secret the job declares must be given, as the hub would.
56412×
        let inputs = job
56512×
            .secrets
56612×
            .iter()
56712×
            .map(|s| {
5680×
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
5690×
                value
5700×
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
5710×
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
5720×
            })
57312×
            .collect::<Result<Vec<_>>>()?;
574
        // Each job starts from the same files: jobs do not share writes.
57512×
        let out = if sb.runtime == Runtime::Wasm {
57612×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
57717×
            wasm::run(sb, job, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r))?
5780×
        } else if sb.runtime == Runtime::Syscall {
5790×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
5800×
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
5810×
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
582
        } else {
5830×
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
5840×
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
585
        };
58612×
        let _ = workspace::remove_tree(&js);
58712×
        match out.exit_code {
5888×
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
5894×
            other => {
5904×
                println!(
591
                    "── {} failed ({}) in {} ms",
592
                    job.name,
5934×
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
594
                    out.duration_ms
595
                );
5964×
                failed.insert(job.name.clone());
5974×
                worst = 1;
598
            }
599
        }
600
    }
6012×
    let _ = workspace::remove_tree(&scratch);
6022×
    if worst != 0 {
6032×
        std::process::exit(worst);
6040×
    }
6050×
    Ok(())
6060×
}
607
60817×
fn print_record(r: &Record) {
60917×
    match r.stream.as_str() {
61017×
        "out" => println!("   {}", r.text),
61113×
        "err" => eprintln!("   {}", r.text),
61210×
        s => eprintln!("   [{s}] {}", r.text),
613
    }
61417×
}
615
616
#[cfg(test)]
617
mod tests {
618
    #[test]
6191×
    fn a_pipeline_newer_than_flow_is_named_as_such() {
6201×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 92: unknown output `sbom`; outputs are …");
6211×
        assert!(m.contains("does not know") && m.contains(env!("OXY_VERSION_LONG")) && m.contains("newer OxygenFlow"), "{m}");
6221×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 3: a job needs a sandbox");
6231×
        assert!(m.contains("is not valid") && !m.contains("newer"), "{m}");
6241×
    }
625
626
    use super::image_env_file;
627
628
    #[test]
6291×
    fn image_environments_are_checked_lines() {
6301×
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
6311×
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
6321×
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
6331×
        assert!(image_env_file(&["1X=y".into()]).is_err());
6341×
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
6351×
        assert_eq!(image_env_file(&[]).unwrap(), "");
6361×
    }
637
}