OXYGENHUB
# 06a4c472b385 oxygenflow / crates / flow / src / microvm.rs
17.4 KiB · Rust · last changed Prune build caches before they are kept 16 days ago source blame history raw
1
//! Tier 2 (spec §4.3, docs/m0.md §2): one Firecracker microVM per job,
2
//! no network device, the rootfs read-only, the workspace read-write,
3
//! `flow-init` as PID 1. The host reads the framed console, enforces
4
//! the time limit, and writes the receipt's environment.
5
6
use crate::home::Home;
7
use anyhow::{bail, Context, Result};
8
use flow_core::api::{Record, SecretInput};
9
use flow_core::{Environment, Job, MountSource, Sandbox};
10
use std::io::{BufRead, BufReader, Read};
11
use std::path::Path;
12
use std::sync::mpsc;
13
use std::time::{Duration, Instant};
14
15
pub struct Outcome {
16
    /// None when the job never reported an exit (killed at the time limit, or the VM failed).
17
    pub exit_code: Option<i32>,
18
    pub duration_ms: u64,
19
    pub environment: Environment,
20
    pub timed_out: bool,
21
    /// Stopped because the run was cancelled (oxygenflow#32).
22
    pub cancelled: bool,
23
    /// The most memory the sandbox held, in MiB (oxygenflow#41).
24
    pub peak_memory_mib: Option<u64>,
25
    /// Each cache disk the guest pruned before it stopped, by its target
26
    /// (oxygenflow#72); the syscall tier's are pruned by the runner.
27
    pub pruned: Vec<(String, flow_init::prune::Pruned)>,
28
}
29
30
/// Where a job's records go, and whether it is still wanted: asked a few
31
/// times a second while the job runs, and the microVM is stopped on `true`.
32
pub trait Sink {
33
    fn record(&mut self, r: Record);
34
    fn cancelled(&mut self) -> bool {
35
        false
36
    }
37
}
38
39
impl<F: FnMut(Record)> Sink for F {
40
    fn record(&mut self, r: Record) {
41
        self(r)
42
    }
43
}
44
45
/// The receipt environment for a job in this tier.
46
pub fn environment(home: &Home, sandbox: &Sandbox, job: &Job) -> Result<Environment> {
47
    let cfg = home.config.microvm.as_ref().context("flow.toml has no [microvm] section")?;
48
    Ok(Environment {
49
        runtime: "microvm".into(),
50
        parts: vec![
51
            ("firecracker".into(), cfg.firecracker.blake3.clone()),
52
            ("kernel".into(), cfg.kernel.blake3.clone()),
53
            ("init".into(), cfg.init.blake3.clone()),
54
            ("memory_mib".into(), sandbox.memory_mib.to_string()),
55
            ("cpus".into(), sandbox.cpus.to_string()),
56
        ]
57
        .into_iter()
58
        .chain(job.mounts.iter().map(|m| (format!("mount {}", m.target), format!("{} {} MiB", m.source.as_str(), m.size_mib))))
59
        .collect(),
60
        rootfs: sandbox.rootfs.clone(),
61
        argv: job.exec.clone(),
62
        env: job.env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
63
    })
64
}
65
66
/// Boot, run, collect. `scratch` is an empty directory this call may fill.
67
#[allow(clippy::too_many_arguments)]
68
pub fn run(
69
    home: &Home,
70
    sandbox: &Sandbox,
71
    job: &Job,
72
    secrets: &[SecretInput],
73
    workspace: &Path,
74
    scratch: &Path,
75
    timeout: Duration,
76
    sink: &mut dyn Sink,
77
) -> Result<Outcome> {
78
    let cfg = home.config.microvm.as_ref().context("flow.toml has no [microvm] section")?;
79
    let firecracker = home.verified(&home.resolve(&cfg.firecracker.path), &cfg.firecracker.blake3)?;
80
    let kernel = home.verified(&home.resolve(&cfg.kernel.path), &cfg.kernel.blake3)?;
81
    let init = home.verified(&home.resolve(&cfg.init.path), &cfg.init.blake3)?;
82
    let rootfs = home.rootfs(&sandbox.rootfs);
83
    if !rootfs.is_file() {
84
        bail!("rootfs {} is not on this runner (import it with `flow rootfs import`)", sandbox.rootfs);
85
    }
86
    let rootfs = home.verified(&rootfs, &sandbox.rootfs)?;
87
    let environment = environment(home, sandbox, job)?;
88
89
    let percent = home.config.runner.as_ref().and_then(|r| r.cache_prune_percent).unwrap_or(flow_init::prune::DEFAULT_PERCENT);
90
    let mut spec = guest_spec(job, percent);
91
    spec["loopback"] = serde_json::Value::Bool(sandbox.network == flow_core::Network::Loopback);
92
    // Allow-listed egress (oxygenflow#55): a vsock device and the runner's
93
    // proxy behind it; the guest relays 127.0.0.1:3128 to it.
94
    let egress = sandbox.network == flow_core::Network::Egress;
95
    let (egress_tx, egress_rx) = mpsc::channel::<String>();
96
    let mut _proxy = None;
97
    if egress {
98
        if !home.config.runner.as_ref().is_some_and(|r| r.egress) {
99
            bail!("this runner does not allow network egress (a runner allows it with `egress = true` under [runner] in flow.toml)");
100
        }
101
        _proxy = Some(
102
            crate::egress::start(&scratch.join(format!("v.sock_{}", crate::egress::VSOCK_PORT)), sandbox.egress_allow.clone(), egress_tx)
103
                .context("start the egress proxy")?,
104
        );
105
        spec["egress"] = serde_json::Value::Bool(true);
106
        add_proxy_env(&mut spec);
107
        sink.record(Record {
108
            t: 0,
109
            stream: "flow".into(),
110
            text: format!("egress: through this runner, to {} only", sandbox.egress_allow.join(", ")),
111
        });
112
    }
113
    // Secrets ride in the guest's job file, which only flow-init reads,
114
    // outside the root the job is confined to; it writes each as a file.
115
    if !secrets.is_empty() {
116
        spec["secrets"] =
117
            serde_json::Value::Array(secrets.iter().map(|s| serde_json::json!({ "path": s.path, "value": s.value })).collect());
118
    }
119
    // Each `ephemeral://disk` mount is a fresh sparse ext4 disk in the
120
    // scratch directory, attached after the workspace (vdc, vdd, ...).
121
    let mut disks = Vec::new();
122
    for (i, m) in job.mounts.iter().filter(|m| m.source == MountSource::Disk).enumerate() {
123
        let path = scratch.join(format!("mount-{i}.ext4"));
124
        // A disk already in place came from the build cache (#28).
125
        if !path.exists() {
126
            crate::workspace::empty_ext4(&path, m.size_mib, "scratch")?;
127
        }
128
        disks.push(
129
            serde_json::json!({ "drive_id": format!("mount{i}"), "path_on_host": path, "is_root_device": false, "is_read_only": false }),
130
        );
131
    }
132
    let init_bytes = std::fs::read(&init)?;
133
    let spec_bytes = serde_json::to_vec(&spec)?;
134
    let initrd = crate::cpio::newc(&[
135
        crate::cpio::Entry { name: "init", mode: 0o755, data: &init_bytes },
136
        crate::cpio::Entry { name: "job.json", mode: 0o644, data: &spec_bytes },
137
    ]);
138
    let initrd_path = scratch.join("initrd.cpio");
139
    std::fs::write(&initrd_path, initrd)?;
140
    let drives: Vec<serde_json::Value> = [
141
        serde_json::json!({ "drive_id": "rootfs", "path_on_host": rootfs, "is_root_device": false, "is_read_only": true }),
142
        serde_json::json!({ "drive_id": "workspace", "path_on_host": workspace, "is_root_device": false, "is_read_only": false }),
143
    ]
144
    .into_iter()
145
    .chain(disks)
146
    .collect();
147
    let vm = serde_json::json!({
148
        "boot-source": {
149
            "kernel_image_path": kernel,
150
            "initrd_path": initrd_path,
151
            "boot_args": "console=ttyS0 reboot=k panic=-1 pci=off quiet loglevel=0 rdinit=/init",
152
        },
153
        "drives": drives,
154
        "machine-config": { "vcpu_count": sandbox.cpus, "mem_size_mib": sandbox.memory_mib },
155
    });
156
    let mut vm = vm;
157
    if egress {
158
        // Relative to the VMM's working directory (the scratch directory),
159
        // which keeps the socket path short.
160
        vm["vsock"] = serde_json::json!({ "guest_cid": 3, "uds_path": "v.sock" });
161
    }
162
    let vm_path = scratch.join("vm.json");
163
    std::fs::write(&vm_path, serde_json::to_vec_pretty(&vm)?)?;
164
165
    let started = Instant::now();
166
    let mut child = std::process::Command::new(&firecracker)
167
        .arg("--no-api")
168
        .arg("--config-file")
169
        .arg(&vm_path)
170
        .args(["--level", "Error"])
171
        .current_dir(scratch)
172
        .stdin(std::process::Stdio::null())
173
        .stdout(std::process::Stdio::piped())
174
        .stderr(std::process::Stdio::piped())
175
        .spawn()
176
        .with_context(|| format!("start {}", firecracker.display()))?;
177
    let (tx, rx) = mpsc::channel::<(bool, Vec<u8>)>();
178
    let out = child.stdout.take().unwrap();
179
    let err = child.stderr.take().unwrap();
180
    let tx2 = tx.clone();
181
    let readers = [std::thread::spawn(move || lines(out, true, tx)), std::thread::spawn(move || lines(err, false, tx2))];
182
    let mut exit_code = None;
183
    let mut timed_out = false;
184
    let mut cancelled = false;
185
    let deadline = started + timeout;
186
    let t = |s: &Instant| s.elapsed().as_millis() as u64;
187
    // The VMM's peak resident memory is the guest memory it touched: read
188
    // while it runs, since it is gone once it exits.
189
    let mut peak_memory_mib = None;
190
    let mut pruned = Vec::new();
191
    loop {
192
        if let Some(m) = crate::facts::peak_rss_mib(child.id()) {
193
            peak_memory_mib = Some(m);
194
        }
195
        while let Ok(line) = egress_rx.try_recv() {
196
            sink.record(Record { t: t(&started), stream: "flow".into(), text: line });
197
        }
198
        match rx.recv_timeout(Duration::from_millis(200)) {
199
            Ok((from_console, line)) => {
200
                let text = String::from_utf8_lossy(&line).trim_end_matches('\r').to_string();
201
                let rec = |stream: &str, text: &str| Record { t: t(&started), stream: stream.into(), text: text.into() };
202
                if !from_console {
203
                    sink.record(rec("console", &format!("firecracker: {text}")));
204
                } else if let Some(rest) = text.strip_prefix('\u{1e}') {
205
                    let (kind, body) = rest.split_at(rest.len().min(1));
206
                    let body = body.strip_prefix(' ').unwrap_or(body);
207
                    match kind {
208
                        "O" => sink.record(rec("out", body)),
209
                        "E" => sink.record(rec("err", body)),
210
                        "X" => exit_code = body.trim().parse().ok(),
211
                        "F" => sink.record(rec("flow", &format!("guest init failed: {body}"))),
212
                        "C" => match pruned_frame(body) {
213
                            Some(p) => pruned.push(p),
214
                            None => sink.record(rec("console", &text)),
215
                        },
216
                        _ => sink.record(rec("console", &text)),
217
                    }
218
                } else if !text.is_empty() {
219
                    sink.record(rec("console", &text));
220
                }
221
            }
222
            Err(mpsc::RecvTimeoutError::Timeout) => {}
223
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
224
        }
225
        if !timed_out && !cancelled && sink.cancelled() {
226
            cancelled = true;
227
            let _ = child.kill();
228
            sink.record(Record { t: t(&started), stream: "flow".into(), text: "stopped: the run was cancelled".into() });
229
        }
230
        if Instant::now() >= deadline && !timed_out && !cancelled {
231
            timed_out = true;
232
            let _ = child.kill();
233
            sink.record(Record {
234
                t: t(&started),
235
                stream: "flow".into(),
236
                text: format!("stopped at the time limit of {} s", timeout.as_secs()),
237
            });
238
        }
239
    }
240
    let status = child.wait()?;
241
    for r in readers {
242
        let _ = r.join();
243
    }
244
    if exit_code.is_none() && !timed_out && !cancelled {
245
        sink.record(Record {
246
            t: t(&started),
247
            stream: "flow".into(),
248
            text: format!("the microVM ended without the job's exit code ({status})"),
249
        });
250
    }
251
    Ok(Outcome {
252
        exit_code: if timed_out || cancelled { None } else { exit_code },
253
        duration_ms: t(&started),
254
        environment,
255
        timed_out,
256
        cancelled,
257
        peak_memory_mib,
258
        pruned,
259
    })
260
}
261
262
/// A `\x1eC` frame: a cache disk the guest pruned (oxygenflow#72).
263
fn pruned_frame(body: &str) -> Option<(String, flow_init::prune::Pruned)> {
264
    #[derive(serde::Deserialize)]
265
    struct Frame {
266
        target: String,
267
        pruned: flow_init::prune::Pruned,
268
    }
269
    let f: Frame = serde_json::from_str(body).ok()?;
270
    Some((f.target, f.pruned))
271
}
272
273
/// The proxy variables a job with egress gets, in both spellings tools
274
/// read, unless the job sets them itself.
275
fn add_proxy_env(spec: &mut serde_json::Value) {
276
    let Some(env) = spec["env"].as_array_mut() else { return };
277
    let set: Vec<String> = env.iter().filter_map(|kv| kv[0].as_str().map(String::from)).collect();
278
    for (k, v) in [
279
        ("HTTPS_PROXY", crate::egress::GUEST_PROXY),
280
        ("https_proxy", crate::egress::GUEST_PROXY),
281
        ("HTTP_PROXY", crate::egress::GUEST_PROXY),
282
        ("http_proxy", crate::egress::GUEST_PROXY),
283
        ("NO_PROXY", "localhost,127.0.0.1"),
284
        ("no_proxy", "localhost,127.0.0.1"),
285
    ] {
286
        if !set.iter().any(|s| s == k) {
287
            env.push(serde_json::json!([k, v]));
288
        }
289
    }
290
}
291
292
/// What `flow-init` reads from `/job.json`: argv, env, and the mounts
293
/// with the device each disk mount is attached as (vdc onwards). A cache
294
/// disk is pruned to `percent` of its size after a passing job
295
/// (oxygenflow#72), leaving the job's outputs on it.
296
pub fn guest_spec(job: &Job, percent: u8) -> serde_json::Value {
297
    let mut next_disk = b'c';
298
    let mounts: Vec<serde_json::Value> = job
299
        .mounts
300
        .iter()
301
        .map(|m| match m.source {
302
            MountSource::Tmpfs => serde_json::json!({ "kind": "tmpfs", "target": m.target, "size_mib": m.size_mib }),
303
            MountSource::Disk => {
304
                let dev = format!("/dev/vd{}", next_disk as char);
305
                next_disk += 1;
306
                let mut disk = serde_json::json!({ "kind": "disk", "target": m.target, "size_mib": m.size_mib, "device": dev });
307
                if m.cache.is_some() {
308
                    let prefix = format!("{}/", m.target);
309
                    let keep: Vec<&str> = job.outputs.iter().filter_map(|o| o.path.strip_prefix(&prefix)).collect();
310
                    disk["prune"] = percent.into();
311
                    disk["keep"] = keep.into();
312
                }
313
                disk
314
            }
315
        })
316
        .collect();
317
    serde_json::json!({ "argv": job.exec, "env": job.env.iter().collect::<Vec<_>>(), "mounts": mounts })
318
}
319
320
fn lines(r: impl Read, console: bool, tx: mpsc::Sender<(bool, Vec<u8>)>) {
321
    let mut r = BufReader::new(r);
322
    let mut buf = Vec::new();
323
    loop {
324
        buf.clear();
325
        match r.read_until(b'\n', &mut buf) {
326
            Ok(0) | Err(_) => break,
327
            Ok(_) => {
328
                if buf.last() == Some(&b'\n') {
329
                    buf.pop();
330
                }
331
                if tx.send((console, buf.clone())).is_err() {
332
                    break;
333
                }
334
            }
335
        }
336
    }
337
}
338
339
#[cfg(test)]
340
mod tests {
341
    use super::*;
342
    use flow_core::Mount;
343
344
    #[test]
345
    fn a_job_with_egress_gets_the_proxy_variables_unless_it_sets_them() {
346
        let mut spec = serde_json::json!({ "env": [["HTTPS_PROXY", "http://mine:1"]] });
347
        super::add_proxy_env(&mut spec);
348
        let env = spec["env"].as_array().unwrap();
349
        let get = |k: &str| env.iter().find(|kv| kv[0] == k).map(|kv| kv[1].as_str().unwrap().to_string());
350
        assert_eq!(get("HTTPS_PROXY").as_deref(), Some("http://mine:1"), "the job's own is kept");
351
        assert_eq!(get("https_proxy").as_deref(), Some("http://127.0.0.1:3128"));
352
        assert_eq!(get("NO_PROXY").as_deref(), Some("localhost,127.0.0.1"));
353
    }
354
355
    #[test]
356
    fn guest_spec_numbers_disks_after_the_workspace() {
357
        let mut job: Job = serde_json::from_value(serde_json::json!({
358
            "name": "t", "sandbox": "s", "scope": [], "depends_on": [], "env": {"A": "1"}, "exec": ["true"]
359
        }))
360
        .unwrap();
361
        assert_eq!(guest_spec(&job, 60)["mounts"], serde_json::json!([]), "no mounts");
362
        job.mounts = vec![
363
            Mount { source: MountSource::Disk, target: "/src/target".into(), size_mib: 8192, cache: None, key: vec![] },
364
            Mount { source: MountSource::Tmpfs, target: "/tmp/cache".into(), size_mib: 256, cache: None, key: vec![] },
365
            Mount { source: MountSource::Disk, target: "/tmp/z".into(), size_mib: 64, cache: None, key: vec![] },
366
        ];
367
        let spec = guest_spec(&job, 60);
368
        assert_eq!(spec["mounts"][0], serde_json::json!({"kind": "disk", "target": "/src/target", "size_mib": 8192, "device": "/dev/vdc"}));
369
        assert_eq!(spec["mounts"][1], serde_json::json!({"kind": "tmpfs", "target": "/tmp/cache", "size_mib": 256}));
370
        assert_eq!(spec["mounts"][2]["device"], "/dev/vdd");
371
        assert_eq!(spec["env"], serde_json::json!([["A", "1"]]));
372
    }
373
374
    /// oxygenflow#72: a cache disk is pruned in the guest, leaving the
375
    /// job's outputs on it; a plain disk is not, and the guest's report
376
    /// comes back as a frame.
377
    #[test]
378
    fn a_cache_disk_is_pruned_in_the_guest_but_its_outputs_stay() {
379
        let mut job: Job = serde_json::from_value(serde_json::json!({
380
            "name": "t", "sandbox": "s", "scope": [], "depends_on": [], "env": {}, "exec": ["true"],
381
            "outputs": [{"name": "bin", "path": "/src/target/release/tool"}, {"name": "w", "path": "/src/w"}]
382
        }))
383
        .unwrap();
384
        job.mounts = vec![
385
            Mount { source: MountSource::Disk, target: "/src/target".into(), size_mib: 8192, cache: Some("t".into()), key: vec![] },
386
            Mount { source: MountSource::Disk, target: "/tmp/z".into(), size_mib: 64, cache: None, key: vec![] },
387
        ];
388
        let spec = guest_spec(&job, 45);
389
        assert_eq!((spec["mounts"][0]["prune"].as_u64(), &spec["mounts"][0]["keep"]), (Some(45), &serde_json::json!(["release/tool"])));
390
        assert!(spec["mounts"][1].get("prune").is_none() && spec["mounts"][1].get("keep").is_none());
391
        let (target, p) =
392
            pruned_frame(r#"{"target":"/src/target","pruned":{"size":100,"percent":60,"before":90,"after":50,"freed":40,"files":3}}"#)
393
                .unwrap();
394
        assert_eq!((target.as_str(), p.after, p.cap(), p.fits(), p.unpruned), ("/src/target", 50, 60, true, None));
395
        assert!(pruned_frame("not json").is_none());
396
    }
397
}