draupnir 0.1.5

Draupnir — the nordisk boot/provisioning library: fire up a runtime from one BootSpec across three backends (KVM via tunnr · OCI container · Redfish bare-metal virtual-media) and drive its power lifecycle. Odin's ring that drips eight identical copies → boot a fleet of identical machines from one ISO.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! **KVM backend** — fire up an appliance VM by driving **tunnr**.
//!
//! Draupnir does not reimplement VM boot. tunnr owns the QEMU + OVMF (UEFI) + KVM
//! launch and exposes a self-contained, kill-able primitive —
//! `tunnr_vm::boot_test(BootSpec) -> BootHandle`. This backend is the thin adapter
//! that maps a Draupnir [`BootSpec`] onto tunnr's `BootSpec`, calls `boot_test`,
//! and adapts the returned `BootHandle` into a [`Machine`] / [`Lifecycle`].
//!
//! The trait wiring compiles unconditionally; the live tunnr call is behind the
//! `backend-tunnr` feature (an optional path dep on `tunnr-vm`, exactly how `jera`
//! wires it — switch to a version once tunnr publishes to crates.io). Without the
//! feature every entry point returns an honest [`Error::Unsupported`] rather than
//! pretending to boot.
//!
//! **Live handles.** [`Boot::boot`] returns a plain-data [`Machine`] (an id + power
//! state), but [`Lifecycle`] needs tunnr's `BootHandle` to kill/poll the exact QEMU
//! process group. The backend therefore keeps a small registry
//! (`machine id → BootHandle`) so `power_off`/`status` address the VM that `boot`
//! actually launched.

use crate::{Boot, BootSpec, CloudInit, Error, Lifecycle, Machine, PowerState, Result};
#[cfg(feature = "backend-tunnr")]
use crate::ImageSource;

#[cfg(feature = "backend-tunnr")]
use std::collections::HashMap;
#[cfg(feature = "backend-tunnr")]
use std::sync::{Arc, Mutex};

/// The registry of live tunnr boot handles, keyed by [`Machine::id`].
#[cfg(feature = "backend-tunnr")]
type LiveHandles = Arc<Mutex<HashMap<String, tunnr_vm::BootHandle>>>;

/// The KVM boot backend (drives tunnr).
#[derive(Default, Clone)]
pub struct KvmBoot {
    /// Live tunnr handles for the VMs this backend booted, so [`Lifecycle`] can
    /// kill/poll the exact QEMU process group. `BootHandle` is a cheap `Arc` clone.
    #[cfg(feature = "backend-tunnr")]
    live: LiveHandles,
}

impl std::fmt::Debug for KvmBoot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KvmBoot").finish_non_exhaustive()
    }
}

impl KvmBoot {
    /// Construct the KVM backend.
    pub fn new() -> Self {
        Self::default()
    }

    /// **Pure** render of the cloud-init NoCloud seed file set —
    /// `[("user-data", …), ("meta-data", …)]`. When the spec omits `meta-data` a
    /// minimal default carrying an `instance-id`/`local-hostname` is supplied, so
    /// cloud-init always finds both files it expects on a NoCloud datasource. This
    /// is the testable core of the seed authoring (ported from Skidbladnir's
    /// `nocloud_seed_files`); [`build_seed_image`](Self::build_seed_image) writes it
    /// into a FAT image.
    pub fn nocloud_seed_files(ci: &CloudInit) -> Vec<(&'static str, String)> {
        let md = ci
            .meta_data
            .clone()
            .unwrap_or_else(|| "instance-id: draupnir\nlocal-hostname: draupnir\n".to_string());
        let mut files = vec![("user-data", ci.user_data.clone()), ("meta-data", md)];
        // cloud-init reads an optional `network-config` from the same NoCloud volume.
        if let Some(nc) = &ci.network_config {
            files.push(("network-config", nc.clone()));
        }
        files
    }

