OXYGENHUB

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

126 of 448 lines run, 14 of 124 functions · run #226 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 DepsCmd {
77
    /// Whether every crate a Cargo.lock needs is in the image at that
78
    /// version; exit 1 naming each missing one and the versions it has
79
    Check {
80
        /// The lock file (default: Cargo.lock)
81
        #[arg(default_value = "Cargo.lock")]
82
        lock: PathBuf,
83
        #[command(flatten)]
84
        image: DepsSource,
85
    },
86
    /// Print the image's crates as `NAME VERSION` lines (its crates.txt)
87
    List {
88
        #[command(flatten)]
89
        image: DepsSource,
90
    },
91
}
92
93
/// Where the image's crate set comes from: its crate list (the crates.txt
94
/// published with the image), a vendor directory, or the lock files it is
95
/// built from; inside a job, /opt/vendor.
96
#[derive(clap::Args)]
97
#[group(multiple = false)]
98
struct DepsSource {
99
    /// The image's crate list (crates.txt, written by images/rust/build.sh)
100
    #[arg(long, value_name = "FILE")]
101
    list: Option<PathBuf>,
102
    /// A cargo vendor directory (default inside a job: /opt/crates.txt, else /opt/vendor)
103
    #[arg(long, value_name = "DIR")]
104
    vendor: Option<PathBuf>,
105
    /// The lock files the image vendors (oxygen's, oxygenhub's,
106
    /// oxygenflow's), as images/rust/build.sh does (repeatable)
107
    #[arg(long = "image-lock", value_name = "LOCK")]
108
    locks: Vec<PathBuf>,
109
}
110
111
impl DepsSource {
1120×
    fn crates(&self) -> Result<BTreeSet<flow::deps::Crate>> {
1130×
        let read = |p: &Path| std::fs::read_to_string(p).with_context(|| p.display().to_string());
1140×
        if let Some(f) = &self.list {
1150×
            return Ok(flow::deps::from_list(&read(f)?));
1160×
        }
1170×
        if !self.locks.is_empty() {
1180×
            let mut all = BTreeSet::new();
1190×
            for l in &self.locks {
1200×
                all.extend(flow::deps::from_lock(&read(l)?).map_err(|e| anyhow::anyhow!("{}: {e}", l.display()))?);
121
            }
1220×
            return Ok(all);
1230×
        }
124
        // Inside a job: the image's own list, else its vendor directory.
1250×
        if self.vendor.is_none() && Path::new("/opt/crates.txt").is_file() {
1260×
            return Ok(flow::deps::from_list(&read(Path::new("/opt/crates.txt"))?));
1270×
        }
1280×
        let dir = self.vendor.clone().unwrap_or_else(|| PathBuf::from("/opt/vendor"));
1290×
        if self.vendor.is_none() && !dir.is_dir() {
1300×
            bail!("say what the image holds: --list crates.txt (published with the image), --vendor DIR, or --image-lock for each lock file it is built from; inside a job, /opt/vendor is read");
1310×
        }
1320×
        flow::deps::from_vendor(&dir).map_err(|e| anyhow::anyhow!(e))
1330×
    }
134
}
135
136
#[derive(Subcommand)]
137
enum Cmd {
138
    /// Validate a pipeline and print its jobs and hash
139
    Check {
140
        /// The pipeline file (default: .flow/pipeline.kdl)
141
        file: Option<PathBuf>,
142
    },
143
    /// Print a file's BLAKE3, for pinning in flow.toml
144
    Hash { file: PathBuf },
145
    /// The crates the build image vendors, for jobs with no network (#101)
146
    Deps {
147
        #[command(subcommand)]
148
        cmd: DepsCmd,
149
    },
150
    /// Rootfs images for sandboxes
151
    Rootfs {
152
        #[command(subcommand)]
153
        cmd: RootfsCmd,
154
    },
155
    /// Run the pipeline on this directory's files, locally
156
    Run {
157
        /// Only these jobs (and what they depend on)
158
        jobs: Vec<String>,
159
        /// The directory to build (default: the current one)
160
        #[arg(long, default_value = ".")]
161
        dir: PathBuf,
162
        /// Minutes before a job is stopped
163
        #[arg(long, default_value_t = 60)]
164
        timeout: u64,
165
        /// A variable for every job, as the hub's settings would give it;
166
        /// the pipeline's own `env` wins
167
        #[arg(long = "var", value_name = "NAME=VALUE")]
168
        vars: Vec<String>,
169
        /// A secret a job's `secret` block names, as the hub would supply
170
        /// it; mounted as a file, never in the environment
171
        #[arg(long = "secret", value_name = "NAME=VALUE")]
172
        secrets: Vec<String>,
173
    },
174
    /// Claim and run jobs for the hub in flow.toml's [runner] (or the
175
    /// runner.toml `flow runner register` wrote)
176
    Runner {
177
        #[command(subcommand)]
178
        cmd: Option<RunnerCmd>,
179
    },
180
    /// Follow the checks of a pushed state on OxygenHub until they finish:
181
    /// exit 0 when all passed, 1 when one failed, 2 at the time limit.
182
    /// Uses $OXY_TOKEN and $OXY_CA as oxy does.
183
    Wait {
184
        /// The repository's URL on the hub (https://hub/owner/name)
185
        url: String,
186
        /// The state hash the push moved the bookmark to (`oxy push --json` prints it)
187
        state: String,
188
        /// Minutes to wait at most
189
        #[arg(long, default_value_t = 60)]
190
        timeout: u64,
191
    },
192
    /// Show which isolation tiers this machine can run jobs in, and why
193
    /// the others cannot
194
    Tiers,
195
    /// The syscall tier's sandbox helper, started by the runner for each job
196
    #[command(name = "__sandbox", hide = true)]
197
    Sandbox { spec: PathBuf },
198
    /// Check that this machine can run the syscall tier
199
    #[command(name = "__sandbox-probe", hide = true)]
200
    SandboxProbe,
201
    /// Rename a program that cannot rename its own file (Windows; #83)
202
    #[command(name = "__rename", hide = true)]
203
    Rename { from: PathBuf, to: PathBuf },
204
    /// The WASM tier's helper, started by the runner for each job
205
    #[command(name = "__wasm", hide = true)]
206
    Wasm { spec: PathBuf },
207
}
208
209
#[derive(Subcommand)]
210
enum RootfsCmd {
211
    /// Make an ext4 rootfs image from a root file system tarball and store it by hash
212
    Import {
213
        tarball: PathBuf,
214
        /// Refuse the tarball unless its SHA-256 matches (as its publisher states it)
215
        #[arg(long)]
216
        sha256: Option<String>,
217
        /// The image's own environment, NAME=value (repeatable): what a
218
        /// Dockerfile's ENV sets and `docker export` loses. Jobs start from
219
        /// it; their sandbox's and their own `env` override it
220
        #[arg(long = "env", value_name = "NAME=VALUE")]
221
        env: Vec<String>,
222
    },
223
    /// List the images this home holds
224
    List,
225
    /// Send an image to a hub, so its runners fetch it instead of having it
226
    /// copied to them: only the chunks the hub lacks travel. Signs in as
227
    /// `oh` is signed in to that hub, or with $OXY_TOKEN and $OXY_CA
228
    Push {
229
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
230
        hash: String,
231
        /// The hub (default: $OH_HUB, else the runner's, from runner.toml or flow.toml)
232
        #[arg(long)]
233
        hub: Option<String>,
234
    },
235
    /// Fetch an image a hub holds into this home, as a runner does for a
236
    /// job whose image it lacks. Signs in as `oh` is, or with $OXY_TOKEN
237
    Pull {
238
        hash: String,
239
        #[arg(long)]
240
        hub: Option<String>,
241
    },
242
}
243
2445×
fn main() {
2455×
    let cli = Cli::parse();
2465×
    if let Err(e) = run(cli) {
2472×
        eprintln!("flow: {e:#}");
2482×
        std::process::exit(1);
2493×
    }
2503×
}
251
2525×
fn run(cli: Cli) -> Result<()> {
2530×
    match cli.cmd {
2540×
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
2550×
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
2560×
        Cmd::Rename { from, to } => {
2570×
            flow::portable::rename(&from, &to).with_context(|| format!("renaming {} to {}", from.display(), to.display()))?;
2580×
            Ok(())
259
        }
2600×
        Cmd::Wasm { spec } => std::process::exit(wasm::wasm_main(&spec)),
2610×
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
2620×
        Cmd::Deps { cmd: DepsCmd::List { image } } => {
2630×
            print!("{}", flow::deps::render_list(&image.crates()?));
2640×
            Ok(())
265
        }
2660×
        Cmd::Deps { cmd: DepsCmd::Check { lock, image } } => {
2670×
            let text = std::fs::read_to_string(&lock).with_context(|| lock.display().to_string())?;
2680×
            let need = flow::deps::from_lock(&text).map_err(|e| anyhow::anyhow!("{}: {e}", lock.display()))?;
2690×
            let missing = flow::deps::missing(&need, &image.crates()?);
2700×
            if missing.is_empty() {
2710×
                println!("deps: all {} crates of {} are in the image", need.len(), lock.display());
2720×
                return Ok(());
2730×
            }
2740×
            eprintln!("deps: {} of {} crates of {} are not in the image:", missing.len(), need.len(), lock.display());
2750×
            for ((name, version), has) in &missing {
2760×
                let instead = match has.as_slice() {
2770×
                    [] => "the image has no version of it".to_string(),
2780×
                    vs => format!("the image has {}: cargo update -p {name}@{version} --precise {}", vs.join(", "), vs.last().unwrap()),
279
                };
2800×
                eprintln!("  {name} {version}  ({instead})");
281
            }
2820×
            eprintln!("pin a version the image has, or rebuild the image with this workspace's lock (images/rust/build.sh)");
2830×
            std::process::exit(1);
284
        }
2850×
        Cmd::Hash { file } => {
2860×
            println!("{}", home::hash_file(&file)?);
2870×
            Ok(())
288
        }
2890×
        Cmd::Rootfs { cmd } => {
2900×
            let home = Home::locate(cli.home.as_deref())?;
2910×
            match cmd {
2920×
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
2930×
                RootfsCmd::Push { hash, hub } => {
2940×
                    let client = image_client(&home, hub)?;
2950×
                    eprintln!("Sending image {} …", &hash[..12.min(hash.len())]);
2960×
                    let m = client.push(&home, &hash)?;
2970×
                    println!(
298
                        "Sent image {}: {} chunks the hub lacked, {} in {:.1} s",
2990×
                        &hash[..12],
300
                        m.chunks,
3010×
                        images::human(m.bytes),
3020×
                        m.elapsed.as_secs_f64()
303
                    );
3040×
                    Ok(())
305
                }
3060×
                RootfsCmd::Pull { hash, hub } => {
3070×
                    let client = image_client(&home, hub)?;
3080×
                    match client.fetch(&home, &hash)? {
3090×
                        Some(m) => {
3100×
                            println!(
311
                                "Fetched image {}: {} chunks, {} in {:.1} s",
3120×
                                &hash[..12],
313
                                m.chunks,
3140×
                                images::human(m.bytes),
3150×
                                m.elapsed.as_secs_f64()
316
                            );
3170×
                            Ok(())
318
                        }
3190×
                        None => anyhow::bail!("the hub does not hold image {}; send it with flow rootfs push", &hash[..12.min(hash.len())]),
320
                    }
321
                }
322
                RootfsCmd::List => {
3230×
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
3240×
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
3250×
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
3260×
                            println!("cas://blob/{h}  {} MiB", size >> 20);
3270×
                        }
328
                    }
3290×
                    Ok(())
330
                }
331
            }
332
        }
