isothrum_runner/adopt.rs
1//! Adopting an existing Terraform deployment as a run ([`Runner::adopt`]): a deployment applied
2//! from a run manifest's module outside the runner (by hand, by another tool, from a home that is
3//! gone), whose local state is in a folder of its own, becomes a run of that manifest, which
4//! `status`, `update`, `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, with the params it was
8//! applied with: a later `down` replays them (the region it was created in, never the caller's
9//! current one). Terraform's data folder stays behind: it names the old state's path as its
10//! backend, which a run's `init` would refuse to change without a prompt; `init` makes a fresh
11//! one. A state in a remote backend isn't adopted: pull it into a local file first
12//! (`terraform state pull > terraform.tfstate`).
13
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16
17use isoloom_manifest::{Driver, SetBy};
18
19use crate::Result;
20use crate::error::Error;
21use crate::manifest::{LoadedManifest, load_manifest};
22use crate::name::RunName;
23use crate::runner::Runner;
24use crate::slot::Asked;
25use crate::state::RunState;
26use crate::store::RunRecord;
27
28/// The state file a deployment must hold to be taken over.
29const STATE: &str = crate::driver::terraform::state::STATE_FILE;
30
31/// The files that move, the state first (the only one required).
32const MOVED: [&str; 2] = [STATE, crate::driver::terraform::state::BACKUP_FILE];
33
34/// An existing Terraform deployment to adopt as a run ([`Runner::adopt`]): where its local state
35/// is, and what the runner can't read from that state (the params it was applied with, where it
36/// is, when it expires).
37#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct Adoption {
40 /// The run it becomes.
41 pub name: RunName,
42 /// The folder holding its Terraform state.
43 pub state_from: PathBuf,
44 /// The params it was applied with (the region, the account's profile or project): only the
45 /// manifest's params a caller sets (`set_by: embedder`) are kept.
46 pub params: BTreeMap<String, String>,
47 /// What the caller calls the place it is on (an account's id), as an operation's
48 /// `host_label`.
49 pub host_label: Option<String>,
50 /// When it stops itself, in seconds since the Unix epoch.
51 pub expires_at: Option<u64>,
52 /// When it was started (RFC 3339), when known (else the time it is taken over).
53 pub started_at: Option<String>,
54 /// Its slot on its place (`${run.slot}`), for a manifest that names one: the one it was
55 /// applied with. Unset, the place's lowest free slot.
56 pub slot: Option<u8>,
57}
58
59impl Adoption {
60 /// The deployment whose state is in `state_from`, as run `name`: no param, place or expiry.
61 #[must_use]
62 pub fn new(name: RunName, state_from: impl Into<PathBuf>) -> Adoption {
63 Adoption {
64 name,
65 state_from: state_from.into(),
66 params: BTreeMap::new(),
67 host_label: None,
68 expires_at: None,
69 started_at: None,
70 slot: None,
71 }
72 }
73
74 /// With the params it was applied with: a later operation replays them, a param left out
75 /// taking its default, and one the manifest requires with none refused.
76 #[must_use]
77 pub fn with_params(mut self, params: impl IntoIterator<Item = (String, String)>) -> Adoption {
78 self.params.extend(params);
79 self
80 }
81
82 /// On the place the caller calls `label` (an operation's `host_label`).
83 #[must_use]
84 pub fn with_host_label(mut self, label: impl Into<String>) -> Adoption {
85 self.host_label = Some(label.into());
86 self
87 }
88
89 /// Stopping itself at `unix_seconds`.
90 #[must_use]
91 pub fn with_expires_at(mut self, unix_seconds: u64) -> Adoption {
92 self.expires_at = Some(unix_seconds);
93 self
94 }
95
96 /// Started at `rfc3339`.
97 #[must_use]
98 pub fn with_started_at(mut self, rfc3339: impl Into<String>) -> Adoption {
99 self.started_at = Some(rfc3339.into());
100 self
101 }
102
103 /// Applied in slot `slot` of its place (`${run.slot}`, 1 to 99): the run keeps it, as its
104 /// resources are named after it; [`Runner::adopt`] refuses one out of range or another run on
105 /// the place holds. Without it, the run takes the lowest free one.
106 #[must_use]
107 pub fn with_slot(mut self, slot: u8) -> Adoption {
108 self.slot = Some(slot);
109 self
110 }
111}
112
113impl Runner {
114 /// Adopts the existing Terraform deployment `adoption` describes, one applied from the
115 /// module of the manifest at `manifest` outside the runner, as a run of that manifest: its
116 /// state moves into the run's state folder, and the run is recorded as up, with the
117 /// manifest's params among `adoption.params`; `status`, `update`, `down` and the reaper then
118 /// act on it like any other run. A run whose record an earlier `down` left absent (its state
119 /// gone with it) adopts one too, its record replaced. Once adopted, the old folder holds no
120 /// state: adopting it again is refused, never a second copy.
121 ///
122 /// ```no_run
123 /// # async fn adopt(runner: &isothrum_runner::Runner) -> isothrum_runner::Result<()> {
124 /// use isothrum_runner::{Adoption, RunName};
125 ///
126 /// // A deployment applied by hand from `.isoloom/cloud-vm/aws/`, its state in `old/`.
127 /// let adoption = Adoption::new(RunName::new("shop")?, "old")
128 /// .with_params([("region".to_owned(), "eu-west-3".to_owned())])
129 /// .with_started_at("2026-10-15T11:00:00Z");
130 /// let record = runner.adopt(".isoloom/cloud-vm/aws/run.json".as_ref(), adoption).await?;
131 /// // From now on, `runner.open(…)?.down(…)` destroys it as it was applied.
132 /// # drop(record);
133 /// # Ok(())
134 /// # }
135 /// ```
136 ///
137 /// # Errors
138 ///
139 /// Fails with `adopt_refused` when the manifest isn't a Terraform one, when the run already
140 /// has a record that isn't absent or a state, when the old folder holds no state, or when the
141 /// slot it was applied in ([`Adoption::with_slot`]) is out of range or another run on its
142 /// place holds it; with `slots_full` when it names no slot and none is free on its place;
143 /// with `locked` while another operation holds the run or another process picks a slot past
144 /// the wait; with `manifest_invalid` or `io` when the manifest can't be read; and with `io`
145 /// when a file can't be moved or the record written (the state is put back then).
146 pub async fn adopt(&self, manifest: &Path, adoption: Adoption) -> Result<RunRecord> {
147 let loaded = load_manifest(manifest)?;
148 let name = adoption.name.clone();
149 let refuse = |reason: String| Error::Adopt { run: name.to_string(), reason };
150 if loaded.manifest.driver != Driver::Terraform {
151 return Err(refuse(format!("its manifest's driver is {}, not terraform", loaded.manifest.driver.id())));
152 }
153 let to = self.store.run_dir(&name)?;
154 let _lock = self.locks.acquire(&name, &self.store.lock_path(&name)).await?;
155 // A record an earlier `down` left absent holds nothing to lose: the run is taken over.
156 if self.store.record(&name)?.is_some_and(|r| r.state != RunState::Absent) {
157 return Err(refuse("the run has a record already".into()));
158 }
159 if to.join(STATE).exists() {
160 return Err(refuse("the run has a Terraform state already".into()));
161 }
162 if !adoption.state_from.join(STATE).is_file() {
163 return Err(refuse(format!("{} holds no {STATE}", adoption.state_from.display())));
164 }
165 let from = adoption.state_from.clone();
166 // The slot is picked and recorded under the home's slots lock, as a start's is.
167 let asked = Asked::Applied(adoption.slot);
168 let slot = crate::slot::choose(&self.store, &loaded.manifest, &name, adoption.host_label.as_deref(), asked).await?;
169 let mut record = self.adopted(loaded, adoption);
170 slot.keep_in(&mut record);
171 let moved = move_files(&from, &to)?;
172 if let Err(e) = self.store.save(&record) {
173 put_back(&moved, &from, &to);
174 return Err(e);
175 }
176 drop(slot);
177 Ok(record)
178 }
179}
180
181impl Runner {
182 /// The record of `adoption`, a run of `loaded`: up, with the manifest's params among its own;
183 /// its slot is kept in it apart ([`crate::slot::choose`]).
184 fn adopted(&self, loaded: LoadedManifest, adoption: Adoption) -> RunRecord {
185 let manifest = &loaded.manifest;
186 let mut record = RunRecord::fresh(adoption.name, loaded.path, manifest.target, manifest.driver);
187 record.params = adoption
188 .params
189 .into_iter()
190 .filter(|(k, _)| manifest.params.iter().any(|p| p.name.as_str() == k && p.set_by == SetBy::Embedder))
191 .collect();
192 record.cloud = manifest.cloud;
193 record.host_label = adoption.host_label;
194 record.expires_at = adoption.expires_at;
195 // A recorded start is what makes a later operation replay the params.
196 record.started_at = Some(adoption.started_at.unwrap_or_else(|| crate::clock::rfc3339(self.config.clock.now())));
197 record.state = RunState::Ready;
198 record
199 }
200}
201
202/// Moves each of [`MOVED`] that `from` holds into `to`; the names moved. A failure puts back
203/// what moved before it.
204fn move_files(from: &Path, to: &Path) -> Result<Vec<&'static str>> {
205 let mut moved = Vec::new();
206 for name in MOVED {
207 let source = from.join(name);
208 if !source.is_file() {
209 continue;
210 }
211 if let Err(e) = move_file(&source, &to.join(name)) {
212 put_back(&moved, from, to);
213 return Err(Error::io(&source, "moved")(e));
214 }
215 moved.push(name);
216 }
217 Ok(moved)
218}
219
220/// Moves `from` to `to`: a rename, else, only when they are on different file systems, a copy
221/// then a removal ([`copy_then_remove`]). Any other failure to rename is the error.
222fn move_file(from: &Path, to: &Path) -> std::io::Result<()> {
223 match std::fs::rename(from, to) {
224 Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => copy_then_remove(from, to),
225 renamed => renamed,
226 }
227}
228
229/// Copies `from` to `to`, then removes `from`; when `from` can't be removed, the copy goes too,
230/// so the file is never in both places.
231fn copy_then_remove(from: &Path, to: &Path) -> std::io::Result<()> {
232 std::fs::copy(from, to)?;
233 std::fs::remove_file(from).inspect_err(|_| {
234 if let Err(e) = std::fs::remove_file(to) {
235 tracing::warn!(error = %e, file = %to.display(), "a copy of a taken-over state couldn't be removed");
236 }
237 })
238}
239
240/// Moves `names` back from `to` to `from`, as best it can (an error is already on its way).
241fn put_back(names: &[&str], from: &Path, to: &Path) {
242 for name in names {
243 if let Err(e) = move_file(&to.join(name), &from.join(name)) {
244 tracing::warn!(error = %e, file = name, "a taken-over state couldn't be put back");
245 }
246 }
247}
248
249#[cfg(test)]
250mod tests;