OXYGENHUB
# e2c125610f43 oxygenflow / crates / flow-core / src / pipeline.rs
38.4 KiB · Rust · last changed Secrets mount as files: secret blocks, the claim's secrets, flow-init writes them 1 month ago source blame history raw
1
//! `.flow/pipeline.kdl`: the M0 subset of spec §3 (docs/m0.md §1), parsed
2
//! from KDL 2.0 and validated before anything runs. Every problem is
3
//! reported with its line, and all of them at once.
4
5
use serde::{Deserialize, Serialize};
6
use std::collections::{BTreeMap, BTreeSet};
7
use std::fmt;
8
9
/// Where a pipeline lives in the state being built.
10
pub const PIPELINE_PATH: &str = ".flow/pipeline.kdl";
11
12
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13
pub struct Pipeline {
14
    pub schema_version: u32,
15
    /// By name.
16
    pub sandboxes: BTreeMap<String, Sandbox>,
17
    /// By name.
18
    pub jobs: BTreeMap<String, Job>,
19
}
20
21
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
22
#[serde(rename_all = "lowercase")]
23
pub enum Runtime {
24
    /// Tier 0 (spec §4.1); refused in M0.
25
    Wasm,
26
    /// Tier 1 (spec §4.2): namespaces, Landlock, seccomp, cgroups.
27
    Syscall,
28
    /// Tier 2 (spec §4.3), the default.
29
    Microvm,
30
}
31
32
impl Runtime {
33
    pub fn as_str(self) -> &'static str {
34
        match self {
35
            Runtime::Wasm => "wasm",
36
            Runtime::Syscall => "syscall",
37
            Runtime::Microvm => "microvm",
38
        }
39
    }
40
}
41
42
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
43
#[serde(rename_all = "lowercase")]
44
pub enum Network {
45
    Isolated,
46
    Loopback,
47
    Egress,
48
}
49
50
impl Network {
51
    pub fn as_str(self) -> &'static str {
52
        match self {
53
            Network::Isolated => "isolated",
54
            Network::Loopback => "loopback",
55
            Network::Egress => "egress",
56
        }
57
    }
58
}
59
60
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61
pub struct Sandbox {
62
    pub name: String,
63
    pub runtime: Runtime,
64
    /// BLAKE3 of the rootfs image, hex.
65
    pub rootfs: String,
66
    pub memory_mib: u32,
67
    pub cpus: u32,
68
    pub network: Network,
69
    /// Environment every job in this sandbox starts from; a job's own `env`
70
    /// overrides it.
71
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72
    pub env: BTreeMap<String, String>,
73
    /// Labels a runner must have to run jobs here (`runs-on`), sorted.
74
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75
    pub runs_on: Vec<String>,
76
    /// How long each job here may run, in seconds (`timeout "2h"`), when
77
    /// the job does not say; the hub caps it at the site's maximum.
78
    #[serde(default, skip_serializing_if = "Option::is_none")]
79
    pub timeout_s: Option<u64>,
80
}
81
82
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83
pub struct Job {
84
    pub name: String,
85
    pub sandbox: String,
86
    /// Glob patterns over repository paths (spec §6.2).
87
    pub scope: Vec<String>,
88
    /// Sorted.
89
    pub depends_on: Vec<String>,
90
    pub env: BTreeMap<String, String>,
91
    /// Executed as is: no shell, no expansion (spec §2.2 I2).
92
    pub exec: Vec<String>,
93
    /// Ephemeral scratch mounts, sorted by target (spec §3.1 `mount`).
94
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95
    pub mounts: Vec<Mount>,
96
    /// Files the job produces, sorted by name (spec §5.2 `output`).
97
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
98
    pub outputs: Vec<Output>,
99
    /// Secrets the job mounts, sorted by name (spec §9 `secret`): the hub
100
    /// supplies each by name, the runner mounts it as a file.
101
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102
    pub secrets: Vec<Secret>,
103
    /// Labels a runner must have to take this job (`runs-on`), sorted;
104
    /// with its sandbox's, what the hub matches against a runner's.
105
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
106
    pub runs_on: Vec<String>,
107
    /// How long the job may run, in seconds (`timeout "90m"`); its
108
    /// sandbox's when absent, else the site's default (oxygenflow#23).
109
    #[serde(default, skip_serializing_if = "Option::is_none")]
110
    pub timeout_s: Option<u64>,
111
}
112
113
impl Job {
114
    /// The job's environment on top of its sandbox's: what it runs with.
115
    pub fn in_sandbox(&self, sandbox: &Sandbox) -> Job {
116
        let mut job = self.clone();
117
        for (k, v) in &sandbox.env {
118
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
119
        }
120
        job.runs_on.extend(sandbox.runs_on.iter().cloned());
121
        job.runs_on.sort();
122
        job.runs_on.dedup();
123
        job.timeout_s = job.timeout_s.or(sandbox.timeout_s);
124
        job
125
    }
126
127
    /// The job with variables that tell it what it builds (`FLOW_STATE`,
128
    /// `FLOW_BOOKMARK` …) added to its environment; a variable the pipeline
129
    /// sets itself keeps the pipeline's value.
130
    pub fn with_flow_env(&self, vars: &[(String, String)]) -> Job {
131
        let mut job = self.clone();
132
        for (k, v) in vars {
133
            job.env.entry(k.clone()).or_insert_with(|| v.clone());
134
        }
135
        job
136
    }
137
}
138
139
/// An ephemeral scratch mount: empty at the start of every job and gone
140
/// after it, so it cannot carry anything between jobs (spec §2.2 I4).
141
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
142
pub struct Mount {
143
    pub source: MountSource,
144
    /// An absolute path under `/src` or `/tmp`.
145
    pub target: String,
146
    pub size_mib: u32,
147
}
148
149
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
150
#[serde(rename_all = "lowercase")]
151
pub enum MountSource {
152
    /// `ephemeral://tmpfs`: memory in the sandbox, counted against its memory-limit.
153
    Tmpfs,
154
    /// `ephemeral://disk`: a fresh sparse disk on the runner, for large build trees.
155
    Disk,
156
}
157
158
impl MountSource {
159
    pub fn as_str(self) -> &'static str {
160
        match self {
161
            MountSource::Tmpfs => "ephemeral://tmpfs",
162
            MountSource::Disk => "ephemeral://disk",
163
        }
164
    }
