OXYGENHUB
# 9e8f4a56630b oxygenflow / crates / flow / src / main.rs
10.0 KiB · Rust · last changed flow wait: follow the checks a push started on OxygenHub until they finish, against the repository's required checks; exit 0 passed, 1 failed, 2 at the time limit 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
    },
80
    /// List the images this home holds
81
    List,
82
}
83
84
fn main() {
85
    let cli = Cli::parse();
86
    if let Err(e) = run(cli) {
87
        eprintln!("flow: {e:#}");
88
        std::process::exit(1);
89
    }
90
}
91
92
fn run(cli: Cli) -> Result<()> {
93
    match cli.cmd {
94
        Cmd::Check { file } => check(&file.unwrap_or_else(|| PathBuf::from(PIPELINE_PATH))),
95
        Cmd::Hash { file } => {
96
            println!("{}", home::hash_file(&file)?);
97
            Ok(())
98
        }
99
        Cmd::Rootfs { cmd } => {
100
            let home = Home::locate(cli.home.as_deref())?;
101
            match cmd {
102
                RootfsCmd::Import { tarball, sha256 } => rootfs_import(&home, &tarball, sha256.as_deref()),
103
                RootfsCmd::List => {
104
                    for e in std::fs::read_dir(home.root.join("cas"))?.flatten() {
105
                        let size = e.metadata().map(|m| m.len()).unwrap_or(0);
106
                        if let Some(h) = e.file_name().to_string_lossy().strip_suffix(".ext4") {
107
                            println!("cas://blob/{h}  {} MiB", size >> 20);
108
                        }
109
                    }
110
                    Ok(())
111
                }
112
            }
113
        }
114
        Cmd::Run { jobs, dir, timeout } => {
115
            let home = Home::locate(cli.home.as_deref())?;
116
            run_local(&home, &dir, &jobs, Duration::from_secs(timeout * 60))
117
        }
118
        Cmd::Runner => {
119
            let home = Home::locate(cli.home.as_deref())?;
120
            // The runner's oxy state (identity, user config) stays in its home.
121
            if std::env::var_os("OXY_HOME").is_none() {
122
                std::env::set_var("OXY_HOME", home.root.join("oxy"));
123
            }
124
            runner::serve(&home)
125
        }
126
        Cmd::Wait { url, state, timeout } => {
127
            let token = std::env::var("OXY_TOKEN").ok();
128
            let ca = std::env::var_os("OXY_CA").map(PathBuf::from);
129
            let code =
130
                wait::wait(&url, &state, token.as_deref(), ca.as_deref(), Duration::from_secs(timeout * 60), Duration::from_secs(15))?;
131
            std::process::exit(code);
132
        }
133
    }
134
}
135
136
fn load(file: &Path) -> Result<Pipeline> {
137
    let src = std::fs::read_to_string(file).with_context(|| format!("read {}", file.display()))?;
138
    Pipeline::parse(&src).map_err(|p| anyhow::anyhow!("{} is not valid:\n{p}", file.display()))
139
}
140
141
fn check(file: &Path) -> Result<()> {
142
    let p = load(file)?;
143
    let depths = p.depths();
144
    for j in p.order() {
145
        let sb = &p.sandboxes[&j.sandbox];
146
        let after = if j.depends_on.is_empty() { String::new() } else { format!(" after {}", j.depends_on.join(", ")) };
147
        println!("{}{}  {} [{}]{after}", "  ".repeat(depths[j.name.as_str()]), j.name, j.exec.join(" "), sb.runtime.as_str());
148
    }
149
    println!("pipeline {}", hex::encode(p.hash()));
150
    Ok(())
151
}
152
153
fn rootfs_import(home: &Home, tarball: &Path, sha256: Option<&str>) -> Result<()> {
154
    if let Some(want) = sha256 {
155
        let out = std::process::Command::new("sha256sum").arg(tarball).output().context("run sha256sum")?;
156
        let got = String::from_utf8_lossy(&out.stdout).split_whitespace().next().unwrap_or("").to_string();
157
        if got != want.to_lowercase() {
158
            bail!("{} has SHA-256 {got}, expected {want}", tarball.display());
159
        }
160
    }
161
    let tmp = home.root.join("work").join(format!("rootfs-{}", std::process::id()));
162
    let _ = std::fs::remove_dir_all(&tmp);
163
    let tree = tmp.join("tree");
164
    std::fs::create_dir_all(&tree)?;
165
    let result = (|| -> Result<String> {
166
        let status = std::process::Command::new("tar").arg("-xf").arg(tarball).arg("-C").arg(&tree).arg("--no-same-owner").status()?;
167
        if !status.success() {
168
            bail!("tar could not unpack {}", tarball.display());
169
        }
170
        // Mount points flow-init needs (docs/m0.md §2).
171
        for d in ["src", "tmp", "proc", "dev", "run"] {
172
            std::fs::create_dir_all(tree.join(d))?;
173
        }
174
        let used: u64 = ignore::WalkBuilder::new(&tree)
175
            .hidden(false)
176
            .ignore(false)
177
            .git_ignore(false)
178
            .build()
179
            .flatten()
180
            .filter_map(|e| e.metadata().ok())
181
            .map(|m| m.len().max(4096))
182
            .sum();
183
        let mib = used * 13 / 10 / (1 << 20) + 64;
184
        let img = tmp.join("rootfs.ext4");
185
        let status = std::process::Command::new("mkfs.ext4")
186
            .args(["-q", "-F", "-L", "rootfs", "-E", "root_owner=0:0", "-d"])
187
            .arg(&tree)
188
            .arg(&img)
189
            .arg(format!("{mib}M"))
190
            .status()
191
            .context("run mkfs.ext4")?;
192
        if !status.success() {
193
            bail!("mkfs.ext4 failed");
194
        }
195
        let hash = home::hash_file(&img)?;
196
        std::fs::rename(&img, home.rootfs(&hash))?;
197
        Ok(hash)
198
    })();
199
    let _ = std::fs::remove_dir_all(&tmp);
200
    let hash = result?;
201
    println!("rootfs \"cas://blob/{hash}\"");
202
    Ok(())
203
}
204
205
fn run_local(home: &Home, dir: &Path, only: &[String], timeout: Duration) -> Result<()> {
206
    let p = load(&dir.join(PIPELINE_PATH))?;
207
    // The named jobs and everything they depend on.
208
    let mut wanted: BTreeSet<String> = only.iter().cloned().collect();
209
    for name in only {
210
        if !p.jobs.contains_key(name) {
211
            bail!("no job {name:?} in the pipeline");
212
        }
213
    }
214
    if !only.is_empty() {
215
        loop {
216
            let more: Vec<String> = wanted.iter().flat_map(|j| p.jobs[j].depends_on.clone()).filter(|d| !wanted.contains(d)).collect();
217
            if more.is_empty() {
218
                break;
219
            }
220
            wanted.extend(more);
221
        }
222
    }
223
    let scratch = home.root.join("work").join(format!("local-{}", std::process::id()));
224
    let _ = std::fs::remove_dir_all(&scratch);
225
    std::fs::create_dir_all(scratch.join("tree"))?;
226
    workspace::copy_tree(dir, &scratch.join("tree"))?;
227
    let mut failed: BTreeSet<String> = BTreeSet::new();
228
    let mut worst = 0;
229
    for job in p.order() {
230
        if !only.is_empty() && !wanted.contains(&job.name) {
231
            continue;
232
        }
233
        if let Some(d) = job.depends_on.iter().find(|d| failed.contains(*d)) {
234
            println!("── {} skipped: {d} failed", job.name);
235
            failed.insert(job.name.clone());
236
            continue;
237
        }
238
        let sb = &p.sandboxes[&job.sandbox];
239
        if sb.runtime != Runtime::Microvm {
240
            bail!("job {}: runtime {} is not available in this build yet", job.name, sb.runtime.as_str());
241
        }
242
        println!("── {} ({})", job.name, job.exec.join(" "));
243
        let js = scratch.join(&job.name);
244
        std::fs::create_dir_all(&js)?;
245
        // Each job starts from the same files: jobs do not share writes.
246
        workspace::image(&scratch.join("tree"), &js.join("workspace.ext4"))?;
247
        let out = microvm::run(home, sb, job, &js.join("workspace.ext4"), &js, timeout, &mut |r: Record| print_record(&r))?;
248
        let _ = std::fs::remove_dir_all(&js);
249
        match out.exit_code {
250
            Some(0) => println!("── {} passed in {} ms", job.name, out.duration_ms),
251
            other => {
252
                println!(
253
                    "── {} failed ({}) in {} ms",
254
                    job.name,
255
                    other.map(|c| format!("exit {c}")).unwrap_or_else(|| "no exit code".into()),
256
                    out.duration_ms
257
                );
258
                failed.insert(job.name.clone());
259
                worst = 1;
260
            }
261
        }
262
    }
263
    let _ = std::fs::remove_dir_all(&scratch);
264
    if worst != 0 {
265
        std::process::exit(worst);
266
    }
267
    Ok(())
268
}
269
270
fn print_record(r: &Record) {
271
    match r.stream.as_str() {
272
        "out" => println!("   {}", r.text),
273
        "err" => eprintln!("   {}", r.text),
274
        s => eprintln!("   [{s}] {}", r.text),
275
    }
276
}