Skip to main content

flowey_hvlite/pipelines/
incubator.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Local standalone mshv provisioning, independent of VMM test discovery.
5
6use anyhow::Context as _;
7use flowey::node::prelude::ReadVar;
8use flowey::pipeline::prelude::*;
9use flowey_lib_hvlite::common::CommonProfile;
10use std::path::Path;
11use std::path::PathBuf;
12
13#[derive(clap::Args)]
14pub struct IncubatorCli {
15    /// Source Incubator profile (currently x64 OpenVMM with mshv boot only).
16    #[arg(long)]
17    profile: PathBuf,
18
19    /// Override the pinned mshv root bzImage, not the child VM's kernel.
20    #[arg(long)]
21    kernel: Option<PathBuf>,
22
23    /// Override the pinned shared x64 test initrd.
24    #[arg(long)]
25    initrd: Option<PathBuf>,
26
27    /// Override the pinned x64 MSVM.fd firmware.
28    #[arg(long)]
29    firmware: Option<PathBuf>,
30
31    /// Use authorized local payloads containing boot/ instead of pinned RPMs.
32    #[arg(long)]
33    boot_artifacts: Option<PathBuf>,
34
35    /// Writable host share (defaults to the OpenVMM checkout).
36    #[arg(long)]
37    share: Option<PathBuf>,
38
39    /// Provisioning/output directory beneath the share (default: target/incubator).
40    #[arg(long)]
41    dir: Option<PathBuf>,
42
43    /// Override Linux options, excluding the required initrd entry point.
44    #[arg(long)]
45    kernel_cmdline: Option<String>,
46
47    /// Override hypervisor options, excluding the loader DLL path.
48    #[arg(long)]
49    hypervisor_cmdline: Option<String>,
50
51    /// Prepare dependencies/profile and print a direct command without booting.
52    #[arg(long, conflicts_with = "incubator_args")]
53    prepare_only: bool,
54
55    /// Release VMM, agent, and EFI builds (Incubator otherwise uses light).
56    #[arg(long)]
57    release: bool,
58
59    /// Automatically install missing build dependencies.
60    #[arg(long)]
61    install_missing_deps: bool,
62
63    /// Enable verbose Flowey output.
64    #[arg(long)]
65    verbose: bool,
66
67    /// Incubator options and guest command, after `--`.
68    #[arg(last = true, required_unless_present = "prepare_only")]
69    incubator_args: Vec<String>,
70}
71
72impl IntoPipeline for IncubatorCli {
73    fn into_pipeline(self, backend_hint: PipelineBackendHint) -> anyhow::Result<Pipeline> {
74        let working_dir = std::env::current_dir().context("getting Incubator working directory")?;
75        let source_profile = read_source_profile(&self.profile)?;
76        anyhow::ensure!(
77            matches!(backend_hint, PipelineBackendHint::Local)
78                && matches!(FlowPlatform::host(backend_hint), FlowPlatform::Linux(_))
79                && matches!(FlowArch::host(backend_hint), FlowArch::X86_64),
80            "incubator provisioning currently requires a local x64 Linux host with KVM"
81        );
82        let kernel = self.kernel.as_deref().map(existing_file).transpose()?;
83        let initrd = self.initrd.as_deref().map(existing_file).transpose()?;
84        let firmware = self.firmware.as_deref().map(existing_file).transpose()?;
85        let boot_artifacts = self
86            .boot_artifacts
87            .map(|path| {
88                anyhow::ensure!(path.is_dir(), "not a payload directory: {}", path.display());
89                fs_canonicalize(&path)
90            })
91            .transpose()?;
92        let share = fs_canonicalize(&self.share.unwrap_or_else(crate::repo_root))?;
93        anyhow::ensure!(
94            share.is_dir(),
95            "share is not a directory: {}",
96            share.display()
97        );
98        let dir = self.dir.unwrap_or_else(|| share.join("target/incubator"));
99        std::fs::create_dir_all(&dir)?;
100        let dir = fs_canonicalize(&dir)?;
101        anyhow::ensure!(
102            dir.starts_with(&share),
103            "--dir must be beneath --share so the guest Pipette source is accessible"
104        );
105
106        let mut pipeline = Pipeline::new();
107        pipeline
108            .new_job(
109                FlowPlatform::host(backend_hint),
110                FlowArch::host(backend_hint),
111                "provision and run standalone mshv Incubator",
112            )
113            .dep_on(|_| flowey_lib_hvlite::_jobs::cfg_versions::Request::Init)
114            .dep_on(
115                |_| flowey_lib_hvlite::_jobs::cfg_hvlite_reposource::Params {
116                    hvlite_repo_source: flowey_lib_common::git_checkout::RepoSource::ExistingClone(
117                        ReadVar::from_static(crate::repo_root()),
118                    ),
119                },
120            )
121            .dep_on(|_| flowey_lib_hvlite::_jobs::cfg_common::Params {
122                local_only: Some(flowey_lib_hvlite::_jobs::cfg_common::LocalOnlyParams {
123                    interactive: true,
124                    auto_install: self.install_missing_deps,
125                    ignore_rust_version: true,
126                }),
127                verbose: ReadVar::from_static(self.verbose),
128                locked: false,
129                deny_warnings: false,
130                no_incremental: false,
131            })
132            .dep_on(
133                |ctx| flowey_lib_hvlite::_jobs::local_run_incubator::Params {
134                    profile: CommonProfile::from_release(self.release),
135                    source_profile,
136                    working_dir,
137                    kernel,
138                    initrd,
139                    firmware,
140                    boot_artifacts,
141                    share,
142                    dir,
143                    kernel_cmdline: self.kernel_cmdline,
144                    hypervisor_cmdline: self.hypervisor_cmdline,
145                    prepare_only: self.prepare_only,
146                    incubator_args: self.incubator_args,
147                    done: ctx.new_done_handle(),
148                },
149            )
150            .finish();
151        Ok(pipeline)
152    }
153}
154
155fn read_source_profile(path: &Path) -> anyhow::Result<String> {
156    let contents = std::fs::read_to_string(path)
157        .with_context(|| format!("reading Incubator profile {}", path.display()))?;
158    flowey_lib_hvlite::_jobs::local_run_incubator::parse_source_profile(&contents)
159        .with_context(|| format!("validating Incubator profile {}", path.display()))?;
160    Ok(contents)
161}
162
163#[expect(
164    clippy::disallowed_methods,
165    reason = "resolve symlinks before enforcing containment within the host share"
166)]
167fn fs_canonicalize(path: &Path) -> anyhow::Result<PathBuf> {
168    std::fs::canonicalize(path).with_context(|| format!("resolving {}", path.display()))
169}
170
171fn existing_file(path: &Path) -> anyhow::Result<PathBuf> {
172    anyhow::ensure!(path.is_file(), "not an input file: {}", path.display());
173    fs_canonicalize(path)
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use clap::Parser;
180    use test_with_tracing::test;
181
182    #[derive(Parser)]
183    struct Cli {
184        #[command(flatten)]
185        incubator: IncubatorCli,
186    }
187
188    #[test]
189    fn preparation_needs_neither_a_kernel_override_nor_a_command() -> anyhow::Result<()> {
190        let cli = Cli::try_parse_from(["incubator", "--profile", "source.toml", "--prepare-only"])?;
191        assert!(cli.incubator.prepare_only);
192        assert!(cli.incubator.kernel.is_none());
193        assert!(cli.incubator.incubator_args.is_empty());
194        Ok(())
195    }
196
197    #[test]
198    fn commands_preserve_shell_arguments_and_conflicting_modes_are_rejected() -> anyhow::Result<()>
199    {
200        let cli = Cli::try_parse_from([
201            "incubator",
202            "--profile",
203            "source.toml",
204            "--",
205            "--timeout",
206            "600",
207            "--guest-env",
208            "TEST=hello world",
209            "--no-pty",
210            "--",
211            "/bin/sh",
212            "-c",
213            "exit 17",
214        ])?;
215        assert_eq!(
216            cli.incubator.incubator_args,
217            [
218                "--timeout",
219                "600",
220                "--guest-env",
221                "TEST=hello world",
222                "--no-pty",
223                "--",
224                "/bin/sh",
225                "-c",
226                "exit 17"
227            ]
228        );
229        for args in [
230            vec!["incubator"],
231            vec!["incubator", "--prepare-only"],
232            vec!["incubator", "--profile", "source.toml", "--timeout", "600"],
233            vec![
234                "incubator",
235                "--profile",
236                "source.toml",
237                "--prepare-only",
238                "--",
239                "/bin/sh",
240            ],
241        ] {
242            assert!(Cli::try_parse_from(args).is_err());
243        }
244        Ok(())
245    }
246}