OXYGENHUB

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

126 of 402 lines run, 14 of 108 functions · run #196 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
    /// Ask this home's running runner to drain: claim nothing more, finish
48
    /// and report what it holds, then stop (as SIGTERM does on Linux; on
49
    /// Windows, the way to stop a runner without losing its job)
50
    Drain,
51
    /// Install a new flow build in place of this one (docs/jetstream.md
52
    /// §8.2): check it, keep this one as flow.prev, and have the running
53
    /// runner leave with notice so its unit starts the new build. A build
54
    /// that does not reach the hub goes back to flow.prev by itself
55
    Update {
56
        /// The new flow binary
57
        #[arg(long)]
58
        from: PathBuf,
59
        /// Seconds the running runner has to finish what it holds; jobs
60
        /// that will not finish in time are handed back with their checkpoints
61
        #[arg(long, default_value_t = 600)]
62
        notice: u64,
63
        /// Check the build and say what would happen, changing nothing
64
        #[arg(long)]
65
        dry_run: bool,
66
        /// Install a build older than this one
67
        #[arg(long)]
68
        allow_older: bool,
69
        /// The installed binary to replace (default: this one)
70
        #[arg(long)]
71
        exe: Option<PathBuf>,
72
    },
73
}
74
75
#[derive(Subcommand)]
76
enum Cmd {
77
    /// Validate a pipeline and print its jobs and hash
78
    Check {
79
        /// The pipeline file (default: .flow/pipeline.kdl)
80
        file: Option<PathBuf>,
81
    },
82
    /// Print a file's BLAKE3, for pinning in flow.toml
83
    Hash { file: PathBuf },
84
    /// Rootfs images for sandboxes
85
    Rootfs {
86
        #[command(subcommand)]
87
        cmd: RootfsCmd,
88
    },
89
    /// Run the pipeline on this directory's files, locally
90
    Run {
91
        /// Only these jobs (and what they depend on)
92
        jobs: Vec<String>,
93
        /// The directory to build (default: the current one)
94
        #[arg(long, default_value = ".")]
95
        dir: PathBuf,
96
        /// Minutes before a job is stopped
97
        #[arg(long, default_value_t = 60)]
98
        timeout: u64,
99
        /// A variable for every job, as the hub's settings would give it;
100
        /// the pipeline's own `env` wins
101
        #[arg(long = "var", value_name = "NAME=VALUE")]
102
        vars: Vec<String>,
103
        /// A secret a job's `secret` block names, as the hub would supply
104
        /// it; mounted as a file, never in the environment
105
        #[arg(long = "secret", value_name = "NAME=VALUE")]
106
        secrets: Vec<String>,
107
    },
108
    /// Claim and run jobs for the hub in flow.toml's [runner] (or the
109
    /// runner.toml `flow runner register` wrote)
110
    Runner {
111
        #[command(subcommand)]
112
        cmd: Option<RunnerCmd>,
113
    },
114
    /// Follow the checks of a pushed state on OxygenHub until they finish:
115
    /// exit 0 when all passed, 1 when one failed, 2 at the time limit.
116
    /// Uses $OXY_TOKEN and $OXY_CA as oxy does.
117
    Wait {
118
        /// The repository's URL on the hub (https://hub/owner/name)
119
        url: String,
120
        /// The state hash the push moved the bookmark to (`oxy push --json` prints it)
121
        state: String,
122
        /// Minutes to wait at most
123
        #[arg(long, default_value_t = 60)]
124
        timeout: u64,
125
    },
126
    /// Show which isolation tiers this machine can run jobs in, and why
127
    /// the others cannot
128
    Tiers,
129
    /// The syscall tier's sandbox helper, started by the runner for each job
130
    #[command(name = "__sandbox", hide = true)]
131
    Sandbox { spec: PathBuf },
132
    /// Check that this machine can run the syscall tier
133
    #[command(name = "__sandbox-probe", hide = true)]
134
    SandboxProbe,
135
    /// Rename a program that cannot rename its own file (Windows; #83)
136
    #[command(name = "__rename", hide = true)]
137
    Rename { from: PathBuf, to: PathBuf },
138
    /// The WASM tier's helper, started by the runner for each job
139
    #[command(name = "__wasm", hide = true)]
140
    Wasm { spec: PathBuf },
141
}
142
143
#[derive(Subcommand)]
144
enum RootfsCmd {
145
    /// Make an ext4 rootfs image from a root file system tarball and store it by hash
146
    Import {
147
        tarball: PathBuf,
148
        /// Refuse the tarball unless its SHA-256 matches (as its publisher states it)
149
        #[arg(long)]
150
        sha256: Option<String>,
151
        /// The image's own environment, NAME=value (repeatable): what a
152
        /// Dockerfile's ENV sets and `docker export` loses. Jobs start from
153
        /// it; their sandbox's and their own `env` override it
154
        #[arg(long = "env", value_name = "NAME=VALUE")]
155
        env: Vec<String>,
156
    },
157
    /// List the images this home holds
158
    List,
159
    /// Send an image to a hub, so its runners fetch it instead of having it
160
    /// copied to them: only the chunks the hub lacks travel. Signs in as
161
    /// `oh` is signed in to that hub, or with $OXY_TOKEN and $OXY_CA
162
    Push {
163
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
164
        hash: String,
165
        /// The hub (default: $OH_HUB, else the runner's, from runner.toml or flow.toml)
166
        #[arg(long)]
167
        hub: Option<String>,
168
    },
169
    /// Fetch an image a hub holds into this home, as a runner does for a
170
    /// job whose image it lacks. Signs in as `oh` is, or with $OXY_TOKEN
171
    Pull {
172
        hash: String,
173
        #[arg(long)]
174
        hub: Option<String>,
175
    },
176
}
177
1785×
fn main() {
1795×
    let cli = Cli::parse();
1805×
    if let Err(e) = run(cli) {
1812×
        eprintln!("flow: {e:#}");
1822×
        std::process::exit(1);
1833×
    }
1843×
}
185
1865×
fn run(cli: Cli) -> Result<()> {
1870×
    match cli.cmd {
1880×
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
1890×
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
1900×
        Cmd::Rename { from, to } => {
1910×
            flow::portable::rename(&from, &to).with_context(|| format!("renaming {} to {}", from.display(), to.display()))?;
1920×
            Ok(())
193
        }
1940×
        Cmd::Wasm { spec } => std::process::exit(wasm::wasm_main(&spec)),
1950×
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
1960×
        Cmd::Hash { file } => {
1970×
            println!("{}", home::hash_file(&file)?);
1980×
            Ok(())
199
        }
2000×
        Cmd::Rootfs { cmd } => {
2010×
            let home = Home::locate(cli.home.as_deref())?;
2020×
            match cmd {
2030×
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
2040×
                RootfsCmd::Push { hash, hub } => {
2050×
                    let client = image_client(&home, hub)?;
2060×
                    eprintln!("Sending image {} …", &hash[..12.min(hash.len())]);
2070×
                    let m = client.push(&home, &hash)?;
2080×
                    println!(
209
                        "Sent image {}: {} chunks the hub lacked, {} in {:.1} s",
2100×
                        &hash[..12],
211
                        m.chunks,
2120×
                        images::human(m.bytes),
2130×
                        m.elapsed.as_secs_f64()
214
                    );
2150×
                    Ok(())
216
                }
2170×
                RootfsCmd::Pull { hash, hub } => {
2180×
                    let client = image_client(&home, hub)?;
2190×
                    match client.fetch(&home, &hash)? {
2200×
                        Some(m) => {
2210×
                            println!(
222
                                "Fetched image {}: {} chunks, {} in {:.1} s",
2230×
                                &hash[..12],
224
                                m.chunks,
2250×
                                images::human(m.bytes),
2260×
                                m.elapsed.as_secs_f64()
227
                            );
2280×
                            Ok(())
229
                        }
2300×
                        None => anyhow::bail!("the hub does not hold image {}; send it with flow rootfs push", &hash[..12.min(hash.len())]),
231
                    }
232
                }
233
                RootfsCmd::List => {
2340×
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
2350×
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
2360×
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
2370×
                            println!("cas://blob/{h}  {} MiB", size >> 20);
2380×
                        }
239
                    }
2400×
                    Ok(())
241
                }
242
            }
243
        }