165
}
166
167
/// A file a job produces (spec §5.2): read from the job's disks when it
168
/// ends, kept in the repository as a blob, and named by its receipt.
169
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
170
pub struct Output {
171
    /// The artifact's name, unique in the job.
172
    pub name: String,
173
    /// A clean absolute path under `/src`, not on a tmpfs mount.
174
    pub path: String,
175
}
176
177
/// A secret the job reads as a file (spec §9): never in the environment.
178
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
179
pub struct Secret {
180
    /// Which secret, as the hub names it; unique in the job.
181
    pub name: String,
182
    /// A clean absolute path under `/run/secrets/`, unique in the job;
183
    /// the file is 0400, the job's user's, on an in-memory mount.
184
    pub mount_path: String,
185
}
186
187
/// A secret's mount path: under `/run/secrets/`, no `.` or `..`.
188
pub fn secret_path_ok(p: &str) -> bool {
189
    p.strip_prefix("/run/secrets/").is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
190
}
191
192
/// Artifacts a job may declare.
193
pub const MAX_OUTPUTS: usize = 16;
194
195
/// Whether `p` is a clean absolute path strictly under `/src`, with nothing
196
/// a debugfs command line would have to quote.
197
fn output_path_ok(p: &str) -> bool {
198
    p.strip_prefix("/src/").is_some_and(|rest| {
199
        !rest.is_empty()
200
            && rest.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
201
            && p.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')
202
    })
203
}
204
205
/// Mounts a job may declare.
206
pub const MAX_MOUNTS: usize = 4;
207
/// The most secrets a job may mount.
208
pub const MAX_SECRETS: usize = 8;
209
/// Sizes a mount may have: 16 MiB to 64 GiB.
210
pub const MIN_MOUNT_MIB: u64 = 16;
211
pub const MAX_MOUNT_MIB: u64 = 64 * 1024;
212
213
/// Whether `t` is a clean absolute path strictly under `/src` or `/tmp`.
214
fn mount_target_ok(t: &str) -> bool {
215
    let under = t.strip_prefix("/src/").or_else(|| t.strip_prefix("/tmp/"));
216
    under.is_some_and(|rest| !rest.is_empty() && rest.split('/').all(|c| !c.is_empty() && c != "." && c != ".."))
217
}
218
219
/// One problem in a pipeline, at a 1-based line.
220
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
221
pub struct Problem {
222
    pub line: usize,
223
    pub message: String,
224
}
225
226
impl fmt::Display for Problem {
227
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228
        write!(f, "line {}: {}", self.line, self.message)
229
    }
230
}
231
232
/// Every problem found, in line order.
233
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
234
pub struct Problems(pub Vec<Problem>);
235
236
impl fmt::Display for Problems {
237
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238
        let lines: Vec<String> = self.0.iter().map(|p| p.to_string()).collect();
239
        f.write_str(&lines.join("\n"))
240
    }
241
}
242
243
const MIN_MEMORY_MIB: u64 = 64;
244
const MAX_MEMORY_MIB: u64 = 16 * 1024;
245
const MAX_CPUS: i128 = 16;
246
247
/// Nodes of the full spec that M0 recognises and refuses.
248
const LATER_TOP: &[&str] = &["publish", "secret"];
249
const LATER_JOB: &[&str] = &["attest"];
250
251
struct Ctx<'a> {
252
    src: &'a str,
253
    problems: Vec<Problem>,
254
}
255
256
impl Ctx<'_> {
257
    fn line(&self, span: SourceSpan) -> usize {
258
        let at = span.offset().min(self.src.len());
259
        self.src[..at].bytes().filter(|b| *b == b'\n').count() + 1
260
    }
261
262
    fn err(&mut self, span: SourceSpan, message: impl Into<String>) {
263
        let line = self.line(span);
264
        self.problems.push(Problem { line, message: message.into() });
265
    }
266
267
    /// The node's arguments as strings; properties and other types are errors.
268
    fn strings(&mut self, node: &KdlNode) -> Vec<String> {
269
        let mut out = Vec::new();
270
        for e in node.entries() {
271
            if let Some(k) = e.name() {
272
                self.err(e.span(), format!("`{}` takes no property `{}`", node.name().value(), k.value()));
273
                continue;
274
            }
275
            match e.value() {
276
                KdlValue::String(s) => out.push(s.clone()),
277
                other => self.err(e.span(), format!("`{}` takes strings, not {}", node.name().value(), kind_of(other))),
278
            }
279
        }
280
        out
281
    }