    /// Map a Draupnir [`BootSpec`] onto tunnr's `tunnr_vm::BootSpec`.
    ///
    /// Field-for-field this is the seam `jera::vm` already wires. Only compiled
    /// with `backend-tunnr` (the type comes from the optional `tunnr-vm` dep).
    #[cfg(feature = "backend-tunnr")]
    pub fn to_tunnr_spec(&self, spec: &BootSpec) -> Result<tunnr_vm::BootSpec> {
        use std::path::PathBuf;
        use std::time::Duration;

        let (kernel, rootfs_or_disk) = match &spec.image {
            ImageSource::KernelRootfs { kernel, rootfs } => (kernel.clone(), rootfs.clone()),
            ImageSource::Disk(disk) => {
                // tunnr attaches a non-cpio image as a virtio -drive; a kernel is
                // still required for the direct-kernel boot path.
                (spec.cmdline_kernel(), disk.clone())
            }
            other => {
                return Err(Error::Spec(format!("kvm backend cannot boot {other:?}")))
            }
        };
        let mut boot = tunnr_vm::BootSpec::smoke(PathBuf::from(kernel), PathBuf::from(rootfs_or_disk));
        boot.mem_mb = spec.mem_mb;
        boot.cores = spec.cores;
        boot.headless = true;
        // Let a slow appliance boot be tuned without a rebuild (parity with jera).
        if let Some(secs) = std::env::var("DRAUPNIR_VM_BOOT_TIMEOUT")
            .ok()
            .and_then(|s| s.parse().ok())
        {
            boot.timeout = Duration::from_secs(secs);
        }
        if !spec.cmdline.is_empty() {
            boot.kernel_cmdline = spec.cmdline.clone();
        }
        // cloud-init NoCloud: author the seed image and attach it as a read-only
        // virtio drive (verbatim `extra_qemu_args` — tunnr's spec-appended seam).
        // The guest's cloud-init finds it by its `cidata` vfat label at first boot.
        if let Some(ci) = &spec.cloud_init {
            let seed = Self::build_seed_image(&Self::seed_path(&spec.name), ci)?;
            boot.extra_qemu_args.push("-drive".into());
            boot.extra_qemu_args.push(format!(
                "file={},format=raw,if=virtio,readonly=on",
                seed.display()
            ));
        }
        Ok(boot)
    }

    /// The temp path the NoCloud seed image for `name` is authored at.
    #[cfg(feature = "backend-tunnr")]
    fn seed_path(name: &str) -> std::path::PathBuf {
        std::env::temp_dir().join(format!("draupnir-{name}-seed.img"))
    }

    /// Materialize a [`CloudInit`] into a **NoCloud seed image** at `out`: a
    /// FAT12/16 image, volume-labelled `cidata`, holding `user-data` + `meta-data`
    /// at its root. **Pure Rust** via `fatfs` — no `genisoimage`/`mkisofs`
    /// subprocess (zero-shell), the same authoring Skidbladnir uses.
    #[cfg(feature = "backend-tunnr")]
    pub fn build_seed_image(out: &std::path::Path, ci: &CloudInit) -> Result<std::path::PathBuf> {
        let blobs: Vec<(String, Vec<u8>)> = Self::nocloud_seed_files(ci)
            .into_iter()
            .map(|(n, c)| (n.to_string(), c.into_bytes()))
            .collect();
        // cloud-init matches the label case-insensitively; "cidata" is canonical.
        Self::build_fat_image(out, "cidata", &blobs)?;
        Ok(out.to_path_buf())
    }

