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::ffi::OsString;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex, PoisonError};
9
10use isoloom_manifest::{Arch, HostOs, Protocol};
11
12use crate::Result;
13use crate::clock::{Clock, SystemClock};
14use crate::encoding::wire_name;
15use crate::error::Error;
16use crate::events::EventLog;
17use crate::host_env::HostEnv;
18use crate::manifest::load_manifest;
19use crate::name::RunName;
20use crate::net::{HostPorts, LoopbackPorts};
21use crate::process::{ProcessRunner, SystemProcesses};
22use crate::run::Running;
23use crate::state::Op;
24use crate::store::{RunLocks, RunRecord, Store};
25
26/// How a runner is built: its home, and the ports it reaches the world through. Start from
27/// [`RunnerConfig::new`] and set a field to change it (`config.processes = Arc::new(fake)`).
28#[derive(Clone)]
29#[non_exhaustive]
30pub struct RunnerConfig {
31    /// The runner's home (`runs/` under it). An app passes its data folder; the
32    /// `isothrum` command line uses `~/.isothrum`.
33    pub home: PathBuf,
34    /// Starts the tools.
35    pub processes: Arc<dyn ProcessRunner>,
36    /// The host's ports.
37    pub ports: Arc<dyn HostPorts>,
38    /// The time.
39    pub(crate) clock: Arc<dyn Clock>,
40    /// The host's operating system (it picks per-host argv and filters steps).
41    pub host: HostOs,
42    /// The `PATH` the runner hands on where it isn't inherited: to an elevated Hyper-V session,
43    /// and to Vagrant on an ESXi host from macOS, whose relays look for the real `ovftool` in it
44    /// and put their wrapper first (default: the runner's own). The tools the runner starts as
45    /// its children inherit its environment as it is.
46    pub path: Option<OsString>,
47    /// The user's own Terraform plugin cache (`TF_PLUGIN_CACHE_DIR`), which the runs use as it
48    /// is; without one, they share one under the home.
49    pub(crate) tf_plugin_cache: Option<PathBuf>,
50    /// The variables of the runner's environment it hands on where they aren't inherited (the
51    /// proxies, the CA bundles: [`HostEnv`]).
52    pub(crate) host_env: HostEnv,
53    /// The host's CPU architecture: which build of a Vagrant box counts as there already.
54    pub(crate) arch: Arch,
55}
56
57impl RunnerConfig {
58    /// A runner at `home` on this host: real processes (told the Docker CLI's config, see
59    /// [`SystemProcesses`]), the loopback, the system's clock, and what it needs of this process's
60    /// environment, read now (`PATH`, `TF_PLUGIN_CACHE_DIR`, the proxies, the CA bundles,
61    /// Terraform's CLI configuration, Vagrant's variables, `USERPROFILE`).
62    pub fn new(home: impl Into<PathBuf>) -> RunnerConfig {
63        RunnerConfig {
64            home: home.into(),
65            processes: Arc::new(SystemProcesses::default()),
66            ports: Arc::new(LoopbackPorts),
67            clock: Arc::new(SystemClock),
68            host: this_host(),
69            path: std::env::var_os("PATH"),
70            tf_plugin_cache: std::env::var_os("TF_PLUGIN_CACHE_DIR").filter(|d| !d.is_empty()).map(PathBuf::from),
71            host_env: HostEnv::capture(),
72            arch: this_arch(),
73        }
74    }
75}
76
77impl std::fmt::Debug for RunnerConfig {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("RunnerConfig")
80            .field("home", &self.home)
81            .field("host", &self.host)
82            .finish_non_exhaustive()
83    }
84}
85
86/// This build's host operating system.
87#[must_use]
88pub(crate) fn this_host() -> HostOs {
89    if cfg!(windows) {
90        HostOs::Windows
91    } else if cfg!(target_os = "macos") {
92        HostOs::Macos
93    } else {
94        HostOs::Linux
95    }
96}
97
98/// This build's CPU architecture, as Vagrant names a box's build (an x86-64 build reads as
99/// `amd64`, an ARM one as `arm64`).
100#[must_use]
101pub(crate) fn this_arch() -> Arch {
102    if cfg!(target_arch = "aarch64") { Arch::Arm64 } else { Arch::Amd64 }
103}
104
105/// The runner.
106pub struct Runner {
107    pub(crate) config: RunnerConfig,
108    pub(crate) store: Store,
109    pub(crate) locks: RunLocks,
110    flight: Mutex<BTreeMap<RunName, Op>>,
111    reserved: Mutex<BTreeMap<(u16, Protocol), RunName>>,
112}
113
114impl Runner {
115    /// A runner with `config`; its home (with its missing parents) and the home's `runs/` folder
116    /// are created, owner-only (on Windows, a home outside the user's profile gets an owner-only
117    /// DACL).
118    ///
119    /// # Errors
120    ///
121    /// Fails with `io` when the home can't be created or made owner-only (on Windows, its owner
122    /// can't be read or its DACL set), or its `runs/` folder can't be created.
123    pub fn new(config: RunnerConfig) -> Result<Runner> {
124        let store = Store::open(&config.home, config.host_env.get("USERPROFILE").map(Path::new))?;
125        Ok(Runner {
126            config,
127            store,
128            locks: RunLocks::default(),
129            flight: Mutex::default(),
130            reserved: Mutex::default(),
131        })
132    }
133
134    /// Reads and checks the manifest at `manifest`, as run `name` (default: the manifest's
135    /// `environment.name`).
136    ///
137    /// # Errors
138    ///
139    /// Fails as [`load_manifest`](crate::load_manifest) does; with `run_name` when the run's name
140    /// can't name a run; with `unsupported` when this runner can't run the manifest here (its target
141    /// doesn't run on this host, or it has a delivery its driver doesn't take).
142    pub fn open(&self, manifest: &Path, name: Option<RunName>) -> Result<Running<'_>> {
143        let loaded = load_manifest(manifest)?;
144        let name = match name {
145            Some(name) => name,
146            None => RunName::new(loaded.manifest.environment.name.as_str())?,
147        };
148        Running::new(self, loaded, name)
149    }
150
151    /// Every recorded run, with the state its last operation left it in. Reads files only.
152    ///
153    /// # Errors
154    ///
155    /// Fails with `io` when a record can't be read.
156    pub fn runs(&self) -> Result<Vec<RunRecord>> {
157        self.store.records()
158    }
159
160    /// Run `name`'s logged events, oldest first, with how many of its lines it couldn't read as
161    /// one (written by another version of the runner, or cut short).
162    ///
163    /// # Errors
164    ///
165    /// Fails with `io` when the run's event log can't be read.
166    pub fn events(&self, name: &RunName) -> Result<EventLog> {
167        self.store.events(name)
168    }
169
170    /// The public half of the runner's SSH key, one line: what an embedder authorizes where a
171    /// run's SSH goes (a Proxmox node it jumps through). The key is made when the runner has none.
172    ///
173    /// # Errors
174    ///
175    /// Fails with `tool_missing` when `ssh-keygen` isn't installed, `tool_failed` or `timeout`
176    /// when it can't make the key, and `io` when the runner's `ssh/` folder can't be created or
177    /// its public key can't be read.
178    pub async fn ssh_public_key(&self) -> Result<String> {
179        crate::ssh::ensure_key(self.config.processes.as_ref(), &self.config.home).await
180    }
181
182    /// The operations in flight in this runner.
183    pub(crate) fn in_flight(&self) -> Vec<(RunName, Op)> {
184        self.flight
185            .lock()
186            .unwrap_or_else(PoisonError::into_inner)
187            .iter()
188            .map(|(n, o)| (n.clone(), *o))
189            .collect()
190    }
191
192    /// Marks `op` on `name` in flight until the guard drops.
193    pub(crate) fn enter(&self, name: &RunName, op: Op) -> Flight<'_> {
194        self.flight.lock().unwrap_or_else(PoisonError::into_inner).insert(name.clone(), op);
195        Flight {
196            runner: self,
197            name: name.clone(),
198        }
199    }
200
201    /// The operation in flight on `name`, if any.
202    pub(crate) fn op_of(&self, name: &RunName) -> Option<Op> {
203        self.flight.lock().unwrap_or_else(PoisonError::into_inner).get(name).copied()
204    }
205
206    /// Reserves `port` for `name` while it starts; false when another run holds it.
207    pub(crate) fn reserve(&self, name: &RunName, port: u16, protocol: Protocol) -> bool {
208        let mut reserved = self.reserved.lock().unwrap_or_else(PoisonError::into_inner);
209        let holder = reserved.entry((port, protocol)).or_insert_with(|| name.clone());
210        holder == name
211    }
212
213    /// A free loopback port over `protocol` that no run of this runner holds, reserved for `name`
214    /// until this operation ends. The returned socket keeps it bound until dropped, so a port is
215    /// never handed out twice; a port another run holds is refused and held meanwhile so it isn't
216    /// offered again. None when none is left.
217    ///
218    /// # Errors
219    ///
220    /// The loopback couldn't be bound.
221    pub(crate) fn pick_reserved(&self, name: &RunName, protocol: Protocol) -> std::io::Result<Option<crate::net::HeldPort>> {
222        self.pick_where(protocol, |port| self.reserve(name, port, protocol))
223    }
224
225    /// A free loopback port over `protocol` that no run of this runner but `name` holds, not
226    /// reserved: for a query, which holds no reservation past its end (a console's tunnel, whose
227    /// `ssh` binds it at once). None when none is left.
228    ///
229    /// # Errors
230    ///
231    /// The loopback couldn't be bound.
232    pub(crate) fn pick_unreserved(&self, name: &RunName, protocol: Protocol) -> std::io::Result<Option<crate::net::HeldPort>> {
233        self.pick_where(protocol, |port| !self.reserved_elsewhere(name, port, protocol))
234    }
235
236    /// A free loopback port over `protocol` that `take` accepts; one it refuses is held meanwhile
237    /// so it isn't offered again. None when none is left.
238    fn pick_where(&self, protocol: Protocol, take: impl Fn(u16) -> bool) -> std::io::Result<Option<crate::net::HeldPort>> {
239        let mut refused = Vec::new();
240        for _ in 0..64 {
241            let Some(port) = self.config.ports.pick_free(protocol)? else {
242                return Ok(None);
243            };
244            if take(port.port) {
245                return Ok(Some(port));
246            }
247            refused.push(port);
248        }
249        Ok(None)
250    }
251
252    /// Whether another run than `name` holds `port`.
253    pub(crate) fn reserved_elsewhere(&self, name: &RunName, port: u16, protocol: Protocol) -> bool {
254        self.reserved
255            .lock()
256            .unwrap_or_else(PoisonError::into_inner)
257            .get(&(port, protocol))
258            .is_some_and(|h| h != name)
259    }
260
261    /// Each `ports` entry (a host port and its protocol) must be free before run `name` starts:
262    /// not reserved by another run of this runner starting meanwhile, and not already bound on
263    /// this computer.
264    ///
265    /// # Errors
266    ///
267    /// Fails with `port_in_use` at the first port that is reserved elsewhere or already bound.
268    pub(crate) fn ensure_ports_free(&self, name: &RunName, ports: impl IntoIterator<Item = (u16, Protocol)>) -> Result<()> {
269        for (port, protocol) in ports {
270            if self.reserved_elsewhere(name, port, protocol) || self.config.ports.in_use(port, protocol) {
271                return Err(Error::PortInUse {
272                    port,
273                    protocol: wire_name(&protocol),
274                });
275            }
276        }
277        Ok(())
278    }
279
280    /// Frees every port `name` reserved.
281    pub(crate) fn release(&self, name: &RunName) {
282        self.reserved.lock().unwrap_or_else(PoisonError::into_inner).retain(|_, holder| holder != name);
283    }
284}
285
286impl std::fmt::Debug for Runner {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        f.debug_struct("Runner")
289            .field("config", &self.config)
290            .field("in_flight", &self.in_flight())
291            .finish_non_exhaustive()
292    }
293}
294
295/// An operation in flight; cleared when dropped, whatever the outcome (an error, a cancellation).
296pub(crate) struct Flight<'r> {
297    runner: &'r Runner,
298    name: RunName,
299}
300
301impl Drop for Flight<'_> {
302    fn drop(&mut self) {
303        self.runner.flight.lock().unwrap_or_else(PoisonError::into_inner).remove(&self.name);
304        self.runner.release(&self.name);
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn runner(home: &Path) -> Runner {
313        Runner::new(RunnerConfig::new(home)).unwrap()
314    }
315
316    #[test]
317    fn two_runners_share_nothing() {
318        // Regression: the in-flight map and the port reservations kept in statics let two
319        // embedders (or two tests) in one process see each other's operations and ports.
320        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
321        let (a, b) = (runner(a.path()), runner(b.path()));
322        let name = RunName::new("demo").unwrap();
323        let flight = a.enter(&name, Op::Up);
324        assert!(a.reserve(&name, 8080, Protocol::Tcp));
325        assert_eq!(a.in_flight(), [(name.clone(), Op::Up)]);
326        assert_eq!(b.in_flight(), []);
327        assert!(b.reserve(&RunName::new("other").unwrap(), 8080, Protocol::Tcp), "b's ports aren't a's");
328        drop(flight);
329        assert_eq!(a.in_flight(), []);
330    }
331
332    #[test]
333    fn a_port_reserved_by_one_run_is_refused_to_another_until_released() {
334        let home = tempfile::tempdir().unwrap();
335        let r = runner(home.path());
336        let (one, two) = (RunName::new("one").unwrap(), RunName::new("two").unwrap());
337        assert!(r.reserve(&one, 41000, Protocol::Tcp));
338        assert!(r.reserve(&one, 41000, Protocol::Tcp), "its own reservation again");
339        assert!(!r.reserve(&two, 41000, Protocol::Tcp));
340        assert!(r.reserved_elsewhere(&two, 41000, Protocol::Tcp) && !r.reserved_elsewhere(&one, 41000, Protocol::Tcp));
341        assert!(r.reserve(&two, 41000, Protocol::Udp), "another protocol");
342        r.release(&one);
343        assert!(r.reserve(&two, 41000, Protocol::Tcp));
344    }
345}