1use super::PetriVmResourcesOpenVmm;
7use crate::OpenHclServicingFlags;
8use crate::PetriHaltReason;
9use crate::PetriHaltReasonDetail;
10use crate::PetriVmFramebufferAccess;
11use crate::PetriVmInspector;
12use crate::PetriVmRuntime;
13use crate::ShutdownKind;
14use crate::VmScreenshotMeta;
15use crate::openhcl_diag::OpenHclDiagHandler;
16use crate::worker::Worker;
17use anyhow::Context;
18use async_trait::async_trait;
19use chipset_resources::acpi_power_button::PowerButtonRpc;
20use framebuffer::View;
21use futures::FutureExt;
22use futures_concurrency::future::Race;
23use get_resources::ged::FirmwareEvent;
24use get_resources::ged::IpmiSelEvent;
25use hyperv_ic_resources::shutdown::ShutdownRpc;
26use mesh::CancelContext;
27use mesh::Receiver;
28use mesh::RecvError;
29use mesh::rpc::RpcError;
30use mesh::rpc::RpcSend;
31use mesh_process::Mesh;
32use openvmm_defs::rpc::PulseSaveRestoreError;
33use pal_async::socket::PolledSocket;
34use petri_artifacts_core::ResolvedArtifact;
35#[cfg(target_os = "linux")]
36use pipette_client::PIPETTE_PORT;
37use pipette_client::PipetteClient;
38use std::future::Future;
39use std::path::Path;
40use std::sync::Arc;
41use std::time::Duration;
42use vmm_core_defs::HaltReason;
43#[cfg(target_os = "linux")]
44use vmsocket::VmAddress;
45#[cfg(target_os = "linux")]
46use vmsocket::VmSocket;
47use vtl2_settings_proto::Vtl2Settings;
48
49pub struct PetriVmOpenVmm {
54 inner: PetriVmInner,
55 halt: PetriVmHaltReceiver,
56}
57
58#[async_trait]
59impl PetriVmRuntime for PetriVmOpenVmm {
60 type VmInspector = OpenVmmInspector;
61 type VmFramebufferAccess = OpenVmmFramebufferAccess;
62
63 async fn teardown(self) -> anyhow::Result<()> {
64 tracing::info!("waiting for worker");
65 let worker = Arc::into_inner(self.inner.worker)
66 .context("all references to the OpenVMM worker have not been closed")?;
67 worker.shutdown().await?;
68
69 tracing::info!("Worker quit, waiting for mesh");
70 self.inner.mesh.shutdown().await;
71
72 tracing::info!("Mesh shutdown, waiting for logging tasks");
73 for t in self.inner.resources.log_stream_tasks {
74 t.await?;
75 }
76
77 Ok(())
78 }
79
80 async fn wait_for_halt(&mut self, allow_reset: bool) -> anyhow::Result<PetriHaltReasonDetail> {
81 let halt_reason = if let Some(already) = self.halt.already_received.take() {
82 already.map_err(anyhow::Error::from)
83 } else {
84 self.halt
85 .halt_notif
86 .recv()
87 .await
88 .context("Failed to get halt reason")
89 }?;
90
91 tracing::info!(?halt_reason, "Got halt reason");
92
93 let reason = match halt_reason {
94 HaltReason::PowerOff => PetriHaltReason::PowerOff,
95 HaltReason::Reset => PetriHaltReason::Reset,
96 HaltReason::Hibernate => PetriHaltReason::Hibernate,
97 HaltReason::TripleFault { .. } => PetriHaltReason::TripleFault,
98 _ => PetriHaltReason::Other,
99 };
100
101 if allow_reset && reason == PetriHaltReason::Reset {
102 self.reset().await?
103 }
104
105 Ok(PetriHaltReasonDetail {
106 reason,
107 detail: format!("{halt_reason:?}"),
108 })
109 }
110
111 async fn wait_for_agent(&mut self, set_high_vtl: bool) -> anyhow::Result<PipetteClient> {
112 Self::wait_for_agent(self, set_high_vtl).await
113 }
114
115 fn openhcl_diag(&self) -> Option<OpenHclDiagHandler> {
116 self.inner.resources.vtl2_vsock_path.as_ref().map(|path| {
117 OpenHclDiagHandler::new(diag_client::DiagClient::from_hybrid_vsock(
118 self.inner.resources.driver.clone(),
119 path,
120 ))
121 })
122 }
123
124 async fn wait_for_boot_event(
125 &mut self,
126 timeout: Option<Duration>,
127 ) -> anyhow::Result<Option<FirmwareEvent>> {
128 CancelContext::new()
131 .with_timeout(timeout.unwrap_or(Duration::MAX))
132 .until_cancelled(Self::wait_for_boot_event(self))
133 .await
134 .ok()
135 .transpose()
136 }
137
138 async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<()> {
139 Self::wait_for_enlightened_shutdown_ready(self)
140 .await
141 .map(|_| ())
142 }
143
144 async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()> {
145 Self::send_enlightened_shutdown(self, kind).await
146 }
147
148 async fn restart_openhcl(
149 &mut self,
150 new_openhcl: &ResolvedArtifact,
151 flags: OpenHclServicingFlags,
152 ) -> anyhow::Result<()> {
153 Self::save_openhcl(self, new_openhcl, flags).await?;
154 Self::restore_openhcl(self).await
155 }
156
157 async fn save_openhcl(
158 &mut self,
159 new_openhcl: &ResolvedArtifact,
160 flags: OpenHclServicingFlags,
161 ) -> anyhow::Result<()> {
162 Self::save_openhcl(self, new_openhcl, flags).await
163 }
164
165 async fn restore_openhcl(&mut self) -> anyhow::Result<()> {
166 Self::restore_openhcl(self).await
167 }
168
169 async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()> {
170 Self::update_command_line(self, command_line).await
171 }
172
173 fn inspector(&self) -> Option<OpenVmmInspector> {
174 Some(OpenVmmInspector {
175 worker: self.inner.worker.clone(),
176 })
177 }
178
179 fn take_framebuffer_access(&mut self) -> Option<OpenVmmFramebufferAccess> {
180 self.inner
181 .framebuffer_view
182 .take()
183 .map(|view| OpenVmmFramebufferAccess { view })
184 }
185
186 async fn reset(&mut self) -> anyhow::Result<()> {
187 Self::reset(self).await
188 }
189
190 async fn set_vtl2_settings(&mut self, settings: &Vtl2Settings) -> anyhow::Result<()> {
191 Self::set_vtl2_settings(self, settings).await
192 }
193
194 async fn set_vmbus_drive(
195 &mut self,
196 _disk: &crate::Drive,
197 _controller_id: &guid::Guid,
198 _controller_location: u32,
199 ) -> anyhow::Result<()> {
200 todo!("openvmm set vmbus drive")
201 }
202
203 async fn add_pcie_device(
204 &mut self,
205 port_name: String,
206 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
207 ) -> anyhow::Result<()> {
208 Self::add_pcie_device(self, port_name, resource).await
209 }
210
211 async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
212 Self::remove_pcie_device(self, port_name).await
213 }
214}
215
216pub(super) struct PetriVmInner {
217 pub(super) resources: PetriVmResourcesOpenVmm,
218 pub(super) mesh: Mesh,
219 pub(super) worker: Arc<Worker>,
220 pub(super) framebuffer_view: Option<View>,
221 pub(super) cidata_mounted: bool,
225 pub(super) tcp_pipette_port: Option<u16>,
228 pub(super) pid: i32,
229}
230
231struct PetriVmHaltReceiver {
232 halt_notif: Receiver<HaltReason>,
233 already_received: Option<Result<HaltReason, RecvError>>,
234}
235
236macro_rules! petri_vm_fn {
239 ($(#[$($attrss:tt)*])* $vis:vis async fn $fn_name:ident (&mut self $(,$arg:ident: $ty:ty)*) $(-> $ret:ty)?) => {
240 $(#[$($attrss)*])*
241 $vis async fn $fn_name(&mut self, $($arg:$ty,)*) $(-> $ret)? {
242 Self::wait_for_halt_or_internal(&mut self.halt, self.inner.$fn_name($($arg,)*)).await
243 }
244 };
245}
246
247impl PetriVmOpenVmm {
250 pub(super) fn new(inner: PetriVmInner, halt_notif: Receiver<HaltReason>) -> Self {
251 Self {
252 inner,
253 halt: PetriVmHaltReceiver {
254 halt_notif,
255 already_received: None,
256 },
257 }
258 }
259
260 pub fn vtl2_vsock_path(&self) -> anyhow::Result<&Path> {
262 self.inner
263 .resources
264 .vtl2_vsock_path
265 .as_deref()
266 .context("VM is not configured with OpenHCL")
267 }
268
269 pub fn pid(&self) -> i32 {
271 self.inner.pid
272 }
273
274 petri_vm_fn!(
275 pub async fn wait_for_boot_event(&mut self) -> anyhow::Result<FirmwareEvent>
278 );
279 petri_vm_fn!(
280 pub async fn wait_for_ipmi_sel(&mut self) -> anyhow::Result<IpmiSelEvent>
282 );
283 petri_vm_fn!(
284 pub async fn wait_for_vtl0_start(&mut self) -> anyhow::Result<Result<(), get_resources::ged::Vtl0StartError>>
287 );
288 petri_vm_fn!(
289 pub async fn wait_for_enlightened_shutdown_ready(&mut self) -> anyhow::Result<Option<mesh::OneshotReceiver<()>>>
293 );
294 petri_vm_fn!(
295 pub async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()>
297 );
298 petri_vm_fn!(
299 pub async fn send_acpi_shutdown(&mut self) -> anyhow::Result<()>
303 );
304 petri_vm_fn!(
305 pub async fn wait_for_kvp(&mut self) -> anyhow::Result<mesh::Sender<hyperv_ic_resources::kvp::KvpRpc>>
308 );
309 petri_vm_fn!(
310 pub async fn save_openhcl(
312 &mut self,
313 new_openhcl: &ResolvedArtifact,
314 flags: OpenHclServicingFlags
315 ) -> anyhow::Result<()>
316 );
317 petri_vm_fn!(
318 pub async fn restore_openhcl(
320 &mut self
321 ) -> anyhow::Result<()>
322 );
323 petri_vm_fn!(
324 pub async fn update_command_line(
326 &mut self,
327 command_line: &str
328 ) -> anyhow::Result<()>
329 );
330
331 petri_vm_fn!(
332 pub async fn add_pcie_device(
334 &mut self,
335 port_name: String,
336 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>
337 ) -> anyhow::Result<()>
338 );
339 petri_vm_fn!(
340 pub async fn remove_pcie_device(
342 &mut self,
343 port_name: String
344 ) -> anyhow::Result<()>
345 );
346 petri_vm_fn!(
347 pub async fn eject_pcie_device(
351 &mut self,
352 port_name: String,
353 timeout: Duration
354 ) -> anyhow::Result<()>
355 );
356 petri_vm_fn!(
357 pub async fn reset(&mut self) -> anyhow::Result<()>
359 );
360 petri_vm_fn!(
361 pub async fn add_vpci_device(
363 &mut self,
364 instance_id: guid::Guid,
365 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>
366 ) -> anyhow::Result<()>
367 );
368 petri_vm_fn!(
369 pub async fn remove_vpci_device(
371 &mut self,
372 instance_id: guid::Guid
373 ) -> anyhow::Result<()>
374 );
375 petri_vm_fn!(
376 pub async fn dump_state(&mut self, path: &Path) -> anyhow::Result<()>
378 );
379 petri_vm_fn!(
380 pub async fn wait_for_agent(&mut self, set_high_vtl: bool) -> anyhow::Result<PipetteClient>
382 );
383 petri_vm_fn!(
384 pub async fn set_vtl2_settings(&mut self, settings: &Vtl2Settings) -> anyhow::Result<()>
386 );
387
388 petri_vm_fn!(
389 pub async fn pause(&mut self) -> anyhow::Result<()>
391 );
392 petri_vm_fn!(
393 pub async fn save_state(&mut self) -> anyhow::Result<Vec<u8>>
396 );
397 petri_vm_fn!(
398 pub async fn resume(&mut self) -> anyhow::Result<()>
400 );
401 petri_vm_fn!(
402 pub async fn verify_save_restore(&mut self) -> anyhow::Result<()>
406 );
407 petri_vm_fn!(pub(crate) async fn launch_linux_direct_pipette(&mut self) -> anyhow::Result<()>);
408
409 pub async fn wait_for_halt_or<T, F: Future<Output = anyhow::Result<T>>>(
416 &mut self,
417 future: F,
418 ) -> anyhow::Result<T> {
419 Self::wait_for_halt_or_internal(&mut self.halt, future).await
420 }
421
422 async fn wait_for_halt_or_internal<T, F: Future<Output = anyhow::Result<T>>>(
423 halt: &mut PetriVmHaltReceiver,
424 future: F,
425 ) -> anyhow::Result<T> {
426 let future = &mut std::pin::pin!(future);
427 enum Either<T> {
428 Future(anyhow::Result<T>),
429 Halt(Result<HaltReason, RecvError>),
430 }
431 let res = (
432 future.map(Either::Future),
433 halt.halt_notif.recv().map(Either::Halt),
434 )
435 .race()
436 .await;
437
438 match res {
439 Either::Future(Ok(success)) => Ok(success),
440 Either::Future(Err(e)) => {
441 tracing::warn!(
442 ?e,
443 "Future returned with an error, sleeping for 5 seconds to let outstanding work finish"
444 );
445 let mut c = CancelContext::new().with_timeout(Duration::from_secs(5));
446 c.cancelled().await;
447 Err(e)
448 }
449 Either::Halt(halt_result) => {
450 tracing::warn!(
451 halt_result = format_args!("{:x?}", halt_result),
452 "Halt channel returned while waiting for other future, sleeping for 5 seconds to let outstanding work finish"
453 );
454 let mut c = CancelContext::new().with_timeout(Duration::from_secs(5));
455 let try_again = c.until_cancelled(future).await;
456
457 match try_again {
458 Ok(fut_result) => {
459 halt.already_received = Some(halt_result);
460 if let Err(e) = &fut_result {
461 tracing::warn!(
462 ?e,
463 "Future returned with an error, sleeping for 5 seconds to let outstanding work finish"
464 );
465 let mut c = CancelContext::new().with_timeout(Duration::from_secs(5));
466 c.cancelled().await;
467 }
468 fut_result
469 }
470 Err(_cancel) => match halt_result {
471 Ok(halt_reason) => Err(anyhow::anyhow!("VM halted: {:x?}", halt_reason)),
472 Err(e) => Err(e).context("VM disappeared"),
473 },
474 }
475 }
476 }
477 }
478}
479
480impl PetriVmInner {
481 async fn wait_for_boot_event(&mut self) -> anyhow::Result<FirmwareEvent> {
482 self.resources
483 .firmware_event_recv
484 .recv()
485 .await
486 .context("Failed to get firmware boot event")
487 }
488
489 async fn wait_for_ipmi_sel(&mut self) -> anyhow::Result<IpmiSelEvent> {
490 CancelContext::new()
491 .with_timeout(Duration::from_secs(30))
492 .until_cancelled(self.resources.ipmi_sel_event_recv.recv())
493 .await
494 .context("timed out waiting for an IPMI SEL host notification")?
495 .context("IPMI SEL host notification channel closed")
496 }
497
498 async fn wait_for_enlightened_shutdown_ready(
499 &mut self,
500 ) -> anyhow::Result<Option<mesh::OneshotReceiver<()>>> {
501 let Some(send) = self.resources.shutdown_ic_send.as_ref() else {
502 return Ok(None);
503 };
504 let recv = send
505 .call(ShutdownRpc::WaitReady, ())
506 .await
507 .context("waiting for shutdown IC to be ready")?;
508 Ok(Some(recv))
509 }
510
511 async fn send_enlightened_shutdown(&mut self, kind: ShutdownKind) -> anyhow::Result<()> {
512 let send = self
513 .resources
514 .shutdown_ic_send
515 .as_ref()
516 .context("shutdown IC not configured")?;
517 let shutdown_result = send
518 .call(
519 ShutdownRpc::Shutdown,
520 hyperv_ic_resources::shutdown::ShutdownParams {
521 shutdown_type: match kind {
522 ShutdownKind::Shutdown => {
523 hyperv_ic_resources::shutdown::ShutdownType::PowerOff
524 }
525 ShutdownKind::Reboot => hyperv_ic_resources::shutdown::ShutdownType::Reboot,
526 ShutdownKind::Hibernate => {
527 hyperv_ic_resources::shutdown::ShutdownType::Hibernate
528 }
529 },
530 force: false,
531 },
532 )
533 .await?;
534
535 tracing::info!(?shutdown_result, "Shutdown sent");
536 anyhow::ensure!(
537 shutdown_result == hyperv_ic_resources::shutdown::ShutdownResult::Ok,
538 "Got non-Ok shutdown response"
539 );
540
541 Ok(())
542 }
543
544 async fn send_acpi_shutdown(&mut self) -> anyhow::Result<()> {
545 self.resources
546 .acpi_power_button_send
547 .as_ref()
548 .context("ACPI shutdown requires direct ACPI, UEFI, or PCAT boot")?
549 .call(PowerButtonRpc::Press, ())
550 .await
551 .context("failed to inject ACPI power-button event")?;
552 tracing::info!("ACPI power-button event injected");
553 Ok(())
554 }
555
556 async fn wait_for_kvp(
557 &mut self,
558 ) -> anyhow::Result<mesh::Sender<hyperv_ic_resources::kvp::KvpRpc>> {
559 tracing::info!("Waiting for KVP IC");
560 let send = self
561 .resources
562 .kvp_ic_send
563 .as_ref()
564 .context("KVP IC not configured")?;
565 let (send, _) = send
566 .call_failable(hyperv_ic_resources::kvp::KvpConnectRpc::WaitForGuest, ())
567 .await
568 .context("failed to connect to KVP IC")?;
569
570 Ok(send)
571 }
572
573 async fn save_openhcl(
574 &self,
575 new_openhcl: &ResolvedArtifact,
576 flags: OpenHclServicingFlags,
577 ) -> anyhow::Result<()> {
578 let ged_send = self
579 .resources
580 .ged_send
581 .as_ref()
582 .context("openhcl not configured")?;
583
584 let igvm_file = fs_err::File::open(new_openhcl).context("failed to open igvm file")?;
585 self.worker
586 .save_openhcl(ged_send, flags, igvm_file.into())
587 .await
588 }
589
590 async fn update_command_line(&mut self, command_line: &str) -> anyhow::Result<()> {
591 self.worker.update_command_line(command_line).await
592 }
593
594 async fn add_pcie_device(
595 &mut self,
596 port_name: String,
597 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
598 ) -> anyhow::Result<()> {
599 self.worker.add_pcie_device(port_name, resource).await
600 }
601
602 async fn remove_pcie_device(&mut self, port_name: String) -> anyhow::Result<()> {
603 self.worker.remove_pcie_device(port_name).await
604 }
605
606 async fn eject_pcie_device(
607 &mut self,
608 port_name: String,
609 timeout: Duration,
610 ) -> anyhow::Result<()> {
611 self.worker.eject_pcie_device(port_name, timeout).await
612 }
613
614 async fn add_vpci_device(
615 &mut self,
616 instance_id: guid::Guid,
617 resource: vm_resource::Resource<vm_resource::kind::PciDeviceHandleKind>,
618 ) -> anyhow::Result<()> {
619 self.worker.add_vpci_device(instance_id, resource).await
620 }
621
622 async fn remove_vpci_device(&mut self, instance_id: guid::Guid) -> anyhow::Result<()> {
623 self.worker.remove_vpci_device(instance_id).await
624 }
625
626 async fn dump_state(&mut self, path: &Path) -> anyhow::Result<()> {
627 self.worker.dump_state(path).await
628 }
629 async fn restore_openhcl(&self) -> anyhow::Result<()> {
630 let ged_send = self
631 .resources
632 .ged_send
633 .as_ref()
634 .context("openhcl not configured")?;
635
636 self.worker.restore_openhcl(ged_send).await
637 }
638
639 async fn set_vtl2_settings(&self, settings: &Vtl2Settings) -> anyhow::Result<()> {
640 let ged_send = self
641 .resources
642 .ged_send
643 .as_ref()
644 .context("openhcl not configured")?;
645
646 ged_send
647 .call_failable(
648 get_resources::ged::GuestEmulationRequest::ModifyVtl2Settings,
649 prost::Message::encode_to_vec(settings),
650 )
651 .await?;
652
653 Ok(())
654 }
655
656 async fn wait_for_vtl0_start(
657 &mut self,
658 ) -> anyhow::Result<Result<(), get_resources::ged::Vtl0StartError>> {
659 self.resources
660 .ged_send
661 .as_ref()
662 .context("openhcl not configured")?
663 .call(
664 get_resources::ged::GuestEmulationRequest::WaitForVtl0Start,
665 (),
666 )
667 .await
668 .context("failed to receive OpenHCL VTL0 start report")
669 }
670
671 async fn reset(&mut self) -> anyhow::Result<()> {
672 tracing::info!("Resetting VM");
673 self.worker.reset().await?;
674 while self.resources.firmware_event_recv.try_recv().is_ok() {}
677 self.cidata_mounted = false;
679 if let Some(agent) = self.resources.linux_direct_serial_agent.as_mut() {
682 agent.reset();
683
684 if self.resources.properties.using_vtl0_pipette {
685 self.launch_linux_direct_pipette().await?;
686 }
687 }
688 Ok(())
689 }
690
691 async fn wait_for_agent(&mut self, set_high_vtl: bool) -> anyhow::Result<PipetteClient> {
692 #[cfg(target_os = "linux")]
693 if let Some(guest_cid) = self.resources.properties.vhost_vsock_guest_cid {
694 assert!(
695 !set_high_vtl,
696 "kernel vhost-vsock pipette transport does not support VTL2"
697 );
698 return self.wait_for_agent_vhost_vsock(guest_cid).await;
699 }
700
701 if let Some(port) = self.tcp_pipette_port {
703 assert!(!set_high_vtl, "TCP pipette transport does not support VTL2");
704 return self.wait_for_agent_tcp(port).await;
705 }
706
707 let listener = if set_high_vtl {
708 self.resources
709 .vtl2_pipette_listener
710 .as_mut()
711 .context("VM is not configured with VTL 2")?
712 } else {
713 &mut self.resources.pipette_listener
714 };
715
716 tracing::info!(set_high_vtl, "listening for pipette connection");
717 let client = loop {
718 let (conn, _) = listener
719 .accept()
720 .await
721 .context("failed to accept pipette connection")?;
722 tracing::info!(set_high_vtl, "handshaking with pipette");
723 let socket = PolledSocket::new(&self.resources.driver, conn)?;
724 match PipetteClient::new(&self.resources.driver, socket, &self.resources.output_dir)
725 .await
726 {
727 Ok(client) => break client,
728 Err(e) => {
729 tracing::warn!(
735 error = e.as_ref() as &dyn std::error::Error,
736 "pipette connection not live, retrying"
737 );
738 }
739 }
740 };
741 tracing::info!(set_high_vtl, "completed pipette handshake");
742
743 if !set_high_vtl
748 && self.resources.properties.uses_pipette_as_init
749 && self.resources.properties.has_agent_disk
750 && !self.cidata_mounted
751 {
752 tracing::info!("mounting CIDATA agent disk via pipette");
753 client
754 .unix_shell()
755 .cmd("mkdir")
756 .arg("-p")
757 .arg("/cidata")
758 .run()
759 .await
760 .context("failed to create /cidata mount point")?;
761 client
762 .unix_shell()
763 .cmd("mount")
764 .arg("LABEL=cidata")
765 .arg("/cidata")
766 .run()
767 .await
768 .context("failed to mount CIDATA disk")?;
769 self.cidata_mounted = true;
770 }
771
772 Ok(client)
773 }
774
775 #[cfg(target_os = "linux")]
777 async fn wait_for_agent_vhost_vsock(
778 &mut self,
779 guest_cid: u32,
780 ) -> anyhow::Result<PipetteClient> {
781 tracing::info!(
782 guest_cid,
783 port = PIPETTE_PORT,
784 "connecting to pipette via kernel vhost-vsock"
785 );
786 let socket = loop {
787 let connect = async {
788 let socket = VmSocket::new().context("failed to create AF_VSOCK socket")?;
789 socket
790 .set_connect_timeout(Duration::from_secs(5))
791 .context("failed to set AF_VSOCK connect timeout")?;
792 let mut socket = PolledSocket::new(&self.resources.driver, socket)
793 .context("failed to create polled AF_VSOCK socket")?
794 .convert();
795 socket
796 .connect(&VmAddress::vsock(guest_cid, PIPETTE_PORT).into())
797 .await
798 .context("failed to connect to guest AF_VSOCK listener")?;
799 Ok::<_, anyhow::Error>(socket)
800 };
801
802 match connect.await {
803 Ok(socket) => break socket,
804 Err(error) => {
805 tracing::trace!(
806 error = error.as_ref() as &dyn std::error::Error,
807 "AF_VSOCK connect failed, guest not ready yet"
808 );
809 }
810 }
811
812 pal_async::timer::PolledTimer::new(&self.resources.driver)
813 .sleep(Duration::from_secs(1))
814 .await;
815 };
816 tracing::info!("AF_VSOCK connected, handshaking with pipette");
817 let client = PipetteClient::new(&self.resources.driver, socket, &self.resources.output_dir)
818 .await
819 .context("pipette AF_VSOCK handshake failed")?;
820 tracing::info!("completed pipette AF_VSOCK handshake");
821 Ok(client)
822 }
823
824 async fn wait_for_agent_tcp(&mut self, port: u16) -> anyhow::Result<PipetteClient> {
830 tracing::info!(port, "connecting to pipette via TCP");
831 let addr = std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
832 let client = loop {
833 match PolledSocket::connect_tcp(&self.resources.driver, addr).await {
834 Ok(socket) => {
835 socket
836 .get()
837 .set_nodelay(true)
838 .context("failed to set TCP_NODELAY")?;
839 tracing::info!("TCP connected, handshaking with pipette");
840 match PipetteClient::new(
841 &self.resources.driver,
842 socket,
843 &self.resources.output_dir,
844 )
845 .await
846 {
847 Ok(client) => break client,
848 Err(e) => {
849 tracing::warn!(
850 error = e.as_ref() as &dyn std::error::Error,
851 "pipette TCP connection failed, retrying"
852 );
853 }
854 }
855 }
856 Err(e) => {
857 tracing::trace!(
858 error = &e as &dyn std::error::Error,
859 "TCP connect failed, guest not ready yet"
860 );
861 }
862 }
863 pal_async::timer::PolledTimer::new(&self.resources.driver)
865 .sleep(Duration::from_secs(1))
866 .await;
867 };
868 tracing::info!("completed pipette TCP handshake");
869 Ok(client)
870 }
871
872 async fn pause(&self) -> anyhow::Result<()> {
873 self.worker.pause().await?;
874 Ok(())
875 }
876
877 async fn save_state(&self) -> anyhow::Result<Vec<u8>> {
878 let state_msg = self.worker.save().await?;
879 Ok(mesh::payload::encode(state_msg))
880 }
881
882 async fn resume(&self) -> anyhow::Result<()> {
883 self.worker.resume().await?;
884 Ok(())
885 }
886
887 async fn verify_save_restore(&self) -> anyhow::Result<()> {
888 for i in 0..2 {
889 let result = self.worker.pulse_save_restore().await;
890 match result {
891 Ok(()) => {}
892 Err(RpcError::Channel(err)) => return Err(err.into()),
893 Err(RpcError::Call(PulseSaveRestoreError::ResetNotSupported)) => {
894 tracing::warn!("Reset not supported, could not test save + restore.");
895 break;
896 }
897 Err(RpcError::Call(PulseSaveRestoreError::Other(err))) => {
898 return Err(anyhow::Error::from(err))
899 .context(format!("Save + restore {i} failed."));
900 }
901 }
902 }
903
904 Ok(())
905 }
906
907 async fn launch_linux_direct_pipette(&mut self) -> anyhow::Result<()> {
908 self.resources
910 .linux_direct_serial_agent
911 .as_mut()
912 .unwrap()
913 .run_command("mkdir /cidata && mount LABEL=cidata /cidata && sh -c '/cidata/pipette &'")
914 .await?;
915 Ok(())
916 }
917}
918
919pub struct OpenVmmInspector {
921 worker: Arc<Worker>,
922}
923
924#[async_trait]
925impl PetriVmInspector for OpenVmmInspector {
926 async fn inspect(&self, path: &str) -> anyhow::Result<inspect::Node> {
927 Ok(self.worker.inspect(path).await)
928 }
929}
930
931pub struct OpenVmmFramebufferAccess {
933 view: View,
934}
935
936#[async_trait]
937impl PetriVmFramebufferAccess for OpenVmmFramebufferAccess {
938 async fn screenshot(
939 &mut self,
940 image: &mut Vec<u8>,
941 ) -> anyhow::Result<Option<VmScreenshotMeta>> {
942 const BYTES_PER_PIXEL: usize = 4;
947 let (width, height) = self.view.resolution();
948 let (widthsize, heightsize) = (width as usize, height as usize);
949 let len = widthsize * heightsize * BYTES_PER_PIXEL;
950
951 image.resize(len, 0);
952 for (i, line) in (0..height).zip(image.chunks_exact_mut(widthsize * BYTES_PER_PIXEL)) {
953 self.view.read_line(i, line);
954 for pixel in line.chunks_exact_mut(BYTES_PER_PIXEL) {
955 pixel.swap(0, 2);
956 pixel[3] = 0xFF;
957 }
958 }
959
960 Ok(Some(VmScreenshotMeta {
961 color: image::ExtendedColorType::Rgba8,
962 width,
963 height,
964 }))
965 }
966}