282
283
    /// Exactly one string argument.
284
    fn one_string(&mut self, node: &KdlNode) -> Option<String> {
285
        let v = self.strings(node);
286
        if v.len() != 1 {
287
            self.err(node.span(), format!("`{}` takes one string", node.name().value()));
288
            return None;
289
        }
290
        v.into_iter().next()
291
    }
292
293
    fn one_integer(&mut self, node: &KdlNode) -> Option<i128> {
294
        match node.entries() {
295
            [e] if e.name().is_none() => match e.value() {
296
                KdlValue::Integer(n) => Some(*n),
297
                other => {
298
                    self.err(e.span(), format!("`{}` takes an integer, not {}", node.name().value(), kind_of(other)));
299
                    None
300
                }
301
            },
302
            _ => {
303
                self.err(node.span(), format!("`{}` takes one integer", node.name().value()));
304
                None
305
            }
306
        }
307
    }
308
309
    fn no_children(&mut self, node: &KdlNode) {
310
        if node.children().is_some() {
311
            self.err(node.span(), format!("`{}` takes no block", node.name().value()));
312
        }
313
    }
314
315
    fn name_ok(&mut self, span: SourceSpan, what: &str, name: &str) -> bool {
316
        let ok = !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
317
        if !ok {
318
            self.err(span, format!("{what} name {name:?} must be 1 to 64 of A-Z a-z 0-9 . _ -"));
319
        }
320
        ok
321
    }
322
}
323
324
use kdl::{KdlDocument, KdlNode, KdlValue};
325
use miette::SourceSpan;
326
327
fn kind_of(v: &KdlValue) -> &'static str {
328
    match v {
329
        KdlValue::String(_) => "a string",
330
        KdlValue::Integer(_) => "an integer",
331
        KdlValue::Float(_) => "a number",
332
        KdlValue::Bool(_) => "a boolean",
333
        KdlValue::Null => "null",
334
    }
335
}
336
337
/// `"512MiB"`, `"4GiB"`, `"65536KiB"` to MiB.
338
fn parse_memory(s: &str) -> Option<u64> {
339
    let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit())?);
340
    let n: u64 = num.parse().ok()?;
341
    let mib = match unit {
342
        "KiB" => n.is_multiple_of(1024).then_some(n / 1024)?,
343
        "MiB" => n,
344
        "GiB" => n.checked_mul(1024)?,
345
        _ => return None,
346
    };
347
    Some(mib)
