isothrum_runner/adopt.rs
1//! Adopting an existing Terraform deployment as a run ([`Runner::adopt`]): a deployment applied
2//! from a module outside the runner (by hand, by another tool, from a home that is gone), whose
3//! local state is in a folder of its own, becomes a run of that module, which `status`, `update`,
4//! `down` and the reaper then act on like any other.
5//!
6//! The deployment's state moves into the run's state folder (`terraform.tfstate`, and its
7//! `.backup` when there is one), and the run's record says it is up. Terraform's data folder stays
8//! behind: it names the old state's path as its backend, which a run's `init` would refuse to
9//! change without a prompt; `init` makes a fresh one. A state in a remote backend isn't adopted:
10//! pull it into a local file first (`terraform state pull > terraform.tfstate`).
11
12use std::path::{Path, PathBuf};
13
14use crate::Result;
15use crate::error::Error;
16use crate::name::RunName;
17use crate::project::Format;
18use crate::runner::Runner;
19use crate::state::RunState;
20use crate::store::RunRecord;
21
22/// An existing Terraform deployment to adopt as a run ([`Runner::adopt`]): where its local state
23/// is, and what the runner can't read from that state (where it is, when it expires).
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[non_exhaustive]
26pub struct Adoption {
27 /// The run it becomes.
28 pub name: RunName,
29 /// The folder holding its Terraform state.
30 pub state_from: PathBuf,
31 /// What the caller calls the place it is on (an account's id), as an operation's
32 /// `host_label`.
33 pub host_label: Option<String>,
34 /// When it may be removed, in seconds since the Unix epoch (what the reaper reads).
35 pub expires_at: Option<u64>,
36 /// When it was started (RFC 3339), when known (else the time it is taken over).
37 pub started_at: Option<String>,
38}
39
40impl Adoption {
41 /// The deployment whose state is in `state_from`, as run `name`: no place or expiry.
42 #[must_use]
43 pub fn new(name: RunName, state_from: impl Into<PathBuf>) -> Adoption {
44 Adoption {
45 name,
46 state_from: state_from.into(),
47 host_label: None,
48 expires_at: None,
49 started_at: None,
50 }
51 }
52
53 /// On the place the caller calls `label` (an operation's `host_label`).
54 #[must_use]
55 pub fn with_host_label(mut self, label: impl Into<String>) -> Adoption {
56 self.host_label = Some(label.into());
57 self
58 }
59
60 /// Expiring at `unix_seconds`.
61 #[must_use]
62 pub fn with_expires_at(mut self, unix_seconds: u64) -> Adoption {
63 self.expires_at = Some(unix_seconds);
64 self
65 }
66
67 /// Started at `rfc3339`.
68 #[must_use]
69 pub fn with_started_at(mut self, rfc3339: impl Into<String>) -> Adoption {
70 self.started_at = Some(rfc3339.into());
71 self
72 }
73}
74
75impl Runner {
76 /// Adopts the existing Terraform deployment `adoption` describes, one applied from the
77 /// module in folder `module` outside the runner, as a run of that module: its state moves
78 /// into the run's state folder, and the run is recorded as up; `status`, `update`, `down` and
79 /// the reaper then act on it like any other run. A run whose record an earlier `down` left
80 /// absent adopts one too, its record replaced. Once adopted, the old folder holds no state:
81 /// adopting it again is refused, never a second copy.
82 ///
83 /// # Errors
84 ///
85 /// Fails with `project_invalid` when `module` isn't a Terraform module; with `adopt_refused`
86 /// when the run already has a record that isn't absent or a state, or when the old folder
87 /// holds no state; with `locked` while another operation holds the run; and with `io` when a
88 /// file can't be moved or the record written (the state is put back then).
89 pub async fn adopt(&self, module: &Path, adoption: Adoption) -> Result<RunRecord> {
90 let run = self.open_as(module, Format::Terraform, Some(adoption.name.clone()))?;
91 let name = adoption.name.clone();
92 let refuse = |reason: String| Error::Adopt { run: name.to_string(), reason };
93 self.store.run_dir(&name)?;
94 let _lock = self.locks.acquire(&name, &self.store.lock_path(&name)).await?;
95 // A record an earlier `down` left absent holds nothing to lose: the run is taken over.
96 if self.store.record(&name)?.is_some_and(|r| r.state != RunState::Absent) {
97 return Err(refuse("the run has a record already".into()));
98 }
99 let moved = run.take_state(&adoption.state_from)?;
100 let mut record = RunRecord::fresh(name.clone(), run.project().dir.clone(), Format::Terraform);
101 record.host_label = adoption.host_label;
102 record.expires_at = adoption.expires_at;
103 record.started_at = Some(adoption.started_at.unwrap_or_else(|| crate::clock::rfc3339(self.config.clock.now())));
104 record.state = RunState::Ready;
105 if let Err(e) = self.store.save_adopted(&record) {
106 run.give_state_back(&adoption.state_from, &moved);
107 return Err(e);
108 }
109 Ok(record)
110 }
111}