microsoft/openvmm
Publicmirrored from https://github.com/microsoft/openvmmAvailable
hyperv/tools/hypestv/src/windows/hyperv.rs
64lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | //! Functions for interacting with Hyper-V VMs. |
| 5 | |
| 6 | use anyhow::Context as _; |
| 7 | |
| 8 | /// Runs hcsdiag with the given arguments. |
| 9 | pub fn run_hcsdiag( |
| 10 | f: impl FnOnce(&mut std::process::Command) -> &mut std::process::Command, |
| 11 | ) -> anyhow::Result<()> { |
| 12 | let mut cmd = std::process::Command::new("hcsdiag.exe"); |
| 13 | f(&mut cmd); |
| 14 | let status = cmd.status().context("failed to launch hcsdiag")?; |
| 15 | if !status.success() { |
| 16 | anyhow::bail!("hcsdiag failed with exit code: {}", status); |
| 17 | } |
| 18 | Ok(()) |
| 19 | } |
| 20 | |
| 21 | /// Runs hvc with the given arguments. |
| 22 | pub fn run_hvc( |
| 23 | f: impl FnOnce(&mut std::process::Command) -> &mut std::process::Command, |
| 24 | ) -> anyhow::Result<()> { |
| 25 | let mut cmd = std::process::Command::new("hvc.exe"); |
| 26 | f(&mut cmd); |
| 27 | let status = cmd.status().context("failed to launch hvc")?; |
| 28 | if !status.success() { |
| 29 | anyhow::bail!("hvc failed with exit code: {}", status); |
| 30 | } |
| 31 | Ok(()) |
| 32 | } |
| 33 | |
| 34 | /// Runs hvc with the given arguments and returns the output. |
| 35 | pub fn hvc_output( |
| 36 | f: impl FnOnce(&mut std::process::Command) -> &mut std::process::Command, |
| 37 | ) -> anyhow::Result<String> { |
| 38 | let mut cmd = std::process::Command::new("hvc.exe"); |
| 39 | f(&mut cmd); |
| 40 | let output = cmd.output().expect("failed to launch hvc"); |
| 41 | if !output.status.success() { |
| 42 | anyhow::bail!("hvc failed with exit code: {}", output.status); |
| 43 | } |
| 44 | String::from_utf8(output.stdout).context("output is not utf-8") |
| 45 | } |
| 46 | |
| 47 | pub fn powershell_script(script: &str, args: &[&str]) -> anyhow::Result<String> { |
| 48 | let mut cmd = std::process::Command::new("powershell.exe"); |
| 49 | cmd.arg("-NoProfile") |
| 50 | .arg("-Command") |
| 51 | .arg(format!("&{{{script}}}")) |
| 52 | .args( |
| 53 | args.iter() |
| 54 | .map(|arg| format!("\"{}\"", arg.replace('`', "``").replace('"', "`\""))), |
| 55 | ); |
| 56 | let output = cmd.output().expect("failed to launch powershell"); |
| 57 | if !output.status.success() { |
| 58 | anyhow::bail!( |
| 59 | "powershell failed:\n{}", |
| 60 | String::from_utf8_lossy(&output.stderr) |
| 61 | ); |
| 62 | } |
| 63 | String::from_utf8(output.stdout).context("output is not utf-8") |
| 64 | } |
| 65 | |