OXYGENHUB
# f3b5b86e23ef oxygenflow / crates / flow / src / main.rs
31.0 KiB · Rust · last changed flow deps check: is every crate of a Cargo.lock in the image (closes #101) 1 day ago source blame history raw
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 {
112
    fn crates(&self) -> Result<BTreeSet<flow::deps::Crate>> {
113
        let read = |p: &Path| std::fs::read_to_string(p).with_context(|| p.display().to_string());
114
        if let Some(f) = &self.list {
115
            return Ok(flow::deps::from_list(&read(f)?));
116
        }
117
        if !self.locks.is_empty() {
118
            let mut all = BTreeSet::new();
119
            for l in &self.locks {
120
                all.extend(flow::deps::from_lock(&read(l)?).map_err(|e| anyhow::anyhow!("{}: {e}", l.display()))?);
121
            }
122
            return Ok(all);
123
        }
124
        // Inside a job: the image's own list, else its vendor directory.
125
        if self.vendor.is_none() && Path::new("/opt/crates.txt").is_file() {
126
            return Ok(flow::deps::from_list(&read(Path::new("/opt/crates.txt"))?));
127
        }
128
        let dir = self.vendor.clone().unwrap_or_else(|| PathBuf::from("/opt/vendor"));
129
        if self.vendor.is_none() && !dir.is_dir() {
130
            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");
131
        }
132
        flow::deps::from_vendor(&dir).map_err(|e| anyhow::anyhow!(e))
133
    }
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. Uses
227
    /// $OXY_TOKEN (a token that may write repositories) and $OXY_CA
228
    Push {
229
        /// The image's hash, as pipelines pin it (cas://blob/HASH)
230
        hash: String,
231
        /// The hub (default: 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. Uses $OXY_TOKEN and $OXY_CA
237
    Pull {
238
        hash: String,
239
        #[arg(long)]
240
        hub: Option<String>,
241
    },
242
}
243
244
fn main() {
245
    let cli = Cli::parse();
246
    if let Err(e) = run(cli) {
247
        eprintln!("flow: {e:#}");
248
        std::process::exit(1);
249
    }
250
}
251
252
fn run(cli: Cli) -> Result<()> {
253
    match cli.cmd {
254
        Cmd::Sandbox { spec } => std::process::exit(syscall::sandbox_main(&spec)),
255
        Cmd::SandboxProbe => std::process::exit(syscall::probe_main()),
256
        Cmd::Rename { from, to } => {
257
            flow::portable::rename(&from, &to).with_context(|| format!("renaming {} to {}", from.display(), to.display()))?;
258
            Ok(())
259
        }
260
        Cmd::Wasm { spec } => std::process::exit(wasm::wasm_main(&spec)),
261
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
262
        Cmd::Deps { cmd: DepsCmd::List { image } } => {
263
            print!("{}", flow::deps::render_list(&image.crates()?));
264
            Ok(())
265
        }
266
        Cmd::Deps { cmd: DepsCmd::Check { lock, image } } => {
267
            let text = std::fs::read_to_string(&lock).with_context(|| lock.display().to_string())?;
268
            let need = flow::deps::from_lock(&text).map_err(|e| anyhow::anyhow!("{}: {e}", lock.display()))?;
269
            let missing = flow::deps::missing(&need, &image.crates()?);
270
            if missing.is_empty() {
271
                println!("deps: all {} crates of {} are in the image", need.len(), lock.display());
272
                return Ok(());
273
            }
274
            eprintln!("deps: {} of {} crates of {} are not in the image:", missing.len(), need.len(), lock.display());
275
            for ((name, version), has) in &missing {
276
                let instead = match has.as_slice() {
277
                    [] => "the image has no version of it".to_string(),
278
                    vs => format!("the image has {}: cargo update -p {name}@{version} --precise {}", vs.join(", "), vs.last().unwrap()),
279
                };
280
                eprintln!("  {name} {version}  ({instead})");
281
            }
282
            eprintln!("pin a version the image has, or rebuild the image with this workspace's lock (images/rust/build.sh)");
283
            std::process::exit(1);
284
        }
285
        Cmd::Hash { file } => {
286
            println!("{}", home::hash_file(&file)?);
287
            Ok(())
288
        }
289
        Cmd::Rootfs { cmd } => {
290
            let home = Home::locate(cli.home.as_deref())?;
291
            match cmd {
292
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
293
                RootfsCmd::Push { hash, hub } => {
294
                    let client = image_client(&home, hub)?;
295
                    eprintln!("Sending image {} …", &hash[..12.min(hash.len())]);
296
                    let m = client.push(&home, &hash)?;
297
                    println!(
298
                        "Sent image {}: {} chunks the hub lacked, {} in {:.1} s",
299
                        &hash[..12],
300
                        m.chunks,
301
                        images::human(m.bytes),
302
                        m.elapsed.as_secs_f64()
303
                    );
304
                    Ok(())
305
                }
306
                RootfsCmd::Pull { hash, hub } => {
307
                    let client = image_client(&home, hub)?;
308
                    match client.fetch(&home, &hash)? {
309
                        Some(m) => {
310
                            println!(
311
                                "Fetched image {}: {} chunks, {} in {:.1} s",
312
                                &hash[..12],
313
                                m.chunks,
314
                                images::human(m.bytes),
315
                                m.elapsed.as_secs_f64()
316
                            );
317
                            Ok(())
318
                        }
319
                        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 => {
323
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
324
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
325
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
326
                            println!("cas://blob/{h}  {} MiB", size >> 20);
327
                        }
328
                    }
329
                    Ok(())
330
                }
331
            }
332
        }
333
        Cmd::Run { jobs, dir, timeout, vars, secrets } => {
334
            let home = Home::locate(cli.home.as_deref())?;
335
            let pairs = |what: &str, list: &[String]| {
336
                list.iter()
337
                    .map(|e| {
338
                        e.split_once('=')
339
                            .map(|(k, v)| (k.to_string(), v.to_string()))
340
                            .ok_or_else(|| anyhow::anyhow!("--{what} {e:?}: expected NAME=VALUE"))
341
                    })
342
                    .collect::<Result<Vec<_>>>()
343
            };
344
            let (vars, secrets) = (pairs("var", &vars)?, pairs("secret", &secrets)?);
345
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60), &vars, &secrets)
346
        }
347
        Cmd::Runner { cmd: Some(RunnerCmd::Bench) } => {
348
            let home = Home::locate(cli.home.as_deref())?;
349
            let (speed, ms) = facts::bench();
350
            let f = facts::now(&home, Some(speed));
351
            println!("speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
352
            println!("free disk {} MiB at {}", f.free_disk_mib.unwrap_or(0), home.root.display());
353
            match f.load_x100 {
354
                Some(l) => println!("load {:.2}", l as f64 / 100.0),
355
                None => println!("load not measured here"),
356
            }
357
            if let Some(k) = f.kernel {
358
                println!("kernel {k}");
359
            }
360
            Ok(())
361
        }
362
        Cmd::Runner { cmd: Some(RunnerCmd::Register { hub, token, name, ca, label }) } => {
363
            let home = Home::locate(cli.home.as_deref())?;
364
            if std::env::var_os("OXY_HOME").is_none() {
365
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
366
            }
367
            let name = name.unwrap_or_else(|| {
368
                std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).unwrap_or_else(|_| "flow".into())
369
            });
370
            let token = match token {
371
                Some(t) => t,
372
                None => {
373
                    eprintln!("Paste the registration token from the hub's Admin → Runners, then press Enter:");
374
                    let mut line = String::new();
375
                    std::io::stdin().read_line(&mut line)?;
376
                    line.trim().to_string()
377
                }
378
            };
379
            let got = runner::register(&home, &hub, &token, &name, ca, label)?;
380
            println!("registered as {} (runner {}); start it with `flow runner`", got.name, got.id);
381
            Ok(())
382
        }
383
        Cmd::Runner { cmd: Some(RunnerCmd::Drain) } => {
384
            let home = Home::locate(cli.home.as_deref())?;
385
            if flow::update::ask_to_drain(&home.root)? {
386
                println!("asked the runner to drain: it claims nothing more and stops once its jobs are done and reported");
387
            } else {
388
                println!("no runner of this home is running; the next one starts afresh");
389
            }
390
            Ok(())
391
        }
392
        Cmd::Runner { cmd: Some(RunnerCmd::Update { from, notice, dry_run, allow_older, exe }) } => {
393
            let home = Home::locate(cli.home.as_deref())?;
394
            let exe = match exe {
395
                Some(e) => e,
396
                None => std::env::current_exe().context("finding this flow binary")?,
397
            };
398
            let done = flow::update::install(&home, &exe, &from, Duration::from_secs(notice), dry_run, allow_older)?;
399
            if dry_run {
400
                println!(
401
                    "flow {} checks out: it would replace flow {} at {} (dry run: nothing changed)",
402
                    done.to,
403
                    done.from,
404
                    done.exe.display()
405
                );
406
                return Ok(());
407
            }
408
            println!("flow {} installed at {}; flow {} kept as {}", done.to, done.exe.display(), done.from, flow::update::PREV);
409
            match done.told {
410
                Some(pid) => println!("the runner (pid {pid}) leaves within {notice} s, then its unit starts flow {}", done.to),
411
                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
            }
417
            Ok(())
418
        }
419
        Cmd::Runner { cmd: None } => {
420
            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).
423
            if let flow::update::Start::RolledBack(p) = flow::update::on_start(&home.root)? {
424
                #[cfg(unix)]
425
                {
426
                    use std::os::unix::process::CommandExt;
427
                    let err = std::process::Command::new(&p.exe).args(std::env::args_os().skip(1)).exec();
428
                    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
                }
439
            }
440
            // The runner's oxy state (identity, user config) stays in its home.
441
            if std::env::var_os("OXY_HOME").is_none() {
442
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
443
            }
444
            runner::serve(&home)
445
        }
446
        Cmd::Tiers => {
447
            let home = Home::locate(cli.home.as_deref())?;
448
            match runner::tiers(&home) {
449
                Ok((have, missing)) => {
450
                    for t in have {
451
                        println!("{t}: available");
452
                    }
453
                    for why in missing {
454
                        println!("{}", why.replacen(": ", ": unavailable: ", 1));
455
                    }
456
                }
457
                Err(why) => println!("{why}"),
458
            }
459
            Ok(())
460
        }
461
        Cmd::Wait { url, state, timeout } => {
462
            let token = std::env::var("OXY_TOKEN").ok();
463
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
464
            let code =
465
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
466
            std::process::exit(code);
467
        }
468
    }
