draupnir 0.1.9

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! **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.

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

#[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", …)]` (plus `network-config` when set).
    /// A thin re-export of the owned builder [`crate::seed::seed_files`] so the
    /// seed lives in exactly one place (draupnir's [`crate::seed`] module); kept
    /// here for the KVM backend's existing call sites.
    pub fn nocloud_seed_files(ci: &CloudInit) -> Vec<(&'static str, String)> {
        crate::seed::seed_files(ci)
    }

    /// The **serial console** captured so far for a live KVM guest — read off the
    /// tunnr `BootHandle` in the registry (`tunnr_vm::BootHandle::boot_log`). This is
    /// the KVM-console surface a consumer (jera → dwarves) streams to make the boot's
    /// console **visible in the forge**: draupnir's [`Lifecycle`] exposes power state,
    /// but the boot handle it keeps alive also holds the live `-serial mon:stdio`
    /// capture, so a caller that has the [`Machine`] can read the console without
    /// re-implementing any capture. `None` when no live VM matches `machine` (or the
    /// `backend-tunnr` feature is off — no tunnr handle to read).
    #[cfg(feature = "backend-tunnr")]
    pub fn serial_log(&self, machine: &Machine) -> Option<String> {
        self.live
            .lock()
            .unwrap()
            .get(&machine.id)
            .map(|h| h.boot_log())
    }

    /// Without `backend-tunnr` there is no live tunnr handle, so no console to read.
    #[cfg(not(feature = "backend-tunnr"))]
    pub fn serial_log(&self, _machine: &Machine) -> Option<String> {
        None
    }

    /// 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, base_snapshot) = match &spec.image {
            ImageSource::KernelRootfs { kernel, rootfs } => (kernel.clone(), rootfs.clone(), false),
            ImageSource::Disk { kernel, disk } => {
                // tunnr attaches a non-cpio image as a virtio -drive; a kernel is
                // still required for the direct-kernel boot path and now travels
                // in the spec (validated non-empty by BootSpec::validate).
                (kernel.clone(), disk.clone(), false)
            }
            ImageSource::BootloaderDisk { disk } => {
                // A self-booting disk: hand tunnr an EMPTY kernel path so its
                // `is_direct_kernel_boot()` is false and OVMF firmware-boots the
                // disk directly (no `-kernel`), exactly as real hardware would.
                // COW-protect the base: a matrix boot of a shared, content-addressed
                // base OS disk must never mutate it (tunnr opens it snapshot=on).
                (String::new(), disk.clone(), true)
            }
            // A LIVE boot off the medium: the ISO is the whole payload, there is no
            // target disk. Empty kernel → tunnr firmware-boots it, and tunnr's own
            // `.iso` arm renders it `-cdrom <iso> -boot d`. `base_snapshot` is
            // meaningless for a read-only CD, so it stays false.
            ImageSource::Iso(iso) => (String::new(), iso.clone(), false),
            other => return Err(Error::Spec(format!("kvm backend cannot boot {other:?}"))),
        };
        // Fail by name before anything is launched: a medium that is not on disk is
        // a build that did not happen, not a boot that did not come up.
        Self::check_medium_present(spec)?;
        let mut boot =
            tunnr_vm::BootSpec::smoke(PathBuf::from(kernel), PathBuf::from(rootfs_or_disk));
        // COW-protection is the default, but it is not always right: a caller that
        // booted its OWN per-run disk copy in order to boot it a SECOND time needs the
        // writes to survive. `persist_disk` is that opt-out — it can only ever turn
        // COW off, never on, so an image source that already persists is unaffected.
        boot.base_snapshot = base_snapshot && !spec.persist_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 through tunnr's
        // native `with_seed` seam (its `seed` field), so tunnr owns the exact
        // read-only virtio-disk argv — no hand-rolled `extra_qemu_args` drift.
        // 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 = boot.with_seed(seed);
        }
        // Airgap for the KVM path: a `NetMode::None` spec cuts the guest off from all
        // egress. tunnr expresses this as `NetConfig::None` (`-nic none`); every other
        // net mode leaves tunnr's default user-mode virtio-net (byte-identical). This
        // is the KVM twin of the container backend's `--network none` — the one wire a
        // real airgap (egress-isolation) VM test asserts against.
        if spec.net == crate::NetMode::None {
            boot.net = tunnr_vm::NetConfig::None;
        }
        // Host-specific extra QEMU devices tunnr's spec does not model natively (the
        // Skidbladnir report / guest-agent virtio-serial ports, a data drive, a
        // `-snapshot` base-image guard, `-cpu host`) ride through verbatim. Empty
        // leaves the argv byte-identical to a spec that never named them.
        // The removable medium + boot order, then the caller's own extras LAST so a
        // caller can still override (QEMU takes the last `-boot`). Empty when the
        // spec names no medium and no boot order → byte-identical argv to before.
        boot.extra_qemu_args = Self::medium_qemu_args(spec);
        boot.extra_qemu_args.extend(spec.extra_qemu_args.iter().cloned());
        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"))
    }

    /// **Wait for a NAMED LINE on the guest's serial console, or a deadline — never
    /// for the VM to exit.**
    ///
    /// The KVM half of the one stage-2 observation shape ([`Seen`]); its sibling is
    /// `exe::ExeBoot::await_marker`, and both return the same type for the same
    /// reason. An appliance that boots correctly **serves forever** — waiting for
    /// QEMU to exit is waiting for the appliance to fail. So this polls the captured
    /// console (`tunnr_vm::BootHandle::boot_log`, read through
    /// [`serial_log`](KvmBoot::serial_log)) for `marker`, and reports what it saw:
    /// the marker with the console line it was on, the VM having died first, or the
    /// budget elapsing with the guest still up.
    ///
    /// All three are `Ok` — a deadline is an observation, not an error. `Err` is
    /// reserved for "this backend never booted that machine".
    ///
    /// Give the boot a real budget: `DRAUPNIR_VM_BOOT_TIMEOUT` (seconds) raises
    /// tunnr's own SIGKILL backstop, which is a *separate* clock. A budget longer
    /// than that backstop can only ever observe [`Seen::Exited`].
    pub fn await_serial_marker(
        &self,
        machine: &Machine,
        marker: &str,
        budget: std::time::Duration,
        poll: std::time::Duration,
    ) -> Result<Seen> {
        let started = std::time::Instant::now();
        let deadline = started + budget;
        loop {
            let console = self.serial_log(machine).ok_or_else(|| {
                Error::Backend(format!("no live KVM guest for {}", machine.id))
            })?;
            if let Some(line) = console.lines().find(|l| l.contains(marker)) {
                let seen = Seen::Marker {
                    line: line.to_string(),
                    after: started.elapsed(),
                };
                self.record_seen(machine, &seen, true);
                return Ok(seen);
            }
            // Powered Off means the QEMU process is gone (failed / killed / timed
            // out) — the guest cannot print the marker any more, so stop waiting for
            // something that can never arrive and report the console instead.
            if self.status(machine)? == PowerState::Off {
                let seen = Seen::Exited {
                    code: None,
                    tail: console,
                    after: started.elapsed(),
                };
                self.record_seen(machine, &seen, false);
                return Ok(seen);
            }
            let now = std::time::Instant::now();
            if now >= deadline {
                let seen = Seen::StillRunning {
                    tail: console,
                    waited: started.elapsed(),
                };
                self.record_seen(machine, &seen, false);
                return Ok(seen);
            }
            std::thread::sleep(poll.min(deadline.saturating_duration_since(now)));
        }
    }

    /// Record a console observation as a functional-status row, so a marker that
    /// never appeared is visible in nornir's matrix rather than swallowed.
    fn record_seen(&self, machine: &Machine, seen: &Seen, ok: bool) {
        crate::functional_status(
            "draupnir/kvm",
            "await_serial_marker",
            ok,
            &format!("`{}`: {}", machine.id, seen.detail()),
        );
    }

    /// **The removable-medium QEMU argv** — the ONE place a draupnir
    /// [`BootSpec`]'s [`medium`](BootSpec::medium) / [`boot_order`](crate::BootOrder)
    /// become QEMU flags. Pure (no I/O, no feature gate) so it is unit-testable with
    /// no KVM and no tunnr, exactly like tunnr's own `build_qemu_args`.
    ///
    /// Emits, in order:
    /// * `-cdrom <iso>` when the spec carries an explicit
    ///   [`medium`](BootSpec::medium) — an ISO *alongside* the payload disk, which is
    ///   the install shape. Deliberately **not** emitted when the medium comes from
    ///   an [`ImageSource::Iso`] payload: tunnr already renders that as its own
    ///   `-cdrom` (`tunnr/src/boot_primitive.rs:758-765`), and a second `-cdrom` is a
    ///   duplicate-drive error, not a merge. One writer per flag.
    /// * `-boot d|c` for [`BootOrder::Medium`](crate::BootOrder::Medium) /
    ///   [`Disk`](crate::BootOrder::Disk). Safe to repeat: QEMU takes the last
    ///   `-boot`, and for an ISO payload the value tunnr emits (`d`) is the value we
    ///   emit, so the two agree by construction rather than by coincidence.
    ///
    /// [`BootOrder::Auto`](crate::BootOrder::Auto) with no medium returns an **empty**
    /// vector — which is what makes every spec written before this existed produce a
    /// byte-identical argv.
    pub fn medium_qemu_args(spec: &BootSpec) -> Vec<String> {
        let mut args = Vec::new();
        if let Some(iso) = &spec.medium {
            args.push("-cdrom".into());
            args.push(iso.clone());
        }
        if let Some(order) = spec.boot_order.qemu_value() {
            args.push("-boot".into());
            args.push(order.into());
        }
        args
    }

    /// **Fail BY NAME when the medium is not there.** A `-cdrom` pointing at a path
    /// that does not exist makes QEMU die with its own message deep inside a boot,
    /// which reads as "the appliance did not come up" rather than "you named an ISO
    /// that was never built" — the two failures a chain matrix must never confuse.
    ///
    /// Checks whatever [`BootSpec::medium_path`] resolves to (explicit medium or an
    /// [`ImageSource::Iso`] payload), so both spellings of "boot off the medium" are
    /// covered by one check. A spec with no medium is trivially `Ok` and untouched.
    /// Pure of feature gates so it is provable without KVM.
    pub fn check_medium_present(spec: &BootSpec) -> Result<()> {
        let Some(medium) = spec.medium_path() else {
            return Ok(());
        };
        if std::path::Path::new(medium).is_file() {
            Ok(())
        } else {
            Err(Error::Spec(format!(
                "boot medium `{medium}` does not exist (spec `{}`): the ISO must be on \
                 disk before a machine can be booted off it",
                spec.name
            )))
        }
    }

    /// Materialize a [`CloudInit`] into a **NoCloud seed image** at `out` — a thin
    /// call onto the owned builder [`crate::seed::build_seed_image`] (vfat, volume
    /// label `cidata`, pure-Rust `fatfs`, no `genisoimage`/`mkisofs`). The seed
    /// authoring lives in exactly one place ([`crate::seed`]); this is the KVM
    /// backend's call site.
    #[cfg(feature = "backend-tunnr")]
    pub fn build_seed_image(out: &std::path::Path, ci: &CloudInit) -> Result<std::path::PathBuf> {
        crate::seed::build_seed_image(out, ci)
    }
}

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(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"));
    }
}

