1use 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#[derive(Clone)]
26#[non_exhaustive]
27pub struct RunnerConfig {
28 pub home: PathBuf,
31 pub processes: Arc<dyn ProcessRunner>,
33 pub ports: Arc<dyn HostPorts>,
35 pub clock: Arc<dyn Clock>,
37 pub host: HostOs,
39 pub path: Option<String>,
42}
43
44impl RunnerConfig {
45 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 #[must_use]
61 pub fn with_processes(mut self, processes: Arc<dyn ProcessRunner>) -> RunnerConfig {
62 self.processes = processes;
63 self
64 }
65
66 #[must_use]
68 pub fn with_ports(mut self, ports: Arc<dyn HostPorts>) -> RunnerConfig {
69 self.ports = ports;
70 self
71 }
72
73 #[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#[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
102pub 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 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 pub fn add_hooks(&mut self, hooks: Arc<dyn Hooks>) {
132 self.hooks.push(hooks);
133 }
134
135 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 pub fn runs(&self) -> Result<Vec<RunRecord>> {
157 self.store.records()
158 }
159
160 pub fn events(&self, name: &RunName) -> Result<Vec<Event>> {
166 self.store.events(name)
167 }
168
169 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 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 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 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 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 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 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 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 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
269pub(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 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}