Skip to main content

isothrum_runner/
store.rs

1//! The runner's state, one folder per run under the embedder's home:
2//!
3//! ```text
4//! <home>/runs/<run name>/
5//!   record.json     the run's record (atomic, owner-only)
6//!   lock            the OS lock: one operation per run across processes
7//!   events.jsonl    the last operations' events, so a reattached UI can replay them
8//!   …               what the manifest keeps in `${run.state_dir}` (Compose's pinned ports)
9//! ```
10//!
11//! The run's folder holds only the run and its generated files, so replacing it never strands a
12//! run. `Store` is a struct over the file system, not a trait: tests use a temporary home.
13
14mod fs;
15mod lock;
16
17use std::collections::BTreeMap;
18use std::io::{BufRead, BufReader};
19use std::path::{Path, PathBuf};
20
21use isoloom_manifest::{Cloud, Driver, Target};
22use serde::{Deserialize, Serialize};
23
24pub(crate) use fs::{create_private, private_dir, write_private};
25pub(crate) use lock::RunLocks;
26
27use crate::Result;
28use crate::error::{Error, ErrorCode};
29use crate::events::Event;
30use crate::name::RunName;
31use crate::state::{Op, RunState};
32
33/// The record format's version.
34const RECORD_VERSION: u32 = 0;
35
36/// How many event lines a run's log keeps before an operation trims it to half.
37const EVENTS_KEPT: usize = 4000;
38
39/// The last operation on a run and how it ended.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[non_exhaustive]
42pub struct LastOp {
43    /// The operation.
44    pub op: Op,
45    /// Whether it succeeded.
46    pub ok: bool,
47    /// Its failure's code, when it failed.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub code: Option<ErrorCode>,
50    /// When it ended.
51    pub at: String,
52}
53
54/// What the runner keeps about a run (never a secret's value).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[non_exhaustive]
57pub struct RunRecord {
58    /// The record format's version.
59    pub version: u32,
60    /// The run's name.
61    pub name: RunName,
62    /// The manifest the run was started from, absolute.
63    pub manifest: PathBuf,
64    /// Its SHA-256.
65    pub manifest_sha256: String,
66    /// Its target.
67    pub target: Target,
68    /// Its driver.
69    pub driver: Driver,
70    /// Its cloud, for a cloud target's run: what the reaper picks runs by.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub cloud: Option<Cloud>,
73    /// The Vagrant provider the run uses, when it has one.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub provider: Option<String>,
76    /// What the embedder calls the place the run is on (a server, an account).
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub host_label: Option<String>,
79    /// Where it stood after its last operation.
80    pub state: RunState,
81    /// Every param the run was started with: a later operation (a `down`) replays them, so it acts
82    /// on what was created, not on what the embedder's settings say now.
83    pub params: BTreeMap<String, String>,
84    /// The host ports a local VM run forwards from this computer, by `"<machine>/<port>"`: a free
85    /// one the runner pinned at the first start, kept so a resume forwards the same port.
86    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
87    pub vm_host_ports: BTreeMap<String, u16>,
88    /// When it was last started.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub started_at: Option<String>,
91    /// Its slot on its place (`${run.slot}`, 1 to 99), held from its first start to its `down`.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub slot: Option<u8>,
94    /// The login its SSH goes through first (`user@host`), when the embedder gave one.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub ssh_jump: Option<String>,
97    /// When it stops itself (the manifest's `expiry`), in seconds since the Unix epoch.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub expires_at: Option<u64>,
100    /// The last operation.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub last: Option<LastOp>,
103}
104
105impl RunRecord {
106    /// A record of a run never started yet.
107    pub(crate) fn fresh(name: RunName, manifest: PathBuf, sha256: String, target: Target, driver: Driver) -> RunRecord {
108        RunRecord {
109            version: RECORD_VERSION,
110            name,
111            manifest,
112            manifest_sha256: sha256,
113            target,
114            driver,
115            cloud: None,
116            provider: None,
117            host_label: None,
118            state: RunState::Absent,
119            params: BTreeMap::new(),
120            vm_host_ports: BTreeMap::new(),
121            started_at: None,
122            slot: None,
123            ssh_jump: None,
124            expires_at: None,
125            last: None,
126        }
127    }
128}
129
130/// The runner's state folder.
131#[derive(Debug, Clone)]
132pub(crate) struct Store {
133    runs: PathBuf,
134}
135
136impl Store {
137    /// The store under `home`, its `runs/` folder created owner-only.
138    pub(crate) fn open(home: &Path) -> Result<Store> {
139        let runs = home.join("runs");
140        private_dir(&runs).map_err(Error::io(&runs, "created"))?;
141        Ok(Store { runs })
142    }
143
144    /// Run `name`'s folder, created owner-only.
145    pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
146        let dir = self.runs.join(name.as_str());
147        private_dir(&dir).map_err(Error::io(&dir, "created"))?;
148        Ok(dir)
149    }
150
151    /// Run `name`'s lock file.
152    pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
153        self.runs.join(name.as_str()).join("lock")
154    }
155
156    /// Run `name`'s record, when it has one.
157    pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
158        let path = self.runs.join(name.as_str()).join("record.json");
159        match std::fs::read(&path) {
160            Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| Error::io(&path, "read")(e.into())),
161            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
162            Err(e) => Err(Error::io(&path, "read")(e)),
163        }
164    }
165
166    /// Writes `record` whole.
167    pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
168        let path = self.run_dir(&record.name)?.join("record.json");
169        let text = serde_json::to_vec_pretty(record).map_err(|e| Error::io(&path, "written")(e.into()))?;
170        write_private(&path, &text).map_err(Error::io(&path, "written"))
171    }
172
173    /// Every run's record, by name.
174    pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
175        let entries = std::fs::read_dir(&self.runs).map_err(Error::io(&self.runs, "read"))?;
176        let mut names: Vec<RunName> = entries.flatten().filter_map(|e| RunName::new(&e.file_name().to_string_lossy()).ok()).collect();
177        names.sort();
178        let mut records = Vec::new();
179        for name in names {
180            records.extend(self.record(&name)?);
181        }
182        Ok(records)
183    }
184
185    /// Run `name`'s event log, opened to append, trimmed to its newer half once it is long.
186    pub(crate) fn event_log(&self, name: &RunName) -> Result<std::fs::File> {
187        let path = self.run_dir(name)?.join("events.jsonl");
188        let lines = read_lines(&path)?;
189        if lines.len() > EVENTS_KEPT {
190            let newer: Vec<&str> = lines.iter().skip(lines.len().saturating_sub(EVENTS_KEPT / 2)).map(String::as_str).collect();
191            let kept = newer.join("\n") + "\n";
192            write_private(&path, kept.as_bytes()).map_err(Error::io(&path, "written"))?;
193        }
194        fs::append_private(&path).map_err(Error::io(&path, "written"))
195    }
196
197    /// Run `name`'s logged events, oldest first (a line that doesn't parse is skipped).
198    pub(crate) fn events(&self, name: &RunName) -> Result<Vec<Event>> {
199        let path = self.runs.join(name.as_str()).join("events.jsonl");
200        Ok(read_lines(&path)?.iter().filter_map(|l| serde_json::from_str(l).ok()).collect())
201    }
202}
203
204/// `path`'s lines; none when it doesn't exist.
205fn read_lines(path: &Path) -> Result<Vec<String>> {
206    match std::fs::File::open(path) {
207        Ok(f) => BufReader::new(f).lines().collect::<Result<_, _>>().map_err(Error::io(path, "read")),
208        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
209        Err(e) => Err(Error::io(path, "read")(e)),
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use std::io::Write;
216
217    use super::*;
218
219    fn record(name: &str) -> RunRecord {
220        RunRecord::fresh(
221            RunName::new(name).unwrap(),
222            "/labs/x/.isoloom/docker/run.json".into(),
223            "ab".repeat(32),
224            Target::Docker,
225            Driver::Compose,
226        )
227    }
228
229    #[test]
230    fn records_are_kept_per_run_and_listed_by_name() {
231        let home = tempfile::tempdir().unwrap();
232        let store = Store::open(home.path()).unwrap();
233        assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
234        let mut b = record("b");
235        b.params.insert("ISOLOOM_PUBLISH_FIXED".into(), "1".into());
236        store.save(&b).unwrap();
237        store.save(&record("a")).unwrap();
238        std::fs::create_dir_all(home.path().join("runs").join("Not A Run")).unwrap();
239        let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
240        assert_eq!(names, ["a", "b"]);
241        assert_eq!(store.record(&b.name).unwrap(), Some(b));
242    }
243
244    #[test]
245    fn the_event_log_is_trimmed_to_its_newer_half() {
246        let home = tempfile::tempdir().unwrap();
247        let store = Store::open(home.path()).unwrap();
248        let name = RunName::new("r").unwrap();
249        let mut log = store.event_log(&name).unwrap();
250        for seq in 0..=EVENTS_KEPT {
251            writeln!(log, "{{\"seq\":{seq}}}").unwrap();
252        }
253        drop(log);
254        drop(store.event_log(&name).unwrap());
255        let lines = read_lines(&home.path().join("runs/r/events.jsonl")).unwrap();
256        assert_eq!(lines.len(), EVENTS_KEPT / 2);
257        assert_eq!(lines.last().unwrap(), &format!("{{\"seq\":{EVENTS_KEPT}}}"));
258    }
259}