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). `None` from a daemon before it.
68    #[serde(default)]
69    pub revision: Option<String>,
70}
71
72/// `PUT /v1/config` query parameters.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
74pub struct ReplaceQuery {
75    /// The revision of the config the new text was made from; absent, the text replaces whatever runs.
76    pub revision: Option<String>,
77}
78
79/// `POST /v1/config/check` and `PUT /v1/config`: what `runnerd check-config` prints for a config. `PUT` refuses
80/// an invalid one with 422 and this body, which has an [`ErrorResponse`](super::ErrorResponse)'s `message`.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct ConfigCheck {
83    /// Whether the daemon can run it.
84    pub valid: bool,
85    /// `valid, memory caps sum to …`, or why it is not valid.
86    pub message: String,
87    /// What a valid config should still fix.
88    pub warnings: Vec<String>,
89    /// `[host] admission`, which decides what must fit `MemoryMax`: `memory_caps` under caps, `memory_needed`
90    /// under measured. Caps from a daemon before it said.
91    #[serde(default)]
92    pub admission: AdmissionPolicy,
93    /// Bytes every slot and the mirror take at their caps, all at once, when it parses.
94    pub memory_caps: Option<u64>,
95    /// Bytes the admission rule must fit in `MemoryMax`, when it parses: `memory_caps` under caps; under measured,
96    /// the largest single runner with the mirror. `None` from a daemon before it said.
97    #[serde(default)]
98    pub memory_needed: Option<u64>,
99    /// The `MemoryMax` of the slice it names; `None` when unlimited or unknown.
100    pub memory_max: Option<u64>,
101    /// From `PUT /v1/config`, once written: the revision of the text written, to make the next change against.
102    /// `None` from a check, or from a daemon before it.
103    #[serde(default)]
104    pub revision: Option<String>,
105}
106
107/// `GET /v1/doctor`: what `runnerd doctor` checks, for the config the daemon runs with.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Doctor {
110    /// In the order a new user fixes them.
111    pub checks: Vec<Check>,
112}
113
114/// One thing the host needs to run runners. Its `Display` is the line `runnerd doctor` prints.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct Check {
117    /// Such as `Docker` or `sysbox`.
118    pub name: String,
119    /// The outcome.
120    pub status: CheckStatus,
121    /// What was found.
122    pub detail: String,
123    /// What to run or change to pass, for a failed check.
124    pub fix: Option<String>,
125}
126
127/// How a [`Check`] came out.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
129#[serde(rename_all = "kebab-case")]
130pub enum CheckStatus {
131    /// Ready.
132    Pass,
133    /// Runners cannot run until it is fixed.
134    Fail,
135    /// Works, but unsafe.
136    Warn,
137    /// Not checked, because a check it depends on failed or no config was given.
138    Skip,
139    /// For information.
140    Info,
141}
142
143impl CheckStatus {
144    /// Its label, as every client shows it: `ok`, `FAIL`, `WARN`, `skip` or `info`; a failure and a warning in
145    /// capitals so they stand out uncoloured.
146    pub fn label(self) -> &'static str {
147        match self {
148            CheckStatus::Pass => "ok",
149            CheckStatus::Fail => "FAIL",
150            CheckStatus::Warn => "WARN",
151            CheckStatus::Skip => "skip",
152            CheckStatus::Info => "info",
153        }
154    }
155
156    /// What it means for the reader: a warning is not a failure.
157    pub fn tone(self) -> super::Tone {
158        match self {
159            CheckStatus::Pass => super::Tone::Good,
160            CheckStatus::Fail => super::Tone::Bad,
161            CheckStatus::Warn => super::Tone::Warn,
162            CheckStatus::Skip => super::Tone::Quiet,
163            CheckStatus::Info => super::Tone::Neutral,
164        }
165    }
166}
167
168impl Doctor {
169    /// Whether runners can run: no check failed. Warnings, skips and notes pass.
170    pub fn passed(&self) -> bool {
171        Doctor::all_passed(&self.checks)
172    }
173
174    /// `Doctor::passed` of checks not yet in a `Doctor`, as `runnerd doctor` runs them.
175    pub fn all_passed(checks: &[Check]) -> bool {
176        !checks.iter().any(|check| check.status == CheckStatus::Fail)
177    }
178}
179
180impl fmt::Display for Check {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        let status = self.status.label();
183        write!(f, "{status:<5} {}: {}", self.name, self.detail)?;
184        if let Some(fix) = &self.fix {
185            for (i, line) in fix.lines().enumerate() {
186                let label = if i == 0 { "fix:" } else { "" };
187                write!(f, "\n      {label:<4} {line}")?;
188            }
189        }
190        Ok(())
191    }
192}