1use 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#[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(crate) clock: Arc<dyn Clock>,
37 pub host: HostOs,
39 pub(crate) tf_plugin_cache: Option<PathBuf>,
42 pub(crate) host_env: HostEnv,
45}
46
47impl RunnerConfig {
48 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#[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#[must_use]
89pub fn this_arch() -> Arch {
90 if cfg!(target_arch = "aarch64") { Arch::Arm64 } else { Arch::Amd64 }
91}
92
93pub struct Runner {
95 pub(crate) config: RunnerConfig,
96 pub(crate) store: Home,
97 pub(crate) locks: RunLocks,
98 flight: Mutex<BTreeMap<RunName, InFlight>>,
99 reservations: PortReservations,
101}
102
103pub const RUN_KEY_VAR: &str = "ISOTHRUM_RUN_KEY";
107
108#[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 pub fn new(mut config: RunnerConfig) -> Result<Runner> {
138 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 pub fn open(&self, dir: &Path, name: Option<RunName>) -> Result<Running<'_>> {
161 self.open_project(dir, None, name)
162 }
163
164 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 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 pub fn runs(&self) -> Result<Vec<RunRecord>> {
201 self.store.records()
202 }
203
204 pub fn run_record(&self, name: &RunName) -> Result<Option<RunRecord>> {
212 self.store.record(name)
213 }
214
215 #[must_use]
217 pub fn copy_key(&self, name: &RunName) -> String {
218 copy_key(&self.config.home, name)
219 }
220
221 pub fn events(&self, name: &RunName) -> Result<EventLog> {
228 self.store.events(name)
229 }
230
231 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 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 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 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 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 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 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 pub(crate) fn release(&self, name: &RunName) {
289 self.reservations.release(name);
290 }
291
292 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 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 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#[derive(Debug, Clone, Copy)]
335struct InFlight {
336 op: Op,
337 id: OperationId,
338 begun: Option<(Transition, Desired)>,
339}
340
341pub(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 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 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}