Skip to main content

isothrum_runner/
store.rs

1//! The runner's state, one folder per run under the embedder's home (the reference, with what
2//! each target keeps in a run's folder: `docs/reference/state.md`):
3//!
4//! ```text
5//! <home>/slots.lock          the OS lock a start holds while it picks its slot (`${run.slot}`)
6//! <home>/ssh/                the runner's SSH key, `id_ed25519` and `.pub`, made on first use
7//! <home>/terraform-plugins/  the Terraform provider cache every run of this home shares
8//! <home>/relay/              on macOS, the wrappers that send a tool through a loopback relay
9//! <home>/runs/<run name>/
10//!   record.json         the run's record (atomic, owner-only)
11//!   lock                the OS lock: one operation per run across processes
12//!   events.jsonl        the last operations' events, so a reattached UI can replay them
13//!   seen.json           the run's machines as the runner last read them, for a status while
14//!                       an operation holds the run; removed by a down
15//!   ssh_config          the run's SSH settings, with its `known_hosts`, for a run reached over
16//!                       SSH
17//!   guest-<machine>.in  a guest delivery's values, only while it is delivered
18//!   consoles.json       the graphical consoles the runner chose (VMware's VNC: port and
19//!                       password per machine); removed by a down
20//!   proxmox-console.curl  a Proxmox console request's credentials, only while curl runs (removed
21//!                       however the request ends)
22//!   elevated/<token>/   an elevated session's folder (Hyper-V): each request's `env-<n>.json`,
23//!                       its variables, until the broker starts the program
24//!   …                   what the manifest keeps in `${run.state_dir}`: Compose's pinned ports,
25//!                       Vagrant's state, Terraform's state and module copy
26//! ```
27//!
28//! The run's folder holds only the run and its generated files, so replacing it never strands a
29//! run. `Store` is a struct over the file system, not a trait: tests use a temporary home.
30
31#[cfg(any(windows, test))]
32mod acl;
33mod fs;
34mod lock;
35mod transient;
36
37use std::collections::BTreeMap;
38use std::path::{Path, PathBuf};
39
40use isoloom_manifest::{Cloud, Driver, Provider, Target};
41use serde::{Deserialize, Serialize};
42
43pub(crate) use fs::{create_private, if_there, private_dir, remove_path, write_private};
44pub(crate) use transient::Transient;
45
46/// Creates `dir` (with its missing parents) owner-only ([`private_dir`]); [`Error::Io`] naming it
47/// when that fails.
48pub(crate) fn create_dir(dir: &Path) -> Result<()> {
49    private_dir(dir).map_err(Error::io(dir, "created"))
50}
51
52/// Writes `contents` to `path` whole and owner-only ([`write_private`]); [`Error::Io`] naming it
53/// when that fails.
54pub(crate) fn write(path: &Path, contents: &[u8]) -> Result<()> {
55    write_private(path, contents).map_err(Error::io(path, "written"))
56}
57
58/// Removes `path`, a file or a folder, nothing there being fine ([`remove_path`]); [`Error::Io`]
59/// naming it when that fails.
60pub(crate) fn remove(path: &Path) -> Result<()> {
61    remove_path(path).map_err(Error::io(path, "removed"))
62}
63pub(crate) use lock::{RunLocks, SlotsLock};
64
65use crate::Result;
66use crate::error::{Error, ErrorCode};
67use crate::events::EventLog;
68use crate::name::RunName;
69use crate::state::{Op, RunState};
70use crate::status::MachineStatus;
71
72/// The record format's version.
73const RECORD_VERSION: u32 = 0;
74
75/// A run's record, in its folder.
76const RECORD_FILE: &str = "record.json";
77
78/// A run's event log, in its folder.
79const EVENTS_FILE: &str = "events.jsonl";
80
81/// What the runner last saw of a run, in its folder.
82const SEEN_FILE: &str = "seen.json";
83
84/// A run's OS lock file, in its folder.
85const LOCK_FILE: &str = "lock";
86
87/// How many event lines a run's log keeps before an operation trims it to half.
88pub(crate) const EVENTS_KEPT: usize = 4000;
89
90/// The last operation on a run and how it ended.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92#[non_exhaustive]
93pub struct LastOp {
94    /// The operation.
95    pub op: Op,
96    /// Whether it succeeded.
97    pub ok: bool,
98    /// Its failure's code, when it failed.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub code: Option<ErrorCode>,
101    /// When it ended.
102    pub at: String,
103}
104
105/// What the runner keeps about a run (never a secret's value).
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct RunRecord {
109    /// The record format's version.
110    pub version: u32,
111    /// The run's name.
112    pub name: RunName,
113    /// The manifest the run was last brought up or updated from, absolute: what a later
114    /// operation that has only the record (a sweep's `down`) reopens.
115    pub manifest: PathBuf,
116    /// Its target.
117    pub target: Target,
118    /// Its driver.
119    pub driver: Driver,
120    /// Its cloud, for a cloud target's run: what the reaper picks runs by.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub cloud: Option<Cloud>,
123    /// The Vagrant provider the run uses, when it has one.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub provider: Option<Provider>,
126    /// What the embedder calls the place the run is on (a server, an account).
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub host_label: Option<String>,
129    /// Where it stood after its last operation.
130    pub state: RunState,
131    /// Every param the run was started with: a later operation (a `down`) replays them, so it acts
132    /// on what was created, not on what the embedder's settings say now.
133    pub params: BTreeMap<String, String>,
134    /// The host ports a local VM run forwards from this computer, by `"<machine>/<port>"`: a free
135    /// one the runner pinned at the first start, kept so a resume forwards the same port.
136    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
137    pub vm_host_ports: BTreeMap<String, u16>,
138    /// The boot digest (the manifest's `native.boot_digest`) of the Vagrantfile each VM of the run
139    /// was last brought up or updated with, by machine name: what an update compares to reload a
140    /// running VM whose boot-time settings changed. Empty for a run recorded before the runner
141    /// kept them.
142    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
143    pub vm_boot_digests: BTreeMap<String, String>,
144    /// When it was last started.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub started_at: Option<String>,
147    /// Its slot on its place (`${run.slot}`, 1 to 99), held from its first start to its `down`.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub slot: Option<u8>,
150    /// The login its SSH goes through first (`user@host`), when the embedder gave one.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub ssh_jump: Option<String>,
153    /// When it stops itself (the manifest's `expiry`), in seconds since the Unix epoch.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub expires_at: Option<u64>,
156    /// The last operation.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub last: Option<LastOp>,
159}
160
161impl RunRecord {
162    /// The params a later operation replays: those of the run's start, once it was started
163    /// (`started_at`); none for a run never started, whose record holds no start's.
164    pub(crate) fn replayed_params(&self) -> Option<&BTreeMap<String, String>> {
165        self.started_at.is_some().then_some(&self.params)
166    }
167
168    /// A record of a run never started yet.
169    pub(crate) fn fresh(name: RunName, manifest: PathBuf, target: Target, driver: Driver) -> RunRecord {
170        RunRecord {
171            version: RECORD_VERSION,
172            name,
173            manifest,
174            target,
175            driver,
176            cloud: None,
177            provider: None,
178            host_label: None,
179            state: RunState::Absent,
180            params: BTreeMap::new(),
181            vm_host_ports: BTreeMap::new(),
182            vm_boot_digests: BTreeMap::new(),
183            started_at: None,
184            slot: None,
185            ssh_jump: None,
186            expires_at: None,
187            last: None,
188        }
189    }
190}
191
192/// What the runner last saw of a run when it read it (a status, an operation's own reads): its
193/// machines, and where their ports answer. Never an output's value, which may be secret. What a
194/// status shows while an operation holds the run, whose tools it then doesn't ask.
195#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
196pub(crate) struct Seen {
197    /// Every machine of the manifest, as read.
198    pub(crate) machines: Vec<MachineStatus>,
199    /// The host port each published machine port got: its machine, its port's name, the port.
200    pub(crate) published: Vec<(String, String, u16)>,
201    /// Where each machine's published ports answer.
202    pub(crate) hosts: BTreeMap<String, String>,
203}
204
205/// The runner's state folder.
206#[derive(Debug, Clone)]
207pub(crate) struct Store {
208    runs: PathBuf,
209    /// The home's `slots.lock`: one slot pick at a time.
210    slots_lock: PathBuf,
211}
212
213impl Store {
214    /// The store under `home` (owner-only on Windows, see [`fs::private_home`]), its `runs/`
215    /// folder created owner-only.
216    pub(crate) fn open(home: &Path, profile: Option<&Path>) -> Result<Store> {
217        fs::private_home(home, profile).map_err(Error::io(home, "made owner-only"))?;
218        let runs = home.join("runs");
219        create_dir(&runs)?;
220        Ok(Store {
221            runs,
222            slots_lock: home.join("slots.lock"),
223        })
224    }
225
226    /// Holds the home's slots while a start picks its slot and records it.
227    pub(crate) async fn hold_slots(&self) -> Result<SlotsLock> {
228        lock::hold_slots(&self.slots_lock).await
229    }
230
231    /// Run `name`'s folder, created owner-only.
232    pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
233        let dir = self.run_dir_path(name);
234        create_dir(&dir)?;
235        Ok(dir)
236    }
237
238    /// Run `name`'s folder (not made: [`Store::run_dir`] makes it).
239    pub(crate) fn run_dir_path(&self, name: &RunName) -> PathBuf {
240        self.runs.join(name.as_str())
241    }
242
243    /// Run `name`'s record file (its folder not made).
244    fn record_path(&self, name: &RunName) -> PathBuf {
245        self.run_dir_path(name).join(RECORD_FILE)
246    }
247
248    /// Run `name`'s event log (its folder not made).
249    fn events_path(&self, name: &RunName) -> PathBuf {
250        self.run_dir_path(name).join(EVENTS_FILE)
251    }
252
253    /// Run `name`'s lock file.
254    pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
255        self.run_dir_path(name).join(LOCK_FILE)
256    }
257
258    /// Whether an operation holds run `name` now, in this process or another ([`lock::held`]).
259    pub(crate) fn held(&self, name: &RunName) -> Result<bool> {
260        let path = self.lock_path(name);
261        lock::held(&path).map_err(Error::io(&path, "read"))
262    }
263
264    /// Run `name`'s [`Seen`] file (its folder not made).
265    fn seen_path(&self, name: &RunName) -> PathBuf {
266        self.run_dir_path(name).join(SEEN_FILE)
267    }
268
269    /// What the runner last saw of run `name`, when it ever read it.
270    pub(crate) fn seen(&self, name: &RunName) -> Result<Option<Seen>> {
271        read_json(&self.seen_path(name))
272    }
273
274    /// Keeps `seen` as what the runner last saw of run `name`, whole.
275    pub(crate) fn keep_seen(&self, name: &RunName, seen: &Seen) -> Result<()> {
276        self.run_dir(name)?;
277        write_json(&self.seen_path(name), seen)
278    }
279
280    /// Forgets what the runner last saw of run `name` (a run gone: the next start is a new run).
281    pub(crate) fn forget_seen(&self, name: &RunName) -> Result<()> {
282        let path = self.seen_path(name);
283        remove(&path)
284    }
285
286    /// Run `name`'s record, when it has one.
287    pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
288        read_json(&self.record_path(name))
289    }
290
291    /// Writes `record` whole.
292    pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
293        self.run_dir(&record.name)?;
294        write_json(&self.record_path(&record.name), record)
295    }
296
297    /// Every run's record, by name.
298    pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
299        let entries = std::fs::read_dir(&self.runs).map_err(Error::io(&self.runs, "read"))?;
300        let mut names = Vec::new();
301        for entry in entries {
302            let entry = entry.map_err(Error::io(&self.runs, "read"))?;
303            names.extend(RunName::new(&entry.file_name().to_string_lossy()).ok());
304        }
305        names.sort();
306        let mut records = Vec::new();
307        for name in names {
308            records.extend(self.record(&name)?);
309        }
310        Ok(records)
311    }
312
313    /// Run `name`'s event log, opened to append.
314    pub(crate) fn event_log(&self, name: &RunName) -> Result<std::fs::File> {
315        self.run_dir(name)?;
316        let path = self.events_path(name);
317        fs::append_private(&path).map_err(Error::io(&path, "written"))
318    }
319
320    /// Trims run `name`'s event log to its newer half once it is long. The trimmed log replaces
321    /// the file, so only the holder of the run's lock trims it, with no handle of its own still
322    /// open on it: an operation appending to it would go on appending to the file it replaced.
323    pub(crate) fn trim_event_log(&self, name: &RunName) -> Result<()> {
324        self.run_dir(name)?;
325        let path = self.events_path(name);
326        let lines = read_lines(&path)?;
327        if lines.len() > EVENTS_KEPT {
328            let mut kept = Vec::new();
329            for line in lines.iter().skip(lines.len().saturating_sub(EVENTS_KEPT / 2)) {
330                kept.extend_from_slice(line);
331                kept.push(b'\n');
332            }
333            write(&path, &kept)?;
334        }
335        Ok(())
336    }
337
338    /// Run `name`'s logged events, oldest first, with how many of its lines aren't an event
339    /// this runner reads (a line cut short, mid-character included).
340    pub(crate) fn events(&self, name: &RunName) -> Result<EventLog> {
341        let path = self.events_path(name);
342        let mut log = EventLog::default();
343        for (n, line) in read_lines(&path)?.iter().enumerate().filter(|(_, l)| !l.trim_ascii().is_empty()) {
344            match serde_json::from_slice(line) {
345                Ok(event) => log.events.push(event),
346                Err(e) => {
347                    // Counted for the caller; why (a line cut short, an event kind this runner
348                    // doesn't know) is traced.
349                    tracing::debug!(line = n + 1, error = %e, path = %path.display(), "a line of the event log isn't an event this runner reads");
350                    log.unreadable += 1;
351                }
352            }
353        }
354        Ok(log)
355    }
356}
357
358/// `path`'s lines, as bytes: a log cut short (a full disk, a killed process) can end mid-character,
359/// and that line is one like any other. None when the file doesn't exist.
360fn read_lines(path: &Path) -> Result<Vec<Vec<u8>>> {
361    let Some(bytes) = if_there(std::fs::read(path)).map_err(Error::io(path, "read"))? else {
362        return Ok(Vec::new());
363    };
364    let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
365    if body.is_empty() {
366        return Ok(Vec::new());
367    }
368    Ok(body
369        .split(|b| *b == b'\n')
370        .map(|line| line.strip_suffix(b"\r").unwrap_or(line).to_vec())
371        .collect())
372}
373
374/// The JSON file at `path`, read; `None` when there is none.
375///
376/// # Errors
377///
378/// It exists but can't be read, or doesn't hold a `T` (`InvalidData`).
379pub(crate) fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Option<T>> {
380    let Some(bytes) = if_there(std::fs::read(path)).map_err(Error::io(path, "read"))? else {
381        return Ok(None);
382    };
383    serde_json::from_slice(&bytes).map(Some).map_err(|e| Error::io(path, "read")(e.into()))
384}
385
386/// Writes `value` as the JSON file at `path`, whole and owner-only: [`read_json`]'s counterpart.
387fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
388    let text = serde_json::to_vec_pretty(value).map_err(|e| Error::io(path, "written")(e.into()))?;
389    write(path, &text)
390}
391
392#[cfg(test)]
393mod tests {
394    use std::io::Write;
395
396    use super::*;
397
398    fn record(name: &str) -> RunRecord {
399        RunRecord::fresh(
400            RunName::new(name).unwrap(),
401            "/work/x/.isoloom/docker/run.json".into(),
402            Target::Docker,
403            Driver::Compose,
404        )
405    }
406
407    #[test]
408    fn records_are_kept_per_run_and_listed_by_name() {
409        let home = tempfile::tempdir().unwrap();
410        let store = Store::open(home.path(), None).unwrap();
411        assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
412        let mut b = record("b");
413        b.params.insert("ISOLOOM_PUBLISH_FIXED".into(), "1".into());
414        store.save(&b).unwrap();
415        store.save(&record("a")).unwrap();
416        std::fs::create_dir_all(home.path().join("runs").join("Not A Run")).unwrap();
417        let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
418        assert_eq!(names, ["a", "b"]);
419        assert_eq!(store.record(&b.name).unwrap(), Some(b));
420    }
421
422    /// A store in a home of its own, and run `r`.
423    fn run_r() -> (tempfile::TempDir, Store, RunName) {
424        let home = tempfile::tempdir().unwrap();
425        let store = Store::open(home.path(), None).unwrap();
426        (home, store, RunName::new("r").unwrap())
427    }
428
429    #[test]
430    fn the_event_log_is_trimmed_to_its_newer_half() {
431        let (home, store, name) = run_r();
432        let mut log = store.event_log(&name).unwrap();
433        for seq in 0..=EVENTS_KEPT {
434            writeln!(log, "{{\"seq\":{seq}}}").unwrap();
435        }
436        drop(log);
437        store.trim_event_log(&name).unwrap();
438        let lines = read_lines(&home.path().join("runs/r/events.jsonl")).unwrap();
439        assert_eq!(lines.len(), EVENTS_KEPT / 2);
440        assert_eq!(lines.last().unwrap(), format!("{{\"seq\":{EVENTS_KEPT}}}").as_bytes());
441    }
442
443    #[tokio::test]
444    async fn an_event_log_line_this_runner_cant_read_is_counted_not_dropped_unsaid() {
445        let (_home, store, name) = run_r();
446        let mut log = store.event_log(&name).unwrap();
447        let read = r#"{"v":0,"seq":1,"time":"2026-10-15T12:00:00Z","run":"r","op":"up","event":"result","ok":true,"data":null}"#;
448        // A 1.x warning code this runner no longer has, and a line cut short.
449        let older = r#"{"v":0,"seq":2,"time":"2026-10-15T12:00:01Z","run":"r","op":"up","event":"warning","code":"hook_failed","message":"x"}"#;
450        writeln!(log, "{read}\n{older}\n{{\"v\":0,\"se\n").unwrap();
451        drop(log);
452        let (events, traced) = crate::testing::traced(async { store.events(&name) }).await;
453        let events = events.unwrap();
454        assert_eq!((events.events.len(), events.unreadable), (1, 2));
455        // Why each line isn't read is traced, by its number.
456        assert!(traced.contains("line=2") && traced.contains("hook_failed"), "{traced}");
457        assert!(traced.contains("line=3"), "{traced}");
458    }
459
460    /// A log cut mid-character (a full disk, a killed process) holds a line that isn't UTF-8: it
461    /// is one unreadable line, and the log still opens, is read and is trimmed.
462    #[test]
463    fn a_line_cut_mid_character_is_unreadable_and_the_log_goes_on() {
464        let (home, store, name) = run_r();
465        let read = r#"{"v":0,"seq":1,"time":"2026-10-15T12:00:00Z","run":"r","op":"up","event":"result","ok":true,"data":null}"#;
466        let mut log = store.event_log(&name).unwrap();
467        log.write_all(format!("{read}\n").as_bytes()).unwrap();
468        // `é` is 0xC3 0xA9: the line ends after its first byte.
469        log.write_all(b"{\"v\":0,\"message\":\"d\xC3").unwrap();
470        drop(log);
471        let mut reopened = store.event_log(&name).expect("the log opens to append");
472        reopened.write_all(format!("\n{read}\n").as_bytes()).unwrap();
473        drop(reopened);
474        let events = store.events(&name).unwrap();
475        assert_eq!((events.events.len(), events.unreadable), (2, 1));
476
477        let mut many = store.event_log(&name).unwrap();
478        for seq in 0..=EVENTS_KEPT {
479            writeln!(many, "{{\"seq\":{seq}}}").unwrap();
480        }
481        drop(many);
482        store.trim_event_log(&name).expect("a long log with such a line is trimmed");
483        assert_eq!(read_lines(&home.path().join("runs/r/events.jsonl")).unwrap().len(), EVENTS_KEPT / 2);
484    }
485
486    #[test]
487    fn a_files_lines_are_split_on_line_feeds() {
488        let dir = tempfile::tempdir().unwrap();
489        let path = dir.path().join("f");
490        assert_eq!(read_lines(&path).unwrap(), Vec::<Vec<u8>>::new(), "no file, no line");
491        for (text, lines) in [
492            (&b""[..], vec![]),
493            (b"a\n", vec![b"a".to_vec()]),
494            (b"a\r\nb", vec![b"a".to_vec(), b"b".to_vec()]),
495            (b"a\n\nb\n", vec![b"a".to_vec(), b"".to_vec(), b"b".to_vec()]),
496        ] {
497            std::fs::write(&path, text).unwrap();
498            assert_eq!(read_lines(&path).unwrap(), lines, "{text:?}");
499        }
500    }
501}