469
}
470
471
/// The hub image commands talk to: `--hub`, else the runner's; with
472
/// $OXY_TOKEN, else the runner's own token.
473
fn image_client(home: &Home, hub: Option<String>) -> Result<images::Client> {
474
    let runner = home.config.runner.clone();
475
    let hub = hub.or_else(|| runner.as_ref().map(|r| r.hub.clone())).context("name the hub with --hub https://HUB")?;
476
    let token = std::env::var("OXY_TOKEN")
477
        .ok()
478
        .or_else(|| runner.as_ref().map(|r| r.token.clone()))
479
        .context("set OXY_TOKEN to a token of yours on the hub")?;
480
    let ca = std::env::var_os("OXY_CA").map(PathBuf::from).or_else(|| runner.as_ref().and_then(|r| r.ca.clone()));
481
    images::Client::new(&hub, &token, ca.as_deref())
482
}
483
484
fn load(file: &Path) -> Result<Pipeline> {
485
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
486
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display()))
487
}
488
489
fn check(file: &Path) -> Result<()> {
490
    let p = load(file)?;
491
    let depths = p.depths();
492
    for j in p.order() {
493
        let sb = &p.sandboxes[&j.sandbox];
494
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
495
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
496
    }
497
    println!("pipeline {}", hex::encode(p.hash()));
498
    Ok(())
499
}
500
501
/// The image environment file flow-init reads (`/etc/flow/env`): one
502
/// `NAME=value` per line, names checked as a pipeline's are.
503
fn image_env_file(env: &[String]) -> Result<String> {
504
    let mut out = String::new();
505
    for e in env {
506
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
507
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
508
        if !ok || v.contains('\n') || v.contains('\0') {
509
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
510
        }
511
        out.push_str(&format!("{k}={v}\n"));
512
    }
513
    Ok(out)
514
}
515
516
/// The architecture an ELF file was built for, by its header.
517
fn elf_arch(path: &Path) -> Option<&'static str> {
518
    let bytes = std::fs::read(path).ok()?;
