1use std::collections::BTreeMap;
8
9use crate::status::MachineState;
10
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub(crate) struct Reading {
14 pub(crate) states: BTreeMap<String, String>,
16}
17
18pub(crate) fn parse(out: &str) -> Reading {
20 let mut read = Reading::default();
21 for (target, kind, data) in out.lines().filter_map(fields) {
22 if kind == "state" && !target.is_empty() {
23 read.states.insert(target.to_owned(), data.to_owned());
24 }
25 }
26 read
27}
28
29pub(crate) fn host_name(out: &str) -> Option<String> {
32 out.lines()
33 .filter_map(|line| line.trim().strip_prefix("HostName"))
34 .map(str::trim)
35 .find(|host| !host.is_empty())
36 .map(str::to_owned)
37}
38
39pub(crate) fn machine_state(label: &str) -> MachineState {
48 match label {
49 "running" | "started" | "powered_on" => MachineState::Running,
50 "not_created" => MachineState::Absent,
51 "poweroff" | "powered_off" | "off" | "shutoff" | "stopped" | "not_running" | "saved" | "suspended" | "paused" | "pmsuspended" | "aborted-saved" => {
52 MachineState::Stopped
53 }
54 other => MachineState::Unknown(other.to_owned()),
55 }
56}
57
58#[must_use]
62pub fn plugins(out: &str) -> Vec<(String, Option<String>)> {
63 let lines: Vec<(&str, &str, &str)> = out.lines().filter_map(fields).collect();
64 let version = |name: &str| {
65 lines
66 .iter()
67 .find(|(target, kind, _)| *target == name && *kind == "plugin-version")
68 .and_then(|(_, _, data)| {
69 let v = data.split("%!(VAGRANT_COMMA)").next().unwrap_or_default().trim();
70 (!v.is_empty()).then(|| v.to_owned())
71 })
72 };
73 lines
74 .iter()
75 .filter(|(_, kind, data)| *kind == "plugin-name" && !data.is_empty())
76 .map(|(_, _, name)| ((*name).to_owned(), version(name)))
77 .collect()
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
82pub(crate) struct InstalledBox {
83 pub(crate) name: String,
85 pub(crate) provider: String,
87 pub(crate) version: String,
89 pub(crate) architecture: Option<String>,
91}
92
93pub(crate) fn boxes(out: &str) -> Vec<InstalledBox> {
97 type Reading = (String, Option<String>, Option<String>, Option<String>);
99 fn done(reading: Option<Reading>, into: &mut Vec<InstalledBox>) {
100 if let Some((name, Some(provider), Some(version), architecture)) = reading {
101 into.push(InstalledBox {
102 name,
103 provider,
104 version,
105 architecture: architecture.filter(|a| a != "n/a"),
106 });
107 }
108 }
109 let mut listed = Vec::new();
110 let mut reading: Option<Reading> = None;
111 for (_, kind, data) in out.lines().filter_map(fields) {
112 let data = unescape(data).trim().to_owned();
113 match (kind, reading.as_mut()) {
114 ("box-name", _) => {
115 done(reading.take(), &mut listed);
116 reading = Some((data, None, None, None));
117 }
118 ("box-provider", Some(r)) => r.1 = Some(data),
119 ("box-version", Some(r)) => r.2 = Some(data),
120 ("box-architecture", Some(r)) => r.3 = Some(data),
121 _ => {}
122 }
123 }
124 done(reading, &mut listed);
125 listed
126}
127
128pub(crate) fn error(stdout: &[String]) -> Option<String> {
134 let data = stdout
135 .iter()
136 .rev()
137 .filter_map(|line| fields(line))
138 .find_map(|(_, kind, data)| (kind == "error-exit").then_some(data))?;
139 let (class, message) = data.split_once(',').unwrap_or((data, ""));
140 let (class, message) = (unescape(class), unescape(message));
141 match (class.trim(), message.trim()) {
142 ("", "") => None,
143 (class, "") => Some(class.to_owned()),
144 ("", message) => Some(message.to_owned()),
145 (class, message) => Some(format!("{message} ({class})")),
146 }
147}
148
149const VAGRANT_LOCKED: [&str; 4] = [
153 "Vagrant::Errors::MachineActionLockedError",
154 "another process is already executing an action on the machine",
155 "Vagrant::Errors::MachineLocked,",
156 "Vagrant can't use the requested machine because it is locked!",
157];
158
159const ESXI_ALREADY_OFF: [&str; 2] = ["existingState = \"poweredOff\"", "in the current state (Powered off)"];
162
163fn said_any<'a>(lines: impl IntoIterator<Item = &'a String>, wordings: &[&str]) -> bool {
165 lines.into_iter().any(|line| wordings.iter().any(|said| line.contains(said)))
166}
167
168fn unescape(field: &str) -> String {
171 field.replace("%!(VAGRANT_COMMA)", ",").replace("\\r", "").replace("\\n", "\n")
172}
173
174pub(crate) fn fields(line: &str) -> Option<(&str, &str, &str)> {
178 let mut parts = line.trim_end_matches('\r').splitn(4, ',');
179 let (_ts, target, kind, data) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
180 Some((target, kind, data))
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub(crate) enum Failure {
186 Locked,
189 AlreadyOff,
191 Other,
193}
194
195impl Failure {
196 pub(crate) fn of<'a>(lines: impl IntoIterator<Item = &'a String> + Clone) -> Failure {
198 if said_any(lines.clone(), &VAGRANT_LOCKED) {
199 Failure::Locked
200 } else if said_any(lines, &ESXI_ALREADY_OFF) {
201 Failure::AlreadyOff
202 } else {
203 Failure::Other
204 }
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn a_held_lock_is_read_in_each_of_vagrant_s_wordings() {
214 let action = lines(
216 "1794307174,,error-exit,Vagrant::Errors::MachineActionLockedError,An action 'read_state' was attempted on the machine 'web'%!(VAGRANT_COMMA)\\nbut another process is already executing an action on the machine.",
217 );
218 let human = lines(
219 "An action 'read_state' was attempted on the machine 'web',\nbut another process is already executing an action on the machine.\nVagrant locks each machine for access by only one process at a time.",
220 );
221 let index = lines("1794342958,,error-exit,Vagrant::Errors::MachineLocked,Vagrant can't use the requested machine because it is locked! This");
222 for (wording, said) in [("action", &action), ("human", &human), ("index", &index)] {
223 assert_eq!(Failure::of(said.iter()), Failure::Locked, "{wording}");
224 }
225 assert_eq!(
226 Failure::of(&lines("VBoxManage: error: Cannot unregister the machine 'web-vm - web' while it is locked")),
227 Failure::Other
228 );
229 assert_eq!(Failure::of(&Vec::new()), Failure::Other);
230 }
231
232 #[test]
233 fn esxi_refusing_to_halt_a_vm_already_off_is_read() {
234 let off = lines(
236 "There was an error talking to ESXi.\n Unable to shutdown the VM:\n (vim.fault.InvalidPowerState) {\n existingState = \"poweredOff\"\n msg = \"shutdownGuest\nThe attempted operation cannot be performed in the current state (Powered off).\"\n}",
237 );
238 assert_eq!(Failure::of(&off), Failure::AlreadyOff);
239 assert_eq!(
240 Failure::of(&lines("There was an error talking to ESXi.\n Unable to shutdown the VM: timed out")),
241 Failure::Other
242 );
243 }
244
245 #[test]
246 fn boxes_are_read_one_per_architecture_and_one_of_no_architecture_has_none() {
247 let listed = boxes(include_str!("fixtures/vagrant/2.4.9-box-list.txt"));
248 let held = |provider: &str, arch: &str| InstalledBox {
249 name: "bento/debian-12".into(),
250 provider: provider.into(),
251 version: "202510.26.0".into(),
252 architecture: Some(arch.into()),
253 };
254 assert_eq!(
255 listed,
256 [held("virtualbox", "arm64"), held("vmware_desktop", "amd64"), held("vmware_desktop", "arm64")]
257 );
258 let out = "1,,box-name,generic/alpine319\n1,,box-provider,libvirt\n1,,box-version,4.3.12\n\
260 1,,box-architecture,n/a\n1,,box-info,Author,Ladar Levison\n1,,box-name,cut\n1,,box-provider,qemu\n";
261 assert_eq!(
262 boxes(out),
263 [InstalledBox {
264 name: "generic/alpine319".into(),
265 provider: "libvirt".into(),
266 version: "4.3.12".into(),
267 architecture: None,
268 }]
269 );
270 assert_eq!(boxes(""), []);
271 }
272
273 #[test]
274 fn plugins_are_read_by_name_with_their_versions() {
275 let out = "1794305819,,ui,info,vagrant-qemu (0.7.0%!(VAGRANT_COMMA) global)\n\
277 1794305819,,plugin-name,vagrant-qemu\n\
278 1794305819,vagrant-qemu,plugin-version,0.7.0%!(VAGRANT_COMMA) global\n\
279 1794305819,,plugin-name,vagrant-vmware-esxi\r\n\
280 1794305819,,plugin-name,vagrant_utm\n\
281 1794305819,vagrant_utm,plugin-version,0.2.0\n";
282 assert_eq!(
283 plugins(out),
284 [
285 ("vagrant-qemu".to_owned(), Some("0.7.0".to_owned())),
286 ("vagrant-vmware-esxi".to_owned(), None),
287 ("vagrant_utm".to_owned(), Some("0.2.0".to_owned())),
288 ]
289 );
290 assert_eq!(plugins(""), Vec::<(String, Option<String>)>::new());
291 }
292
293 fn lines(text: &str) -> Vec<String> {
294 text.lines().map(str::to_owned).collect()
295 }
296
297 #[test]
298 fn a_machine_readable_error_is_read_whole_with_its_class() {
299 let said = "Vagrant can't use the requested machine because it is locked! This\\nmeans that another Vagrant \
301 process is currently reading or modifying\\nthe machine.\\n\\nName: probe\\nProvider: libvirt";
302 let out = lines(&format!(
303 "1794342958,,ui,error,{said}\n1794342958,,error-exit,Vagrant::Errors::MachineLocked,{said}\n"
304 ));
305 assert_eq!(
306 error(&out).as_deref(),
307 Some(
308 "Vagrant can't use the requested machine because it is locked! This\nmeans that another Vagrant \
309 process is currently reading or modifying\nthe machine.\n\nName: probe\nProvider: libvirt \
310 (Vagrant::Errors::MachineLocked)"
311 )
312 );
313 let commas = lines("1,,error-exit,Vagrant::Errors::VagrantError,a%!(VAGRANT_COMMA) b\\r\\n");
314 assert_eq!(error(&commas).as_deref(), Some("a, b (Vagrant::Errors::VagrantError)"));
315 assert_eq!(error(&lines("1,,error-exit,Vagrant::Errors::X,")).as_deref(), Some("Vagrant::Errors::X"));
316 assert_eq!(error(&lines("1,web,state,running\n==> web: up")), None);
317 assert_eq!(error(&lines("1,,error-exit,")), None);
318 }
319
320 #[test]
321 fn ssh_configs_host_name_is_the_vms_address() {
322 let out = "Host web\r\n HostName 172.16.1.53\r\n User vagrant\r\n Port 22\r\n";
323 assert_eq!(host_name(out).as_deref(), Some("172.16.1.53"));
324 assert_eq!(host_name("Host web\n HostName \n User vagrant\n"), None);
325 assert_eq!(host_name(""), None);
326 }
327
328 #[test]
329 fn windows_line_endings_and_blank_lines_are_read_the_same() {
330 let out = "1,dc01,provider-name,hyperv\r\n\r\n1,dc01,state,running\r\n1,gateway,state,off\r\n";
331 let r = parse(out);
332 assert_eq!(r.states["dc01"], "running", "no carriage return in the state");
333 assert_eq!(machine_state(&r.states["gateway"]), MachineState::Stopped);
334 }
335
336 #[test]
337 fn a_state_with_vagrants_comma_escape_is_kept_whole_and_is_not_running() {
338 let r = parse("1,a,state,running%!(VAGRANT_COMMA) with a note\n");
339 assert_eq!(r.states["a"], "running%!(VAGRANT_COMMA) with a note");
340 assert!(matches!(machine_state(&r.states["a"]), MachineState::Unknown(_)));
341 }
342
343 #[test]
344 fn non_state_lines_and_malformed_output_give_no_machine() {
345 let out = "ts,,ui,info,Current machine states:\nts,box,metadata,provider,virtualbox\nts,,state,running\nshort,line\n";
346 assert!(parse(out).states.is_empty());
347 assert!(parse("").states.is_empty());
348 }
349
350 #[test]
351 fn every_providers_labels_map_to_a_state() {
352 assert_eq!(machine_state("running"), MachineState::Running);
353 assert_eq!(machine_state("started"), MachineState::Running, "UTM's running VM");
354 assert_eq!(machine_state("powered_on"), MachineState::Running, "ESXi's VM before its SSH address");
355 assert_eq!(machine_state("not_created"), MachineState::Absent);
356 for stopped in [
357 "poweroff",
358 "saved",
359 "aborted-saved",
360 "suspended",
361 "shutoff",
362 "off",
363 "not_running",
364 "powered_off",
365 "stopped",
366 "paused",
367 ] {
368 assert_eq!(machine_state(stopped), MachineState::Stopped, "{stopped}");
369 }
370 assert_eq!(machine_state("gurumeditation"), MachineState::Unknown("gurumeditation".into()));
371 assert_eq!(machine_state("aborted"), MachineState::Unknown("aborted".into()), "a VM that died");
372 }
373
374 #[test]
377 fn status_fixtures_read_as_vagrant_prints_them() {
378 let read = parse(include_str!("fixtures/vagrant/2.4.1-status-virtualbox.txt"));
379 assert_eq!(read.states.keys().collect::<Vec<_>>(), ["db", "web"]);
380 assert_eq!(
381 (machine_state(&read.states["web"]), machine_state(&read.states["db"])),
382 (MachineState::Running, MachineState::Stopped)
383 );
384 let hyperv = parse(include_str!("fixtures/vagrant/2.4.3-windows-status-hyperv.txt"));
385 assert_eq!(
386 machine_state(&hyperv.states["dc01"]),
387 MachineState::Stopped,
388 "no carriage return left in the label"
389 );
390 assert_eq!(machine_state(&hyperv.states["ws01"]), MachineState::Absent);
391 let cut = parse(include_str!("fixtures/vagrant/2.4.1-status-cut.txt"));
392 assert_eq!(machine_state(&cut.states["db"]), MachineState::Unknown("shut".into()));
393 assert_eq!(parse("").states.len(), 0);
394 let ssh = include_str!("fixtures/vagrant/2.4.1-ssh-config-windows.txt");
395 assert_eq!(host_name(ssh).as_deref(), Some("127.0.0.1"));
396 }
397
398 #[test]
399 fn failure_fixtures_read_as_vagrant_prints_them() {
400 let of = |text: &str| Failure::of(&lines(text));
401 assert_eq!(of(include_str!("fixtures/vagrant/2.4.9-error-machine-locked.txt")), Failure::Locked);
402 assert_eq!(of(include_str!("fixtures/vagrant/2.4.1-error-action-locked-human.txt")), Failure::Locked);
403 assert_eq!(of(include_str!("fixtures/vagrant/vmware-esxi-2.5.5-halt-already-off.txt")), Failure::AlreadyOff);
404 assert_eq!(of(include_str!("fixtures/vagrant/2.4.1-status-virtualbox.txt")), Failure::Other);
405 let locked = lines(include_str!("fixtures/vagrant/2.4.9-error-machine-locked.txt"));
406 assert!(error(&locked).is_some_and(|e| e.ends_with("Provider: libvirt (Vagrant::Errors::MachineLocked)")));
407 let plugins = plugins(include_str!("fixtures/vagrant/2.4.1-plugin-list.txt"));
408 assert_eq!(
409 plugins,
410 [
411 ("vagrant-libvirt".to_owned(), Some("0.12.2".to_owned())),
412 ("vagrant-qemu".to_owned(), Some("0.3.12".to_owned()))
413 ]
414 );
415 }
416}
417
418#[cfg(test)]
419mod proptests {
420 use proptest::prelude::*;
421
422 use super::*;
423
424 fn machine() -> impl Strategy<Value = String> {
426 prop_oneof![Just("gateway".to_owned()), "[a-z][a-z0-9_-]{0,12}"]
427 }
428
429 fn state() -> impl Strategy<Value = String> {
431 prop_oneof![
432 Just("running".to_owned()),
433 Just("poweroff".to_owned()),
434 Just("not_created".to_owned()),
435 "[a-z_ ,]{1,16}"
436 ]
437 }
438
439 proptest! {
440 #[test]
441 fn any_output_is_read_without_panicking(text in "(?s).{0,400}") {
442 let _ = parse(&text);
443 drop(plugins(&text));
444 }
445
446 #[test]
447 fn every_machines_last_state_reads_back_whole(
448 machines in proptest::collection::vec((machine(), state(), "[0-9]{10}"), 0..6),
449 noise in proptest::collection::vec("[0-9]{10},[a-z]{0,6},(metadata|ui),[^\n]{0,20}", 0..4),
450 ) {
451 let mut lines: Vec<String> = machines.iter().map(|(name, state, ts)| format!("{ts},{name},state,{state}")).collect();
452 lines.extend(noise);
453 let read = parse(&lines.join("\n"));
454 let mut want = BTreeMap::new();
455 for (name, state, _) in &machines {
456 want.insert(name.clone(), state.clone());
457 }
458 prop_assert_eq!(read.states, want);
459 }
460 }
461}