OXYGENHUB
# a67b97e9a717 oxygenflow / crates / flow / src / main.rs
11.0 KiB · Rust · last changed Job artifacts: output declarations, extraction and upload 1 month ago source blame history raw
e0918b88 Andy McCall 1
//! `flow`: check pipelines, run them locally, and run jobs for OxygenHub
2
//! (docs/spec.md, docs/m0.md).
3
4
mod cpio;
5
mod home;
6
mod microvm;
a67b97e9 Andy McCall ↶ 7
mod outputs;
e0918b88 Andy McCall 8
mod runner;
9
mod workspace;
10
11
use anyhow::{bail, Context, Result};
12
use clap::{Parser, Subcommand};
13
use flow_core::api::Record;
14
use flow_core::{Pipeline, Runtime, PIPELINE_PATH};
15
use home::Home;
16
use std::collections::BTreeSet;
17
use std::path::{Path, PathBuf};
18
use std::time::Duration;
19
20
#[derive(Parser)]
21
#[command(name = "flow", version, about = "OxygenFlow: hermetic pipelines for Oxygen repositories")]
22
struct Cli {
23
    /// The Flow home (default $FLOW_HOME, else ~/.local/share/flow).
24
    #[arg(long, global = true)]
25
    home: Option<PathBuf>,
26
    #[command(subcommand)]
27
    cmd: Cmd,
28
}
29
30
#[derive(Subcommand)]
31
enum Cmd {
32
    /// Validate a pipeline and print its jobs and hash
33
    Check {
34
        /// The pipeline file (default: .flow/pipeline.kdl)
35
        file: Option<PathBuf>,
36
    },
37
    /// Print a file's BLAKE3, for pinning in flow.toml
38
    Hash { file: PathBuf },
39
    /// Rootfs images for sandboxes
40
    Rootfs {
41
        #[command(subcommand)]
42
        cmd: RootfsCmd,
43
    },
44
    /// Run the pipeline on this directory's files, locally
45
    Run {
46
        /// Only these jobs (and what they depend on)
47
        jobs: Vec<String>,
48
        /// The directory to build (default: the current one)
49
        #[arg(long, default_value = ".")]
50
        dir: PathBuf,
51
        /// Minutes before a job is stopped
52
        #[arg(long, default_value_t = 60)]
53
        timeout: u64,
54
    },
55
    /// Claim and run jobs for the hub in flow.toml's [runner]
56
    Runner,
57
}
58
59
#[derive(Subcommand)]
60
enum RootfsCmd {
61
    /// Make an ext4 rootfs image from a root file system tarball and store it by hash
62
    Import {
63
        tarball: PathBuf,
64
        /// Refuse the tarball unless its SHA-256 matches (as its publisher states it)
65
        #[arg(long)]
66
        sha256: Option<String>,
a72abeee Andy McCall ↶ 67
        /// The image's own environment, NAME=value (repeatable): what a
68
        /// Dockerfile's ENV sets and `docker export` loses. Jobs start from
69
        /// it; their sandbox's and their own `env` override it
70
        #[arg(long = "env", value_name = "NAME=VALUE")]
71
        env: Vec<String>,
e0918b88 Andy McCall 72
    },
73
    /// List the images this home holds
74
    List,
75
}
76
77
fn main() {
78
    let cli = Cli::parse();
79
    if let Err(e) = run(cli) {
80
        eprintln!("flow: {e:#}");
81
        std::process::exit(1);
82
    }
83
}
84
85
fn run(cli: Cli) -> Result<()> {
86
    match cli.cmd {
87
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
88
        Cmd::Hash { file } => {
89
            println!("{}", home::hash_file(&file)?);
90
            Ok(())
91
        }
92
        Cmd::Rootfs { cmd } => {
93
            let home = Home::locate(cli.home.as_deref())?;
94
            match cmd {
a72abeee Andy McCall ↶ 95
                RootfsCmd::Import { tarball, sha256, env } => rootfs_import(&home, &tarball, sha256.as_deref(), &env),
e0918b88 Andy McCall 96
                RootfsCmd::List => {
97
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
98
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
99
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
100
                            println!("cas://blob/{h}  {} MiB", size >> 20);
101
                        }
102
                    }
103
                    Ok(())
104
                }
105
            }
106
        }