2442×
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
2452×
            let home = Home::locate(cli.home.as_deref())?;
2464×
            let pairs = |what: &str, list: &[String]| {
2474×
                list.iter()
2484×
                    .map(|e| {
2490×
                        e.split_once('=')
2500×
                            .map(|(k, v)| (k.to_string(), v.to_string()))
2510×
                            .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE"))
2520×
                    })
2534×
                    .collect::<Result<Vec<_>>>()
2544×
            };
2552×
            let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?);
2562×
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets)
257
        }
258
        Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => {
2590×
            let home = Home::locate(cli.home.as_deref())?;
2600×
            let (speed, ms) = facts::bench();
2610×
            let f = facts::now(&home, Some(speed));
2620×
            println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
2630×
            println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display());
2640×
            match f.load_x100 {
2650×
                Some(l) => println!("load {:.2}", l as f64 / 100.0),
2660×
                None => println!("load not measured here"),
267
            }
2680×
            if let Some(k) = f.kernel {
2690×
                println!("kernel {k}");
2700×
            }
2710×
            Ok(())
272
        }
2730×
        Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => {
2740×
            let home = Home::locate(cli.home.as_deref())?;
2750×
            if std::env::var_os("OXY_HOME").is_none() {
2760×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
2770×
            }
2780×
            let name = name.unwrap_or_else(|| {
2790×
                std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into())
2800×
            });
