Skip to main content

isothrum_runner/
runner.rs

1//! The engine: one per embedder. It holds what the launcher kept in process-wide statics (the
2//! operations in flight, the per-run locks, the ports being pinned), so two runners in one
3//! process never share them.
4
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, Mutex, PoisonError};
8
9use isoloom_manifest::{HostOs, Protocol};
10
11use crate::Result;
12use crate::clock::{Clock, SystemClock};
13use crate::error::Error;
14use crate::events::Event;
15use crate::hooks::Hooks;
16use crate::manifest::load_manifest;
17use crate::name::RunName;
18use crate::net::{HostPorts, LoopbackPorts};
19use crate::process::{ProcessRunner, SystemProcesses};
20use crate::run::Running;
21use crate::state::Op;
22use crate::store::{RunLocks, RunRecord, Store};
23
24/// How a runner is built: its home, and the ports it reaches the world through.
25#[derive(Clone)]
26#[non_exhaustive]
27pub struct RunnerConfig {
28    /// The runner's home (`runs/` under it). The launcher passes its app 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 clock: Arc<dyn Clock>,
37    /// The host's operating system (it picks per-host argv and filters steps).
38    pub host: HostOs,
39    /// The tools' `PATH`, where the macOS relays look for the real `ovftool` and put their
40    /// wrapper first (default: the runner's own).
41    pub path: Option<String>,
42}
43
44impl RunnerConfig {
45    /// A runner at `home` on this host: real processes, the loopback, the system's clock.
46    pub fn new(home: impl Into<PathBuf>) -> RunnerConfig {
47        RunnerConfig {
48            home: home.into(),
49            processes: Arc::new(SystemProcesses::default()),
50            ports: Arc::new(LoopbackPorts),
51            clock: Arc::new(SystemClock),
52            host: this_host(),
53            path: std::env::var("PATH").ok(),
54        }
55    }
56}
57
58impl RunnerConfig {
59    /// Starts the tools through `processes` (a fake in tests).
60    #[must_use]
61    pub fn with_processes(mut self, processes: Arc<dyn ProcessRunner>) -> RunnerConfig {
62        self.processes = processes;
63        self
64    }
65
66    /// Reads the host's ports through `ports`.
67    #[must_use]
68    pub fn with_ports(mut self, ports: Arc<dyn HostPorts>) -> RunnerConfig {
69        self.ports = ports;
70        self
71    }
72
73    /// Reads the time from `clock`.
74    #[must_use]
75    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> RunnerConfig {
76        self.clock = clock;
77        self
78    }
79}
80
81impl std::fmt::Debug for RunnerConfig {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.debug_struct("RunnerConfig")
84            .field("home", &self.home)
85            .field("host", &self.host)
86            .finish_non_exhaustive()
87    }
88}
89
90/// This build's host operating system.
91#[must_use]
92pub fn this_host() -> HostOs {
93    if cfg!(windows) {
94        HostOs::Windows
95    } else if cfg!(target_os = "macos") {
96        HostOs::Macos
97    } else {
98        HostOs::Linux
99    }
100}
101
102/// The runner.
103pub struct Runner {
104    pub(crate) config: RunnerConfig,
105    pub(crate) store: Store,
106    pub(crate) hooks: Vec<Arc<dyn Hooks>>,
107    pub(crate) locks: RunLocks,
108    flight: Mutex<BTreeMap<RunName, Op>>,
109    reserved: Mutex<BTreeMap<(u16, Protocol), RunName>>,
110}
111
112impl Runner {
113    /// A runner with `config`; its home's `runs/` folder is created owner-only.
114    ///
115    /// # Errors
116    ///
117    /// Fails with `io` when the home's `runs/` folder can't be created.
118    pub fn new(config: RunnerConfig) -> Result<Runner> {
119        let store = Store::open(&config.home)?;
120        Ok(Runner {
121            config,
122            store,
123            hooks: Vec::new(),
124            locks: RunLocks::default(),
125            flight: Mutex::default(),
126            reserved: Mutex::default(),
127        })
128    }
129
130    /// Adds the embedder's hooks around lifecycle edges.
131    pub fn add_hooks(&mut self, hooks: Arc<dyn Hooks>) {
132        self.hooks.push(hooks);
133    }
134
135    /// Reads and checks the manifest at `manifest`, as run `name` (default: the run's 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 (its driver, a
141    /// delivery, this host).
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.
161    ///
162    /// # Errors
163    ///
164    /// Fails with `io` when the run's event log can't be read.
165    pub fn events(&self, name: &RunName) -> Result<Vec<Event>> {
166        self.store.events(name)
167    }
168
169    /// The public half of the runner's SSH key, one line: what an embedder authorizes where a
170    /// run's SSH goes (a Proxmox node it jumps through). The key is made when the runner has none.
171    ///
172    /// # Errors
173    ///
174    /// Fails with `tool_missing` when `ssh-keygen` isn't installed, `tool_failed` or `timeout`
175    /// when it can't make the key, and `io` when the runner's `ssh/` folder can't be created.
176    pub async fn ssh_public_key(&self) -> Result<String> {
177        crate::ssh::ensure_key(self.config.processes.as_ref(), &self.config.home).await
178    }
179
180    /// The operations in flight in this runner (a quit guard, a UI rehydrating).
181    pub fn in_flight(&self) -> Vec<(RunName, Op)> {
182        self.flight
183            .lock()
184            .unwrap_or_else(PoisonError::into_inner)
185            .iter()
186            .map(|(n, o)| (n.clone(), *o))
187            .collect()
188    }
189
190    /// Marks `op` on `name` in flight until the guard drops.
191    pub(crate) fn enter(&self, name: &RunName, op: Op) -> Flight<'_> {
192        self.flight.lock().unwrap_or_else(PoisonError::into_inner).insert(name.clone(), op);
193        Flight {
194            runner: self,
195            name: name.clone(),
196        }
197    }
198
199    /// The operation in flight on `name`, if any.
200    pub(crate) fn op_of(&self, name: &RunName) -> Option<Op> {
201        self.flight.lock().unwrap_or_else(PoisonError::into_inner).get(name).copied()
202    }
203
204    /// Reserves `port` for `name` while it starts; false when another run holds it.
205    pub(crate) fn reserve(&self, name: &RunName, port: u16, protocol: Protocol) -> bool {
206        let mut reserved = self.reserved.lock().unwrap_or_else(PoisonError::into_inner);
207        let holder = reserved.entry((port, protocol)).or_insert_with(|| name.clone());
208        holder == name
209    }
210
211    /// A free loopback port over `protocol` that no run of this runner holds, reserved for `name`
212    /// until this operation ends. The returned socket keeps it bound until dropped, so a port is
213    /// never handed out twice; a port another run holds is refused and held meanwhile so it isn't
214    /// offered again.
215    pub(crate) fn pick_reserved(&self, name: &RunName, protocol: Protocol) -> Option<crate::net::HeldPort> {
216        let mut refused = Vec::new();
217        for _ in 0..64 {
218            let port = self.config.ports.pick_free(protocol)?;
219            if self.reserve(name, port.port, protocol) {
220                return Some(port);
221            }
222            refused.push(port);
223        }
224        None
225    }
226
227    /// Whether another run than `name` holds `port`.
228    pub(crate) fn reserved_elsewhere(&self, name: &RunName, port: u16, protocol: Protocol) -> bool {
229        self.reserved
230            .lock()
231            .unwrap_or_else(PoisonError::into_inner)
232            .get(&(port, protocol))
233            .is_some_and(|h| h != name)
234    }
235
236    /// Each `ports` entry (a host port and its protocol) must be free before run `name` starts:
237    /// not reserved by another run of this runner starting meanwhile, and not already bound on
238    /// this computer.
239    ///
240    /// # Errors
241    ///
242    /// Fails with `port_in_use` at the first port that is reserved elsewhere or already bound.
243    pub(crate) fn ensure_ports_free(&self, name: &RunName, ports: impl IntoIterator<Item = (u16, Protocol)>) -> Result<()> {
244        for (port, protocol) in ports {
245            if self.reserved_elsewhere(name, port, protocol) || self.config.ports.in_use(port, protocol) {
246                let protocol = if protocol == Protocol::Udp { "udp" } else { "tcp" };
247                return Err(Error::PortInUse { port, protocol });
248            }
249        }
250        Ok(())
251    }
252
253    /// Frees every port `name` reserved.
254    pub(crate) fn release(&self, name: &RunName) {
255        self.reserved.lock().unwrap_or_else(PoisonError::into_inner).retain(|_, holder| holder != name);
256    }
257}
258
259impl std::fmt::Debug for Runner {
260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261        f.debug_struct("Runner")
262            .field("config", &self.config)
263            .field("hooks", &self.hooks.len())
264            .field("in_flight", &self.in_flight())
265            .finish_non_exhaustive()
266    }
267}
268
269/// An operation in flight; cleared when dropped, whatever the outcome (an error, a cancellation).
270pub(crate) struct Flight<'r> {
271    runner: &'r Runner,
272    name: RunName,
273}
274
275impl Drop for Flight<'_> {
276    fn drop(&mut self) {
277        self.runner.flight.lock().unwrap_or_else(PoisonError::into_inner).remove(&self.name);
278        self.runner.release(&self.name);
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    fn runner(home: &Path) -> Runner {
287        Runner::new(RunnerConfig::new(home)).unwrap()
288    }
289
290    #[test]
291    fn two_runners_share_nothing() {
292        // Regression (R5): the launcher's in-flight map, run locks and probe cache were statics,
293        // so two embedders (or two tests) in one process saw each other's operations.
294        let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
295        let (a, b) = (runner(a.path()), runner(b.path()));
296        let name = RunName::new("lab").unwrap();
297        let flight = a.enter(&name, Op::Up);
298        assert!(a.reserve(&name, 8080, Protocol::Tcp));
299        assert_eq!(a.in_flight(), [(name.clone(), Op::Up)]);
300        assert_eq!(b.in_flight(), []);
301        assert!(b.reserve(&RunName::new("other").unwrap(), 8080, Protocol::Tcp), "b's ports aren't a's");
302        drop(flight);
303        assert_eq!(a.in_flight(), []);
304    }
305
306    #[test]
307    fn a_port_reserved_by_one_run_is_refused_to_another_until_released() {
308        let home = tempfile::tempdir().unwrap();
309        let r = runner(home.path());
310        let (one, two) = (RunName::new("one").unwrap(), RunName::new("two").unwrap());
311        assert!(r.reserve(&one, 41000, Protocol::Tcp));
312        assert!(r.reserve(&one, 41000, Protocol::Tcp), "its own reservation again");
313        assert!(!r.reserve(&two, 41000, Protocol::Tcp));
314        assert!(r.reserved_elsewhere(&two, 41000, Protocol::Tcp) && !r.reserved_elsewhere(&one, 41000, Protocol::Tcp));
315        assert!(r.reserve(&two, 41000, Protocol::Udp), "another protocol");
316        r.release(&one);
317        assert!(r.reserve(&two, 41000, Protocol::Tcp));
318    }
319}