3332×
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
3342×
            let home = Home::locate(cli.home.as_deref())?;
3354×
            let pairs = |what: &str, list: &[String]| {
3364×
                list.iter()
3374×
                    .map(|e| {
3380×
                        e.split_once('=')
3390×
                            .map(|(k, v)| (k.to_string(), v.to_string()))
3400×
                            .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE"))
3410×
                    })
3424×
                    .collect::<Result<Vec<_>>>()
3434×
            };
3442×
            let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?);
3452×
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets)
346
        }
347
        Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => {
3480×
            let home = Home::locate(cli.home.as_deref())?;
3490×
            let (speed, ms) = facts::bench();
3500×
            let f = facts::now(&home, Some(speed));
3510×
            println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
3520×
            println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display());
3530×
            match f.load_x100 {
3540×
                Some(l) => println!("load {:.2}", l as f64 / 100.0),
3550×
                None => println!("load not measured here"),
356
            }
3570×
            if let Some(k) = f.kernel {
3580×
                println!("kernel {k}");
3590×
            }
3600×
            Ok(())
361
        }
3620×
        Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => {
3630×
            let home = Home::locate(cli.home.as_deref())?;
3640×
            if std::env::var_os("OXY_HOME").is_none() {
3650×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
3660×
            }
3670×
            let name = name.unwrap_or_else(|| {
3680×
                std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into())
3690×
            });
