Skip to main content

xtask/tasks/guest_test/
download_image.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use crate::Xtask;
5use anyhow::Context;
6use clap::Parser;
7use petri_artifacts_vmm_test::ErasedVmmTestImage;
8use petri_artifacts_vmm_test::parse_vmm_test_image;
9use petri_artifacts_vmm_test::vmm_test_images;
10use std::path::PathBuf;
11use std::process::Command;
12
13/// Download an image from Azure Blob Storage.
14///
15/// If no specific images are specified this command will download all available images.
16#[derive(Parser)]
17pub struct DownloadImageTask {
18    /// The folder to download the images to.
19    #[clap(short, long, default_value = "images")]
20    output_folder: PathBuf,
21    /// The test artifacts to download.
22    #[clap(long, value_parser = parse_vmm_test_image)]
23    artifacts: Vec<ErasedVmmTestImage>,
24    /// Redownload images even if the file already exists.
25    #[clap(short, long)]
26    force: bool,
27}
28
29impl Xtask for DownloadImageTask {
30    fn run(mut self, _ctx: crate::XtaskCtx) -> anyhow::Result<()> {
31        if self.artifacts.is_empty() {
32            self.artifacts = vmm_test_images().to_vec();
33        }
34
35        let filenames = self
36            .artifacts
37            .into_iter()
38            .map(|x| x.filename())
39            .collect::<Vec<_>>();
40
41        if !self.output_folder.exists() {
42            std::fs::create_dir(&self.output_folder)?;
43        }
44
45        let vhd_list = filenames.join(";");
46        run_azcopy_command(&[
47            "copy",
48            &petri_artifacts_vmm_test::artifacts::blob_storage_url(),
49            self.output_folder.to_str().unwrap(),
50            "--include-path",
51            &vhd_list,
52            "--overwrite",
53            &self.force.to_string(),
54        ])?;
55
56        Ok(())
57    }
58}
59
60fn run_azcopy_command(args: &[&str]) -> anyhow::Result<Option<String>> {
61    let azcopy_cmd =
62        which::which("azcopy").context("Failed to find `azcopy`. Is AzCopy installed?")?;
63
64    let mut cmd = Command::new(azcopy_cmd);
65    cmd.args(args);
66
67    let mut child = cmd.spawn().context("Failed to run `azcopy` command.")?;
68    let exit = child
69        .wait()
70        .context("Failed to wait for 'azcopy' command.")?;
71    anyhow::ensure!(exit.success(), "azcopy command failed.");
72    Ok(None)
73}