107
        Cmd::Run { jobs, dir, timeout } => {
108
            let home = Home::locate(cli.home.as_deref())?;
109
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60))
110
        }
111
        Cmd::Runner => {
112
            let home = Home::locate(cli.home.as_deref())?;
113
            // The runner's oxy state (identity, user config) stays in its home.
114
            if std::env::var_os("OXY_HOME").is_none() {
115
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
116
            }
117
            runner::serve(&home)
118
        }
119
    }
120
}
121
122
fn load(file: &Path) -> Result<Pipeline> {
123
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
124
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display()))
125
}
126
127
fn check(file: &Path) -> Result<()> {
128
    let p = load(file)?;
129
    let depths = p.depths();
130
    for j in p.order() {
131
        let sb = &p.sandboxes[&j.sandbox];
132
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
133
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
134
    }
135
    println!("pipeline {}", hex::encode(p.hash()));
136
    Ok(())
137
}
138
a72abeee Andy McCall ↶ 139
/// The image environment file flow-init reads (`/etc/flow/env`): one
140
/// `NAME=value` per line, names checked as a pipeline's are.
141
fn image_env_file(env: &[String]) -> Result<String> {
142
    let mut out = String::new();
143
    for e in env {
144
        let Some((k, v)) = e.split_once('=') else { bail!("--env {e:?}: expected NAME=value") };
145
        let ok = !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
146
        if !ok || v.contains('\n') || v.contains('\0') {
147
            bail!("--env {e:?}: a name is letters, digits and _, and a value is one line");
148
        }
149
        out.push_str(&format!("{k}={v}\n"));
150
    }
151
    Ok(out)
152
}
153
154
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>, env: &[String]) -> Result<()> {
155
    let env_file = image_env_file(env)?;
e0918b88 Andy McCall 156
    if let Some(want) = sha256 {
157
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
158
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
159
        if got != want.to_lowercase() {
160
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
161
        }
162
    }
163
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
164
    let _ = std::fs::remove_dir_all(&tmp);
165
    let tree = tmp.join("tree");
166
    std::fs::create_dir_all(&tree)?;
167
    let result = (|| -> Result<String> {
168
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
169
        if !status.success() {
170
            bail!("tar could not unpack {}", tarball.display());
171
        }
172
        // Mount points flow-init needs (docs/m0.md §2).
173
        for d in ["src", "tmp", "proc", "dev", "run"] {
174
            std::fs::create_dir_all(tree.join(d))?;
a72abeee Andy McCall ↶ 175
        }
176
        if !env_file.is_empty() {
177
            std::fs::create_dir_all(tree.join("etc/flow"))?;
178
            std::fs::write(tree.join("etc/flow/env"), &env_file)?;
e0918b88 Andy McCall 179
        }
180
        let used: u64 = ignore::WalkBuilder::new(&tree)
181
            .hidden(false)
182
            .ignore(false)
183
            .git_ignore(false)
184
            .build()
185
            .flatten()
186
            .filter_map(|e| e.metadata().ok())
187
            .map(|m| m.len().max(4096))
188
            .sum();
189
        let mib = used * 13 / 10 / (1 << 20) + 64;
190
        let img = tmp.join("rootfs.ext4");
191
        let status = std::process::Command::new("mkfs.ext4")
192
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
193
            .arg(&tree)
194
            .arg(&img)
195
            .arg(format!("{mib}M"))
196
            .status()
197
            .context("run mkfs.ext4")?;
198
        if !status.success() {
199
            bail!("mkfs.ext4 failed");
200
        }
201
        let hash = home::hash_file(&img)?;
202
        std::fs::rename(&img, home.rootfs(&hash))?;
203
        Ok(hash)
204
    })();
205
    let _ = std::fs::remove_dir_all(&tmp);
206
    let hash = result?;
207
    println!("rootfs \"cas://blob/{hash}\"");
208
    Ok(())
209
}
210
211
fn run_local(home: &Home, dir: &Path, only: &[String], timeout: Duration) -> Result<()> {
212
    let p = load(&dir.join(PIPELINE_PATH))?;
213
    // The named jobs and everything they depend on.
214
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
215
    for name in only {
216
        if !p.jobs.contains_key(name) {
217
            bail!("no job {name:?} in the pipeline");
218
        }
219
    }
220
    if !only.is_empty() {
221
        loop {
222
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
223
            if more.is_empty() {
224
                break;
225
            }
226
            wanted.extend(more);
227
        }
228
    }
229
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
230
    let _ = std::fs::remove_dir_all(&scratch);
231
    std::fs::create_dir_all(scratch.join("tree"))?;
232
    workspace::copy_tree(dir, &scratch.join("tree"))?;
233
    let mut failed: BTreeSet<String> = BTreeSet::new();
234
    let mut worst = 0;
235
    for job in p.order() {
236
        if !only.is_empty() && !wanted.contains(&job.name) {
237
            continue;
238
        }
239
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
240
            println!("── {} skipped: {d} failed", job.name);
241
            failed.insert(job.name.clone());
242
            continue;
243
        }
244
        let sb = &p.sandboxes[&job.sandbox];
245
        if sb.runtime != Runtime::Microvm {
246
            bail!("job {}: runtime {} is not available in this build yet", job.name, sb.runtime.as_str());
247
        }
248
        println!("── {} ({})", job.name, job.exec.join(" "));
249
        let js = scratch.join(&job.name);
250
        std::fs::create_dir_all(&js)?;
251
        // Each job starts from the same files: jobs do not share writes.
252
        workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
a72abeee Andy McCall ↶ 253
        let job = &job.in_sandbox(sb).with_flow_env(&[("FLOW_JOB".into(), job.name.clone()), ("FLOW_RUN".into(), "local".into())]);
e0918b88 Andy McCall 254
        let out = microvm::run(home, sb, job, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?;
255
        let _ = std::fs::remove_dir_all(&js);
256
        match out.exit_code {
257
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
258
            other => {
259
                println!(
260
                    "── {} failed ({}) in {} ms",
261
                    job.name,
262
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
263
                    out.duration_ms
264
                );
265
                failed.insert(job.name.clone());
266
                worst = 1;
267
            }
268
        }
269
    }
270
    let _ = std::fs::remove_dir_all(&scratch);
271
    if worst != 0 {
272
        std::process::exit(worst);
273
    }
274
    Ok(())
275
}
276
277
fn print_record(r: &Record) {
278
    match r.stream.as_str() {
279
        "out" => println!("   {}", r.text),
280
        "err" => eprintln!("   {}", r.text),
281
        s => eprintln!("   [{s}] {}", r.text),
a72abeee Andy McCall ↶ 282
    }
283
}
284
285
#[cfg(test)]
286
mod tests {
287
    use super::image_env_file;
288
289
    #[test]
290
    fn image_environments_are_checked_lines() {
291
        let f = image_env_file(&["PATH=/opt/bin:/usr/bin".into(), "X16EMU=/opt/x16emu".into(), "EMPTY=".into()]).unwrap();
292
        assert_eq!(f, "PATH=/opt/bin:/usr/bin\nX16EMU=/opt/x16emu\nEMPTY=\n");
293
        assert!(image_env_file(&["NOEQUALS".into()]).is_err());
294
        assert!(image_env_file(&["1X=y".into()]).is_err());
295
        assert!(image_env_file(&["X=two\nlines".into()]).is_err());
296
        assert_eq!(image_env_file(&[]).unwrap(), "");
e0918b88 Andy McCall 297
    }
298
}