1use std::path::PathBuf;
7
8use isothrum_runner::{ErrorReport, RunOptions, Runner, SecretValue, Secrets};
9
10use super::{Course, Failure, Step, TestVm};
11
12const MODULE: &str = include_str!("proxmox.tf");
14const MACHINE: &str = "selftest_vm";
16const IMAGE: &str = "_download_file.selftest_image";
18const NETWORK: &str = "_sdn_applier.selftest_net";
19const VM: &str = "_virtual_environment_vm.selftest_vm";
20const NO_ADDRESS: &str = "got no IPv4 address on bridge";
22const API_PORT: u16 = 8006;
24
25#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub enum SignIn {
29 Token(SecretValue),
31 Password {
34 user: String,
36 password: SecretValue,
38 },
39}
40
41#[derive(Debug, Clone)]
43#[non_exhaustive]
44pub struct Key {
45 pub private_file: PathBuf,
47 pub public: String,
49}
50
51impl Key {
52 #[must_use]
54 pub fn new(private_file: impl Into<PathBuf>, public: impl Into<String>) -> Key {
55 Key {
56 private_file: private_file.into(),
57 public: public.into(),
58 }
59 }
60}
61
62#[derive(Debug, Clone)]
64#[non_exhaustive]
65pub struct Proxmox {
66 pub endpoint: String,
68 pub insecure: bool,
70 pub sign_in: SignIn,
72 pub node: String,
74 pub bridge: String,
76 pub datastore: Option<String>,
78 pub image_datastore: Option<String>,
80 pub snippets_datastore: Option<String>,
82 pub node_ssh_user: Option<String>,
84 pub node_ssh_key_file: Option<PathBuf>,
86 pub node_address: Option<String>,
88 pub key: Option<Key>,
90 pub jump: Option<String>,
93 pub jump_known_hosts: Option<PathBuf>,
96}
97
98impl Proxmox {
99 #[must_use]
102 pub fn new(endpoint: impl Into<String>, sign_in: SignIn, node: impl Into<String>) -> Proxmox {
103 Proxmox {
104 endpoint: endpoint.into(),
105 insecure: false,
106 sign_in,
107 node: node.into(),
108 bridge: "vmbr0".to_owned(),
109 datastore: None,
110 image_datastore: None,
111 snippets_datastore: None,
112 node_ssh_user: None,
113 node_ssh_key_file: None,
114 node_address: None,
115 key: None,
116 jump: None,
117 jump_known_hosts: None,
118 }
119 }
120
121 pub(super) fn api_address(&self) -> String {
123 let rest = self.endpoint.split_once("://").map_or(self.endpoint.as_str(), |(_, r)| r);
124 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
125 let authority = authority.rsplit_once('@').map_or(authority, |(_, a)| a);
126 let has_port = match authority.rsplit_once(']') {
127 Some((_, after)) => after.starts_with(':'),
128 None => authority.contains(':'),
129 };
130 if has_port { authority.to_owned() } else { format!("{authority}:{API_PORT}") }
131 }
132
133 fn options(&self, vm: &TestVm<'_>, public: &str) -> RunOptions {
135 let (zone, vnet) = network_ids(vm.name);
136 let mut secrets = Secrets::new();
137 let mut opts = RunOptions::new()
138 .with_env("endpoint", self.endpoint.clone())
139 .with_env("insecure", self.insecure.to_string())
140 .with_env("node", self.node.clone())
141 .with_env("bridge", self.bridge.clone())
142 .with_env("name", vm.name)
143 .with_env("hostname", vm.hostname)
144 .with_env("zone", zone)
145 .with_env("vnet", vnet)
146 .with_env("ssh_public_key", public.trim());
147 match &self.sign_in {
148 SignIn::Token(token) => secrets.insert("api_token", token.clone()),
149 SignIn::Password { user, password } => {
150 opts = opts.with_env("username", user.clone());
151 secrets.insert("password", password.clone());
152 }
153 }
154 let optional = [
155 ("datastore", self.datastore.clone()),
156 ("image_datastore", self.image_datastore.clone()),
157 ("snippets_datastore", self.snippets_datastore.clone()),
158 ("node_ssh_user", self.node_ssh_user.clone()),
159 ("node_ssh_key_file", self.node_ssh_key_file.as_ref().map(|f| f.to_string_lossy().into_owned())),
160 ("node_address", self.node_address.clone()),
161 ("ssh_private_key_file", self.key.as_ref().map(|k| k.private_file.to_string_lossy().into_owned())),
163 ("ssh_jump", self.jump.clone()),
164 (
165 "ssh_jump_known_hosts_file",
166 self.jump_known_hosts.as_ref().map(|f| f.to_string_lossy().into_owned()),
167 ),
168 ];
169 for (name, value) in optional {
170 if let Some(value) = value.filter(|v| !v.is_empty()) {
171 opts = opts.with_env(name, value);
172 }
173 }
174 opts.with_secrets(secrets)
175 }
176}
177
178pub(super) fn project() -> (&'static str, String) {
180 ("main.tf", MODULE.to_owned())
181}
182
183pub(super) async fn prepared(p: &Proxmox, vm: &TestVm<'_>, runner: &Runner) -> Result<(RunOptions, Pve), String> {
186 let public = match &p.key {
187 Some(key) => key.public.clone(),
188 None => runner.ssh_public_key().await.map_err(|e| e.to_string())?,
189 };
190 Ok((p.options(vm, &public), Pve))
191}
192
193fn network_ids(name: &str) -> (String, String) {
196 let hash = name.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193)) & 0x00ff_ffff;
198 (format!("st{hash:06x}"), format!("sn{hash:06x}"))
199}
200
201pub(super) struct Pve;
204
205impl Course for Pve {
206 const UP: &'static [Step] = &[Step::Image, Step::Network, Step::Vm, Step::Address];
207
208 fn machine(&self) -> &'static str {
209 MACHINE
210 }
211
212 fn ends(&mut self, line: &str) -> Option<usize> {
213 let (address, _) = line.split_once(": Creation complete")?;
214 if address.ends_with(IMAGE) {
215 Some(0)
216 } else if address.ends_with(NETWORK) {
217 Some(1)
218 } else if address.ends_with(VM) {
219 Some(3)
220 } else {
221 None
222 }
223 }
224
225 fn explain(&self, report: &ErrorReport) -> Option<(usize, Failure)> {
226 let said = &report.message;
227 let boxed = || Box::new(report.clone());
228 if said.contains(NO_ADDRESS) {
229 Some((3, Failure::NoAddress(boxed())))
230 } else if said.contains("does not exist") && said.contains("bridge") {
231 Some((2, Failure::NoBridge(boxed())))
232 } else if said.contains(IMAGE) {
233 Some((0, Failure::ImageDownload(boxed())))
234 } else if said.contains("_sdn_") {
235 Some((1, Failure::Runner(boxed())))
236 } else {
237 None
238 }
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn token() -> SignIn {
247 SignIn::Token(SecretValue::new("root@pam!t=s3cret"))
248 }
249
250 #[test]
251 fn the_api_address_is_the_endpoints_host_and_port() {
252 for (endpoint, address) in [
253 ("https://pve.lan:8006/", "pve.lan:8006"),
254 ("https://10.0.0.5/", "10.0.0.5:8006"),
255 ("https://10.0.0.5", "10.0.0.5:8006"),
256 ("https://[fd00::5]:8443/api2/json", "[fd00::5]:8443"),
257 ("https://[fd00::5]/", "[fd00::5]:8006"),
258 ("pve.lan:9000", "pve.lan:9000"),
259 ] {
260 assert_eq!(Proxmox::new(endpoint, token(), "pve").api_address(), address, "{endpoint}");
261 }
262 }
263
264 #[test]
265 fn the_values_name_the_modules_variables_and_the_secret_is_never_a_value() {
266 let vm = TestVm::new("test-vm-1", "probe");
267 let mut p = Proxmox::new("https://pve:8006/", token(), "pve2");
268 p.bridge = "vmbr1".into();
269 p.image_datastore = Some("isos".into());
270 p.jump = Some("root@pve".into());
271 p.jump_known_hosts = Some("/app/nodes_known_hosts".into());
272 p.key = Some(Key::new("/keys/id_ed25519", "ssh-ed25519 AAAA me\n"));
273 let opts = p.options(&vm, "ssh-ed25519 AAAA me\n");
274 let value = |k: &str| opts.env.get(k).map(String::as_str);
275 assert_eq!(value("node"), Some("pve2"));
276 assert_eq!(value("bridge"), Some("vmbr1"));
277 assert_eq!(value("image_datastore"), Some("isos"));
278 assert_eq!(value("datastore"), None, "the module's default");
279 assert_eq!(value("ssh_public_key"), Some("ssh-ed25519 AAAA me"));
280 assert_eq!(value("ssh_private_key_file"), Some("/keys/id_ed25519"));
281 assert_eq!(value("ssh_jump"), Some("root@pve"));
282 assert_eq!(value("ssh_jump_known_hosts_file"), Some("/app/nodes_known_hosts"));
283 assert_eq!(opts.secrets.get("api_token").map(SecretValue::expose), Some("root@pam!t=s3cret"));
284 assert!(opts.env.values().all(|v| !v.contains("s3cret")));
285 for name in opts.env.keys().map(String::as_str).chain(opts.secrets.iter().map(|(k, _)| k)) {
287 let declared = MODULE.contains(&format!("variable \"{name}\""));
288 assert!(
289 declared || ["ssh_private_key_file", "ssh_jump", "ssh_jump_known_hosts_file"].contains(&name),
290 "{name} isn't a variable"
291 );
292 }
293 let password = Proxmox::new(
294 "https://pve:8006/",
295 SignIn::Password {
296 user: "root@pam".into(),
297 password: SecretValue::new("pw"),
298 },
299 "pve",
300 );
301 let signed_in = password.options(&vm, "k");
302 assert_eq!(signed_in.env.get("username").map(String::as_str), Some("root@pam"));
303 assert_eq!(signed_in.secrets.get("password").map(SecretValue::expose), Some("pw"));
304 }
305
306 #[test]
307 fn the_network_ids_are_short_stable_and_the_vms_own() {
308 let (zone, vnet) = network_ids("cyber-test-0123456789abcdef");
309 assert_eq!((zone.len(), vnet.len()), (8, 8));
310 assert!(zone.starts_with("st") && vnet.starts_with("sn") && zone.get(2..) == vnet.get(2..));
311 assert!(zone.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
312 assert_eq!(network_ids("cyber-test-0123456789abcdef"), (zone.clone(), vnet));
313 assert_ne!(network_ids("cyber-test-fedcba9876543210").0, zone);
314 }
315
316 #[test]
317 fn a_step_ends_on_its_resource_even_with_the_providers_name_masked() {
318 for prefix in ["proxmox", "***"] {
319 let mut pve = Pve;
320 assert_eq!(
321 pve.ends(&format!(
322 "{prefix}_download_file.selftest_image: Creation complete after 3s [id=local:iso/x.img]"
323 )),
324 Some(0)
325 );
326 assert_eq!(pve.ends(&format!("{prefix}_sdn_applier.selftest_net: Creation complete after 1s")), Some(1));
327 assert_eq!(
328 pve.ends(&format!("{prefix}_virtual_environment_vm.selftest_vm: Creation complete after 41s [id=101]")),
329 Some(3)
330 );
331 assert_eq!(
332 pve.ends(&format!("{prefix}_virtual_environment_vm.selftest_vm: Still creating... [10s elapsed]")),
333 None
334 );
335 assert_eq!(pve.ends(&format!("{prefix}_sdn_applier.selftest_finalizer: Creation complete after 1s")), None);
336 }
337 assert_eq!(Pve.machine(), MACHINE);
338 }
339
340 #[test]
341 fn the_failures_people_hit_belong_to_their_step() {
342 let failed = |message: &str| ErrorReport::new(isothrum_runner::ErrorCode::ToolFailed, message);
343 let explained = |message: &str| Pve.explain(&failed(message)).map(|(at, why)| (at, std::mem::discriminant(&why)));
344 let no_address = format!(
345 "step `up`: terraform failed: Resource postcondition failed (proxmox_virtual_environment_vm.selftest_vm): the VM {NO_ADDRESS} `vmbr1` within 8m"
346 );
347 let report = failed("x");
348 assert_eq!(
349 explained(&no_address),
350 Some((3, std::mem::discriminant(&Failure::NoAddress(Box::new(report.clone())))))
351 );
352 assert_eq!(
353 explained("error creating VM: bridge 'sn12ab34' does not exist"),
354 Some((2, std::mem::discriminant(&Failure::NoBridge(Box::new(report.clone())))))
355 );
356 assert_eq!(
357 explained("Error downloading (***_download_file.selftest_image): 404"),
358 Some((0, std::mem::discriminant(&Failure::ImageDownload(Box::new(report.clone())))))
359 );
360 assert_eq!(
361 explained("Error (proxmox_sdn_zone_simple.selftest_zone): zone exists").map(|(at, _)| at),
362 Some(1)
363 );
364 assert_eq!(explained("401 Unauthorized"), None);
365 }
366
367 #[test]
369 fn the_module_has_the_watched_resources_and_says_no_address_as_explained() {
370 for resource in [
371 "resource \"proxmox_download_file\" \"selftest_image\"",
372 "resource \"proxmox_sdn_applier\" \"selftest_net\"",
373 "resource \"proxmox_virtual_environment_vm\" \"selftest_vm\"",
374 "output \"ssh_user\"",
375 NO_ADDRESS,
376 ] {
377 assert!(MODULE.contains(resource), "{resource} missing from the module");
378 }
379 for end in [IMAGE, NETWORK, VM] {
380 let (kind, name) = end.trim_start_matches('_').split_once('.').unwrap();
381 assert!(MODULE.contains(&format!("\"proxmox_{kind}\" \"{name}\"")), "{end}");
382 }
383 assert!(MODULE.contains("depends_on = [proxmox_sdn_applier.selftest_finalizer, proxmox_download_file.selftest_image]"));
386 assert!(MODULE.contains("depends_on = [proxmox_sdn_applier.selftest_net]"));
387 }
388}