1use 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#[derive(Clone)]
29#[non_exhaustive]
30pub struct RunnerConfig {
31 pub home: PathBuf,
34 pub processes: Arc<dyn ProcessRunner>,
36 pub ports: Arc<dyn HostPorts>,
38 pub(crate) clock: Arc<dyn Clock>,
40 pub host: HostOs,
42 pub path: Option<OsString>,
47 pub(crate) tf_plugin_cache: Option<PathBuf>,
50 pub(crate) host_env: HostEnv,
53 pub(crate) arch: Arch,
55}
56
57impl RunnerConfig {
58 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#[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#[must_use]
101pub(crate) fn this_arch() -> Arch {
102 if cfg!(target_arch = "aarch64") { Arch::Arm64 } else { Arch::Amd64 }
103}
104
105pub 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 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 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<EventLog> {
167 self.store.events(name)
168 }
169
170 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 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 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 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 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 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 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 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 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 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 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
295pub(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 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}