runnerd_core/api/jobs.rs
1//! Job history as clients read it: one record per GitHub job a runner of this daemon ran, its timeline, steps,
2//! metrics and log size; the queries that list them; sample series for graphs; per-repository aggregates; cache
3//! sizes. Times are seconds since the Unix epoch, sizes are bytes, CPU is in millicores (1000 = one core busy).
4
5use serde::{Deserialize, Serialize};
6
7mod facts;
8
9pub use facts::{
10 JobTitle, Milestone, Outcome, OutcomeKind, Phase, PhaseKind, RunComparison, SampleUsage,
11 job_title,
12};
13
14/// Where a job is in its life, as this daemon saw it.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "kebab-case")]
17pub enum JobState {
18 /// Waiting for a runner.
19 Queued,
20 /// A runner of this daemon took it.
21 Running,
22 /// GitHub reports it completed; `conclusion` says how.
23 Completed,
24 /// Its runner's container is gone and GitHub did not report the job completed in time.
25 Lost,
26 /// A runner of another machine took it, or it ended before any runner did, as when a newer push cancelled it.
27 /// One no runner took has no `started_at`, except in records of versions that kept the start GitHub gives it.
28 Elsewhere,
29}
30
31impl JobState {
32 /// Whether the job can still change.
33 pub fn is_final(self) -> bool {
34 matches!(
35 self,
36 JobState::Completed | JobState::Lost | JobState::Elsewhere
37 )
38 }
39}
40
41/// A job without its steps: what lists and events carry.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct JobSummary {
44 /// GitHub's job ID, also its check run ID.
45 pub id: u64,
46 /// `owner/name` on GitHub.
47 pub repository: String,
48 /// The workflow run it belongs to.
49 pub run_id: u64,
50 /// 1 for the first attempt of the run, higher for re-runs.
51 pub run_attempt: u32,
52 /// The workflow's name.
53 pub workflow: Option<String>,
54 /// The job's name in the workflow.
55 pub name: String,
56 /// The branch the run is for.
57 pub branch: Option<String>,
58 /// The job's page on GitHub.
59 pub url: Option<String>,
60 /// The workflow's `runs-on` labels.
61 pub labels: Vec<String>,
62 /// Where the job is.
63 pub state: JobState,
64 /// GitHub's conclusion once completed: `success`, `failure`, `cancelled`, `skipped`, `timed_out`, ….
65 pub conclusion: Option<String>,
66 /// The runner that ran it.
67 pub runner: Option<JobRunner>,
68 /// When each phase started.
69 pub timeline: Timeline,
70 /// CPU, memory and network use while it ran.
71 pub metrics: JobMetrics,
72 /// How much of its log is stored.
73 pub log: LogSummary,
74}
75
76/// `GET /v1/jobs/{id}`: a job with its steps.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct Job {
79 /// Everything but the steps.
80 #[serde(flatten)]
81 pub summary: JobSummary,
82 /// The steps as GitHub numbers them, including `Set up job` and `Complete job`.
83 pub steps: Vec<Step>,
84 /// Its record, for a failed job of a profile that records failures.
85 #[serde(default)]
86 pub record: Option<super::RecordNote>,
87 /// How its runner was admitted; `None` for one started before runnerd recorded it.
88 #[serde(default)]
89 pub admission: Option<super::Admission>,
90}
91
92impl Job {
93 /// The lines across its memory and CPU charts, as every client labels them: what admission reserved of the
94 /// budget, when the record has it, and the cap its container ran with, or for a record without it, `profile`'s
95 /// limit as configured now. A reservation of the whole cap is one line.
96 pub fn chart_lines(&self, profile: Option<&super::ProfileStatus>) -> ChartLines {
97 let limits = self.limits(profile);
98 let admission = self.admission.as_ref();
99 let name = profile.map_or("profile", |profile| profile.name.as_str());
100 ChartLines {
101 memory: chart_lines(
102 limits.memory,
103 admission.map(|admission| admission.reserved),
104 |value| crate::config::ByteSize(value).to_string(),
105 name,
106 ),
107 cpu: chart_lines(
108 limits.cpu,
109 admission
110 .and_then(|admission| admission.cpu)
111 .map(|cpu| cpu.reserved),
112 super::cpus,
113 name,
114 ),
115 }
116 }
117
118 /// What its container may use of each resource, as every client scales its use against: the cap it ran with,
119 /// or, for a record without it, `profile`'s limit as configured now. Each resource falls back on its own, so a
120 /// reload that changes the profile never replaces a cap the record has.
121 pub fn limits(&self, profile: Option<&super::ProfileStatus>) -> Limits {
122 let runner = self.summary.runner.as_ref();
123 let limit = |cap: Option<u64>, now: Option<u64>| match (cap, now) {
124 (Some(value), _) => Some(Limit {
125 value,
126 source: LimitSource::Cap,
127 }),
128 (None, Some(value)) => Some(Limit {
129 value,
130 source: LimitSource::ProfileNow,
131 }),
132 (None, None) => None,
133 };
134 Limits {
135 memory: limit(
136 runner.and_then(|runner| runner.memory_cap),
137 profile.map(|profile| profile.memory),
138 ),
139 cpu: limit(
140 runner.and_then(|runner| runner.cpu_cap),
141 profile.map(|profile| u64::from(profile.cpus) * 1000),
142 ),
143 }
144 }
145}
146
147/// What a job's container may use, from `Job::limits`.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub struct Limits {
150 /// In bytes.
151 pub memory: Option<Limit>,
152 /// In millicores.
153 pub cpu: Option<Limit>,
154}
155
156impl Limits {
157 /// The limits as one clause, such as `capped at 6G and 4 CPUs`, `capped at 6G; profile now 4 CPUs` or `profile
158 /// now 6G and 4 CPUs`; `None` without either.
159 pub fn line(&self) -> Option<String> {
160 let memory = self.memory.map(|limit| {
161 (
162 limit.source,
163 crate::config::ByteSize(limit.value).to_string(),
164 )
165 });
166 let cpu = self
167 .cpu
168 .map(|limit| (limit.source, super::cpus(limit.value)));
169 let clause = |source: LimitSource, figures: &str| match source {
170 LimitSource::Cap => format!("capped at {figures}"),
171 LimitSource::ProfileNow => format!("profile now {figures}"),
172 };
173 match (memory, cpu) {
174 (Some((memory_source, memory)), Some((cpu_source, cpu)))
175 if memory_source == cpu_source =>
176 {
177 Some(clause(memory_source, &format!("{memory} and {cpu}")))
178 }
179 (Some((memory_source, memory)), Some((cpu_source, cpu))) => Some(format!(
180 "{}; {}",
181 clause(memory_source, &memory),
182 clause(cpu_source, &cpu)
183 )),
184 (Some((source, figure)), None) | (None, Some((source, figure))) => {
185 Some(clause(source, &figure))
186 }
187 (None, None) => None,
188 }
189 }
190}
191
192/// One resource's limit for a job's container.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct Limit {
195 /// Bytes or millicores.
196 pub value: u64,
197 /// Where it comes from.
198 pub source: LimitSource,
199}
200
201/// Where a job's limit comes from.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum LimitSource {
204 /// The cap its container ran with.
205 Cap,
206 /// Its profile's limit in the config now, for a record without its container's cap; a reload since may have
207 /// changed it.
208 ProfileNow,
209}
210
211/// One resource's lines: `value` writes a figure, such as `8.5G` or `3.6 CPUs`.
212fn chart_lines(
213 limit: Option<Limit>,
214 reserved: Option<u64>,
215 value: fn(u64) -> String,
216 profile: &str,
217) -> Vec<ChartLine> {
218 let line = |figure, kind, label: &str| ChartLine {
219 value: figure,
220 kind,
221 label: format!("{label} {}", value(figure)),
222 };
223 let mut lines = vec![];
224 match limit {
225 Some(Limit {
226 value: cap,
227 source: LimitSource::Cap,
228 }) if reserved == Some(cap) => {
229 return vec![line(cap, ChartLineKind::CapAndReserved, "cap and reserved")];
230 }
231 Some(Limit {
232 value: cap,
233 source: LimitSource::Cap,
234 }) => lines.push(line(cap, ChartLineKind::Cap, "cap")),
235 Some(Limit {
236 value: now,
237 source: LimitSource::ProfileNow,
238 }) => lines.push(line(
239 now,
240 ChartLineKind::ProfileNow,
241 &format!("{profile} now"),
242 )),
243 None => {}
244 }
245 if let Some(reserved) = reserved {
246 lines.push(line(reserved, ChartLineKind::Reserved, "reserved"));
247 }
248 lines
249}
250
251/// The lines across a job's memory and CPU charts, from `Job::chart_lines`.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct ChartLines {
254 /// In bytes.
255 pub memory: Vec<ChartLine>,
256 /// In millicores.
257 pub cpu: Vec<ChartLine>,
258}
259
260/// A line across a job's memory or CPU chart.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct ChartLine {
263 /// Bytes or millicores.
264 pub value: u64,
265 /// What it stands for.
266 pub kind: ChartLineKind,
267 /// Its label, such as `cap 8.5G` or `reserved 3.6 CPUs`.
268 pub label: String,
269}
270
271/// What a line across a job's chart stands for.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum ChartLineKind {
274 /// The most its container may use: its cap.
275 Cap,
276 /// Its profile's limit in the config now, for a record without its container's cap; a reload since may have
277 /// changed it.
278 ProfileNow,
279 /// What admission counted against the budget for its runner.
280 Reserved,
281 /// A reservation of the whole cap, as admission by caps makes.
282 CapAndReserved,
283}
284
285/// The runner a job ran on.
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
287pub struct JobRunner {
288 /// The runner's name, also its container's.
289 pub name: String,
290 /// The profile it ran in.
291 pub profile: String,
292 /// The slot it ran in, 1-based.
293 pub slot: usize,
294 /// Its container's memory cap in bytes, which a reload since may have changed in the profile. `None` in records
295 /// from before runnerd kept it.
296 pub memory_cap: Option<u64>,
297 /// Its container's CPU limit in millicores, the unit of the CPU use in `Sample` and `JobMetrics`. `None` in
298 /// records from before runnerd kept it, or when Docker reports no limit.
299 pub cpu_cap: Option<u64>,
300}
301
302/// A job's phases, in the order they happen. A runner's container starts before GitHub gives it a job.
303#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
304pub struct Timeline {
305 /// GitHub queued the job.
306 pub queued_at: u64,
307 /// The container of the runner that took it started.
308 pub container_started_at: Option<u64>,
309 /// The runner started the job.
310 pub started_at: Option<u64>,
311 /// The job finished, by GitHub's clock; or when its container was found gone.
312 pub finished_at: Option<u64>,
313 /// The container and the runner's registration were removed.
314 pub cleaned_at: Option<u64>,
315}
316
317impl Timeline {
318 /// When the runner that took it began to start for it: its container's start, or the job's queueing when that
319 /// container waited for jobs before, as a warm runner does. `None` until a runner took it.
320 pub fn runner_from(&self) -> Option<u64> {
321 self.container_started_at
322 .map(|started| started.max(self.queued_at))
323 }
324}
325
326/// What a job used, over the samples taken while it ran (every few seconds). `None` until a sample exists.
327#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
328pub struct JobMetrics {
329 /// CPU time, in milliseconds.
330 pub cpu_time: Option<u64>,
331 /// The highest CPU use of a sample interval, in millicores.
332 pub cpu_peak: Option<u64>,
333 /// CPU time over wall time, in millicores.
334 pub cpu_average: Option<u64>,
335 /// The highest memory use without page cache.
336 pub memory_peak: Option<u64>,
337 /// The average memory use without page cache.
338 pub memory_average: Option<u64>,
339 /// Bytes the container received.
340 pub network_received: Option<u64>,
341 /// Bytes the container sent.
342 pub network_sent: Option<u64>,
343 /// Of the bytes received, those the Docker Hub mirror served.
344 pub mirror_bytes: u64,
345 /// What the shared build cache served it and took from it.
346 pub build_cache: BuildCacheCounts,
347 /// Times the kernel held its container's sockets' receive windows small because the container's memory was
348 /// under pressure (`memory.events` `sock_throttled`): reclaim went badly, mostly because the host was short of
349 /// memory, and its downloads slowed. `None` when the kernel does not count it, or in records from before.
350 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub sock_throttled: Option<u64>,
352}
353
354/// What the shared build cache served one runner and took from it (ADR 0052), counted by the cache itself.
355#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
356pub struct BuildCacheCounts {
357 /// Lookups that found an entry.
358 pub hits: u64,
359 /// Lookups that found none.
360 pub misses: u64,
361 /// Bytes of the entries it served.
362 pub read_bytes: u64,
363 /// Bytes of the entries it stored.
364 pub written_bytes: u64,
365 /// Entries it was sent and did not store: the job may not write (a pull request, another branch), or the
366 /// cache was full.
367 pub refused: u64,
368 /// Whether the job could write: a push, scheduled or manually started run of a branch that may write.
369 pub writer: bool,
370}
371
372impl BuildCacheCounts {
373 /// Hits and misses.
374 pub fn lookups(&self) -> u64 {
375 self.hits + self.misses
376 }
377
378 /// Hits in percent of lookups, `None` without any.
379 pub fn hit_percent(&self) -> Option<u64> {
380 let lookups = self.lookups();
381 (lookups > 0).then(|| self.hits * 100 / lookups)
382 }
383
384 /// Adds `other`'s counts; `writer` stays.
385 pub fn add(&mut self, other: &BuildCacheCounts) {
386 self.hits += other.hits;
387 self.misses += other.misses;
388 self.read_bytes += other.read_bytes;
389 self.written_bytes += other.written_bytes;
390 self.refused += other.refused;
391 }
392}
393
394/// A job's stored log.
395#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
396pub struct LogSummary {
397 /// Lines stored.
398 pub lines: u64,
399 /// Bytes stored.
400 pub bytes: u64,
401 /// Set once the log reached `history.log_max` and later lines were dropped.
402 pub truncated: bool,
403}
404
405/// One step of a job, as GitHub reports it.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct Step {
408 /// GitHub's step number; numbers may skip.
409 pub number: u32,
410 /// The name GitHub shows, such as `Set up job` or `Run docker run --rm hello-world`.
411 pub name: String,
412 /// `pending`, `queued`, `in_progress` or `completed`.
413 pub status: String,
414 /// Once completed: `success`, `failure`, `skipped`, `cancelled`, ….
415 pub conclusion: Option<String>,
416 /// When it started.
417 pub started_at: Option<u64>,
418 /// When it completed.
419 pub completed_at: Option<u64>,
420}
421
422/// `GET /v1/jobs` query parameters. Jobs come newest first (by ID, which grows with time).
423#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
424pub struct JobQuery {
425 /// Only this `owner/name`.
426 pub repository: Option<String>,
427 /// Only jobs in this state.
428 pub state: Option<JobState>,
429 /// Only jobs with this conclusion, such as `failure`.
430 pub conclusion: Option<String>,
431 /// Only jobs of the workflow with this name, such as `CI`.
432 pub workflow: Option<String>,
433 /// Only jobs with this name in their workflow, such as `build`.
434 pub name: Option<String>,
435 /// Only jobs queued at or after this time.
436 pub since: Option<u64>,
437 /// Only jobs queued before this time.
438 pub until: Option<u64>,
439 /// Only jobs with a smaller ID: the `next` of the previous page.
440 pub before: Option<u64>,
441 /// At most this many jobs; default 50, at most 500.
442 pub limit: Option<u32>,
443}
444
445/// `GET /v1/jobs`: one page of jobs.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447pub struct JobPage {
448 /// Newest first.
449 pub jobs: Vec<JobSummary>,
450 /// Pass as `before` for the next page; `None` on the last page.
451 pub next: Option<u64>,
452}
453
454/// `GET /v1/jobs/{id}/logs` query parameters. The response is `text/plain`, one log line per line.
455#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456pub struct LogQuery {
457 /// Start at this line, 0-based.
458 pub from: Option<u64>,
459 /// Keep the response open and send lines as they are stored, until the job finishes.
460 #[serde(default)]
461 pub follow: bool,
462}
463
464/// One sample of a container's use.
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466pub struct Sample {
467 /// When it was taken.
468 pub at: u64,
469 /// CPU use since the previous sample, in millicores.
470 pub cpu: u64,
471 /// Memory use without page cache.
472 pub memory: u64,
473 /// Bytes received since the container started.
474 pub network_received: u64,
475 /// Bytes sent since the container started.
476 pub network_sent: u64,
477}
478
479/// `GET /v1/jobs/{id}/samples`: what the job's container used over time, from its start to its removal. Samples
480/// older than `history.samples` are deleted; the job's metrics stay.
481#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
482pub struct SampleSeries {
483 /// The job.
484 pub job: u64,
485 /// Seconds between samples.
486 pub interval: u64,
487 /// Oldest first.
488 pub samples: Vec<Sample>,
489}
490
491/// One sample of the whole slice runners run in.
492#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
493pub struct HostSample {
494 /// When it was taken.
495 pub at: u64,
496 /// CPU use of the slice since the previous sample, in millicores.
497 pub cpu: u64,
498 /// Memory use of the slice less its inactive page cache, as `docker stats` counts it: a conservative number,
499 /// since active page cache still counts, which the high-water mark of measured admission compares to
500 /// `MemoryMax`.
501 pub memory: u64,
502}
503
504/// The host's memory at one moment, beside the slice's: what admission fits new runners in besides `MemoryMax`
505/// (ADR 0055). Read every few seconds; not kept in the history.
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
507pub struct HostMemory {
508 /// When it was read.
509 pub at: u64,
510 /// `MemTotal` in `/proc/meminfo`, in bytes.
511 pub total: u64,
512 /// `MemAvailable`: what the host could give without swapping, page cache it can drop included, in bytes.
513 pub available: u64,
514 /// The slice's memory without page cache and reclaimable slab: what the runners hold that `MemAvailable` leaves
515 /// out.
516 pub slice: u64,
517 /// `/proc/pressure/memory`'s `some` line: the share of time at least one task waited for memory. `None` on a
518 /// kernel without pressure stall information.
519 pub some: Option<Pressure>,
520 /// Its `full` line: the share of time every task that could run waited for memory.
521 pub full: Option<Pressure>,
522 /// The programs outside the slice that hold the most memory, largest first: at most a few, none under a floor.
523 /// Read less often than the rest. Empty when none is that large.
524 #[serde(default, skip_serializing_if = "Vec::is_empty")]
525 pub holders: Vec<Holder>,
526}
527
528impl HostMemory {
529 /// What the host holds outside the slice's runners, in bytes: its other programs, tmpfs and the kernel, without
530 /// page cache it can drop.
531 pub fn outside(&self) -> u64 {
532 self.total
533 .saturating_sub(self.available)
534 .saturating_sub(self.slice)
535 }
536
537 /// What holds the host's memory outside the slice, as the clients say it: `programs outside CI hold 30G` and,
538 /// with `holders`, `, most java 9.3G and qemu-system-x86 5.8G`.
539 pub fn outside_line(&self) -> String {
540 let size = |bytes: u64| crate::config::ByteSize(bytes).to_string();
541 let line = format!("programs outside CI hold {}", size(self.outside()));
542 let named: Vec<String> = self
543 .holders
544 .iter()
545 .map(|holder| format!("{} {}", holder.name, size(holder.memory)))
546 .collect();
547 match named.as_slice() {
548 [] => line,
549 [one] => format!("{line}, most {one}"),
550 [rest @ .., last] => format!("{line}, most {} and {last}", rest.join(", ")),
551 }
552 }
553}
554
555/// A program outside the slice and the memory its processes hold.
556#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
557pub struct Holder {
558 /// Its processes' name, as `/proc/<pid>/comm` says it: never a command line, argument or path.
559 pub name: String,
560 /// What its processes hold that the host can't drop as page cache (`RssAnon` and `RssShmem`), in bytes.
561 pub memory: u64,
562}
563
564/// One line of a pressure stall file, in hundredths of a percent: 250 is 2.5% of the time.
565#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
566pub struct Pressure {
567 /// Over the last 10 seconds.
568 pub avg10: u32,
569 /// Over the last 60 seconds.
570 pub avg60: u32,
571}
572
573/// `GET /v1/host/samples` query parameters.
574#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
575pub struct HostSampleQuery {
576 /// Only samples taken at or after this time; default the last hour, at most the last 24 hours.
577 pub since: Option<u64>,
578}
579
580/// `GET /v1/host/samples`: the slice's use over time, oldest first.
581#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
582pub struct HostSamples {
583 /// Seconds between samples.
584 pub interval: u64,
585 /// Oldest first.
586 pub samples: Vec<HostSample>,
587}
588
589/// How `GET /v1/stats` groups jobs in time.
590#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
591#[serde(rename_all = "kebab-case")]
592pub enum Bucket {
593 /// By UTC hour.
594 Hour,
595 /// By UTC day.
596 #[default]
597 Day,
598}
599
600/// `GET /v1/activity` query parameters.
601#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
602pub struct ActivityQuery {
603 /// The start of the window; default 24 hours ago. It ends now.
604 pub since: Option<u64>,
605}
606
607/// `GET /v1/activity`: every job runnerd's runners started or finished in a window, by when that happened rather
608/// than when the job was queued, so a job that waited or ran long counts in the window it started or ended in.
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610pub struct Activity {
611 /// The start of the window.
612 pub since: u64,
613 /// When it was read: the end of the window.
614 pub until: u64,
615 /// Each job that started in the window, oldest start first.
616 pub started: Vec<Started>,
617 /// The jobs that finished in the window: completed, or lost with their runner.
618 pub finished: u64,
619 /// Of those, the ones that failed, timed out or were lost, as `GET /v1/stats` counts failures.
620 pub failed: u64,
621 /// Of the failed, the ones their runner failed rather than their own steps: lost with their runner, or failed
622 /// after the kernel killed a process of theirs for memory at their cap.
623 pub runner_failed: u64,
624}
625
626impl Activity {
627 /// The 95th percentile of the waits of the jobs that started, by nearest rank as sizing's are; `None` when none
628 /// started.
629 pub fn wait_p95(&self) -> Option<u64> {
630 let mut waits: Vec<u64> = self.started.iter().map(|start| start.waited).collect();
631 waits.sort_unstable();
632 let rank = (waits.len() * 95).div_ceil(100);
633 waits.get(rank.checked_sub(1)?).copied()
634 }
635
636 /// The longest wait of the jobs that started in each of the 24 hours before `until`, oldest hour first; 0 for
637 /// an hour without a start. Counted back from `until`, so the hours are the day the other figures count.
638 pub fn wait_hours(&self) -> [u64; 24] {
639 const HOUR: u64 = 3600;
640 let since = self.until.saturating_sub(24 * HOUR);
641 let mut hours = [0u64; 24];
642 for start in self
643 .started
644 .iter()
645 .filter(|start| (since..=self.until).contains(&start.at))
646 {
647 // A start exactly 24 hours ago is in the oldest hour.
648 let back =
649 usize::try_from((self.until - start.at) / HOUR).map_or(23, |back| back.min(23));
650 hours[23 - back] = hours[23 - back].max(start.waited);
651 }
652 hours
653 }
654}
655
656/// A job that started: when, and how long it had waited since it was queued.
657#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
658pub struct Started {
659 /// When it started.
660 pub at: u64,
661 /// Seconds it waited.
662 pub waited: u64,
663}
664
665/// `GET /v1/stats` query parameters.
666#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
667pub struct StatsQuery {
668 /// Only this `owner/name`.
669 pub repository: Option<String>,
670 /// Only jobs queued at or after this time; default 30 days ago. At most 744 buckets before `until` (or now)
671 /// are counted: 31 days of hours, two years of days.
672 pub since: Option<u64>,
673 /// Only jobs queued before this time.
674 pub until: Option<u64>,
675 /// The bucket size; default a day.
676 #[serde(default)]
677 pub bucket: Bucket,
678}
679
680/// `GET /v1/stats`: finished jobs per repository and time bucket, for trends. Sums, so clients can average.
681#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub struct Stats {
683 /// The bucket size.
684 pub bucket: Bucket,
685 /// By bucket start, then repository.
686 pub rows: Vec<StatsRow>,
687}
688
689/// The finished jobs of one repository in one bucket.
690#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
691pub struct StatsRow {
692 /// The bucket's start.
693 pub start: u64,
694 /// `owner/name`.
695 pub repository: String,
696 /// Jobs completed or lost.
697 pub jobs: u64,
698 /// Of those, concluded `success`.
699 pub succeeded: u64,
700 /// Of those, concluded `failure` or `timed_out`, or lost.
701 pub failed: u64,
702 /// Of those, concluded `cancelled`.
703 pub cancelled: u64,
704 /// Seconds from queued to started, summed.
705 pub queue_seconds: u64,
706 /// Seconds from started to finished, summed.
707 pub run_seconds: u64,
708 /// CPU time, in milliseconds, summed.
709 pub cpu_time: u64,
710 /// The highest memory peak of a job.
711 pub memory_peak: u64,
712 /// Bytes received, summed.
713 pub network_received: u64,
714 /// Bytes from the mirror, summed.
715 pub mirror_bytes: u64,
716}
717
718/// What a cache volume holds.
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(rename_all = "kebab-case", tag = "kind")]
721pub enum CacheKind {
722 /// A profile's read-only snapshot.
723 Snapshot {
724 /// The profile.
725 profile: String,
726 },
727 /// A slot's layer changes and Docker Engine data.
728 Slot {
729 /// The profile.
730 profile: String,
731 /// 1-based.
732 slot: usize,
733 },
734 /// The pnpm store all slots share.
735 Pnpm,
736 /// The Maven repository all slots share.
737 Maven,
738 /// The Docker Hub mirror's storage.
739 Mirror,
740 /// The build cache every runner shares: a directory of the daemon's, not a Docker volume.
741 Build,
742}
743
744/// One cache volume and its size.
745#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
746pub struct CacheVolume {
747 /// The Docker volume.
748 pub name: String,
749 /// What it holds.
750 #[serde(flatten)]
751 pub kind: CacheKind,
752 /// Its size at `measured_at`.
753 pub bytes: u64,
754 /// The size above which runnerd empties it, or for a snapshot starts it over at its next reseed, if it has one.
755 pub limit: Option<u64>,
756}
757
758/// `GET /v1/caches`: every cache volume of the configured profiles, as last measured. Docker measures volumes
759/// slowly, so runnerd measures them at start and whenever no runner runs after jobs ended.
760#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
761pub struct Caches {
762 /// When the sizes were measured; `None` before the first measurement.
763 pub measured_at: Option<u64>,
764 /// By name.
765 pub volumes: Vec<CacheVolume>,
766 /// The shared build cache now, when it is on.
767 pub build: Option<BuildCacheStats>,
768}
769
770/// The shared build cache (ADR 0052): its size now, and what it served the jobs of the last 7 days.
771#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
772pub struct BuildCacheStats {
773 /// The entries' bytes.
774 pub bytes: u64,
775 /// How many entries it holds.
776 pub entries: u64,
777 /// `[caches.build] max_size`.
778 pub limit: u64,
779 /// The runners of the last 7 days, summed.
780 pub week: BuildCacheCounts,
781}
782
783/// `GET /v1/caches/history` query parameters.
784#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
785pub struct CacheHistoryQuery {
786 /// Only measurements at or after this time; default 30 days ago.
787 pub since: Option<u64>,
788}
789
790/// One volume's size at one measurement.
791#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
792pub struct CacheSize {
793 /// When it was measured.
794 pub at: u64,
795 /// The Docker volume.
796 pub name: String,
797 /// Its size.
798 pub bytes: u64,
799}
800
801/// `GET /v1/caches/history`: every measurement, oldest first.
802#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
803pub struct CacheHistory {
804 /// Oldest first.
805 pub sizes: Vec<CacheSize>,
806}