519
    if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" {
520
        return None;
521
    }
522
    let little = bytes[5] == 1;
523
    let machine = if little { u16::from_le_bytes([bytes[18], bytes[19]]) } else { u16::from_be_bytes([bytes[18], bytes[19]]) };
524
    Some(match machine {
525
        0x3E => "x86_64",
526
        0xB7 => "aarch64",
527
        0xF3 => "riscv64",
528
        0x03 => "x86",
529
        0x28 => "arm",
530
        0x15 => "powerpc64",
531
        0x16 => "s390x",
532
        _ => return None,
533
    })
534
}
535
536
/// The architecture of an unpacked rootfs: its shell's, or the first
537
/// program's found under bin.
538
fn tree_arch(tree: &Path) -> Option<&'static str> {
539
    for rel in ["bin/sh", "bin/busybox", "usr/bin/env", "bin/bash", "usr/bin/sh"] {
540
        let p = tree.join(rel);
541
        let p = std::fs::canonicalize(&p).unwrap_or(p);
542
        if let Some(a) = elf_arch(&p) {
543
            return Some(a);
544
        }
545
    }
546
    None
547
}
548
549
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
550
    let env_file = image_env_file(env)?;
551
    if let Some(want) = sha256 {
552
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
553
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
554
        if got != want.to_lowercase() {
555
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
556
        }
557
    }
