pub(crate) mod argv;
mod console;
mod copy_module;
pub(crate) mod gone;
mod guest;
pub(crate) mod state;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use isoloom_manifest::{Action, ExpiryUnit, Machine, Step, TerraformIdentity};
use super::{Driver, GuestUse, Observed};
use crate::console::ShellCommand;
use crate::executor::Cx;
use crate::process::ProcessSpec;
use crate::status::{MachineState, MachineStatus, PublishedPort};
use crate::vars::PortKey;
use crate::{Error, Result, RunnerConfig};
const LOCK_FILE: &str = ".terraform.tfstate.lock.info";
const FORGOTTEN: [&str; 4] = [state::STATE_FILE, state::BACKUP_FILE, ".terraform", copy_module::COPY];
const PUBLISHED: &str = "published";
#[derive(Debug, Clone)]
pub(crate) struct Terraform {
identity: TerraformIdentity,
}
impl Terraform {
pub(crate) fn new(identity: TerraformIdentity) -> Terraform {
Terraform { identity }
}
fn module(&self, cx: &Cx<'_>) -> PathBuf {
cx.run.dir().join(self.identity.module.as_str())
}
pub(crate) fn gone(&self, cx: &Cx<'_>) -> Result<Vec<gone::Gone>> {
if self.identity.gone.is_empty() {
return Ok(Vec::new());
}
let dir = cx.state_dir();
Ok(state::read_json(dir)?.map(|s| gone::in_state(&s, &self.identity.gone)).unwrap_or_default())
}
pub(crate) async fn forget_gone(&self, cx: &Cx<'_>, list: &str, step: &Step, seen: &std::collections::BTreeSet<String>) -> Result<bool> {
gone::forget(cx, list, step, self.gone(cx)?, seen).await
}
fn checked_module(&self, cx: &Cx<'_>) -> Result<PathBuf> {
match copied_from(cx)? {
Some((at, from)) => copy_module::inside_project(cx.run.dir(), &at, &from),
None => Ok(self.module(cx)),
}
}
}
pub(crate) fn plugin_cache(config: &RunnerConfig) -> PathBuf {
config.tf_plugin_cache.clone().unwrap_or_else(|| config.home.join("terraform-plugins"))
}
fn copy_module(cx: &Cx<'_>, list: &str, step: &Step) -> Result<()> {
let (at, with) = (crate::executor::plan::at(list, step), super::with_of(step));
let (from, when) = (cx.vars.with_arg(with, &at, "from")?, cx.vars.with_arg(with, &at, "when")?);
copy_module::run(cx, &at, from.as_deref(), when.as_deref())
}
impl Driver for Terraform {
fn preflight(&self, cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
let checked = self.checked_module(cx).and_then(|module| {
if copy_module::has_terraform_files(&module)? {
return Ok(());
}
Err(Error::Malformed {
at: format!("the Terraform module {}", module.display()),
reason: "it has no `.tf` file: generate the run's files again".to_owned(),
})
});
std::future::ready(checked)
}
fn prepare(&self, cx: &Cx<'_>) -> Result<()> {
let config = &cx.run.runner.config;
if config.tf_plugin_cache.is_some() {
return Ok(());
}
let cache = plugin_cache(config);
crate::store::create_dir(&cache)
}
fn env(&self, cx: &Cx<'_>) -> Result<Vec<(String, String)>> {
let cache = plugin_cache(&cx.run.runner.config);
let mut env = vec![("TF_PLUGIN_CACHE_DIR".to_owned(), cache.display().to_string())];
env.extend(expiry_var(cx));
Ok(env)
}
fn action(&self, cx: &Cx<'_>, list: &str, step: &Step, action: Action) -> impl Future<Output = Result<()>> {
let state_dir = cx.state_dir();
let done = match action {
Action::TerraformClearLock => remove(&state_dir.join(LOCK_FILE)),
Action::TerraformReadState => state::read(state_dir).map(drop),
Action::TerraformCopyModule => copy_module(cx, list, step),
other => Err(super::foreign_action(isoloom_manifest::Driver::Terraform, step, other)),
};
std::future::ready(done)
}
async fn observe(&self, cx: &Cx<'_>) -> Result<Observed> {
let tf = state::read(cx.state_dir())?;
let mut seen = observed(cx.run.manifest(), &tf);
if tf.resources {
on_server(cx, &mut seen).await?;
}
Ok(seen)
}
fn before_down(&self, _cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
fn before_update(&self, _cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
fn after_update(&self, _cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
fn after_down(&self, cx: &Cx<'_>) -> impl Future<Output = Result<()>> {
let state_dir = cx.state_dir();
std::future::ready(FORGOTTEN.iter().try_for_each(|f| remove(&state_dir.join(f))))
}
fn restart(&self, _cx: &Cx<'_>, _machine: &Machine, _id: &str) -> impl Future<Output = Result<()>> {
std::future::ready(Ok(()))
}
fn attach(&self, _cx: &Cx<'_>, _machine: &Machine, _image: Option<&str>, _network: Option<&str>) -> impl Future<Output = Result<()>> {
std::future::ready(Err(on_demand("hot-adding")))
}
fn retire(&self, _cx: &Cx<'_>, machine: &Machine) -> impl Future<Output = Result<()>> {
std::future::ready(if machine.on_demand {
Err(on_demand("taking out"))
} else if super::is_compose_service(machine) {
Err(super::no_vm_for("taking out", machine))
} else {
Ok(())
})
}
fn console_command(&self, cx: &Cx<'_>, machine: &Machine, user: Option<&str>) -> Result<ShellCommand> {
console::command(cx, machine, user)
}
fn in_guest(&self, cx: &Cx<'_>, _vm: &Machine, script: &str, use_: GuestUse) -> Result<ProcessSpec> {
console::in_guest(cx, script, use_)
}
}
fn on_demand(what: &str) -> Error {
Error::Unsupported {
what: format!("{what} an on-demand access machine on a server or cloud target"),
}
}
fn observed(manifest: &isoloom_manifest::Manifest, tf: &state::TfState) -> Observed {
let machine_state = match (tf.resources, tf.tainted) {
(false, _) => MachineState::Absent,
(true, true) => MachineState::Unhealthy,
(true, false) => MachineState::Running,
};
let published = published(tf);
let machines = manifest
.machines
.iter()
.map(|m| MachineStatus {
name: m.name.to_string(),
role: m.role,
state: machine_state.clone(),
addresses: super::static_addresses(m),
published: m
.ports
.iter()
.filter_map(|p| {
let host_port = *published.get(&(m.name.to_string(), p.name.to_string()))?;
Some(PublishedPort {
port: p.port.get(),
protocol: p.kind.transport(),
host_port,
})
})
.collect(),
console: None,
})
.collect();
Observed {
machines,
published,
hosts: BTreeMap::new(),
outputs: tf.outputs.clone(),
sensitive: tf.sensitive.clone(),
busy: None,
}
}
async fn on_server(cx: &Cx<'_>, seen: &mut Observed) -> Result<()> {
let mut vars = cx.vars.clone();
let read = crate::outputs::read(cx.run.manifest(), &vars, &seen.outputs, &seen.sensitive);
crate::outputs::bind(&mut vars, &read.values);
let states = crate::graphical::proxmox_vm_states(cx, &vars).await?;
for m in &mut seen.machines {
match states.get(&m.name) {
Some(MachineState::Running) | None => {}
Some(state) => m.state = state.clone(),
}
}
Ok(())
}
fn published(tf: &state::TfState) -> BTreeMap<PortKey, u16> {
let mut out = BTreeMap::new();
for (key, address) in tf.maps.get(PUBLISHED).into_iter().flatten() {
if let (Some((machine, port)), Some(host_port)) = (key.split_once('/'), state::port_of(address)) {
out.insert((machine.to_owned(), port.to_owned()), host_port);
} else {
tracing::warn!(
key,
address,
"a `published` entry isn't `<machine>/<port>` at `<address>:<port>`: it is left out"
);
}
}
out
}
fn copied_from(cx: &Cx<'_>) -> Result<Option<(String, String)>> {
for step in &cx.run.manifest().lifecycle.up {
if let isoloom_manifest::Run::Action {
action: Action::TerraformCopyModule,
with,
} = &step.run
&& let at = crate::executor::plan::at(crate::executor::UP, step)
&& let Some(from) = cx.vars.with_arg(with, &at, "from")?
{
return Ok(Some((at, from)));
}
}
Ok(None)
}
fn expiry_var(cx: &Cx<'_>) -> Option<(String, String)> {
let expiry = cx.run.manifest().expiry.as_ref()?;
let at = cx.expires_at?;
let value = match expiry.unit {
ExpiryUnit::UnixSeconds => at.to_string(),
};
Some((format!("TF_VAR_{}", expiry.tf_var), value))
}
fn remove(path: &Path) -> Result<()> {
crate::store::remove(path)
}
#[cfg(test)]
mod tests;