2810×
            let token = match token {
2820×
                Some(t) => t,
283
                None => {
2840×
                    eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:");
2850×
                    let mut line = String::new();
2860×
                    std::io::stdin().read_line(&mut line)?;
2870×
                    line.trim().to_string()
288
                }
289
            };
2900×
            let got = runner::register(&home, &hub, &token, &name, ca, label)?;
2910×
            println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id);
2920×
            Ok(())
293
        }
294
        Cmd::Runner { cmd: Some(RunnerCmd::Drain) } => {
2950×
            let home = Home::locate(cli.home.as_deref())?;
2960×
            if flow::update::ask_to_drain(&home.root)? {
2970×
                println!("asked the runner to drain: it claims nothing more and stops once its jobs are done and reported");
2980×
            } else {
2990×
                println!("no runner of this home is running; the next one starts afresh");
3000×
            }
3010×
            Ok(())
302
        }
3030×
        Cmd::Runner { cmd: Some(RunnerCmd::Update { from, notice, dry_run, allow_older, exe }) } => {
3040×
            let home = Home::locate(cli.home.as_deref())?;
3050×
            let exe = match exe {
3060×
                Some(e) => e,
3070×
                None => std::env::current_exe().context("finding this flow binary")?,
308
            };
3090×
            let done = flow::update::install(&home, &exe, &from, Duration::from_secs(notice), dry_run, allow_older)?;
3100×
            if dry_run {
3110×
                println!(
312
                    "flow {} checks out: it would replace flow {} at {} (dry run: nothing changed)",
313
                    done.to,
314
                    done.from,
3150×
                    done.exe.display()
316
                );
3170×
                return Ok(());
3180×
            }
3190×
            println!("flow {} installed at {}; flow {} kept as {}", done.to, done.exe.display(), done.from, flow::update::PREV);
3200×
            match done.told {
3210×
                Some(pid) => println!("the runner (pid {pid}) leaves within {notice} s, then its unit starts flow {}", done.to),
3220×
                None => println!(
323
                    "no runner of this home was told (none runs, or one from before runner updates, which does not listen): \
324
                     restart its unit, e.g. `systemctl restart --no-block flow-runner`; it drains and starts flow {}",
325
                    done.to
326
                ),
327
            }
3280×
            Ok(())
329
        }
