petri/vm/openvmm/
mod.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Code managing the lifetime of a `PetriVmOpenVmm`. All VMs live the same lifecycle:
5//! * A `PetriVmConfigOpenVmm` is built for the given firmware and architecture in `construct`.
6//! * The configuration is optionally modified from the defaults using the helpers in `modify`.
7//! * The `PetriVmOpenVmm` is started by the code in `start`.
8//! * The VM is interacted with through the methods in `runtime`.
9//! * The VM is either shut down by the code in `runtime`, or gets dropped and cleaned up automatically.
10
11mod construct;
12mod modify;
13mod runtime;
14mod start;
15
16pub use runtime::OpenVmmFramebufferAccess;
17pub use runtime::OpenVmmInspector;
18pub use runtime::PetriVmOpenVmm;
19
20use crate::BootDeviceType;
21use crate::Firmware;
22use crate::OpenHclServicingFlags;
23use crate::PetriDiskType;
24use crate::PetriLogFile;
25use crate::PetriVmConfig;
26use crate::PetriVmResources;
27use crate::PetriVmgsDisk;
28use crate::PetriVmgsResource;
29use crate::PetriVmmBackend;
30use crate::VmmQuirks;
31use crate::disk_image::AgentImage;
32use crate::linux_direct_serial_agent::LinuxDirectSerialAgent;
33use anyhow::Context;
34use async_trait::async_trait;
35use disk_backend_resources::LayeredDiskHandle;
36use disk_backend_resources::layer::DiskLayerHandle;
37use disk_backend_resources::layer::RamDiskLayerHandle;
38use get_resources::ged::FirmwareEvent;
39use guid::Guid;
40use hvlite_defs::config::Config;
41use hvlite_helpers::disk::open_disk_type;
42use hyperv_ic_resources::shutdown::ShutdownRpc;
43use mesh::Receiver;
44use mesh::Sender;
45use net_backend_resources::mac_address::MacAddress;
46use pal_async::DefaultDriver;
47use pal_async::socket::PolledSocket;
48use pal_async::task::Task;
49use petri_artifacts_common::tags::GuestQuirksInner;
50use petri_artifacts_common::tags::MachineArch;
51use petri_artifacts_common::tags::OsFlavor;
52use petri_artifacts_core::ArtifactResolver;
53use petri_artifacts_core::ResolvedArtifact;
54use std::path::Path;
55use std::path::PathBuf;
56use std::sync::Arc;
57use std::time::Duration;
58use storvsp_resources::ScsiControllerHandle;
59use tempfile::TempPath;
60use unix_socket::UnixListener;
61use vm_resource::IntoResource;
62use vm_resource::Resource;
63use vm_resource::kind::DiskHandleKind;
64use vmgs_resources::VmgsDisk;
65use vmgs_resources::VmgsResource;
66use vtl2_settings_proto::Vtl2Settings;
67
68/// The instance guid used for all of our SCSI drives.
69pub(crate) const SCSI_INSTANCE: Guid = guid::guid!("27b553e8-8b39-411b-a55f-839971a7884f");
70
71/// The instance guid for the NVMe controller automatically added for boot media
72/// for paravisor storage translation.
73pub(crate) const PARAVISOR_BOOT_NVME_INSTANCE: Guid =
74    guid::guid!("92bc8346-718b-449a-8751-edbf3dcd27e4");
75
76/// The instance guid for the NVMe controller automatically added for boot media.
77pub(crate) const BOOT_NVME_INSTANCE: Guid = guid::guid!("e23a04e2-90f5-4852-bc9d-e7ac691b756c");
78
79/// The instance guid for the MANA nic automatically added when specifying `PetriVmConfigOpenVmm::with_nic`
80const MANA_INSTANCE: Guid = guid::guid!("f9641cf4-d915-4743-a7d8-efa75db7b85a");
81
82/// The namespace ID for the NVMe controller automatically added for boot media.
83pub(crate) const BOOT_NVME_NSID: u32 = 37;
84
85/// The LUN ID for the NVMe controller automatically added for boot media.
86pub(crate) const BOOT_NVME_LUN: u32 = 1;
87
88/// The MAC address used by the NIC assigned with [`PetriVmConfigOpenVmm::with_nic`].
89pub const NIC_MAC_ADDRESS: MacAddress = MacAddress::new([0x00, 0x15, 0x5D, 0x12, 0x12, 0x12]);
90
91/// OpenVMM Petri Backend
92pub struct OpenVmmPetriBackend {
93    openvmm_path: ResolvedArtifact,
94}
95
96#[async_trait]
97impl PetriVmmBackend for OpenVmmPetriBackend {
98    type VmmConfig = PetriVmConfigOpenVmm;
99    type VmRuntime = PetriVmOpenVmm;
100
101    fn check_compat(firmware: &Firmware, arch: MachineArch) -> bool {
102        arch == MachineArch::host()
103            && !(firmware.is_openhcl() && (!cfg!(windows) || arch == MachineArch::Aarch64))
104            && !(firmware.is_pcat() && arch == MachineArch::Aarch64)
105    }
106
107    fn quirks(firmware: &Firmware) -> (GuestQuirksInner, VmmQuirks) {
108        (
109            firmware.quirks().openvmm,
110            VmmQuirks {
111                // Workaround for #1684
112                flaky_boot: firmware.is_pcat().then_some(Duration::from_secs(15)),
113            },
114        )
115    }
116
117    fn default_servicing_flags() -> OpenHclServicingFlags {
118        OpenHclServicingFlags {
119            enable_nvme_keepalive: true,
120            override_version_checks: false,
121            stop_timeout_hint_secs: None,
122        }
123    }
124
125    fn create_guest_dump_disk() -> anyhow::Result<
126        Option<(
127            Arc<TempPath>,
128            Box<dyn FnOnce() -> anyhow::Result<Box<dyn fatfs::ReadWriteSeek>>>,
129        )>,
130    > {
131        Ok(None) // TODO #2403
132    }
133
134    fn new(resolver: &ArtifactResolver<'_>) -> Self {
135        OpenVmmPetriBackend {
136            openvmm_path: resolver
137                .require(petri_artifacts_vmm_test::artifacts::OPENVMM_NATIVE)
138                .erase(),
139        }
140    }
141
142    async fn run(
143        self,
144        config: PetriVmConfig,
145        modify_vmm_config: Option<impl FnOnce(PetriVmConfigOpenVmm) -> PetriVmConfigOpenVmm + Send>,
146        resources: &PetriVmResources,
147    ) -> anyhow::Result<Self::VmRuntime> {
148        let mut config = PetriVmConfigOpenVmm::new(&self.openvmm_path, config, resources)?;
149
150        if let Some(f) = modify_vmm_config {
151            config = f(config);
152        }
153
154        config.run().await
155    }
156}
157
158/// Configuration state for a test VM.
159pub struct PetriVmConfigOpenVmm {
160    // Direct configuration related information.
161    firmware: Firmware,
162    arch: MachineArch,
163    config: Config,
164    boot_device_type: BootDeviceType,
165
166    // Runtime resources
167    resources: PetriVmResourcesOpenVmm,
168
169    // Logging
170    openvmm_log_file: PetriLogFile,
171
172    // Resources that are only used during startup.
173    /// Single VMBus SCSI controller shared for all VTL0 disks added by petri.
174    petri_vtl0_scsi: ScsiControllerHandle,
175
176    ged: Option<get_resources::ged::GuestEmulationDeviceHandle>,
177    framebuffer_view: Option<framebuffer::View>,
178}
179/// Various channels and resources used to interact with the VM while it is running.
180struct PetriVmResourcesOpenVmm {
181    log_stream_tasks: Vec<Task<anyhow::Result<()>>>,
182    firmware_event_recv: Receiver<FirmwareEvent>,
183    shutdown_ic_send: Sender<ShutdownRpc>,
184    kvp_ic_send: Sender<hyperv_ic_resources::kvp::KvpConnectRpc>,
185    ged_send: Option<Sender<get_resources::ged::GuestEmulationRequest>>,
186    pipette_listener: PolledSocket<UnixListener>,
187    vtl2_pipette_listener: Option<PolledSocket<UnixListener>>,
188    linux_direct_serial_agent: Option<LinuxDirectSerialAgent>,
189
190    // Externally injected management stuff also needed at runtime.
191    driver: DefaultDriver,
192    agent_image: Option<AgentImage>,
193    openhcl_agent_image: Option<AgentImage>,
194    openvmm_path: ResolvedArtifact,
195    output_dir: PathBuf,
196
197    // TempPaths that cannot be dropped until the end.
198    vtl2_vsock_path: Option<TempPath>,
199    _vmbus_vsock_path: TempPath,
200
201    vtl2_settings: Option<Vtl2Settings>,
202}
203
204impl PetriVmConfigOpenVmm {
205    /// Get the OS that the VM will boot into.
206    pub fn os_flavor(&self) -> OsFlavor {
207        self.firmware.os_flavor()
208    }
209}
210
211fn memdiff_disk(path: &Path) -> anyhow::Result<Resource<DiskHandleKind>> {
212    let disk = open_disk_type(path, true)
213        .with_context(|| format!("failed to open disk: {}", path.display()))?;
214    Ok(LayeredDiskHandle {
215        layers: vec![
216            RamDiskLayerHandle { len: None }.into_resource().into(),
217            DiskLayerHandle(disk).into_resource().into(),
218        ],
219    }
220    .into_resource())
221}
222
223fn memdiff_vmgs(vmgs: &PetriVmgsResource) -> anyhow::Result<VmgsResource> {
224    let convert_disk = |disk: &PetriVmgsDisk| -> anyhow::Result<VmgsDisk> {
225        Ok(VmgsDisk {
226            disk: match &disk.disk {
227                PetriDiskType::Memory => LayeredDiskHandle::single_layer(RamDiskLayerHandle {
228                    len: Some(vmgs_format::VMGS_DEFAULT_CAPACITY),
229                })
230                .into_resource(),
231                PetriDiskType::Differencing(path) => memdiff_disk(path)?,
232                PetriDiskType::Persistent(path) => open_disk_type(path, false)?,
233            },
234            encryption_policy: disk.encryption_policy,
235        })
236    };
237
238    Ok(match vmgs {
239        PetriVmgsResource::Disk(disk) => VmgsResource::Disk(convert_disk(disk)?),
240        PetriVmgsResource::ReprovisionOnFailure(disk) => {
241            VmgsResource::ReprovisionOnFailure(convert_disk(disk)?)
242        }
243        PetriVmgsResource::Reprovision(disk) => VmgsResource::Reprovision(convert_disk(disk)?),
244        PetriVmgsResource::Ephemeral => VmgsResource::Ephemeral,
245    })
246}