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