330
        Cmd::Runner { cmd: None } => {
3310×
            let home = Home::locate(cli.home.as_deref())?;
332
            // A new build on trial that keeps failing to start goes back to
333
            // the one before, which then runs in its place (#85).
3340×
            if let flow::update::Start::RolledBack(p) = flow::update::on_start(&home.root)? {
335
                #[cfg(unix)]
336
                {
337
                    use std::os::unix::process::CommandExt;
3380×
                    let err = std::process::Command::new(&p.exe).args(std::env::args_os().skip(1)).exec();
3390×
                    bail!("starting flow {} again after the rollback: {err}", p.from);
340
                }
341
                // Windows has no exec: run the restored build and end with it.
342
                #[cfg(not(unix))]
343
                {
344
                    let status = std::process::Command::new(&p.exe)
345
                        .args(std::env::args_os().skip(1))
346
                        .status()
347
                        .with_context(|| format!("starting flow {} again after the rollback", p.from))?;
348
                    std::process::exit(status.code().unwrap_or(1));
349
                }
3500×
            }
351
            // The runner's oxy state (identity, user config) stays in its home.
3520×
            if std::env::var_os("OXY_HOME").is_none() {
3530×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
3540×
            }
3550×
            runner::serve(&home)
356
        }
357
        Cmd::Tiers => {
3583×
            let home = Home::locate(cli.home.as_deref())?;
3593×
            match runner::tiers(&home) {
3603×
                Ok((have, missing)) => {
3613×
                    for t in have {
3623×
                        println!("{t}: available");
3633×
                    }
3646×
                    for why in missing {
3656×
                        println!("{}", why.replacen(": ", ": unavailable: ", 1));
3666×
                    }
367
                }
3680×
                Err(why) => println!("{why}"),
369
            }
3703×
            Ok(())
371
        }
3720×
        Cmd::Wait { url, state, timeout } => {
3730×
            let token = std::env::var("OXY_TOKEN").ok();
3740×
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
3750×
            let code =
3760×
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
3770×
            std::process::exit(code);
378
        }
379
    }
3805×
}
381
382
/// The hub image commands talk to: `--hub`, else $OH_HUB, else the
383
/// runner's. The token: $OXY_TOKEN, else the login `oh auth login` (or
384
/// `oxy auth login`) saved for that hub in Oxygen's credential store
385
/// (oxygenflow#44), else the runner's own.
3860×
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
3870×
    let runner = home.config.runner.clone();
3880×
    let hub = hub
3890×
        .or_else(|| std::env::var("OH_HUB").ok().filter(|h| !h.is_empty()))
3900×
        .or_else(|| runner.as_ref().map(|r| r.hub.clone()))
3910×
        .context("name the hub with --hub https://HUB (or set OH_HUB)")?;
3920×
    let (saved_token, saved_ca) = oxy_core::credentials::Credentials::user().lookup(&hub);
3930×
    let token = std::env::var("OXY_TOKEN")
3940×
        .ok()
3950×
        .filter(|t| !t.is_empty())
3960×
        .or(saved_token)
3970×
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
3980×
        .with_context(|| format!("no token for {hub}: sign in with `oh auth login --hub {hub}`, or set OXY_TOKEN"))?;
3990×
    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()));
4000×
    images::Client::new(&hub, &token, ca.as_deref())
4010×
}
402
4032×
fn load(file: &Path) -> Result<Pipeline> {
4042×
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
4052×
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{}", not_valid(file, &p.to_string())))
4062×
}
407
408
/// Why a pipeline did not parse. When it names something this flow does
409
/// not know (a node, an output, an event), the pipeline may simply be
410
/// newer than this flow (oxygenflow#43): say so, with this flow's version.
4112×
fn not_valid(file: &Path, problems: &str) -> String {
4122×
    if problems.contains("unknown ") {
4131×
        format!(
414
            "{} uses something this flow ({}) does not know:\n{problems}\n\
415
             If the pipeline was written for a newer OxygenFlow, update flow (build it from oxygenflow main); \
416
             otherwise fix the lines named.",
4171×
            file.display(),
418
            env!("OXY_VERSION_LONG")
419
        )
420
    } else {
4211×
        format!("{} is not valid:\n{problems}", file.display())
422
    }
4232×
}
424
4250×
fn check(file: &Path) -> Result<()> {
4260×
    let p = load(file)?;
4270×
    let depths = p.depths();
4280×
    for j in p.order() {
4290×
        let sb = &p.sandboxes[&j.sandbox];
4300×
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
4310×
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
432
    }
4330×
    println!("pipeline {}", hex::encode(p.hash()));
4340×
    Ok(())
4350×
}
436
437
/// The image environment file flow-init reads (`/etc/flow/env`): one
438
/// `NAME=value` per line, names checked as a pipeline's are.
4395×
fn image_env_file(env: &[String]) -> Result<String> {
4405×
    let mut out = String::new();
4416×
    for e in env {
4426×
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
44316×
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
4445×
        if !ok || v.contains('\n') || v.contains('\0') {
4452×
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
4463×
        }
4473×
        out.push_str(&format!("{k}={v}\n"));
448
    }
4492×
    Ok(out)
4505×
}
451
452
/// The architecture an ELF file was built for, by its header.
4530×
fn elf_arch(path: &Path) -> Option<&'static str> {
4540×
    let mut head = [0u8; 20];