/// The boot-off-a-medium argv seam. Pure — no tunnr, no KVM, no feature — so the
/// flags a medium turns into are pinned on every build, not only the one that can
/// launch a VM.
#[cfg(test)]
mod medium_tests {
    use super::*;
    use crate::BootOrder;

    #[test]
    fn a_spec_with_no_medium_and_no_boot_order_emits_nothing() {
        // The additive-parity guard, at the argv. Empty here is what makes every
        // pre-existing launch byte-identical.
        // RED-when-broken: make `medium_qemu_args` always push "-boot" and this fails.
        for spec in [
            BootSpec::kvm_kernel_rootfs("a", "/bzImage", "/rootfs.cpio.gz"),
            BootSpec::kvm_disk("b", "/bzImage", "/d.qcow2"),
            BootSpec::kvm_bootloader_disk("c", "/d.qcow2"),
        ] {
            assert!(
                KvmBoot::medium_qemu_args(&spec).is_empty(),
                "{} adds no argv",
                spec.name
            );
        }
    }

    #[test]
    fn the_install_leg_renders_cdrom_plus_boot_d() {
        let spec = BootSpec::kvm_install_from_medium("app", "/images/g.iso", "/target.qcow2");
        assert_eq!(
            KvmBoot::medium_qemu_args(&spec),
            vec!["-cdrom", "/images/g.iso", "-boot", "d"],
            "boot OFF the medium with the target disk still attached"
        );
    }

