1#[cfg(windows)]
6pub mod hyperv;
7pub mod openvmm;
9pub mod qemu;
11pub mod vtl2_settings;
12
13use crate::PetriLogSource;
14use crate::PetriTestParams;
15use crate::ShutdownKind;
16use crate::disk_image::AgentImage;
17use crate::disk_image::ImageEntry;
18use crate::disk_image::SECTOR_SIZE;
19use crate::mshv_boot::MshvBoot;
20use crate::openhcl_diag::OpenHclDiagHandler;
21use crate::test::PetriPostTestHook;
22use crate::vtl2_settings::ControllerType;
23use crate::vtl2_settings::Vtl2LunBuilder;
24use crate::vtl2_settings::Vtl2StorageBackingDeviceBuilder;
25use crate::vtl2_settings::Vtl2StorageControllerBuilder;
26use anyhow::Context;
27use async_trait::async_trait;
28use futures::FutureExt as _;
29use get_resources::ged::FirmwareEvent;
30use guid::Guid;
31use mesh::CancelContext;
32use openvmm_defs::config::Vtl2BaseAddressType;
33use pal_async::DefaultDriver;
34use pal_async::task::Spawn;
35use pal_async::task::Task;
36use pal_async::timer::PolledTimer;
37use petri_artifact_resolver_openvmm_known_paths::resolve_artifact;
38use petri_artifacts_common::tags::GuestQuirks;
39use petri_artifacts_common::tags::GuestQuirksInner;
40use petri_artifacts_common::tags::InitialRebootCondition;
41use petri_artifacts_common::tags::IsLoadable;
42use petri_artifacts_common::tags::IsOpenhclIgvm;
43use petri_artifacts_common::tags::IsTestVmgs;
44use petri_artifacts_common::tags::MachineArch;
45use petri_artifacts_common::tags::OsFlavor;
46use petri_artifacts_core::ArtifactHandle;
47use petri_artifacts_core::ArtifactId;
48use petri_artifacts_core::ArtifactResolver;
49use petri_artifacts_core::ArtifactSource;
50use petri_artifacts_core::ErasedArtifactHandle;
51use petri_artifacts_core::ResolvedArtifact;
52use petri_artifacts_core::ResolvedArtifactSource;
53use petri_artifacts_core::ResolvedOptionalArtifact;
54use petri_artifacts_core::env::PETRI_REMOTE_ARTIFACTS;
55use petri_artifacts_core::tags::IsNextestArchive;
56use petri_artifacts_vmm_test::env::*;
57use pipette_client::PipetteClient;
58use std::collections::BTreeMap;
59use std::collections::HashMap;
60use std::fmt::Debug;
61use std::io::Write;
62use std::panic::AssertUnwindSafe;
63use std::path::Path;
64use std::path::PathBuf;
65use std::path::absolute;
66use std::sync::Arc;
67use std::time::Duration;
68use tempfile::TempPath;
69use vmgs_resources::GuestStateEncryptionPolicy;
70use vtl2_settings_proto::StorageController;
71use vtl2_settings_proto::Vtl2Settings;
72
73pub struct PetriVmArtifacts<T: PetriVmmBackend> {
76 pub backend: T,
78 pub firmware: Firmware,
80 pub arch: MachineArch,
82 pub agent_image: Option<AgentImage>,
84 pub openhcl_agent_image: Option<AgentImage>,
86 pub pipette_binary: Option<ResolvedArtifact>,
88 pub nested_test: Option<NestedTestDeps>,
90}
91
92impl<T: PetriVmmBackend> PetriVmArtifacts<T> {
93 pub fn new(
97 resolver: &ArtifactResolver<'_>,
98 firmware: Firmware,
99 arch: MachineArch,
100 with_vtl0_pipette: bool,
101 ) -> Option<Self> {
102 Self::new_maybe_nested(resolver, firmware, arch, with_vtl0_pipette, None)
103 }
104
105 pub fn new_maybe_nested(
109 resolver: &ArtifactResolver<'_>,
110 firmware: Firmware,
111 arch: MachineArch,
112 with_vtl0_pipette: bool,
113 nested_test: Option<NestedTestDeps>,
114 ) -> Option<Self> {
115 let different_nested_target = nested_test
118 .as_ref()
119 .map(|t| t.archive.target_triple().unwrap())
120 .is_some_and(|t| {
121 let host_target = target_lexicon::Triple::host();
122 host_target.operating_system != t.operating_system
123 });
124
125 if !(T::SUPPORTS_CPU_EMULATION || arch == MachineArch::host())
126 || !T::check_compat(&firmware, arch)
127 || different_nested_target && !T::supports_file_sharing(&firmware)
128 {
129 return None;
130 }
131
132 let pipette_binary = if with_vtl0_pipette {
133 Some(Self::resolve_pipette_binary(
134 resolver,
135 firmware.os_flavor(),
136 arch,
137 ))
138 } else {
139 None
140 };
141
142 Some(Self {
143 backend: T::new(resolver, arch),
144 arch,
145 agent_image: (!firmware.is_isolated_without_paravisor()).then(|| {
146 if with_vtl0_pipette {
147 AgentImage::new(firmware.os_flavor()).with_pipette(resolver, arch)
148 } else {
149 AgentImage::new(firmware.os_flavor())
150 }
151 }),
152 openhcl_agent_image: if firmware.is_openhcl() {
153 Some(AgentImage::new(OsFlavor::Linux).with_pipette(resolver, arch))
154 } else {
155 None
156 },
157 pipette_binary,
158 firmware,
159 nested_test,
160 })
161 }
162
163 fn resolve_pipette_binary(
164 resolver: &ArtifactResolver<'_>,
165 os_flavor: OsFlavor,
166 arch: MachineArch,
167 ) -> ResolvedArtifact {
168 use petri_artifacts_common::artifacts as common_artifacts;
169 match (os_flavor, arch) {
170 (OsFlavor::Linux, MachineArch::X86_64) => resolver
171 .require(common_artifacts::PIPETTE_LINUX_X64_MUSL)
172 .erase(),
173 (OsFlavor::Linux, MachineArch::Aarch64) => resolver
174 .require(common_artifacts::PIPETTE_LINUX_AARCH64_MUSL)
175 .erase(),
176 (OsFlavor::Windows, MachineArch::X86_64) => resolver
177 .require(common_artifacts::PIPETTE_WINDOWS_X64)
178 .erase(),
179 (OsFlavor::Windows, MachineArch::Aarch64) => resolver
180 .require(common_artifacts::PIPETTE_WINDOWS_AARCH64)
181 .erase(),
182 (OsFlavor::FreeBsd | OsFlavor::Uefi, _) => {
183 panic!("No pipette binary for this OS flavor")
184 }
185 }
186 }
187}
188
189pub struct PetriVmBuilder<T: PetriVmmBackend> {
191 backend: T,
193 config: PetriVmConfig,
195 modify_vmm_config: Option<ModifyFn<T::VmmConfig>>,
197 resources: PetriVmResources,
199
200 guest_quirks: GuestQuirksInner,
202 vmm_quirks: VmmQuirks,
203
204 expected_boot_event: Option<FirmwareEvent>,
207 override_expect_reset: bool,
208
209 agent_image: Option<AgentImage>,
213 openhcl_agent_image: Option<AgentImage>,
215 boot_device_type: BootDeviceType,
217 pcie_boot_port: Option<String>,
220
221 minimal_mode: bool,
223 pipette_binary: Option<ResolvedArtifact>,
225 enable_serial: bool,
227 use_virtio_console: bool,
228 enable_screenshots: bool,
230 use_virtio_vsock: bool,
232 #[cfg(target_os = "linux")]
234 vhost_vsock_guest_cid: Option<u32>,
235 no_vmbus: bool,
237 no_hv: bool,
239 capture_inspect_on_failure: bool,
241 watchdog_timeout: Option<Duration>,
242 external_pipette: bool,
243
244 nested_test: Option<ResolvedNestedTestDeps>,
245}
246
247const INSPECT_TIMEOUT: Duration = Duration::from_secs(10);
249
250impl<T: PetriVmmBackend> Debug for PetriVmBuilder<T> {
251 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
252 let Self {
253 backend,
254 config,
255 modify_vmm_config,
256 resources,
257 guest_quirks,
258 vmm_quirks,
259 expected_boot_event,
260 override_expect_reset,
261 agent_image,
262 openhcl_agent_image,
263 boot_device_type,
264 pcie_boot_port,
265 minimal_mode,
266 pipette_binary,
267 enable_serial,
268 use_virtio_console,
269 enable_screenshots,
270 use_virtio_vsock,
271 #[cfg(target_os = "linux")]
272 vhost_vsock_guest_cid,
273 no_vmbus,
274 no_hv,
275 capture_inspect_on_failure,
276 watchdog_timeout,
277 external_pipette,
278 nested_test,
279 } = self;
280
281 let mut s = f.debug_struct("PetriVmBuilder");
282 s.field("backend", backend)
283 .field("config", config)
284 .field("modify_vmm_config", modify_vmm_config)
285 .field("resources", resources)
286 .field("guest_quirks", guest_quirks)
287 .field("vmm_quirks", vmm_quirks)
288 .field("expected_boot_event", expected_boot_event)
289 .field("override_expect_reset", override_expect_reset)
290 .field("agent_image", agent_image)
291 .field("openhcl_agent_image", openhcl_agent_image)
292 .field("boot_device_type", boot_device_type)
293 .field("pcie_boot_port", pcie_boot_port)
294 .field("minimal_mode", minimal_mode)
295 .field("pipette_binary", pipette_binary)
296 .field("enable_serial", enable_serial)
297 .field("use_virtio_console", use_virtio_console)
298 .field("enable_screenshots", enable_screenshots)
299 .field("use_virtio_vsock", use_virtio_vsock);
300 #[cfg(target_os = "linux")]
301 s.field("vhost_vsock_guest_cid", vhost_vsock_guest_cid);
302 s.field("no_vmbus", no_vmbus)
303 .field("no_hv", no_hv)
304 .field("capture_inspect_on_failure", capture_inspect_on_failure)
305 .field("watchdog_timeout", watchdog_timeout)
306 .field("external_pipette", external_pipette)
307 .field("nested_test", nested_test)
308 .finish()
309 }
310}
311
312#[derive(Debug, Clone)]
314pub struct PetriVmConfig {
315 pub name: String,
317 pub arch: MachineArch,
319 pub host_log_levels: Option<OpenvmmLogConfig>,
321 pub firmware: Firmware,
323 pub hibernation_enabled: bool,
325 pub ipmi_enabled: bool,
327 pub memory: MemoryConfig,
329 pub proc_topology: ProcessorTopology,
331 pub nested_virt_enabled: bool,
333 pub vmgs: PetriVmgsResource,
335 pub tpm: Option<TpmConfig>,
337 pub vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
339 pub pcie_nvme_drives: Vec<PcieNvmeDrive>,
341 pub pcie_virtio_blk_drives: Vec<PcieVirtioBlkDrive>,
343 pub physical_nvme_devices: HashMap<Guid, PhysicalNvmeDevice>,
345 pub guest_shares: HashMap<String, GuestShare>,
347}
348
349#[derive(Debug, Clone)]
351pub struct GuestShare {
352 pub host_path: PathBuf,
354 pub guest_path: String,
356}
357
358#[derive(Debug, Clone)]
360pub struct PcieNvmeDrive {
361 pub port_name: String,
363 pub nsid: u32,
365 pub drive: Drive,
367}
368
369#[derive(Debug, Clone)]
371pub struct PcieVirtioBlkDrive {
372 pub port_name: String,
374 pub drive: Drive,
376}
377
378#[derive(Debug, Clone)]
381pub struct PhysicalNvmeDevice {
382 pub target_vtl: Vtl,
384 pub nsid: u32,
386 pub namespace_size_mib: u64,
388}
389
390#[derive(Clone)]
393pub struct PetriVmProperties {
394 pub is_openhcl: bool,
396 pub is_isolated: bool,
398 pub is_pcat: bool,
400 pub is_linux_direct: bool,
402 pub using_vtl0_pipette: bool,
404 pub external_pipette: bool,
406 pub using_vpci: bool,
408 pub os_flavor: OsFlavor,
410 pub minimal_mode: bool,
412 pub uses_pipette_as_init: bool,
414 pub enable_serial: bool,
416 pub use_virtio_console: bool,
418 pub has_agent_disk: bool,
420 pub use_virtio_vsock: bool,
422 #[cfg(target_os = "linux")]
424 pub vhost_vsock_guest_cid: Option<u32>,
425 pub no_vmbus: bool,
427 pub no_hv: bool,
429}
430
431pub struct PetriVmRuntimeConfig {
433 pub vtl2_settings: Option<Vtl2Settings>,
435 pub ide_controllers: Option<[[Option<Drive>; 2]; 2]>,
437 pub vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
439}
440
441#[derive(Debug)]
443pub struct PetriVmResources {
444 pub driver: DefaultDriver,
446 pub log_source: PetriLogSource,
448 pub prebuilt_initrd: Option<PetriInitrd>,
450}
451
452#[async_trait]
454pub trait PetriVmmBackend: Debug {
455 type VmmConfig: 'static;
457
458 type VmRuntime: PetriVmRuntime;
460
461 const SUPPORTS_VMBUS: bool;
463
464 const SUPPORTS_CPU_EMULATION: bool = false;
469
470 const SUPPORTS_FILE_SHARING: bool = false;
472
473 fn supports_file_sharing(firmware: &Firmware) -> bool {
475 Self::SUPPORTS_FILE_SHARING && firmware.os_flavor() == OsFlavor::Linux
476 }
477
478 fn check_compat(firmware: &Firmware, arch: MachineArch) -> bool;
487
488 fn quirks(firmware: &Firmware) -> (GuestQuirksInner, VmmQuirks);
490
491 fn default_servicing_flags() -> OpenHclServicingFlags;
493
494 fn create_guest_dump_disk() -> anyhow::Result<
497 Option<(
498 Arc<TempPath>,
499 Box<dyn FnOnce() -> anyhow::Result<Box<dyn fatfs::ReadWriteSeek>>>,
500 )>,
501 >;
502
503 fn build_custom_init_script(pipette_path: &str) -> Option<String>;
506
507 fn new(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self;
512
513 async fn run(
515 self,
516 config: PetriVmConfig,
517 modify_vmm_config: Option<ModifyFn<Self::VmmConfig>>,
518 resources: &PetriVmResources,
519 properties: &PetriVmProperties,
520 ) -> anyhow::Result<(Self::VmRuntime, PetriVmRuntimeConfig)>;
521}
522
523pub(crate) const PETRI_IDE_BOOT_CONTROLLER_NUMBER: u32 = 0;
525pub(crate) const PETRI_IDE_BOOT_LUN: u8 = 0;
526pub(crate) const PETRI_IDE_BOOT_CONTROLLER: Guid =
527 guid::guid!("ca56751f-e643-4bef-bf54-f73678e8b7b5");
528
529pub(crate) const PETRI_SCSI_BOOT_LUN: u32 = 0;
531pub(crate) const PETRI_SCSI_PIPETTE_LUN: u32 = 1;
532pub(crate) const PETRI_SCSI_CRASH_LUN: u32 = 2;
533pub(crate) const PETRI_SCSI_VTL0_CONTROLLER: Guid =
535 guid::guid!("27b553e8-8b39-411b-a55f-839971a7884f");
536pub(crate) const PETRI_SCSI_VTL2_CONTROLLER: Guid =
538 guid::guid!("766e96f8-2ceb-437e-afe3-a93169e48a7c");
539pub(crate) const PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER: Guid =
541 guid::guid!("6c474f47-ed39-49e6-bbb9-142177a1da6e");
542
543pub(crate) const PETRI_NVME_BOOT_NSID: u32 = 37;
545pub(crate) const PETRI_NVME_BOOT_VTL0_CONTROLLER: Guid =
547 guid::guid!("e23a04e2-90f5-4852-bc9d-e7ac691b756c");
548pub(crate) const PETRI_NVME_BOOT_VTL2_CONTROLLER: Guid =
550 guid::guid!("92bc8346-718b-449a-8751-edbf3dcd27e4");
551
552pub(crate) const PETRI_PCIE_NVME_AGENT_PORT: &str = "s0rc0rp1";
554pub(crate) const PETRI_PCIE_NVME_AGENT_NSID: u32 = 1;
556
557const NESTED_TEST_CONTENT_DIR: &str = "vmm_tests";
558const NESTED_IMAGES_DIR: &str = "images";
559const NESTED_RESULTS_DIR: &str = "test_results";
560const NESTED_TEST_BINARY: &str = "nested_test";
561const NESTED_TEMP_DIR: &str = "temp";
562const NESTED_CONTENT_TAG: &str = "testcontent";
563const NESTED_IMAGES_TAG: &str = "testimages";
564
565pub struct PetriVm<T: PetriVmmBackend> {
567 resources: PetriVmResources,
568 runtime: PetriVmRuntimeGuard<T::VmRuntime>,
569 watchdog_tasks: Vec<Task<()>>,
570 openhcl_diag_handler: Option<OpenHclDiagHandler>,
571
572 arch: MachineArch,
573 guest_quirks: GuestQuirksInner,
574 vmm_quirks: VmmQuirks,
575 expected_boot_event: Option<FirmwareEvent>,
576
577 config: PetriVmRuntimeConfig,
578 properties: PetriVmProperties,
579
580 nested_test: Option<ResolvedNestedTestDeps>,
581 guest_shares: HashMap<String, GuestShare>,
582 name: String,
583}
584
585struct PetriVmRuntimeGuard<T: PetriVmRuntime> {
589 runtime: Option<T>,
590 driver: DefaultDriver,
591 log_source: PetriLogSource,
592 capture_inspect_on_drop: bool,
593}
594
595impl<T: PetriVmRuntime> PetriVmRuntimeGuard<T> {
596 fn take_for_teardown(&mut self) -> T {
597 self.runtime.take().expect("runtime has already been taken")
598 }
599}
600
601impl<T: PetriVmRuntime> std::ops::Deref for PetriVmRuntimeGuard<T> {
602 type Target = T;
603
604 fn deref(&self) -> &T {
605 self.runtime
606 .as_ref()
607 .expect("runtime has already been taken")
608 }
609}
610
611impl<T: PetriVmRuntime> std::ops::DerefMut for PetriVmRuntimeGuard<T> {
612 fn deref_mut(&mut self) -> &mut T {
613 self.runtime
614 .as_mut()
615 .expect("runtime has already been taken")
616 }
617}
618
619impl<T: PetriVmRuntime> Drop for PetriVmRuntimeGuard<T> {
620 fn drop(&mut self) {
621 let Some(runtime) = self.runtime.take() else {
622 return;
623 };
624 if !self.capture_inspect_on_drop {
625 return;
626 }
627 let inspector = runtime.inspector();
628 let openhcl_diag_handler = runtime.openhcl_diag();
629 if inspector.is_none() && openhcl_diag_handler.is_none() {
630 return;
631 }
632 let log_source = self.log_source.clone();
633
634 let capture = async move {
635 let vmm = async {
636 if let Some(inspector) = &inspector {
637 collect_inspect("vmm", inspector.inspect(""), &log_source, "failure").await;
638 }
639 };
640 let openhcl = async {
641 if let Some(diag) = &openhcl_diag_handler {
642 collect_inspect(
643 "openhcl",
644 diag.inspect("", None, None),
645 &log_source,
646 "failure",
647 )
648 .await;
649 }
650 };
651 futures::future::join(vmm, openhcl).await;
652 drop(runtime);
653 };
654
655 self.driver
659 .spawn("petri-inspect-on-drop", async move {
660 if let Err(e) = AssertUnwindSafe(capture).catch_unwind().await {
663 tracing::error!(?e, "panicked while collecting inspect state");
664 }
665 })
666 .detach();
667 }
668}
669
670impl<T: PetriVmmBackend> PetriVmBuilder<T> {
671 pub fn new(
673 params: PetriTestParams<'_>,
674 artifacts: PetriVmArtifacts<T>,
675 driver: &DefaultDriver,
676 ) -> anyhow::Result<Self> {
677 let isolated_without_paravisor = artifacts.firmware.is_isolated_without_paravisor();
678 let mshv = artifacts.firmware.mshv_boot().is_some();
679 let builder = Self::minimal(params.test_name, params.log_source, artifacts, driver)?
680 .clear_minimal_mode()
681 .with_serial_output()
682 .with_capture_inspect_on_failure();
683 if isolated_without_paravisor || mshv {
684 Ok(builder)
685 } else {
686 builder
687 .add_petri_scsi_controllers()
688 .add_guest_crash_disk(params.post_test_hooks)
689 }
690 }
691
692 pub fn minimal(
703 test_name: &str,
704 log_source: &PetriLogSource,
705 artifacts: PetriVmArtifacts<T>,
706 driver: &DefaultDriver,
707 ) -> anyhow::Result<Self> {
708 let isolated_without_paravisor = artifacts.firmware.is_isolated_without_paravisor();
709 match &artifacts.firmware {
710 Firmware::Uefi {
711 guest: UefiGuest::Mshv(_),
712 ..
713 } => anyhow::ensure!(
714 artifacts.arch == MachineArch::X86_64,
715 "mshv boot requires x86-64 UEFI"
716 ),
717 Firmware::OpenhclUefi {
718 guest: UefiGuest::Mshv(_),
719 ..
720 } => anyhow::bail!("mshv boot with OpenHCL is not supported"),
721 _ => {}
722 }
723 let (guest_quirks, vmm_quirks) = T::quirks(&artifacts.firmware);
724 let expected_boot_event = artifacts.firmware.expected_boot_event();
725 let boot_device_type = match artifacts.firmware {
726 Firmware::LinuxDirect { .. } | Firmware::IgvmLinuxDirect { .. } => BootDeviceType::None,
727 Firmware::OpenhclLinuxDirect { .. } => BootDeviceType::None,
728 Firmware::Pcat { .. } => BootDeviceType::Ide,
729 Firmware::OpenhclPcat { .. } => BootDeviceType::IdeViaScsi,
730 Firmware::Uefi {
731 guest: UefiGuest::None,
732 ..
733 }
734 | Firmware::OpenhclUefi {
735 guest: UefiGuest::None,
736 ..
737 } => BootDeviceType::None,
738 Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } => BootDeviceType::Scsi,
739 };
740
741 let supports_file_sharing = T::supports_file_sharing(&artifacts.firmware);
742 let external_pipette = isolated_without_paravisor && artifacts.pipette_binary.is_some();
743 let builder = Self {
744 backend: artifacts.backend,
745 config: PetriVmConfig {
746 name: test_name.to_string(),
747 arch: artifacts.arch,
748 host_log_levels: None,
749 firmware: artifacts.firmware,
750 hibernation_enabled: false,
751 ipmi_enabled: false,
752 memory: Default::default(),
753 proc_topology: Default::default(),
754 nested_virt_enabled: false,
755
756 vmgs: PetriVmgsResource::Ephemeral,
757 tpm: None,
758 vmbus_storage_controllers: HashMap::new(),
759 pcie_nvme_drives: Vec::new(),
760 pcie_virtio_blk_drives: Vec::new(),
761 physical_nvme_devices: HashMap::new(),
762 guest_shares: HashMap::new(),
763 },
764 modify_vmm_config: None,
765 resources: PetriVmResources {
766 driver: driver.clone(),
767 log_source: log_source.clone(),
768 prebuilt_initrd: None,
769 },
770
771 guest_quirks,
772 vmm_quirks,
773 expected_boot_event,
774 override_expect_reset: false,
775
776 agent_image: artifacts.agent_image,
777 openhcl_agent_image: artifacts.openhcl_agent_image,
778 boot_device_type,
779 pcie_boot_port: None,
780
781 minimal_mode: true,
782 pipette_binary: artifacts.pipette_binary,
783 enable_serial: false,
784 use_virtio_console: false,
785 enable_screenshots: true,
786 use_virtio_vsock: isolated_without_paravisor,
787 #[cfg(target_os = "linux")]
788 vhost_vsock_guest_cid: None,
789 no_vmbus: !T::SUPPORTS_VMBUS || isolated_without_paravisor,
790 no_hv: false,
791 capture_inspect_on_failure: false,
792 watchdog_timeout: Some(Duration::from_mins(10)),
793 external_pipette: false,
794
795 nested_test: artifacts
796 .nested_test
797 .map(|t| t.resolve(!supports_file_sharing))
798 .transpose()?,
799 };
800 Ok(if external_pipette {
801 builder.with_external_pipette()
802 } else {
803 builder
804 })
805 }
806
807 fn clear_minimal_mode(mut self) -> Self {
808 self.minimal_mode = false;
809 self
810 }
811
812 pub fn with_shared_directory(
816 mut self,
817 tag: &str,
818 host_path: impl AsRef<Path>,
819 guest_path: &str,
820 ) -> Self {
821 assert!(
822 T::supports_file_sharing(&self.config.firmware),
823 "directory sharing requires a backend with Linux file-sharing support"
824 );
825 assert!(
826 !tag.is_empty()
827 && !tag.starts_with('-')
828 && tag
829 .bytes()
830 .all(|c| c.is_ascii_alphanumeric() || b"-_".contains(&c)),
831 "invalid filesystem share tag"
832 );
833 assert!(
834 guest_path.starts_with('/')
835 && !guest_path.contains('\0')
836 && !guest_path.split('/').any(|c| c == ".."),
837 "guest mount point must be an absolute path without parent traversal"
838 );
839 assert!(
840 !self.config.guest_shares.contains_key(tag),
841 "duplicate filesystem share tag: {tag}"
842 );
843 self.config.guest_shares.insert(
844 tag.into(),
845 GuestShare {
846 host_path: host_path.as_ref().to_path_buf(),
847 guest_path: guest_path.into(),
848 },
849 );
850 self
851 }
852
853 fn with_capture_inspect_on_failure(mut self) -> Self {
854 self.capture_inspect_on_failure = true;
855 self
856 }
857
858 pub fn is_minimal(&self) -> bool {
860 self.minimal_mode
861 }
862
863 pub fn with_watchdog_timeout(mut self, timeout: Option<Duration>) -> Self {
866 self.watchdog_timeout = timeout;
867 self
868 }
869
870 pub fn with_external_pipette(mut self) -> Self {
876 self.external_pipette = true;
877 self.agent_image = None;
878 self.pipette_binary = None;
879 self
880 }
881
882 pub fn with_prebuilt_initrd(mut self, initrd: PetriInitrd) -> Self {
889 self.resources.prebuilt_initrd = Some(initrd);
890 self
891 }
892
893 pub fn prepare_initrd(&self) -> anyhow::Result<PetriInitrd> {
904 if let Some(boot) = self.config.firmware.mshv_boot() {
905 return boot.prepare_initrd(
906 self.pipette_binary
907 .as_ref()
908 .context("mshv initrd preparation requires Pipette")?,
909 );
910 }
911 self.prepare_custom_initrd(T::build_custom_init_script)
912 }
913
914 pub fn prepare_custom_initrd(
916 &self,
917 build_custom_init_script: impl FnOnce(&str) -> Option<String>,
918 ) -> anyhow::Result<PetriInitrd> {
919 const PIPETTE_PATH: &str = "pipette";
920 const INIT_SCRIPT_NAME: &str = "custom-init.sh";
921
922 let initrd_path = self
923 .config
924 .firmware
925 .linux_direct_initrd()
926 .context("prepare_initrd requires Linux direct boot with initrd")?;
927 let pipette_path = self
928 .pipette_binary
929 .as_ref()
930 .context("prepare_initrd requires a pipette binary")?;
931
932 let pipette_data = std::fs::read(pipette_path.get()).with_context(|| {
933 format!(
934 "failed to read pipette binary at {}",
935 pipette_path.get().display()
936 )
937 })?;
938
939 let mut files = vec![crate::initrd::InitrdFile {
940 name: PIPETTE_PATH,
941 contents: &pipette_data,
942 permissions: 0o755,
943 }];
944 let script = build_custom_init_script(PIPETTE_PATH);
945 let rdinit = if let Some(script) = &script {
946 files.push(crate::initrd::InitrdFile {
947 name: INIT_SCRIPT_NAME,
948 contents: script.as_bytes(),
949 permissions: 0o755,
950 });
951 format!("/{INIT_SCRIPT_NAME}")
952 } else {
953 format!("/{PIPETTE_PATH}")
954 };
955 PetriInitrd::prepare(initrd_path, &files, &rdinit, None)
956 }
957
958 pub fn with_serial_output(mut self) -> Self {
967 self.enable_serial = true;
968 self
969 }
970
971 pub fn without_serial_output(mut self) -> Self {
976 self.enable_serial = false;
977 self
978 }
979
980 pub fn without_screenshots(mut self) -> Self {
985 self.enable_screenshots = false;
986 self
987 }
988
989 pub fn with_virtio_vsock(mut self, enable: bool) -> Self {
1002 self.use_virtio_vsock = enable;
1003 #[cfg(target_os = "linux")]
1004 {
1005 self.vhost_vsock_guest_cid = None;
1006 }
1007 self
1008 }
1009
1010 #[cfg(target_os = "linux")]
1016 pub fn with_vhost_vsock(mut self, guest_cid: u32) -> Self {
1017 assert!(
1018 (3..u32::MAX).contains(&guest_cid),
1019 "vhost-vsock guest CID must be between 3 and {}",
1020 u32::MAX - 1
1021 );
1022 self.use_virtio_vsock = true;
1023 self.vhost_vsock_guest_cid = Some(guest_cid);
1024 self
1025 }
1026
1027 pub fn with_no_vmbus(mut self) -> Self {
1035 self.no_vmbus = true;
1036 if self.config.firmware.os_flavor() != OsFlavor::Windows {
1037 self.use_virtio_vsock = true;
1038 }
1039 self.config.vmbus_storage_controllers.clear();
1040 self
1041 }
1042
1043 pub fn with_no_hv(mut self) -> Self {
1049 self.no_hv = true;
1050 self.with_no_vmbus()
1051 }
1052
1053 fn add_petri_scsi_controllers(mut self) -> Self {
1054 if T::SUPPORTS_VMBUS {
1055 self = self.add_vmbus_storage_controller(
1056 &PETRI_SCSI_VTL0_CONTROLLER,
1057 Vtl::Vtl0,
1058 VmbusStorageType::Scsi,
1059 );
1060
1061 if self.is_openhcl() {
1062 self = self.add_vmbus_storage_controller(
1063 &PETRI_SCSI_VTL2_CONTROLLER,
1064 Vtl::Vtl2,
1065 VmbusStorageType::Scsi,
1066 )
1067 }
1068 }
1069 self
1070 }
1071
1072 fn add_guest_crash_disk(
1073 self,
1074 post_test_hooks: &mut Vec<PetriPostTestHook>,
1075 ) -> anyhow::Result<Self> {
1076 let supports_vmbus_crash_disk = !self.no_vmbus
1077 && matches!(
1078 self.config.firmware.os_flavor(),
1079 OsFlavor::Windows | OsFlavor::Linux
1080 );
1081
1082 let (disk, disk_hook) = supports_vmbus_crash_disk
1083 .then(|| T::create_guest_dump_disk().context("failed to create guest dump disk"))
1084 .transpose()?
1085 .flatten()
1086 .unzip();
1087
1088 if let Some(disk_hook) = disk_hook {
1089 let logger = self.resources.log_source.clone();
1090 post_test_hooks.push(PetriPostTestHook::new(
1091 "extract guest crash dumps".into(),
1092 move |test_passed| {
1093 if test_passed {
1094 return Ok(());
1095 }
1096 let mut disk = disk_hook()?;
1097 let gpt = gptman::GPT::read_from(&mut disk, SECTOR_SIZE)?;
1098 let partition = fscommon::StreamSlice::new(
1099 &mut disk,
1100 gpt[1].starting_lba * SECTOR_SIZE,
1101 gpt[1].ending_lba * SECTOR_SIZE,
1102 )?;
1103 let fs = fatfs::FileSystem::new(partition, fatfs::FsOptions::new())?;
1104 for entry in fs.root_dir().iter() {
1105 let Ok(entry) = entry else {
1106 tracing::warn!(?entry, "failed to read entry in guest crash dump disk");
1107 continue;
1108 };
1109 if !entry.is_file() {
1110 tracing::warn!(
1111 ?entry,
1112 "skipping non-file entry in guest crash dump disk"
1113 );
1114 continue;
1115 }
1116 logger.write_attachment(&entry.file_name(), entry.to_file())?;
1117 }
1118 Ok(())
1119 },
1120 ));
1121 }
1122
1123 Ok(if let Some(disk) = disk {
1124 self.add_vmbus_drive(
1125 Drive::new(Some(Disk::Temporary(disk)), false),
1126 &PETRI_SCSI_VTL0_CONTROLLER,
1127 Some(PETRI_SCSI_CRASH_LUN),
1128 )
1129 } else {
1130 self
1131 })
1132 }
1133
1134 fn add_agent_disks(self) -> anyhow::Result<Self> {
1135 self.add_agent_disk_inner(Vtl::Vtl0)?
1136 .add_agent_disk_inner(Vtl::Vtl2)
1137 }
1138
1139 fn add_agent_disk_inner(mut self, target_vtl: Vtl) -> anyhow::Result<Self> {
1140 let (agent_image, controller_id) = match target_vtl {
1141 Vtl::Vtl0 => (self.agent_image.as_ref(), PETRI_SCSI_VTL0_CONTROLLER),
1142 Vtl::Vtl1 => panic!("no VTL1 agent disk"),
1143 Vtl::Vtl2 => (
1144 self.openhcl_agent_image.as_ref(),
1145 PETRI_SCSI_VTL2_CONTROLLER,
1146 ),
1147 };
1148
1149 if target_vtl == Vtl::Vtl0
1152 && self.uses_pipette_as_init()
1153 && !agent_image.is_some_and(|i| i.has_extras())
1154 {
1155 return Ok(self);
1156 }
1157
1158 let Some(agent_disk) = agent_image
1159 .map(|i| {
1160 i.build(crate::disk_image::ImageType::Vhd)
1161 .context("failed to build agent image")
1162 })
1163 .transpose()?
1164 .flatten()
1165 else {
1166 return Ok(self);
1167 };
1168
1169 if self.no_vmbus {
1172 self.config.pcie_nvme_drives.push(PcieNvmeDrive {
1173 port_name: PETRI_PCIE_NVME_AGENT_PORT.into(),
1174 nsid: PETRI_PCIE_NVME_AGENT_NSID,
1175 drive: Drive::new(
1176 Some(Disk::Temporary(Arc::new(agent_disk.into_temp_path()))),
1177 false,
1178 ),
1179 });
1180 return Ok(self);
1181 }
1182
1183 if !self
1186 .config
1187 .vmbus_storage_controllers
1188 .contains_key(&controller_id)
1189 {
1190 self = self.add_vmbus_storage_controller(
1191 &controller_id,
1192 target_vtl,
1193 VmbusStorageType::Scsi,
1194 );
1195 }
1196
1197 Ok(self.add_vmbus_drive(
1198 Drive::new(
1199 Some(Disk::Temporary(Arc::new(agent_disk.into_temp_path()))),
1200 false,
1201 ),
1202 &controller_id,
1203 Some(PETRI_SCSI_PIPETTE_LUN),
1204 ))
1205 }
1206
1207 fn add_boot_disk(mut self) -> anyhow::Result<Self> {
1208 if self.boot_device_type.requires_vtl2() && !self.is_openhcl() {
1209 panic!("boot device type {:?} requires vtl2", self.boot_device_type);
1210 }
1211
1212 if self.no_vmbus && self.boot_device_type.requires_vmbus() {
1213 panic!(
1214 "boot device type {:?} requires vmbus, but vmbus is disabled; \
1215 use with_boot_device_type(BootDeviceType::PcieNvme) or similar",
1216 self.boot_device_type
1217 );
1218 }
1219
1220 if self.boot_device_type.requires_vpci_boot() {
1221 self.config
1222 .firmware
1223 .uefi_config_mut()
1224 .expect("vpci boot requires uefi")
1225 .enable_vpci_boot = true;
1226 }
1227
1228 let builder = if let Some(boot_drive) = self.config.firmware.boot_drive(
1229 self.use_virtio_vsock,
1230 self.resources.prebuilt_initrd.as_ref(),
1231 )? {
1232 match self.boot_device_type {
1233 BootDeviceType::None => unreachable!(),
1234 BootDeviceType::Ide => self.add_ide_drive(
1235 boot_drive,
1236 PETRI_IDE_BOOT_CONTROLLER_NUMBER,
1237 PETRI_IDE_BOOT_LUN,
1238 ),
1239 BootDeviceType::IdeViaScsi => self
1240 .add_vmbus_drive(
1241 boot_drive,
1242 &PETRI_SCSI_VTL2_CONTROLLER,
1243 Some(PETRI_SCSI_BOOT_LUN),
1244 )
1245 .add_vtl2_storage_controller(
1246 Vtl2StorageControllerBuilder::new(ControllerType::Ide)
1247 .with_instance_id(PETRI_IDE_BOOT_CONTROLLER)
1248 .add_lun(
1249 Vtl2LunBuilder::disk()
1250 .with_channel(PETRI_IDE_BOOT_CONTROLLER_NUMBER)
1251 .with_location(PETRI_IDE_BOOT_LUN as u32)
1252 .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1253 ControllerType::Scsi,
1254 PETRI_SCSI_VTL2_CONTROLLER,
1255 PETRI_SCSI_BOOT_LUN,
1256 )),
1257 )
1258 .build(),
1259 ),
1260 BootDeviceType::IdeViaNvme => todo!(),
1261 BootDeviceType::Scsi => self.add_vmbus_drive(
1262 boot_drive,
1263 &PETRI_SCSI_VTL0_CONTROLLER,
1264 Some(PETRI_SCSI_BOOT_LUN),
1265 ),
1266 BootDeviceType::ScsiViaScsi => self
1267 .add_vmbus_drive(
1268 boot_drive,
1269 &PETRI_SCSI_VTL2_CONTROLLER,
1270 Some(PETRI_SCSI_BOOT_LUN),
1271 )
1272 .add_vtl2_storage_controller(
1273 Vtl2StorageControllerBuilder::new(ControllerType::Scsi)
1274 .with_instance_id(PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER)
1275 .add_lun(
1276 Vtl2LunBuilder::disk()
1277 .with_location(PETRI_SCSI_BOOT_LUN)
1278 .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1279 ControllerType::Scsi,
1280 PETRI_SCSI_VTL2_CONTROLLER,
1281 PETRI_SCSI_BOOT_LUN,
1282 )),
1283 )
1284 .build(),
1285 ),
1286 BootDeviceType::ScsiViaNvme => self
1287 .add_vmbus_storage_controller(
1288 &PETRI_NVME_BOOT_VTL2_CONTROLLER,
1289 Vtl::Vtl2,
1290 VmbusStorageType::Nvme,
1291 )
1292 .add_vmbus_drive(
1293 boot_drive,
1294 &PETRI_NVME_BOOT_VTL2_CONTROLLER,
1295 Some(PETRI_NVME_BOOT_NSID),
1296 )
1297 .add_vtl2_storage_controller(
1298 Vtl2StorageControllerBuilder::new(ControllerType::Scsi)
1299 .with_instance_id(PETRI_SCSI_VTL0_VIA_VTL2_CONTROLLER)
1300 .add_lun(
1301 Vtl2LunBuilder::disk()
1302 .with_location(PETRI_SCSI_BOOT_LUN)
1303 .with_physical_device(Vtl2StorageBackingDeviceBuilder::new(
1304 ControllerType::Nvme,
1305 PETRI_NVME_BOOT_VTL2_CONTROLLER,
1306 PETRI_NVME_BOOT_NSID,
1307 )),
1308 )
1309 .build(),
1310 ),
1311 BootDeviceType::Nvme => self
1312 .add_vmbus_storage_controller(
1313 &PETRI_NVME_BOOT_VTL0_CONTROLLER,
1314 Vtl::Vtl0,
1315 VmbusStorageType::Nvme,
1316 )
1317 .add_vmbus_drive(
1318 boot_drive,
1319 &PETRI_NVME_BOOT_VTL0_CONTROLLER,
1320 Some(PETRI_NVME_BOOT_NSID),
1321 ),
1322 BootDeviceType::NvmeViaScsi => todo!(),
1323 BootDeviceType::NvmeViaNvme => todo!(),
1324 BootDeviceType::PcieNvme => {
1325 let port_name = self
1326 .pcie_boot_port
1327 .clone()
1328 .unwrap_or_else(|| "s0rc0rp0".into());
1329 self.config.pcie_nvme_drives.push(PcieNvmeDrive {
1330 port_name,
1331 nsid: 1,
1332 drive: boot_drive,
1333 });
1334 self
1335 }
1336 BootDeviceType::PcieVirtioBlk => {
1337 self.config.pcie_virtio_blk_drives.push(PcieVirtioBlkDrive {
1338 port_name: self
1339 .pcie_boot_port
1340 .clone()
1341 .unwrap_or_else(|| "s0rc0rp0".into()),
1342 drive: boot_drive,
1343 });
1344 self
1345 }
1346 }
1347 } else {
1348 self
1349 };
1350 Ok(builder)
1351 }
1352
1353 fn has_agent_disk(&self) -> bool {
1358 if self.uses_pipette_as_init() {
1359 self.agent_image.as_ref().is_some_and(|i| i.has_extras())
1360 } else {
1361 self.agent_image.is_some()
1362 }
1363 }
1364
1365 pub fn properties(&self) -> PetriVmProperties {
1367 PetriVmProperties {
1368 is_openhcl: self.config.firmware.is_openhcl(),
1369 is_isolated: self.config.firmware.isolation().is_some(),
1370 is_pcat: self.config.firmware.is_pcat(),
1371 is_linux_direct: self.config.firmware.is_linux_direct(),
1372 using_vtl0_pipette: self.using_vtl0_pipette(),
1373 external_pipette: self.external_pipette,
1374 using_vpci: self.boot_device_type.requires_vpci_boot(),
1375 os_flavor: self.config.firmware.os_flavor(),
1376 minimal_mode: self.minimal_mode,
1377 uses_pipette_as_init: self.uses_pipette_as_init(),
1378 enable_serial: self.enable_serial,
1379 use_virtio_console: self.use_virtio_console,
1380 has_agent_disk: self.has_agent_disk(),
1381 use_virtio_vsock: self.use_virtio_vsock,
1382 #[cfg(target_os = "linux")]
1383 vhost_vsock_guest_cid: self.vhost_vsock_guest_cid,
1384 no_vmbus: self.no_vmbus,
1385 no_hv: self.no_hv,
1386 }
1387 }
1388
1389 fn uses_pipette_as_init(&self) -> bool {
1394 ((self.config.firmware.is_linux_direct() && !self.config.firmware.is_openhcl())
1395 || self
1396 .config
1397 .firmware
1398 .mshv_boot()
1399 .is_some_and(|boot| matches!(&boot.initrd, crate::mshv_boot::MshvInitrd::Base(_))))
1400 && self.pipette_binary.is_some()
1401 }
1402
1403 pub fn using_vtl0_pipette(&self) -> bool {
1405 self.external_pipette
1406 || self.uses_pipette_as_init()
1407 || self
1408 .agent_image
1409 .as_ref()
1410 .is_some_and(|x| x.contains_pipette())
1411 }
1412
1413 pub async fn run_without_agent(self) -> anyhow::Result<PetriVm<T>> {
1417 self.run_core().await
1418 }
1419
1420 pub async fn run(self) -> anyhow::Result<(PetriVm<T>, PipetteClient)> {
1423 assert!(self.using_vtl0_pipette());
1424
1425 let mut vm = self.add_nested_artifacts_to_agent_disk().run_core().await?;
1426 let client = vm.wait_for_agent().await?;
1427
1428 Ok((vm, client))
1429 }
1430
1431 async fn run_core(mut self) -> anyhow::Result<PetriVm<T>> {
1432 if self.uses_pipette_as_init() && self.resources.prebuilt_initrd.is_none() {
1436 self.resources.prebuilt_initrd = Some(self.prepare_initrd()?);
1437 }
1438 self = self.add_boot_disk()?.add_agent_disks()?;
1440
1441 tracing::debug!(builder = ?self);
1442
1443 let arch = self.config.arch;
1444 let expect_reset = self.expect_reset();
1445 let properties = self.properties();
1446 let guest_shares = self.config.guest_shares.clone();
1447 let name = self.config.name.clone();
1448
1449 let (mut runtime, config) = self
1450 .backend
1451 .run(
1452 self.config,
1453 self.modify_vmm_config,
1454 &self.resources,
1455 &properties,
1456 )
1457 .await?;
1458 let openhcl_diag_handler = runtime.openhcl_diag();
1459 let watchdog_tasks = Self::start_watchdog_tasks(
1460 &self.resources,
1461 &mut runtime,
1462 self.enable_screenshots,
1463 self.watchdog_timeout,
1464 )?;
1465
1466 let mut vm = PetriVm {
1467 runtime: PetriVmRuntimeGuard {
1468 runtime: Some(runtime),
1469 driver: self.resources.driver.clone(),
1470 log_source: self.resources.log_source.clone(),
1471 capture_inspect_on_drop: self.capture_inspect_on_failure,
1472 },
1473 resources: self.resources,
1474 watchdog_tasks,
1475 openhcl_diag_handler,
1476
1477 arch,
1478 guest_quirks: self.guest_quirks,
1479 vmm_quirks: self.vmm_quirks,
1480 expected_boot_event: self.expected_boot_event,
1481
1482 config,
1483 properties,
1484
1485 nested_test: self.nested_test,
1486 guest_shares,
1487 name,
1488 };
1489
1490 if expect_reset {
1491 vm.wait_for_reset_core().await?;
1492 }
1493
1494 vm.wait_for_expected_boot_event().await?;
1495
1496 Ok(vm)
1497 }
1498
1499 fn expect_reset(&self) -> bool {
1500 self.override_expect_reset
1501 || matches!(
1502 (
1503 self.guest_quirks.initial_reboot,
1504 self.expected_boot_event,
1505 &self.config.firmware,
1506 &self.config.tpm,
1507 ),
1508 (
1509 Some(InitialRebootCondition::Always),
1510 Some(FirmwareEvent::BootSuccess | FirmwareEvent::BootAttempt),
1511 _,
1512 _,
1513 ) | (
1514 Some(InitialRebootCondition::WithTpm),
1515 Some(FirmwareEvent::BootSuccess | FirmwareEvent::BootAttempt),
1516 _,
1517 Some(_),
1518 )
1519 )
1520 }
1521
1522 fn start_watchdog_timer(
1523 driver: &DefaultDriver,
1524 watchdog_timeout: Option<Duration>,
1525 ) -> Option<Task<()>> {
1526 watchdog_timeout.map(|timeout| {
1527 let timer_driver = driver.clone();
1529 driver.spawn("timer-watchdog", async move {
1530 PolledTimer::new(&timer_driver).sleep(timeout).await;
1531 tracing::error!(?timeout, "Test timeout reached, aborting.");
1532 panic!("Test timed out");
1533 })
1534 })
1535 }
1536
1537 fn start_watchdog_tasks(
1538 resources: &PetriVmResources,
1539 runtime: &mut T::VmRuntime,
1540 enable_screenshots: bool,
1541 watchdog_timeout: Option<Duration>,
1542 ) -> anyhow::Result<Vec<Task<()>>> {
1543 let mut tasks = Vec::new();
1544
1545 tasks.extend(Self::start_watchdog_timer(
1546 &resources.driver,
1547 watchdog_timeout,
1548 ));
1549
1550 if enable_screenshots {
1551 if let Some(mut framebuffer_access) = runtime.take_framebuffer_access() {
1552 let mut timer = PolledTimer::new(&resources.driver);
1553 let log_source = resources.log_source.clone();
1554
1555 tasks.push(
1556 resources
1557 .driver
1558 .spawn("petri-watchdog-screenshot", async move {
1559 let mut image = Vec::new();
1560 let mut last_image = Vec::new();
1561 loop {
1562 timer.sleep(Duration::from_secs(2)).await;
1563 tracing::trace!("Taking screenshot.");
1564
1565 let VmScreenshotMeta {
1566 color,
1567 width,
1568 height,
1569 } = match framebuffer_access.screenshot(&mut image).await {
1570 Ok(Some(meta)) => meta,
1571 Ok(None) => {
1572 tracing::debug!("VM off, skipping screenshot.");
1573 continue;
1574 }
1575 Err(e) => {
1576 tracing::error!(?e, "Failed to take screenshot");
1577 continue;
1578 }
1579 };
1580
1581 if image == last_image {
1582 tracing::debug!(
1583 "No change in framebuffer, skipping screenshot."
1584 );
1585 continue;
1586 }
1587
1588 let r = log_source.create_attachment("screenshot.png").and_then(
1589 |mut f| {
1590 image::write_buffer_with_format(
1591 &mut f,
1592 &image,
1593 width.into(),
1594 height.into(),
1595 color,
1596 image::ImageFormat::Png,
1597 )
1598 .map_err(Into::into)
1599 },
1600 );
1601
1602 if let Err(e) = r {
1603 tracing::error!(?e, "Failed to save screenshot");
1604 } else {
1605 tracing::info!("Screenshot saved.");
1606 }
1607
1608 std::mem::swap(&mut image, &mut last_image);
1609 }
1610 }),
1611 );
1612 }
1613 }
1614
1615 Ok(tasks)
1616 }
1617
1618 pub fn with_expect_boot_failure(mut self) -> Self {
1621 self.expected_boot_event = Some(FirmwareEvent::BootFailed);
1622 self
1623 }
1624
1625 pub fn with_expect_no_boot_event(mut self) -> Self {
1628 self.expected_boot_event = None;
1629 self
1630 }
1631
1632 pub fn with_expect_reset(mut self) -> Self {
1636 self.override_expect_reset = true;
1637 self
1638 }
1639
1640 pub fn with_secure_boot(mut self) -> Self {
1642 self.config
1643 .firmware
1644 .uefi_config_mut()
1645 .expect("Secure boot is only supported for UEFI firmware.")
1646 .secure_boot_enabled = true;
1647
1648 match self.os_flavor() {
1649 OsFlavor::Windows => self.with_windows_secure_boot_template(),
1650 OsFlavor::Linux => self.with_uefi_ca_secure_boot_template(),
1651 _ => panic!(
1652 "Secure boot unsupported for OS flavor {:?}",
1653 self.os_flavor()
1654 ),
1655 }
1656 }
1657
1658 pub fn with_windows_secure_boot_template(mut self) -> Self {
1660 self.config
1661 .firmware
1662 .uefi_config_mut()
1663 .expect("Secure boot is only supported for UEFI firmware.")
1664 .secure_boot_template = Some(SecureBootTemplate::MicrosoftWindows);
1665 self
1666 }
1667
1668 pub fn with_uefi_ca_secure_boot_template(mut self) -> Self {
1670 self.config
1671 .firmware
1672 .uefi_config_mut()
1673 .expect("Secure boot is only supported for UEFI firmware.")
1674 .secure_boot_template = Some(SecureBootTemplate::MicrosoftUefiCertificateAuthority);
1675 self
1676 }
1677
1678 pub fn with_custom_uefi_json(mut self, json: impl Into<Vec<u8>>) -> Self {
1680 self.config
1681 .firmware
1682 .uefi_config_mut()
1683 .expect("Custom UEFI variables are only supported for UEFI firmware.")
1684 .custom_uefi_json = Some(json.into());
1685 self
1686 }
1687
1688 pub fn with_processor_topology(mut self, topology: ProcessorTopology) -> Self {
1690 self.config.proc_topology = topology;
1691 self
1692 }
1693
1694 pub fn with_memory(mut self, memory: MemoryConfig) -> Self {
1696 self.config.memory = memory;
1697 self
1698 }
1699
1700 pub fn with_vtl2_base_address_type(mut self, address_type: Vtl2BaseAddressType) -> Self {
1705 self.config
1706 .firmware
1707 .openhcl_config_mut()
1708 .expect("OpenHCL firmware is required to set custom VTL2 address type.")
1709 .vtl2_base_address_type = Some(address_type);
1710 self
1711 }
1712
1713 pub fn with_custom_openhcl(mut self, artifact: ResolvedArtifact<impl IsOpenhclIgvm>) -> Self {
1715 match &mut self.config.firmware {
1716 Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
1717 | Firmware::OpenhclPcat { igvm_firmware, .. }
1718 | Firmware::OpenhclUefi { igvm_firmware, .. } => {
1719 *igvm_firmware = IgvmFirmwareSource::File(artifact.erase());
1720 }
1721 Firmware::LinuxDirect { .. }
1722 | Firmware::IgvmLinuxDirect { .. }
1723 | Firmware::Uefi { .. }
1724 | Firmware::Pcat { .. } => {
1725 panic!("Custom OpenHCL is only supported for OpenHCL firmware.")
1726 }
1727 }
1728 self
1729 }
1730
1731 pub fn with_openhcl_from_vmgs(mut self) -> Self {
1733 match &mut self.config.firmware {
1734 Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
1735 | Firmware::OpenhclPcat { igvm_firmware, .. }
1736 | Firmware::OpenhclUefi { igvm_firmware, .. } => {
1737 *igvm_firmware = IgvmFirmwareSource::VmgsOrInBox;
1738 }
1739 Firmware::LinuxDirect { .. }
1740 | Firmware::IgvmLinuxDirect { .. }
1741 | Firmware::Uefi { .. }
1742 | Firmware::Pcat { .. } => {
1743 panic!("Loading OpenHCL from VMGS is only supported for OpenHCL firmware.")
1744 }
1745 }
1746 self
1747 }
1748
1749 pub fn with_openhcl_command_line(mut self, additional_command_line: &str) -> Self {
1751 append_cmdline(
1752 &mut self
1753 .config
1754 .firmware
1755 .openhcl_config_mut()
1756 .expect("OpenHCL command line is only supported for OpenHCL firmware.")
1757 .custom_command_line,
1758 additional_command_line,
1759 );
1760 self
1761 }
1762
1763 pub fn with_mana_keepalive(mut self, enable: bool) -> Self {
1765 self.config
1766 .firmware
1767 .openhcl_config_mut()
1768 .expect("MANA keepalive is only supported for OpenHCL firmware.")
1769 .enable_mana_keepalive = enable;
1770 self
1771 }
1772
1773 pub fn with_confidential_filtering(self) -> Self {
1775 if !self.config.firmware.is_openhcl() {
1776 panic!("Confidential filtering is only supported for OpenHCL");
1777 }
1778 self.with_openhcl_command_line(&format!(
1779 "{}=1 {}=0",
1780 underhill_confidentiality::OPENHCL_CONFIDENTIAL_ENV_VAR_NAME,
1781 underhill_confidentiality::OPENHCL_CONFIDENTIAL_DEBUG_ENV_VAR_NAME
1782 ))
1783 }
1784
1785 pub fn with_openhcl_log_levels(mut self, levels: OpenvmmLogConfig) -> Self {
1787 self.config
1788 .firmware
1789 .openhcl_config_mut()
1790 .expect("OpenHCL firmware is required to set custom OpenHCL log levels.")
1791 .log_levels = levels;
1792 self
1793 }
1794
1795 pub fn with_host_log_levels(mut self, levels: OpenvmmLogConfig) -> Self {
1799 if let OpenvmmLogConfig::Custom(ref custom_levels) = levels {
1800 for key in custom_levels.keys() {
1801 if !["OPENVMM_LOG", "OPENVMM_SHOW_SPANS"].contains(&key.as_str()) {
1802 panic!("Unsupported OpenVMM log level key: {}", key);
1803 }
1804 }
1805 }
1806
1807 self.config.host_log_levels = Some(levels.clone());
1808 self
1809 }
1810
1811 pub fn with_agent_file(mut self, name: &str, file_path: impl AsRef<Path>) -> Self {
1813 self.agent_image
1814 .as_mut()
1815 .expect("no guest pipette")
1816 .add_file(name, file_path);
1817 self
1818 }
1819
1820 pub fn with_openhcl_agent_file(mut self, name: &str, file_path: impl AsRef<Path>) -> Self {
1822 self.openhcl_agent_image
1823 .as_mut()
1824 .expect("no openhcl pipette")
1825 .add_file(name, file_path);
1826 self
1827 }
1828
1829 pub fn with_uefi_frontpage(mut self, enable: bool) -> Self {
1831 self.config
1832 .firmware
1833 .uefi_config_mut()
1834 .expect("UEFI frontpage is only supported for UEFI firmware.")
1835 .disable_frontpage = !enable;
1836 self
1837 }
1838
1839 pub fn with_efi_diagnostics_log_level(mut self, level: EfiDiagnosticsLogLevel) -> Self {
1845 self.config
1846 .firmware
1847 .uefi_config_mut()
1848 .expect("EFI diagnostics log level is only supported for UEFI firmware.")
1849 .efi_diagnostics_log_level = level;
1850 self
1851 }
1852
1853 pub fn with_efi_diagnostics_rate_limit(mut self, limit: u32) -> Self {
1859 self.config
1860 .firmware
1861 .uefi_config_mut()
1862 .expect("EFI diagnostics rate limit is only supported for UEFI firmware.")
1863 .efi_diagnostics_rate_limit = Some(limit);
1864 self
1865 }
1866
1867 pub fn with_default_boot_always_attempt(mut self, enable: bool) -> Self {
1869 self.config
1870 .firmware
1871 .uefi_config_mut()
1872 .expect("Default boot always attempt is only supported for UEFI firmware.")
1873 .default_boot_always_attempt = enable;
1874 self
1875 }
1876
1877 pub fn with_uefi_force_dma_bounce(mut self, enable: bool) -> Self {
1879 self.config
1880 .firmware
1881 .uefi_config_mut()
1882 .expect("force DMA bounce is only supported for UEFI firmware.")
1883 .force_dma_bounce = enable;
1884 self
1885 }
1886
1887 pub fn with_vmbus_redirect(mut self, enable: bool) -> Self {
1889 self.config
1890 .firmware
1891 .openhcl_config_mut()
1892 .expect("VMBus redirection is only supported for OpenHCL firmware.")
1893 .vmbus_redirect = enable;
1894 self
1895 }
1896
1897 pub fn with_hibernation_enabled(mut self, enable: bool) -> Self {
1903 self.config.hibernation_enabled = enable;
1904 self
1905 }
1906
1907 pub fn with_ipmi(mut self, enable: bool) -> Self {
1909 self.config.ipmi_enabled = enable;
1910 self
1911 }
1912
1913 pub fn with_guest_state_lifetime(
1915 mut self,
1916 guest_state_lifetime: PetriGuestStateLifetime,
1917 ) -> Self {
1918 let disk = match self.config.vmgs {
1919 PetriVmgsResource::Disk(disk)
1920 | PetriVmgsResource::ReprovisionOnFailure(disk)
1921 | PetriVmgsResource::ReprovisionSingle(disk) => disk,
1922 PetriVmgsResource::Ephemeral => PetriVmgsDisk::default(),
1923 };
1924 self.config.vmgs = match guest_state_lifetime {
1925 PetriGuestStateLifetime::Disk => PetriVmgsResource::Disk(disk),
1926 PetriGuestStateLifetime::ReprovisionOnFailure => {
1927 PetriVmgsResource::ReprovisionOnFailure(disk)
1928 }
1929 PetriGuestStateLifetime::ReprovisionSingle => {
1930 PetriVmgsResource::ReprovisionSingle(disk)
1931 }
1932 PetriGuestStateLifetime::Ephemeral => {
1933 if !matches!(disk.disk, Disk::Memory(_)) {
1934 panic!("attempted to use ephemeral guest state after specifying backing vmgs")
1935 }
1936 PetriVmgsResource::Ephemeral
1937 }
1938 };
1939 self
1940 }
1941
1942 pub fn with_guest_state_encryption(mut self, policy: GuestStateEncryptionPolicy) -> Self {
1944 match &mut self.config.vmgs {
1945 PetriVmgsResource::Disk(vmgs)
1946 | PetriVmgsResource::ReprovisionOnFailure(vmgs)
1947 | PetriVmgsResource::ReprovisionSingle(vmgs) => {
1948 vmgs.encryption_policy = policy;
1949 }
1950 PetriVmgsResource::Ephemeral => {
1951 panic!("attempted to encrypt ephemeral guest state")
1952 }
1953 }
1954 self
1955 }
1956
1957 pub fn with_initial_vmgs(self, disk: ResolvedArtifact<impl IsTestVmgs>) -> Self {
1959 self.with_backing_vmgs(Disk::Differencing(DiskPath::Local(disk.into())))
1960 }
1961
1962 pub fn with_persistent_vmgs(self, disk: impl AsRef<Path>) -> Self {
1964 self.with_backing_vmgs(Disk::Persistent(disk.as_ref().to_path_buf()))
1965 }
1966
1967 fn with_backing_vmgs(mut self, disk: Disk) -> Self {
1968 match &mut self.config.vmgs {
1969 PetriVmgsResource::Disk(vmgs)
1970 | PetriVmgsResource::ReprovisionOnFailure(vmgs)
1971 | PetriVmgsResource::ReprovisionSingle(vmgs) => {
1972 if !matches!(vmgs.disk, Disk::Memory(_)) {
1973 panic!("already specified a backing vmgs file");
1974 }
1975 vmgs.disk = disk;
1976 }
1977 PetriVmgsResource::Ephemeral => {
1978 panic!("attempted to specify a backing vmgs with ephemeral guest state")
1979 }
1980 }
1981 self
1982 }
1983
1984 pub fn with_boot_device_type(mut self, boot: BootDeviceType) -> Self {
1988 self.boot_device_type = boot;
1989 self
1990 }
1991
1992 pub fn with_pcie_boot_port(mut self, port_name: &str) -> Self {
1998 self.pcie_boot_port = Some(port_name.to_string());
1999 self
2000 }
2001
2002 pub fn with_tpm(mut self, enable: bool) -> Self {
2004 if enable {
2005 self.config.tpm.get_or_insert_default();
2006 } else {
2007 self.config.tpm = None;
2008 }
2009 self
2010 }
2011
2012 pub fn with_tpm_state_persistence(mut self, tpm_state_persistence: bool) -> Self {
2014 self.config
2015 .tpm
2016 .as_mut()
2017 .expect("TPM persistence requires a TPM")
2018 .no_persistent_secrets = !tpm_state_persistence;
2019 self
2020 }
2021
2022 pub fn with_hardware_sealing_policy(mut self, policy: PetriHardwareSealingPolicy) -> Self {
2024 self.config
2025 .tpm
2026 .as_mut()
2027 .expect("hardware sealing policy requires a TPM")
2028 .hardware_sealing_policy = policy;
2029 self
2030 }
2031
2032 pub fn with_tpm_version(mut self, version: PetriTpmVersion) -> Self {
2034 self.config
2035 .tpm
2036 .as_mut()
2037 .expect("TPM version requires a TPM")
2038 .version = version;
2039 self
2040 }
2041
2042 pub fn with_custom_vtl2_settings(
2046 mut self,
2047 f: impl FnOnce(&mut Vtl2Settings) + 'static + Send + Sync,
2048 ) -> Self {
2049 f(self
2050 .config
2051 .firmware
2052 .vtl2_settings()
2053 .expect("Custom VTL 2 settings are only supported with OpenHCL"));
2054 self
2055 }
2056
2057 pub fn add_vtl2_storage_controller(self, controller: StorageController) -> Self {
2059 self.with_custom_vtl2_settings(move |v| {
2060 v.dynamic
2061 .as_mut()
2062 .unwrap()
2063 .storage_controllers
2064 .push(controller)
2065 })
2066 }
2067
2068 pub fn add_vmbus_storage_controller(
2070 mut self,
2071 id: &Guid,
2072 target_vtl: Vtl,
2073 controller_type: VmbusStorageType,
2074 ) -> Self {
2075 if self
2076 .config
2077 .vmbus_storage_controllers
2078 .insert(
2079 *id,
2080 VmbusStorageController::new(target_vtl, controller_type),
2081 )
2082 .is_some()
2083 {
2084 panic!("storage controller {id} already existed");
2085 }
2086 self
2087 }
2088
2089 pub fn add_vmbus_drive(
2091 mut self,
2092 drive: Drive,
2093 controller_id: &Guid,
2094 controller_location: Option<u32>,
2095 ) -> Self {
2096 let controller = self
2097 .config
2098 .vmbus_storage_controllers
2099 .get_mut(controller_id)
2100 .unwrap_or_else(|| panic!("storage controller {controller_id} does not exist"));
2101
2102 _ = controller.set_drive(controller_location, drive, false);
2103
2104 self
2105 }
2106
2107 pub fn add_ide_drive(
2109 mut self,
2110 drive: Drive,
2111 controller_number: u32,
2112 controller_location: u8,
2113 ) -> Self {
2114 self.config
2115 .firmware
2116 .ide_controllers_mut()
2117 .expect("Host IDE requires PCAT with no HCL")[controller_number as usize]
2118 [controller_location as usize] = Some(drive);
2119
2120 self
2121 }
2122
2123 pub fn add_physical_nvme_device(mut self, vsid: Guid, device: PhysicalNvmeDevice) -> Self {
2125 if self
2126 .config
2127 .physical_nvme_devices
2128 .insert(vsid, device)
2129 .is_some()
2130 {
2131 panic!("physical NVMe device {vsid} already existed");
2132 }
2133 self
2134 }
2135
2136 pub fn os_flavor(&self) -> OsFlavor {
2138 self.config.firmware.os_flavor()
2139 }
2140
2141 pub fn is_openhcl(&self) -> bool {
2143 self.config.firmware.is_openhcl()
2144 }
2145
2146 pub fn isolation(&self) -> Option<IsolationType> {
2148 self.config.firmware.isolation()
2149 }
2150
2151 pub fn arch(&self) -> MachineArch {
2153 self.config.arch
2154 }
2155
2156 pub fn log_source(&self) -> &PetriLogSource {
2158 &self.resources.log_source
2159 }
2160
2161 pub fn default_servicing_flags(&self) -> OpenHclServicingFlags {
2163 T::default_servicing_flags()
2164 }
2165
2166 pub fn modify_backend(
2169 mut self,
2170 f: impl FnOnce(T::VmmConfig) -> T::VmmConfig + 'static + Send,
2171 ) -> Self {
2172 let previous = self.modify_vmm_config.take();
2173 self.modify_vmm_config = Some(ModifyFn(Box::new(move |config| {
2174 let config = match previous {
2175 Some(previous) => previous.0(config),
2176 None => config,
2177 };
2178 f(config)
2179 })));
2180 self
2181 }
2182
2183 fn add_nested_artifacts_to_agent_disk(mut self) -> Self {
2184 let Some(nested_test) = self.nested_test.as_ref() else {
2185 return self;
2186 };
2187
2188 if T::supports_file_sharing(&self.config.firmware) {
2191 self.config.guest_shares.insert(
2192 NESTED_CONTENT_TAG.into(),
2193 GuestShare {
2194 host_path: PathBuf::from(
2195 std::env::var(VMM_TESTS_CONTENT_DIR).expect("test content dir not set"),
2196 ),
2197 guest_path: self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into()]),
2198 },
2199 );
2200 self.config.guest_shares.insert(
2201 NESTED_IMAGES_TAG.into(),
2202 GuestShare {
2203 host_path: PathBuf::from(
2204 std::env::var(VMM_TEST_IMAGES).expect("test images dir not set"),
2205 ),
2206 guest_path: self.agent_disk_path(&[NESTED_IMAGES_DIR.into()]),
2207 },
2208 );
2209
2210 return self;
2211 }
2212
2213 let mut extras = Vec::new();
2214
2215 let path_builder = FatFsPathBuilder(self.os_flavor());
2216
2217 extras.push((NESTED_TEST_CONTENT_DIR.to_string(), ImageEntry::Dir));
2218 extras.push((
2219 path_builder
2220 .build_guest_path(&[NESTED_TEST_CONTENT_DIR.into(), NESTED_RESULTS_DIR.into()]),
2221 ImageEntry::Dir,
2222 ));
2223 extras.push((
2224 path_builder.build_guest_path(&[NESTED_IMAGES_DIR.into()]),
2225 ImageEntry::Dir,
2226 ));
2227 extras.push((
2228 path_builder.build_guest_path(&[
2229 NESTED_TEST_CONTENT_DIR.into(),
2230 path_builder.binary_with_extension(NESTED_TEST_BINARY),
2231 ]),
2232 ImageEntry::File(nested_test.test_binary.to_path_buf()),
2233 ));
2234
2235 for (handle, src) in &nested_test.artifacts {
2236 let relative_path = path_builder.convert_guest_path(&handle.relative_path());
2237 let dest = if handle.is_image() {
2238 path_builder.build_guest_path(&[NESTED_IMAGES_DIR.into(), relative_path])
2239 } else {
2240 path_builder.build_guest_path(&[NESTED_TEST_CONTENT_DIR.into(), relative_path])
2241 };
2242
2243 for parent in path_builder.parents(&dest) {
2244 if !extras.iter().any(|(p, _)| p == parent) {
2245 extras.push((parent.to_string(), ImageEntry::Dir))
2246 }
2247 }
2248
2249 extras.push((dest, ImageEntry::File(src.clone())));
2250 }
2251
2252 let image = self.agent_image.as_mut().expect("no guest pipette");
2253 image.add_extras(extras);
2254 image.allocate_free_space(150 * 1024 * 1024);
2256
2257 self
2258 }
2259
2260 pub fn with_nested_virt(mut self) -> Self {
2262 self.config.nested_virt_enabled = true;
2263 self
2264 }
2265
2266 pub fn with_custom_linux_kernel(
2268 mut self,
2269 custom_kernel: ResolvedArtifact<impl IsLoadable>,
2270 ) -> Self {
2271 let Firmware::LinuxDirect { kernel, .. } = &mut self.config.firmware else {
2272 panic!("VM is not linux direct");
2273 };
2274 *kernel = custom_kernel.erase();
2275 self
2276 }
2277}
2278
2279impl<T: PetriVmmBackend> PetriVm<T> {
2280 pub async fn teardown(mut self) -> anyhow::Result<()> {
2282 tracing::info!("Tearing down VM...");
2283 self.runtime.take_for_teardown().teardown().await?;
2284 Ok(())
2285 }
2286
2287 pub async fn wait_for_halt(&mut self) -> anyhow::Result<PetriHaltReasonDetail> {
2289 tracing::info!("Waiting for VM to halt...");
2290 let halt_reason = self.runtime.wait_for_halt(false).await?;
2291 tracing::info!("VM halted: {halt_reason:?}. Cancelling watchdogs...");
2292 futures::future::join_all(self.watchdog_tasks.drain(..).map(|t| t.cancel())).await;
2293 Ok(halt_reason)
2294 }
2295
2296 pub async fn wait_for_clean_shutdown(&mut self) -> anyhow::Result<()> {
2298 let halt_reason = self.wait_for_halt().await?;
2299 if halt_reason.reason != PetriHaltReason::PowerOff {
2300 anyhow::bail!("Expected PowerOff, got {halt_reason:?}");
2301 }
2302 tracing::info!("VM was cleanly powered off and torn down.");
2303 Ok(())
2304 }
2305
2306 pub async fn wait_for_teardown(mut self) -> anyhow::Result<PetriHaltReasonDetail> {
2309 let halt_reason = self.wait_for_halt().await?;
2310 self.teardown().await?;
2311 Ok(halt_reason)
2312 }
2313
2314 pub async fn wait_for_clean_teardown(mut self) -> anyhow::Result<()> {
2316 self.wait_for_clean_shutdown().await?;
2317 self.teardown().await
2318 }
2319
2320 pub async fn wait_for_reset_no_agent(&mut self) -> anyhow::Result<()> {
2322 self.wait_for_reset_core().await?;
2323 self.wait_for_expected_boot_event().await?;
2324 Ok(())
2325 }
2326
2327 pub async fn wait_for_reset(&mut self) -> anyhow::Result<PipetteClient> {
2329 self.wait_for_reset_no_agent().await?;
2330 self.wait_for_agent().await
2331 }
2332
2333 async fn wait_for_reset_core(&mut self) -> anyhow::Result<()> {
2334 tracing::info!("Waiting for VM to reset...");
2335 let halt_reason = self.runtime.wait_for_halt(true).await?;
2336 if halt_reason.reason != PetriHaltReason::Reset {
2337 anyhow::bail!("Expected reset, got {halt_reason:?}");
2338 }
2339 tracing::info!("VM reset.");
2340 Ok(())
2341 }
2342
2343 pub async fn inspect_openhcl(
2354 &self,
2355 path: impl Into<String>,
2356 depth: Option<usize>,
2357 timeout: Option<Duration>,
2358 ) -> anyhow::Result<inspect::Node> {
2359 self.openhcl_diag()?
2360 .inspect(path.into().as_str(), depth, timeout)
2361 .await
2362 }
2363
2364 pub async fn inspect_update_openhcl(
2374 &self,
2375 path: impl Into<String>,
2376 value: impl Into<String>,
2377 ) -> anyhow::Result<inspect::Value> {
2378 self.openhcl_diag()?
2379 .inspect_update(path.into(), value.into())
2380 .await
2381 }
2382
2383 pub async fn test_inspect_openhcl(&mut self) -> anyhow::Result<()> {
2385 self.inspect_openhcl("", None, None).await.map(|_| ())
2386 }
2387
2388 pub async fn dump_openhcl_saved_state(&self) -> anyhow::Result<Vec<u8>> {
2392 self.openhcl_diag()?.dump_saved_state().await
2393 }
2394
2395 pub async fn inspect_vmm(&self, path: &str) -> anyhow::Result<inspect::Node> {
2406 use anyhow::Context;
2407
2408 let inspector = self
2409 .runtime
2410 .inspector()
2411 .context("this VMM backend does not support inspect")?;
2412 inspector.inspect(path).await
2413 }
2414
2415 pub async fn wait_for_vtl2_ready(&mut self) -> anyhow::Result<()> {
2421 self.openhcl_diag()?.wait_for_vtl2().await
2422 }
2423
2424 pub async fn kmsg(&self) -> anyhow::Result<diag_client::kmsg_stream::KmsgStream> {
2426 self.openhcl_diag()?.kmsg().await
2427 }
2428
2429 pub async fn openhcl_core_dump(&self, name: &str, path: &Path) -> anyhow::Result<()> {
2432 self.openhcl_diag()?.core_dump(name, path).await
2433 }
2434
2435 pub async fn openhcl_crash(&self, name: &str) -> anyhow::Result<()> {
2437 self.openhcl_diag()?.crash(name).await
2438 }
2439
2440 async fn wait_for_agent(&mut self) -> anyhow::Result<PipetteClient> {
2443 self.runtime.wait_for_enlightened_shutdown_ready().await?;
2453 let client = self.runtime.wait_for_agent(false).await?;
2454 self.mount_guest_shares(&client).await?;
2455 Ok(client)
2456 }
2457
2458 async fn mount_guest_shares(&self, client: &PipetteClient) -> anyhow::Result<()> {
2459 if !self.guest_shares.is_empty() {
2460 anyhow::ensure!(
2461 self.properties.os_flavor == OsFlavor::Linux,
2462 "directory sharing requires a Linux guest"
2463 );
2464 let mut shares = self.guest_shares.iter().collect::<Vec<_>>();
2465 shares.sort_by_key(|(tag, share)| {
2467 (
2468 share
2469 .guest_path
2470 .split('/')
2471 .filter(|part| !part.is_empty() && *part != ".")
2472 .count(),
2473 *tag,
2474 )
2475 });
2476 for (tag, share) in shares {
2477 let shell = client.unix_shell();
2478 shell
2479 .cmd("mkdir")
2480 .args(["-p", &share.guest_path])
2481 .run()
2482 .await?;
2483 shell
2484 .cmd("mount")
2485 .args([
2486 "-t",
2487 "9p",
2488 "-o",
2489 "trans=virtio,version=9p2000.L",
2490 tag,
2491 &share.guest_path,
2492 ])
2493 .run()
2494 .await
2495 .with_context(|| format!("mounting guest share {tag}"))?;
2496 }
2497 }
2498 Ok(())
2499 }
2500
2501 pub async fn wait_for_vtl2_agent(&mut self) -> anyhow::Result<PipetteClient> {
2505 self.launch_vtl2_pipette().await?;
2507 self.runtime.wait_for_agent(true).await
2508 }
2509
2510 async fn wait_for_expected_boot_event(&mut self) -> anyhow::Result<()> {
2517 if let Some(expected_event) = self.expected_boot_event {
2518 let event = self.wait_for_boot_event().await?;
2519
2520 anyhow::ensure!(
2521 event == expected_event,
2522 "Did not receive expected boot event"
2523 );
2524 } else {
2525 tracing::warn!("Boot event not emitted for configured firmware or manually ignored.");
2526 }
2527
2528 Ok(())
2529 }
2530
2531 async fn wait_for_boot_event(&mut self) -> anyhow::Result<FirmwareEvent> {
2534 tracing::info!("Waiting for boot event...");
2535 let boot_event = loop {
2536 if let Some(event) = self
2537 .runtime
2538 .wait_for_boot_event(self.vmm_quirks.flaky_boot)
2539 .await?
2540 {
2541 break event;
2542 }
2543
2544 tracing::error!("Did not get boot event in required time, resetting...");
2545 if let Some(inspector) = self.runtime.inspector() {
2546 collect_inspect(
2547 "vmm",
2548 Box::pin(async move { inspector.inspect("").await }),
2549 &self.resources.log_source,
2550 "timeout",
2551 )
2552 .await;
2553 }
2554
2555 self.runtime.reset().await?;
2556 };
2557 tracing::info!("Got boot event: {boot_event:?}");
2558 Ok(boot_event)
2559 }
2560
2561 pub async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()> {
2564 tracing::info!("Waiting for enlightened shutdown to be ready");
2565 self.runtime.wait_for_enlightened_shutdown_ready().await?;
2566
2567 let mut wait_time = Duration::from_secs(10);
2573
2574 if let Some(duration) = self.guest_quirks.hyperv_shutdown_ic_sleep {
2576 wait_time += duration;
2577 }
2578
2579 tracing::info!(
2580 "Shutdown IC reported ready, waiting for an extra {}s",
2581 wait_time.as_secs()
2582 );
2583 PolledTimer::new(&self.resources.driver)
2584 .sleep(wait_time)
2585 .await;
2586
2587 tracing::info!("Sending enlightened shutdown command");
2588 self.runtime.send_enlightened_shutdown(kind).await
2589 }
2590
2591 pub async fn restart_openhcl(
2594 &mut self,
2595 new_openhcl: ResolvedArtifact<impl IsOpenhclIgvm>,
2596 flags: OpenHclServicingFlags,
2597 ) -> anyhow::Result<()> {
2598 self.runtime
2599 .restart_openhcl(&new_openhcl.erase(), flags)
2600 .await
2601 }
2602
2603 pub async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()> {
2606 self.runtime.update_command_line(command_line).await
2607 }
2608
2609 pub async fn add_pcie_device(
2611 &mut self,
2612 port_name: String,
2613 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
2614 ) -> anyhow::Result<()> {
2615 self.runtime.add_pcie_device(port_name, resource).await
2616 }
2617
2618 pub async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
2620 self.runtime.remove_pcie_device(port_name).await
2621 }
2622
2623 pub async fn save_openhcl(
2626 &mut self,
2627 new_openhcl: ResolvedArtifact<impl IsOpenhclIgvm>,
2628 flags: OpenHclServicingFlags,
2629 ) -> anyhow::Result<()> {
2630 self.runtime.save_openhcl(&new_openhcl.erase(), flags).await
2631 }
2632
2633 pub async fn restore_openhcl(&mut self) -> anyhow::Result<()> {
2636 self.runtime.restore_openhcl().await
2637 }
2638
2639 pub fn arch(&self) -> MachineArch {
2641 self.arch
2642 }
2643
2644 pub fn backend(&mut self) -> &mut T::VmRuntime {
2646 &mut self.runtime
2647 }
2648
2649 async fn launch_vtl2_pipette(&self) -> anyhow::Result<()> {
2650 tracing::debug!("Launching VTL 2 pipette...");
2651
2652 let res = self
2654 .openhcl_diag()?
2655 .run_vtl2_command("sh", &["-c", "mkdir /cidata && mount LABEL=cidata /cidata"])
2656 .await?;
2657
2658 if !res.exit_status.success() {
2659 anyhow::bail!("Failed to mount VTL 2 pipette drive: {:?}", res);
2660 }
2661
2662 let res = self
2663 .openhcl_diag()?
2664 .run_detached_vtl2_command("sh", &["-c", "/cidata/pipette 2>&1 | logger &"])
2665 .await?;
2666
2667 if !res.success() {
2668 anyhow::bail!("Failed to spawn VTL 2 pipette: {:?}", res);
2669 }
2670
2671 Ok(())
2672 }
2673
2674 fn openhcl_diag(&self) -> anyhow::Result<&OpenHclDiagHandler> {
2675 if let Some(ohd) = self.openhcl_diag_handler.as_ref() {
2676 Ok(ohd)
2677 } else {
2678 anyhow::bail!("VM is not configured with OpenHCL")
2679 }
2680 }
2681
2682 pub async fn get_guest_state_file(&self) -> anyhow::Result<Option<PathBuf>> {
2684 self.runtime.get_guest_state_file().await
2685 }
2686
2687 pub async fn modify_vtl2_settings(
2689 &mut self,
2690 f: impl FnOnce(&mut Vtl2Settings),
2691 ) -> anyhow::Result<()> {
2692 if self.openhcl_diag_handler.is_none() {
2693 panic!("Custom VTL 2 settings are only supported with OpenHCL");
2694 }
2695 f(self
2696 .config
2697 .vtl2_settings
2698 .get_or_insert_with(default_vtl2_settings));
2699 self.runtime
2700 .set_vtl2_settings(self.config.vtl2_settings.as_ref().unwrap())
2701 .await
2702 }
2703
2704 pub fn get_vmbus_storage_controllers(&self) -> &HashMap<Guid, VmbusStorageController> {
2706 &self.config.vmbus_storage_controllers
2707 }
2708
2709 pub async fn set_vmbus_drive(
2711 &mut self,
2712 drive: Drive,
2713 controller_id: &Guid,
2714 controller_location: Option<u32>,
2715 ) -> anyhow::Result<()> {
2716 let controller = self
2717 .config
2718 .vmbus_storage_controllers
2719 .get_mut(controller_id)
2720 .unwrap_or_else(|| panic!("storage controller {controller_id} does not exist"));
2721
2722 let controller_location = controller.set_drive(controller_location, drive, true);
2723 let disk = controller.drives.get(&controller_location).unwrap();
2724
2725 self.runtime
2726 .set_vmbus_drive(disk, controller_id, controller_location)
2727 .await?;
2728
2729 Ok(())
2730 }
2731
2732 pub async fn run_nested_test(
2734 &self,
2735 client: &PipetteClient,
2736 env: BTreeMap<String, String>,
2737 ) -> anyhow::Result<()> {
2738 self.run_nested_test_with_suffix(client, env, "").await
2739 }
2740
2741 pub async fn run_nested_test_with_suffix(
2745 &self,
2746 client: &PipetteClient,
2747 env: BTreeMap<String, String>,
2748 suffix: &str,
2749 ) -> anyhow::Result<()> {
2750 let nested_test = self.nested_test.as_ref().context("no nested test")?;
2751 let results_dir = if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2752 NESTED_RESULTS_DIR.to_owned()
2753 } else {
2754 format!("{NESTED_RESULTS_DIR}{suffix}")
2755 };
2756
2757 let test_binary_path =
2758 if let Some(test_content_dir) = self.guest_shares.get(NESTED_CONTENT_TAG) {
2759 let test_content_dir = absolute(&test_content_dir.host_path)?;
2760 let local_test_binary_path = absolute(&nested_test.test_binary)?;
2761
2762 self.convert_guest_path(
2763 local_test_binary_path
2764 .strip_prefix(&test_content_dir)
2765 .context("test binary should be under content dir")?,
2766 )
2767 } else {
2768 self.binary_with_extension(NESTED_TEST_BINARY)
2769 };
2770
2771 let mut cmd = client
2772 .command(self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), test_binary_path]));
2773 cmd.arg("--ignored")
2774 .arg("--exact")
2775 .arg(&nested_test.test_name)
2776 .env(
2777 VMM_TESTS_CONTENT_DIR,
2778 self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into()]),
2779 )
2780 .env(
2781 VMM_TEST_IMAGES,
2782 self.agent_disk_path(&[NESTED_IMAGES_DIR.into()]),
2783 )
2784 .env(
2785 TEST_OUTPUT_PATH,
2786 self.agent_disk_path(&[NESTED_TEST_CONTENT_DIR.into(), results_dir.clone()]),
2787 )
2788 .stdout(crate::pipette::process::Stdio::piped())
2789 .stderr(crate::pipette::process::Stdio::piped());
2790
2791 for (k, v) in env {
2792 cmd.env(k, v);
2793 }
2794
2795 if self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2796 cmd.env(PETRI_NESTED_TEST_PARENT, format!("{}{suffix}", self.name));
2799 }
2800
2801 if let Ok(v) = std::env::var(PETRI_REMOTE_ARTIFACTS) {
2802 cmd.env(PETRI_REMOTE_ARTIFACTS, v);
2803 }
2804
2805 let mut child = cmd.spawn().await?;
2806
2807 self.resources
2809 .driver
2810 .spawn(
2811 "log_nested",
2812 crate::log_task(
2813 self.resources
2814 .log_source
2815 .log_file(&format!("stdout{suffix}"))?,
2816 child.stdout.take().unwrap(),
2817 "nested stdout",
2818 ),
2819 )
2820 .detach();
2821
2822 let output = child.wait_with_output().await?;
2823
2824 if !self.guest_shares.contains_key(NESTED_CONTENT_TAG) {
2826 let test_results_dir = self.agent_disk_path(&[
2827 NESTED_TEST_CONTENT_DIR.into(),
2828 results_dir,
2829 nested_test.test_name.replace("::", "__"),
2830 ]);
2831
2832 for file in client.list_dir(&test_results_dir).await? {
2833 let data = client
2834 .read_file(self.build_guest_path(&[test_results_dir.clone(), file.clone()]))
2835 .await?;
2836 let mut output = self
2837 .resources
2838 .log_source
2839 .create_attachment_no_prefix(&format!("{suffix}{file}"))?;
2840 output.write_all(&data)?;
2841 }
2842 }
2843
2844 if !output.status.success() {
2845 anyhow::bail!(
2846 "nested test exited with status {}: {}",
2847 output.status,
2848 String::from_utf8_lossy(&output.stderr)
2849 );
2850 }
2851
2852 Ok(())
2853 }
2854}
2855
2856#[async_trait]
2858pub trait PetriVmRuntime: Send + Sync + 'static {
2859 type VmInspector: PetriVmInspector;
2861 type VmFramebufferAccess: PetriVmFramebufferAccess;
2863
2864 async fn teardown(self) -> anyhow::Result<()>;
2866 async fn wait_for_halt(&mut self, allow_reset: bool) -> anyhow::Result<PetriHaltReasonDetail>;
2869 async fn wait_for_agent(&mut self, set_high_vtl: bool) -> anyhow::Result<PipetteClient>;
2871 fn openhcl_diag(&self) -> Option<OpenHclDiagHandler>;
2873 async fn wait_for_boot_event(
2876 &mut self,
2877 timeout: Option<Duration>,
2878 ) -> anyhow::Result<Option<FirmwareEvent>>;
2879 async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<()>;
2882 async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()>;
2884 async fn restart_openhcl(
2887 &mut self,
2888 new_openhcl: &ResolvedArtifact,
2889 flags: OpenHclServicingFlags,
2890 ) -> anyhow::Result<()>;
2891 async fn save_openhcl(
2895 &mut self,
2896 new_openhcl: &ResolvedArtifact,
2897 flags: OpenHclServicingFlags,
2898 ) -> anyhow::Result<()>;
2899 async fn restore_openhcl(&mut self) -> anyhow::Result<()>;
2902 async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()>;
2905 fn inspector(&self) -> Option<Self::VmInspector> {
2907 None
2908 }
2909 fn take_framebuffer_access(&mut self) -> Option<Self::VmFramebufferAccess> {
2912 None
2913 }
2914 async fn reset(&mut self) -> anyhow::Result<()>;
2916 async fn get_guest_state_file(&self) -> anyhow::Result<Option<PathBuf>> {
2918 Ok(None)
2919 }
2920 async fn set_vtl2_settings(&mut self, settings: &Vtl2Settings) -> anyhow::Result<()>;
2922 async fn set_vmbus_drive(
2924 &mut self,
2925 disk: &Drive,
2926 controller_id: &Guid,
2927 controller_location: u32,
2928 ) -> anyhow::Result<()>;
2929 async fn add_pcie_device(
2931 &mut self,
2932 port_name: String,
2933 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
2934 ) -> anyhow::Result<()> {
2935 let _ = (port_name, resource);
2936 anyhow::bail!("PCIe hotplug not supported by this backend")
2937 }
2938 async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
2940 let _ = port_name;
2941 anyhow::bail!("PCIe hotplug not supported by this backend")
2942 }
2943}
2944
2945#[async_trait]
2947pub trait PetriVmInspector: Send + Sync + 'static {
2948 async fn inspect(&self, path: &str) -> anyhow::Result<inspect::Node>;
2951}
2952
2953pub struct NoPetriVmInspector;
2955#[async_trait]
2956impl PetriVmInspector for NoPetriVmInspector {
2957 async fn inspect(&self, _path: &str) -> anyhow::Result<inspect::Node> {
2958 unreachable!()
2959 }
2960}
2961
2962pub struct VmScreenshotMeta {
2964 pub color: image::ExtendedColorType,
2966 pub width: u16,
2968 pub height: u16,
2970}
2971
2972#[async_trait]
2974pub trait PetriVmFramebufferAccess: Send + 'static {
2975 async fn screenshot(&mut self, image: &mut Vec<u8>)
2978 -> anyhow::Result<Option<VmScreenshotMeta>>;
2979}
2980
2981pub struct NoPetriVmFramebufferAccess;
2983#[async_trait]
2984impl PetriVmFramebufferAccess for NoPetriVmFramebufferAccess {
2985 async fn screenshot(
2986 &mut self,
2987 _image: &mut Vec<u8>,
2988 ) -> anyhow::Result<Option<VmScreenshotMeta>> {
2989 unreachable!()
2990 }
2991}
2992
2993#[derive(Debug, Clone)]
2995pub struct ProcessorTopology {
2996 pub vp_count: u32,
2998 pub enable_smt: Option<bool>,
3000 pub vps_per_socket: Option<u32>,
3002 pub apic_mode: Option<ApicMode>,
3004}
3005
3006impl Default for ProcessorTopology {
3007 fn default() -> Self {
3008 Self {
3009 vp_count: 2,
3010 enable_smt: None,
3011 vps_per_socket: None,
3012 apic_mode: None,
3013 }
3014 }
3015}
3016
3017impl ProcessorTopology {
3018 pub fn heavy() -> Self {
3020 Self {
3021 vp_count: 16,
3022 vps_per_socket: Some(8),
3023 ..Default::default()
3024 }
3025 }
3026
3027 pub fn very_heavy() -> Self {
3029 Self {
3030 vp_count: 32,
3031 vps_per_socket: Some(16),
3032 ..Default::default()
3033 }
3034 }
3035}
3036
3037#[derive(Debug, Clone, Copy)]
3039pub enum ApicMode {
3040 Xapic,
3042 X2apicSupported,
3044 X2apicEnabled,
3046}
3047
3048#[derive(Debug, Clone)]
3050pub struct MemoryConfig {
3051 pub startup_bytes: u64,
3054 pub dynamic_memory_range: Option<(u64, u64)>,
3058 pub numa_mem_sizes: Option<Vec<u64>>,
3061 pub private_memory: Option<bool>,
3080 pub transparent_hugepages: bool,
3092}
3093
3094impl Default for MemoryConfig {
3095 fn default() -> Self {
3096 Self {
3097 startup_bytes: 4 * 1024 * 1024 * 1024, dynamic_memory_range: None,
3099 numa_mem_sizes: None,
3100 private_memory: None,
3101 transparent_hugepages: true,
3102 }
3103 }
3104}
3105
3106#[derive(Debug, Clone)]
3108pub struct UefiConfig {
3109 pub secure_boot_enabled: bool,
3111 pub secure_boot_template: Option<SecureBootTemplate>,
3113 pub custom_uefi_json: Option<Vec<u8>>,
3115 pub disable_frontpage: bool,
3117 pub default_boot_always_attempt: bool,
3119 pub enable_vpci_boot: bool,
3121 pub force_dma_bounce: bool,
3123 pub efi_diagnostics_log_level: EfiDiagnosticsLogLevel,
3125 pub efi_diagnostics_rate_limit: Option<u32>,
3128}
3129
3130impl Default for UefiConfig {
3131 fn default() -> Self {
3132 Self {
3133 secure_boot_enabled: false,
3134 secure_boot_template: None,
3135 custom_uefi_json: None,
3136 disable_frontpage: true,
3137 default_boot_always_attempt: false,
3138 enable_vpci_boot: false,
3139 force_dma_bounce: false,
3140 efi_diagnostics_log_level: EfiDiagnosticsLogLevel::Default,
3141 efi_diagnostics_rate_limit: None,
3142 }
3143 }
3144}
3145
3146#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3151pub enum EfiDiagnosticsLogLevel {
3152 #[default]
3154 Default,
3155 Info,
3157 Full,
3159}
3160
3161#[derive(Debug, Clone)]
3163pub enum OpenvmmLogConfig {
3164 TestDefault,
3168 BuiltInDefault,
3171 Custom(BTreeMap<String, String>),
3181}
3182
3183#[derive(Debug, Clone)]
3185pub struct OpenHclConfig {
3186 pub vmbus_redirect: bool,
3188 pub enable_mana_keepalive: bool,
3190 pub custom_command_line: Option<String>,
3194 pub log_levels: OpenvmmLogConfig,
3198 pub vtl2_base_address_type: Option<Vtl2BaseAddressType>,
3201 pub vtl2_settings: Option<Vtl2Settings>,
3203}
3204
3205impl OpenHclConfig {
3206 pub fn command_line(&self) -> String {
3209 let mut cmdline = self.custom_command_line.clone();
3210
3211 if self.enable_mana_keepalive {
3212 append_cmdline(&mut cmdline, "OPENHCL_MANA_KEEP_ALIVE=host,privatepool");
3213 }
3214
3215 match &self.log_levels {
3216 OpenvmmLogConfig::TestDefault => {
3217 let default_log_levels = {
3218 let openhcl_tracing = if let Ok(x) =
3220 std::env::var("OPENVMM_LOG").or_else(|_| std::env::var("HVLITE_LOG"))
3221 {
3222 format!("OPENVMM_LOG={x}")
3223 } else {
3224 "OPENVMM_LOG=debug".to_owned()
3225 };
3226 let openhcl_show_spans = if let Ok(x) = std::env::var("OPENVMM_SHOW_SPANS") {
3227 format!("OPENVMM_SHOW_SPANS={x}")
3228 } else {
3229 "OPENVMM_SHOW_SPANS=false".to_owned()
3230 };
3231 format!("{openhcl_tracing} {openhcl_show_spans}")
3232 };
3233 append_cmdline(&mut cmdline, &default_log_levels);
3234 }
3235 OpenvmmLogConfig::BuiltInDefault => {
3236 }
3238 OpenvmmLogConfig::Custom(levels) => {
3239 levels.iter().for_each(|(key, value)| {
3240 append_cmdline(&mut cmdline, format!("{key}={value}"));
3241 });
3242 }
3243 }
3244
3245 cmdline.unwrap_or_default()
3246 }
3247}
3248
3249impl Default for OpenHclConfig {
3250 fn default() -> Self {
3251 Self {
3252 vmbus_redirect: false,
3253 enable_mana_keepalive: true,
3254 custom_command_line: None,
3255 log_levels: OpenvmmLogConfig::TestDefault,
3256 vtl2_base_address_type: None,
3257 vtl2_settings: None,
3258 }
3259 }
3260}
3261
3262#[derive(Debug, Clone)]
3264pub struct TpmConfig {
3265 pub no_persistent_secrets: bool,
3267 pub hardware_sealing_policy: PetriHardwareSealingPolicy,
3269 pub version: PetriTpmVersion,
3271}
3272
3273impl Default for TpmConfig {
3274 fn default() -> Self {
3275 Self {
3276 no_persistent_secrets: true,
3277 hardware_sealing_policy: PetriHardwareSealingPolicy::Default,
3278 version: PetriTpmVersion::default(),
3279 }
3280 }
3281}
3282
3283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3285pub enum PetriTpmVersion {
3286 V138,
3288 #[default]
3290 V185,
3291}
3292
3293impl From<PetriTpmVersion> for tpm_resources::TpmVersion {
3294 fn from(version: PetriTpmVersion) -> Self {
3295 match version {
3296 PetriTpmVersion::V138 => tpm_resources::TpmVersion::V138,
3297 PetriTpmVersion::V185 => tpm_resources::TpmVersion::V185,
3298 }
3299 }
3300}
3301
3302impl From<PetriTpmVersion> for get_resources::ged::GedTpmVersion {
3303 fn from(version: PetriTpmVersion) -> Self {
3304 match version {
3305 PetriTpmVersion::V138 => get_resources::ged::GedTpmVersion::V138,
3306 PetriTpmVersion::V185 => get_resources::ged::GedTpmVersion::V185,
3307 }
3308 }
3309}
3310
3311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
3316pub enum PetriHardwareSealingPolicy {
3317 #[default]
3319 Default,
3320 HashPolicy,
3322 SignerPolicy,
3324}
3325
3326#[derive(Debug, Clone)]
3328pub enum IgvmFirmwareSource {
3329 File(ResolvedArtifact),
3331 VmgsOrInBox,
3333}
3334
3335#[derive(Debug, Clone)]
3339pub enum Firmware {
3340 LinuxDirect {
3342 kernel: ResolvedArtifact,
3344 initrd: ResolvedArtifact,
3346 },
3347 IgvmLinuxDirect {
3349 igvm_path: ResolvedArtifact,
3351 isolation: IsolationType,
3353 },
3354 OpenhclLinuxDirect {
3356 igvm_firmware: IgvmFirmwareSource,
3358 openhcl_config: OpenHclConfig,
3360 },
3361 Pcat {
3363 guest: PcatGuest,
3365 bios_firmware: ResolvedOptionalArtifact,
3367 svga_firmware: ResolvedOptionalArtifact,
3369 ide_controllers: [[Option<Drive>; 2]; 2],
3371 },
3372 OpenhclPcat {
3374 guest: PcatGuest,
3376 igvm_firmware: IgvmFirmwareSource,
3378 bios_firmware: ResolvedOptionalArtifact,
3380 svga_firmware: ResolvedOptionalArtifact,
3382 openhcl_config: OpenHclConfig,
3384 },
3385 Uefi {
3387 guest: UefiGuest,
3389 uefi_firmware: ResolvedArtifact,
3391 uefi_config: UefiConfig,
3393 },
3394 OpenhclUefi {
3396 guest: UefiGuest,
3398 isolation: Option<IsolationType>,
3400 igvm_firmware: IgvmFirmwareSource,
3402 uefi_config: UefiConfig,
3404 openhcl_config: OpenHclConfig,
3406 },
3407}
3408
3409#[derive(Debug, Copy, Clone, PartialEq, Eq)]
3411pub enum BootDeviceType {
3412 None,
3414 Ide,
3416 IdeViaScsi,
3418 IdeViaNvme,
3420 Scsi,
3422 ScsiViaScsi,
3424 ScsiViaNvme,
3426 Nvme,
3428 NvmeViaScsi,
3430 NvmeViaNvme,
3432 PcieNvme,
3434 PcieVirtioBlk,
3436}
3437
3438impl BootDeviceType {
3439 fn requires_vtl2(&self) -> bool {
3440 match self {
3441 BootDeviceType::None
3442 | BootDeviceType::Ide
3443 | BootDeviceType::Scsi
3444 | BootDeviceType::Nvme
3445 | BootDeviceType::PcieNvme
3446 | BootDeviceType::PcieVirtioBlk => false,
3447 BootDeviceType::IdeViaScsi
3448 | BootDeviceType::IdeViaNvme
3449 | BootDeviceType::ScsiViaScsi
3450 | BootDeviceType::ScsiViaNvme
3451 | BootDeviceType::NvmeViaScsi
3452 | BootDeviceType::NvmeViaNvme => true,
3453 }
3454 }
3455
3456 fn requires_vpci_boot(&self) -> bool {
3457 matches!(
3458 self,
3459 BootDeviceType::Nvme | BootDeviceType::NvmeViaScsi | BootDeviceType::NvmeViaNvme
3460 )
3461 }
3462
3463 fn requires_vmbus(&self) -> bool {
3464 match self {
3465 BootDeviceType::None
3466 | BootDeviceType::Ide
3467 | BootDeviceType::PcieNvme
3468 | BootDeviceType::PcieVirtioBlk => false,
3469 BootDeviceType::IdeViaScsi
3470 | BootDeviceType::IdeViaNvme
3471 | BootDeviceType::Scsi
3472 | BootDeviceType::ScsiViaScsi
3473 | BootDeviceType::ScsiViaNvme
3474 | BootDeviceType::Nvme
3475 | BootDeviceType::NvmeViaScsi
3476 | BootDeviceType::NvmeViaNvme => true,
3477 }
3478 }
3479}
3480
3481impl Firmware {
3482 pub fn linux_direct(
3485 resolver: &ArtifactResolver<'_>,
3486 arch: MachineArch,
3487 isolation: Option<IsolationType>,
3488 ) -> Self {
3489 use petri_artifacts_vmm_test::artifacts::loadable::*;
3490 use petri_artifacts_vmm_test::artifacts::snp_igvm::SNP_LINUX_DIRECT_IGVM_X64;
3491 match (arch, isolation) {
3492 (MachineArch::X86_64, None) => Firmware::LinuxDirect {
3493 kernel: resolver.require(LINUX_DIRECT_TEST_KERNEL_X64).erase(),
3494 initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_X64).erase(),
3495 },
3496 (MachineArch::Aarch64, None) => Firmware::LinuxDirect {
3497 kernel: resolver.require(LINUX_DIRECT_TEST_KERNEL_AARCH64).erase(),
3498 initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_AARCH64).erase(),
3499 },
3500 (MachineArch::X86_64, Some(IsolationType::Snp)) => Firmware::IgvmLinuxDirect {
3501 igvm_path: resolver.require(SNP_LINUX_DIRECT_IGVM_X64).erase(),
3502 isolation: IsolationType::Snp,
3503 },
3504 (arch, Some(isolation)) => {
3505 panic!("Linux direct does not support {isolation:?} isolation on {arch:?}")
3506 }
3507 }
3508 }
3509
3510 pub fn linux_direct_bzimage(resolver: &ArtifactResolver<'_>) -> Self {
3515 use petri_artifacts_vmm_test::artifacts::loadable::*;
3516 Firmware::LinuxDirect {
3517 kernel: resolver.require(LINUX_DIRECT_TEST_BZIMAGE_X64).erase(),
3518 initrd: resolver.require(LINUX_DIRECT_TEST_INITRD_X64).erase(),
3519 }
3520 }
3521
3522 pub fn openhcl_linux_direct(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
3524 use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3525 match arch {
3526 MachineArch::X86_64 => Firmware::OpenhclLinuxDirect {
3527 igvm_firmware: IgvmFirmwareSource::File(
3528 resolver.require(LATEST_LINUX_DIRECT_TEST_X64).erase(),
3529 ),
3530 openhcl_config: Default::default(),
3531 },
3532 MachineArch::Aarch64 => todo!("Linux direct not yet supported on aarch64"),
3533 }
3534 }
3535
3536 pub fn pcat(resolver: &ArtifactResolver<'_>, guest: PcatGuest) -> Self {
3538 use petri_artifacts_vmm_test::artifacts::loadable::*;
3539 Firmware::Pcat {
3540 guest,
3541 bios_firmware: resolver.try_require(PCAT_FIRMWARE_X64).erase(),
3542 svga_firmware: resolver.try_require(SVGA_FIRMWARE_X64).erase(),
3543 ide_controllers: [[None, None], [None, None]],
3544 }
3545 }
3546
3547 pub fn openhcl_pcat(resolver: &ArtifactResolver<'_>, guest: PcatGuest) -> Self {
3549 use petri_artifacts_vmm_test::artifacts::loadable::*;
3550 use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3551 Firmware::OpenhclPcat {
3552 guest,
3553 igvm_firmware: IgvmFirmwareSource::File(resolver.require(LATEST_STANDARD_X64).erase()),
3554 bios_firmware: resolver.try_require(PCAT_FIRMWARE_X64).erase(),
3555 svga_firmware: resolver.try_require(SVGA_FIRMWARE_X64).erase(),
3556 openhcl_config: OpenHclConfig {
3557 vmbus_redirect: true,
3559 ..Default::default()
3560 },
3561 }
3562 }
3563
3564 pub fn uefi(resolver: &ArtifactResolver<'_>, arch: MachineArch, guest: UefiGuest) -> Self {
3566 use petri_artifacts_vmm_test::artifacts::loadable::*;
3567 let uefi_firmware = match arch {
3568 MachineArch::X86_64 => resolver.require(UEFI_FIRMWARE_X64).erase(),
3569 MachineArch::Aarch64 => resolver.require(UEFI_FIRMWARE_AARCH64).erase(),
3570 };
3571 Firmware::Uefi {
3572 guest,
3573 uefi_firmware,
3574 uefi_config: Default::default(),
3575 }
3576 }
3577
3578 pub fn openhcl_uefi(
3580 resolver: &ArtifactResolver<'_>,
3581 arch: MachineArch,
3582 guest: UefiGuest,
3583 isolation: Option<IsolationType>,
3584 ) -> Self {
3585 use petri_artifacts_vmm_test::artifacts::openhcl_igvm::*;
3586 let igvm_firmware = IgvmFirmwareSource::File(match arch {
3587 MachineArch::X86_64 if isolation.is_some() => resolver.require(LATEST_CVM_X64).erase(),
3588 MachineArch::X86_64 => resolver.require(LATEST_STANDARD_X64).erase(),
3589 MachineArch::Aarch64 => resolver.require(LATEST_STANDARD_AARCH64).erase(),
3590 });
3591 Firmware::OpenhclUefi {
3592 guest,
3593 isolation,
3594 igvm_firmware,
3595 uefi_config: Default::default(),
3596 openhcl_config: Default::default(),
3597 }
3598 }
3599
3600 fn is_openhcl(&self) -> bool {
3601 match self {
3602 Firmware::OpenhclLinuxDirect { .. }
3603 | Firmware::OpenhclUefi { .. }
3604 | Firmware::OpenhclPcat { .. } => true,
3605 Firmware::LinuxDirect { .. }
3606 | Firmware::IgvmLinuxDirect { .. }
3607 | Firmware::Pcat { .. }
3608 | Firmware::Uefi { .. } => false,
3609 }
3610 }
3611
3612 fn isolation(&self) -> Option<IsolationType> {
3613 match self {
3614 Firmware::IgvmLinuxDirect { isolation, .. } => Some(*isolation),
3615 Firmware::OpenhclUefi { isolation, .. } => *isolation,
3616 Firmware::LinuxDirect { .. }
3617 | Firmware::Pcat { .. }
3618 | Firmware::Uefi { .. }
3619 | Firmware::OpenhclLinuxDirect { .. }
3620 | Firmware::OpenhclPcat { .. } => None,
3621 }
3622 }
3623
3624 fn is_isolated_without_paravisor(&self) -> bool {
3626 self.isolation().is_some() && !self.is_openhcl()
3627 }
3628
3629 fn is_linux_direct(&self) -> bool {
3630 match self {
3631 Firmware::LinuxDirect { .. }
3632 | Firmware::IgvmLinuxDirect { .. }
3633 | Firmware::OpenhclLinuxDirect { .. } => true,
3634 Firmware::Pcat { .. }
3635 | Firmware::Uefi { .. }
3636 | Firmware::OpenhclUefi { .. }
3637 | Firmware::OpenhclPcat { .. } => false,
3638 }
3639 }
3640
3641 pub fn linux_direct_initrd(&self) -> Option<&Path> {
3643 match self {
3644 Firmware::LinuxDirect { initrd, .. } => Some(initrd.get()),
3645 _ => None,
3646 }
3647 }
3648
3649 fn is_pcat(&self) -> bool {
3650 match self {
3651 Firmware::Pcat { .. } | Firmware::OpenhclPcat { .. } => true,
3652 Firmware::Uefi { .. }
3653 | Firmware::OpenhclUefi { .. }
3654 | Firmware::LinuxDirect { .. }
3655 | Firmware::IgvmLinuxDirect { .. }
3656 | Firmware::OpenhclLinuxDirect { .. } => false,
3657 }
3658 }
3659
3660 fn os_flavor(&self) -> OsFlavor {
3661 match self {
3662 Firmware::LinuxDirect { .. }
3663 | Firmware::OpenhclLinuxDirect { .. }
3664 | Firmware::Uefi {
3665 guest: UefiGuest::Mshv(_),
3666 ..
3667 }
3668 | Firmware::OpenhclUefi {
3669 guest: UefiGuest::Mshv(_),
3670 ..
3671 }
3672 | Firmware::IgvmLinuxDirect { .. } => OsFlavor::Linux,
3673 Firmware::Uefi {
3674 guest: UefiGuest::GuestTestUefi { .. } | UefiGuest::None,
3675 ..
3676 }
3677 | Firmware::OpenhclUefi {
3678 guest: UefiGuest::GuestTestUefi { .. } | UefiGuest::None,
3679 ..
3680 } => OsFlavor::Uefi,
3681 Firmware::Pcat {
3682 guest: PcatGuest::Vhd(cfg),
3683 ..
3684 }
3685 | Firmware::OpenhclPcat {
3686 guest: PcatGuest::Vhd(cfg),
3687 ..
3688 }
3689 | Firmware::Uefi {
3690 guest: UefiGuest::Vhd(cfg),
3691 ..
3692 }
3693 | Firmware::OpenhclUefi {
3694 guest: UefiGuest::Vhd(cfg),
3695 ..
3696 } => cfg.os_flavor,
3697 Firmware::Pcat {
3698 guest: PcatGuest::Iso(cfg),
3699 ..
3700 }
3701 | Firmware::OpenhclPcat {
3702 guest: PcatGuest::Iso(cfg),
3703 ..
3704 } => cfg.os_flavor,
3705 }
3706 }
3707
3708 fn quirks(&self) -> GuestQuirks {
3709 match self {
3710 Firmware::Pcat {
3711 guest: PcatGuest::Vhd(cfg),
3712 ..
3713 }
3714 | Firmware::Uefi {
3715 guest: UefiGuest::Vhd(cfg),
3716 ..
3717 }
3718 | Firmware::OpenhclUefi {
3719 guest: UefiGuest::Vhd(cfg),
3720 ..
3721 } => cfg.quirks.clone(),
3722 Firmware::Pcat {
3723 guest: PcatGuest::Iso(cfg),
3724 ..
3725 } => cfg.quirks.clone(),
3726 _ => Default::default(),
3727 }
3728 }
3729
3730 fn expected_boot_event(&self) -> Option<FirmwareEvent> {
3731 match self {
3732 Firmware::LinuxDirect { .. }
3733 | Firmware::IgvmLinuxDirect { .. }
3734 | Firmware::OpenhclLinuxDirect { .. }
3735 | Firmware::Uefi {
3736 guest: UefiGuest::GuestTestUefi(_),
3737 ..
3738 }
3739 | Firmware::OpenhclUefi {
3740 guest: UefiGuest::GuestTestUefi(_),
3741 ..
3742 } => None,
3743 Firmware::Pcat { .. } | Firmware::OpenhclPcat { .. } => {
3744 Some(FirmwareEvent::BootAttempt)
3746 }
3747 Firmware::Uefi {
3748 guest: UefiGuest::None,
3749 ..
3750 }
3751 | Firmware::OpenhclUefi {
3752 guest: UefiGuest::None,
3753 ..
3754 } => Some(FirmwareEvent::NoBootDevice),
3755 Firmware::Uefi { .. } | Firmware::OpenhclUefi { .. } => {
3756 Some(FirmwareEvent::BootSuccess)
3757 }
3758 }
3759 }
3760
3761 fn openhcl_config(&self) -> Option<&OpenHclConfig> {
3762 match self {
3763 Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3764 | Firmware::OpenhclUefi { openhcl_config, .. }
3765 | Firmware::OpenhclPcat { openhcl_config, .. } => Some(openhcl_config),
3766 Firmware::LinuxDirect { .. }
3767 | Firmware::IgvmLinuxDirect { .. }
3768 | Firmware::Pcat { .. }
3769 | Firmware::Uefi { .. } => None,
3770 }
3771 }
3772
3773 fn openhcl_config_mut(&mut self) -> Option<&mut OpenHclConfig> {
3774 match self {
3775 Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3776 | Firmware::OpenhclUefi { openhcl_config, .. }
3777 | Firmware::OpenhclPcat { openhcl_config, .. } => Some(openhcl_config),
3778 Firmware::LinuxDirect { .. }
3779 | Firmware::IgvmLinuxDirect { .. }
3780 | Firmware::Pcat { .. }
3781 | Firmware::Uefi { .. } => None,
3782 }
3783 }
3784
3785 fn openhcl_firmware(&self) -> Option<&IgvmFirmwareSource> {
3786 match self {
3787 Firmware::OpenhclLinuxDirect { igvm_firmware, .. }
3788 | Firmware::OpenhclUefi { igvm_firmware, .. }
3789 | Firmware::OpenhclPcat { igvm_firmware, .. } => Some(igvm_firmware),
3790 Firmware::LinuxDirect { .. }
3791 | Firmware::IgvmLinuxDirect { .. }
3792 | Firmware::Pcat { .. }
3793 | Firmware::Uefi { .. } => None,
3794 }
3795 }
3796
3797 fn into_runtime_config(
3798 self,
3799 vmbus_storage_controllers: HashMap<Guid, VmbusStorageController>,
3800 ) -> PetriVmRuntimeConfig {
3801 match self {
3802 Firmware::OpenhclLinuxDirect { openhcl_config, .. }
3803 | Firmware::OpenhclUefi { openhcl_config, .. }
3804 | Firmware::OpenhclPcat { openhcl_config, .. } => PetriVmRuntimeConfig {
3805 vtl2_settings: Some(
3806 openhcl_config
3807 .vtl2_settings
3808 .unwrap_or_else(default_vtl2_settings),
3809 ),
3810 ide_controllers: None,
3811 vmbus_storage_controllers,
3812 },
3813 Firmware::Pcat {
3814 ide_controllers, ..
3815 } => PetriVmRuntimeConfig {
3816 vtl2_settings: None,
3817 ide_controllers: Some(ide_controllers),
3818 vmbus_storage_controllers,
3819 },
3820 Firmware::LinuxDirect { .. }
3821 | Firmware::IgvmLinuxDirect { .. }
3822 | Firmware::Uefi { .. } => PetriVmRuntimeConfig {
3823 vtl2_settings: None,
3824 ide_controllers: None,
3825 vmbus_storage_controllers,
3826 },
3827 }
3828 }
3829
3830 fn uefi_config(&self) -> Option<&UefiConfig> {
3831 match self {
3832 Firmware::Uefi { uefi_config, .. } | Firmware::OpenhclUefi { uefi_config, .. } => {
3833 Some(uefi_config)
3834 }
3835 Firmware::LinuxDirect { .. }
3836 | Firmware::IgvmLinuxDirect { .. }
3837 | Firmware::OpenhclLinuxDirect { .. }
3838 | Firmware::Pcat { .. }
3839 | Firmware::OpenhclPcat { .. } => None,
3840 }
3841 }
3842
3843 fn uefi_config_mut(&mut self) -> Option<&mut UefiConfig> {
3844 match self {
3845 Firmware::Uefi { uefi_config, .. } | Firmware::OpenhclUefi { uefi_config, .. } => {
3846 Some(uefi_config)
3847 }
3848 Firmware::LinuxDirect { .. }
3849 | Firmware::IgvmLinuxDirect { .. }
3850 | Firmware::OpenhclLinuxDirect { .. }
3851 | Firmware::Pcat { .. }
3852 | Firmware::OpenhclPcat { .. } => None,
3853 }
3854 }
3855
3856 fn mshv_boot(&self) -> Option<&MshvBoot> {
3857 match self {
3858 Firmware::Uefi {
3859 guest: UefiGuest::Mshv(boot),
3860 ..
3861 } => Some(boot),
3862 _ => None,
3863 }
3864 }
3865
3866 fn boot_drive(
3867 &self,
3868 use_virtio_vsock: bool,
3869 prepared: Option<&PetriInitrd>,
3870 ) -> anyhow::Result<Option<Drive>> {
3871 if let Firmware::Uefi {
3872 guest: UefiGuest::Mshv(boot),
3873 ..
3874 }
3875 | Firmware::OpenhclUefi {
3876 guest: UefiGuest::Mshv(boot),
3877 ..
3878 } = self
3879 {
3880 return Ok(Some(Drive::new(
3881 Some(
3882 boot.build(use_virtio_vsock, prepared)
3883 .context("composing mshv boot disk")?,
3884 ),
3885 false,
3886 )));
3887 }
3888 Ok(match self {
3889 Firmware::LinuxDirect { .. }
3890 | Firmware::IgvmLinuxDirect { .. }
3891 | Firmware::OpenhclLinuxDirect { .. } => None,
3892 Firmware::Pcat { guest, .. } | Firmware::OpenhclPcat { guest, .. } => {
3893 Some((guest.disk_path(), guest.is_dvd()))
3894 }
3895 Firmware::Uefi { guest, .. } | Firmware::OpenhclUefi { guest, .. } => {
3896 guest.disk_path().map(|dp| (dp, false))
3897 }
3898 }
3899 .map(|(disk_path, is_dvd)| Drive::new(Some(Disk::Differencing(disk_path)), is_dvd)))
3900 }
3901
3902 fn vtl2_settings(&mut self) -> Option<&mut Vtl2Settings> {
3903 self.openhcl_config_mut()
3904 .map(|c| c.vtl2_settings.get_or_insert_with(default_vtl2_settings))
3905 }
3906
3907 fn ide_controllers(&self) -> Option<&[[Option<Drive>; 2]; 2]> {
3908 match self {
3909 Firmware::Pcat {
3910 ide_controllers, ..
3911 } => Some(ide_controllers),
3912 _ => None,
3913 }
3914 }
3915
3916 fn ide_controllers_mut(&mut self) -> Option<&mut [[Option<Drive>; 2]; 2]> {
3917 match self {
3918 Firmware::Pcat {
3919 ide_controllers, ..
3920 } => Some(ide_controllers),
3921 _ => None,
3922 }
3923 }
3924}
3925
3926#[derive(Debug, Clone)]
3929pub enum PcatGuest {
3930 Vhd(BootImageConfig<boot_image_type::Vhd>),
3932 Iso(BootImageConfig<boot_image_type::Iso>),
3934}
3935
3936impl PcatGuest {
3937 fn disk_path(&self) -> DiskPath {
3938 match self {
3939 PcatGuest::Vhd(disk) => disk.disk_path(),
3940 PcatGuest::Iso(disk) => disk.disk_path(),
3941 }
3942 }
3943
3944 fn is_dvd(&self) -> bool {
3945 matches!(self, Self::Iso(_))
3946 }
3947}
3948
3949#[derive(Debug, Clone)]
3952pub enum UefiGuest {
3953 Mshv(MshvBoot),
3956 Vhd(BootImageConfig<boot_image_type::Vhd>),
3958 GuestTestUefi(ResolvedArtifact),
3960 None,
3962}
3963
3964impl UefiGuest {
3965 pub fn guest_test_uefi(resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
3967 use petri_artifacts_vmm_test::artifacts::test_vhd::*;
3968 let artifact = match arch {
3969 MachineArch::X86_64 => resolver.require(GUEST_TEST_UEFI_X64).erase(),
3970 MachineArch::Aarch64 => resolver.require(GUEST_TEST_UEFI_AARCH64).erase(),
3971 };
3972 UefiGuest::GuestTestUefi(artifact)
3973 }
3974
3975 fn disk_path(&self) -> Option<DiskPath> {
3976 match self {
3977 UefiGuest::Vhd(vhd) => Some(vhd.disk_path()),
3978 UefiGuest::GuestTestUefi(p) => Some(DiskPath::Local(p.get().to_path_buf())),
3979 UefiGuest::None => None,
3980 UefiGuest::Mshv(_) => None,
3981 }
3982 }
3983}
3984
3985pub mod boot_image_type {
3987 mod private {
3988 pub trait Sealed {}
3989 impl Sealed for super::Vhd {}
3990 impl Sealed for super::Iso {}
3991 }
3992
3993 pub trait BootImageType: private::Sealed {}
3996
3997 #[derive(Debug, Clone)]
3999 pub enum Vhd {}
4000
4001 #[derive(Debug, Clone)]
4003 pub enum Iso {}
4004
4005 impl BootImageType for Vhd {}
4006 impl BootImageType for Iso {}
4007}
4008
4009#[derive(Debug, Clone)]
4011pub struct BootImageConfig<T: boot_image_type::BootImageType> {
4012 artifact: ResolvedArtifactSource,
4014 os_flavor: OsFlavor,
4016 quirks: GuestQuirks,
4020 _type: core::marker::PhantomData<T>,
4022}
4023
4024impl<T: boot_image_type::BootImageType> BootImageConfig<T> {
4025 fn disk_path(&self) -> DiskPath {
4027 match self.artifact.get() {
4028 ArtifactSource::Local(p) => DiskPath::Local(p.clone()),
4029 ArtifactSource::Remote { url } => DiskPath::Remote { url: url.clone() },
4030 }
4031 }
4032}
4033
4034impl BootImageConfig<boot_image_type::Vhd> {
4035 pub fn from_vhd<A>(artifact: ResolvedArtifactSource<A>) -> Self
4037 where
4038 A: petri_artifacts_common::tags::IsTestVhd,
4039 {
4040 BootImageConfig {
4041 artifact: artifact.erase(),
4042 os_flavor: A::OS_FLAVOR,
4043 quirks: A::quirks(),
4044 _type: std::marker::PhantomData,
4045 }
4046 }
4047}
4048
4049impl BootImageConfig<boot_image_type::Iso> {
4050 pub fn from_iso<A>(artifact: ResolvedArtifactSource<A>) -> Self
4052 where
4053 A: petri_artifacts_common::tags::IsTestIso,
4054 {
4055 BootImageConfig {
4056 artifact: artifact.erase(),
4057 os_flavor: A::OS_FLAVOR,
4058 quirks: A::quirks(),
4059 _type: std::marker::PhantomData,
4060 }
4061 }
4062}
4063
4064#[derive(Debug, Clone, Copy)]
4066pub enum IsolationType {
4067 Vbs,
4069 Snp,
4071 Tdx,
4073}
4074
4075#[derive(Debug, Clone, Copy)]
4077pub struct OpenHclServicingFlags {
4078 pub enable_nvme_keepalive: bool,
4081 pub enable_mana_keepalive: bool,
4083 pub override_version_checks: bool,
4085 pub stop_timeout_hint_secs: Option<u16>,
4087}
4088
4089#[derive(Debug, Clone)]
4091pub enum DiskPath {
4092 Local(PathBuf),
4094 Remote {
4096 url: String,
4098 },
4099}
4100
4101impl From<PathBuf> for DiskPath {
4102 fn from(path: PathBuf) -> Self {
4103 DiskPath::Local(path)
4104 }
4105}
4106
4107#[derive(Debug, Clone)]
4109pub enum Disk {
4110 Memory(u64),
4112 Differencing(DiskPath),
4114 SqliteDifferencing {
4118 base: DiskPath,
4120 dbhd_path: PathBuf,
4122 },
4123 Persistent(PathBuf),
4125 Temporary(Arc<TempPath>),
4127}
4128
4129#[derive(Debug, Clone)]
4131pub enum TempOrPersistentPath {
4132 Temp(Arc<TempPath>),
4134 Persistent(PathBuf),
4136}
4137
4138impl AsRef<Path> for TempOrPersistentPath {
4139 fn as_ref(&self) -> &Path {
4140 match self {
4141 TempOrPersistentPath::Temp(temp_path) => temp_path.as_ref(),
4142 TempOrPersistentPath::Persistent(path_buf) => path_buf.as_ref(),
4143 }
4144 }
4145}
4146
4147#[derive(Debug, Clone)]
4149pub struct PetriInitrd {
4150 pub path: TempOrPersistentPath,
4152 pub rdinit_param: String,
4154}
4155
4156#[derive(Debug, Clone)]
4158pub struct PetriVmgsDisk {
4159 pub disk: Disk,
4161 pub encryption_policy: GuestStateEncryptionPolicy,
4163}
4164
4165impl Default for PetriVmgsDisk {
4166 fn default() -> Self {
4167 PetriVmgsDisk {
4168 disk: Disk::Memory(vmgs_format::VMGS_DEFAULT_CAPACITY),
4169 encryption_policy: GuestStateEncryptionPolicy::None(false),
4171 }
4172 }
4173}
4174
4175#[derive(Debug, Clone)]
4177pub enum PetriVmgsResource {
4178 Disk(PetriVmgsDisk),
4180 ReprovisionOnFailure(PetriVmgsDisk),
4182 ReprovisionSingle(PetriVmgsDisk),
4184 Ephemeral,
4186}
4187
4188impl PetriVmgsResource {
4189 pub fn vmgs(&self) -> Option<&PetriVmgsDisk> {
4191 match self {
4192 PetriVmgsResource::Disk(vmgs)
4193 | PetriVmgsResource::ReprovisionOnFailure(vmgs)
4194 | PetriVmgsResource::ReprovisionSingle(vmgs) => Some(vmgs),
4195 PetriVmgsResource::Ephemeral => None,
4196 }
4197 }
4198
4199 pub fn disk(&self) -> Option<&Disk> {
4201 self.vmgs().map(|vmgs| &vmgs.disk)
4202 }
4203
4204 pub fn encryption_policy(&self) -> Option<GuestStateEncryptionPolicy> {
4206 self.vmgs().map(|vmgs| vmgs.encryption_policy)
4207 }
4208}
4209
4210#[derive(Debug, Clone, Copy)]
4212pub enum PetriGuestStateLifetime {
4213 Disk,
4216 ReprovisionOnFailure,
4218 ReprovisionSingle,
4220 Ephemeral,
4222}
4223
4224#[derive(Debug, Clone, Copy)]
4226pub enum SecureBootTemplate {
4227 MicrosoftWindows,
4229 MicrosoftUefiCertificateAuthority,
4231}
4232
4233#[derive(Default, Debug, Clone)]
4236pub struct VmmQuirks {
4237 pub flaky_boot: Option<Duration>,
4240}
4241
4242#[derive(Debug, Clone, Copy, Eq, PartialEq)]
4244pub enum PetriHaltReason {
4245 PowerOff,
4247 Reset,
4249 Hibernate,
4251 TripleFault,
4253 Other,
4255}
4256
4257impl PetriHaltReason {
4258 pub fn with_detail(self, detail: String) -> PetriHaltReasonDetail {
4260 PetriHaltReasonDetail {
4261 reason: self,
4262 detail,
4263 }
4264 }
4265}
4266
4267#[derive(Debug, Clone)]
4269pub struct PetriHaltReasonDetail {
4270 pub reason: PetriHaltReason,
4272 pub detail: String,
4274}
4275
4276pub(crate) fn linux_vsock_blacklist(use_virtio_vsock: bool) -> &'static str {
4277 if use_virtio_vsock {
4278 "initcall_blacklist=hv_sock_init"
4279 } else {
4280 "initcall_blacklist=virtio_vsock_init"
4281 }
4282}
4283
4284fn append_cmdline(cmd: &mut Option<String>, add_cmd: impl AsRef<str>) {
4285 if let Some(cmd) = cmd.as_mut() {
4286 cmd.push(' ');
4287 cmd.push_str(add_cmd.as_ref());
4288 } else {
4289 *cmd = Some(add_cmd.as_ref().to_string());
4290 }
4291}
4292
4293async fn collect_inspect(
4294 name: &'static str,
4295 inspect: impl Future<Output = anyhow::Result<inspect::Node>>,
4296 log_source: &PetriLogSource,
4297 prefix: &str,
4298) {
4299 let node = match CancelContext::new()
4300 .with_timeout(INSPECT_TIMEOUT)
4301 .until_cancelled(inspect)
4302 .await
4303 {
4304 Ok(Ok(node)) => node,
4305 Ok(Err(e)) => {
4306 tracing::warn!(name, ?e, "failed to collect inspect state");
4307 return;
4308 }
4309 Err(_) => {
4310 tracing::warn!(name, "timed out collecting inspect state");
4311 return;
4312 }
4313 };
4314
4315 if let Err(e) = log_source.write_attachment(
4316 &format!("{prefix}_inspect_{name}.log"),
4317 format!("{node:#}").as_bytes(),
4318 ) {
4319 tracing::error!(name, ?e, "failed to save inspect log");
4320 }
4321}
4322
4323pub struct ModifyFn<T>(pub Box<dyn FnOnce(T) -> T + Send>);
4325
4326impl<T> Debug for ModifyFn<T> {
4327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4328 f.debug_tuple("ModifyFn").finish_non_exhaustive()
4329 }
4330}
4331
4332fn default_vtl2_settings() -> Vtl2Settings {
4334 Vtl2Settings {
4335 version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
4336 fixed: None,
4337 dynamic: Some(Default::default()),
4338 namespace_settings: Default::default(),
4339 }
4340}
4341
4342#[derive(Debug, Copy, Clone, PartialEq, Eq)]
4344pub enum Vtl {
4345 Vtl0 = 0,
4347 Vtl1 = 1,
4349 Vtl2 = 2,
4351}
4352
4353#[derive(Debug, Copy, Clone, PartialEq, Eq)]
4355pub enum VmbusStorageType {
4356 Scsi,
4358 Nvme,
4360 VirtioBlk,
4362}
4363
4364#[derive(Debug, Clone)]
4366pub struct Drive {
4367 pub disk: Option<Disk>,
4369 pub is_dvd: bool,
4371}
4372
4373impl Drive {
4374 pub fn new(disk: Option<Disk>, is_dvd: bool) -> Self {
4376 Self { disk, is_dvd }
4377 }
4378}
4379
4380#[derive(Debug, Clone)]
4382pub struct VmbusStorageController {
4383 pub target_vtl: Vtl,
4385 pub controller_type: VmbusStorageType,
4387 pub drives: HashMap<u32, Drive>,
4389}
4390
4391impl VmbusStorageController {
4392 pub fn new(target_vtl: Vtl, controller_type: VmbusStorageType) -> Self {
4394 Self {
4395 target_vtl,
4396 controller_type,
4397 drives: HashMap::new(),
4398 }
4399 }
4400
4401 pub fn set_drive(
4403 &mut self,
4404 lun: Option<u32>,
4405 drive: Drive,
4406 allow_modify_existing: bool,
4407 ) -> u32 {
4408 let lun = lun.unwrap_or_else(|| {
4409 let mut lun = None;
4411 for x in 0..u8::MAX as u32 {
4412 if !self.drives.contains_key(&x) {
4413 lun = Some(x);
4414 break;
4415 }
4416 }
4417 lun.expect("all locations on this controller are in use")
4418 });
4419
4420 if self.drives.insert(lun, drive).is_some() && !allow_modify_existing {
4421 panic!("a disk with lun {lun} already existed on this controller");
4422 }
4423
4424 lun
4425 }
4426}
4427
4428pub(crate) fn petri_disk_cache_dir() -> String {
4430 if let Ok(dir) = std::env::var("PETRI_CACHE_DIR") {
4431 return dir;
4432 }
4433
4434 #[cfg(target_os = "macos")]
4435 {
4436 if let Some(home) = std::env::home_dir() {
4437 return home.join("Library/Caches/petri").display().to_string();
4438 }
4439 }
4440
4441 #[cfg(windows)]
4442 {
4443 if let Ok(local) = std::env::var("LOCALAPPDATA") {
4444 return format!("{local}\\petri\\cache");
4445 }
4446 }
4447
4448 if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
4450 return format!("{xdg}/petri");
4451 }
4452 if let Some(home) = std::env::home_dir() {
4453 return home.join(".cache/petri").display().to_string();
4454 }
4455
4456 ".cache/petri".to_string()
4457}
4458
4459pub struct NestedTestDeps {
4461 pub archive: ErasedArtifactHandle,
4463 pub binary: String,
4465 pub test_name: String,
4467}
4468
4469impl NestedTestDeps {
4470 pub fn new<A: IsNextestArchive>(
4472 archive: ArtifactHandle<A>,
4473 binary: &str,
4474 test_name: &str,
4475 ) -> Self {
4476 Self {
4477 archive: archive.erase(),
4478 binary: binary.into(),
4479 test_name: test_name.into(),
4480 }
4481 }
4482}
4483
4484#[derive(Debug)]
4486pub struct ResolvedNestedTestDeps {
4487 pub test_binary: TempPath,
4489 pub test_name: String,
4491 pub artifacts: Vec<(ErasedArtifactHandle, PathBuf)>,
4493}
4494
4495mod nextest_binaries_metadata_schema {
4496 use serde::Deserialize;
4497 use serde::Serialize;
4498 use std::collections::HashMap;
4499 use std::path::PathBuf;
4500
4501 #[derive(Serialize, Deserialize)]
4502 #[serde(rename_all = "kebab-case")]
4503 pub struct RustBuildMeta {
4504 pub target_directory: PathBuf,
4505 }
4506
4507 #[derive(Serialize, Deserialize)]
4508 #[serde(rename_all = "kebab-case")]
4509 pub struct Binary {
4510 pub binary_name: String,
4511 pub binary_path: PathBuf,
4512 }
4513
4514 #[derive(Serialize, Deserialize)]
4515 #[serde(rename_all = "kebab-case")]
4516 pub struct BinariesMetadata {
4517 pub rust_build_meta: RustBuildMeta,
4518 pub rust_binaries: HashMap<String, Binary>,
4519 }
4520}
4521
4522impl NestedTestDeps {
4523 fn extract_binary(&self) -> anyhow::Result<TempPath> {
4525 let temp_dir = tempfile::tempdir()?;
4526
4527 let archive = resolve_artifact(self.archive)?;
4530
4531 let mut cmd = std::process::Command::new("tar");
4532 cmd.arg("--zstd")
4533 .arg("-xvf")
4534 .arg(archive)
4535 .current_dir(&temp_dir);
4536 futures::executor::block_on(crate::run_host_cmd(cmd))?;
4537
4538 let meta_file = fs_err::File::open(
4539 temp_dir
4540 .path()
4541 .join("target")
4542 .join("nextest")
4543 .join("binaries-metadata.json"),
4544 )?;
4545 let meta: nextest_binaries_metadata_schema::BinariesMetadata =
4546 serde_json::from_reader(meta_file)?;
4547
4548 let build_binary_path = meta
4549 .rust_binaries
4550 .iter()
4551 .find(|(_, b)| b.binary_name == self.binary)
4552 .context("binary missing")?
4553 .1
4554 .binary_path
4555 .clone();
4556
4557 let local_binary_path = temp_dir.path().join(
4558 build_binary_path
4559 .strip_prefix(meta.rust_build_meta.target_directory.parent().unwrap())?,
4560 );
4561
4562 let test_content_temp_dir =
4564 PathBuf::from(std::env::var(VMM_TESTS_CONTENT_DIR)?).join(NESTED_TEMP_DIR);
4565 fs_err::create_dir_all(&test_content_temp_dir)?;
4566 let temp_path = tempfile::NamedTempFile::new_in(&test_content_temp_dir)
4567 .context("failed to create temp nested test")?
4568 .into_temp_path();
4569
4570 fs_err::copy(&local_binary_path, &temp_path)?;
4571
4572 Ok(temp_path)
4573 }
4574
4575 fn resolve(&self, discover_artifacts: bool) -> anyhow::Result<ResolvedNestedTestDeps> {
4576 let test_binary = self
4577 .extract_binary()
4578 .context("failed to extract nextest binary")?;
4579
4580 let artifacts = if discover_artifacts {
4581 petri_artifacts_core::query_test_binary_artifacts(&test_binary, &[&self.test_name])
4582 .context("failed to query test binary for artifacts")?
4583 .into_artifacts_list()
4584 .into_iter()
4585 .filter(|id| {
4586 id != petri_artifacts_common::artifacts::TEST_LOG_DIRECTORY::GLOBAL_UNIQUE_ID
4587 })
4588 .map(|id| {
4589 let handle = petri_artifacts_core::artifact_from_id(&id)
4590 .with_context(|| format!("unknown artifact handle: {id}"))?;
4591 Ok((handle, resolve_artifact(handle)?))
4592 })
4593 .collect::<anyhow::Result<Vec<_>>>()?
4594 } else {
4595 Vec::new()
4596 };
4597
4598 Ok(ResolvedNestedTestDeps {
4599 test_binary,
4600 test_name: self.test_name.clone(),
4601 artifacts,
4602 })
4603 }
4604}
4605
4606trait PetriGuestPaths {
4607 fn os_flavor(&self) -> OsFlavor;
4609
4610 fn path_separator(&self) -> &'static str {
4612 match self.os_flavor() {
4613 OsFlavor::Windows => "\\",
4614 _ => "/",
4615 }
4616 }
4617
4618 fn agent_disk_root(&self) -> &'static str {
4622 match self.os_flavor() {
4623 OsFlavor::Windows => "D:",
4624 _ => "/cidata",
4625 }
4626 }
4627
4628 fn build_guest_path(&self, components: &[String]) -> String {
4631 components.join(self.path_separator())
4632 }
4633
4634 fn convert_guest_path(&self, path: &Path) -> String {
4637 self.build_guest_path(
4638 &path
4639 .iter()
4640 .map(|c| c.to_str().expect("path not utf8").to_string())
4641 .collect::<Vec<_>>(),
4642 )
4643 }
4644
4645 fn parents<'a>(&self, path: &'a str) -> Vec<&'a str> {
4647 path.match_indices(self.path_separator())
4648 .map(|(x, _)| &path[0..x])
4649 .collect()
4650 }
4651
4652 fn agent_disk_path(&self, components: &[String]) -> String {
4656 self.build_guest_path(&[&[self.agent_disk_root().into()], components].concat())
4657 }
4658
4659 fn binary_with_extension(&self, name: &str) -> String {
4661 match self.os_flavor() {
4662 OsFlavor::Windows => format!("{name}.exe"),
4663 _ => name.into(),
4664 }
4665 }
4666}
4667
4668struct FatFsPathBuilder(OsFlavor);
4669
4670impl PetriGuestPaths for FatFsPathBuilder {
4671 fn os_flavor(&self) -> OsFlavor {
4672 self.0
4673 }
4674
4675 fn path_separator(&self) -> &'static str {
4676 "/"
4677 }
4678}
4679
4680impl<T: PetriVmmBackend> PetriGuestPaths for PetriVm<T> {
4681 fn os_flavor(&self) -> OsFlavor {
4682 self.properties.os_flavor
4683 }
4684}
4685
4686impl<T: PetriVmmBackend> PetriGuestPaths for PetriVmBuilder<T> {
4687 fn os_flavor(&self) -> OsFlavor {
4688 self.os_flavor()
4689 }
4690}
4691
4692#[cfg(test)]
4693mod tests {
4694 use super::*;
4695 use crate::Drive;
4696 use crate::VmbusStorageController;
4697 use crate::VmbusStorageType;
4698 use crate::Vtl;
4699
4700 #[derive(Clone, Copy)]
4701 enum TestInspectBehavior {
4702 Success,
4703 Error,
4704 Panic,
4705 }
4706
4707 #[derive(Clone)]
4708 struct TestInspector(TestInspectBehavior);
4709
4710 #[async_trait::async_trait]
4711 impl PetriVmInspector for TestInspector {
4712 async fn inspect(&self, _path: &str) -> anyhow::Result<inspect::Node> {
4713 match self.0 {
4714 TestInspectBehavior::Success => Ok(inspect::Node::Unevaluated),
4715 TestInspectBehavior::Error => anyhow::bail!("inspect failed"),
4716 TestInspectBehavior::Panic => panic!("inspect panicked"),
4717 }
4718 }
4719 }
4720
4721 struct TestFramebuffer;
4722
4723 #[async_trait::async_trait]
4724 impl PetriVmFramebufferAccess for TestFramebuffer {
4725 async fn screenshot(
4726 &mut self,
4727 _image: &mut Vec<u8>,
4728 ) -> anyhow::Result<Option<VmScreenshotMeta>> {
4729 unreachable!()
4730 }
4731 }
4732
4733 struct TestRuntime(TestInspectBehavior);
4734
4735 #[async_trait::async_trait]
4736 impl PetriVmRuntime for TestRuntime {
4737 type VmInspector = TestInspector;
4738 type VmFramebufferAccess = TestFramebuffer;
4739
4740 async fn teardown(self) -> anyhow::Result<()> {
4741 Ok(())
4742 }
4743
4744 async fn wait_for_halt(
4745 &mut self,
4746 _allow_reset: bool,
4747 ) -> anyhow::Result<PetriHaltReasonDetail> {
4748 unreachable!()
4749 }
4750
4751 async fn wait_for_agent(&mut self, _set_high_vtl: bool) -> anyhow::Result<PipetteClient> {
4752 unreachable!()
4753 }
4754
4755 fn openhcl_diag(&self) -> Option<OpenHclDiagHandler> {
4756 None
4757 }
4758
4759 async fn wait_for_boot_event(
4760 &mut self,
4761 _timeout: Option<Duration>,
4762 ) -> anyhow::Result<Option<FirmwareEvent>> {
4763 unreachable!()
4764 }
4765
4766 async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<()> {
4767 unreachable!()
4768 }
4769
4770 async fn send_enlightened_shutdown(&mut self, _kind: ShutdownKind) -> anyhow::Result<()> {
4771 unreachable!()
4772 }
4773
4774 async fn restart_openhcl(
4775 &mut self,
4776 _new_openhcl: &ResolvedArtifact,
4777 _flags: OpenHclServicingFlags,
4778 ) -> anyhow::Result<()> {
4779 unreachable!()
4780 }
4781
4782 async fn save_openhcl(
4783 &mut self,
4784 _new_openhcl: &ResolvedArtifact,
4785 _flags: OpenHclServicingFlags,
4786 ) -> anyhow::Result<()> {
4787 unreachable!()
4788 }
4789
4790 async fn restore_openhcl(&mut self) -> anyhow::Result<()> {
4791 unreachable!()
4792 }
4793
4794 async fn update_command_line(&mut self, _command_line: &str) -> anyhow::Result<()> {
4795 unreachable!()
4796 }
4797
4798 fn inspector(&self) -> Option<Self::VmInspector> {
4799 Some(TestInspector(self.0))
4800 }
4801
4802 async fn reset(&mut self) -> anyhow::Result<()> {
4803 unreachable!()
4804 }
4805
4806 async fn set_vtl2_settings(&mut self, _settings: &Vtl2Settings) -> anyhow::Result<()> {
4807 unreachable!()
4808 }
4809
4810 async fn set_vmbus_drive(
4811 &mut self,
4812 _disk: &Drive,
4813 _controller_id: &Guid,
4814 _controller_location: u32,
4815 ) -> anyhow::Result<()> {
4816 unreachable!()
4817 }
4818 }
4819
4820 fn test_runtime_guard(
4821 driver: DefaultDriver,
4822 log_source: &PetriLogSource,
4823 behavior: TestInspectBehavior,
4824 ) -> PetriVmRuntimeGuard<TestRuntime> {
4825 PetriVmRuntimeGuard {
4826 runtime: Some(TestRuntime(behavior)),
4827 driver,
4828 log_source: log_source.clone(),
4829 capture_inspect_on_drop: true,
4830 }
4831 }
4832
4833 fn run_failed_test(
4834 log_source: &PetriLogSource,
4835 behavior: TestInspectBehavior,
4836 ) -> anyhow::Result<()> {
4837 let pool = pal_async::DefaultPool::new();
4838 let driver = pool.driver();
4839 drop(test_runtime_guard(driver.clone(), log_source, behavior));
4840 drop(driver);
4841 pool.run();
4842 anyhow::bail!("original test failure")
4843 }
4844
4845 fn inspect_attachment_count(log_source: &PetriLogSource) -> usize {
4846 fs_err::read_dir(log_source.output_dir())
4847 .unwrap()
4848 .filter_map(Result::ok)
4849 .filter(|entry| {
4850 entry
4851 .file_name()
4852 .to_string_lossy()
4853 .starts_with("failure_inspect_vmm")
4854 })
4855 .count()
4856 }
4857
4858 #[test]
4859 fn test_runtime_guard_failure_capture() {
4860 let temp_dir = tempfile::tempdir().unwrap();
4861 let log_source = crate::tracing::try_init_tracing(
4862 temp_dir.path(),
4863 tracing::level_filters::LevelFilter::DEBUG,
4864 None,
4865 )
4866 .unwrap();
4867
4868 let error = run_failed_test(&log_source, TestInspectBehavior::Success).unwrap_err();
4869 assert_eq!(error.to_string(), "original test failure");
4870 assert_eq!(inspect_attachment_count(&log_source), 1);
4871
4872 let pool = pal_async::DefaultPool::new();
4873 let driver = pool.driver();
4874 let mut guard =
4875 test_runtime_guard(driver.clone(), &log_source, TestInspectBehavior::Success);
4876 let _runtime = guard.take_for_teardown();
4877 drop(guard);
4878 drop(driver);
4879 pool.run();
4880 assert_eq!(inspect_attachment_count(&log_source), 1);
4881
4882 for behavior in [TestInspectBehavior::Error, TestInspectBehavior::Panic] {
4883 let error = run_failed_test(&log_source, behavior).unwrap_err();
4884 assert_eq!(error.to_string(), "original test failure");
4885 assert_eq!(inspect_attachment_count(&log_source), 1);
4886 }
4887 }
4888
4889 #[test]
4890 fn test_vmbus_storage_controller() {
4891 let mut controller = VmbusStorageController::new(Vtl::Vtl0, VmbusStorageType::Scsi);
4892 assert_eq!(
4893 controller.set_drive(Some(1), Drive::new(None, false), false),
4894 1
4895 );
4896 assert!(controller.drives.contains_key(&1));
4897 assert_eq!(
4898 controller.set_drive(None, Drive::new(None, false), false),
4899 0
4900 );
4901 assert!(controller.drives.contains_key(&0));
4902 assert_eq!(
4903 controller.set_drive(None, Drive::new(None, false), false),
4904 2
4905 );
4906 assert!(controller.drives.contains_key(&2));
4907 assert_eq!(
4908 controller.set_drive(Some(0), Drive::new(None, false), true),
4909 0
4910 );
4911 assert!(controller.drives.contains_key(&0));
4912 }
4913}