Skip to main content

petri/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! A Rust-based testing framework for VMMs.
5//!
6//! At this time - `petri` supports testing OpenVMM, OpenHCL,
7//! and Hyper-V based VMs.
8
9// TODO: Remove this dependency by adding a frontend worker that handles
10// hypervisor auto-detection in the spawned openvmm process instead of
11// requiring probes to be registered in the petri process.
12extern crate openvmm_hypervisors as _;
13
14pub mod disk_image;
15pub mod initrd;
16pub mod linux_bootstrap;
17mod linux_direct_serial_agent;
18pub mod mshv_boot;
19pub mod mshv_image;
20// TODO: Add docs and maybe a trait interface for this, or maybe this can
21// remain crate-local somehow without violating interface privacy.
22#[expect(missing_docs)]
23pub mod openhcl_diag;
24pub mod requirements;
25mod test;
26mod tracing;
27mod vm;
28mod worker;
29
30pub use petri_artifacts_core::ArtifactHandle;
31pub use petri_artifacts_core::ArtifactResolver;
32pub use petri_artifacts_core::ArtifactSource;
33pub use petri_artifacts_core::AsArtifactHandle;
34pub use petri_artifacts_core::ErasedArtifactHandle;
35pub use petri_artifacts_core::RemoteAccess;
36pub use petri_artifacts_core::ResolveTestArtifact;
37pub use petri_artifacts_core::ResolvedArtifact;
38pub use petri_artifacts_core::ResolvedArtifactSource;
39pub use petri_artifacts_core::ResolvedOptionalArtifact;
40pub use petri_artifacts_core::TestArtifactRequirements;
41pub use petri_artifacts_core::TestArtifacts;
42pub use pipette_client as pipette;
43pub use test::PetriTestParams;
44pub use test::RunTest;
45pub use test::SimpleTest;
46pub use test::TestCase;
47pub use test::test_macro_support;
48pub use test::test_main;
49pub use tracing::*;
50pub use vm::*;
51
52use jiff::Timestamp;
53use pal_async::process::PolledChild;
54use std::ops::Deref;
55use std::ops::DerefMut;
56use std::process::Command;
57use std::process::Stdio;
58use thiserror::Error;
59
60/// 1 kibibyte's worth of bytes.
61pub const SIZE_1_KB: u64 = 1024;
62/// 1 mebibyte's worth of bytes.
63pub const SIZE_1_MB: u64 = 1024 * SIZE_1_KB;
64/// 1 gibibyte's worth of bytes.
65pub const SIZE_1_GB: u64 = 1024 * SIZE_1_MB;
66
67/// The kind of shutdown to perform.
68#[expect(missing_docs)] // Self-describing names.
69pub enum ShutdownKind {
70    Shutdown,
71    Reboot,
72    Hibernate,
73}
74
75/// Error running command
76#[derive(Error, Debug)]
77pub enum CommandError {
78    /// failed to launch command
79    #[error("failed to launch command")]
80    Launch(#[from] std::io::Error),
81    /// command exited with non-zero status
82    #[error("command exited with non-zero status ({0}): {1}")]
83    Command(std::process::ExitStatus, String),
84}
85
86/// Run a command on the host and return the output
87pub async fn run_host_cmd(mut cmd: Command) -> Result<String, CommandError> {
88    cmd.stderr(Stdio::piped()).stdin(Stdio::null());
89
90    let cmd_debug = format!("{cmd:?}");
91    ::tracing::debug!(cmd = cmd_debug, "executing command");
92
93    let start = Timestamp::now();
94    let output = blocking::unblock(move || cmd.output()).await?;
95    let time_elapsed = Timestamp::now() - start;
96
97    let stdout_str = String::from_utf8_lossy(&output.stdout).to_string();
98    let stderr_str = String::from_utf8_lossy(&output.stderr).to_string();
99    ::tracing::debug!(
100        cmd = cmd_debug,
101        stdout_str,
102        stderr_str,
103        "command exited in {:.3}s with status {}",
104        time_elapsed.total(jiff::Unit::Second).unwrap(),
105        output.status
106    );
107
108    if !output.status.success() {
109        return Err(CommandError::Command(output.status, stderr_str));
110    }
111
112    Ok(stdout_str.trim().to_owned())
113}
114
115/// Owns a process launched by a test, killing it on drop.
116///
117/// [`std::process::Child`] deliberately does *not* kill the process when it is
118/// dropped. Without this guard, any test that fails or panics before reaching
119/// its `TeardownVM`/`Quit` calls leaves an orphaned process behind.
120pub struct TestChild(PolledChild<std::process::Child>);
121
122impl TestChild {
123    /// Create a new test child that will be killed on drop
124    pub fn new(child: PolledChild<std::process::Child>) -> Self {
125        Self(child)
126    }
127}
128
129impl Deref for TestChild {
130    type Target = PolledChild<std::process::Child>;
131
132    fn deref(&self) -> &Self::Target {
133        &self.0
134    }
135}
136
137impl DerefMut for TestChild {
138    fn deref_mut(&mut self) -> &mut Self::Target {
139        &mut self.0
140    }
141}
142
143impl Drop for TestChild {
144    fn drop(&mut self) {
145        let child = self.0.get_mut();
146        // `kill` reports success for an already-reaped child, so ask `try_wait`
147        // whether the process is actually gone rather than relying on that.
148        if let Ok(Some(_)) = child.try_wait() {
149            return;
150        }
151        ::tracing::warn!(
152            "killing test child process which was still running at the end of the test"
153        );
154        if let Err(err) = child.kill() {
155            ::tracing::warn!(
156                error = &err as &dyn std::error::Error,
157                "failed to kill test child process"
158            );
159            return;
160        }
161        // Reap the process so it doesn't linger as a zombie. It was just
162        // killed, so this returns promptly.
163        let _ = child.wait();
164    }
165}