use std::fmt;
use super::{Call, CliError, argv, said_any};
use crate::process::Captured;
use crate::tool_output::osascript::AppleEvent;
use crate::tool_output::vagrant as said;
const TOOL: &str = "vagrant";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Failure {
AlreadyExists,
Locked {
acted: bool,
machines: Vec<String>,
},
UnknownMachine,
PortsUnsupported,
OtherProvider,
AlreadyOff,
SignInRefused {
server: Option<String>,
},
ScriptingPassing {
number: i32,
reason: String,
},
VmnetNotEnabled {
reason: String,
},
Booting {
reason: String,
},
Lacks {
need: crate::error::ProviderNeed,
reason: String,
},
Other(String),
}
impl Failure {
pub(crate) fn of(out: &Captured) -> Failure {
match said::Failure::of(out.stdout.iter().chain(&out.stderr_tail)) {
said::Failure::Locked => {
return Failure::Locked {
acted: acted(out),
machines: locked_machines(out),
};
}
said::Failure::AlreadyOff => return Failure::AlreadyOff,
said::Failure::Other => {}
}
if said_any(out, &["unable to connect to esxi host"]) && said_any(out, &["authentication failed", "incorrect user name or password"]) {
Failure::SignInRefused { server: refused_host(out) }
} else if said_any(out, &["verr_already_exists", "could not rename"]) {
Failure::AlreadyExists
} else if said_any(out, &["different provider", "single provider at a time"]) {
Failure::OtherProvider
} else if said_any(out, &["was not found configured for"]) {
Failure::UnknownMachine
} else if said_any(out, &["does not support listing forwarded ports"]) {
Failure::PortsUnsupported
} else if let Some(event) = AppleEvent::of(out.stdout.iter().chain(&out.stderr_tail)).filter(|e| e.passes()) {
Failure::ScriptingPassing {
number: event.number(),
reason: out.reason(),
}
} else if let Some(need) = refused_by_the_system(out) {
Failure::Lacks { need, reason: out.reason() }
} else if said_any(out, &["failed to create a new vmware networking device"]) && said_any(out, &["failed to enable device"]) {
Failure::VmnetNotEnabled { reason: out.reason() }
} else if said_any(
out,
&[
"timeout during server version negotiating",
"ssh connection was unexpectedly closed by the remote end",
"ssh connection was reset!",
],
) {
Failure::Booting { reason: out.reason() }
} else if said_any(out, &["unable to find a satisfying virtiofsd", "virtiofsd was not found or is not executable"]) {
Failure::Lacks {
need: crate::error::ProviderNeed::Virtiofsd,
reason: out.reason(),
}
} else {
Failure::Other(out.reason())
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Failure::AlreadyExists => f.write_str("an earlier VM holds the name"),
Failure::Locked { .. } => f.write_str("another process holds the machine's lock"),
Failure::UnknownMachine => f.write_str("the Vagrantfile defines no such machine"),
Failure::PortsUnsupported => f.write_str("the provider can't list forwarded ports"),
Failure::OtherProvider => f.write_str("the machine is recorded on another provider"),
Failure::AlreadyOff => f.write_str("the VM is already off"),
Failure::SignInRefused { .. } => f.write_str("the ESXi host refused the run's credentials"),
Failure::ScriptingPassing { reason, .. }
| Failure::VmnetNotEnabled { reason }
| Failure::Booting { reason }
| Failure::Lacks { reason, .. }
| Failure::Other(reason) => f.write_str(reason),
}
}
}
fn refused_by_the_system(out: &Captured) -> Option<crate::error::ProviderNeed> {
let event = AppleEvent::of(out.stdout.iter().chain(&out.stderr_tail));
if event.is_some_and(|e| e.number() == NOT_AUTHORIZED) {
Some(crate::error::ProviderNeed::Automation)
} else if (event.is_some() || said_any(out, &["osstatus error", "error from event"])) && said_any(out, &["operation not permitted"]) {
Some(crate::error::ProviderNeed::AppApproval)
} else {
None
}
}
const NOT_AUTHORIZED: i32 = -1743;
fn refused_host(out: &Captured) -> Option<String> {
out.stdout.iter().chain(&out.stderr_tail).find_map(|l| {
let (_, after) = l.split_once("Authentication failed for user ")?;
let (_, host) = after.trim().rsplit_once('@')?;
(!host.is_empty()).then(|| host.to_owned())
})
}
const ACTING: &str = "==> ";
fn acted(out: &Captured) -> bool {
out.stdout.iter().chain(&out.stderr_tail).any(|line| line.starts_with(ACTING))
}
fn locked_machines(out: &Captured) -> Vec<String> {
let mut named: Vec<String> = Vec::new();
for line in out.stdout.iter().chain(&out.stderr_tail) {
for part in line.split("\\n") {
let found = part
.split_once("on the machine '")
.and_then(|(_, rest)| rest.split_once('\''))
.map(|(define, _)| define)
.or_else(|| part.trim().strip_prefix("Name:").map(str::trim));
if let Some(define) = found.filter(|d| !d.is_empty())
&& !named.iter().any(|n| n == define)
{
named.push(define.to_owned());
}
}
}
named
}
pub(crate) const MIN_VERSION: &str = "2.4.0";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Provision {
Default,
Yes,
No,
}
pub(crate) async fn up(call: &Call<'_>, provider: Option<&str>, provision: Provision, machines: &[String]) -> Result<(), CliError<Failure>> {
let mut args = argv(["up"]);
if let Some(provider) = provider {
args.extend(["--provider".to_owned(), provider.to_owned()]);
}
match provision {
Provision::Default => {}
Provision::Yes => args.push("--provision".into()),
Provision::No => args.push("--no-provision".into()),
}
args.extend(machines.iter().cloned());
call.ok(TOOL, args, Failure::of).await.map(drop)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProvisionerName(String);
impl ProvisionerName {
pub(crate) fn new(name: &str) -> Option<ProvisionerName> {
let plain = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
(!name.is_empty() && !name.starts_with('-') && name.chars().all(plain)).then(|| ProvisionerName(name.to_owned()))
}
}
pub(crate) async fn provision_with(call: &Call<'_>, name: &ProvisionerName, machines: &[String]) -> Result<(), CliError<Failure>> {
let mut args = argv(["provision", "--provision-with"]);
args.push(name.0.clone());
args.extend(machines.iter().cloned());
call.ok(TOOL, args, Failure::of).await.map(drop)
}
pub(crate) async fn package(call: &Call<'_>, machine: &str, output: &std::path::Path) -> Result<(), CliError<Failure>> {
let mut args = argv(["package"]);
args.push(machine.to_owned());
args.push("--output".to_owned());
args.push(output.display().to_string());
call.ok(TOOL, args, Failure::of).await.map(drop)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Verb {
Halt,
Suspend,
Provision,
Destroy,
}
pub(crate) async fn act(call: &Call<'_>, verb: Verb, machines: &[String]) -> Result<(), CliError<Failure>> {
let mut args = match verb {
Verb::Halt => argv(["halt"]),
Verb::Suspend => argv(["suspend"]),
Verb::Provision => argv(["provision"]),
Verb::Destroy => argv(["destroy", "-f"]),
};
args.extend(machines.iter().cloned());
call.ok(TOOL, args, Failure::of).await.map(drop)
}
pub(crate) async fn status(call: &Call<'_>) -> Result<said::Reading, CliError<Failure>> {
let out = call.ok(TOOL, argv(["status", "--machine-readable"]), Failure::of).await?;
Ok(said::parse(&out.stdout.join("\n")))
}
pub(crate) async fn boxes(call: &Call<'_>) -> Result<Vec<said::InstalledBox>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["box", "list", "--machine-readable"]), Failure::of).await?;
Ok(said::boxes(&out.stdout.join("\n")))
}
pub(crate) async fn remove_box(call: &Call<'_>, held: &said::InstalledBox) -> Result<(), CliError<Failure>> {
let mut args = argv(["box", "remove"]);
args.extend([
held.name.clone(),
"--provider".into(),
held.provider.clone(),
"--box-version".into(),
held.version.clone(),
]);
if let Some(arch) = &held.architecture {
args.extend(["--architecture".into(), arch.clone()]);
}
call.ok(TOOL, args, Failure::of).await.map(drop)
}
pub(crate) async fn ssh_host(call: &Call<'_>, machine: &str) -> Result<String, CliError<Failure>> {
let out = call.ok(TOOL, argv(["ssh-config", machine]), Failure::of).await?;
said::host_name(&out.stdout.join("\n")).ok_or_else(|| CliError::Unexpected {
tool: TOOL,
what: format!("an ssh-config for `{machine}` with no HostName"),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Forward {
pub(crate) guest: crate::port::GuestPort,
pub(crate) host: crate::port::HostPort,
}
pub(crate) fn forwards(out: &str) -> Result<Vec<Forward>, String> {
out.lines()
.filter_map(said::fields)
.filter(|(_, kind, _)| *kind == "forwarded_port")
.map(|(_, _, data)| {
let (guest, host) = data.split_once(',').ok_or_else(|| format!("a forward that isn't `guest,host`: {data}"))?;
let port = |p: &str| p.trim().parse::<u16>().map_err(|e| format!("a forward's port `{p}`: {e}"));
Ok(Forward {
guest: crate::port::GuestPort::new(port(guest)?),
host: crate::port::HostPort::new(port(host)?),
})
})
.collect()
}
pub(crate) async fn port(call: &Call<'_>, machine: &str) -> Result<Vec<Forward>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["port", machine, "--machine-readable"]), Failure::of).await?;
forwards(&out.stdout.join("\n")).map_err(|what| CliError::Unexpected { tool: TOOL, what })
}
pub(crate) async fn plugins(call: &Call<'_>) -> Result<Vec<(String, Option<String>)>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["plugin", "list", "--machine-readable"]), Failure::of).await?;
Ok(said::plugins(&out.stdout.join("\n")))
}
pub(crate) async fn supported_version(call: &Call<'_>) -> Result<Option<crate::project::platform::Version>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["--version"]), Failure::of).await?;
super::version(TOOL, &out.stdout.join("\n"), Some(MIN_VERSION))
}
fn ssh_args(machine: &str, script: &str) -> Vec<String> {
let mut args = argv(["ssh", machine, "-c", script, "--"]);
args.extend(NON_INTERACTIVE.iter().flat_map(|o| ["-o".to_owned(), (*o).to_owned()]));
args
}
const NON_INTERACTIVE: [&str; 2] = ["BatchMode=yes", "ConnectTimeout=20"];
pub(crate) fn console_spec(call: &Call<'_>, machine: &str, script: Option<&str>) -> crate::process::ProcessSpec {
let args = match script {
None => argv(["ssh", machine]),
Some(script) => argv(["ssh", machine, "-c", script]),
};
call.spec(TOOL, args)
}
pub(crate) async fn ssh_run(call: &Call<'_>, machine: &str, script: &str) -> Result<Captured, CliError<Failure>> {
call.run(TOOL, ssh_args(machine, script)).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::Exit;
fn failed(stdout: &str, stderr: &str) -> Failure {
let lines = |t: &str| t.lines().map(str::to_owned).collect();
Failure::of(&Captured::new(TOOL, Exit::new(Some(1)), lines(stdout), lines(stderr)))
}
#[test]
fn failures_read_as_vagrant_prints_them() {
assert_eq!(
failed(include_str!("../tool_output/fixtures/vagrant/2.4.9-error-machine-locked.txt"), ""),
Failure::Locked {
acted: false,
machines: vec!["probe".to_owned()]
}
);
assert_eq!(
failed("", include_str!("../tool_output/fixtures/vagrant/vmware-esxi-2.5.5-halt-already-off.txt")),
Failure::AlreadyOff
);
assert_eq!(
failed("", include_str!("../tool_output/fixtures/vagrant/vmware-esxi-2.5.5-auth-failed.txt")),
Failure::SignInRefused {
server: Some("esxi.stack.example".to_owned())
}
);
assert_eq!(
failed("", include_str!("../tool_output/fixtures/vagrant/2.4.1-virtualbox-7.0-already-exists.txt")),
Failure::AlreadyExists
);
assert_eq!(
failed("", include_str!("../tool_output/fixtures/vagrant/2.4.1-other-provider.txt")),
Failure::OtherProvider
);
assert_eq!(
failed(include_str!("../tool_output/fixtures/vagrant/2.4.9-machine-not-found.txt"), ""),
Failure::UnknownMachine
);
assert_eq!(
failed(include_str!("../tool_output/fixtures/vagrant/2.4.9-libvirt-port-unsupported.txt"), ""),
Failure::PortsUnsupported
);
for said in [
include_str!("../tool_output/fixtures/vagrant/vagrant-libvirt-no-virtiofsd.txt"),
include_str!("../tool_output/fixtures/vagrant/vagrant-qemu-0.8-no-virtiofsd.txt"),
] {
assert!(
matches!(
failed("", said),
Failure::Lacks {
need: crate::error::ProviderNeed::Virtiofsd,
..
}
),
"{said}"
);
}
for said in [
"virtiofsd failed to start for /home/ada/shared. Check the log at /tmp/x.log",
"Call to virDomainCreate failed: Requested operation is not valid: network 'default' is not active",
] {
assert!(matches!(failed("", said), Failure::Other(_)), "{said}");
}
assert_eq!(
failed("", "The box 'nope' could not be found"),
Failure::Other("The box 'nope' could not be found (exited with code 1)".to_owned())
);
}
#[test]
fn the_system_refusing_the_hypervisors_app_says_whether_the_automation_or_the_apps_approval() {
use crate::error::ProviderNeed::{AppApproval, Automation};
for (said, need) in [
("execution error: Not authorized to send Apple events to UTM. (-1743)", Automation),
("erreur d’exécution : Non autorisé à envoyer des Apple Events à UTM. (-1743)", Automation),
(
"execution error: Not authorized to send Apple events to UTM. (-1743)\nOperation not permitted",
Automation,
),
(
include_str!("../tool_output/fixtures/vagrant/vagrant_utm-0.2-start-not-permitted.txt"),
AppApproval,
),
] {
match failed("", said) {
Failure::Lacks { need: lacks, .. } => assert_eq!(lacks, need, "{said}"),
other => panic!("{said}: {other:?}"),
}
}
for said in [
"cp: /data/disk.img: Operation not permitted",
"Error from event: The operation couldn’t be completed. (OSStatus error -2700.)",
] {
assert!(matches!(failed("", said), Failure::Other(_)), "{said}");
}
}
#[test]
fn a_lock_refusal_says_whether_it_had_acted_and_on_which_machines() {
let action = "1,,error-exit,Vagrant::Errors::MachineActionLockedError,An action 'up' was attempted on the machine 'web'%!(VAGRANT_COMMA)\\nbut another process is already executing an action on the machine.";
assert_eq!(
failed(&format!("Bringing machine 'web' up with 'libvirt' provider...\n{action}"), ""),
Failure::Locked {
acted: false,
machines: vec!["web".to_owned()]
}
);
let after = failed(
"==> web: Removing domain...",
"Vagrant can't use the requested machine because it is locked! This\nName: web\nName: web",
);
assert_eq!(
after,
Failure::Locked {
acted: true,
machines: vec!["web".to_owned()]
},
"an action announced on stdout, the index lock's name on stderr, named once"
);
}
fn forward(guest: u16, host: u16) -> Forward {
Forward {
guest: crate::port::GuestPort::new(guest),
host: crate::port::HostPort::new(host),
}
}
#[test]
fn forwards_read_as_vagrant_prints_them() {
let read = forwards(include_str!("../tool_output/fixtures/vagrant/2.4.1-port.txt")).unwrap();
assert_eq!(read, [forward(22, 2222), forward(80, 8080)]);
let cut = forwards("1,web,forwarded_port,22");
assert_eq!(
cut,
Err("a forward that isn't `guest,host`: 22".to_owned()),
"a cut record isn't a shorter list"
);
assert_eq!(forwards("").unwrap(), Vec::<Forward>::new());
}
}