    /// Author a **FAT12/16 image** at `out`, volume-labelled `label` (≤11 chars),
    /// holding `files` (name → bytes) at the root — pure Rust via `fatfs`, into an
    /// in-memory buffer written out in one shot. Sized to the payload + 1 MiB slack,
    /// min 2 MiB, rounded up to 512 KiB.
    #[cfg(feature = "backend-tunnr")]
    fn build_fat_image(out: &std::path::Path, label: &str, files: &[(String, Vec<u8>)]) -> Result<()> {
        use std::io::Write;
        if let Some(dir) = out.parent() {
            std::fs::create_dir_all(dir)
                .map_err(|e| Error::Backend(format!("mkdir {}: {e}", dir.display())))?;
        }
        let payload: u64 = files.iter().map(|(_, b)| b.len() as u64).sum();
        let needed = (payload + 1024 * 1024).max(2 * 1024 * 1024);
        let size = needed.div_ceil(512 * 1024) * 512 * 1024;
        let mut cursor = std::io::Cursor::new(vec![0u8; size as usize]);
        let mut lbl = [b' '; 11];
        for (i, b) in label.bytes().take(11).enumerate() {
            lbl[i] = b;
        }
        fatfs::format_volume(&mut cursor, fatfs::FormatVolumeOptions::new().volume_label(lbl))
            .map_err(|e| Error::Backend(format!("format FAT {}: {e}", out.display())))?;
        {
            let fs = fatfs::FileSystem::new(&mut cursor, fatfs::FsOptions::new())
                .map_err(|e| Error::Backend(format!("open FAT {}: {e}", out.display())))?;
            let root = fs.root_dir();
            for (name, bytes) in files {
                let mut file = root
                    .create_file(name)
                    .map_err(|e| Error::Backend(format!("create {name} in FAT: {e}")))?;
                file.truncate().ok();
                file.write_all(bytes)
                    .map_err(|e| Error::Backend(format!("write {name} in FAT: {e}")))?;
                file.flush().ok();
            }
        }
        std::fs::write(out, cursor.into_inner())
            .map_err(|e| Error::Backend(format!("write {}: {e}", out.display())))?;
        Ok(())
    }
}

impl Boot for KvmBoot {
    fn boot(&self, spec: &BootSpec) -> Result<Machine> {
        spec.validate()?;
        #[cfg(feature = "backend-tunnr")]
        {
            let tunnr_spec = self.to_tunnr_spec(spec)?;
            let handle = tunnr_vm::boot_test(tunnr_spec)
                .map_err(|e| Error::Backend(format!("tunnr boot_test: {e}")))?;
            let id = handle.id().to_string();
            let machine = Machine::started(&id, spec);
            self.live.lock().unwrap().insert(id, handle);
            Ok(machine)
        }
        #[cfg(not(feature = "backend-tunnr"))]
        {
            let _ = spec;
            Err(Error::Unsupported(
                "kvm backend needs the `backend-tunnr` feature (drives tunnr's KVM boot primitive)"
                    .into(),
            ))
        }
    }
}

impl Lifecycle for KvmBoot {
    fn power_on(&self, machine: &Machine) -> Result<()> {
        let _ = machine;
        // tunnr's primitive is fire-and-forget (a booted VM has no re-power line);
        // the honest answer is "boot a fresh instance", not a fake success.
        Err(Error::Unsupported(
            "kvm/tunnr VMs are fire-and-forget: re-power by calling draupnir::boot() again".into(),
        ))
    }

    fn power_off(&self, machine: &Machine) -> Result<()> {
        #[cfg(feature = "backend-tunnr")]
        {
            let handle = self
                .live
                .lock()
                .unwrap()
                .remove(&machine.id)
                .ok_or_else(|| Error::Backend(format!("no live tunnr VM for {}", machine.id)))?;
            handle.kill();
            Ok(())
        }
        #[cfg(not(feature = "backend-tunnr"))]
        {
            let _ = machine;
            Err(Error::Unsupported(
                "kvm backend needs the `backend-tunnr` feature".into(),
            ))
        }
    }

    fn status(&self, machine: &Machine) -> Result<PowerState> {
        #[cfg(feature = "backend-tunnr")]
        {
            let guard = self.live.lock().unwrap();
            let Some(handle) = guard.get(&machine.id) else {
                return Ok(PowerState::Unknown);
            };
            Ok(map_status(handle.poll_status()))
        }
        #[cfg(not(feature = "backend-tunnr"))]
        {
            let _ = machine;
            Err(Error::Unsupported(
                "kvm backend needs the `backend-tunnr` feature".into(),
            ))
        }
    }
}

/// Map a tunnr `BootStatus` onto draupnir's [`PowerState`]: still booting or booted
/// OK ⇒ powered `On`; any terminal (failed/killed/timed-out) ⇒ `Off`.
#[cfg(feature = "backend-tunnr")]
fn map_status(s: tunnr_vm::BootStatus) -> PowerState {
    match s {
        tunnr_vm::BootStatus::Booting | tunnr_vm::BootStatus::BootedOk => PowerState::On,
        tunnr_vm::BootStatus::Failed(_)
        | tunnr_vm::BootStatus::Killed
        | tunnr_vm::BootStatus::TimedOut => PowerState::Off,
    }
}