3700×
            let token = match token {
3710×
                Some(t) => t,
372
                None => {
3730×
                    eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:");
3740×
                    let mut line = String::new();
3750×
                    std::io::stdin().read_line(&mut line)?;
3760×
                    line.trim().to_string()
377
                }
378
            };
3790×
            let got = runner::register(&home, &hub, &token, &name, ca, label)?;
3800×
            println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id);
3810×
            Ok(())
382
        }
383
        Cmd::Runner { cmd: Some(RunnerCmd::Drain) } => {
3840×
            let home = Home::locate(cli.home.as_deref())?;
3850×
            if flow::update::ask_to_drain(&home.root)? {
3860×
                println!("asked the runner to drain: it claims nothing more and stops once its jobs are done and reported");
3870×
            } else {
3880×
                println!("no runner of this home is running; the next one starts afresh");
3890×
            }
3900×
            Ok(())
391
        }
3920×
        Cmd::Runner { cmd: Some(RunnerCmd::Update { from, notice, dry_run, allow_older, exe }) } => {
3930×
            let home = Home::locate(cli.home.as_deref())?;
3940×
            let exe = match exe {
3950×
                Some(e) => e,
3960×
                None => std::env::current_exe().context("finding this flow binary")?,
397
            };
3980×
            let done = flow::update::install(&home, &exe, &from, Duration::from_secs(notice), dry_run, allow_older)?;
3990×
            if dry_run {
4000×
                println!(
401
                    "flow {} checks out: it would replace flow {} at {} (dry run: nothing changed)",
402
                    done.to,
403
                    done.from,
4040×
                    done.exe.display()
405
                );
4060×
                return Ok(());
4070×
            }
4080×
            println!("flow {} installed at {}; flow {} kept as {}", done.to, done.exe.display(), done.from, flow::update::PREV);
4090×
            match done.told {
4100×
                Some(pid) => println!("the runner (pid {pid}) leaves within {notice} s, then its unit starts flow {}", done.to),
4110×
                None => println!(
412
                    "no runner of this home was told (none runs, or one from before runner updates, which does not listen): \
413
                     restart its unit, e.g. `systemctl restart --no-block flow-runner`; it drains and starts flow {}",
414
                    done.to
415
                ),
416
            }
4170×
            Ok(())
418
        }