348
}
349
350
/// The line of the first escape KDL 2.0 does not have but shells and C
351
/// do (`\0NN`, `\e`, `\xNN`), as someone colouring output writes them.
352
fn foreign_escape_line(src: &str) -> Option<usize> {
353
    src.lines()
354
        .position(|l| {
355
            let b = l.as_bytes();
356
            b.windows(2).enumerate().any(|(i, w)| {
357
                w[0] == b'\\'
358
                    && (i == 0 || b[i - 1] != b'\\')
359
                    && (w[1] == b'e' || w[1] == b'x' || (w[1] == b'0' && b.get(i + 2).is_some_and(u8::is_ascii_digit)))
360
            })
361
        })
362
        .map(|i| i + 1)
363
}
364
365
impl Pipeline {
366
    /// Parse and validate a pipeline document.
367
    pub fn parse(src: &str) -> Result<Pipeline, Problems> {
368
        let doc = match KdlDocument::parse_v2(src) {
369
            Ok(d) => d,
370
            Err(e) => {
371
                let mut ctx = Ctx { src, problems: Vec::new() };
372
                for d in &e.diagnostics {
373
                    let msg = d.message.clone().or_else(|| d.label.clone()).unwrap_or_else(|| "not valid KDL 2.0".into());
374
                    ctx.err(d.span, msg);
375
                }
376
                if ctx.problems.is_empty() {
377
                    ctx.problems.push(Problem { line: 1, message: "not valid KDL 2.0".into() });
378
                }
379
                if let Some(line) = foreign_escape_line(src) {
380
                    ctx.problems.push(Problem {
381
                        line,
382
                        message: "KDL strings have no \\033, \\e or \\x escapes: write ESC (for ANSI colours) as \\u{1b}".into(),
383
                    });
384
                }
385
                return Err(Problems(ctx.problems));
386
            }
387
        };
388
        let mut ctx = Ctx { src, problems: Vec::new() };
389
        let mut schema = None;
390
        let mut sandboxes = BTreeMap::new();
391
        let mut jobs: BTreeMap<String, (Job, SourceSpan)> = BTreeMap::new();
392
        for node in doc.nodes() {
393
            match node.name().value() {
394
                "schema-version" => {
395
                    ctx.no_children(node);
396
                    match ctx.one_integer(node) {
397
                        Some(1) => schema = Some(1),
398
                        Some(n) => ctx.err(node.span(), format!("schema-version {n} is not supported; this runner reads 1")),
399
                        None => {}
400
                    }
401
                }
402
                "sandbox" => {
403
                    if let Some(sb) = parse_sandbox(&mut ctx, node) {
404
                        if sandboxes.contains_key(&sb.name) {
405
                            ctx.err(node.span(), format!("sandbox {:?} is declared twice", sb.name));
406
                        } else {
407
                            sandboxes.insert(sb.name.clone(), sb);
408
                        }
409
                    }
410
                }
411
                "job" => {
412
                    if let Some(job) = parse_job(&mut ctx, node) {
413
                        if jobs.contains_key(&job.name) {
414
                            ctx.err(node.span(), format!("job {:?} is declared twice", job.name));
415
                        } else {
416
                            jobs.insert(job.name.clone(), (job, node.span()));
417
                        }
418
                    }
419
                }
420
                n if LATER_TOP.contains(&n) => ctx.err(node.span(), format!("`{n}` is not in M0 yet")),
421
                n => ctx.err(node.span(), format!("unknown node `{n}`; expected schema-version, sandbox or job")),
422
            }
423
        }
424
        if schema.is_none() && !ctx.problems.iter().any(|p| p.message.contains("schema-version")) {
425
            ctx.problems.push(Problem { line: 1, message: "`schema-version 1` is required".into() });
426
        }
427
        if jobs.is_empty() && ctx.problems.is_empty() {
428
            ctx.problems.push(Problem { line: 1, message: "a pipeline needs at least one job".into() });
429
        }
430
        // References and cycles.
431
        for (job, span) in jobs.values() {
432
            if !job.sandbox.is_empty() && !sandboxes.contains_key(&job.sandbox) {
433
                ctx.err(*span, format!("job {:?} uses sandbox {:?}, which is not declared", job.name, job.sandbox));
434
            }
435
            for d in &job.depends_on {
436
                if !jobs.contains_key(d) {
437
                    ctx.err(*span, format!("job {:?} depends on {:?}, which is not declared", job.name, d));
438
                } else if d == &job.name {
439
                    ctx.err(*span, format!("job {:?} depends on itself", job.name));
440
                }
441
            }
442
        }
443
        let graph: BTreeMap<&str, Vec<&str>> =
444
            jobs.values().map(|(j, _)| (j.name.as_str(), j.depends_on.iter().map(String::as_str).collect())).collect();
445
        if let Some(cycle) = find_cycle(&graph) {
446
            let span = jobs[cycle[0]].1;
447
            ctx.err(span, format!("jobs depend on each other in a cycle: {}", cycle.join(" → ")));
448
        }
449
        if !ctx.problems.is_empty() {
450
            ctx.problems.sort_by_key(|p| p.line);
451
            return Err(Problems(ctx.problems));
452
        }
453
        Ok(Pipeline { schema_version: 1, sandboxes, jobs: jobs.into_iter().map(|(k, (j, _))| (k, j)).collect() })
454
    }
455
456
    /// Jobs in an order where each comes after what it depends on (ties by name).
457
    pub fn order(&self) -> Vec<&Job> {
458
        let mut done: BTreeSet<&str> = BTreeSet::new();
459
        let mut out = Vec::with_capacity(self.jobs.len());
460
        while out.len() < self.jobs.len() {
461
            let before = out.len();
462
            for j in self.jobs.values() {
463
                if !done.contains(j.name.as_str()) && j.depends_on.iter().all(|d| done.contains(d.as_str())) {
464
                    out.push(j);
465
                }
466
            }
467
            for j in &out[before..] {
468
                done.insert(j.name.as_str());
469
            }
470
            if out.len() == before {
471
                break; // validated pipelines have no cycles
472
            }
473
        }
474
        out
475
    }
476
477
    /// Each job's depth: 0 without dependencies, else one more than its deepest dependency.
478
    pub fn depths(&self) -> BTreeMap<&str, usize> {
479
        let mut depth: BTreeMap<&str, usize> = BTreeMap::new();
480
        for j in self.order() {
481
            let d = j.depends_on.iter().map(|x| depth.get(x.as_str()).copied().unwrap_or(0) + 1).max().unwrap_or(0);
482
            depth.insert(j.name.as_str(), d);
483
        }
484
        depth
485
    }
486
}
487
488
fn find_cycle<'a>(graph: &BTreeMap<&'a str, Vec<&'a str>>) -> Option<Vec<&'a str>> {
489
    #[derive(Clone, Copy, PartialEq)]
490
    enum Mark {
491
        Visiting,
492
        Done,
493
    }
494
    fn visit<'a>(
495
        n: &'a str,
496
        graph: &BTreeMap<&'a str, Vec<&'a str>>,
497
        marks: &mut BTreeMap<&'a str, Mark>,
498
        stack: &mut Vec<&'a str>,
499
    ) -> Option<Vec<&'a str>> {
500
        match marks.get(n) {
501
            Some(Mark::Done) => return None,
502
            Some(Mark::Visiting) => {
503
                let at = stack.iter().position(|s| *s == n).unwrap_or(0);
504
                let mut c = stack[at..].to_vec();
505
                c.push(n);
506
                return Some(c);
507
            }
508
            None => {}
509
        }
510
        marks.insert(n, Mark::Visiting);
511
        stack.push(n);
512
        for d in graph.get(n).into_iter().flatten() {
513
            if graph.contains_key(d) && *d != n {
514
                if let Some(c) = visit(d, graph, marks, stack) {
515
                    return Some(c);
516
                }
517
            }
518
        }