#[cfg(feature = "backend-tunnr")]
impl BootSpec {
    /// Kernel path for a disk boot (tunnr's direct-kernel launch still needs a
    /// `-kernel`). Placeholder until the disk-boot kernel is threaded through the
    /// spec; kept private-ish behind the feature.
    fn cmdline_kernel(&self) -> String {
        // A disk-image boot still requires a kernel for tunnr's direct-kernel
        // launch; carrying it explicitly is a follow-up (see design.md).
        String::new()
    }
}

#[cfg(test)]
mod seed_tests {
    use super::*;

    #[test]
    fn nocloud_seed_files_render_user_data_and_a_default_meta_data() {
        let ci = CloudInit::user_data("#cloud-config\nruncmd:\n  - [echo, hi]\n");
        let files = KvmBoot::nocloud_seed_files(&ci);
        assert_eq!(files[0].0, "user-data");
        assert_eq!(files[0].1, "#cloud-config\nruncmd:\n  - [echo, hi]\n");
        assert_eq!(files[1].0, "meta-data");
        // A default meta-data is supplied when the spec omits it.
        assert!(files[1].1.contains("instance-id"), "default meta-data has an instance-id");
        assert!(files[1].1.contains("local-hostname"));
    }

    #[test]
    fn nocloud_seed_files_pass_through_an_explicit_meta_data() {
        let ci = CloudInit {
            user_data: "#cloud-config\n".into(),
            meta_data: Some("instance-id: node-7\n".into()),
            network_config: None,
        };
        let files = KvmBoot::nocloud_seed_files(&ci);
        assert_eq!(files[1].1, "instance-id: node-7\n");
    }

    #[test]
    fn nocloud_seed_files_omit_network_config_by_default_and_emit_it_when_set() {
        // No network-config → just the two required files.
        let plain = CloudInit::user_data("#cloud-config\n");
        let files = KvmBoot::nocloud_seed_files(&plain);
        assert_eq!(files.len(), 2);
        assert!(!files.iter().any(|(n, _)| *n == "network-config"));

        // With one → a third `network-config` file carrying the document.
        let net = CloudInit::user_data("#cloud-config\n")
            .with_network_config("version: 2\nethernets:\n  eth0:\n    dhcp4: true\n");
        let files = KvmBoot::nocloud_seed_files(&net);
        assert_eq!(files.len(), 3);
        let nc = files.iter().find(|(n, _)| *n == "network-config").expect("network-config present");
        assert!(nc.1.contains("dhcp4: true"));
    }
}

#[cfg(all(test, feature = "backend-tunnr"))]
mod tests {
    use super::*;
    use crate::ImageSource;

    /// Author the NoCloud seed image, then read it back through `fatfs` and confirm
    /// the two files + their contents survive and the volume label is `cidata`
    /// (proves the guest's cloud-init will find `user-data`/`meta-data`).
    #[test]
    fn build_seed_image_writes_a_cidata_fat_with_both_files() {
        let out = std::env::temp_dir()
            .join(format!("draupnir-seedtest-{}.img", std::process::id()));
        let _ = std::fs::remove_file(&out);
        let ci = CloudInit::user_data("#cloud-config\nruncmd:\n  - [echo, hi]\n");
        let path = KvmBoot::build_seed_image(&out, &ci).unwrap();
        assert_eq!(path, out);

        let img = std::fs::File::options().read(true).write(true).open(&out).unwrap();
        let fs = fatfs::FileSystem::new(img, fatfs::FsOptions::new()).unwrap();
        assert_eq!(fs.volume_label().to_ascii_lowercase(), "cidata");
        let mut names: Vec<String> = fs.root_dir().iter().map(|e| e.unwrap().file_name()).collect();
        names.sort();
        assert!(names.iter().any(|n| n == "user-data"), "user-data present, got {names:?}");
        assert!(names.iter().any(|n| n == "meta-data"), "meta-data present, got {names:?}");
        // Content survives the round-trip.
        use std::io::Read;
        let mut buf = String::new();
        fs.root_dir().open_file("user-data").unwrap().read_to_string(&mut buf).unwrap();
        assert!(buf.contains("runcmd"), "user-data content survives: {buf:?}");

        let _ = std::fs::remove_file(&out);
    }