419
        Cmd::Runner { cmd: None } => {
4200×
            let home = Home::locate(cli.home.as_deref())?;
421
            // A new build on trial that keeps failing to start goes back to
422
            // the one before, which then runs in its place (#85).
4230×
            if let flow::update::Start::RolledBack(p) = flow::update::on_start(&home.root)? {
424
                #[cfg(unix)]
425
                {
426
                    use std::os::unix::process::CommandExt;
4270×
                    let err = std::process::Command::new(&p.exe).args(std::env::args_os().skip(1)).exec();
4280×
                    bail!("starting flow {} again after the rollback: {err}", p.from);
429
                }
430
                // Windows has no exec: run the restored build and end with it.
431
                #[cfg(not(unix))]
432
                {
433
                    let status = std::process::Command::new(&p.exe)
434
                        .args(std::env::args_os().skip(1))
435
                        .status()
436
                        .with_context(|| format!("starting flow {} again after the rollback", p.from))?;
437
                    std::process::exit(status.code().unwrap_or(1));
438
                }
4390×
            }
440
            // The runner's oxy state (identity, user config) stays in its home.
4410×
            if std::env::var_os("OXY_HOME").is_none() {
4420×
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
4430×
            }
4440×
            runner::serve(&home)
445
        }
446
        Cmd::Tiers => {
4473×
            let home = Home::locate(cli.home.as_deref())?;
4483×
            match runner::tiers(&home) {
4493×
                Ok((have, missing)) => {
4503×
                    for t in have {
4513×
                        println!("{t}: available");
4523×
                    }
4536×
                    for why in missing {
4546×
                        println!("{}", why.replacen(": ", ": unavailable: ", 1));
4556×
                    }
456
                }
4570×
                Err(why) => println!("{why}"),
458
            }
4593×
            Ok(())
460
        }
