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
114/// How current the daemon's doctor checks are (ADR 0132). Times are seconds since the Unix epoch.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "kebab-case", tag = "kind")]
117pub enum DoctorState {
118    /// No run has finished since the daemon started.
119    NotRun,
120    /// Run for the config the daemon runs with, recently enough to stand.
121    Ready {
122        /// When the run finished.
123        at: u64,
124    },
125    /// Run for a config replaced since, or too long ago: they may no longer hold. A new run is under way or due.
126    Stale {
127        /// When the run finished.
128        at: u64,
129    },
130    /// The last run did not finish.
131    Failed {
132        /// When it gave up.
133        at: u64,
134        /// Why.
135        error: String,
136    },
137    /// A state from a newer daemon than this client knows: the checks are not known to be current.
138    #[serde(other)]
139    Unknown,
140}
141
142impl DoctorState {
143    /// Why the checks are not to be read as current, as every client says it; `None` when they are.
144    pub fn line(&self, now: u64) -> Option<String> {
145        match self {
146            DoctorState::Ready { .. } => None,
147            DoctorState::NotRun => Some("Host checks have not finished yet".to_owned()),
148            DoctorState::Stale { at } => Some(format!(
149                "Host checks are from {} and may no longer hold; a new run is due",
150                super::ago(*at, now)
151            )),
152            DoctorState::Failed { error, .. } => {
153                Some(format!("Host checks could not finish: {error}"))
154            }
155            DoctorState::Unknown => {
156                Some("Host checks are in a state this client does not know".to_owned())
157            }
158        }
159    }
160}
161
162/// One thing the host needs to run runners. Its `Display` is the line `runnerd doctor` prints.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct Check {
165    /// Such as `Docker` or `sysbox`.
166    pub name: String,
167    /// The outcome.
168    pub status: CheckStatus,
169    /// What was found.
170    pub detail: String,
171    /// What to run or change to pass, for a failed check.
172    pub fix: Option<String>,
173}
174
175/// How a [`Check`] came out.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "kebab-case")]
178pub enum CheckStatus {
179    /// Ready.
180    Pass,
181    /// Runners cannot run until it is fixed.
182    Fail,
183    /// Works, but unsafe.
184    Warn,
185    /// Not checked, because a check it depends on failed or no config was given.
186    Skip,
187    /// For information.
188    Info,
189}
190
191impl CheckStatus {
192    /// Its label, as every client shows it: `ok`, `FAIL`, `WARN`, `skip` or `info`; a failure and a warning in
193    /// capitals so they stand out uncoloured.
194    pub fn label(self) -> &'static str {
195        match self {
196            CheckStatus::Pass => "ok",
197            CheckStatus::Fail => "FAIL",
198            CheckStatus::Warn => "WARN",
199            CheckStatus::Skip => "skip",
200            CheckStatus::Info => "info",
201        }
202    }
203
204    /// What it means for the reader: a warning is not a failure.
205    pub fn tone(self) -> super::Tone {
206        match self {
207            CheckStatus::Pass => super::Tone::Good,
208            CheckStatus::Fail => super::Tone::Bad,
209            CheckStatus::Warn => super::Tone::Warn,
210            CheckStatus::Skip => super::Tone::Quiet,
211            CheckStatus::Info => super::Tone::Neutral,
212        }
213    }
214}
215
216impl Doctor {
217    /// Whether runners can run as far as the checks say: they are of a current run, or a daemon that says nothing of
218    /// its run, and none failed. Warnings, skips and notes pass; checks that are not current never do.
219    pub fn passed(&self) -> bool {
220        matches!(self.state, None | Some(DoctorState::Ready { .. }))
221            && Doctor::all_passed(&self.checks)
222    }
223
224    /// `Doctor::passed` of checks not yet in a `Doctor`, as `runnerd doctor` runs them.
225    pub fn all_passed(checks: &[Check]) -> bool {
226        !checks.iter().any(|check| check.status == CheckStatus::Fail)
227    }
228}
229
230impl fmt::Display for Check {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        let status = self.status.label();
233        write!(f, "{status:<5} {}: {}", self.name, self.detail)?;
234        if let Some(fix) = &self.fix {
235            for (i, line) in fix.lines().enumerate() {
236                let label = if i == 0 { "fix:" } else { "" };
237                write!(f, "\n      {label:<4} {line}")?;
238            }
239        }
240        Ok(())
241    }
242}