    /// A spec carrying cloud-init makes `to_tunnr_spec` append a read-only virtio
    /// `-drive` for the seed image; a spec without it appends nothing.
    #[test]
    fn to_tunnr_spec_attaches_the_seed_drive_only_when_cloud_init_is_present() {
        let plain = BootSpec::kvm_kernel_rootfs("plain", "/bzImage", "/rootfs.cpio.gz");
        let t = KvmBoot::new().to_tunnr_spec(&plain).unwrap();
        assert!(!t.extra_qemu_args.iter().any(|a| a.contains("seed.img")), "no seed drive without cloud-init");

        let seeded = BootSpec::kvm_kernel_rootfs("seeded", "/bzImage", "/rootfs.cpio.gz")
            .with_cloud_init(CloudInit::user_data("#cloud-config\n"));
        let t = KvmBoot::new().to_tunnr_spec(&seeded).unwrap();
        let drive = t
            .extra_qemu_args
            .windows(2)
            .find(|w| w[0] == "-drive" && w[1].contains("draupnir-seeded-seed.img"))
            .expect("a -drive for the seed image is appended");
        assert!(drive[1].contains("format=raw"), "raw virtio drive: {:?}", drive[1]);
        assert!(drive[1].contains("readonly=on"), "read-only: {:?}", drive[1]);
        let _ = std::fs::remove_file(KvmBoot::seed_path("seeded"));
    }

    #[test]
    fn kvm_spec_maps_kernel_rootfs_mem_and_cores_onto_tunnr() {
        let mut spec = BootSpec::kvm_kernel_rootfs("appliance", "/bzImage", "/rootfs.cpio.gz");
        spec.mem_mb = 1024;
        spec.cores = 4;
        spec.cmdline = "korp.smoke=1".into();
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        assert_eq!(t.kernel, std::path::PathBuf::from("/bzImage"));
        assert_eq!(t.rootfs_or_disk, std::path::PathBuf::from("/rootfs.cpio.gz"));
        assert_eq!(t.mem_mb, 1024);
        assert_eq!(t.cores, 4);
        assert!(t.headless);
        assert_eq!(t.kernel_cmdline, "korp.smoke=1");
    }

    #[test]
    fn kvm_spec_rejects_a_non_kvm_image() {
        let mut spec = BootSpec::kvm_kernel_rootfs("bad", "/k", "/r");
        spec.image = ImageSource::OciImage("redis:7".into());
        assert!(matches!(KvmBoot::new().to_tunnr_spec(&spec), Err(Error::Spec(_))));
    }

    #[test]
    fn status_of_an_unknown_machine_is_unknown() {
        let kvm = KvmBoot::new();
        let m = Machine {
            id: "boot-does-not-exist".into(),
            spec_name: "x".into(),
            backend: crate::Backend::Kvm,
            power: PowerState::Unknown,
        };
        assert_eq!(kvm.status(&m).unwrap(), PowerState::Unknown);
    }

    #[test]
    fn map_status_folds_live_states_to_on_and_every_terminal_to_off() {
        // The two live states are `On`; every terminal (failed for any reason,
        // killed, timed-out) collapses to `Off` — a booted VM that later died is
        // powered off, not still on.
        assert_eq!(map_status(tunnr_vm::BootStatus::Booting), PowerState::On);
        assert_eq!(map_status(tunnr_vm::BootStatus::BootedOk), PowerState::On);
        assert_eq!(
            map_status(tunnr_vm::BootStatus::Failed("qemu exited 1".into())),
            PowerState::Off
        );
        assert_eq!(map_status(tunnr_vm::BootStatus::Killed), PowerState::Off);
        assert_eq!(map_status(tunnr_vm::BootStatus::TimedOut), PowerState::Off);
    }
}