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