4610×
        Cmd::Wait { url, state, timeout } => {
4620×
            let token = std::env::var("OXY_TOKEN").ok();
4630×
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
4640×
            let code =
4650×
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
4660×
            std::process::exit(code);
467
        }
468
    }
4695×
}
470
471
/// The hub image commands talk to: `--hub`, else $OH_HUB, else the
472
/// runner's. The token: $OXY_TOKEN, else the login `oh auth login` (or
473
/// `oxy auth login`) saved for that hub in Oxygen's credential store
474
/// (oxygenflow#44), else the runner's own.
4750×
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
4760×
    let runner = home.config.runner.clone();
4770×
    let hub = hub
4780×
        .or_else(|| std::env::var("OH_HUB").ok().filter(|h| !h.is_empty()))
4790×
        .or_else(|| runner.as_ref().map(|r| r.hub.clone()))
4800×
        .context("name the hub with --hub https://HUB (or set OH_HUB)")?;
4810×
    let (saved_token, saved_ca) = oxy_core::credentials::Credentials::user().lookup(&hub);
4820×
    let token = std::env::var("OXY_TOKEN")
4830×
        .ok()
4840×
        .filter(|t| !t.is_empty())
4850×
        .or(saved_token)
4860×
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
4870×
        .with_context(|| format!("no token for {hub}: sign in with `oh auth login --hub {hub}`, or set OXY_TOKEN"))?;
4880×
    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()));
4890×
    images::Client::new(&hub, &token, ca.as_deref())
4900×
}
491
4922×
fn load(file: &Path) -> Result<Pipeline> {
4932×
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
4942×
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{}", not_valid(file, &p.to_string())))
4952×
}
496
497
/// Why a pipeline did not parse. When it names something this flow does
498
/// not know (a node, an output, an event), the pipeline may simply be
499
/// newer than this flow (oxygenflow#43): say so, with this flow's version.
5002×
fn not_valid(file: &Path, problems: &str) -> String {
5012×
    if problems.contains("unknown ") {
5021×
        format!(
503
            "{} uses something this flow ({}) does not know:\n{problems}\n\
504
             If the pipeline was written for a newer OxygenFlow, update flow (build it from oxygenflow main); \
505
             otherwise fix the lines named.",
5061×
            file.display(),
507
            env!("OXY_VERSION_LONG")
508
        )
509
    } else {
5101×
        format!("{} is not valid:\n{problems}", file.display())
511
    }
5122×
}
513
5140×
fn check(file: &Path) -> Result<()> {
5150×
    let p = load(file)?;
5160×
    let depths = p.depths();
5170×
    for j in p.order() {
5180×
        let sb = &p.sandboxes[&j.sandbox];
5190×
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
5200×
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
521
    }
5220×
    println!("pipeline {}", hex::encode(p.hash()));
5230×
    Ok(())
5240×
}
525
526
/// The image environment file flow-init reads (`/etc/flow/env`): one
527
/// `NAME=value` per line, names checked as a pipeline's are.
5285×
fn image_env_file(env: &[String]) -> Result<String> {
5295×
    let mut out = String::new();
5306×
    for e in env {
5316×
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
53216×
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
5335×
        if !ok || v.contains('\n') || v.contains('\0') {
5342×
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
5353×
        }
5363×
        out.push_str(&format!("{k}={v}\n"));
537
    }
5382×
    Ok(out)
5395×
}
540
541
/// The architecture an ELF file was built for, by its header.
5420×
fn elf_arch(path: &Path) -> Option<&'static str> {
5430×
    let mut head = [0u8; 20];
