Skip to main content

flowey_hvlite/pipelines/
vmm_tests_run.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Pipeline to discover artifacts and run VMM tests in a single command.
5//!
6//! This pipeline:
7//! 1. Discovers required artifacts for the specified test filter (at pipeline
8//!    construction time)
9//! 2. Builds the necessary dependencies
10//! 3. Runs the tests
11
12use anyhow::Context as _;
13use flowey::node::prelude::ReadVar;
14use flowey::pipeline::prelude::*;
15use flowey_lib_hvlite::_jobs::local_build_and_run_nextest_vmm_tests::VmmTestSelections;
16use flowey_lib_hvlite::common::CommonArch;
17use flowey_lib_hvlite::common::CommonPlatform;
18use flowey_lib_hvlite::common::CommonTriple;
19use flowey_lib_hvlite::init_vmm_tests_content_dir::VmmTestsBuiltArtifactsSelections;
20use flowey_lib_hvlite::init_vmm_tests_content_dir::VmmTestsPreBuiltArtifactsSelections;
21use flowey_lib_hvlite::init_vmm_tests_env::PetriParams;
22use flowey_lib_hvlite::install_vmm_tests_external_deps::VmmTestsExternalDeps;
23use flowey_lib_hvlite::install_vmm_tests_external_deps::VmmTestsExternalDepsLinux;
24use flowey_lib_hvlite::install_vmm_tests_external_deps::VmmTestsExternalDepsWindows;
25use petri_artifacts_core::ArtifactId;
26use petri_artifacts_core::ArtifactListOutput;
27use petri_artifacts_core::ArtifactTarget;
28use petri_artifacts_core::artifact_from_id;
29use petri_artifacts_vmm_test::ErasedVmmTestImage;
30use petri_artifacts_vmm_test::vmm_test_image_from_id;
31use std::collections::BTreeMap;
32use std::collections::BTreeSet;
33use std::num::NonZeroU64;
34use std::path::Path;
35use std::path::PathBuf;
36use std::process::Command;
37use std::process::Stdio;
38
39/// Build and run VMM tests with automatic artifact discovery
40#[derive(clap::Args)]
41pub struct VmmTestsRunCli {
42    /// Specify what target to build the VMM tests for
43    ///
44    /// If not specified, defaults to the current host target.
45    #[clap(long)]
46    target: Option<VmmTestTargetCli>,
47
48    /// Directory for the output artifacts.
49    ///
50    /// If not specified, defaults to `target/vmm_tests`.
51    /// WSL-to-Windows runs must override this to a Windows-accessible output
52    /// directory (a DrvFs mount like `/mnt/c/...`) only when the selected tests
53    /// use disk images that require a Windows filesystem (Hyper-V disks, or
54    /// VHDX / dynamic VHD1 images); otherwise the default works.
55    #[clap(long)]
56    dir: Option<PathBuf>,
57
58    /// Test filter (nextest filter expression)
59    ///
60    /// Examples:
61    ///   - `test(alpine)` - run tests with "alpine" in the name
62    ///   - `test(/^boot_/)` - run tests starting with "boot_"
63    ///   - `all()` - run all tests
64    #[clap(long, default_value = "all()")]
65    filter: String,
66
67    /// pass `--verbose` to cargo
68    #[clap(long)]
69    verbose: bool,
70    /// Automatically install any missing required dependencies.
71    #[clap(long)]
72    install_missing_deps: bool,
73
74    /// Release build instead of debug build
75    #[clap(long)]
76    release: bool,
77
78    /// Build only, do not run
79    #[clap(long)]
80    build_only: bool,
81    /// Copy extras to output dir (symbols, etc)
82    #[clap(long)]
83    copy_extras: bool,
84
85    /// Skip the interactive VHD download prompt
86    #[clap(long)]
87    skip_vhd_prompt: bool,
88
89    /// Download all disk images upfront instead of streaming on demand.
90    ///
91    /// By default, VHD/ISO disk images are streamed on demand via HTTP
92    /// and cached locally, avoiding large upfront downloads. Use this
93    /// flag to force all images to be downloaded before tests run.
94    #[clap(long)]
95    no_lazy_fetch: bool,
96
97    /// Optional: custom kernel modules
98    #[clap(long)]
99    custom_kernel_modules: Option<PathBuf>,
100    /// Optional: custom kernel image
101    #[clap(long)]
102    custom_kernel: Option<PathBuf>,
103    /// Override the pinned mshv root bzImage, independent of the child's kernel.
104    #[clap(long)]
105    mshv_kernel: Option<PathBuf>,
106    /// Use extracted MSHV payloads instead of preparing them from RPMs.
107    #[clap(long)]
108    mshv_boot_artifacts: Option<PathBuf>,
109    /// Optional: custom UEFI firmware (MSVM.fd) to use instead of the
110    /// downloaded release. Path to a locally-built MSVM.fd file.
111    #[clap(long)]
112    custom_uefi_firmware: Option<PathBuf>,
113
114    /// use the nextest CI profile rather than the default one
115    #[clap(long)]
116    ci_profile: bool,
117
118    /// Don't reuse prepped vhds, even if they already exist.
119    /// Use when making changes to prep_steps
120    #[clap(long)]
121    no_reuse_prepped_vhds: bool,
122
123    /// Disable secure AVIC support for SNP. This adds the
124    /// `disable_secure_avic` cargo feature and sets `secure_avic` to
125    /// `disabled` in the IGVM manifest.
126    #[clap(long)]
127    disable_secure_avic: bool,
128
129    /// How many times to run the tests
130    #[clap(long)]
131    repetitions: Option<u64>,
132
133    /// Run emulated tests
134    #[clap(long)]
135    include_emulated: bool,
136}
137
138struct CargoNextestListRequest<'a> {
139    repo_root: &'a Path,
140    target: &'a str,
141    filter: &'a str,
142    release: bool,
143    include_ignored: bool,
144}
145
146struct RustSuite {
147    binary_path: PathBuf,
148    testcases: Vec<String>,
149}
150
151/// Result of resolving artifact requirements to build/download selections
152#[derive(Debug)]
153struct ResolvedArtifactSelections {
154    target: target_lexicon::Triple,
155
156    /// What to build
157    build: VmmTestsBuiltArtifactsSelections,
158    /// Prebuilt artifacts to download
159    prebuilt_artifacts: VmmTestsPreBuiltArtifactsSelections,
160    /// Prep steps variants
161    prep_steps_variants: BTreeSet<String>,
162    /// What to download
163    downloads: BTreeSet<ErasedVmmTestImage>,
164    /// Downloads that must happen even when lazy fetch is enabled (e.g.
165    /// VHDs needed by prep_steps, which copies them to create prepped images).
166    force_downloads: BTreeSet<ErasedVmmTestImage>,
167    /// Whether any of the tests require Hyper-V
168    needs_hyperv: bool,
169    /// Whether any of the tests require hardware isolation
170    needs_hardware_isolation: bool,
171
172    // Relative paths to artifacts used by the pipeline
173    flowey_hvlite_path: Option<PathBuf>,
174
175    // TODO: use one virtio-win artifact per arch so that it can be part of
176    // `VmmTestsPreBuiltArtifactsSelections`.
177    needs_virtio_win_drivers: bool,
178}
179
180impl ResolvedArtifactSelections {
181    fn new(target: target_lexicon::Triple, build_only: bool) -> anyhow::Result<Self> {
182        let mut build = VmmTestsBuiltArtifactsSelections::default();
183        build.require_nextest_vmm_tests_archive_for(ArtifactTarget::Triple(target.clone()))?;
184        let flowey_hvlite_path = build_only
185            .then(|| build.require_flowey_hvlite_for(ArtifactTarget::Triple(target.clone())))
186            .transpose()?;
187
188        Ok(Self {
189            target: target.clone(),
190
191            build,
192            prebuilt_artifacts: Default::default(),
193            prep_steps_variants: Default::default(),
194            downloads: Default::default(),
195            force_downloads: Default::default(),
196            needs_hyperv: Default::default(),
197            needs_hardware_isolation: Default::default(),
198
199            flowey_hvlite_path,
200
201            needs_virtio_win_drivers: Default::default(),
202        })
203    }
204}
205
206impl IntoPipeline for VmmTestsRunCli {
207    fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline> {
208        if !matches!(backend_hint, PipelineBackendHint::Local) {
209            anyhow::bail!("vmm-tests-run is for local use only")
210        }
211
212        let Self {
213            target,
214            dir,
215            filter,
216            verbose,
217            install_missing_deps,
218            release,
219            build_only,
220            copy_extras,
221            skip_vhd_prompt,
222            no_lazy_fetch,
223            custom_kernel_modules,
224            custom_kernel,
225            mshv_kernel,
226            mshv_boot_artifacts,
227            custom_uefi_firmware,
228            ci_profile,
229            no_reuse_prepped_vhds,
230            disable_secure_avic,
231            repetitions,
232            include_emulated,
233        } = self;
234
235        let repetitions =
236            NonZeroU64::new(repetitions.unwrap_or(1)).context("repetitions must not be zero")?;
237
238        let target = resolve_target(target, backend_hint)?;
239        let target_os = target.as_triple().operating_system;
240        let target_architecture = target.common_arch()?;
241        let target_str = target.as_triple().to_string();
242
243        // Windows *guest* payloads (e.g. pipette) must be PE binaries even when
244        // the VMM host target is Linux. On a non-WSL Linux build host the MSVC
245        // toolchain / Windows SDK is unavailable, so cross-compile those guest
246        // binaries with the GNU (mingw-w64) toolchain instead.
247        let windows_guest_platform =
248            if matches!(FlowPlatform::host(backend_hint), FlowPlatform::Linux(_))
249                && !flowey_cli::running_in_wsl()
250            {
251                CommonPlatform::WindowsGnu
252            } else {
253                CommonPlatform::WindowsMsvc
254            };
255
256        let repo_root = crate::repo_root();
257
258        let include_ignored = build_only;
259
260        // By default, filter out tests that run inside emulators with
261        // different architectures so that you don't need qemu installed
262        let filter = if !include_emulated {
263            // This is kind of a hack, but the macro should always include
264            // the architecture in this format at least once.
265            //
266            // Using target arch here rather than host arch (which is what
267            // matters for requiring qemu), since presumably you really wanted
268            // the native tests for a different architecture if you manually
269            // specified it.
270            match target_architecture {
271                CommonArch::X86_64 => format!("({filter}) & !test(_aarch64_)"),
272                CommonArch::Aarch64 => format!("({filter}) & !test(_x64_)"),
273            }
274        } else {
275            filter
276        };
277
278        // Run artifact discovery inline at pipeline construction time since
279        // flowey doesn't support conditional requests yet
280        log::info!(
281            "Discovering artifacts for filter: {} (target: {})",
282            filter,
283            target
284        );
285
286        // Determine which tests match the filter
287        let suites = run_cargo_nextest_list(CargoNextestListRequest {
288            repo_root: &repo_root,
289            target: &target_str,
290            filter: &filter,
291            release,
292            // When using build-only mode, we need to enumerate tests that could be
293            // run on any system so that we build all necessary dependencies. By default
294            // petri marks incompatible tests as ignored.
295            //
296            include_ignored,
297        })?;
298
299        if suites.is_empty() {
300            anyhow::bail!("No tests found for the given filter");
301        }
302
303        // Query for the required artifacts
304        let mut artifacts = Vec::new();
305        let mut nested = Vec::new();
306        for suite in suites.values() {
307            let mut output = query_test_binary_artifacts(suite)?;
308            nested.append(&mut output.nested);
309            artifacts.append(&mut output.into_artifacts_list());
310        }
311
312        // Query artifacts for nested tests
313        // Note that this requires qemu-user-static to be installed to run
314        // binaries for other architectures.
315        for (id, tests) in nested {
316            let nested_target_str = artifact_from_id(&id)
317                .with_context(|| format!("unknown artifact handle: {id}"))?
318                .target_triple()
319                .context("archive artifact should have associated target triple")?
320                .to_string();
321            log::info!(
322                "{} nested tests require artifacts for {}",
323                tests.len(),
324                nested_target_str
325            );
326            let nested_filter = tests
327                .into_iter()
328                .map(|t| format!("test(={t})"))
329                .collect::<Vec<_>>()
330                .join(" + ");
331
332            // Artifact discovery only needs to execute the test binary far enough
333            // to dump its static artifact metadata (`--list-required-artifacts`),
334            // which never boots a VM. So we run it directly rather than through the
335            // full emulator. The binary is built for the test target, so on a foreign
336            // host this relies on the binary being executable (natively, or via
337            // binfmt/user-mode emulation).
338            //
339            // Running outside the real guest means the per-test host capability
340            // checks (the source of nextest's `#[ignore]` flag) would wrongly drop
341            // emulated tests, so for the emulated path we enumerate ignored tests
342            // too — their artifacts still need to be built.
343            let nested_suites = run_cargo_nextest_list(CargoNextestListRequest {
344                repo_root: &repo_root,
345                target: &nested_target_str,
346                filter: &nested_filter,
347                release,
348                include_ignored: true,
349            })?;
350            for suite in nested_suites.values() {
351                let output = query_test_binary_artifacts(suite)?;
352                if !output.nested.is_empty() {
353                    anyhow::bail!("recursive nesting not supported");
354                }
355                artifacts.append(&mut output.into_artifacts_list());
356            }
357        }
358
359        // Resolve to build selections
360        let mut resolved = ResolvedArtifactSelections::new(target.as_triple(), build_only)?;
361        for artifact in artifacts {
362            resolved.resolve_artifact(&artifact)?;
363        }
364
365        // Determine whether we need hyper-v and/or hardware isolation
366        resolved.needs_hyperv = suites
367            .values()
368            .any(|s| s.testcases.iter().any(|name| name.contains("hyperv")));
369        resolved.needs_hardware_isolation = suites.values().any(|s| {
370            s.testcases
371                .iter()
372                .any(|name| name.contains("snp") || name.contains("tdx"))
373        });
374
375        // Determine lazy fetch mode.
376        //
377        // By default, VHD/ISO downloads are skipped and disk images are
378        // streamed on demand via HTTP (with local SQLite caching). This
379        // avoids multi-GB upfront downloads for dev-inner-loop scenarios.
380        //
381        // Lazy fetch is disabled for all downloads when the user passes
382        // --no-lazy-fetch and for any downloads that are used by a selected
383        // Hyper-V test.
384        //
385        // When both Hyper-V and non-Hyper-V tests are selected, only the
386        // artifacts required by Hyper-V tests are downloaded upfront; the
387        // rest are lazy-fetched.
388        if no_lazy_fetch {
389            log::info!("Lazy fetch disabled");
390        } else {
391            let mut hyperv_tests: usize = 0;
392            let mut hyperv_artifacts = Vec::new();
393            for suite in suites.values() {
394                let hyperv_testcases: Vec<_> = suite
395                    .testcases
396                    .iter()
397                    .filter(|name| name.contains("hyperv"))
398                    .cloned()
399                    .collect();
400
401                if !hyperv_testcases.is_empty() {
402                    hyperv_tests += hyperv_testcases.len();
403                    hyperv_artifacts.append(
404                        &mut query_test_binary_artifacts(&RustSuite {
405                            binary_path: suite.binary_path.clone(),
406                            testcases: hyperv_testcases,
407                        })?
408                        .into_artifacts_list(),
409                    );
410                }
411            }
412
413            resolved.downloads.retain(|a| !a.supports_blob_disk());
414
415            // Re-add force_downloads (prep_steps dependencies) that were removed.
416            resolved
417                .downloads
418                .extend(resolved.force_downloads.iter().cloned());
419
420            if hyperv_tests == 0 {
421                log::info!("Lazy fetch enabled: disk images will be streamed on demand via HTTP");
422            } else {
423                log::info!(
424                    "Downloading disk images required by {} Hyper-V tests",
425                    hyperv_tests
426                );
427            }
428
429            // Re-add only the downloads needed for hyper-v. Other selections should
430            // remain the same since resolve_artifact can only add selections
431            for artifact in hyperv_artifacts {
432                resolved.resolve_artifact(&artifact)?;
433            }
434        }
435
436        log::info!("Resolved selections: {:?}", resolved);
437
438        // Validate the output directory now that we know which disk images the
439        // selected tests need. When targeting Windows from WSL, the only hard
440        // filesystem constraint is that certain disk images must live on a
441        // Windows filesystem rather than a `\\wsl$` 9p path:
442        //
443        // - Hyper-V tests attach their VHDs to a real Hyper-V VM, whose worker
444        //   process can't open disks over 9p, so any Hyper-V disk needs a
445        //   Windows path regardless of format.
446        // - OpenVMM opens fixed VHD1, VMGS, and raw/ISO images as plain files
447        //   (fine over 9p), but routes VHDX (and dynamic/differencing VHD1)
448        //   disks through the Windows virtual-disk mount API, which requires a
449        //   real local volume. The only such artifact today is the `.vhdx`.
450        //
451        // All other cases (streamed disks, or fixed-VHD1 files even with
452        // `--no-lazy-fetch`) work fine from the default WSL-side directory.
453        let needs_windows_disk = !build_only
454            && (resolved.needs_hyperv
455                || resolved
456                    .downloads
457                    .iter()
458                    .any(|a| a.filename().ends_with(".vhdx")));
459        validate_output_dir(dir.as_deref(), target_os, needs_windows_disk)?;
460        let test_content_dir = dir.unwrap_or_else(|| repo_root.join("target").join("vmm_tests"));
461        std::fs::create_dir_all(&test_content_dir).context("failed to create output directory")?;
462
463        let openvmm_repo = flowey_lib_common::git_checkout::RepoSource::ExistingClone(
464            ReadVar::from_static(repo_root),
465        );
466
467        let mut pipeline = Pipeline::new();
468
469        let mut job = pipeline.new_job(
470            FlowPlatform::host(backend_hint),
471            FlowArch::host(backend_hint),
472            "build all dependencies and run vmm tests",
473        );
474
475        job = job.dep_on(|_| flowey_lib_hvlite::_jobs::cfg_versions::Request::Init);
476        if let Some(path) = mshv_boot_artifacts {
477            anyhow::ensure!(
478                path.is_dir(),
479                "MSHV boot artifacts is not a directory: {}",
480                path.display()
481            );
482            let path = std::path::absolute(path)?;
483            job = job.dep_on(move |_| {
484                flowey_lib_hvlite::_jobs::cfg_versions::Request::LocalMshvBootArtifacts(
485                    ReadVar::from_static(path),
486                )
487            });
488        }
489        if let Some(path) = mshv_kernel {
490            anyhow::ensure!(
491                path.is_file(),
492                "mshv root kernel is not a file: {}",
493                path.display()
494            );
495            let path = std::path::absolute(path)?;
496            job = job.dep_on(move |_| {
497                flowey_lib_hvlite::_jobs::cfg_versions::Request::LocalMshvKernel(
498                    ReadVar::from_static(path),
499                )
500            });
501        }
502
503        // Override kernel with local paths if both kernel and modules are specified
504        if let (Some(kernel_path), Some(modules_path)) =
505            (custom_kernel.clone(), custom_kernel_modules.clone())
506        {
507            job =
508                job.dep_on(
509                    move |_| flowey_lib_hvlite::_jobs::cfg_versions::Request::LocalKernel {
510                        arch: target_architecture,
511                        kernel: ReadVar::from_static(kernel_path),
512                        modules: ReadVar::from_static(modules_path),
513                    },
514                );
515        }
516
517        // Override UEFI firmware with a local MSVM.fd path
518        if let Some(fw_path) = custom_uefi_firmware {
519            job = job.dep_on(move |_| {
520                flowey_lib_hvlite::_jobs::cfg_versions::Request::LocalUefi(
521                    target_architecture,
522                    ReadVar::from_static(fw_path),
523                )
524            });
525        }
526
527        job = job
528            .dep_on(
529                |_| flowey_lib_hvlite::_jobs::cfg_hvlite_reposource::Params {
530                    hvlite_repo_source: openvmm_repo.clone(),
531                },
532            )
533            .dep_on(|_| flowey_lib_hvlite::_jobs::cfg_common::Params {
534                local_only: Some(flowey_lib_hvlite::_jobs::cfg_common::LocalOnlyParams {
535                    interactive: true,
536                    auto_install: install_missing_deps,
537                    ignore_rust_version: true,
538                }),
539                verbose: ReadVar::from_static(verbose),
540                locked: false,
541                deny_warnings: false,
542                no_incremental: false,
543            })
544            .dep_on(|ctx| {
545                flowey_lib_hvlite::_jobs::local_build_and_run_nextest_vmm_tests::Params {
546                    target,
547                    windows_guest_platform,
548                    test_content_dir,
549                    selections: selections_from_resolved(filter, resolved, target_os),
550                    release,
551                    build_only,
552                    copy_extras,
553                    custom_kernel_modules,
554                    custom_kernel,
555                    skip_vhd_prompt,
556                    nextest_profile: if ci_profile {
557                        flowey_lib_hvlite::run_cargo_nextest_run::NextestProfile::Ci
558                    } else {
559                        flowey_lib_hvlite::run_cargo_nextest_run::NextestProfile::Default
560                    },
561                    petri_params: PetriParams {
562                        disable_remote_artifacts: no_lazy_fetch,
563                        reuse_prepped_vhds: !no_reuse_prepped_vhds,
564                        require_2mb_hugetlb: false, // TODO
565                    },
566                    disable_secure_avic,
567                    repetitions,
568                    done: ctx.new_done_handle(),
569                }
570            });
571
572        job.finish();
573
574        Ok(pipeline)
575    }
576}
577
578/// Get test binaries and associated matching tests for a given nextest filter.
579// TODO: this function should really be a flowey node without automatic
580// dependency installation, but that would require conditional requests.
581fn run_cargo_nextest_list<'a>(
582    req: CargoNextestListRequest<'a>,
583) -> anyhow::Result<BTreeMap<String, RustSuite>> {
584    let CargoNextestListRequest {
585        repo_root,
586        target,
587        filter,
588        release,
589        include_ignored,
590    } = req;
591
592    let target_os = target
593        .parse::<target_lexicon::Triple>()
594        .context("invalid test discovery target")?
595        .operating_system;
596    anyhow::ensure!(
597        target_lexicon::Triple::host().operating_system != target_lexicon::OperatingSystem::Windows
598            || target_os == target_lexicon::OperatingSystem::Windows,
599        "vmm-tests-run cannot discover {target_os} tests on Windows; use a Linux/WSL host \
600         or exclude cross-OS nested tests with --filter"
601    );
602
603    // Check that cargo-nextest is available
604    let nextest_check = Command::new("cargo")
605        .args(["nextest", "--version"])
606        .stdout(Stdio::null())
607        .stderr(Stdio::null())
608        .status();
609    match nextest_check {
610        Ok(status) if status.success() => {}
611        _ => anyhow::bail!(
612            "cargo-nextest not found. Run 'cargo install --locked cargo-nextest' first."
613        ),
614    }
615
616    // Step 1: Use nextest to resolve the filter expression to test names and
617    // get the binary path
618    let mut cmd = Command::new("cargo");
619    cmd.stderr(Stdio::inherit());
620    cmd.current_dir(repo_root).args([
621        "nextest",
622        "list",
623        "-p",
624        "vmm_tests",
625        "--target",
626        target,
627        "--filter-expr",
628        filter,
629        "--message-format",
630        "json",
631    ]);
632    if release {
633        cmd.arg("--release");
634    }
635    if include_ignored {
636        cmd.args(["--run-ignored", "all"]);
637    }
638    let nextest_output = cmd.output().context("failed to run cargo nextest list")?;
639    anyhow::ensure!(nextest_output.status.success(), "cargo nextest list failed",);
640    let nextest_stdout = String::from_utf8(nextest_output.stdout)
641        .map_err(|e| anyhow::anyhow!("nextest output is not valid UTF-8: {}", e))?;
642
643    parse_nextest_output(&nextest_stdout)
644}
645
646/// Parse `cargo nextest list --message-format json` output to extract test
647/// names and binary path.
648fn parse_nextest_output(stdout: &str) -> anyhow::Result<BTreeMap<String, RustSuite>> {
649    let json: serde_json::Value = serde_json::from_str(stdout)
650        .map_err(|e| anyhow::anyhow!("failed to parse nextest JSON output: {}", e))?;
651
652    let mut suites = BTreeMap::new();
653
654    for (name, suite) in json
655        .get("rust-suites")
656        .and_then(|s| s.as_object())
657        .context("no rust-suites object")?
658    {
659        let binary_path = PathBuf::from(
660            suite
661                .get("binary-path")
662                .and_then(|v| v.as_str())
663                .context("no binary-path str")?,
664        );
665
666        let testcases: Vec<_> = suite
667            .get("testcases")
668            .and_then(|t| t.as_object())
669            .context("no testcases object")?
670            .iter()
671            .filter(|(_, test_info)| {
672                test_info
673                    .get("filter-match")
674                    .and_then(|fm| fm.get("status"))
675                    .and_then(|s| s.as_str())
676                    .is_some_and(|s| s == "matches")
677            })
678            .map(|(test_name, _)| test_name.to_owned())
679            .collect();
680
681        if !testcases.is_empty() {
682            suites.insert(
683                name.to_owned(),
684                RustSuite {
685                    binary_path,
686                    testcases,
687                },
688            );
689        }
690    }
691
692    Ok(suites)
693}
694
695/// Runs the test binary with `--list-required-artifacts --tests-from-stdin`
696/// and returns all the required and optional artifacts for all test defined
697/// in the RustSuite.
698fn query_test_binary_artifacts(suite: &RustSuite) -> anyhow::Result<ArtifactListOutput> {
699    log::info!("Using test binary: {}", suite.binary_path.display());
700    log::info!("Querying artifacts for {} tests", suite.testcases.len());
701
702    petri_artifacts_core::query_test_binary_artifacts(&suite.binary_path, &suite.testcases)
703}
704
705#[derive(clap::ValueEnum, Copy, Clone)]
706pub(crate) enum VmmTestTargetCli {
707    /// Windows Aarch64
708    WindowsAarch64,
709    /// Windows X64
710    WindowsX64,
711    /// Linux X64
712    LinuxX64,
713    /// Linux X64 with statically linked musl binaries
714    LinuxMuslX64,
715}
716
717/// Resolve a CLI target option to a CommonTriple, defaulting to the host.
718pub(crate) fn resolve_target(
719    target: Option<VmmTestTargetCli>,
720    backend_hint: PipelineBackendHint,
721) -> anyhow::Result<CommonTriple> {
722    let target = if let Some(t) = target {
723        t
724    } else {
725        match (
726            FlowArch::host(backend_hint),
727            FlowPlatform::host(backend_hint),
728        ) {
729            (FlowArch::Aarch64, FlowPlatform::Windows) => VmmTestTargetCli::WindowsAarch64,
730            (FlowArch::X86_64, FlowPlatform::Windows) => VmmTestTargetCli::WindowsX64,
731            (FlowArch::X86_64, FlowPlatform::Linux(_)) => VmmTestTargetCli::LinuxX64,
732            _ => anyhow::bail!("unsupported host"),
733        }
734    };
735
736    Ok(match target {
737        VmmTestTargetCli::WindowsAarch64 => CommonTriple::AARCH64_WINDOWS_MSVC,
738        VmmTestTargetCli::WindowsX64 => CommonTriple::X86_64_WINDOWS_MSVC,
739        VmmTestTargetCli::LinuxX64 => CommonTriple::X86_64_LINUX_GNU,
740        VmmTestTargetCli::LinuxMuslX64 => CommonTriple::X86_64_LINUX_MUSL,
741    })
742}
743
744/// Validate the output directory path based on the current platform.
745///
746/// When running under WSL and targeting Windows, some disk images must live on
747/// a Windows-accessible path (a DrvFs mount like `/mnt/c/...`) rather than a
748/// `\\wsl$` 9p path: Hyper-V disks (attached to a real Hyper-V VM) and VHDX /
749/// dynamic VHD1 images (opened via the Windows virtual-disk mount API). This
750/// constraint only applies when the selected tests actually use such a disk
751/// (`needs_windows_disk`); fixed-VHD1, VMGS, ISO, and streamed disks work fine
752/// from the WSL side. On native Windows or Linux this check is a no-op.
753fn validate_output_dir(
754    dir: Option<&Path>,
755    target_os: target_lexicon::OperatingSystem,
756    needs_windows_disk: bool,
757) -> anyhow::Result<()> {
758    if needs_windows_disk
759        && flowey_cli::running_in_wsl()
760        && matches!(target_os, target_lexicon::OperatingSystem::Windows)
761    {
762        if let Some(dir) = dir {
763            if !flowey_cli::is_wsl_windows_path(dir) {
764                anyhow::bail!(
765                    "When targeting Windows from WSL, --dir must be a path on Windows \
766                        (i.e., on a DrvFs mount like /mnt/c/vmm_tests) because the selected \
767                        tests use disk images that require a Windows filesystem (Hyper-V \
768                        disks, or VHDX / dynamic VHD1 images). \
769                        Got: {}",
770                    dir.display()
771                );
772            }
773        } else {
774            anyhow::bail!(
775                "The selected tests use disk images that require a Windows filesystem \
776                    (Hyper-V disks, or VHDX / dynamic VHD1 images) when targeting Windows \
777                    from WSL. Specify an output directory on a DrvFs mount with --dir \
778                    (e.g., --dir /mnt/c/vmm_tests)."
779            )
780        }
781    }
782    Ok(())
783}
784
785/// Resolve `ResolvedArtifactSelections` to `VmmTestSelections`.
786fn selections_from_resolved(
787    filter: String,
788    resolved: ResolvedArtifactSelections,
789    target_os: target_lexicon::OperatingSystem,
790) -> VmmTestSelections {
791    let ResolvedArtifactSelections {
792        target,
793        build,
794        prebuilt_artifacts,
795        prep_steps_variants,
796        downloads,
797        force_downloads: _,
798        needs_hyperv,
799        needs_hardware_isolation,
800        flowey_hvlite_path,
801        needs_virtio_win_drivers,
802    } = resolved;
803    let needs_whp = build
804        .openvmm_for(ArtifactTarget::Triple(target))
805        .expect("no native openvmm");
806
807    VmmTestSelections {
808        filter,
809        downloaded_artifacts: downloads.into_iter().collect(),
810        build,
811        prebuilt_artifacts,
812        prep_steps_variants: prep_steps_variants.into_iter().collect(),
813        external_deps: match target_os {
814            target_lexicon::OperatingSystem::Windows => {
815                VmmTestsExternalDeps::Windows(VmmTestsExternalDepsWindows {
816                    hyperv: needs_hyperv,
817                    whp: needs_whp,
818                    hardware_isolation: needs_hardware_isolation,
819                })
820            }
821            target_lexicon::OperatingSystem::Linux => {
822                VmmTestsExternalDeps::Linux(VmmTestsExternalDepsLinux {
823                    hugetlb_2mb_overcommit_pages: None, // TODO
824                    prepare_vhost_vsock: false,         // TODO
825                })
826            }
827            _ => unreachable!(),
828        },
829        flowey_hvlite_path,
830        needs_virtio_win_drivers,
831    }
832}
833
834impl ResolvedArtifactSelections {
835    /// Resolve a single artifact ID and update selections.
836    fn resolve_artifact(&mut self, id: &str) -> anyhow::Result<()> {
837        use petri_artifacts_common::artifacts::*;
838        use petri_artifacts_vmm_test::artifacts::*;
839
840        match id {
841            vmfw_dll::LATEST_CVM_X64::GLOBAL_UNIQUE_ID => {
842                self.build.vmfirmwareigvm_cvm_x64 = true;
843                self.build.openhcl_cvm_x64 = true;
844            }
845            _ if self.build.resolve_artifact(id) => {}
846            _ if self.prebuilt_artifacts.resolve_artifact(id) => {}
847            _ if let Some(image) = vmm_test_image_from_id(id) => {
848                self.downloads.insert(image);
849            }
850
851            loadable::PCAT_FIRMWARE_X64::GLOBAL_UNIQUE_ID
852            | loadable::SVGA_FIRMWARE_X64::GLOBAL_UNIQUE_ID => {
853                // We can't legally distribute these, so hope they are already
854                // on the host (which should always be the case for windows).
855            }
856
857            test_vhd::GEN2_WINDOWS_DATA_CENTER_CORE2025_X64_PREPPED::GLOBAL_UNIQUE_ID => {
858                self.build
859                    .require_openvmm_for(ArtifactTarget::Triple(self.target.clone()))?;
860                self.build
861                    .require_prep_steps_for(ArtifactTarget::Triple(self.target.clone()))?;
862                self.prep_steps_variants.insert("standard".into());
863                // prep_steps needs actual VHD files on disk to copy them.
864                // Force download even when lazy fetch is enabled.
865                self.force_downloads
866                    .insert(test_vhd::GEN2_WINDOWS_DATA_CENTER_CORE2022_X64.into());
867                self.force_downloads
868                    .insert(test_vhd::GEN2_WINDOWS_DATA_CENTER_CORE2025_X64.into());
869            }
870            test_vhd::GEN2_WINDOWS_DATA_CENTER_CORE2022_X64_NO_VMBUS_PREPPED::GLOBAL_UNIQUE_ID => {
871                self.build
872                    .require_openvmm_for(ArtifactTarget::Triple(self.target.clone()))?;
873                self.build
874                    .require_prep_steps_for(ArtifactTarget::Triple(self.target.clone()))?;
875                self.needs_virtio_win_drivers = true;
876                self.prep_steps_variants.insert("no-vmbus".into());
877                self.force_downloads
878                    .insert(test_vhd::GEN2_WINDOWS_DATA_CENTER_CORE2022_X64.into());
879            }
880
881            // OpenHCL usermode binaries (built as part of IGVM)
882            openhcl_igvm::um_bin::LATEST_LINUX_DIRECT_TEST_X64::GLOBAL_UNIQUE_ID
883            | openhcl_igvm::um_dbg::LATEST_LINUX_DIRECT_TEST_X64::GLOBAL_UNIQUE_ID => {
884                self.build.openhcl_linux_direct_x64 = true;
885            }
886
887            // Common artifacts (always available, no build needed)
888            TEST_LOG_DIRECTORY::GLOBAL_UNIQUE_ID => {}
889
890            // Virtio-win drivers (downloaded from openvmm-deps)
891            virtio_win::VIRTIO_WINDOWS_DRIVERS::GLOBAL_UNIQUE_ID => {
892                self.needs_virtio_win_drivers = true;
893            }
894
895            _ => anyhow::bail!("unknown artifact: {id}"),
896        };
897        Ok(())
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904    use petri_artifacts_vmm_test::artifacts::openhcl_igvm;
905    use petri_artifacts_vmm_test::artifacts::vmfw_dll;
906    use test_with_tracing::test;
907
908    #[test]
909    fn linux_targets_resolve() {
910        use clap::ValueEnum;
911
912        for (name, expected) in [
913            ("linux-x64", CommonTriple::X86_64_LINUX_GNU),
914            ("linux-musl-x64", CommonTriple::X86_64_LINUX_MUSL),
915        ] {
916            let target = VmmTestTargetCli::from_str(name, false).unwrap();
917            assert_eq!(
918                resolve_target(Some(target), PipelineBackendHint::Local).unwrap(),
919                expected
920            );
921        }
922    }
923
924    #[test]
925    fn linux_musl_bundle_selects_musl_artifacts() {
926        use petri_artifacts_common::artifacts::PIPETTE_LINUX_X64_MUSL;
927        use petri_artifacts_vmm_test::artifacts::*;
928
929        let target = CommonTriple::X86_64_LINUX_MUSL.as_triple();
930        let mut selections = ResolvedArtifactSelections::new(target.clone(), true).unwrap();
931        for id in [
932            OPENVMM_LINUX_X64_MUSL::GLOBAL_UNIQUE_ID,
933            PIPETTE_LINUX_X64_MUSL::GLOBAL_UNIQUE_ID,
934            snp_igvm::SNP_LINUX_DIRECT_IGVM_X64::GLOBAL_UNIQUE_ID,
935        ] {
936            selections.resolve_artifact(id).unwrap();
937        }
938
939        assert!(selections.build.nextest_vmm_tests_archive_linux_musl_x64);
940        assert!(selections.build.flowey_hvlite_linux_musl_x64);
941        assert!(selections.build.openvmm_linux_musl_x64);
942        assert!(selections.build.pipette_linux_musl_x64);
943        assert!(selections.build.snp_linux_direct_igvm_x64);
944        assert!(!selections.build.nextest_vmm_tests_archive_linux_x64);
945        assert!(!selections.build.flowey_hvlite_linux_x64);
946        assert!(!selections.build.openvmm_linux_x64);
947        assert_eq!(
948            selections.flowey_hvlite_path,
949            Some(host_tools::FLOWEY_HVLITE_LINUX_X64_MUSL::relative_path())
950        );
951        assert_eq!(
952            VmmTestsBuiltArtifactsSelections::default()
953                .require_nextest_vmm_tests_archive_for(ArtifactTarget::Triple(target))
954                .unwrap(),
955            host_tools::NEXTEST_VMM_TESTS_ARCHIVE_LINUX_X64_MUSL::relative_path()
956        );
957    }
958
959    #[test]
960    fn mshv_root_artifacts_do_not_replace_the_child_kernel() -> anyhow::Result<()> {
961        use petri_artifacts_vmm_test::artifacts::loadable;
962
963        for target in [
964            CommonTriple::X86_64_LINUX_GNU,
965            CommonTriple::X86_64_WINDOWS_MSVC,
966        ] {
967            let mut selections = ResolvedArtifactSelections::new(target.as_triple(), false)?;
968            for id in [
969                loadable::MSHV_HOST_BOOT_X64::GLOBAL_UNIQUE_ID,
970                loadable::MSHV_TEST_KERNEL_X64::GLOBAL_UNIQUE_ID,
971                loadable::MSHV_BOOT_ARTIFACTS_X64::GLOBAL_UNIQUE_ID,
972            ] {
973                selections.resolve_artifact(id)?;
974            }
975            assert!(selections.build.mshv_host_boot_x64);
976            assert!(selections.prebuilt_artifacts.mshv_test_kernel_x64);
977            assert!(selections.build.mshv_boot_artifacts_x64);
978            assert!(!selections.prebuilt_artifacts.test_linux_kernel_x64);
979
980            selections
981                .resolve_artifact(loadable::LINUX_DIRECT_TEST_KERNEL_X64::GLOBAL_UNIQUE_ID)?;
982            assert!(selections.prebuilt_artifacts.test_linux_kernel_x64);
983            assert!(selections.prebuilt_artifacts.mshv_test_kernel_x64);
984        }
985        Ok(())
986    }
987
988    #[test]
989    fn cvm_dll_selects_cvm_igvm_and_dll() {
990        let mut selections =
991            ResolvedArtifactSelections::new(CommonTriple::X86_64_WINDOWS_MSVC.as_triple(), false)
992                .unwrap();
993        selections
994            .resolve_artifact(vmfw_dll::LATEST_CVM_X64::GLOBAL_UNIQUE_ID)
995            .unwrap();
996
997        assert!(selections.build.vmfirmwareigvm_cvm_x64);
998        assert!(selections.build.openhcl_cvm_x64);
999    }
1000
1001    #[test]
1002    fn cvm_igvm_does_not_select_dll() {
1003        let mut selections =
1004            ResolvedArtifactSelections::new(CommonTriple::X86_64_WINDOWS_MSVC.as_triple(), false)
1005                .unwrap();
1006        selections
1007            .resolve_artifact(openhcl_igvm::LATEST_CVM_X64::GLOBAL_UNIQUE_ID)
1008            .unwrap();
1009
1010        assert!(selections.build.openhcl_cvm_x64);
1011        assert!(!selections.build.vmfirmwareigvm_cvm_x64);
1012    }
1013}