mod adopt;
mod console;
mod jump;
mod machines;
mod required;
mod route;
use machines::{machines_of, run_state, with_named_addresses};
mod screen;
mod teardown;
mod tunnelled;
use std::path::{Path, PathBuf};
use std::time::Duration;
use super::{Change, FormatDriver, Found, Output, Ran, Seen, SeenMachine, ToolCx, tool_error};
use crate::Result;
use crate::cli::terraform::{self as tf, Backend, Failure, StateAt};
use crate::cli::{Call, CliError};
use crate::console::ShellCommand;
use crate::error::Error;
use crate::events::{Stream, WarningCode};
use crate::state::{Park, RunState};
use crate::steps::{Phase, StepCount};
use crate::store::{Lifetime, ResourceKind};
use crate::tool_output::sign_in;
use machines::{text_of, vm_named};
const STATE_FILE: &str = "terraform.tfstate";
const BACKUP_FILE: &str = "terraform.tfstate.backup";
const LOCK_INFO: &str = ".terraform.tfstate.lock.info";
const DATA_DIR: &str = ".terraform";
const DATA_DIR_VAR: &str = "TF_DATA_DIR";
const AUTOMATION_VAR: &str = "TF_IN_AUTOMATION";
const INPUT_PREFIX: &str = "TF_VAR_";
const MASK: &str = "***";
const MASKED_FROM: usize = 4;
const INIT_LIMIT: Duration = Duration::from_secs(30 * 60);
const APPLY_LIMIT: Duration = Duration::from_secs(2 * 60 * 60);
const READ_LIMIT: Duration = Duration::from_secs(5 * 60);
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Terraform;
struct Module<'c, 'a> {
cx: &'c ToolCx<'a>,
data_dir: PathBuf,
state_file: PathBuf,
masks: Vec<String>,
extra: Vec<(String, String)>,
}
impl<'c, 'a> Module<'c, 'a> {
fn of(cx: &'c ToolCx<'a>) -> Module<'c, 'a> {
let mut masks: Vec<String> = cx
.env
.iter()
.filter(|(name, value)| name.starts_with(INPUT_PREFIX) && value.chars().count() >= MASKED_FROM)
.map(|(_, value)| value.clone())
.collect();
masks.sort_by_key(|v| std::cmp::Reverse(v.len()));
masks.dedup();
Module {
cx,
data_dir: cx.state_dir.join(DATA_DIR),
state_file: cx.state_dir.join(STATE_FILE),
masks,
extra: Vec::new(),
}
}
fn with_env(&self, vars: &[(&str, String)]) -> Module<'c, 'a> {
let mut extra = self.extra.clone();
extra.extend(vars.iter().map(|(k, v)| ((*k).to_owned(), v.clone())));
Module {
cx: self.cx,
data_dir: self.data_dir.clone(),
state_file: self.state_file.clone(),
masks: self.masks.clone(),
extra,
}
}
fn mask(&self, text: &str) -> String {
self.masks.iter().fold(text.to_owned(), |t, v| t.replace(v.as_str(), MASK))
}
fn say(&self, stream: Stream, line: &str) {
(self.cx.sink)(stream, &self.mask(line));
}
fn call<'s>(&'s self, limit: Duration, sink: &'s (dyn Fn(Stream, &str) + Send + Sync)) -> Call<'s> {
let mut call = self.cx.call(limit);
call.env.push((DATA_DIR_VAR.to_owned(), self.data_dir.display().to_string()));
call.env.push((AUTOMATION_VAR.to_owned(), "1".to_owned()));
call.env.extend(self.extra.iter().cloned());
call.sink = sink;
call
}
fn error<F: std::fmt::Display>(&self, step: &str, e: CliError<F>) -> Error {
match tool_error(step, e) {
Error::ToolFailed { step, reason } if sign_in::expired(&reason) => Error::CredentialsExpired {
step,
cloud: sign_in::cloud_named(&reason),
reason: self.mask(&reason),
},
Error::ToolFailed { step, reason } => Error::ToolFailed {
step,
reason: self.mask(&reason),
},
other => other,
}
}
fn state(&self) -> Result<StateAt<'_>> {
match tf::backend(&self.data_dir) {
Ok(Backend::Local) => Ok(StateAt::File(&self.state_file)),
Ok(Backend::Other(_)) => Ok(StateAt::Backend),
Err(reason) => Err(Error::ToolFailed {
step: "init".to_owned(),
reason,
}),
}
}
async fn init(&self) -> Result<StateAt<'_>> {
crate::store::remove(&self.cx.state_dir.join(LOCK_INFO))?;
let say = |s: Stream, l: &str| self.say(s, l);
tf::init(&self.call(INIT_LIMIT, &say)).await.map_err(|e| self.error("init", e))?;
if let Backend::Other(name) = tf::backend(&self.data_dir).map_err(|reason| Error::ToolFailed {
step: "init".to_owned(),
reason,
})? {
(self.cx.warn)(
WarningCode::SharedState,
&format!("the module keeps its state in its own `{name}` backend: every copy of it shares that state"),
);
}
self.state()
}
async fn apply(&self, step: &str, state: StateAt<'_>, change: tf::Change<'_>) -> std::result::Result<(), CliError<Failure>> {
let say = |s: Stream, l: &str| self.say(s, l);
let call = self.call(APPLY_LIMIT, &say);
let count = std::sync::Mutex::new(StepCount::new(0, None));
let steps = &self.cx.steps;
let applying = |moved: tf::Applying| {
let mut count = count.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
match moved {
tf::Applying::Planned(total) => count.total = Some(total),
tf::Applying::Applied => count.done += 1,
tf::Applying::Provisioning => {
steps.start(Phase::Ready, None);
return;
}
}
steps.count(Phase::Apply, None, *count);
};
let progress: &(dyn Fn(tf::Applying) + Send + Sync) = if change == tf::Change::Apply { &applying } else { &tf::unheard };
match tf::apply(&call, state, change, progress).await {
Err(CliError::Failed {
failure: Failure::StateLocked { id: Some(id) },
..
}) if state == StateAt::Backend => {
(self.cx.warn)(
WarningCode::Retrying,
&format!("the state's lock `{id}` is held by no run of this one: released, then `{step}` again"),
);
tf::force_unlock(&self.call(READ_LIMIT, &say), &id).await?;
tf::apply(&call, state, change, progress).await
}
done => done,
}
}
async fn shown(&self, state: StateAt<'_>) -> Result<tf::Shown> {
tf::show(&self.call(READ_LIMIT, &super::discard), state)
.await
.map_err(|e| self.error("show", e))
}
}
fn refused(what: &str) -> Error {
Error::Declined {
what: format!("{what} on a Terraform run: a module's machines are made and removed by its apply and destroy only"),
}
}
pub(crate) fn plugin_cache(config: &crate::RunnerConfig) -> PathBuf {
config.tf_plugin_cache.clone().unwrap_or_else(|| config.home.join("terraform-plugins"))
}
impl FormatDriver for Terraform {
fn ready_by_observation(&self, _failed_start: bool) -> bool {
false
}
async fn probe(&self, cx: &ToolCx<'_>) -> Result<()> {
let module = Module::of(cx);
let found = tf::version(&module.call(READ_LIMIT, &super::discard))
.await
.map_err(|e| module.error("probe", e))?;
super::unknown_version(cx, found.as_ref(), "terraform", tf::MIN_VERSION);
Ok(())
}
async fn up(&self, cx: &ToolCx<'_>) -> Result<()> {
required::refuse_unset(cx)?;
let module = Module::of(cx);
cx.steps.start(Phase::Init, None);
let state = module.init().await?;
cx.steps.done(Phase::Init, None);
cx.steps.start(Phase::Apply, None);
jump::through(&module, async |m| {
m.apply("apply", state, tf::Change::Apply).await.map_err(|e| m.error("apply", e))
})
.await?;
cx.steps.end(true);
Ok(())
}
async fn down(&self, cx: &ToolCx<'_>) -> Result<()> {
let module = Module::of(cx);
let state = module.init().await?;
jump::through(&module, async |m| m.destroy(state).await).await?;
module.forget(state)
}
fn park(&self, _cx: &ToolCx<'_>, _mode: Park) -> impl Future<Output = Result<()>> {
std::future::ready(Err(refused("parking")))
}
fn resume(&self, _cx: &ToolCx<'_>) -> impl Future<Output = Result<()>> {
std::future::ready(Err(refused("resuming")))
}
async fn update(&self, cx: &ToolCx<'_>) -> Result<()> {
self.up(cx).await
}
async fn machines(&self, cx: &ToolCx<'_>) -> Result<Vec<String>> {
let module = Module::of(cx);
let state = module.init().await?;
let say = |s: Stream, l: &str| module.say(s, l);
let planned = tf::plan(&module.call(APPLY_LIMIT, &say), state).await.map_err(|e| module.error("plan", e))?;
let held = module.shown(state).await?;
let removed = |at: &str| planned.iter().any(|p| p.address == at && p.action == tf::Action::Delete);
let mut names: Vec<String> = held
.managed
.iter()
.filter(|r| machines::is_vm(&r.kind) && !removed(&r.address))
.map(|r| machines::machine_name(&r.address, &r.kind))
.chain(
planned
.iter()
.filter(|p| machines::is_vm(&p.kind) && matches!(p.action, tf::Action::Create | tf::Action::Replace))
.map(|p| machines::machine_name(&p.address, &p.kind)),
)
.collect();
names.sort();
names.dedup();
Ok(names)
}
async fn reapply(&self, cx: &ToolCx<'_>, _change: &Change) -> Result<()> {
let module = Module::of(cx);
let state = module.init().await?;
let say = |s: Stream, l: &str| module.say(s, l);
tf::plan(&module.call(APPLY_LIMIT, &say), state).await.map_err(|e| module.error("plan", e))?;
jump::through(&module, async |m| {
m.apply("apply", state, tf::Change::Apply).await.map_err(|e| m.error("apply", e))
})
.await
}
fn provision(&self, _cx: &ToolCx<'_>, _machine: Option<&str>, _with: Option<&str>) -> impl Future<Output = Result<()>> {
std::future::ready(Err(refused("provisioning a machine again")))
}
fn attach(&self, _cx: &ToolCx<'_>, machine: &str) -> impl Future<Output = Result<()>> {
std::future::ready(Err(refused(&format!("starting `{machine}` on its own"))))
}
fn retire(&self, _cx: &ToolCx<'_>, machine: &str) -> impl Future<Output = Result<()>> {
std::future::ready(Err(refused(&format!("removing `{machine}` on its own"))))
}
async fn exec(&self, cx: &ToolCx<'_>, machine: &str, argv: &[String]) -> Result<Ran> {
console::exec(&Module::of(cx), machine, argv).await
}
async fn console(&self, cx: &ToolCx<'_>, machine: &str, user: Option<&str>) -> Result<ShellCommand> {
console::of(&Module::of(cx), machine, user).await
}
async fn observe(&self, cx: &ToolCx<'_>) -> Result<(Seen, RunState)> {
let module = Module::of(cx);
let state = module.state()?;
let held = module.shown(state).await?;
let outputs = match state {
StateAt::File(file) if !file.exists() => std::collections::BTreeMap::new(),
_ => tf::outputs(&module.call(READ_LIMIT, &super::discard), state)
.await
.map_err(|e| module.error("output", e))?,
};
let mut machines = machines_of(&held.managed);
with_named_addresses(&mut machines, &outputs);
screen::on_server(cx, &outputs, &held.managed, &mut machines).await?;
let seen = Seen {
machines,
outputs: outputs
.into_iter()
.map(|(name, o)| {
let output = Output {
value: text_of(&o.value),
sensitive: o.sensitive,
};
(name, output)
})
.collect(),
};
Ok((seen, run_state(&held)))
}
async fn found(&self, cx: &ToolCx<'_>) -> Result<Vec<Found>> {
let module = Module::of(cx);
let held = module.shown(module.state()?).await?;
Ok(held
.managed
.into_iter()
.filter_map(|r| {
let kind = if machines::is_vm(&r.kind) { ResourceKind::Vm } else { ResourceKind::Module };
Some(Found {
native_id: r.id?,
key: r.address,
kind,
lifetime: Lifetime::Run,
})
})
.collect())
}
async fn destroy_by_id(&self, cx: &ToolCx<'_>, key: &str, _kind: ResourceKind, native_id: &str) -> Result<()> {
let module = Module::of(cx);
let state = module.init().await?;
let held = module.shown(state).await?;
match held.managed.iter().find(|r| r.address == key) {
Some(r) if r.id.as_deref() == Some(native_id) => {}
Some(r) => {
return Err(Error::Unsupported {
what: format!(
"removing `{key}`'s object `{native_id}`: the state holds another one there (`{}`), and Terraform reaches an object through its address only",
r.id.as_deref().unwrap_or("no id")
),
});
}
None => {
let say = |s: Stream, l: &str| module.say(s, l);
match tf::import(&module.call(READ_LIMIT, &say), state, key, native_id).await {
Ok(()) => {}
Err(CliError::Failed {
failure: Failure::NoSuchObject,
..
}) => return Ok(()),
Err(e) => return Err(module.error("import", e)),
}
}
}
module
.apply("destroy", state, tf::Change::DestroyOne(key))
.await
.map_err(|e| module.error("destroy", e))
}
fn graphical(&self, _cx: &ToolCx<'_>, seen: &Seen, machine: &SeenMachine) -> impl Future<Output = Result<Option<crate::graphical::ConsoleOffer>>> {
std::future::ready(Ok(
screen::offer(machine).or_else(|| tunnelled::offer(&tunnelled::texts(&seen.outputs), machine))
))
}
async fn reach_graphical(&self, cx: &ToolCx<'_>, machine: &str) -> Result<crate::graphical::Console> {
let module = Module::of(cx);
let state = module.state()?;
let held = module.shown(state).await?;
let vm = vm_named(cx, &held, machine)?;
if screen::is_proxmox(Some(&vm.kind)) {
screen::reach(cx, machine).await
} else {
tunnelled::reach(&module, state, vm, machine).await
}
}
fn native_app(&self, _cx: &ToolCx<'_>, seen: &Seen) -> Option<crate::graphical::NativeApp> {
screen::app(seen)
}
async fn native_console(&self, cx: &ToolCx<'_>, machine: &str) -> Result<crate::graphical::NativeConsole> {
screen::native(cx, machine).await
}
async fn published(&self, cx: &ToolCx<'_>) -> Result<Vec<super::Published>> {
let module = Module::of(cx);
let out = tunnelled::outputs(&module, module.state()?).await?;
Ok(tunnelled::published(&out))
}
}
#[cfg(test)]
pub(crate) mod tests;