4550×
    std::io::Read::read_exact(&mut std::fs::File::open(path).ok()?, &mut head).ok()?;
4560×
    jet::rootfs::elf_arch(&head)
4570×
}
458
459
/// The architecture of an unpacked rootfs: its shell's, or the first
460
/// program's found under bin.
4610×
fn tree_arch(tree: &Path) -> Option<&'static str> {
4620×
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
4630×
        let p = tree.join(rel);
4640×
        let p = std::fs::canonicalize(&p).unwrap_or(p);
4650×
        if let Some(a) = elf_arch(&p) {
4660×
            return Some(a);
4670×
        }
468
    }
4690×
    None
4700×
}
471
4720×
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
4730×
    let env_file = image_env_file(env)?;
4740×
    if let Some(want) = sha256 {
4750×
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
4760×
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
4770×
        if got != want.to_lowercase() {
4780×
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
4790×
        }
4800×
    }
4810×
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
4820×
    let _ = std::fs::remove_dir_all(&tmp);
4830×
    let tree = tmp.join("tree");
4840×
    std::fs::create_dir_all(&tree)?;
4850×
    let result = (|| -> Result<String> {
4860×
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
4870×
        if !status.success() {
4880×
            bail!("tar could not unpack {}", tarball.display());
4890×
        }
490
        // The image's architecture must be this machine's: there is no
491
        // emulation tier (spec §11.2).
4920×
        let arch = tree_arch(&tree).unwrap_or("unknown");
4930×
        if arch != "unknown" && arch != std::env::consts::ARCH {
4940×
            bail!(
495
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
4960×
                tarball.display(),
497
                std::env::consts::ARCH
498
            );
4990×
        }
500
        // Mount points flow-init needs (docs/m0.md §2).
5010×
        for d in ["src", "tmp", "proc", "dev", "run"] {
5020×
            std::fs::create_dir_all(tree.join(d))?;
503
        }
5040×
        if !env_file.is_empty() {
5050×
            std::fs::create_dir_all(tree.join("etc/flow"))?;
5060×
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
5070×
        }
5080×
        let used: u64 = ignore::WalkBuilder::new(&tree)
5090×
            .hidden(false)
5100×
            .ignore(false)
5110×
            .git_ignore(false)
5120×
            .build()
5130×
            .flatten()
5140×
            .filter_map(|e| e.metadata().ok())
5150×
            .map(|m| m.len().max(4096))
5160×
            .sum();
5170×
        let mib = used * 13 / 10 / (1 << 20) + 64;
5180×
        let img = tmp.join("rootfs.ext4");
5190×
        let status = std::process::Command::new("mkfs.ext4")
5200×
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
5210×
            .arg(&tree)
5220×
            .arg(&img)
5230×
            .arg(format!("{mib}M"))
5240×
            .status()
5250×
            .context("run mkfs.ext4")?;
5260×
        if !status.success() {
5270×
            bail!("mkfs.ext4 failed");
5280×
        }
5290×
        let hash = home::hash_file(&img)?;
5300×
        std::fs::rename(&img, home.rootfs(&hash))?;
5310×
        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) });
5320×
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
5330×
        Ok(hash)
534
    })();
5350×
    let _ = std::fs::remove_dir_all(&tmp);
5360×
    let hash = result?;
5370×
    println!("rootfs \"cas://blob/{hash}\"");
5380×
    Ok(())