519
        stack.pop();
520
        marks.insert(n, Mark::Done);
521
        None
522
    }
523
    let mut marks = BTreeMap::new();
524
    for n in graph.keys() {
525
        let mut stack = Vec::new();
526
        if let Some(c) = visit(n, graph, &mut marks, &mut stack) {
527
            return Some(c);
528
        }
529
    }
530
    None
531
}
532
533
fn block<'a>(ctx: &mut Ctx, node: &'a KdlNode) -> &'a [KdlNode] {
534
    match node.children() {
535
        Some(d) => d.nodes(),
536
        None => {
537
            ctx.err(node.span(), format!("`{}` needs a block {{ … }}", node.name().value()));
538
            &[]
539
        }
540
    }
541
}
542
543
fn parse_sandbox(ctx: &mut Ctx, node: &KdlNode) -> Option<Sandbox> {
544
    let name = ctx.one_string(node)?;
545
    let named = ctx.name_ok(node.span(), "sandbox", &name);
546
    let (mut runtime, mut rootfs, mut memory, mut cpus, mut network) =
547
        (Some(Runtime::Microvm), None, Some(1024u32), Some(1u32), Some(Network::Isolated));
548
    let mut seen = BTreeSet::new();
549
    let mut env = BTreeMap::new();
550
    let mut runs_on = Vec::new();
551
    let mut timeout_s = None;
552
    for c in block(ctx, node) {
553
        let key = c.name().value();
554
        if key != "runs-on" && !seen.insert(key.to_string()) {
555
            ctx.err(c.span(), format!("`{key}` is given twice"));
556
        }
557
        if key == "env" {
558
            parse_env(ctx, c, &mut env);
559
            continue;
560
        }
561
        if key == "runs-on" {
562
            ctx.no_children(c);
563
            parse_labels(ctx, c, &mut runs_on);
564
            continue;
565
        }
566
        ctx.no_children(c);
567
        match key {
568
            "runtime" => {
569
                runtime = match ctx.one_string(c).as_deref() {
570
                    Some("microvm") => Some(Runtime::Microvm),
571
                    Some("syscall") | Some("gvisor") => Some(Runtime::Syscall),
572
                    Some("wasm") => {
573
                        ctx.err(c.span(), "runtime \"wasm\" is not in M0 yet; use \"microvm\" or \"syscall\"");
574
                        None
575
                    }
576
                    Some(other) => {
577
                        ctx.err(c.span(), format!("runtime {other:?}: expected \"microvm\", \"syscall\" or \"wasm\""));
578
                        None
579
                    }
580
                    None => None,
581
                }
582
            }
583
            "rootfs" => {
584
                rootfs = match ctx.one_string(c) {
585
                    Some(r) => match r.strip_prefix("cas://blob/") {
586
                        Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) => {
587
                            Some(h.to_string())
588
                        }
589
                        _ => {
590
                            ctx.err(c.span(), format!("rootfs {r:?}: expected \"cas://blob/\" and 64 lower-case hex digits"));
591
                            None
592
                        }
593
                    },
594
                    None => None,
595
                }
596
            }
597
            "memory-limit" => {
598
                memory = match ctx.one_string(c) {
599
                    Some(m) => match parse_memory(&m) {
600
                        Some(mib) if (MIN_MEMORY_MIB..=MAX_MEMORY_MIB).contains(&mib) => Some(mib as u32),
601
                        Some(_) => {
602
                            ctx.err(c.span(), format!("memory-limit {m:?} must be from 64MiB to 16GiB"));
603
                            None
604
                        }
605
                        None => {
606
                            ctx.err(c.span(), format!("memory-limit {m:?}: expected a whole number of KiB, MiB or GiB, as \"4GiB\""));
607
                            None
608
                        }
609
                    },
610
                    None => None,
611
                }
612
            }
613
            "cpu-limit" => {
614
                cpus = match ctx.one_integer(c) {
615
                    Some(n) if (1..=MAX_CPUS).contains(&n) => Some(n as u32),
616
                    Some(n) => {
617
                        ctx.err(c.span(), format!("cpu-limit {n} must be from 1 to {MAX_CPUS}"));
618
                        None
619
                    }
620
                    None => None,
621
                }
622
            }
623
            "network" => {
624
                network = match ctx.one_string(c).as_deref() {
625
                    Some("isolated") => Some(Network::Isolated),
626
                    // Loopback only: the guest's `lo` comes up, and it still has
627
                    // no device that reaches anything outside it.
628
                    Some("loopback") => Some(Network::Loopback),
629
                    Some("egress") => {
630
                        ctx.err(c.span(), "network \"egress\" is not in M0; M0 has \"isolated\" and \"loopback\"");
631
                        None
632
                    }
633
                    Some(other) => {
634
                        ctx.err(c.span(), format!("network {other:?}: expected \"isolated\", \"loopback\" or \"egress\""));
635
                        None
636
                    }
637
                    None => None,
638
                }
639
            }
640
            "timeout" => timeout_s = parse_timeout(ctx, c),
641
            other => ctx.err(c.span(), format!("unknown sandbox setting `{other}`")),
642
        }
643
    }
644
    if rootfs.is_none() && !seen.contains("rootfs") {
645
        ctx.err(node.span(), format!("sandbox {name:?} needs a rootfs"));
646
    }