558
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
559
    let _ = std::fs::remove_dir_all(&tmp);
560
    let tree = tmp.join("tree");
561
    std::fs::create_dir_all(&tree)?;
562
    let result = (|| -> Result<String> {
563
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
564
        if !status.success() {
565
            bail!("tar could not unpack {}", tarball.display());
566
        }
567
        // The image's architecture must be this machine's: there is no
568
        // emulation tier (spec §11.2).
569
        let arch = tree_arch(&tree).unwrap_or("unknown");
570
        if arch != "unknown" && arch != std::env::consts::ARCH {
571
            bail!(
572
                "{} is a {arch} image; this runner is {}, and jobs here run no other architecture",
573
                tarball.display(),
574
                std::env::consts::ARCH
575
            );
576
        }
577
        // Mount points flow-init needs (docs/m0.md §2).
578
        for d in ["src", "tmp", "proc", "dev", "run"] {
579
            std::fs::create_dir_all(tree.join(d))?;
580
        }
581
        if !env_file.is_empty() {
582
            std::fs::create_dir_all(tree.join("etc/flow"))?;
583
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
584
        }
585
        let used: u64 = ignore::WalkBuilder::new(&tree)
586
            .hidden(false)
587
            .ignore(false)
588
            .git_ignore(false)
589
            .build()
590
            .flatten()
591
            .filter_map(|e| e.metadata().ok())
592
            .map(|m| m.len().max(4096))
593
            .sum();
594
        let mib = used * 13 / 10 / (1 << 20) + 64;
595
        let img = tmp.join("rootfs.ext4");
596
        let status = std::process::Command::new("mkfs.ext4")
597
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
598
            .arg(&tree)
599
            .arg(&img)
600
            .arg(format!("{mib}M"))
601
            .status()
602
            .context("run mkfs.ext4")?;
603
        if !status.success() {
604
            bail!("mkfs.ext4 failed");
605
        }
606
        let hash = home::hash_file(&img)?;
607
        std::fs::rename(&img, home.rootfs(&hash))?;
608
        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) });
609
        std::fs::write(home.image_manifest(&hash), manifest.to_string())?;
610
        Ok(hash)
611
    })();
612
    let _ = std::fs::remove_dir_all(&tmp);
613
    let hash = result?;
614
    println!("rootfs \"cas://blob/{hash}\"");
615
    Ok(())