5390×
}
540
5412×
fn run_local(
5422×
    home: &Home,
5432×
    dir: &Path,
5442×
    only: &[String],
5452×
    timeout: Duration,
5462×
    vars: &[(String, String)],
5472×
    secrets: &[(String, String)],
5482×
) -> Result<()> {
5492×
    let p = load(&dir.join(PIPELINE_PATH))?;
550
    // The named jobs and everything they depend on.
5512×
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
5522×
    for name in only {
5530×
        if !p.jobs.contains_key(name) {
5540×
            bail!("no job {name:?} in the pipeline");
5550×
        }
556
    }
5572×
    if !only.is_empty() {
558
        loop {
5590×
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
5600×
            if more.is_empty() {
5610×
                break;
5620×
            }
5630×
            wanted.extend(more);
564
        }
5652×
    }
5662×
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
5672×
    let _ = std::fs::remove_dir_all(&scratch);
5682×
    std::fs::create_dir_all(scratch.join("tree"))?;
5692×
    workspace::copy_tree(dir, &scratch.join("tree"))?;
5702×
    let mut failed: BTreeSet<String> = BTreeSet::new();
5712×
    let mut worst = 0;
57212×
    for job in p.order() {
57312×
        if !only.is_empty() && !wanted.contains(&job.name) {
5740×
            continue;
57512×
        }
57612×
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
5770×
            println!("── {} skipped: {d} failed", job.name);
5780×
            failed.insert(job.name.clone());
5790×
            continue;
58012×
        }
58112×
        let sb = &p.sandboxes[&job.sandbox];
58212×
        println!("── {} ({})", job.name, job.exec.join(" "));
58312×
        let js = scratch.join(&job.name);
58412×
        std::fs::create_dir_all(&js)?;
58512×
        let job = &job
58612×
            .in_sandbox(sb)
58712×
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
58812×
            .with_flow_env(vars);
589
        // Identities come from a hub: a local run has none.
59012×
        for i in &job.identities {
5910×
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
5920×
        }
593
        // Each secret the job declares must be given, as the hub would.
59412×
        let inputs = job
59512×
            .secrets
59612×
            .iter()
59712×
            .map(|s| {
5980×
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
5990×
                value
6000×
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
6010×
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
6020×
            })
60312×
            .collect::<Result<Vec<_>>>()?;
604
        // Each job starts from the same files: jobs do not share writes.
60512×
        let out = if sb.runtime == Runtime::Wasm {
60612×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
60717×
            wasm::run(sb, job, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r))?
6080×
        } else if sb.runtime == Runtime::Syscall {
6090×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
6100×
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
6110×
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
612
        } else {
6130×
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
6140×
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
615
        };
61612×
        let _ = workspace::remove_tree(&js);
61712×
        match out.exit_code {
6188×
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
6194×
            other => {
6204×
                println!(
621
                    "── {} failed ({}) in {} ms",
622
                    job.name,
6234×
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
624
                    out.duration_ms
625
                );
6264×
                failed.insert(job.name.clone());
6274×
                worst = 1;
628
            }
629
        }
630
    }
6312×
    let _ = workspace::remove_tree(&scratch);
6322×
    if worst != 0 {
6332×
        std::process::exit(worst);
6340×
    }
6350×
    Ok(())
6360×
}
637
63817×
fn print_record(r: &Record) {
63917×
    match r.stream.as_str() {
64017×
        "out" => println!("   {}", r.text),
64113×
        "err" => eprintln!("   {}", r.text),
64210×
        s => eprintln!("   [{s}] {}", r.text),
643
    }
64417×
}
645
646
#[cfg(test)]
647
mod tests {
648
    #[test]
6491×
    fn a_pipeline_newer_than_flow_is_named_as_such() {
6501×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 92: unknown output `sbom`; outputs are …");
6511×
        assert!(m.contains("does not know") && m.contains(env!("OXY_VERSION_LONG")) && m.contains("newer OxygenFlow"), "{m}");
6521×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 3: a job needs a sandbox");
6531×
        assert!(m.contains("is not valid") && !m.contains("newer"), "{m}");
6541×
    }
655
656
    use super::image_env_file;
657
658
    #[test]
6591×
    fn image_environments_are_checked_lines() {
6601×
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
6611×
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
6621×
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
6631×
        assert!(image_env_file(&["1X=y".into()]).is_err());
6641×
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
6651×
        assert_eq!(image_env_file(&[]).unwrap(), "");
6661×
    }
667
}