647
    if !named {
648
        return None;
649
    }
650
    Some(Sandbox { name, runtime: runtime?, rootfs: rootfs?, memory_mib: memory?, cpus: cpus?, network: network?, env, runs_on, timeout_s })
651
}
652
653
/// The longest a pipeline may ask a job to run.
654
pub const MAX_TIMEOUT_S: u64 = 24 * 3600;
655
656
/// A duration: whole hours, minutes and seconds in that order, each
657
/// optional, as "90m", "2h", "1h30m" or "45s".
658
pub fn parse_duration(s: &str) -> Option<u64> {
659
    let (mut total, mut num, mut last) = (0u64, String::new(), 0u8);
660
    for ch in s.chars() {
661
        if ch.is_ascii_digit() {
662
            num.push(ch);
663
            continue;
664
        }
665
        let (unit, mult) = match ch {
666
            'h' => (1, 3600),
667
            'm' => (2, 60),
668
            's' => (3, 1),
669
            _ => return None,
670
        };
671
        // Each unit once, largest first, each with its number.
672
        if num.is_empty() || unit <= last {
673
            return None;
674
        }
675
        last = unit;
676
        total = total.checked_add(num.parse::<u64>().ok()?.checked_mul(mult)?)?;
677
        num.clear();
678
    }
679
    (num.is_empty() && total > 0).then_some(total)
680
}
681
682
/// A `timeout` line: one duration, from a minute to a day.
683
fn parse_timeout(ctx: &mut Ctx, c: &KdlNode) -> Option<u64> {
684
    let t = ctx.one_string(c)?;
685
    match parse_duration(&t) {
686
        Some(secs) if (60..=MAX_TIMEOUT_S).contains(&secs) => Some(secs),
687
        Some(_) => {
688
            ctx.err(c.span(), format!("timeout {t:?} must be from 1m to 24h"));
689
            None
690
        }
691
        None => {
692
            ctx.err(c.span(), format!("timeout {t:?}: expected hours, minutes and seconds, as \"90m\" or \"1h30m\""));
693
            None
694
        }
695
    }
696
}
697
698
/// The labels of a `runs-on` line: lower-case letters, digits, `-`, `_`
699
/// and `.`, at most 64 bytes each; into `into`, sorted, once each.
700
fn parse_labels(ctx: &mut Ctx, c: &KdlNode, into: &mut Vec<String>) {
701
    let labels = ctx.strings(c);
702
    if labels.is_empty() {
703
        ctx.err(c.span(), "`runs-on` needs one or more labels, as runs-on \"riscv64\"");
704
    }
705
    for l in labels {
706
        let ok = !l.is_empty()
707
            && l.len() <= 64
708
            && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_' | b'.'));
709
        if ok {
710
            into.push(l);
711
        } else {
712
            ctx.err(c.span(), format!("runs-on {l:?}: a label is lower-case letters, digits, -, _ and ., at most 64"));
713
        }
714
    }
715
    into.sort();
716
    into.dedup();
717
}
718
719
/// An `env` block of `NAME "value"` lines, into `env`.
720
fn parse_env(ctx: &mut Ctx, c: &KdlNode, env: &mut BTreeMap<String, String>) {
721
    if !c.entries().is_empty() {
722
        ctx.err(c.span(), "`env` takes a block of NAME \"value\" lines");
723
    }
724
    for e in block(ctx, c) {
725
        let k = e.name().value().to_string();
726
        let valid =
727
            !k.is_empty() && !k.starts_with(|c: char| c.is_ascii_digit()) && k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
728
        if !valid {
729
            ctx.err(e.span(), format!("environment name {k:?} must be letters, digits and _"));
730
            continue;
731
        }
732
        ctx.no_children(e);
733
        if let Some(v) = ctx.one_string(e) {
734
            if env.insert(k.clone(), v).is_some() {
735
                ctx.err(e.span(), format!("environment {k} is set twice"));
736
            }
737
        }
738
    }
739
}
740
741
/// `mount { source "ephemeral://disk"; target "/src/target"; size "8GiB" }`.
742
fn parse_mount(ctx: &mut Ctx, node: &KdlNode) -> Option<Mount> {
743
    let (mut source, mut target, mut size) = (None, None, None);
744
    let mut seen = BTreeSet::new();
745
    for c in block(ctx, node) {
746
        let key = c.name().value();
747
        if !seen.insert(key.to_string()) {
748
            ctx.err(c.span(), format!("`{key}` is given twice"));
749
            continue;
750
        }
751
        ctx.no_children(c);
752
        match key {
753
            "source" => {
754
                source = match ctx.one_string(c).as_deref() {
755
                    Some("ephemeral://tmpfs") => Some(MountSource::Tmpfs),
756
                    Some("ephemeral://disk") => Some(MountSource::Disk),
757
                    Some(other) => {
758
                        ctx.err(
759
                            c.span(),
760
                            format!("mount source {other:?} is not in M0 yet; M0 mounts \"ephemeral://tmpfs\" or \"ephemeral://disk\""),
761
                        );
762
                        None
763
                    }
764
                    None => None,
765
                }
766
            }
767
            "target" => {
768
                target = match ctx.one_string(c) {
769
                    Some(t) if mount_target_ok(&t) => Some(t),
770
                    Some(t) => {
771
                        ctx.err(
772
                            c.span(),
773
                            format!("mount target {t:?} must be an absolute path under /src or /tmp, without . or .. or a trailing /"),
774
                        );
775
                        None
776
                    }
777
                    None => None,
778
                }
779
            }
780
            "size" => {
781
                size = match ctx.one_string(c) {
782
                    Some(m) => match parse_memory(&m) {
783
                        Some(mib) if (MIN_MOUNT_MIB..=MAX_MOUNT_MIB).contains(&mib) => Some(mib as u32),
784
                        Some(_) => {
785
                            ctx.err(c.span(), format!("mount size {m:?} must be from 16MiB to 64GiB"));
786
                            None
787
                        }
788
                        None => {
789
                            ctx.err(c.span(), format!("mount size {m:?}: expected a whole number of KiB, MiB or GiB, as \"8GiB\""));
790
                            None
791
                        }
792
                    },
793
                    None => None,
794
                }
795
            }
796
            "readonly" | "include" => ctx.err(c.span(), format!("mount `{key}` is not in M0 yet")),
797
            other => ctx.err(c.span(), format!("unknown mount setting `{other}`")),
798
        }
799
    }
800
    for (name, missing) in [("source", source.is_none()), ("target", target.is_none()), ("size", size.is_none())] {
801
        if missing && !seen.contains(name) {
802
            ctx.err(node.span(), format!("a mount needs a {name}"));
803
        }
804
    }
805
    Some(Mount { source: source?, target: target?, size_mib: size? })
806
}
807
808
/// `output { artifact "name" { path "/src/target/release/tool" } }`.
809
/// `secret "deploy-token" { mount-path "/run/secrets/token" }` (spec §9.1).
810
/// The hub is the vault: the secret of that name set for the repository,
811
/// its organisation or the site. `vault-ref` is not in this slice.
812
fn parse_secret(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
813
    let Some(name) = ctx.one_string(node) else {
814
        ctx.err(node.span(), "`secret` takes a name and a block with mount-path");
815
        return;
816
    };
817
    if !ctx.name_ok(node.span(), "secret", &name) {
818
        return;
819
    }
820
    let mut path = None;
821
    for c in block(ctx, node) {
822
        ctx.no_children(c);
823
        match c.name().value() {
824
            "mount-path" => match ctx.one_string(c) {
825
                Some(p) if secret_path_ok(&p) => path = Some(p),
826
                Some(p) => {
827
                    ctx.err(c.span(), format!("secret mount-path {p:?} must be an absolute path under /run/secrets/, without . or .."))
828
                }
829
                None => {}
830
            },
831
            "vault-ref" => ctx.err(c.span(), "`vault-ref` is not in M0; the hub supplies the secret of that name"),
832
            other => ctx.err(c.span(), format!("unknown secret setting `{other}`")),
833
        }
834
    }
835
    let Some(mount_path) = path else {
836
        ctx.err(node.span(), format!("secret {name:?} needs a mount-path"));
837
        return;
838
    };
839
    if job.secrets.iter().any(|s| s.name == name) {
840
        ctx.err(node.span(), format!("secret {name:?} is given twice"));
841
    } else if job.secrets.iter().any(|s| s.mount_path == mount_path) {
842
        ctx.err(node.span(), format!("two secrets mount at {mount_path:?}"));
843
    } else if job.secrets.len() == MAX_SECRETS {
844
        ctx.err(node.span(), format!("a job has at most {MAX_SECRETS} secrets"));
845
    } else {
846
        job.secrets.push(Secret { name, mount_path });
847
    }
848
}
849
850
fn parse_output(ctx: &mut Ctx, node: &KdlNode, job: &mut Job) {
851
    if !node.entries().is_empty() {
852
        ctx.err(node.span(), "`output` takes a block of artifacts");
853
    }
854
    for a in block(ctx, node) {
855
        if a.name().value() != "artifact" {
856
            ctx.err(a.span(), format!("unknown output `{}`; outputs are `artifact \"name\" {{ path \"/src/…\" }}`", a.name().value()));
857
            continue;
858
        }
859
        let Some(name) = ctx.one_string(a) else { continue };
860
        if !ctx.name_ok(a.span(), "artifact", &name) {
861
            continue;
862
        }
863
        let mut path = None;
864
        for c in block(ctx, a) {
865
            ctx.no_children(c);
866
            match c.name().value() {
867
                "path" => match ctx.one_string(c) {
868
                    Some(p) if output_path_ok(&p) => path = Some(p),
869
                    Some(p) => ctx.err(
870
                        c.span(),
871
                        format!("artifact path {p:?} must be an absolute path under /src, without . or .., quotes or spaces"),
872
                    ),
873
                    None => {}
874
                },
875
                "format" => {
876
                    if ctx.one_string(c).as_deref() != Some("blob") {
877
                        ctx.err(c.span(), "artifact format is \"blob\"");
878
                    }
879
                }
880
                other => ctx.err(c.span(), format!("unknown artifact setting `{other}`")),
881
            }
882
        }
883
        let Some(path) = path else {
884
            ctx.err(a.span(), format!("artifact {name:?} needs a path"));
885
            continue;
886
        };
887
        if job.outputs.iter().any(|o| o.name == name) {
888
            ctx.err(a.span(), format!("artifact {name:?} is given twice"));
889
        } else if job.outputs.len() == MAX_OUTPUTS {
890
            ctx.err(a.span(), format!("a job has at most {MAX_OUTPUTS} artifacts"));
891
        } else {
892
            job.outputs.push(Output { name, path });
893
        }
894
    }
895
}
896
897
fn parse_job(ctx: &mut Ctx, node: &KdlNode) -> Option<Job> {
898
    let name = ctx.one_string(node)?;
899
    let named = ctx.name_ok(node.span(), "job", &name);
900
    let mut job = Job {
901
        name: name.clone(),
902
        sandbox: String::new(),
903
        scope: vec![],
904
        depends_on: vec![],
905
        env: BTreeMap::new(),
906
        exec: vec![],
907
        mounts: vec![],
908
        secrets: vec![],
909
        outputs: vec![],
910
        runs_on: vec![],
911
        timeout_s: None,
912
    };
913
    let mut seen = BTreeSet::new();
914
    let mut outputs_at = None;
915
    for c in block(ctx, node) {
916
        let key = c.name().value();
917
        if key != "scope" && key != "depends-on" && key != "mount" && key != "secret" && key != "runs-on" && !seen.insert(key.to_string()) {
918
            ctx.err(c.span(), format!("`{key}` is given twice"));
919
        }
920
        match key {
921
            "sandbox" => {
922
                ctx.no_children(c);
923
                job.sandbox = ctx.one_string(c).unwrap_or_default();
924
            }
925
            "scope" => {
926
                ctx.no_children(c);
927
                for g in ctx.strings(c) {
928
                    match globset::Glob::new(&g) {
929
                        Ok(_) => job.scope.push(g),
930
                        Err(e) => ctx.err(c.span(), format!("scope {g:?}: {e}")),
931
                    }
932
                }
933
            }
934
            "depends-on" => {
935
                ctx.no_children(c);
936
                job.depends_on.extend(ctx.strings(c));
937
            }
938
            "runs-on" => {
939
                ctx.no_children(c);
940
                parse_labels(ctx, c, &mut job.runs_on);
941
            }
942
            "timeout" => {
943
                ctx.no_children(c);
944
                job.timeout_s = parse_timeout(ctx, c);
945
            }
946
            "env" => parse_env(ctx, c, &mut job.env),
947
            "exec" => {
948
                ctx.no_children(c);
949
                job.exec = ctx.strings(c);
950
                if job.exec.is_empty() {
951
                    ctx.err(c.span(), "`exec` needs a program and its arguments");
952
                } else if job.exec.iter().any(|a| a.contains('\0')) {
953
                    ctx.err(c.span(), "`exec` arguments cannot contain NUL");
954
                }
955
            }
956
            "mount" => {
957
                if !c.entries().is_empty() {
958
                    ctx.err(c.span(), "`mount` takes a block of source, target and size");
959
                }
960
                if let Some(m) = parse_mount(ctx, c) {
961
                    if job.mounts.len() == MAX_MOUNTS {
962
                        ctx.err(c.span(), format!("a job has at most {MAX_MOUNTS} mounts"));
963
                    } else if let Some(other) = job.mounts.iter().find(|o| {
964
                        o.target == m.target
965
                            || m.target.starts_with(&format!("{}/", o.target))
966
                            || o.target.starts_with(&format!("{}/", m.target))
967
                    }) {
968
                        ctx.err(c.span(), format!("mount {:?} overlaps mount {:?}", m.target, other.target));
969
                    } else {
970
                        job.mounts.push(m);
971
                    }
972
                }
973
            }
974
            "output" => {
975
                outputs_at = Some(c.span());
976
                parse_output(ctx, c, &mut job);
977
            }
978
            "secret" => parse_secret(ctx, c, &mut job),
979
            n if LATER_JOB.contains(&n) => ctx.err(c.span(), format!("`{n}` is not in M0 yet")),
980
            other => ctx.err(c.span(), format!("unknown job setting `{other}`")),
981
        }
982
    }
983
    job.mounts.sort_by(|a, b| a.target.cmp(&b.target));
984
    job.outputs.sort_by(|a, b| a.name.cmp(&b.name));
985
    job.secrets.sort_by(|a, b| a.name.cmp(&b.name));
986
    // A tmpfs is gone when the job ends; nothing on it can be kept.
987
    for o in &job.outputs {
988
        if let Some(m) = job.mounts.iter().find(|m| m.source == MountSource::Tmpfs && o.path.starts_with(&format!("{}/", m.target))) {
989
            ctx.err(
990
                outputs_at.unwrap_or(node.span()),
991
                format!(
992
                    "artifact {:?} is on the tmpfs mount {:?}, which is gone when the job ends; use ephemeral://disk",
993
                    o.name, m.target
994
                ),
995
            );
996
        }
997
    }
998
    if job.sandbox.is_empty() && !seen.contains("sandbox") {
999
        ctx.err(node.span(), format!("job {name:?} needs a sandbox"));
1000
    }
1001
    if job.exec.is_empty() && !seen.contains("exec") {
1002
        ctx.err(node.span(), format!("job {name:?} needs an exec"));
1003
    }
1004
    job.depends_on.sort();
1005
    job.depends_on.dedup();
1006
    // Kept even when incomplete, so its references are checked too; the
1007
    // problems above already make the pipeline invalid.
1008
    named.then_some(job)
1009
}