Skip to main content

runnerd_core/api/
control.rs

1//! The control endpoints' types: pausing with or without cancelling running jobs, what a refused request names,
2//! the config file and its check, and the doctor's checks. Plain data; the engine and the daemon act on them.
3
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use crate::api::AdmissionPolicy;
9
10/// A runner of this daemon that holds a slot, and the job it runs, if it took one.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct RunningJob {
13    /// `owner/name` the runner is registered on.
14    pub repository: String,
15    /// The runner's name, also its container's.
16    pub runner: String,
17    /// The job's ID; `None` while the runner waits for a job or before its log shows which it took.
18    pub job: Option<u64>,
19}
20
21impl fmt::Display for RunningJob {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self.job {
24            Some(job) => write!(f, "job {job} on {}", self.runner),
25            None => write!(f, "{}", self.runner),
26        }
27    }
28}
29
30/// The body of a 409 refused because runners use what the request would change. Has the `message` of an
31/// [`ErrorResponse`](super::ErrorResponse), so a client that reads only that still gets it.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Busy {
34    /// What went wrong, naming the jobs.
35    pub message: String,
36    /// The runners in the way.
37    pub jobs: Vec<RunningJob>,
38}
39
40/// `POST /v1/repositories/{owner}/{name}/pause` and `POST /v1/repositories/pause` query parameters.
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct PauseQuery {
43    /// Cancel the repository's running jobs and remove their runners. Without it, a pause while the repository
44    /// runs a job is refused with [`Busy`].
45    #[serde(default)]
46    pub force: bool,
47}
48
49/// `POST /v1/repositories/{owner}/{name}/pause` and `POST /v1/repositories/pause`: the repository, or every one,
50/// is paused, and stays paused when the daemon restarts.
51#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
52pub struct Paused {
53    /// The runners a forced pause stopped: those whose runs it cancelled go once they report the job cancelled,
54    /// within 90 s, the others at once. Empty without `force`.
55    pub stopped: Vec<RunningJob>,
56}
57
58/// `GET /v1/config`: the config the daemon runs with. Parse `text` with `config::Config::parse` for its fields.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct ConfigFile {
61    /// The file it was read from, and `PUT /v1/config` writes.
62    pub path: String,
63    /// The TOML, as last loaded or written by the daemon, with each `[[notify.targets]]` entry's `url` and header
64    /// values shown as `config::SECRET_SHOWN`; `PUT /v1/config` puts them back.
65    pub text: String,
66    /// `config::revision` of `text`: send it as `PUT /v1/config?revision=` and a config replaced meanwhile, as
67    /// by auto sizing, is not overwritten (409).
68    pub revision: String,
69}
70
71/// `PUT /v1/config` query parameters.
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct ReplaceQuery {
74    /// The revision of the config the new text was made from; absent, the text replaces whatever runs.
75    pub revision: Option<String>,
76}
77
78/// `POST /v1/config/check` and `PUT /v1/config`: what `runnerd check-config` prints for a config. `PUT` refuses
79/// an invalid one with 422 and this body, which has an [`ErrorResponse`](super::ErrorResponse)'s `message`.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ConfigCheck {
82    /// Whether the daemon can run it.
83    pub valid: bool,
84    /// `valid, memory caps sum to …`, or why it is not valid.
85    pub message: String,
86    /// What a valid config should still fix.
87    pub warnings: Vec<String>,
88    /// `[host] admission`, which decides what must fit `MemoryMax`: `memory_caps` under caps, `memory_needed`
89    /// under measured.
90    pub admission: AdmissionPolicy,
91    /// Bytes every slot and the mirror take at their caps, all at once, when it parses.
92    pub memory_caps: Option<u64>,
93    /// Bytes the admission rule must fit in `MemoryMax`, when it parses: `memory_caps` under caps; under measured,
94    /// the largest single runner with the mirror.
95    pub memory_needed: Option<u64>,
96    /// The `MemoryMax` of the slice it names; `None` when unlimited or unknown.
97    pub memory_max: Option<u64>,
98    /// From `PUT /v1/config`, once written: the revision of the text written, to make the next change against.
99    /// `None` from a check.
100    pub revision: Option<String>,
101}
102
103/// `GET /v1/doctor`: what `runnerd doctor` checks, for the config the daemon runs with.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Doctor {
106    /// In the order a new user fixes them.
107    pub checks: Vec<Check>,
108    /// How current `checks` are (ADR 0132); absent from `runnerd doctor` and from a daemon before 0.2, which ran
109    /// them for the request.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub state: Option<DoctorState>,
112}
113
114impl Doctor {
115    /// What a client says while it waits for the checks.
116    pub const CHECKING: &'static str = "Checking the host";
117
118    /// The checks as a client lays them out at `now`: those that need the reader first, the rest folded into a count
119    /// by label. Checks that are not current need nothing of the reader: they all fold, under the line saying why.
120    pub fn summary(&self, now: u64) -> DoctorSummary<'_> {
121        let not_current = self.state.as_ref().and_then(|state| state.line(now));
122        let current = not_current.is_none();
123        let (problems, rest): (Vec<&Check>, Vec<&Check>) = self.checks.iter().partition(|check| {
124            current && matches!(check.status.tone(), super::Tone::Bad | super::Tone::Warn)
125        });
126        let mut counts: Vec<CheckCount> = Vec::new();
127        for check in &rest {
128            let label = check.status.label();
129            match counts.iter_mut().find(|count| count.label == label) {
130                Some(count) => count.count += 1,
131                None => counts.push(CheckCount { label, count: 1 }),
132            }
133        }
134        DoctorSummary {
135            not_current,
136            problems,
137            rest,
138            counts,
139        }
140    }
141}
142
143/// The doctor's checks laid out for a reader, from [`Doctor::summary`].
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct DoctorSummary<'doctor> {
146    /// Why the checks are not to be read as current, as [`DoctorState::line`] says it; `None` when they are.
147    pub not_current: Option<String>,
148    /// Current checks that failed or warn, in the doctor's order: each stands with its fix.
149    pub problems: Vec<&'doctor Check>,
150    /// Every other check, in the doctor's order: folded into one line.
151    pub rest: Vec<&'doctor Check>,
152    /// How many of `rest` carry each label, in the order the labels first come.
153    pub counts: Vec<CheckCount>,
154}
155
156/// How many checks carry one [`CheckStatus::label`].
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct CheckCount {
159    /// Such as `ok`.
160    pub label: &'static str,
161    /// At least 1.
162    pub count: usize,
163}
164
165/// `GET /v1/doctor` query parameters.
166#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
167pub struct DoctorQuery {
168    /// Take the last run as it stands when it is of the config running and no older than the daemon's own refresh
169    /// (10 minutes), instead of asking for a new one past a minute. A daemon before 0.2 ignores it.
170    #[serde(default)]
171    pub recent: bool,
172}
173
174/// How current the daemon's doctor checks are (ADR 0132). Times are seconds since the Unix epoch.
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(rename_all = "kebab-case", tag = "kind")]
177pub enum DoctorState {
178    /// No run has finished since the daemon started.
179    NotRun,
180    /// Run for the config the daemon runs with, recently enough to stand.
181    Ready {
182        /// When the run finished.
183        at: u64,
184    },
185    /// Run for a config replaced since, or too long ago: they may no longer hold. A new run is under way or due.
186    Stale {
187        /// When the run finished.
188        at: u64,
189    },
190    /// The last run did not finish.
191    Failed {
192        /// When it gave up.
193        at: u64,
194        /// Why.
195        error: String,
196    },
197    /// A state from a newer daemon than this client knows: the checks are not known to be current.
198    #[serde(other)]
199    Unknown,
200}
201
202impl DoctorState {
203    /// How old current checks are, as every client says it beside them: `Checked 4m 00s ago`; `None` when they are not
204    /// current, which [`DoctorState::line`] says.
205    pub fn checked(&self, now: u64) -> Option<String> {
206        match self {
207            DoctorState::Ready { at } => Some(format!("Checked {}", super::ago(*at, now))),
208            DoctorState::NotRun
209            | DoctorState::Stale { .. }
210            | DoctorState::Failed { .. }
211            | DoctorState::Unknown => None,
212        }
213    }
214
215    /// Why the checks are not to be read as current, as every client says it; `None` when they are.
216    pub fn line(&self, now: u64) -> Option<String> {
217        match self {
218            DoctorState::Ready { .. } => None,
219            DoctorState::NotRun => Some("Host checks have not finished yet".to_owned()),
220            DoctorState::Stale { at } => Some(format!(
221                "Host checks are from {} and may no longer hold; a new run is due",
222                super::ago(*at, now)
223            )),
224            DoctorState::Failed { error, .. } => {
225                Some(format!("Host checks could not finish: {error}"))
226            }
227            DoctorState::Unknown => {
228                Some("Host checks are in a state this client does not know".to_owned())
229            }
230        }
231    }
232}
233
234/// One thing the host needs to run runners. Its `Display` is the line `runnerd doctor` prints.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct Check {
237    /// Such as `Docker` or `sysbox`.
238    pub name: String,
239    /// The outcome.
240    pub status: CheckStatus,
241    /// What was found.
242    pub detail: String,
243    /// What to run or change to pass, for a failed check.
244    pub fix: Option<String>,
245}
246
247/// How a [`Check`] came out.
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "kebab-case")]
250pub enum CheckStatus {
251    /// Ready.
252    Pass,
253    /// Runners cannot run until it is fixed.
254    Fail,
255    /// Works, but unsafe.
256    Warn,
257    /// Not checked, because a check it depends on failed or no config was given.
258    Skip,
259    /// For information.
260    Info,
261}
262
263impl CheckStatus {
264    /// Its label, as every client shows it: `ok`, `FAIL`, `WARN`, `skip` or `info`; a failure and a warning in
265    /// capitals so they stand out uncoloured.
266    pub fn label(self) -> &'static str {
267        match self {
268            CheckStatus::Pass => "ok",
269            CheckStatus::Fail => "FAIL",
270            CheckStatus::Warn => "WARN",
271            CheckStatus::Skip => "skip",
272            CheckStatus::Info => "info",
273        }
274    }
275
276    /// What it means for the reader: a warning is not a failure.
277    pub fn tone(self) -> super::Tone {
278        match self {
279            CheckStatus::Pass => super::Tone::Good,
280            CheckStatus::Fail => super::Tone::Bad,
281            CheckStatus::Warn => super::Tone::Warn,
282            CheckStatus::Skip => super::Tone::Quiet,
283            CheckStatus::Info => super::Tone::Neutral,
284        }
285    }
286}
287
288impl Doctor {
289    /// Whether runners can run as far as the checks say: they are of a current run, or a daemon that says nothing of
290    /// its run, and none failed. Warnings, skips and notes pass; checks that are not current never do.
291    pub fn passed(&self) -> bool {
292        matches!(self.state, None | Some(DoctorState::Ready { .. }))
293            && Doctor::all_passed(&self.checks)
294    }
295
296    /// `Doctor::passed` of checks not yet in a `Doctor`, as `runnerd doctor` runs them.
297    pub fn all_passed(checks: &[Check]) -> bool {
298        !checks.iter().any(|check| check.status == CheckStatus::Fail)
299    }
300}
301
302impl fmt::Display for Check {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        let status = self.status.label();
305        write!(f, "{status:<5} {}: {}", self.name, self.detail)?;
306        if let Some(fix) = &self.fix {
307            for (i, line) in fix.lines().enumerate() {
308                let label = if i == 0 { "fix:" } else { "" };
309                write!(f, "\n      {label:<4} {line}")?;
310            }
311        }
312        Ok(())
313    }
314}
315
316#[cfg(test)]
317mod tests;