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