use std::future::Future;
use std::time::Duration;
use isoloom_manifest::{Run, Step};
use crate::Result;
use crate::driver::STATUS;
use crate::events::WarningCode;
use crate::executor::{Cx, Echo, Hold, call, capture_output, once, plan, stdout_of};
use crate::process::{Captured, ProcessSpec};
pub(super) const PATIENCE: Duration = Duration::from_secs(60);
pub(super) const QUERY_PATIENCE: Duration = Duration::from_secs(10);
const POLL: Duration = Duration::from_secs(2);
const LOCKED: [&str; 4] = [
"Vagrant::Errors::MachineActionLockedError",
"another process is already executing an action on the machine",
"Vagrant::Errors::MachineLocked,",
"Vagrant can't use the requested machine because it is locked!",
];
const ACTING: &str = "==> ";
pub(super) fn refused(out: &Captured) -> bool {
!out.success() && out.stdout.iter().chain(&out.stderr).any(|line| LOCKED.iter().any(|said| line.contains(said)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verb {
Read,
Converges,
Repeats,
}
fn verb(args: &[String]) -> Option<Verb> {
let provisions = args
.iter()
.any(|a| a == "--provision" || a == "--provision-with" || a.starts_with("--provision-with="));
match args.first().map(String::as_str) {
Some("status") => Some(Verb::Read),
Some("destroy" | "halt" | "suspend") => Some(Verb::Converges),
Some("up") if !provisions => Some(Verb::Converges),
Some("up" | "provision" | "reload" | "resume") => Some(Verb::Repeats),
_ => None,
}
}
fn again(args: &[String], acted: bool) -> bool {
match verb(args) {
Some(Verb::Read | Verb::Converges) => true,
Some(Verb::Repeats) => !acted,
None => false,
}
}
fn announces(line: &str) -> bool {
line.starts_with(ACTING)
}
fn acted(out: &Captured) -> bool {
out.stdout.iter().chain(&out.stderr).any(|line| announces(line))
}
#[derive(Debug)]
struct Patience {
lasts: Duration,
deadline: Option<tokio::time::Instant>,
}
impl Default for Patience {
fn default() -> Patience {
Patience::of(PATIENCE)
}
}
impl Patience {
fn of(lasts: Duration) -> Patience {
Patience { lasts, deadline: None }
}
async fn wait(&mut self) -> bool {
let now = tokio::time::Instant::now();
let deadline = *self.deadline.get_or_insert(now + self.lasts);
if now + POLL > deadline {
return false;
}
tokio::time::sleep(POLL).await;
true
}
}
async fn waiting<F, Fut>(what: &str, mut patience: Patience, safe: impl Fn(&Captured) -> bool, mut retrying: impl FnMut(), mut attempt: F) -> Result<Captured>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<Captured>>,
{
loop {
let out = attempt().await?;
if !refused(&out) || !safe(&out) || !patience.wait().await {
return Ok(out);
}
tracing::debug!(call = what, "another Vagrant process holds a machine's lock: tried again");
retrying();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum StatusRead {
Read(String),
Busy(Vec<String>),
}
pub(super) async fn read_status(cx: &Cx<'_>) -> Result<StatusRead> {
let step: &Step = &cx.run.manifest().lifecycle.status;
let patience = Patience::of(if cx.query { QUERY_PATIENCE } else { PATIENCE });
let still = |_: &Captured| !cx.query || !cx.run.runner.store.held(cx.run.name()).unwrap_or(false);
let out = waiting(STATUS, patience, still, || {}, || capture_output(cx, STATUS, step)).await?;
if cx.query && refused(&out) {
return Ok(StatusRead::Busy(locked_machines(&out)));
}
stdout_of(cx, step.id.as_str(), None, &out).map(StatusRead::Read)
}
pub(super) async fn read_status_output(cx: &Cx<'_>) -> Result<String> {
match read_status(cx).await? {
StatusRead::Read(out) => Ok(out),
StatusRead::Busy(_) => Err(crate::error::Error::ToolFailed {
step: STATUS.to_owned(),
reason: "another Vagrant process holds the run's machines".to_owned(),
}),
}
}
pub(super) fn locked_machines(out: &Captured) -> Vec<String> {
let mut named = Vec::new();
for line in out.stdout.iter().chain(&out.stderr) {
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(super) async fn call_retrying(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, limit: Duration, echo: Echo) -> Result<Captured> {
let reads = verb(&spec.args) == Some(Verb::Read);
let retrying = || {
if !reads {
warn_retrying(cx, id);
}
};
let safe = |out: &Captured| again(&spec.args, acted(out));
waiting(id, Patience::default(), safe, retrying, || call(cx, id, spec, limit, echo)).await
}
pub(super) async fn call_ok_retrying(cx: &Cx<'_>, id: &str, spec: &ProcessSpec, limit: Duration, echo: Echo) -> Result<String> {
let out = call_retrying(cx, id, spec, limit, echo).await?;
stdout_of(cx, id, Some(spec), &out)
}
pub(crate) async fn run_step(cx: &Cx<'_>, list: &str, step: &Step, observe: &mut (dyn FnMut(&str) + Send)) -> Result<()> {
let Some(args) = vagrant_args(cx, list, step)? else {
return once(cx, list, step, observe, Hold::No).await?.result(cx, step);
};
let mut patience = Patience::default();
loop {
let stale = cx.stale.seen();
let mut announced = false;
let ended = {
let mut watch = |line: &str| {
announced |= announces(line);
observe(line);
};
once(cx, list, step, &mut watch, Hold::No).await?
};
if !refused(&ended.last) || !again(&args, announced) || !patience.wait().await {
return ended.result(cx, step);
}
cx.stale.rewind(stale);
warn_retrying(cx, step.id.as_str());
}
}
fn vagrant_args(cx: &Cx<'_>, list: &str, step: &Step) -> Result<Option<Vec<String>>> {
let Run::Argv(argv) = &step.run else { return Ok(None) };
let command = plan::command(argv, cx.scope.host, &cx.vars, &plan::at(list, step))?;
Ok((command.program == "vagrant").then_some(command.args))
}
fn warn_retrying(cx: &Cx<'_>, id: &str) {
cx.events.warning(
WarningCode::Retrying,
&format!("step `{id}`: another Vagrant process held a machine's lock; running the command again"),
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::process::Exit;
fn ended(code: i32, stdout: &[&str], stderr: &[&str]) -> Captured {
let lines = |l: &[&str]| l.iter().map(|s| (*s).to_owned()).collect();
Captured {
exit: Exit::new(Some(code)),
stdout: lines(stdout),
stderr: lines(stderr),
}
}
#[test]
fn only_a_lock_held_by_another_process_is_refused() {
let read = "1,,error-exit,Vagrant::Errors::MachineActionLockedError,An action 'read_state' was attempted";
assert!(refused(&ended(1, &[read], &[])));
let halt = "but another process is already executing an action on the machine.";
assert!(refused(&ended(1, &[], &["An action 'halt' was attempted on the machine 'web',", halt])));
assert!(!refused(&ended(
1,
&[],
&["SSH connection was refused! This usually happens if the VM failed to"]
)));
assert!(!refused(&ended(1, &["1,,error-exit,Vagrant::Errors::VBoxManageError,locked"], &[])));
assert!(!refused(&ended(1, &["1,,error-exit,Vagrant::Errors::MachineLockedOut,x"], &[])));
assert!(!refused(&ended(0, &[read], &[])));
}
#[test]
fn only_what_a_second_run_does_nothing_twice_with_is_run_again() {
let args = |line: &str| line.split(' ').map(str::to_owned).collect::<Vec<_>>();
for converges in [
"status --machine-readable",
"destroy --force",
"destroy -f web",
"halt",
"suspend web",
"up --provider libvirt",
] {
assert!(again(&args(converges), true), "{converges}");
}
assert!(again(&args("up web --no-provision"), true), "an up that never provisions");
for twice in [
"provision web",
"reload web --no-provision",
"resume web",
"up --provider libvirt --provision",
"up --provider libvirt --provision-with setup",
"up --provision-with=setup",
] {
assert!(again(&args(twice), false), "{twice}: refused before it acted");
assert!(!again(&args(twice), true), "{twice}: refused once it had acted");
}
for never in ["ssh web -c true", "ssh-config web", "plugin list"] {
assert!(!again(&args(never), false), "{never}");
}
assert_eq!(verb(&args("status --machine-readable")), Some(Verb::Read));
assert_eq!(verb(&args("up web")), Some(Verb::Converges));
assert_eq!(verb(&args("up web --provision")), Some(Verb::Repeats));
assert_eq!(verb(&args("ssh web -c true")), None);
}
#[test]
fn an_action_announced_on_either_stream_counts_as_acted() {
let booting = "Bringing machine 'web' up with 'libvirt' provider...";
assert!(acted(&ended(1, &[booting, "==> web: Removing domain..."], &[])));
assert!(acted(&ended(1, &[booting], &["==> web: Removing domain..."])), "on standard error too");
assert!(!acted(&ended(1, &[booting, " web: SSH address: 1.2.3.4:22"], &[])));
}
#[test]
fn a_machines_index_lock_held_by_another_process_is_refused() {
let said = "Vagrant can't use the requested machine because it is locked! This\\nmeans that another Vagrant \
process is currently reading or modifying\\nthe machine.";
let fog = "[fog][WARNING] Unrecognized arguments: libvirt_ip_command";
let read = format!("1794342958,,error-exit,Vagrant::Errors::MachineLocked,{said}");
assert!(refused(&ended(1, &[&format!("1794342958,,ui,error,{said}"), &read], &[fog])));
let halt = [
fog,
"Vagrant can't use the requested machine because it is locked! This",
"means that another Vagrant process is currently reading or modifying",
];
assert!(refused(&ended(1, &[], &halt)));
}
}