5440×
    std::io::Read::read_exact(&mut std::fs::File::open(path).ok()?, &mut head).ok()?;
5450×
    jet::rootfs::elf_arch(&head)
5460×
}
547
548
/// The architecture of an unpacked rootfs: its shell's, or the first
549
/// program's found under bin.
5500×
fn tree_arch(tree: &Path) -> Option<&'static str> {
5510×
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
5520×
        let p = tree.join(rel);
5530×
        let p = std::fs::canonicalize(&p).unwrap_or(p);
5540×
        if let Some(a) = elf_arch(&p) {
5550×
            return Some(a);
5560×
        }
557
    }
5580×
    None
5590×
}
560
5610×
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
5620×
    let env_file = image_env_file(env)?;
5630×
    if let Some(want) = sha256 {
5640×
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
5650×
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
5660×
        if got != want.to_lowercase() {
5670×
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
5680×
        }
5690×
    }
5700×
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
5710×
    let _ = std::fs::remove_dir_all(&tmp);
5720×
    let tree = tmp.join("tree");
5730×
    std::fs::create_dir_all(&tree)?;
5740×
    let result = (|| -> Result<String> {
5750×
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
5760×
        if !status.success() {
5770×
            bail!("tar could not unpack {}", tarball.display());
5780×
        }
579
        // The image's architecture must be this machine's: there is no
580
        // emulation tier (spec §11.2).
5810×
        let arch = tree_arch(&tree).unwrap_or("unknown");
5820×
        if arch != "unknown" && arch != std::env::consts::ARCH {
5830×
            bail!(
584
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
5850×
                tarball.display(),
586
                std::env::consts::ARCH
587
            );
5880×
        }
589
        // Mount points flow-init needs (docs/m0.md §2).
5900×
        for d in ["src", "tmp", "proc", "dev", "run"] {
5910×
            std::fs::create_dir_all(tree.join(d))?;
592
        }
5930×
        if !env_file.is_empty() {
5940×
            std::fs::create_dir_all(tree.join("etc/flow"))?;
5950×
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
5960×
        }
5970×
        let used: u64 = ignore::WalkBuilder::new(&tree)
5980×
            .hidden(false)
5990×
            .ignore(false)
6000×
            .git_ignore(false)
6010×
            .build()
6020×
            .flatten()
6030×
            .filter_map(|e| e.metadata().ok())
6040×
            .map(|m| m.len().max(4096))
6050×
            .sum();
6060×
        let mib = used * 13 / 10 / (1 << 20) + 64;
6070×
        let img = tmp.join("rootfs.ext4");
6080×
        let status = std::process::Command::new("mkfs.ext4")
6090×
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
6100×
            .arg(&tree)
6110×
            .arg(&img)
6120×
            .arg(format!("{mib}M"))
6130×
            .status()
6140×
            .context("run mkfs.ext4")?;
6150×
        if !status.success() {
6160×
            bail!("mkfs.ext4 failed");
6170×
        }
6180×
        let hash = home::hash_file(&img)?;
6190×
        std::fs::rename(&img, home.rootfs(&hash))?;
6200×
        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) });
6210×
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
6220×
        Ok(hash)
623
    })();
6240×
    let _ = std::fs::remove_dir_all(&tmp);
6250×
    let hash = result?;
6260×
    println!("rootfs \"cas://blob/{hash}\"");
6270×
    Ok(())
