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