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