runnerd_core/api.rs
1//! The daemon's JSON API, version 1: the request and response types every client deserializes, and the
2//! principal a transport authenticates. Plain data only: no I/O, no Docker or GitHub types, no secrets but a
3//! [`Pairing`]'s one-time link, which its `Debug` leaves out.
4//!
5//! Routes, all under the authenticated principal:
6//!
7//! | Route | Body |
8//! |---|---|
9//! | `GET /v1/status` | [`Status`] |
10//! | `POST /v1/repositories/{owner}/{name}/pause?`[`PauseQuery`] | [`Paused`]; 409 [`Busy`] while it runs a job |
11//! | `POST /v1/repositories/{owner}/{name}/resume` | none, 204 |
12//! | `POST /v1/repositories/pause?`[`PauseQuery`] | [`Paused`]; 409 [`Busy`] while any runs a job, pausing none |
13//! | `POST /v1/repositories/resume` | none, 204: every repository resumed |
14//! | `POST /v1/profiles/{name}/reseed` | none, 202; 409 while it reseeds; `cache.reseeded` when done |
15//! | `POST /v1/caches/{name}/clean` | none, 204; 409 [`Busy`] while a runner uses it |
16//! | `GET /v1/config` | [`ConfigFile`] |
17//! | `POST /v1/config/check` | TOML in, [`ConfigCheck`] |
18//! | `PUT /v1/config` | TOML in, [`ConfigCheck`]; 422 [`ConfigCheck`] when invalid |
19//! | `GET /v1/doctor` | [`Doctor`] |
20//! | `POST /v1/shutdown` | [`ShutdownRequest`] in, 202 [`ShutdownAnswer`] |
21//! | `GET /v1/dashboard` | [`Dashboard`] |
22//! | `POST /v1/dashboard/sign-out` | none, 204 |
23//! | `POST /v1/dashboard/pairings?`[`PairingQuery`] | [`Pairings`]; 409 when the dashboard is off or has no `[web] origins` |
24//! | `GET /v1/jobs?`[`JobQuery`] | [`JobPage`] |
25//! | `GET /v1/jobs/{id}` | [`Job`] |
26//! | `GET /v1/jobs/{id}/samples` | [`SampleSeries`] |
27//! | `GET /v1/jobs/{id}/logs?`[`LogQuery`] | `text/plain`, one line per log line |
28//! | `GET /v1/host/samples?`[`HostSampleQuery`] | [`HostSamples`] |
29//! | `GET /v1/stats?`[`StatsQuery`] | [`Stats`] |
30//! | `GET /v1/activity?`[`ActivityQuery`] | [`Activity`] |
31//! | `GET /v1/sizing?`[`SizingQuery`] | [`Sizing`] |
32//! | `GET /v1/insights?`[`InsightsQuery`] | [`Insights`] |
33//! | `GET /v1/digest` | [`Digest`] |
34//! | `GET /v1/savings` | [`Savings`] |
35//! | `POST /v1/notify/test?`[`NotifyTestQuery`] | [`NotifyTest`]; 404 without `[notify]` targets or with no such one |
36//! | `GET /v1/caches` | [`Caches`] |
37//! | `GET /v1/caches/history?`[`CacheHistoryQuery`] | [`CacheHistory`] |
38//! | `GET /v1/events?`[`EventQuery`] | `text/event-stream` of [`EventEnvelope`] |
39//! | `GET /v1/records` | [`Records`] |
40//! | `DELETE /v1/records/{job}` | [`RemovedRecords`]; 409 while a shell is open in it |
41//! | `DELETE /v1/records?`[`RemoveRecordsQuery`] | [`RemovedRecords`]; records with an open shell stay |
42//! | `POST /v1/records/{job}/shell?`[`ShellQuery`] | `Upgrade:` [`SHELL_PROTOCOL`], 101, then the shell's terminal; 409 when the budget is full |
43//!
44//! Errors carry an [`ErrorResponse`].
45
46use serde::{Deserialize, Serialize};
47
48mod admission;
49mod budget;
50mod control;
51mod events;
52mod insights;
53mod jobs;
54mod labels;
55mod records;
56mod results;
57mod savings;
58mod sizing;
59mod slots;
60mod stats;
61mod storage;
62mod tone;
63mod units;
64
65pub use admission::{Admission, AdmissionPolicy, Basis, CpuAdmission, JobPeak, cores, cpus};
66pub use budget::{
67 BudgetParts, ClosedKind, ClosedPart, FreePart, HeldKind, HeldPart, Reading, SlotPart,
68};
69pub use control::{
70 Busy, Check, CheckStatus, ConfigCheck, ConfigFile, Doctor, PauseQuery, Paused, ReplaceQuery,
71 RunningJob,
72};
73pub use events::{Event, EventEnvelope, EventQuery, RunnerFailure};
74pub use insights::{
75 AutoNote, Delivery, Digest, INSIGHT_DAYS, INSIGHT_DAYS_MAX, Insight, InsightKind, Insights,
76 InsightsQuery, LongWait, Notification, NotifyEvent, NotifyTest, NotifyTestQuery, Priority,
77 RepositoryWaits, RunLink, Severity, WaitSpread, WeekWaits,
78};
79pub use jobs::{
80 Activity, ActivityQuery, Bucket, BuildCacheCounts, BuildCacheStats, CacheHistory,
81 CacheHistoryQuery, CacheKind, CacheSize, CacheVolume, Caches, ChartLine, ChartLineKind,
82 ChartLines, Holder, HostMemory, HostSample, HostSampleQuery, HostSamples, Job, JobMetrics,
83 JobPage, JobQuery, JobRunner, JobState, JobSummary, JobTitle, Limit, LimitSource, Limits,
84 LogQuery, LogSummary, Milestone, Outcome, OutcomeKind, Phase, PhaseKind, Pressure,
85 RunComparison, Sample, SampleSeries, SampleUsage, Started, Stats, StatsQuery, StatsRow, Step,
86 Timeline, Total, job_title,
87};
88pub use labels::{Column, View};
89pub use records::{
90 Record, RecordLimits, RecordNote, RecordRemoval, Records, RemoveRecordsQuery, RemovedRecords,
91 SHELL_PROTOCOL, ShellQuery,
92};
93pub use results::{force_pause_consequence, reseed_requested, reseeded};
94pub use savings::{
95 Period, PricedRun, PricedRunner, Pricing, PricingHistory, SELF_HOSTED_RATE, SavedWindow,
96 Savings, Sku, Usd, Visibility, billed_minutes, reads_since,
97};
98pub use sizing::{
99 Advice, AutoPlan, GRANULE, JobSizing, MemoryBound, MemoryHold, Need, PAGE_CACHE_ROOM, Peaks,
100 ProfilePlan, ProfileSizing, Resize, RevertCause, SAMPLE_INTERVAL, SLOT_DISK, Sizing,
101 SizingChange, SizingHold, SizingQuery, SizingRefused, SizingRevert, Spread, Starts, need,
102 period, sampled_note,
103};
104pub use slots::{Figure, Health, SlotState};
105pub use stats::StatsSummary;
106pub use storage::{
107 ACTIONS_CACHE, BUILD_CACHE_TOOLS, BuildCacheActivity, CacheLimit, RECORDS_NEAR_FULL,
108 RecordState, actions_cache_place, records_near_full,
109};
110pub use tone::{Tone, Toned};
111#[cfg(feature = "host")]
112pub(crate) use units::days_from_civil;
113pub use units::{ago, cores_used, cpu_time, duration, in_cores};
114
115/// Who sent a request, as the transport authenticated it. Handlers get it from one place, so a new transport only
116/// has to produce one.
117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(rename_all = "kebab-case", tag = "kind")]
119pub enum Principal {
120 /// The user the daemon runs as, on the local Unix socket.
121 LocalOwner {
122 /// The Unix user ID the socket's peer runs as.
123 uid: u32,
124 },
125}
126
127/// `GET /v1/status`: what the daemon serves and runs right now.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct Status {
130 /// The daemon's version, from its `Cargo.toml`.
131 pub version: String,
132 /// Set once the daemon stops polling to shut down. [`Status::stopping_line`] says how.
133 pub shutting_down: bool,
134 /// How it stops, once it does; absent from a daemon before it said.
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub stopping: Option<Stopping>,
137 /// The memory budget and what runners use of it.
138 pub budget: Budget,
139 /// Every configured profile with its slots.
140 pub profiles: Vec<ProfileStatus>,
141 /// Every configured repository.
142 pub repositories: Vec<RepositoryStatus>,
143 /// Queued jobs the repositories' runners can take and none holds yet, at the last poll, oldest first. No event
144 /// carries the list: `job.queued` announces a job, `job.started` and `job.finished` its leaving the queue.
145 /// A repository whose last listing failed, as while GitHub rate-limits runnerd, or that is no longer polled
146 /// because runnerd is shutting down, shows no jobs here, while the history keeps its jobs queued.
147 pub queued: Vec<QueuedJob>,
148}
149
150/// The memory budget runners and the mirror share, in bytes.
151#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
152pub struct Budget {
153 /// The systemd slice runner containers run in.
154 pub slice: String,
155 /// The slice's `MemoryMax`; `None` when it is unlimited.
156 pub memory_max: Option<u64>,
157 /// Memory the running containers reserve: the runners' caps, or under measured admission the larger of each
158 /// runner's predicted peak and its last sampled memory, and the caps of the seed containers, shells and the
159 /// mirror.
160 pub memory_in_use: u64,
161 /// What a new runner must fit in beside them.
162 pub admission: AdmissionPolicy,
163 /// Under measured admission, whether the slice is at the high-water mark, so no runner starts.
164 pub held: bool,
165 /// The mirror's part of `memory_in_use`: its cap while it is enabled or still running, else 0.
166 pub mirror_memory: u64,
167 /// The seed containers' part of `memory_in_use`, one per profile that reseeds, by profile name.
168 pub seed_memory: Vec<SeedMemory>,
169 /// The shells' part of `memory_in_use`, one per shell open in a record, by job.
170 pub shell_memory: Vec<ShellMemory>,
171 /// What the host's memory leaves runners beside its other programs, from a recent reading of it; absent
172 /// without one.
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub host: Option<HostBudget>,
175 /// The CPU budget, under `[host] cpu_overcommit`. Absent without one.
176 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub cpu: Option<CpuBudget>,
178 /// The CPUs the slice may use, in millicores: its `AllowedCPUs` or the host's, less under a lower `CPUQuota`,
179 /// whether or not a CPU budget admits runners. The runners' CPU limits are quotas that may add up past it.
180 /// Absent when it could not be read.
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub slice_cpus: Option<u64>,
183}
184
185/// What the host's memory leaves the runners (ADR 0055). New runners fit in the lower of `MemoryMax` and
186/// `limit`; running ones are never stopped for it.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188pub struct HostBudget {
189 /// The reading it comes from.
190 pub memory: HostMemory,
191 /// What the slice may hold now: what its runners hold without page cache plus the host's `MemAvailable`, less
192 /// a margin kept free for the host's page cache; with a ceiling, plus what the host can still grow by
193 /// (`HostMemory::growable`, ADR 0084).
194 pub limit: u64,
195 /// What that leaves new runners beside what the running ones reserve, in bytes.
196 pub spare: u64,
197 /// Whether the host's tasks stall for memory (`full` pressure), so no runner starts until they stop.
198 pub stalled: bool,
199}
200
201/// Hundredths of a percent as a percentage: `1.5%`, `12%`.
202pub fn percent(hundredths: u32) -> String {
203 let whole = hundredths / 100;
204 match hundredths % 100 / 10 {
205 0 => format!("{whole}%"),
206 tenth => format!("{whole}.{tenth}%"),
207 }
208}
209
210/// The CPU budget runners share, in millicores.
211#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
212pub struct CpuBudget {
213 /// The CPUs the slice may use: its `AllowedCPUs` or the host's, less under a lower `CPUQuota`.
214 pub cpus: u64,
215 /// Those times `cpu_overcommit`: what the runners' reservations must fit.
216 pub budget: u64,
217 /// What the runners reserve: each its predicted average CPU under measured admission, else its `cpus`.
218 pub in_use: u64,
219 /// Whether a queued job waits for CPU that memory and a slot have room for.
220 pub held: bool,
221}
222
223impl CpuBudget {
224 /// The budget's line as clients show it beside memory, such as `CPU 4.5 of 32 CPUs reserved` or, while a job
225 /// waits for it, `CPU 30 of 32 CPUs reserved; a job waits for CPU`.
226 pub fn line(&self) -> String {
227 let mut line = format!(
228 "CPU {} of {} CPUs reserved",
229 cores(self.in_use),
230 cores(self.budget)
231 );
232 if self.held {
233 line.push_str("; a job waits for CPU");
234 }
235 line
236 }
237}
238
239impl Budget {
240 /// How runners are admitted, as clients add it to the budget's line: nothing under caps, else `by predicted
241 /// peaks`, and why nothing starts while the slice is at the high-water mark.
242 pub fn admission_note(&self) -> Option<&'static str> {
243 match (self.admission, self.held) {
244 (AdmissionPolicy::Caps, _) => None,
245 (AdmissionPolicy::Measured, false) => Some("by predicted peaks"),
246 (AdmissionPolicy::Measured, true) => Some(
247 "by predicted peaks; the slice is past 90% of its MemoryMax, so no runner starts",
248 ),
249 }
250 }
251}
252
253/// A shell container's memory cap: its record's profile's limit when the shell opened.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct ShellMemory {
256 /// The job whose record the shell runs.
257 pub job: u64,
258 /// Its cap in bytes.
259 pub memory: u64,
260}
261
262/// A seed container's memory cap: its profile's limit when the reseed started, or, for a requested reseed whose
263/// profile drained, the room it holds until it starts.
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265pub struct SeedMemory {
266 /// The profile it reseeds.
267 pub profile: String,
268 /// Its cap in bytes.
269 pub memory: u64,
270}
271
272/// A runner profile and what runs in its slots.
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274pub struct ProfileStatus {
275 /// The name under `[profiles]` in `runnerd.toml`.
276 pub name: String,
277 /// The image its runners run, such as `runnerd-runner:base`.
278 pub image: String,
279 /// CPUs per slot.
280 pub cpus: u32,
281 /// Bytes per slot.
282 pub memory: u64,
283 /// Set while slot 1's layers become the profile's snapshot.
284 pub reseeding: bool,
285 /// Index 0 is slot 1.
286 pub slots: Vec<SlotStatus>,
287}
288
289/// One slot of a profile: room for one job.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291pub struct SlotStatus {
292 /// 1-based.
293 pub slot: usize,
294 /// `None` when the slot is free.
295 pub runner: Option<RunnerStatus>,
296}
297
298/// A runner registered for one job, in its container.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300pub struct RunnerStatus {
301 /// `owner/name` the runner is registered on.
302 pub repository: String,
303 /// The runner's name, also its container's.
304 pub name: String,
305 /// The runner's ID on GitHub.
306 pub runner_id: u64,
307 /// The Docker container ID.
308 pub container: String,
309 /// Whether it runs a job, as GitHub or its log reports it: its log names the job before GitHub lists it busy.
310 pub busy: bool,
311 /// Seconds since the Unix epoch.
312 pub started_at: u64,
313 /// What it takes of the budget: its cap under caps; under measured admission the larger of its predicted peak
314 /// and its last sampled memory.
315 pub reserved: u64,
316 /// A warm runner: idle, and no queued job of its repository waits for it; it takes the next one GitHub hands
317 /// out.
318 pub warm: bool,
319}
320
321/// A configured repository and its queue.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323pub struct RepositoryStatus {
324 /// `owner/name` on GitHub.
325 pub name: String,
326 /// Its pools in config order, one per `[[repositories]]` entry: a job runs in the one whose labels match it
327 /// (ADR 0058).
328 pub pools: Vec<PoolStatus>,
329 /// Paused repositories get no new runners; their running jobs finish.
330 pub paused: bool,
331 /// Its jobs in `Status::queued`: queued ones none of its runners took yet, those no pool serves too.
332 pub queued_jobs: usize,
333}
334
335/// One of a repository's pools: its runners in one profile.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337pub struct PoolStatus {
338 /// The profile its jobs run in.
339 pub profile: String,
340 /// The labels its runners register with.
341 pub labels: Vec<String>,
342 /// Its jobs in `Status::queued`: those its labels match.
343 pub queued_jobs: usize,
344}
345
346/// A queued job runners of this daemon can take, as GitHub listed it at the last poll.
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348pub struct QueuedJob {
349 /// GitHub's job ID.
350 pub id: u64,
351 /// The repository whose runners can take it, `owner/name`.
352 pub repository: String,
353 /// The profile of its repository's pool whose labels match it; `None` when no pool's do.
354 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub profile: Option<String>,
356 /// The workflow run it belongs to.
357 pub run_id: u64,
358 /// 1 for the first attempt of the run, higher for re-runs.
359 pub run_attempt: u32,
360 /// The workflow's name.
361 pub workflow: Option<String>,
362 /// The job's name in the workflow.
363 pub name: String,
364 /// The branch the run is for.
365 pub branch: Option<String>,
366 /// The job's page on GitHub.
367 pub url: Option<String>,
368 /// When GitHub queued it, in seconds since the Unix epoch; 0 if GitHub did not say.
369 pub queued_at: u64,
370 /// Why no runner has it yet, as the last plan saw it. `None` before the daemon has planned with it, and while
371 /// it shuts down.
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub waiting: Option<Waiting>,
374}
375
376/// The slot of an idle runner of `job`'s repository, in its pool's profile when known, such as `jvm 2`.
377fn starting_for(job: &QueuedJob, status: &Status) -> Option<String> {
378 status
379 .profiles
380 .iter()
381 .filter(|profile| job.profile.as_ref().is_none_or(|own| *own == profile.name))
382 .find_map(|profile| {
383 profile
384 .slots
385 .iter()
386 .find(|slot| {
387 slot.runner
388 .as_ref()
389 .is_some_and(|runner| runner.repository == job.repository && !runner.busy)
390 })
391 .map(|slot| format!("{}\u{a0}{}", profile.name, slot.slot))
392 })
393}
394
395impl QueuedJob {
396 /// Where it runs, as every client names it: its repository, and its pool's profile when the repository has
397 /// several pools in `status`, such as `halyard/ledger · light`.
398 pub fn place(&self, status: &Status) -> String {
399 let pools = status
400 .repositories
401 .iter()
402 .find(|repository| repository.name == self.repository)
403 .map_or(0, |repository| repository.pools.len());
404 match self.profile.as_deref().filter(|_| pools > 1) {
405 Some(profile) => format!("{}\u{a0}· {profile}", self.repository),
406 None => self.repository.clone(),
407 }
408 }
409}
410
411impl RepositoryStatus {
412 /// The profile of its first pool, which every client colours it by.
413 pub fn first_profile(&self) -> &str {
414 self.pools.first().map_or("", |pool| pool.profile.as_str())
415 }
416
417 /// Its pools' profiles, as every client lists them on one line: `jvm` or `jvm + light`.
418 pub fn profiles(&self) -> String {
419 self.pools
420 .iter()
421 .map(|pool| pool.profile.as_str())
422 .collect::<Vec<_>>()
423 .join(" + ")
424 }
425
426 /// The profile of its pool whose labels match a job asking for `labels`, as the daemon picks it.
427 pub fn pool_for(&self, labels: &[String]) -> Option<String> {
428 self.pools
429 .iter()
430 .find(|pool| crate::config::labels_match(labels, &pool.labels))
431 .map(|pool| pool.profile.clone())
432 }
433}
434
435/// What failed, that holds a repository's runners back for a while.
436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
437#[serde(rename_all = "kebab-case")]
438pub enum HoldCause {
439 /// Its runners ended without taking a job.
440 NoJob,
441 /// Its runners ended without a job after waiting for one, twice in a row.
442 IdleExits,
443 /// GitHub did not register its runner.
444 Register,
445 /// Docker did not start its runner's container.
446 Start,
447}
448
449/// Why a queued job has no runner of its own yet. Jobs are served oldest first; each takes the first of these that
450/// holds for it.
451#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(rename_all = "kebab-case", tag = "kind")]
453pub enum Waiting {
454 /// Its repository is paused.
455 Paused,
456 /// Runners of its repository failed, so none starts before `until` (seconds since the Unix epoch).
457 Backoff {
458 /// When runners may start again.
459 until: u64,
460 /// What failed.
461 cause: HoldCause,
462 },
463 /// A runner started for it and waits for GitHub to hand it the job: a runner takes any job its labels match,
464 /// so not necessarily this one.
465 RunnerStarting,
466 /// Slot 1 of its profile is becoming the profile's snapshot, so none of the profile's slots starts.
467 Reseeding {
468 /// The profile.
469 profile: String,
470 },
471 /// Its profile's image is being pulled, so none of the profile's slots starts.
472 PullingImage {
473 /// The profile.
474 profile: String,
475 },
476 /// Every slot of its profile holds a runner.
477 NoSlot {
478 /// The profile.
479 profile: String,
480 },
481 /// What its runner would reserve does not fit the memory budget left. Under measured admission, `free` is 0
482 /// while the slice is at the high-water mark (`Budget::held`).
483 Memory {
484 /// What its runner would reserve, in bytes.
485 needs: u64,
486 /// What the budget has left, in bytes.
487 free: u64,
488 },
489 /// What its runner would reserve does not fit what the host's memory has to spare beside its other programs
490 /// (`HostBudget::spare`), though it fits the slice's budget. `free` is 0 while the host's tasks stall for memory
491 /// (`HostBudget::stalled`).
492 HostMemory {
493 /// What its runner would reserve, in bytes.
494 needs: u64,
495 /// What the host has to spare, in bytes.
496 free: u64,
497 },
498 /// What its runner would reserve does not fit the CPU budget left, in millicores.
499 Cpu {
500 /// What its runner would reserve.
501 needs: u64,
502 /// What the CPU budget has left.
503 free: u64,
504 },
505 /// An older job has waited long enough for CPU that no younger one takes CPU before it.
506 BehindCpu {
507 /// The older job's ID.
508 job: u64,
509 },
510 /// An older job is about to have a runner start for it, which takes the slot, memory or CPU this one would
511 /// otherwise start with: what holds it is that start, not what runs now.
512 BehindStart {
513 /// The older job's ID.
514 job: u64,
515 },
516 /// No pool of its repository has every label it asks for, so no runner of this daemon can take it (ADR 0058).
517 NoPool {
518 /// The labels it asks for.
519 labels: Vec<String>,
520 },
521 /// A reason from a newer daemon than this client knows, so a reason added later does not keep the client from
522 /// reading the status.
523 #[serde(other)]
524 Unknown,
525}
526
527/// What a [`Waiting`] reason waits on, which clients draw it by.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub enum WaitKind {
530 /// Something the owner can act on: a pause, runners that failed to take a job, or labels no pool serves.
531 Act,
532 /// Something that clears by itself shortly: a runner starting, a reseed, an image pull, an older job's start.
533 Soon,
534 /// Room: a slot, memory or CPU that a running job holds.
535 Full,
536 /// A reason this client does not know (`Waiting::Unknown`), drawn neutral.
537 Other,
538}
539
540impl Waiting {
541 /// What it waits on.
542 pub fn kind(&self) -> WaitKind {
543 match self {
544 Waiting::Paused | Waiting::Backoff { .. } | Waiting::NoPool { .. } => WaitKind::Act,
545 Waiting::Unknown => WaitKind::Other,
546 Waiting::RunnerStarting
547 | Waiting::Reseeding { .. }
548 | Waiting::PullingImage { .. }
549 | Waiting::BehindStart { .. } => WaitKind::Soon,
550 Waiting::NoSlot { .. }
551 | Waiting::Memory { .. }
552 | Waiting::HostMemory { .. }
553 | Waiting::Cpu { .. }
554 | Waiting::BehindCpu { .. } => WaitKind::Full,
555 }
556 }
557
558 /// Why `job` waits, in the owner's words with the numbers that hold it, as every client says it: such as
559 /// `All 2 node slots are busy` or `Needs 9G of memory; 2.5G of the budget is free`. `status` is the one `job`
560 /// is queued in, which names the slot of a starting runner and the older job one waits behind.
561 pub fn reason(&self, job: &QueuedJob, status: &Status, now: u64) -> String {
562 let size = |bytes: u64| crate::config::ByteSize(bytes).to_string();
563 let older_name = |id: u64| {
564 status
565 .queued
566 .iter()
567 .find(|candidate| candidate.id == id)
568 .map_or_else(|| "an older job".to_owned(), |older| older.name.clone())
569 };
570 match self {
571 Waiting::Paused => format!("{} is paused", job.repository),
572 Waiting::Unknown => "Waits for a reason this client does not know yet".to_owned(),
573 Waiting::NoPool { labels } if labels.is_empty() => {
574 "It asks for no labels, so no profile serves it".to_owned()
575 }
576 Waiting::NoPool { labels } => format!(
577 "No profile serves the {} {}",
578 if labels.len() == 1 { "label" } else { "labels" },
579 labels.join(", ")
580 ),
581 Waiting::Backoff { until, cause } => format!(
582 "{}; retrying in {}",
583 match cause {
584 HoldCause::NoJob => "Runners failed to take a job",
585 HoldCause::IdleExits => "Runners ended without a job after waiting for one",
586 HoldCause::Register => "Runners cannot register with GitHub",
587 HoldCause::Start => "Runners cannot start",
588 },
589 duration(until.saturating_sub(now))
590 ),
591 Waiting::RunnerStarting => match starting_for(job, status) {
592 Some(slot) => format!("A runner is starting for it in {slot}"),
593 None => "A runner is starting for it".to_owned(),
594 },
595 Waiting::Reseeding { profile } => format!("{profile} is rebuilding its snapshot"),
596 Waiting::PullingImage { profile } => format!("Pulling {profile}'s image"),
597 Waiting::NoSlot { profile } => {
598 let slots = status
599 .profiles
600 .iter()
601 .find(|candidate| &candidate.name == profile)
602 .map_or(0, |profile| profile.slots.len());
603 if slots == 1 {
604 format!("The {profile} slot is busy")
605 } else {
606 format!("All {slots} {profile} slots are busy")
607 }
608 }
609 Waiting::Memory { .. } if status.budget.held => {
610 "The slice is past 90% of its MemoryMax, so nothing starts".to_owned()
611 }
612 Waiting::Memory { needs, free } => format!(
613 "Needs {} of memory; {} of the budget is free",
614 size(*needs),
615 size(*free)
616 ),
617 Waiting::HostMemory { needs, free } => {
618 let host = status.budget.host.as_ref();
619 let reason = if host.is_some_and(|host| host.stalled) {
620 "The host is short of memory: its programs stall waiting for it, so nothing starts"
621 .to_owned()
622 } else {
623 format!(
624 "The host is short of memory: needs {}; the host has {} to spare",
625 size(*needs),
626 size(*free)
627 )
628 };
629 match host {
630 Some(host) => format!("{reason}; {}", host.memory.outside_line()),
631 None => reason,
632 }
633 }
634 Waiting::Cpu { needs, free } => {
635 format!(
636 "Needs {}; {} are free",
637 cpus(*needs),
638 admission::free_cores(*free)
639 )
640 }
641 Waiting::BehindCpu { job: older } => {
642 format!("Behind {}, which waits for CPU", older_name(*older))
643 }
644 Waiting::BehindStart { job: older } => {
645 format!(
646 "Next after {}, whose runner starts first",
647 older_name(*older)
648 )
649 }
650 }
651 }
652}
653
654/// `GET /v1/dashboard`: the dashboard's `[web]` settings, as the daemon read them when it started.
655#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
656pub struct Dashboard {
657 /// `[web] open`: the one of `[web] origins` that `runnerctl web` opens the dashboard on; the loopback address
658 /// when none.
659 #[serde(default, skip_serializing_if = "Option::is_none")]
660 pub open: Option<String>,
661}
662
663/// `POST /v1/dashboard/pairings`: which of `[web] origins` to make a link for.
664#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
665pub struct PairingQuery {
666 /// One of `[web] origins`; each of them when none.
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub origin: Option<String>,
669}
670
671/// `POST /v1/dashboard/pairings`: fresh one-time links that sign a device in to the dashboard.
672#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
673pub struct Pairings {
674 /// One per origin asked for.
675 pub links: Vec<Pairing>,
676}
677
678/// A link that signs one device in to the dashboard on `origin`, and nowhere else, within `lifetime`.
679#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
680pub struct Pairing {
681 /// One of `[web] origins`.
682 pub origin: String,
683 /// The link with its one-time code: a credential, which `Debug` leaves out.
684 pub url: String,
685 /// Seconds it works for from when it was made.
686 pub lifetime: u64,
687}
688
689impl std::fmt::Debug for Pairing {
690 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
691 formatter
692 .debug_struct("Pairing")
693 .field("origin", &self.origin)
694 .field("lifetime", &self.lifetime)
695 .finish_non_exhaustive()
696 }
697}
698
699/// `POST /v1/shutdown`.
700#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
701pub struct ShutdownRequest {
702 /// Kill running jobs and delete their runners instead of waiting for them.
703 #[serde(default)]
704 pub force: bool,
705}
706
707/// What `POST /v1/shutdown` answers: how the daemon stops now, which a stop asked for earlier may have made more
708/// urgent than the request.
709#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
710pub struct ShutdownAnswer {
711 /// How it stops.
712 pub stopping: Stopping,
713}
714
715/// How a stopping daemon treats running jobs (ADR 0091).
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
717#[serde(rename_all = "kebab-case")]
718pub enum Stopping {
719 /// `runnerd stop`: it waits for running jobs, then removes every runner.
720 WaitsForJobs,
721 /// A signal: it removes idle runners and leaves running jobs to the next start.
722 LeavesJobs,
723 /// `runnerd stop --force` or a second signal: it kills running jobs.
724 KillsJobs,
725 /// A kind of stop from a newer daemon than this client knows, so one added later does not keep the client from
726 /// reading the status.
727 #[serde(other)]
728 Unknown,
729}
730
731impl Stopping {
732 /// What it does, as every client says it: `shutting down: waits for running jobs`.
733 pub fn line(self) -> &'static str {
734 match self {
735 Stopping::WaitsForJobs => "shutting down: waits for running jobs",
736 Stopping::LeavesJobs => "shutting down: leaves running jobs to the next start",
737 Stopping::KillsJobs => "shutting down: kills running jobs",
738 Stopping::Unknown => "shutting down",
739 }
740 }
741}
742
743impl Status {
744 /// What a stopping daemon does, as every client says it ([`Stopping::line`]); `shutting down` from a daemon
745 /// that does not say how; `None` while it runs.
746 pub fn stopping_line(&self) -> Option<&'static str> {
747 match (self.stopping, self.shutting_down) {
748 (Some(stopping), _) => Some(stopping.line()),
749 (None, true) => Some("shutting down"),
750 (None, false) => None,
751 }
752 }
753}
754
755/// The body of every error response.
756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
757pub struct ErrorResponse {
758 /// What went wrong, for people to read.
759 pub message: String,
760}