6280×
}
629
6302×
fn run_local(
6312×
    home: &Home,
6322×
    dir: &Path,
6332×
    only: &[String],
6342×
    timeout: Duration,
6352×
    vars: &[(String, String)],
6362×
    secrets: &[(String, String)],
6372×
) -> Result<()> {
6382×
    let p = load(&dir.join(PIPELINE_PATH))?;
639
    // The named jobs and everything they depend on.
6402×
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
6412×
    for name in only {
6420×
        if !p.jobs.contains_key(name) {
6430×
            bail!("no job {name:?} in the pipeline");
6440×
        }
645
    }
6462×
    if !only.is_empty() {
647
        loop {
6480×
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
6490×
            if more.is_empty() {
6500×
                break;
6510×
            }
6520×
            wanted.extend(more);
653
        }
6542×
    }
6552×
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
6562×
    let _ = std::fs::remove_dir_all(&scratch);
6572×
    std::fs::create_dir_all(scratch.join("tree"))?;
6582×
    workspace::copy_tree(dir, &scratch.join("tree"))?;
6592×
    let mut failed: BTreeSet<String> = BTreeSet::new();
6602×
    let mut worst = 0;
66112×
    for job in p.order() {
66212×
        if !only.is_empty() && !wanted.contains(&job.name) {
6630×
            continue;
66412×
        }
66512×
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
6660×
            println!("── {} skipped: {d} failed", job.name);
6670×
            failed.insert(job.name.clone());
6680×
            continue;
66912×
        }
67012×
        let sb = &p.sandboxes[&job.sandbox];
67112×
        println!("── {} ({})", job.name, job.exec.join(" "));
67212×
        let js = scratch.join(&job.name);
67312×
        std::fs::create_dir_all(&js)?;
67412×
        let job = &job
67512×
            .in_sandbox(sb)
67612×
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
67712×
            .with_flow_env(vars);
678
        // Identities come from a hub: a local run has none.
67912×
        for i in &job.identities {
6800×
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
6810×
        }
682
        // Each secret the job declares must be given, as the hub would.
68312×
        let inputs = job
68412×
            .secrets
68512×
            .iter()
68612×
            .map(|s| {
6870×
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
6880×
                value
6890×
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
6900×
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
6910×
            })
69212×
            .collect::<Result<Vec<_>>>()?;
693
        // Each job starts from the same files: jobs do not share writes.
69412×
        let out = if sb.runtime == Runtime::Wasm {
69512×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
69617×
            wasm::run(sb, job, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r))?
6970×
        } else if sb.runtime == Runtime::Syscall {
6980×
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
6990×
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
7000×
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
701
        } else {
7020×
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
7030×
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
704
        };
70512×
        let _ = workspace::remove_tree(&js);
70612×
        match out.exit_code {
7078×
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
7084×
            other => {
7094×
                println!(
710
                    "── {} failed ({}) in {} ms",
711
                    job.name,
7124×
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
713
                    out.duration_ms
714
                );
7154×
                failed.insert(job.name.clone());
7164×
                worst = 1;
717
            }
718
        }
719
    }
7202×
    let _ = workspace::remove_tree(&scratch);
7212×
    if worst != 0 {
7222×
        std::process::exit(worst);
7230×
    }
7240×
    Ok(())
7250×
}
726
72717×
fn print_record(r: &Record) {
72817×
    match r.stream.as_str() {
72917×
        "out" => println!("   {}", r.text),
73013×
        "err" => eprintln!("   {}", r.text),
73110×
        s => eprintln!("   [{s}] {}", r.text),
732
    }
73317×
}
734
735
#[cfg(test)]
736
mod tests {
737
    #[test]
7381×
    fn a_pipeline_newer_than_flow_is_named_as_such() {
7391×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 92: unknown output `sbom`; outputs are …");
7401×
        assert!(m.contains("does not know") && m.contains(env!("OXY_VERSION_LONG")) && m.contains("newer OxygenFlow"), "{m}");
7411×
        let m = super::not_valid(std::path::Path::new(".flow/pipeline.kdl"), "line 3: a job needs a sandbox");
7421×
        assert!(m.contains("is not valid") && !m.contains("newer"), "{m}");
7431×
    }
744
745
    use super::image_env_file;
746
747
    #[test]
7481×
    fn image_environments_are_checked_lines() {
7491×
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
7501×
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
7511×
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
7521×
        assert!(image_env_file(&["1X=y".into()]).is_err());
7531×
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
7541×
        assert_eq!(image_env_file(&[]).unwrap(), "");
7551×
    }
756
}