Skip to main content

isothrum_runner/
store.rs

1//! The runner's state: the home's transactional store ([`Store`], `<home>/state.db`: the runs,
2//! the journal of operations, the events, the resources each run made, what the runs' downloads
3//! fetched, the host ports reserved, the leases), and one folder per run for what the tools keep
4//! (the reference, with what each target keeps in a run's folder: `docs/reference/state.md`):
5//!
6//! ```text
7//! <home>/state.db            the store (SQLite, WAL: with `state.db-wal` and `state.db-shm`)
8//! <home>/ssh/                the runner's SSH key, `id_ed25519` and `.pub`, made on first use
9//! <home>/terraform-plugins/  the Terraform provider cache every run of this home shares
10//! <home>/runs/<run name>/
11//!   lock                the OS lock: one operation per run across processes
12//!   elevated/<token>/   an elevated session's folder (Hyper-V): each request's `env-<n>.json`,
13//!                       its variables, until the broker starts the program
14//!   …                   what each format's driver keeps: Vagrant's dotfile folder, Terraform's
15//!                       state
16//! ```
17//!
18//! A home starts empty: files another release left in it are neither read nor removed.
19
20#[cfg(any(windows, test))]
21mod acl;
22mod db;
23mod fs;
24mod lock;
25
26use std::path::{Path, PathBuf};
27use std::sync::Arc;
28
29use serde::{Deserialize, Serialize};
30
31#[cfg(test)]
32pub(crate) use db::dead_pid;
33pub use db::{
34    CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, MIRROR_FILE, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, Owner,
35    PortReservation, Recovered, Reserver, ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope, Store, Tx,
36};
37pub(crate) use fs::{create_private, if_there, private_dir, remove_path, write_private};
38
39/// Creates `dir` (with its missing parents) owner-only ([`private_dir`]); [`Error::Io`] naming it
40/// when that fails.
41pub(crate) fn create_dir(dir: &Path) -> Result<()> {
42    private_dir(dir).map_err(Error::io(dir, "created"))
43}
44
45/// Writes `contents` to `path` whole and owner-only ([`write_private`]); [`Error::Io`] naming it
46/// when that fails.
47pub(crate) fn write(path: &Path, contents: &[u8]) -> Result<()> {
48    write_private(path, contents).map_err(Error::io(path, "written"))
49}
50
51/// Removes `path`, a file or a folder, nothing there being fine ([`remove_path`]); [`Error::Io`]
52/// naming it when that fails.
53pub(crate) fn remove(path: &Path) -> Result<()> {
54    remove_path(path).map_err(Error::io(path, "removed"))
55}
56
57/// The JSON a runner wrote at `path` ([`write_json`]), read back; `T`'s default when nothing is
58/// there. [`Error::Io`] naming it when it can't be read or isn't what was written.
59pub(crate) fn read_json<T: serde::de::DeserializeOwned + Default>(path: &Path) -> Result<T> {
60    match if_there(std::fs::read_to_string(path)).map_err(Error::io(path, "read"))? {
61        Some(text) => serde_json::from_str(&text).map_err(|e| Error::io(path, "read")(std::io::Error::new(std::io::ErrorKind::InvalidData, e))),
62        None => Ok(T::default()),
63    }
64}
65
66/// `value` as JSON at `path`, its folder made first ([`create_dir`], [`write()`]).
67pub(crate) fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
68    if let Some(dir) = path.parent() {
69        create_dir(dir)?;
70    }
71    let json = serde_json::to_string(value).map_err(|e| Error::io(path, "written")(std::io::Error::other(e)))?;
72    write(path, json.as_bytes())
73}
74pub(crate) use lock::{RunLocks, hold};
75
76use crate::Result;
77use crate::error::{Error, ErrorCode};
78use crate::events::EventLog;
79use crate::name::RunName;
80use crate::project::Format;
81use crate::project::platform::{Cloud, Provider};
82use crate::state::{Desired, Op, Park, RunState};
83use crate::status::MachineStatus;
84
85/// The record format's version.
86const RECORD_VERSION: u32 = 0;
87
88/// A run's OS lock file, in its folder.
89const LOCK_FILE: &str = "lock";
90
91/// How many event lines a run's log keeps before an operation trims it to half.
92pub(crate) const EVENTS_KEPT: usize = 4000;
93
94/// The last operation on a run and how it ended.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[non_exhaustive]
97pub struct LastOp {
98    /// The operation.
99    pub op: Op,
100    /// Whether it succeeded.
101    pub ok: bool,
102    /// Its failure's code, when it failed.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub code: Option<ErrorCode>,
105    /// When it ended.
106    pub at: String,
107}
108
109impl LastOp {
110    /// Operation `op`, ended at `at` with failure `code`, or succeeded without one: the one place
111    /// `ok` is derived, so it never disagrees with `code`.
112    pub(crate) fn ended(op: Op, code: Option<ErrorCode>, at: String) -> LastOp {
113        LastOp {
114            op,
115            ok: code.is_none(),
116            code,
117            at,
118        }
119    }
120}
121
122/// What the runner keeps about a run (never a secret's value).
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124#[non_exhaustive]
125pub struct RunRecord {
126    /// The record format's version.
127    pub version: u32,
128    /// The run's name.
129    pub name: RunName,
130    /// The project folder the run was last brought up or updated from, absolute: what a later
131    /// operation that has only the record (a sweep's `down`) reopens.
132    #[serde(alias = "manifest")]
133    pub project: PathBuf,
134    /// The project's format.
135    #[serde(alias = "driver")]
136    pub format: Format,
137    /// Its cloud, for a run on one: what the embedder sweeps runs by.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub cloud: Option<Cloud>,
140    /// The Vagrant provider the run uses, when it has one.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub provider: Option<Provider>,
143    /// The Docker context its `docker` calls go to ([`crate::RunOptions::docker_context`]).
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub docker_context: Option<String>,
146    /// What the embedder calls the place the run is on (a server, an account).
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub host_label: Option<String>,
149    /// Where it stood after its last operation.
150    pub state: RunState,
151    /// How its last park parked it ([`Park::Pause`] or [`Park::Shutdown`]); none once a start,
152    /// a resume or a down followed. Meaningful while `state` is [`RunState::Parked`].
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub parked: Option<Park>,
155    /// When it was last started.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub started_at: Option<String>,
158    /// When it may be removed ([`crate::RunOptions::lifetime`] from its start), in seconds since
159    /// the Unix epoch: what the reaper reads.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub expires_at: Option<u64>,
162    /// The last operation.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub last: Option<LastOp>,
165    /// The values (not the secrets, which are never kept) the run was started or last updated
166    /// with ([`crate::RunOptions::with_env`]): every later operation gives them to the tool again
167    /// unless the caller gives a value of the same name, so a `down`, an auto-stop or an update
168    /// sees the variables its start applied (a Terraform module's `region`).
169    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
170    pub env: std::collections::BTreeMap<String, String>,
171}
172
173impl RunRecord {
174    /// Whether its lifetime ([`crate::RunOptions::lifetime`]) passed at `now` and its last
175    /// operation didn't leave it absent: a run that may still hold something, for a reaper to
176    /// take down.
177    #[must_use]
178    pub fn expired(&self, now: std::time::SystemTime) -> bool {
179        let now = crate::clock::unix_seconds(now);
180        self.state != RunState::Absent && self.expires_at.is_some_and(|at| at <= now)
181    }
182
183    /// A record of a run of the `format` project in `project`, never started yet.
184    pub(crate) fn fresh(name: RunName, project: PathBuf, format: Format) -> RunRecord {
185        RunRecord {
186            version: RECORD_VERSION,
187            name,
188            project,
189            format,
190            cloud: None,
191            provider: None,
192            docker_context: None,
193            host_label: None,
194            state: RunState::Absent,
195            parked: None,
196            started_at: None,
197            expires_at: None,
198            last: None,
199            env: std::collections::BTreeMap::new(),
200        }
201    }
202}
203
204/// What the runner last saw of a run when it read it (a status, an operation's own reads): its
205/// machines, and where their ports answer. Never an output's value, which may be secret. What a
206/// status shows while an operation holds the run, whose tools it then doesn't ask.
207#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
208#[non_exhaustive]
209pub struct LastObserved {
210    /// Every machine the tool reported, as read.
211    pub machines: Vec<MachineStatus>,
212}
213
214/// The runner's home: its folders, and its store.
215#[derive(Debug, Clone)]
216pub(crate) struct Home {
217    runs: PathBuf,
218    /// The home's store: the runs, the journal, the events, the resources, the leases.
219    db: Arc<Store>,
220}
221
222impl Home {
223    /// The home's folders under `home` (owner-only on Windows, see [`fs::private_home`]), its `runs/`
224    /// folder created owner-only.
225    pub(crate) fn open(home: &Path, profile: Option<&Path>) -> Result<Home> {
226        fs::private_home(home, profile).map_err(Error::io(home, "made owner-only"))?;
227        let runs = home.join("runs");
228        create_dir(&runs)?;
229        let db = Arc::new(Store::open(home)?);
230        Ok(Home { runs, db })
231    }
232
233    /// Run `name`'s folder, created owner-only.
234    pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
235        let dir = self.run_dir_path(name);
236        create_dir(&dir)?;
237        Ok(dir)
238    }
239
240    /// Run `name`'s folder (not made: [`Home::run_dir`] makes it).
241    pub(crate) fn run_dir_path(&self, name: &RunName) -> PathBuf {
242        self.runs.join(name.as_str())
243    }
244
245    /// Run `name`'s lock file.
246    pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
247        self.run_dir_path(name).join(LOCK_FILE)
248    }
249
250    /// The home's transactional store.
251    pub(crate) fn db(&self) -> &Arc<Store> {
252        &self.db
253    }
254
255    /// Run `name`'s record, when it has one.
256    pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
257        Ok(self.db.read(|tx| tx.run(name))?.map(|r| r.record))
258    }
259
260    /// Records `record`'s fields; a new run's row starts in the record's state. An existing run's
261    /// state moves only by a transition ([`db::Tx::apply`]).
262    pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
263        self.run_dir(&record.name)?;
264        self.db.write(|tx| tx.save_record(record, Desired::Running))
265    }
266
267    /// Records `record`, an adopted deployment's, as a run that is up: a new row is made ready,
268    /// one an earlier `down` left absent moves to ready ([`crate::state::Transition::adopted`]).
269    pub(crate) fn save_adopted(&self, record: &RunRecord) -> Result<()> {
270        self.run_dir(&record.name)?;
271        self.db.write(|tx| {
272            tx.save_record(record, Desired::Running)?;
273            if let Some(row) = tx.run(&record.name)?
274                && row.state != RunState::Ready
275            {
276                tx.apply(&record.name, crate::state::Transition::adopted(row.state)?)?;
277            }
278            Ok(())
279        })
280    }
281
282    /// Every run's record, by name.
283    pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
284        self.db.read(|tx| tx.runs().map(|rows| rows.into_iter().map(|r| r.record).collect()))
285    }
286
287    /// Trims run `name`'s events to the newer half once they are many.
288    pub(crate) fn trim_event_log(&self, name: &RunName) -> Result<()> {
289        self.db.write(|tx| {
290            let (events, unreadable) = tx.events_after(EventCursor::default(), Some(name), EVENTS_KEPT + 1)?;
291            if events.len() + unreadable > EVENTS_KEPT {
292                tx.trim_events(name, EVENTS_KEPT / 2)?;
293            }
294            Ok(())
295        })
296    }
297
298    /// Run `name`'s logged events, oldest first, with how many of its rows aren't an event this
299    /// runner reads (another version's kind).
300    pub(crate) fn events(&self, name: &RunName) -> Result<EventLog> {
301        let (events, unreadable) = self.db.read(|tx| tx.events_after(EventCursor::default(), Some(name), usize::MAX))?;
302        Ok(EventLog {
303            events: events.into_iter().map(|(_, e)| e).collect(),
304            unreadable,
305        })
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    fn record(name: &str) -> RunRecord {
314        RunRecord::fresh(RunName::new(name).unwrap(), "/work/x".into(), Format::Compose)
315    }
316
317    #[test]
318    fn records_are_kept_per_run_and_listed_by_name() {
319        let home = tempfile::tempdir().unwrap();
320        let store = Home::open(home.path(), None).unwrap();
321        assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
322        let mut b = record("b");
323        b.host_label = Some("server".into());
324        store.save(&b).unwrap();
325        store.save(&record("a")).unwrap();
326        let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
327        assert_eq!(names, ["a", "b"]);
328        assert_eq!(store.record(&b.name).unwrap(), Some(b));
329    }
330}