    #[test]
    fn the_boot_installed_leg_renders_boot_c_and_no_cdrom() {
        let spec = BootSpec::kvm_boot_installed_disk("app", "/target.qcow2");
        let argv = KvmBoot::medium_qemu_args(&spec);
        assert_eq!(argv, vec!["-boot", "c"]);
        assert!(
            !argv.iter().any(|a| a == "-cdrom"),
            "the medium is absent, not merely deprioritised: {argv:?}"
        );
    }

    #[test]
    fn an_iso_payload_does_not_get_a_second_cdrom() {
        // tunnr already renders an `.iso` payload as its own `-cdrom` + `-boot d`
        // (tunnr/src/boot_primitive.rs:758-765). A second `-cdrom` is a QEMU
        // duplicate-drive error, so this path must emit only the boot order.
        // RED-when-broken: render from `medium_path()` instead of the explicit
        // `medium` field and this grows a duplicate `-cdrom`.
        let spec = BootSpec::iso_boot("live", "/images/g.iso");
        assert_eq!(spec.medium_path(), Some("/images/g.iso"), "it IS a medium boot");
        assert_eq!(
            KvmBoot::medium_qemu_args(&spec),
            vec!["-boot", "d"],
            "no second -cdrom for an ISO payload"
        );
    }

    #[test]
    fn a_medium_that_is_not_on_disk_fails_by_name() {
        // "you named an ISO that was never built" must not read as "the appliance
        // did not come up". RED-when-broken: delete `check_medium_present`'s
        // is_file() test and this returns Ok.
        let ghost = BootSpec::kvm_install_from_medium(
            "app",
            "/images/never-built.iso",
            "/target.qcow2",
        );
        let err = KvmBoot::check_medium_present(&ghost).unwrap_err();
        let msg = format!("{err}");
        assert!(matches!(err, Error::Spec(_)));
        assert!(msg.contains("/images/never-built.iso"), "names the ISO: {msg}");
        assert!(msg.contains("does not exist"), "says what is wrong: {msg}");
        assert!(msg.contains("app"), "names the spec: {msg}");

        // A real file passes, and a spec with no medium is trivially fine.
        let real = std::env::current_exe().expect("the test binary is a real file");
        let ok = BootSpec::kvm_install_from_medium(
            "app",
            real.to_string_lossy(),
            "/target.qcow2",
        );
        KvmBoot::check_medium_present(&ok).unwrap();
        KvmBoot::check_medium_present(&BootSpec::kvm_bootloader_disk("n", "/d.qcow2")).unwrap();
    }