616
}
617
618
fn run_local(
619
    home: &Home,
620
    dir: &Path,
621
    only: &[String],
622
    timeout: Duration,
623
    vars: &[(String, String)],
624
    secrets: &[(String, String)],
625
) -> Result<()> {
626
    let p = load(&dir.join(PIPELINE_PATH))?;
627
    // The named jobs and everything they depend on.
628
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
629
    for name in only {
630
        if !p.jobs.contains_key(name) {
631
            bail!("no job {name:?} in the pipeline");
632
        }
633
    }
634
    if !only.is_empty() {
635
        loop {
636
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
637
            if more.is_empty() {
638
                break;
639
            }
640
            wanted.extend(more);
641
        }
642
    }
643
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
644
    let _ = std::fs::remove_dir_all(&scratch);
645
    std::fs::create_dir_all(scratch.join("tree"))?;
646
    workspace::copy_tree(dir, &scratch.join("tree"))?;
647
    let mut failed: BTreeSet<String> = BTreeSet::new();
648
    let mut worst = 0;
649
    for job in p.order() {
650
        if !only.is_empty() && !wanted.contains(&job.name) {
651
            continue;
652
        }
653
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
654
            println!("── {} skipped: {d} failed", job.name);
655
            failed.insert(job.name.clone());
656
            continue;
657
        }
658
        let sb = &p.sandboxes[&job.sandbox];
659
        println!("── {} ({})", job.name, job.exec.join(" "));
660
        let js = scratch.join(&job.name);
661
        std::fs::create_dir_all(&js)?;
662
        let job = &job
663
            .in_sandbox(sb)
664
            .with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())])
665
            .with_flow_env(vars);
666
        // Identities come from a hub: a local run has none.
667
        for i in &job.identities {
668
            println!("── {}: identity {:?} is not available locally; {} will be missing", job.name, i.audience, i.mount_path);
669
        }
670
        // Each secret the job declares must be given, as the hub would.
671
        let inputs = job
672
            .secrets
673
            .iter()
674
            .map(|s| {
675
                let value = secrets.iter().find(|(k, _)| *k == s.name).map(|(_, v)| v.clone());
676
                value
677
                    .map(|value| flow_core::api::SecretInput { name: s.name.clone(), path: s.mount_path.clone(), value })
678
                    .ok_or_else(|| anyhow::anyhow!("job {}: secret {:?} is not given; pass --secret {}=VALUE", job.name, s.name, s.name))
679
            })
680
            .collect::<Result<Vec<_>>>()?;
681
        // Each job starts from the same files: jobs do not share writes.
682
        let out = if sb.runtime == Runtime::Wasm {
683
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
684
            wasm::run(sb, job, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r))?
685
        } else if sb.runtime == Runtime::Syscall {
686
            workspace::copy_tree(&scratch.join("tree"), &js.join("tree"))?;
687
            let group = format!("local-{}-{}", std::process::id(), js.file_name().unwrap_or_default().to_string_lossy());
688
            syscall::run(home, sb, job, &inputs, &js.join("tree"), &js, timeout, &mut |r: Record| print_record(&r), &group)?
689
        } else {
690
            workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
691
            microvm::run(home, sb, job, &inputs, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?
692
        };
693
        let _ = workspace::remove_tree(&js);
694
        match out.exit_code {
695
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
696
            other => {
697
                println!(
698
                    "── {} failed ({}) in {} ms",
699
                    job.name,
700
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
701
                    out.duration_ms
702
                );
703
                failed.insert(job.name.clone());
704
                worst = 1;
705
            }
706
        }
707
    }
708
    let _ = workspace::remove_tree(&scratch);
709
    if worst != 0 {
710
        std::process::exit(worst);
711
    }
712
    Ok(())
713
}
714
715
fn print_record(r: &Record) {
716
    match r.stream.as_str() {
717
        "out" => println!("   {}", r.text),
718
        "err" => eprintln!("   {}", r.text),
719
        s => eprintln!("   [{s}] {}", r.text),
720
    }
721
}
722
723
#[cfg(test)]
724
mod tests {
725
    use super::image_env_file;
726
727
    #[test]
728
    fn image_environments_are_checked_lines() {
729
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
730
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
731
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
732
        assert!(image_env_file(&["1X=y".into()]).is_err());
733
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
734
        assert_eq!(image_env_file(&[]).unwrap(), "");
735
    }
736
}