Skip to main content

isothrum_runner/
runner.rs

1//! The engine: one per embedder. It holds the operations in flight, the per-run locks and the
2//! ports being pinned, never in process-wide statics, so two runners in one process never share
3//! them.
4
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, Mutex, PoisonError};
8
9use crate::Result;
10use crate::clock::{Clock, SystemClock};
11use crate::error::Error;
12use crate::events::EventLog;
13use crate::host_env::HostEnv;
14use crate::name::RunName;
15use crate::net::{HostPorts, LoopbackPorts, PortReservations};
16use crate::process::{ProcessRunner, SystemProcesses};
17use crate::project::platform::{Arch, HostOs, Protocol};
18use crate::project::{Format, Project};
19use crate::run::Running;
20use crate::state::{Desired, Op, Transition};
21use crate::store::{Home, OperationId, RunLocks, RunRecord};
22
23/// How a runner is built: its home, and the ports it reaches the world through. Start from
24/// [`RunnerConfig::new`] and set a field to change it (`config.processes = Arc::new(fake)`).
25#[derive(Clone)]
26#[non_exhaustive]
27pub struct RunnerConfig {
28    /// The runner's home (`runs/` under it). An app passes its data folder; the
29    /// `isothrum` command line uses `~/.isothrum`.
30    pub home: PathBuf,
31    /// Starts the tools.
32    pub processes: Arc<dyn ProcessRunner>,
33    /// The host's ports.
34    pub ports: Arc<dyn HostPorts>,
35    /// The time.
36    pub(crate) clock: Arc<dyn Clock>,
37    /// The host's operating system (it picks the providers a Vagrant run may use, and elevation).
38    pub host: HostOs,
39    /// The user's own Terraform plugin cache (`TF_PLUGIN_CACHE_DIR`), which the runs use as it
40    /// is; without one, they share one under the home.
41    pub(crate) tf_plugin_cache: Option<PathBuf>,
42    /// The variables of the runner's environment it hands on where they aren't inherited (the
43    /// proxies, the CA bundles: [`HostEnv`]).
44    pub(crate) host_env: HostEnv,
45}
46
47impl RunnerConfig {
48    /// A runner at `home` on this host: real processes (told the Docker CLI's config, see
49    /// [`SystemProcesses`]), the loopback, the system's clock, and what it needs of this process's
50    /// environment, read now (`TF_PLUGIN_CACHE_DIR`, the proxies, the CA bundles,
51    /// Terraform's CLI configuration, Vagrant's variables, `USERPROFILE`).
52    pub fn new(home: impl Into<PathBuf>) -> RunnerConfig {
53        RunnerConfig {
54            home: home.into(),
55            processes: Arc::new(SystemProcesses::default()),
56            ports: Arc::new(LoopbackPorts),
57            clock: Arc::new(SystemClock),
58            host: this_host(),
59            tf_plugin_cache: std::env::var_os("TF_PLUGIN_CACHE_DIR").filter(|d| !d.is_empty()).map(PathBuf::from),
60            host_env: HostEnv::capture(),
61        }
62    }
63}
64
65impl std::fmt::Debug for RunnerConfig {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        f.debug_struct("RunnerConfig")
68            .field("home", &self.home)
69            .field("host", &self.host)
70            .finish_non_exhaustive()
71    }
72}
73
74/// This build's host operating system.
75#[must_use]
76pub fn this_host() -> HostOs {
77    if cfg!(windows) {
78        HostOs::Windows
79    } else if cfg!(target_os = "macos") {
80        HostOs::Macos
81    } else {
82        HostOs::Linux
83    }
84}
85
86/// This build's CPU architecture, as Vagrant names a box's build (an x86-64 build reads as
87/// `amd64`, an ARM one as `arm64`).
88#[must_use]
89pub fn this_arch() -> Arch {
90    if cfg!(target_arch = "aarch64") { Arch::Arm64 } else { Arch::Amd64 }
91}
92
93/// The runner.
94pub struct Runner {
95    pub(crate) config: RunnerConfig,
96    pub(crate) store: Home,
97    pub(crate) locks: RunLocks,
98    flight: Mutex<BTreeMap<RunName, InFlight>>,
99    /// The host ports its runs hold while they start, reserved across the home's processes.
100    reservations: PortReservations,
101}
102
103/// The variable every tool of a run gets its run's key in ([`copy_key`]): Isothrum's, set for
104/// every command of every driver, for a project that names what it makes on the host after it
105/// (two copies of one project then never share a VM, a network or a domain name).
106pub const RUN_KEY_VAR: &str = "ISOTHRUM_RUN_KEY";
107
108/// The key of run `name`'s copy on the runner whose home is `home`: six lowercase letters and
109/// digits (FNV-1a of the home and the name, in base 36), the same at every operation of the run.
110/// Every tool of the run gets it in [`RUN_KEY_VAR`]; an embedder hands it on under the name a
111/// project reads (`RunOptions::with_env`). The runner's clean-up only ever takes a VM whose name
112/// carries it. For an embedder that finds its runs' VMs by name.
113#[must_use]
114pub fn copy_key(home: &Path, name: &RunName) -> String {
115    let seed = format!("{}\n{name}", home.display());
116    let mut hash = seed.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193));
117    let mut digits = Vec::with_capacity(7);
118    while hash > 0 {
119        digits.push(char::from_digit(hash % 36, 36).unwrap_or('0'));
120        hash /= 36;
121    }
122    digits.resize(digits.len().max(6), '0');
123    digits.iter().take(6).rev().collect()
124}
125
126impl Runner {
127    /// A runner with `config`; its home (with its missing parents) and the home's `runs/` folder
128    /// are created, owner-only (on Windows, a home outside the user's profile gets an owner-only
129    /// DACL), and its store (`state.db`) opened: made, migrated, or imported from a 2.x home's
130    /// files ([`crate::store::Store::open`]).
131    ///
132    /// # Errors
133    ///
134    /// Fails with `io` when the home can't be created or made owner-only (on Windows, its owner
135    /// can't be read or its DACL set), or its `runs/` folder can't be created; as
136    /// [`crate::store::Store::open`] does for the store.
137    pub fn new(mut config: RunnerConfig) -> Result<Runner> {
138        // A relative home is resolved once, here: the tools run in other folders (the run's, its
139        // state folder) and would read it against theirs.
140        config.home = std::path::absolute(&config.home).map_err(Error::io(&config.home, "made absolute"))?;
141        let store = Home::open(&config.home, config.host_env.get("USERPROFILE").map(Path::new))?;
142        let reservations = PortReservations::new(Arc::clone(&config.ports), Arc::clone(store.db()));
143        Ok(Runner {
144            config,
145            store,
146            locks: RunLocks::default(),
147            flight: Mutex::default(),
148            reservations,
149        })
150    }
151
152    /// The project in folder `dir` (a file in it names its folder), of the format its files show
153    /// ([`Format::detect`]), as run `name` (default: the folder's name, made a run name). Nothing
154    /// runs: a folder that isn't a project is refused before any tool.
155    ///
156    /// # Errors
157    ///
158    /// `project_invalid` when the folder holds no format's files, or several; `run_name` when the
159    /// name can't name a run.
160    pub fn open(&self, dir: &Path, name: Option<RunName>) -> Result<Running<'_>> {
161        self.open_project(dir, None, name)
162    }
163
164    /// The project in folder `dir`, of format `format` (the one to run when its files show
165    /// several), as run `name` ([`Runner::open`]).
166    ///
167    /// # Errors
168    ///
169    /// `project_invalid` when the folder holds no `format` files; `run_name` when the name can't
170    /// name a run.
171    pub fn open_as(&self, dir: &Path, format: Format, name: Option<RunName>) -> Result<Running<'_>> {
172        self.open_project(dir, Some(format), name)
173    }
174
175    fn open_project(&self, dir: &Path, format: Option<Format>, name: Option<RunName>) -> Result<Running<'_>> {
176        let dir = if dir.is_file() { dir.parent().unwrap_or(dir) } else { dir };
177        let project = Project::open(dir, format)?;
178        let name = match name {
179            Some(name) => name,
180            None => RunName::from_folder(&project.dir)?,
181        };
182        Ok(Running::new(self, project, name))
183    }
184
185    /// Recorded run `name`, opened again from the folder and format it was started with.
186    ///
187    /// # Errors
188    ///
189    /// `not_running` when no run of that name is recorded; as [`Runner::open_as`] for its folder.
190    pub fn reopen(&self, name: &RunName) -> Result<Running<'_>> {
191        let record = self.store.record(name)?.ok_or_else(|| Error::NotRunning { run: name.to_string() })?;
192        self.open_as(&record.project, record.format, Some(name.clone()))
193    }
194
195    /// Every recorded run, with the state its last operation left it in. Reads files only.
196    ///
197    /// # Errors
198    ///
199    /// Fails with `io` when a record can't be read.
200    pub fn runs(&self) -> Result<Vec<RunRecord>> {
201        self.store.records()
202    }
203
204    /// Run `name`'s record, with the state its last operation left it in; `None` for a run never
205    /// recorded. Reads one file: an embedder asking after one run doesn't fail on another run's
206    /// record it can't read, as it would reading [`Runner::runs`].
207    ///
208    /// # Errors
209    ///
210    /// Fails with `io` when the record is there and can't be read.
211    pub fn run_record(&self, name: &RunName) -> Result<Option<RunRecord>> {
212        self.store.record(name)
213    }
214
215    /// The key of run `name`'s copy on this runner ([`copy_key`]).
216    #[must_use]
217    pub fn copy_key(&self, name: &RunName) -> String {
218        copy_key(&self.config.home, name)
219    }
220
221    /// Run `name`'s logged events, oldest first, with how many of its lines it couldn't read as
222    /// one (written by another version of the runner, or cut short).
223    ///
224    /// # Errors
225    ///
226    /// Fails with `io` when the run's event log can't be read.
227    pub fn events(&self, name: &RunName) -> Result<EventLog> {
228        self.store.events(name)
229    }
230
231    /// The public half of the runner's SSH key, one line: what an embedder authorizes where a
232    /// run's SSH goes (a Proxmox node it jumps through). The key is made when the runner has none.
233    ///
234    /// # Errors
235    ///
236    /// Fails with `tool_missing` when `ssh-keygen` isn't installed, `tool_failed` or `timeout`
237    /// when it can't make the key, and `io` when the runner's `ssh/` folder can't be created or
238    /// its public key can't be read.
239    pub async fn ssh_public_key(&self) -> Result<String> {
240        crate::ssh::ensure_key(self.config.processes.as_ref(), &self.config.home).await
241    }
242
243    /// The operations in flight in this runner.
244    pub(crate) fn in_flight(&self) -> Vec<(RunName, Op)> {
245        self.flight
246            .lock()
247            .unwrap_or_else(PoisonError::into_inner)
248            .iter()
249            .map(|(n, f)| (n.clone(), f.op))
250            .collect()
251    }
252
253    /// Marks `op` on `name`, journaled as `id`, in flight until the guard drops.
254    pub(crate) fn enter(&self, name: &RunName, op: Op, id: OperationId) -> Flight<'_> {
255        let flight = InFlight { op, id, begun: None };
256        self.flight.lock().unwrap_or_else(PoisonError::into_inner).insert(name.clone(), flight);
257        Flight {
258            runner: self,
259            name: name.clone(),
260        }
261    }
262
263    /// The operation in flight on `name`, if any.
264    pub(crate) fn op_of(&self, name: &RunName) -> Option<Op> {
265        self.flight.lock().unwrap_or_else(PoisonError::into_inner).get(name).map(|f| f.op)
266    }
267
268    /// The journal id of the operation in flight on `name`, if any.
269    pub(crate) fn operation_of(&self, name: &RunName) -> Option<OperationId> {
270        self.flight.lock().unwrap_or_else(PoisonError::into_inner).get(name).map(|f| f.id)
271    }
272
273    /// The transition the operation in flight on `name` began with, once it began acting, and what
274    /// was wanted of the run before it.
275    pub(crate) fn begun(&self, name: &RunName) -> Option<(Transition, Desired)> {
276        self.flight.lock().unwrap_or_else(PoisonError::into_inner).get(name).and_then(|f| f.begun)
277    }
278
279    /// Notes that the operation in flight on `name` began acting with `transition`, `before` wanted
280    /// of the run until then.
281    pub(crate) fn note_begun(&self, name: &RunName, transition: Transition, before: Desired) {
282        if let Some(f) = self.flight.lock().unwrap_or_else(PoisonError::into_inner).get_mut(name) {
283            f.begun = Some((transition, before));
284        }
285    }
286
287    /// Frees every port `name` reserved.
288    pub(crate) fn release(&self, name: &RunName) {
289        self.reservations.release(name);
290    }
291
292    /// A free loopback port over `protocol` reserved for `name` ([`PortReservations::pick_reserved`]).
293    ///
294    /// # Errors
295    ///
296    /// The loopback couldn't be bound.
297    pub(crate) fn pick_reserved(&self, name: &RunName, protocol: Protocol) -> std::io::Result<Option<crate::net::HeldPort>> {
298        self.reservations.pick_reserved(name, protocol, self.operation_of(name))
299    }
300}
301
302impl Runner {
303    /// A free loopback port over `protocol` no other run holds, not reserved
304    /// ([`PortReservations::pick_unreserved`]).
305    ///
306    /// # Errors
307    ///
308    /// The loopback couldn't be bound.
309    pub(crate) fn pick_unreserved(&self, name: &RunName, protocol: Protocol) -> std::io::Result<Option<crate::net::HeldPort>> {
310        self.reservations.pick_unreserved(name, protocol)
311    }
312
313    /// Claims `ports` for run `name`'s operation ([`PortReservations::claim`]).
314    ///
315    /// # Errors
316    ///
317    /// Fails with `port_in_use` at the first port reserved elsewhere or already bound.
318    pub(crate) fn claim_ports(&self, name: &RunName, ports: impl IntoIterator<Item = (crate::port::HostPort, Protocol)>) -> Result<()> {
319        self.reservations.claim(name, ports, self.operation_of(name))
320    }
321}
322
323impl std::fmt::Debug for Runner {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        f.debug_struct("Runner")
326            .field("config", &self.config)
327            .field("in_flight", &self.in_flight())
328            .finish_non_exhaustive()
329    }
330}
331
332/// An operation in flight: what it is, its journal id, and the transition it began acting with
333/// (with what was wanted of the run before it).
334#[derive(Debug, Clone, Copy)]
335struct InFlight {
336    op: Op,
337    id: OperationId,
338    begun: Option<(Transition, Desired)>,
339}
340
341/// An operation in flight; cleared when dropped, whatever the outcome (an error, a cancellation).
342pub(crate) struct Flight<'r> {
343    runner: &'r Runner,
344    name: RunName,
345}
346
347impl Drop for Flight<'_> {
348    fn drop(&mut self) {
349        self.runner.flight.lock().unwrap_or_else(PoisonError::into_inner).remove(&self.name);
350        self.runner.release(&self.name);
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    fn runner(home: &Path) -> Runner {
359        Runner::new(RunnerConfig::new(home)).unwrap()
360    }
361
362    #[test]
363    fn a_copy_key_is_made_of_its_home_and_its_name() {
364        let name = RunName::new("web-vm").unwrap();
365        assert_eq!(copy_key(Path::new("/h"), &name), "r7hhts");
366        assert_eq!(copy_key(Path::new("/other"), &name), "1imar2", "another home, another key");
367        assert_eq!(copy_key(Path::new("/h"), &RunName::new("web-vm-2").unwrap()), "yjcqv3", "another run");
368        let key = copy_key(Path::new("/h"), &name);
369        assert_eq!(key.len(), 6, "{key}");
370        isothrum_test_support::assert_every!(key.bytes(), |b: &u8| b.is_ascii_lowercase() || b.is_ascii_digit());
371    }
372
373    #[test]
374    fn a_relative_home_is_made_absolute_once() {
375        // Refs #131: a relative home was kept as given, and the tools, run in other folders,
376        // read it against theirs (a Terraform state under the project's folder, no SSH key found).
377        let dir = tempfile::tempdir_in(".").unwrap();
378        let relative = PathBuf::from(dir.path().file_name().unwrap());
379        let r = runner(&relative);
380        assert!(r.config.home.is_absolute(), "{}", r.config.home.display());
381        assert_eq!(r.config.home, std::env::current_dir().unwrap().join(&relative));
382        assert!(r.store.db().path().is_absolute());
383    }
384
385    #[test]
386    fn two_runners_share_nothing() {
387        // Regression: the in-flight map and the port reservations kept in statics let two
388        // embedders (or two tests) in one process see each other's operations and ports.
389        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
390        let (a, b) = (runner(a.path()), runner(b.path()));
391        let name = RunName::new("demo").unwrap();
392        let flight = a.enter(&name, Op::Up, crate::store::OperationId(1));
393        assert!(a.reservations.reserve(&name, crate::port::HostPort::new(8080), Protocol::Tcp, None));
394        assert_eq!(a.in_flight(), [(name.clone(), Op::Up)]);
395        assert_eq!(b.in_flight(), []);
396        assert!(
397            b.reservations
398                .reserve(&RunName::new("other").unwrap(), crate::port::HostPort::new(8080), Protocol::Tcp, None),
399            "b's ports aren't a's"
400        );
401        drop(flight);
402        assert_eq!(a.in_flight(), []);
403    }
404}