Skip to main content

flowey_hvlite/pipelines/
vmm_perf.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Build and run the standalone VMM.Perf harness locally.
5
6use anyhow::Context as _;
7use flowey::node::prelude::ReadVar;
8use flowey::pipeline::prelude::*;
9use flowey_lib_hvlite::common::CommonArch;
10use flowey_lib_hvlite::common::CommonPlatform;
11use flowey_lib_hvlite::common::CommonProfile;
12use flowey_lib_hvlite::common::CommonTriple;
13use std::collections::BTreeMap;
14use std::path::PathBuf;
15
16#[derive(clap::ValueEnum, Clone, Copy)]
17enum VmmPerfTargetCli {
18    LinuxX64Gnu,
19    LinuxX64Musl,
20    WindowsX64,
21}
22
23impl VmmPerfTargetCli {
24    fn triple(self) -> CommonTriple {
25        CommonTriple::Common {
26            arch: CommonArch::X86_64,
27            platform: match self {
28                Self::LinuxX64Gnu => CommonPlatform::LinuxGnu,
29                Self::LinuxX64Musl => CommonPlatform::LinuxMusl,
30                Self::WindowsX64 => CommonPlatform::WindowsMsvc,
31            },
32        }
33    }
34}
35
36/// Build and run VMM.Perf without the Petri/nextest test harness.
37#[derive(clap::Args)]
38pub struct VmmPerfCli {
39    /// Target for the OpenVMM and VMM.Perf runner binaries.
40    #[clap(long, value_enum)]
41    target: Option<VmmPerfTargetCli>,
42
43    /// Run only the selected profile variant. May be repeated.
44    #[clap(long, value_name = "PROFILE[:MODIFIER...]")]
45    profile: Vec<String>,
46
47    /// Root directory for benchmark scratch files and results.
48    #[clap(long)]
49    dir: Option<PathBuf>,
50
51    /// Replace the default VM matrix with one parameter set.
52    #[clap(long = "vmm-perf-vmsizes", value_name = "KEY=VALUE,...")]
53    vmm_perf_vm_sizes: Vec<String>,
54
55    /// Override a VMM.Perf parameter on every selected configuration.
56    #[clap(long, value_name = "KEY=VALUE")]
57    vmm_perf_parameter: Vec<String>,
58
59    /// Use a local VMM.Perf runtime archive instead of downloading the pinned version.
60    #[clap(long = "vmm-perf-runtime-archive", value_name = "PATH")]
61    vmm_perf_runtime_archive: Option<PathBuf>,
62
63    /// Release build instead of debug build.
64    #[clap(long)]
65    release: bool,
66
67    /// Build OpenVMM and the runner without executing benchmarks.
68    #[clap(long)]
69    build_only: bool,
70
71    /// Automatically install missing build dependencies.
72    #[clap(long)]
73    install_missing_deps: bool,
74
75    /// Use a local MSVM.fd instead of the configured mu_msvm release.
76    #[clap(long)]
77    custom_uefi_firmware: Option<PathBuf>,
78
79    /// Enable verbose Flowey output.
80    #[clap(long)]
81    verbose: bool,
82}
83
84impl IntoPipeline for VmmPerfCli {
85    fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline> {
86        if !matches!(backend_hint, PipelineBackendHint::Local) {
87            anyhow::bail!("vmm-perf is for local use only")
88        }
89
90        let Self {
91            target,
92            profile,
93            dir,
94            vmm_perf_vm_sizes,
95            vmm_perf_parameter,
96            vmm_perf_runtime_archive,
97            release,
98            build_only,
99            install_missing_deps,
100            custom_uefi_firmware,
101            verbose,
102        } = self;
103
104        let host_platform = FlowPlatform::host(backend_hint);
105        anyhow::ensure!(
106            matches!(FlowArch::host(backend_hint), FlowArch::X86_64),
107            "vmm-perf currently requires an x64 host"
108        );
109        let target = target.unwrap_or(match host_platform {
110            FlowPlatform::Linux(_) => VmmPerfTargetCli::LinuxX64Gnu,
111            FlowPlatform::Windows => VmmPerfTargetCli::WindowsX64,
112            platform => anyhow::bail!("vmm-perf does not support a {platform:?} host"),
113        });
114        anyhow::ensure!(
115            matches!(
116                (host_platform, target),
117                (
118                    FlowPlatform::Linux(_),
119                    VmmPerfTargetCli::LinuxX64Gnu | VmmPerfTargetCli::LinuxX64Musl
120                ) | (FlowPlatform::Windows, VmmPerfTargetCli::WindowsX64)
121            ),
122            "the selected VMM.Perf target does not match the host platform"
123        );
124
125        let vm_sizes_json = serialize_vm_sizes(&vmm_perf_vm_sizes)?;
126        let parameters_json = serialize_parameters(&vmm_perf_parameter)?;
127        let profiles = if profile.is_empty() {
128            flowey_lib_hvlite::run_vmm_perf::default_profiles()
129        } else {
130            profile
131        };
132        let root_dir = std::path::absolute(
133            dir.unwrap_or_else(|| crate::repo_root().join("target").join("vmm_perf")),
134        )
135        .context("failed to resolve VMM.Perf root directory")?;
136        std::fs::create_dir_all(&root_dir)?;
137        let runtime_archive = vmm_perf_runtime_archive
138            .map(|path| {
139                let path = std::path::absolute(path)
140                    .context("failed to resolve local VMM.Perf runtime archive")?;
141                anyhow::ensure!(
142                    path.is_file(),
143                    "local VMM.Perf runtime archive does not exist or is not a file: {}",
144                    path.display()
145                );
146                Ok(path)
147            })
148            .transpose()?;
149
150        let openvmm_repo = flowey_lib_common::git_checkout::RepoSource::ExistingClone(
151            ReadVar::from_static(crate::repo_root()),
152        );
153        let mut pipeline = Pipeline::new();
154        let mut job = pipeline
155            .new_job(
156                FlowPlatform::host(backend_hint),
157                FlowArch::host(backend_hint),
158                "build and run VMM.Perf",
159            )
160            .dep_on(|_| flowey_lib_hvlite::_jobs::cfg_versions::Request::Init);
161
162        if let Some(firmware) = custom_uefi_firmware {
163            job = job.dep_on(move |_| {
164                flowey_lib_hvlite::_jobs::cfg_versions::Request::LocalUefi(
165                    CommonArch::X86_64,
166                    ReadVar::from_static(firmware),
167                )
168            });
169        }
170
171        job.dep_on(
172            |_| flowey_lib_hvlite::_jobs::cfg_hvlite_reposource::Params {
173                hvlite_repo_source: openvmm_repo,
174            },
175        )
176        .dep_on(|_| flowey_lib_hvlite::_jobs::cfg_common::Params {
177            local_only: Some(flowey_lib_hvlite::_jobs::cfg_common::LocalOnlyParams {
178                interactive: true,
179                auto_install: install_missing_deps,
180                ignore_rust_version: true,
181            }),
182            verbose: ReadVar::from_static(verbose),
183            locked: false,
184            deny_warnings: false,
185            no_incremental: false,
186        })
187        .dep_on(
188            |ctx| flowey_lib_hvlite::_jobs::local_build_and_run_vmm_perf::Params {
189                target: target.triple(),
190                profile: CommonProfile::from_release(release),
191                root_dir,
192                profiles,
193                vm_sizes_json,
194                parameters_json,
195                runtime_archive,
196                build_only,
197                done: ctx.new_done_handle(),
198            },
199        )
200        .finish();
201
202        Ok(pipeline)
203    }
204}
205
206fn serialize_vm_sizes(vm_sizes: &[String]) -> anyhow::Result<Option<String>> {
207    if vm_sizes.is_empty() {
208        return Ok(None);
209    }
210
211    let mut parsed = Vec::with_capacity(vm_sizes.len());
212    for (index, vm_size) in vm_sizes.iter().enumerate() {
213        let parameters = parse_parameter_set(
214            vm_size.split(','),
215            &format!("--vmm-perf-vmsizes at position {}", index + 1),
216        )?;
217        parsed.push(serde_json::json!({ "parameters": parameters }));
218    }
219    Ok(Some(serde_json::to_string(&parsed)?))
220}
221
222fn serialize_parameters(parameters: &[String]) -> anyhow::Result<Option<String>> {
223    if parameters.is_empty() {
224        return Ok(None);
225    }
226    let parameters = parse_parameter_set(
227        parameters.iter().map(String::as_str),
228        "--vmm-perf-parameter",
229    )?;
230    Ok(Some(serde_json::to_string(&parameters)?))
231}
232
233fn parse_parameter_set<'a>(
234    values: impl IntoIterator<Item = &'a str>,
235    context: &str,
236) -> anyhow::Result<BTreeMap<String, String>> {
237    let mut parameters = BTreeMap::new();
238    for value in values {
239        let (name, value) = value
240            .split_once('=')
241            .ok_or_else(|| anyhow::anyhow!("{context} value {value:?} must use KEY=VALUE"))?;
242        let name = name.trim();
243        let value = value.trim();
244        anyhow::ensure!(
245            !name.is_empty(),
246            "{context} contains an empty parameter name"
247        );
248        anyhow::ensure!(
249            parameters
250                .insert(name.to_owned(), value.to_owned())
251                .is_none(),
252            "{context} contains duplicate parameter {name:?}"
253        );
254    }
255    anyhow::ensure!(!parameters.is_empty(), "{context} cannot be empty");
256    Ok(parameters)
257}