Skip to main content

flowey_lib_hvlite/
cleanup_leftover_hyperv_vms.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Remove Hyper-V VMs left behind by a previous test run.
5
6use flowey::node::prelude::*;
7
8flowey_request! {
9    pub struct Request {
10        /// Completion indicator
11        pub done: WriteVar<SideEffect>,
12    }
13}
14
15new_simple_flow_node!(struct Node);
16
17impl SimpleFlowNode for Node {
18    type Request = Request;
19
20    fn imports(_ctx: &mut ImportCtx<'_>) {}
21
22    fn process_request(request: Self::Request, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()> {
23        let Request { done } = request;
24
25        // Only meaningful on a dedicated CI machine: locally this would tear
26        // down VMs the developer cares about.
27        if matches!(ctx.backend(), FlowBackend::Local)
28            || !matches!(ctx.platform(), FlowPlatform::Windows)
29        {
30            ctx.emit_side_effect_step([], [done]);
31            return Ok(());
32        }
33
34        ctx.emit_rust_step("remove leftover Hyper-V VMs", |ctx| {
35            done.claim(ctx);
36            move |_rt| {
37                let vms = powershell_builder::PowerShellBuilder::new()
38                    .cmdlet("Get-VM")
39                    .finish()
40                    .build()
41                    .output()?;
42                log::info!(
43                    "removing any existing VMs: {}",
44                    String::from_utf8_lossy(&vms.stdout)
45                );
46
47                powershell_builder::PowerShellBuilder::new()
48                    .cmdlet("Get-VM")
49                    .pipeline()
50                    .cmdlet("Stop-VM")
51                    .flag("TurnOff")
52                    .finish()
53                    .build()
54                    .output()?;
55
56                powershell_builder::PowerShellBuilder::new()
57                    .cmdlet("Get-VM")
58                    .pipeline()
59                    .cmdlet("Remove-VM")
60                    .flag("Force")
61                    .finish()
62                    .build()
63                    .output()?;
64
65                // Remove-VM returns before the worker processes exit, and until
66                // they do they still hold the VMs' disks open.
67                powershell_builder::PowerShellBuilder::new()
68                    .cmdlet("Wait-Process")
69                    .arg("Name", "vmwp")
70                    .arg("Timeout", "60")
71                    .arg("ErrorAction", "SilentlyContinue")
72                    .finish()
73                    .build()
74                    .output()?;
75
76                Ok(())
77            }
78        });
79
80        Ok(())
81    }
82}