    #[test]
    fn a_directory_is_not_a_medium() {
        // `is_file`, not `exists`: a path that happens to be a directory would pass
        // an `exists()` check and then fail inside QEMU.
        let spec = BootSpec::kvm_install_from_medium("app", "/tmp", "/target.qcow2");
        assert!(KvmBoot::check_medium_present(&spec).is_err());
    }

    #[test]
    fn boot_order_maps_to_both_backends_from_one_field() {
        assert_eq!(BootOrder::Auto.qemu_value(), None);
        assert_eq!(BootOrder::Medium.qemu_value(), Some("d"));
        assert_eq!(BootOrder::Disk.qemu_value(), Some("c"));
        assert_eq!(BootOrder::Auto.redfish_target(), None);
        assert_eq!(BootOrder::Medium.redfish_target(), Some(crate::BootTarget::Cd));
        assert_eq!(BootOrder::Disk.redfish_target(), Some(crate::BootTarget::Hdd));
    }
}

#[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` attach the seed image
    /// through tunnr's native `seed` field (`with_seed`); a spec without it leaves
    /// the field `None` and adds no seed `extra_qemu_args`. This pins the
    /// seed-drift fix: the seed rides tunnr's owned seam, not hand-rolled argv.
    #[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.seed.is_none(), "no seed without cloud-init");
        assert!(
            !t.extra_qemu_args.iter().any(|a| a.contains("seed.img")),
            "no hand-rolled seed argv"
        );

        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();
        // The seed rides tunnr's native `seed` field, not `extra_qemu_args`.
        let seed = t
            .seed
            .as_ref()
            .expect("seed image attached via tunnr's with_seed");
        assert!(
            seed.to_string_lossy().contains("draupnir-seeded-seed.img"),
            "the authored seed path is carried: {seed:?}"
        );
        assert!(
            !t.extra_qemu_args.iter().any(|a| a.contains("seed.img")),
            "seed no longer hand-rolled into extra_qemu_args"
        );
        let _ = std::fs::remove_file(KvmBoot::seed_path("seeded"));
    }

    /// A bootloader-in-disk spec validates (no kernel required) and maps to a
    /// tunnr spec with an EMPTY kernel — tunnr's firmware-boot path — and the
    /// disk as `rootfs_or_disk`.
    #[test]
    fn kvm_spec_maps_a_bootloader_disk_onto_an_empty_kernel_tunnr_spec() {
        let spec = BootSpec::kvm_bootloader_disk("selfboot", "/disk.qcow2");
        spec.validate()
            .expect("a bootloader-in-disk spec validates without a kernel");
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        assert!(
            t.kernel.as_os_str().is_empty(),
            "firmware boot: empty kernel, got {:?}",
            t.kernel
        );
        assert!(
            !t.is_direct_kernel_boot(),
            "empty kernel => tunnr firmware-boots the disk"
        );
        assert_eq!(t.rootfs_or_disk, std::path::PathBuf::from("/disk.qcow2"));
        assert!(
            t.base_snapshot,
            "a bootloader-in-disk boot COW-protects its (shared) base disk (snapshot=on)"
        );
    }

    /// RED-when-broken — `persist_disk` is the opt-out that makes **two boots of one
    /// machine** expressible.
    ///
    /// Without it the second boot of an installed disk silently gets a pristine image,
    /// re-runs first-boot provisioning, and reports plausible facts about a machine
    /// that was never installed (measured on oden 2026-08-03: after a full install the
    /// per-run disk copy was byte-identical to the base). The assertion that matters is
    /// that `persist_disk` actually reaches tunnr's drive option, not merely that the
    /// field exists.
    #[test]
    fn persist_disk_turns_the_cow_guard_off_for_a_disk_the_caller_owns() {
        let mut spec = BootSpec::kvm_bootloader_disk("selfboot", "/per-run-copy.qcow2");
        assert!(!spec.persist_disk, "COW protection stays the DEFAULT");
        assert!(
            KvmBoot::new().to_tunnr_spec(&spec).unwrap().base_snapshot,
            "default: writes are thrown away"
        );

        spec.persist_disk = true;
        assert!(
            !KvmBoot::new().to_tunnr_spec(&spec).unwrap().base_snapshot,
            "persist_disk: the caller owns this disk, so its writes must SURVIVE the boot"
        );
    }

    /// The opt-out may only ever turn COW **off**, never on: an image source that
    /// already persists must not become COW-protected by anyone setting the flag.
    #[test]
    fn persist_disk_never_turns_cow_protection_on() {
        for persist in [false, true] {
            let mut spec = BootSpec::kvm_kernel_rootfs("appliance", "/bzImage", "/rootfs.cpio.gz");
            spec.persist_disk = persist;
            assert!(
                !KvmBoot::new().to_tunnr_spec(&spec).unwrap().base_snapshot,
                "kernel+rootfs never COW-protects, persist_disk={persist}"
            );
        }
    }

    #[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_maps_a_disk_boot_with_its_kernel_onto_tunnr() {
        // Regression: a Disk boot must carry a real `-kernel` onto tunnr, not an
        // empty string (the old cmdline_kernel() stub returned "").
        let spec = BootSpec::kvm_disk("disky", "/bzImage", "/disk.qcow2");
        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("/disk.qcow2"));
        assert!(
            !t.kernel.as_os_str().is_empty(),
            "disk boot kernel must be non-empty"
        );
    }

    /// The medium must reach tunnr's actual argv, not merely exist as a field.
    #[test]
    fn the_install_leg_reaches_tunnrs_argv_with_the_target_disk_and_the_cdrom() {
        let iso = write_probe_iso("install-leg");
        let spec = BootSpec::kvm_install_from_medium(
            "app",
            iso.to_string_lossy(),
            "/target.qcow2",
        );
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        // The PAYLOAD is the target disk (firmware boot, no -kernel)...
        assert!(t.kernel.as_os_str().is_empty(), "firmware boot");
        assert_eq!(t.rootfs_or_disk, std::path::PathBuf::from("/target.qcow2"));
        // ...and the medium rides as -cdrom + -boot d.
        assert_eq!(
            t.extra_qemu_args,
            vec![
                "-cdrom".to_string(),
                iso.to_string_lossy().into_owned(),
                "-boot".to_string(),
                "d".to_string()
            ]
        );
        // The install's writes must SURVIVE, or nothing was installed.
        assert!(!t.base_snapshot, "persist_disk turns the COW guard off");
        let _ = std::fs::remove_file(&iso);
    }

    #[test]
    fn the_boot_installed_leg_reaches_tunnrs_argv_with_boot_c_and_no_cdrom() {
        let spec = BootSpec::kvm_boot_installed_disk("app", "/target.qcow2");
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        assert_eq!(t.extra_qemu_args, vec!["-boot".to_string(), "c".to_string()]);
        assert!(!t.base_snapshot, "the installed disk persists");
    }

    #[test]
    fn a_callers_own_extra_qemu_args_still_ride_and_ride_last() {
        // The pre-existing seam is kept whole: the caller's args are appended AFTER
        // the medium's, so a caller can still override (QEMU takes the last -boot).
        let spec = BootSpec::kvm_boot_installed_disk("app", "/target.qcow2")
            .with_extra_qemu_args(["-cpu", "host"]);
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        assert_eq!(
            t.extra_qemu_args,
            vec!["-boot", "c", "-cpu", "host"]
                .into_iter()
                .map(String::from)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn an_iso_payload_maps_onto_tunnrs_own_firmware_cdrom_path() {
        // tunnr renders a `.iso` payload itself; draupnir must hand it over as the
        // payload and add only the boot order.
        let iso = write_probe_iso("payload");
        let spec = BootSpec::iso_boot("live", iso.to_string_lossy());
        let t = KvmBoot::new().to_tunnr_spec(&spec).unwrap();
        assert!(t.kernel.as_os_str().is_empty(), "firmware boots the ISO");
        assert_eq!(t.rootfs_or_disk, iso);
        assert_eq!(t.extra_qemu_args, vec!["-boot".to_string(), "d".to_string()]);
        // ...and tunnr's own pure argv builder turns that into the real flags.
        let argv = tunnr_vm::boot_primitive::build_qemu_args(
            &t,
            std::path::Path::new("/c.fd"),
            std::path::Path::new("/v.fd"),
            None,
        );
        let cdroms = argv.iter().filter(|a| *a == "-cdrom").count();
        assert_eq!(cdroms, 1, "exactly one -cdrom, never two: {argv:?}");
        let _ = std::fs::remove_file(&iso);
    }

    #[test]
    fn to_tunnr_spec_refuses_a_medium_that_is_not_on_disk() {
        // The check runs BEFORE any launch, so a missing ISO is a spec fault here
        // rather than a mystery boot failure later.
        let spec = BootSpec::kvm_install_from_medium("app", "/no/such.iso", "/target.qcow2");
        let err = KvmBoot::new().to_tunnr_spec(&spec).unwrap_err();
        assert!(format!("{err}").contains("/no/such.iso"), "{err}");
    }

    /// A throwaway file to stand in for an ISO where only its EXISTENCE is under
    /// test (the argv shape), not its contents. The real boot proof uses a real ISO.
    fn write_probe_iso(tag: &str) -> std::path::PathBuf {
        let p = std::env::temp_dir().join(format!(
            "draupnir-probe-{tag}-{}.iso",
            std::process::id()
        ));
        std::fs::write(&p, b"not really an iso").unwrap();
        p
    }

    #[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 serial_log_of_an_unknown_machine_is_none() {
        // No live boot for this id → no console (the guard the jera adapter relies on
        // to return an empty drain rather than panic).
        let kvm = KvmBoot::new();
        let m = Machine {
            id: "boot-not-live".into(),
            spec_name: "x".into(),
            backend: crate::Backend::Kvm,
            power: PowerState::Unknown,
        };
        assert!(kvm.serial_log(&m).is_none(), "no live handle → no console");
    }

    #[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);
    }
}