mod booting;
mod busy;
mod clear;
mod dotfile;
mod failures;
mod fetched;
mod forwards;
mod gone;
mod lock;
mod names;
mod passing;
mod preamble;
mod progress;
mod protocols;
mod providers;
mod screen;
use names::{checked_user, key_of, of_key, one, ours, own_address, verb_word};
mod vmnet;
use std::time::Duration;
use self::dotfile::{Dotfile, Record};
use self::failures::vagrant_error;
use self::lock::{PATIENCE, Rerun, STATUS_PATIENCE, retrying};
use self::protocols::Declared;
use super::{Change, FormatDriver, Found, Ran, Seen, SeenMachine, SeenPort, ToolCx, tool_error};
use crate::Result;
use crate::cli::vagrant::{self, Failure, Provision, Verb};
use crate::cli::{Call, CliError, vboxmanage};
use crate::console::ShellCommand;
use crate::error::{Error, ProviderNeed};
use crate::events::WarningCode;
use crate::project::platform::Provider;
use crate::state::{Park, RunState};
use crate::status::MachineState;
use crate::store::{Lifetime, ResourceKind};
const UP_LIMIT: Duration = Duration::from_secs(3600);
const CALL_LIMIT: Duration = Duration::from_secs(900);
const RECONCILE_LIMIT: Duration = Duration::from_secs(180);
const READ_LIMIT: Duration = Duration::from_secs(120);
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Vagrant;
fn call<'a>(cx: &'a ToolCx<'_>, limit: Duration) -> Call<'a> {
let mut call = cx.call(limit);
call.env.retain(|(k, _)| k != dotfile::VAR);
call.env.push((dotfile::VAR.to_owned(), dot(cx).path.display().to_string()));
call
}
fn read<'a>(cx: &'a ToolCx<'_>, limit: Duration) -> Call<'a> {
Call {
sink: &super::discard,
..call(cx, limit)
}
}
fn dot(cx: &ToolCx<'_>) -> Dotfile {
Dotfile::in_state(cx.state_dir)
}
fn up_provision(cx: &ToolCx<'_>) -> Result<Provision> {
Ok(if dot(cx).recorded()?.is_empty() { Provision::Default } else { Provision::Yes })
}
fn asked(cx: &ToolCx<'_>) -> Result<Provider> {
cx.provider.ok_or_else(|| Error::NoProvider {
providers: providers::listed_for(providers::this_host()),
})
}
impl Vagrant {
async fn up_call(&self, cx: &ToolCx<'_>, step: &str, provision: Provision, machines: &[String]) -> std::result::Result<(), CliError<Failure>> {
let provider = cx.provider.map(Provider::id);
let rerun = if provision == Provision::Yes { Rerun::Repeats } else { Rerun::Converges };
let watch = progress::Watch::new(&cx.steps);
let sink = |stream: crate::events::Stream, line: &str| {
watch.see(line);
(cx.sink)(stream, line);
};
let call = &Call {
sink: &sink,
..call(cx, UP_LIMIT)
};
let up = booting::until_it_answers(cx, step, move || {
passing::once_more(cx, step, move || {
retrying(cx.warn, step, rerun, PATIENCE, move || vagrant::up(call, provider, provision, machines))
})
});
let done = fetched::recording(cx, up).await;
if done.is_ok() {
vmnet::address_host_adapters(cx, providers::this_host()).await;
cx.steps.end(true);
}
done
}
async fn act(&self, cx: &ToolCx<'_>, verb: Verb, machines: &[String], limit: Duration) -> std::result::Result<(), CliError<Failure>> {
let rerun = match verb {
Verb::Halt | Verb::Suspend | Verb::Destroy => Rerun::Converges,
Verb::Provision => Rerun::Repeats,
};
let call = call(cx, limit);
retrying(cx.warn, verb_word(verb), rerun, PATIENCE, || vagrant::act(&call, verb, machines)).await
}
async fn status(&self, cx: &ToolCx<'_>) -> Result<std::collections::BTreeMap<String, String>> {
self.read_states(cx).await.map_err(|e| vagrant_error(cx, "status", e))
}
async fn read_states(&self, cx: &ToolCx<'_>) -> std::result::Result<std::collections::BTreeMap<String, String>, CliError<Failure>> {
let call = read(cx, READ_LIMIT);
let read = retrying(cx.warn, "status", Rerun::Read, STATUS_PATIENCE, || vagrant::status(&call)).await?;
Ok(read.states)
}
async fn up_recovering(&self, cx: &ToolCx<'_>, step: &str, provision: Provision, machines: &[String]) -> Result<()> {
match self.up_call(cx, step, provision, machines).await {
Ok(()) => Ok(()),
Err(CliError::Failed {
failure: Failure::AlreadyExists | Failure::OtherProvider,
..
}) => {
tracing::info!(run = %cx.run, "an earlier start's VM holds a name of the run: removing what the run made, then starting again");
self.clear(cx).await?;
self.up_call(cx, step, provision, machines).await.map_err(|e| vagrant_error(cx, step, e))
}
Err(e) => Err(vagrant_error(cx, step, e)),
}
}
}
impl FormatDriver for Vagrant {
fn ready_by_observation(&self, failed_start: bool) -> bool {
!failed_start
}
fn elevates(&self, provider: Option<Provider>) -> bool {
provider == Some(Provider::Hyperv)
}
async fn probe(&self, cx: &ToolCx<'_>) -> Result<()> {
let provider = asked(cx)?;
let host = providers::this_host();
let refuse_for = |need: Option<ProviderNeed>, reason: String| Error::Provider {
need,
provider: provider.id().to_owned(),
reason,
};
let refuse = |reason: String| refuse_for(None, reason);
if !providers::hosts(provider).contains(&host) {
return Err(refuse(format!(
"doesn't run on this computer's system; these do: {}",
providers::listed_for(host)
)));
}
let read = read(cx, READ_LIMIT);
let found = vagrant::supported_version(&read).await.map_err(|e| vagrant_error(cx, "tools", e))?;
super::unknown_version(cx, found.as_ref(), "vagrant", vagrant::MIN_VERSION);
if let Some(plugin) = provider.plugin() {
let installed = vagrant::plugins(&read).await.map_err(|e| vagrant_error(cx, "tools", e))?;
if !installed.iter().any(|(name, _)| name == plugin) {
return Err(refuse_for(
Some(ProviderNeed::Plugin),
format!("needs the Vagrant plugin `{plugin}`: `vagrant plugin install {plugin}`"),
));
}
}
Ok(())
}
async fn up(&self, cx: &ToolCx<'_>) -> Result<()> {
let provider = asked(cx)?;
crate::store::create_dir(cx.state_dir)?;
self.preamble(cx, provider).await?;
self.up_recovering(cx, "up", up_provision(cx)?, &[]).await
}
async fn down(&self, cx: &ToolCx<'_>) -> Result<()> {
self.act(cx, Verb::Destroy, &[], CALL_LIMIT).await.map_err(|e| vagrant_error(cx, "down", e))?;
dot(cx).reset()
}
async fn park(&self, cx: &ToolCx<'_>, mode: Park) -> Result<()> {
let verb = match mode {
Park::Pause => Verb::Suspend,
Park::Shutdown => Verb::Halt,
};
match self.act(cx, verb, &[], CALL_LIMIT).await {
Ok(())
| Err(CliError::Failed {
failure: Failure::AlreadyOff, ..
}) => Ok(()),
Err(e) => Err(vagrant_error(cx, "park", e)),
}
}
async fn resume(&self, cx: &ToolCx<'_>) -> Result<()> {
let provider = asked(cx)?;
self.refuse_resume_if_gone(cx).await?;
self.preamble(cx, provider).await?;
self.up_recovering(cx, "resume", Provision::No, &[]).await
}
async fn update(&self, cx: &ToolCx<'_>) -> Result<()> {
asked(cx)?;
self.up_call(cx, "update", Provision::Yes, &[])
.await
.map_err(|e| vagrant_error(cx, "update", e))
}
async fn machines(&self, cx: &ToolCx<'_>) -> Result<Vec<String>> {
Ok(self.status(cx).await?.into_keys().collect())
}
async fn reapply(&self, cx: &ToolCx<'_>, change: &Change) -> Result<()> {
if !change.added.is_empty() {
asked(cx)?;
self.up_call(cx, "reapply", Provision::Default, &change.added)
.await
.map_err(|e| vagrant_error(cx, "reapply", e))?;
}
if !change.removed.is_empty() {
let defined = self.machines(cx).await?;
let (known, gone): (Vec<String>, Vec<String>) = change.removed.iter().cloned().partition(|m| defined.contains(m));
if !known.is_empty() {
self.act(cx, Verb::Destroy, &known, CALL_LIMIT)
.await
.map_err(|e| vagrant_error(cx, "reapply", e))?;
}
for r in dot(cx).recorded()?.into_iter().filter(|r| gone.contains(&r.machine)) {
self.remove_at_hypervisor(cx, &r).await?;
}
}
if !change.changed.is_empty() {
self.act(cx, Verb::Provision, &change.changed, UP_LIMIT)
.await
.map_err(|e| vagrant_error(cx, "reapply", e))?;
}
Ok(())
}
async fn provision(&self, cx: &ToolCx<'_>, machine: Option<&str>, with: Option<&str>) -> Result<()> {
asked(cx)?;
let machines: Vec<String> = machine.map(one).unwrap_or_default();
let Some(name) = with else {
return self
.up_call(cx, "provision", Provision::Yes, &machines)
.await
.map_err(|e| vagrant_error(cx, "provision", e));
};
let name = vagrant::ProvisionerName::new(name).ok_or_else(|| Error::Input {
name: "provisioner".to_owned(),
reason: format!("`{name}` isn't a provisioner's name (letters, digits, `-`, `_`)"),
})?;
let call = call(cx, super::CHECK_LIMIT);
retrying(cx.warn, "provision", Rerun::Repeats, PATIENCE, || {
vagrant::provision_with(&call, &name, &machines)
})
.await
.map_err(|e| vagrant_error(cx, "provision", e))
}
async fn attach(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
asked(cx)?;
self.up_call(cx, "attach", Provision::Default, &one(machine))
.await
.map_err(|e| vagrant_error(cx, "attach", e))
}
async fn retire(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
self.act(cx, Verb::Destroy, &one(machine), CALL_LIMIT)
.await
.map_err(|e| vagrant_error(cx, "retire", e))
}
async fn package(&self, cx: &ToolCx<'_>, machine: &str, output: &std::path::Path) -> Result<()> {
asked(cx)?;
vagrant::package(&call(cx, UP_LIMIT), machine, output)
.await
.map_err(|e| vagrant_error(cx, "package", e))
}
async fn exec(&self, cx: &ToolCx<'_>, machine: &str, argv: &[String]) -> Result<Ran> {
let script = argv.iter().map(|w| crate::console::sh_word(w)).collect::<Vec<_>>().join(" ");
let out = vagrant::ssh_run(&call(cx, super::CHECK_LIMIT), machine, &script)
.await
.map_err(|e| vagrant_error(cx, "exec", e))?;
Ok(Ran {
exit: out.exit.code.unwrap_or(-1),
stdout: out.stdout.join("\n"),
stderr: out.stderr_tail.join("\n"),
})
}
fn console(&self, cx: &ToolCx<'_>, machine: &str, user: Option<&str>) -> impl Future<Output = Result<ShellCommand>> {
let script = user.map(checked_user).transpose().map(|u| u.map(crate::console::shells::login_shell_as));
std::future::ready(script.map(|script| {
let spec = vagrant::console_spec(&call(cx, READ_LIMIT), machine, script.as_deref());
ShellCommand::of_spec(spec, &cx.project.dir)
}))
}
async fn observe(&self, cx: &ToolCx<'_>) -> Result<(Seen, RunState)> {
let read = read(cx, READ_LIMIT);
let records = dot(cx).recorded()?;
let mut machines = Vec::new();
let states = match self.read_states(cx).await {
Ok(states) => states,
Err(CliError::Failed {
failure: Failure::Locked { machines: named, .. },
..
}) if !named.is_empty() => return Ok((busy::busy(named), RunState::Ready)),
Err(e) => return Err(vagrant_error(cx, "status", e)),
};
let gone = gone::gone(cx, &states)?;
let declared = cx.project.files.first().map(|f| Declared::of_file(f)).unwrap_or_default();
for (name, label) in states {
let state = crate::tool_output::vagrant::machine_state(&label);
let asked = cx.provider.map(Provider::id);
let mine = records.iter().filter(|r| r.machine == name);
let kind = mine
.clone()
.find(|r| Some(r.provider.as_str()) == asked)
.or_else(|| mine.clone().next())
.map(|r| r.provider.clone());
let mut published = Vec::new();
if state == MachineState::Running {
match retrying(cx.warn, "port", Rerun::Read, STATUS_PATIENCE, || vagrant::port(&read, &name)).await {
Ok(forwards) => published.extend(forwards.into_iter().map(|f| SeenPort {
protocol: declared.protocol(&name, f.guest.get()),
guest: f.guest,
host: f.host,
})),
Err(CliError::Failed {
failure: Failure::PortsUnsupported,
..
}) => {
if kind.as_deref() == Some(Provider::Qemu.id()) {
published.extend(forwards::of_qemu(cx, &name).await);
}
}
Err(e) => return Err(vagrant_error(cx, "status", e)),
}
}
let address = if state == MachineState::Running && kind.as_deref().is_some_and(own_address) {
self.address(cx, &name).await
} else {
None
};
machines.push(SeenMachine {
name,
state,
published,
kind,
address,
windows: false,
});
}
let state = gone::run_state(&machines, &gone);
Ok((Seen { machines, ..Seen::default() }, state))
}
fn found(&self, cx: &ToolCx<'_>) -> impl Future<Output = Result<Vec<Found>>> {
let found = dot(cx).recorded().map(|records| {
records
.into_iter()
.map(|r| Found {
key: key_of(&r, cx.provider),
kind: ResourceKind::Vm,
native_id: r.id,
lifetime: Lifetime::Machines,
})
.collect()
});
std::future::ready(found)
}
async fn destroy_by_id(&self, cx: &ToolCx<'_>, key: &str, kind: ResourceKind, native_id: &str) -> Result<()> {
let refused = || Error::Unsupported {
what: format!("removing the {kind:?} resource `{key}` through Vagrant"),
};
if kind != ResourceKind::Vm {
return Err(refused());
}
let (machine, provider) = of_key(key, cx.provider).ok_or_else(refused)?;
let dot = dot(cx);
let recorded = dot.recorded()?;
let record = if let Some(r) = recorded.into_iter().find(|r| r.id == native_id) {
r
} else {
let Some(provider) = provider else {
return Err(Error::NoProvider {
providers: providers::listed_for(providers::this_host()),
});
};
let lost = Record {
machine,
provider,
id: native_id.to_owned(),
};
dot.write_back(&lost)?;
lost
};
match self.act(cx, Verb::Destroy, &one(&record.machine), CALL_LIMIT).await {
Ok(()) => dot.forget(&record.machine, &record.provider),
Err(CliError::Failed {
failure: Failure::UnknownMachine,
..
}) => self.remove_at_hypervisor(cx, &record).await,
Err(e) => Err(vagrant_error(cx, "remove", e)),
}
}
async fn graphical(&self, cx: &ToolCx<'_>, _seen: &Seen, machine: &SeenMachine) -> Result<Option<crate::graphical::ConsoleOffer>> {
Ok(screen::offer(cx, machine).await)
}
async fn reach_graphical(&self, cx: &ToolCx<'_>, machine: &str) -> Result<crate::graphical::Console> {
screen::reach(cx, machine).await
}
fn native_app(&self, cx: &ToolCx<'_>, seen: &Seen) -> Option<crate::graphical::NativeApp> {
screen::app(cx, seen)
}
async fn native_console(&self, cx: &ToolCx<'_>, machine: &str) -> Result<crate::graphical::NativeConsole> {
screen::native(cx, machine).await
}
}
#[cfg(test)]
mod tests;