isothrum_runner/reap.rs
1//! The reaper's half in the runner, so an abandoned run can't keep billing:
2//!
3//! - [`Runner::expired`]: the recorded runs whose expiry passed and that may still hold
4//! something. Destroying one is its `down`, which replays the params it was applied with (the
5//! embedder gives the connection, as for any operation).
6//! - [`Runner::orphans`]: what a cloud still holds tagged past its expiry that no recorded run's
7//! state covers, read through the cloud's own command line (its argv, never a shell). An orphan
8//! is only listed, never deleted: no state says what it belongs to, so a person removes it.
9//!
10//! The sweep's schedule is the embedder's (every few minutes, say; the `isothrum reap` command
11//! sweeps once).
12
13mod tags;
14
15use std::collections::BTreeSet;
16use std::time::{Duration, SystemTime};
17
18use isoloom_manifest::Cloud;
19pub use tags::{Place, Tagged};
20
21use crate::Result;
22use crate::clock::unix_seconds;
23use crate::executor::{Progress, within};
24use crate::process::{ProcessRunner, ProcessSpec};
25use crate::runner::Runner;
26use crate::state::RunState;
27use crate::store::RunRecord;
28
29/// How long a cloud's query may go without progress.
30const QUERY_LIMIT: Duration = Duration::from_secs(120);
31/// The id a query's timeout reads as.
32const QUERY_STEP: &str = "reap";
33
34/// What a cloud still holds past its expiry that no recorded run covers.
35#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
36#[non_exhaustive]
37pub struct Orphans {
38 /// The resources, as the cloud lists them.
39 pub resources: Vec<Tagged>,
40 /// What couldn't be read: a query whose command line is missing or fails, or whose answer is
41 /// of another shape (the cloud wasn't checked there), and a resource no recorded run covers
42 /// whose expiry tag isn't a time (whether it is past its expiry is unknown).
43 pub unread: Vec<String>,
44}
45
46impl Orphans {
47 /// Adds what of `found`, a query's answer, no recorded run covers (`covered`): a resource
48 /// past its expiry at `now`, and one whose expiry can't be read.
49 fn classify(&mut self, found: Vec<tags::Found>, now: u64, covered: &BTreeSet<String>) {
50 for item in found {
51 match item {
52 Ok(t) if orphaned(&t, now, covered) => self.resources.push(t),
53 Err(e) if !is_covered(e.instance.as_ref(), covered) => self.unread.push(e.to_string()),
54 Ok(_) | Err(_) => {}
55 }
56 }
57 }
58}
59
60impl Runner {
61 /// The recorded runs whose expiry passed at `now` and whose last operation didn't leave them
62 /// absent: the reaper's input. Reads files only.
63 ///
64 /// # Errors
65 ///
66 /// Fails with `io` when a record can't be read.
67 pub fn expired(&self, now: SystemTime) -> Result<Vec<RunRecord>> {
68 let now = unix_seconds(now);
69 let records = self.store.records()?;
70 Ok(records
71 .into_iter()
72 .filter(|r| r.state != RunState::Absent && r.expires_at.is_some_and(|at| at <= now))
73 .collect())
74 }
75
76 /// What `cloud` holds in `place` tagged with an expiry past `now` that no recorded run's
77 /// Terraform state covers. A command line that is missing or fails is said in
78 /// [`Orphans::unread`], never an error: the sweep goes on.
79 ///
80 /// # Errors
81 ///
82 /// Fails with `io` when a record or a recorded run's Terraform state can't be read or parsed:
83 /// what that state holds is unknown, so nothing could be told an orphan.
84 pub async fn orphans(&self, cloud: Cloud, place: &Place, now: SystemTime) -> Result<Orphans> {
85 let covered = self.covered(cloud)?;
86 let now = unix_seconds(now);
87 let mut out = Orphans::default();
88 for spec in tags::queries(cloud, place) {
89 let answer = query(self.config.processes.as_ref(), &spec).await.and_then(|text| tags::parse(cloud, &text));
90 match answer {
91 Ok(found) => out.classify(found, now, &covered),
92 Err(why) => out.unread.push(format!("`{}`: {why}", spec.line())),
93 }
94 }
95 Ok(out)
96 }
97
98 /// The environments the states of `cloud`'s recorded runs hold. A run with no state holds
99 /// none; a state that exists but can't be read or parsed fails the sweep, since what it holds
100 /// would otherwise read as orphans.
101 fn covered(&self, cloud: Cloud) -> Result<BTreeSet<String>> {
102 let mut out = BTreeSet::new();
103 for record in self.store.records()?.into_iter().filter(|r| r.cloud == Some(cloud)) {
104 let dir = self.store.run_dir(&record.name)?;
105 if let Some(state) = crate::driver::terraform::state::read_json(&dir)? {
106 tags::instances_in_state(&state, &mut out);
107 }
108 }
109 Ok(out)
110 }
111}
112
113/// Whether `t` is past its expiry at `now` and no recorded run covers its environment.
114fn orphaned(t: &Tagged, now: u64, covered: &BTreeSet<String>) -> bool {
115 t.expires_at.is_some_and(|at| at <= now) && !is_covered(t.instance.as_ref(), covered)
116}
117
118/// Whether a recorded run covers `instance`, a resource's environment (none when it doesn't say).
119fn is_covered(instance: Option<&String>, covered: &BTreeSet<String>) -> bool {
120 instance.is_some_and(|i| covered.contains(i))
121}
122
123/// What `spec` prints, when it ran to a success without going [`QUERY_LIMIT`] without progress
124/// (as every tool call's limit counts); else why not.
125async fn query(processes: &dyn ProcessRunner, spec: &ProcessSpec) -> std::result::Result<String, String> {
126 let progress = Progress::new();
127 let out = within(QUERY_STEP, QUERY_LIMIT, &progress, progress.capture(processes, spec))
128 .await
129 .map_err(|e| match e {
130 crate::Error::Timeout { timed_out, .. } => timed_out.to_string(),
131 other => other.to_string(),
132 })?;
133 out.output().map_err(|why| format!("failed: {why}"))
134}
135
136#[cfg(test)]
137mod tests;