|
| 1 | +// SPDX-FileCopyrightText: Jakob Naucke <jnaucke@redhat.com> |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +use anyhow::{Context, Result, anyhow}; |
| 6 | +use k8s_openapi::chrono::{self, Utc}; |
| 7 | +use serde_json::Value; |
| 8 | +use std::{env, time}; |
| 9 | +use tokio::process::Command; |
| 10 | + |
| 11 | +use super::{VmBackend, VmConfig, generate_ignition, ssh_exec}; |
| 12 | +use crate::{Poller, ensure_command, warn_frame}; |
| 13 | + |
| 14 | +const KEEP_ALIVE_MINUTES: i64 = 60; |
| 15 | + |
| 16 | +pub struct AzureBackend { |
| 17 | + config: VmConfig, |
| 18 | + resource_group: String, |
| 19 | +} |
| 20 | + |
| 21 | +impl AzureBackend { |
| 22 | + pub fn new(config: VmConfig) -> Result<Self> { |
| 23 | + let resource_group = config.namespace.clone(); |
| 24 | + Ok(Self { |
| 25 | + config, |
| 26 | + resource_group, |
| 27 | + }) |
| 28 | + } |
| 29 | + |
| 30 | + async fn az(&self, args: &[&str]) -> Result<Value> { |
| 31 | + ensure_command("az")?; |
| 32 | + let out = ["--output", "json"]; |
| 33 | + let output = Command::new("az").args(args).args(out).output().await?; |
| 34 | + |
| 35 | + if !output.status.success() { |
| 36 | + let stderr = String::from_utf8_lossy(&output.stderr); |
| 37 | + return Err(anyhow!("az {} failed: {stderr}", args.join(" "))); |
| 38 | + } |
| 39 | + |
| 40 | + let stdout = String::from_utf8_lossy(&output.stdout); |
| 41 | + if stdout.trim().is_empty() { |
| 42 | + return Ok(Value::Null); |
| 43 | + } |
| 44 | + serde_json::from_str(&stdout).context("Failed to parse az CLI output as JSON") |
| 45 | + } |
| 46 | + |
| 47 | + async fn az_rg(&self, mut args: Vec<&str>) -> Result<()> { |
| 48 | + ensure_command("az")?; |
| 49 | + args.extend(["--resource-group", &self.resource_group, "--output", "none"]); |
| 50 | + let output = Command::new("az").args(&args).output().await?; |
| 51 | + |
| 52 | + if !output.status.success() { |
| 53 | + let stderr = String::from_utf8_lossy(&output.stderr); |
| 54 | + return Err(anyhow!("az {} failed: {stderr}", args.join(" "))); |
| 55 | + } |
| 56 | + Ok(()) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +#[async_trait::async_trait] |
| 61 | +impl VmBackend for AzureBackend { |
| 62 | + async fn create_vm(&self) -> Result<()> { |
| 63 | + let vm = &self.config.vm_name; |
| 64 | + let vnet = &format!("{vm}-vnet"); |
| 65 | + let ip = &format!("{vm}-ip"); |
| 66 | + let nsg = &format!("{vm}-nsg"); |
| 67 | + let nic = &format!("{vm}-nic"); |
| 68 | + |
| 69 | + let location = env::var("AZURE_LOCATION").unwrap_or("eastus".to_string()); |
| 70 | + let mut args = vec!["group", "create", "--name", &self.resource_group]; |
| 71 | + args.extend(["--location", &location]); |
| 72 | + let output = Command::new("az").args(args).output().await?; |
| 73 | + if !output.status.success() { |
| 74 | + let stderr = String::from_utf8_lossy(&output.stderr); |
| 75 | + return Err(anyhow!("az group create failed: {stderr}")); |
| 76 | + } |
| 77 | + |
| 78 | + let mut args = vec!["network", "vnet", "create", "--name", vnet]; |
| 79 | + args.extend(["--address-prefix", "10.0.0.0/16"]); |
| 80 | + args.extend(["--subnet-name", "default", "--subnet-prefix", "10.0.0.0/24"]); |
| 81 | + self.az_rg(args).await?; |
| 82 | + |
| 83 | + let mut args = vec!["network", "public-ip", "create", "--name", ip]; |
| 84 | + args.extend(["--sku", "Standard", "--allocation-method", "Static"]); |
| 85 | + self.az_rg(args).await?; |
| 86 | + |
| 87 | + self.az_rg(vec!["network", "nsg", "create", "--name", nsg]) |
| 88 | + .await?; |
| 89 | + |
| 90 | + let mut args = vec!["network", "nsg", "rule", "create", "--nsg-name", nsg]; |
| 91 | + args.extend(["--name", "AllowSSH", "--protocol", "Tcp"]); |
| 92 | + args.extend(["--priority", "1000", "--destination-port-range", "22"]); |
| 93 | + args.extend(["--access", "Allow", "--direction", "Inbound"]); |
| 94 | + self.az_rg(args).await?; |
| 95 | + |
| 96 | + let mut args = vec!["network", "nic", "create", "--name", nic]; |
| 97 | + args.extend(["--vnet-name", vnet, "--subnet", "default"]); |
| 98 | + args.extend(["--network-security-group", nsg, "--public-ip-address", ip]); |
| 99 | + self.az_rg(args).await?; |
| 100 | + |
| 101 | + let ign = generate_ignition(&self.config, false).await?; |
| 102 | + let custom_data = ign.to_string(); |
| 103 | + if !self.config.image.starts_with('/') && self.config.image.split(':').count() < 4 { |
| 104 | + let err = "Invalid Image URN. Expected 'Publisher:Offer:Sku:Version'"; |
| 105 | + return Err(anyhow!(err)); |
| 106 | + } |
| 107 | + |
| 108 | + let mut args = vec!["vm", "create", "--name", vm, "--nics", nic]; |
| 109 | + args.extend(["--image", &self.config.image, "--size", "Standard_DC2as_v5"]); |
| 110 | + args.extend(["--os-disk-delete-option", "Delete"]); |
| 111 | + args.extend(["--storage-sku", "StandardSSD_LRS"]); |
| 112 | + args.extend(["--admin-username", "core"]); |
| 113 | + args.extend(["--ssh-key-values", &self.config.ssh_public_key]); |
| 114 | + args.extend(["--custom-data", &custom_data]); |
| 115 | + args.extend(["--security-type", "ConfidentialVM"]); |
| 116 | + args.extend(["--enable-secure-boot", "true", "--enable-vtpm", "true"]); |
| 117 | + args.extend(["--os-disk-security-encryption-type", "VMGuestStateOnly"]); |
| 118 | + |
| 119 | + let err = format!( |
| 120 | + "Request to create the VM {vm} has failed, but it may still have been created. \ |
| 121 | + Log in manually to verify the VM does not keep running." |
| 122 | + ); |
| 123 | + self.az_rg(args).await.context(warn_frame(&err))?; |
| 124 | + |
| 125 | + // Schedule auto-shutdown to control costs if cleanup fails |
| 126 | + let shutdown_time = Utc::now() + chrono::Duration::minutes(KEEP_ALIVE_MINUTES); |
| 127 | + let shutdown_str = shutdown_time.format("%H%M").to_string(); |
| 128 | + let mut args = vec!["vm", "auto-shutdown", "--name", vm]; |
| 129 | + args.extend(["--time", &shutdown_str]); |
| 130 | + let err = format!( |
| 131 | + "Request to auto-shutdown the VM {vm} has failed. \ |
| 132 | + Log in manually to verify the VM was removed correctly." |
| 133 | + ); |
| 134 | + self.az_rg(args).await.context(warn_frame(&err))?; |
| 135 | + |
| 136 | + Ok(()) |
| 137 | + } |
| 138 | + |
| 139 | + async fn wait_for_running(&self, timeout_secs: u64) -> Result<()> { |
| 140 | + let vm_name = &self.config.vm_name; |
| 141 | + let poller = Poller::new() |
| 142 | + .with_timeout(time::Duration::from_secs(timeout_secs)) |
| 143 | + .with_interval(time::Duration::from_secs(5)) |
| 144 | + .with_error_message(format!( |
| 145 | + "virtualMachine {vm_name} did not reach PowerState/running after {timeout_secs}s", |
| 146 | + )); |
| 147 | + |
| 148 | + let args = [ |
| 149 | + "vm", |
| 150 | + "get-instance-view", |
| 151 | + "--resource-group", |
| 152 | + &self.resource_group, |
| 153 | + "--name", |
| 154 | + &self.config.vm_name, |
| 155 | + ]; |
| 156 | + let check_fn = || async move { |
| 157 | + let result = self.az(&args).await?; |
| 158 | + let statuses = result["instanceView"]["statuses"].as_array().unwrap(); |
| 159 | + let check = |s: &&Value| s["code"] == "PowerState/running"; |
| 160 | + let err = anyhow!("virtualMachine {vm_name} is not in running PowerState yet",); |
| 161 | + statuses.iter().find(check).map(|_| ()).ok_or(err) |
| 162 | + }; |
| 163 | + poller.poll_async(check_fn).await |
| 164 | + } |
| 165 | + |
| 166 | + async fn ssh_exec(&self, command: &str) -> Result<String> { |
| 167 | + let (rg, ip_name) = (&self.resource_group, format!("{}-ip", self.config.vm_name)); |
| 168 | + let mut args = vec!["network", "public-ip", "show", "--resource-group", rg]; |
| 169 | + args.extend(["--name", &ip_name]); |
| 170 | + let result = self.az(&args).await?; |
| 171 | + |
| 172 | + let public_ip = result["ipAddress"].as_str().unwrap(); |
| 173 | + ssh_exec(&format!( |
| 174 | + "ssh -i {} -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null core@{public_ip} '{command}'", |
| 175 | + self.config.ssh_private_key.display() |
| 176 | + )).await |
| 177 | + } |
| 178 | + |
| 179 | + async fn get_root_key(&self) -> Result<Option<Vec<u8>>> { |
| 180 | + Ok(None) |
| 181 | + } |
| 182 | + |
| 183 | + async fn cleanup(&self) -> Result<()> { |
| 184 | + self.config.cleanup(); |
| 185 | + let rg = &self.resource_group; |
| 186 | + |
| 187 | + let args1 = ["group", "delete", "--name", rg]; |
| 188 | + let args2 = ["--yes", "--no-wait"]; |
| 189 | + let output = Command::new("az").args(args1).args(args2).output().await?; |
| 190 | + |
| 191 | + if !output.status.success() { |
| 192 | + let stderr = String::from_utf8_lossy(&output.stderr); |
| 193 | + let err = format!( |
| 194 | + "Request to cleanup the Azure resource group {rg} failed. \ |
| 195 | + Log in manually to verify the resource group was removed correctly." |
| 196 | + ); |
| 197 | + return Err(anyhow!("az group delete failed: {stderr}").context(warn_frame(&err))); |
| 198 | + } |
| 199 | + Ok(()) |
| 200 | + } |
| 201 | +} |
0 commit comments