OXYGENHUB
# c0c54484499e oxygenflow / crates / flow / src / microvm.rs
9.7 KiB · Rust · last changed Ephemeral scratch mounts in M0: ephemeral://tmpfs and ephemeral://disk (a sparse disk per job), checked targets and sizes, in the canonical job and the receipt; flow-init mounts them for the job's user; make deploy-runner 1 month 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;
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
}
22
23
/// The receipt environment for a job in this tier.
24
pub fn environment(home: &Home, sandbox: &Sandbox, job: &Job) -> Result<Environment> {
25
    let cfg = home.config.microvm.as_ref().context("flow.toml has no [microvm] section")?;
26
    Ok(Environment {
27
        runtime: "microvm".into(),
28
        parts: vec![
29
            ("firecracker".into(), cfg.firecracker.blake3.clone()),
30
            ("kernel".into(), cfg.kernel.blake3.clone()),
31
            ("init".into(), cfg.init.blake3.clone()),
32
            ("memory_mib".into(), sandbox.memory_mib.to_string()),
33
            ("cpus".into(), sandbox.cpus.to_string()),
34
        ]
35
        .into_iter()
36
        .chain(job.mounts.iter().map(|m| (format!("mount {}", m.target), format!("{} {} MiB", m.source.as_str(), m.size_mib))))
37
        .collect(),
38
        rootfs: sandbox.rootfs.clone(),
39
        argv: job.exec.clone(),
40
        env: job.env.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
41
    })
42
}
43
44
/// Boot, run, collect. `scratch` is an empty directory this call may fill.
45
pub fn run(
46
    home: &Home,
47
    sandbox: &Sandbox,
48
    job: &Job,
49
    workspace: &Path,
50
    scratch: &Path,
51
    timeout: Duration,
52
    sink: &mut dyn FnMut(Record),
53
) -> Result<Outcome> {
54
    let cfg = home.config.microvm.as_ref().context("flow.toml has no [microvm] section")?;
55
    let firecracker = home.verified(&home.resolve(&cfg.firecracker.path), &cfg.firecracker.blake3)?;
56
    let kernel = home.verified(&home.resolve(&cfg.kernel.path), &cfg.kernel.blake3)?;
57
    let init = home.verified(&home.resolve(&cfg.init.path), &cfg.init.blake3)?;
58
    let rootfs = home.rootfs(&sandbox.rootfs);
59
    if !rootfs.is_file() {
60
        bail!("rootfs {} is not on this runner (import it with `flow rootfs import`)", sandbox.rootfs);
61
    }
62
    let rootfs = home.verified(&rootfs, &sandbox.rootfs)?;
63
    let environment = environment(home, sandbox, job)?;
64
65
    let spec = guest_spec(job);
66
    // Each `ephemeral://disk` mount is a fresh sparse ext4 disk in the
67
    // scratch directory, attached after the workspace (vdc, vdd, ...).
68
    let mut disks = Vec::new();
69
    for (i, m) in job.mounts.iter().filter(|m| m.source == MountSource::Disk).enumerate() {
70
        let path = scratch.join(format!("mount-{i}.ext4"));
71
        crate::workspace::empty_ext4(&path, m.size_mib, "scratch")?;
72
        disks.push(
73
            serde_json::json!({ "drive_id": format!("mount{i}"), "path_on_host": path, "is_root_device": false, "is_read_only": false }),
74
        );
75
    }
76
    let init_bytes = std::fs::read(&init)?;
77
    let spec_bytes = serde_json::to_vec(&spec)?;
78
    let initrd = crate::cpio::newc(&[
79
        crate::cpio::Entry { name: "init", mode: 0o755, data: &init_bytes },
80
        crate::cpio::Entry { name: "job.json", mode: 0o644, data: &spec_bytes },
81
    ]);
82
    let initrd_path = scratch.join("initrd.cpio");
83
    std::fs::write(&initrd_path, initrd)?;
84
    let drives: Vec<serde_json::Value> = [
85
        serde_json::json!({ "drive_id": "rootfs", "path_on_host": rootfs, "is_root_device": false, "is_read_only": true }),
86
        serde_json::json!({ "drive_id": "workspace", "path_on_host": workspace, "is_root_device": false, "is_read_only": false }),
87
    ]
88
    .into_iter()
89
    .chain(disks)
90
    .collect();
91
    let vm = serde_json::json!({
92
        "boot-source": {
93
            "kernel_image_path": kernel,
94
            "initrd_path": initrd_path,
95
            "boot_args": "console=ttyS0 reboot=k panic=-1 pci=off quiet loglevel=0 rdinit=/init",
96
        },
97
        "drives": drives,
98
        "machine-config": { "vcpu_count": sandbox.cpus, "mem_size_mib": sandbox.memory_mib },
99
    });
100
    let vm_path = scratch.join("vm.json");
101
    std::fs::write(&vm_path, serde_json::to_vec_pretty(&vm)?)?;
102
103
    let started = Instant::now();
104
    let mut child = std::process::Command::new(&firecracker)
105
        .arg("--no-api")
106
        .arg("--config-file")
107
        .arg(&vm_path)
108
        .args(["--level", "Error"])
109
        .current_dir(scratch)
110
        .stdin(std::process::Stdio::null())
111
        .stdout(std::process::Stdio::piped())
112
        .stderr(std::process::Stdio::piped())
113
        .spawn()
114
        .with_context(|| format!("start {}", firecracker.display()))?;
115
    let (tx, rx) = mpsc::channel::<(bool, Vec<u8>)>();
116
    let out = child.stdout.take().unwrap();
117
    let err = child.stderr.take().unwrap();
118
    let tx2 = tx.clone();
119
    let readers = [std::thread::spawn(move || lines(out, true, tx)), std::thread::spawn(move || lines(err, false, tx2))];
120
    let mut exit_code = None;
121
    let mut timed_out = false;
122
    let deadline = started + timeout;
123
    let t = |s: &Instant| s.elapsed().as_millis() as u64;
124
    loop {
125
        match rx.recv_timeout(Duration::from_millis(200)) {
126
            Ok((from_console, line)) => {
127
                let text = String::from_utf8_lossy(&line).trim_end_matches('\r').to_string();
128
                let rec = |stream: &str, text: &str| Record { t: t(&started), stream: stream.into(), text: text.into() };
129
                if !from_console {
130
                    sink(rec("console", &format!("firecracker: {text}")));
131
                } else if let Some(rest) = text.strip_prefix('\u{1e}') {
132
                    let (kind, body) = rest.split_at(rest.len().min(1));
133
                    let body = body.strip_prefix(' ').unwrap_or(body);
134
                    match kind {
135
                        "O" => sink(rec("out", body)),
136
                        "E" => sink(rec("err", body)),
137
                        "X" => exit_code = body.trim().parse().ok(),
138
                        "F" => sink(rec("flow", &format!("guest init failed: {body}"))),
139
                        _ => sink(rec("console", &text)),
140
                    }
141
                } else if !text.is_empty() {
142
                    sink(rec("console", &text));
143
                }
144
            }
145
            Err(mpsc::RecvTimeoutError::Timeout) => {}
146
            Err(mpsc::RecvTimeoutError::Disconnected) => break,
147
        }
148
        if Instant::now() >= deadline && !timed_out {
149
            timed_out = true;
150
            let _ = child.kill();
151
            sink(Record { t: t(&started), stream: "flow".into(), text: format!("stopped at the time limit of {} s", timeout.as_secs()) });
152
        }
153
    }
154
    let status = child.wait()?;
155
    for r in readers {
156
        let _ = r.join();
157
    }
158
    if exit_code.is_none() && !timed_out {
159
        sink(Record { t: t(&started), stream: "flow".into(), text: format!("the microVM ended without the job's exit code ({status})") });
160
    }
161
    Ok(Outcome { exit_code: if timed_out { None } else { exit_code }, duration_ms: t(&started), environment, timed_out })
162
}
163
164
/// What `flow-init` reads from `/job.json`: argv, env, and the mounts
165
/// with the device each disk mount is attached as (vdc onwards).
166
pub fn guest_spec(job: &Job) -> serde_json::Value {
167
    let mut next_disk = b'c';
168
    let mounts: Vec<serde_json::Value> = job
169
        .mounts
170
        .iter()
171
        .map(|m| match m.source {
172
            MountSource::Tmpfs => serde_json::json!({ "kind": "tmpfs", "target": m.target, "size_mib": m.size_mib }),
173
            MountSource::Disk => {
174
                let dev = format!("/dev/vd{}", next_disk as char);
175
                next_disk += 1;
176
                serde_json::json!({ "kind": "disk", "target": m.target, "size_mib": m.size_mib, "device": dev })
177
            }
178
        })
179
        .collect();
180
    serde_json::json!({ "argv": job.exec, "env": job.env.iter().collect::<Vec<_>>(), "mounts": mounts })
181
}
182
183
fn lines(r: impl Read, console: bool, tx: mpsc::Sender<(bool, Vec<u8>)>) {
184
    let mut r = BufReader::new(r);
185
    let mut buf = Vec::new();
186
    loop {
187
        buf.clear();
188
        match r.read_until(b'\n', &mut buf) {
189
            Ok(0) | Err(_) => break,
190
            Ok(_) => {
191
                if buf.last() == Some(&b'\n') {
192
                    buf.pop();
193
                }
194
                if tx.send((console, buf.clone())).is_err() {
195
                    break;
196
                }
197
            }
198
        }
199
    }
200
}
201
202
#[cfg(test)]
203
mod tests {
204
    use super::*;
205
    use flow_core::Mount;
206
207
    #[test]
208
    fn guest_spec_numbers_disks_after_the_workspace() {
209
        let mut job: Job = serde_json::from_value(serde_json::json!({
210
            "name": "t", "sandbox": "s", "scope": [], "depends_on": [], "env": {"A": "1"}, "exec": ["true"]
211
        }))
212
        .unwrap();
213
        assert_eq!(guest_spec(&job)["mounts"], serde_json::json!([]), "no mounts");
214
        job.mounts = vec![
215
            Mount { source: MountSource::Disk, target: "/src/target".into(), size_mib: 8192 },
216
            Mount { source: MountSource::Tmpfs, target: "/tmp/cache".into(), size_mib: 256 },
217
            Mount { source: MountSource::Disk, target: "/tmp/z".into(), size_mib: 64 },
218
        ];
219
        let spec = guest_spec(&job);
220
        assert_eq!(spec["mounts"][0], serde_json::json!({"kind": "disk", "target": "/src/target", "size_mib": 8192, "device": "/dev/vdc"}));
221
        assert_eq!(spec["mounts"][1], serde_json::json!({"kind": "tmpfs", "target": "/tmp/cache", "size_mib": 256}));
222
        assert_eq!(spec["mounts"][2]["device"], "/dev/vdd");
223
        assert_eq!(spec["env"], serde_json::json!([["A", "1"]]));
224
    }
225
}