forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBb00f3f4Tahinli1 month ago147 commits

ci.rs623 lines, 19.9 KiBHistoryRawDownload
1//! CI models: run and job states, runners, runs, jobs and artifacts. The stored shape is in
2//! migrations/0024_ci.sql; the store functions live in store/ci.rs.
3//!
4//! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and
5//! `runs_on` arrays out of it, so this crate does not depend on forge-ci.
6
7use std::collections::BTreeMap;
8use std::str::FromStr;
9
10use crate::error::{Error, Result};
11
12/// State of a run. Stored as the `as_str` name.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum RunState {
15 WaitingApproval,
16 Queued,
17 Running,
18 Success,
19 Failure,
20 Cancelled,
21 Error,
22}
23
24impl RunState {
25 pub fn as_str(self) -> &'static str {
26 match self {
27 RunState::WaitingApproval => "waiting_approval",
28 RunState::Queued => "queued",
29 RunState::Running => "running",
30 RunState::Success => "success",
31 RunState::Failure => "failure",
32 RunState::Cancelled => "cancelled",
33 RunState::Error => "error",
34 }
35 }
36
37 /// True for states a run cannot leave.
38 pub fn is_terminal(self) -> bool {
39 matches!(
40 self,
41 RunState::Success | RunState::Failure | RunState::Cancelled | RunState::Error
42 )
43 }
44}
45
46impl FromStr for RunState {
47 type Err = Error;
48
49 fn from_str(s: &str) -> Result<Self> {
50 Ok(match s {
51 "waiting_approval" => RunState::WaitingApproval,
52 "queued" => RunState::Queued,
53 "running" => RunState::Running,
54 "success" => RunState::Success,
55 "failure" => RunState::Failure,
56 "cancelled" => RunState::Cancelled,
57 "error" => RunState::Error,
58 other => return Err(Error::Database(format!("unknown CI run state {other:?}"))),
59 })
60 }
61}
62
63/// State of a job. Stored as the `as_str` name.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum JobState {
66 Blocked,
67 Queued,
68 Running,
69 Success,
70 Failure,
71 Cancelled,
72 Error,
73 Skipped,
74}
75
76impl JobState {
77 pub fn as_str(self) -> &'static str {
78 match self {
79 JobState::Blocked => "blocked",
80 JobState::Queued => "queued",
81 JobState::Running => "running",
82 JobState::Success => "success",
83 JobState::Failure => "failure",
84 JobState::Cancelled => "cancelled",
85 JobState::Error => "error",
86 JobState::Skipped => "skipped",
87 }
88 }
89
90 /// True for states a job cannot leave.
91 pub fn is_terminal(self) -> bool {
92 matches!(
93 self,
94 JobState::Success
95 | JobState::Failure
96 | JobState::Cancelled
97 | JobState::Error
98 | JobState::Skipped
99 )
100 }
101}
102
103impl FromStr for JobState {
104 type Err = Error;
105
106 fn from_str(s: &str) -> Result<Self> {
107 Ok(match s {
108 "blocked" => JobState::Blocked,
109 "queued" => JobState::Queued,
110 "running" => JobState::Running,
111 "success" => JobState::Success,
112 "failure" => JobState::Failure,
113 "cancelled" => JobState::Cancelled,
114 "error" => JobState::Error,
115 "skipped" => JobState::Skipped,
116 other => return Err(Error::Database(format!("unknown CI job state {other:?}"))),
117 })
118 }
119}
120
121/// A registered runner. The secret and its hash are never part of this type.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct CiRunner {
124 pub id: String,
125 pub name: String,
126 pub labels: Vec<String>,
127 pub created_at: String,
128 pub last_seen_at: Option<String>,
129 pub disabled: bool,
130 /// The concurrency an admin set in the web UI (1 to 64). `None` means the runner uses the
131 /// value from its own `runner.toml`.
132 pub concurrency_override: Option<u32>,
133 /// What the runner last reported about itself. All `None` for a runner that never has.
134 pub reported: RunnerReport,
135 /// Jobs this runner is running now, counted from the job table.
136 pub running_jobs: u32,
137 /// The runner's effective config as it last reported it, by field key. Secrets are redacted.
138 pub reported_config: BTreeMap<String, serde_json::Value>,
139 /// A restart an admin asked for that the runner has not yet carried out.
140 pub restart: Option<RunnerRestart>,
141 /// Admin-set values by field key. A key here beats the runner's own runner.toml.
142 pub config_overrides: BTreeMap<String, serde_json::Value>,
143}
144
145/// How a runner restarts when an admin asks.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum RestartMode {
148 /// Stop claiming, let the running jobs finish, then restart.
149 Drain,
150 /// Cancel the running jobs and restart at once.
151 Now,
152}
153
154impl RestartMode {
155 pub fn as_str(self) -> &'static str {
156 match self {
157 Self::Drain => "drain",
158 Self::Now => "now",
159 }
160 }
161}
162
163impl std::str::FromStr for RestartMode {
164 type Err = ();
165 fn from_str(s: &str) -> std::result::Result<Self, ()> {
166 match s {
167 "drain" => Ok(Self::Drain),
168 "now" => Ok(Self::Now),
169 _ => Err(()),
170 }
171 }
172}
173
174/// A pending runner restart: asked for, not yet seen to happen.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct RunnerRestart {
177 pub mode: RestartMode,
178 pub requested_at: String,
179}
180
181/// How a runner config field can be changed from the web UI.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum FieldKind {
184 /// Applied on the runner's next check-in, with no restart.
185 Live,
186 /// Stored now, applied when the runner next starts.
187 Restart,
188 /// Shown only.
189 ReadOnly,
190}
191
192/// One field of `runner.toml` as the admin UI sees it. `key` is the dotted TOML path.
193#[derive(Debug, Clone, Copy)]
194pub struct RunnerField {
195 pub key: &'static str,
196 pub kind: FieldKind,
197}
198
199/// Every field the runner reports, in display order. Identity, the secret and the forge URL are
200/// read-only: changing them from the forge would lock the runner out. Only `concurrency` and
201/// `labels` can be applied without a restart, because the forge holds the labels itself and the
202/// runner resizes its job slots live. Everything else is read once at startup.
203pub const RUNNER_FIELDS: &[RunnerField] = &[
204 RunnerField {
205 key: "concurrency",
206 kind: FieldKind::Live,
207 },
208 RunnerField {
209 key: "labels",
210 kind: FieldKind::Live,
211 },
212 RunnerField {
213 key: "auto_update",
214 kind: FieldKind::Restart,
215 },
216 RunnerField {
217 key: "executor",
218 kind: FieldKind::Restart,
219 },
220 RunnerField {
221 key: "work_dir",
222 kind: FieldKind::Restart,
223 },
224 RunnerField {
225 key: "limits.memory",
226 kind: FieldKind::Restart,
227 },
228 RunnerField {
229 key: "limits.reserve_memory",
230 kind: FieldKind::Live,
231 },
232 RunnerField {
233 key: "limits.memory_budget",
234 kind: FieldKind::Live,
235 },
236 RunnerField {
237 key: "limits.cpus",
238 kind: FieldKind::Restart,
239 },
240 RunnerField {
241 key: "limits.pids",
242 kind: FieldKind::Restart,
243 },
244 RunnerField {
245 key: "limits.image_max_gb",
246 kind: FieldKind::Restart,
247 },
248 RunnerField {
249 key: "images.keep_days",
250 kind: FieldKind::Restart,
251 },
252 RunnerField {
253 key: "cache_max_gib",
254 kind: FieldKind::Restart,
255 },
256 RunnerField {
257 key: "sandbox.userns",
258 kind: FieldKind::Restart,
259 },
260 RunnerField {
261 key: "name",
262 kind: FieldKind::ReadOnly,
263 },
264 RunnerField {
265 key: "url",
266 kind: FieldKind::ReadOnly,
267 },
268 RunnerField {
269 key: "runner_id",
270 kind: FieldKind::ReadOnly,
271 },
272 RunnerField {
273 key: "runner_secret",
274 kind: FieldKind::ReadOnly,
275 },
276 RunnerField {
277 key: "registry",
278 kind: FieldKind::ReadOnly,
279 },
280];
281
282/// The field with this key.
283pub fn runner_field(key: &str) -> Option<&'static RunnerField> {
284 RUNNER_FIELDS.iter().find(|f| f.key == key)
285}
286
287fn int_in(
288 raw: &str,
289 lo: i64,
290 hi: i64,
291 what: &str,
292) -> std::result::Result<serde_json::Value, String> {
293 match raw.trim().parse::<i64>() {
294 Ok(n) if (lo..=hi).contains(&n) => Ok(serde_json::Value::from(n)),
295 _ => Err(format!("{what} must be a whole number from {lo} to {hi}")),
296 }
297}
298
299/// Checks `raw` (the text the admin typed) for field `key` and returns the JSON value to store.
300/// `Err` carries a message for the admin. Read-only and unknown fields are refused.
301pub fn validate_runner_field(
302 key: &str,
303 raw: &str,
304) -> std::result::Result<serde_json::Value, String> {
305 use serde_json::Value;
306 let raw = raw.trim();
307 match key {
308 "concurrency" => int_in(
309 raw,
310 i64::from(MIN_RUNNER_CONCURRENCY),
311 i64::from(MAX_RUNNER_CONCURRENCY),
312 "concurrency",
313 ),
314 "labels" => {
315 let labels: Vec<String> = raw
316 .split(',')
317 .map(|l| l.trim().to_owned())
318 .filter(|l| !l.is_empty())
319 .collect();
320 if labels
321 .iter()
322 .any(|l| l.len() > 64 || l.contains(char::is_whitespace))
323 {
324 return Err("each label is 1 to 64 characters with no spaces".into());
325 }
326 Ok(Value::from(labels))
327 }
328 "auto_update" => match raw {
329 "true" => Ok(Value::Bool(true)),
330 "false" => Ok(Value::Bool(false)),
331 _ => Err("auto_update must be true or false".into()),
332 },
333 "executor" => match raw {
334 "builtin" | "podman" => Ok(Value::from(raw)),
335 _ => Err("executor must be builtin or podman".into()),
336 },
337 "sandbox.userns" => match raw {
338 "auto" | "single" | "subuid" => Ok(Value::from(raw)),
339 _ => Err("userns must be auto, single or subuid".into()),
340 },
341 "work_dir" => {
342 if raw.starts_with('/') && raw.len() <= 512 && !raw.contains('\0') {
343 Ok(Value::from(raw))
344 } else {
345 Err("work_dir must be an absolute path".into())
346 }
347 }
348 "limits.memory" => {
349 let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic());
350 let unit = &raw[digits.len()..];
351 let ok = !digits.is_empty()
352 && digits.chars().all(|c| c.is_ascii_digit())
353 && matches!(
354 unit.to_ascii_lowercase().as_str(),
355 "" | "b" | "k" | "m" | "g" | "t" | "kb" | "mb" | "gb" | "tb"
356 );
357 if ok {
358 Ok(Value::from(raw))
359 } else {
360 Err("memory looks like 4g, 512m or a byte count".into())
361 }
362 }
363 "limits.reserve_memory" => {
364 if size_in_range(raw, 64 << 20, 1 << 40) {
365 Ok(Value::from(raw))
366 } else {
367 Err("reserve_memory looks like 1g or 512m, from 64m to 1024g".into())
368 }
369 }
370 "limits.memory_budget" => {
371 if raw == "auto" || size_in_range(raw, 256 << 20, 1 << 50) {
372 Ok(Value::from(raw))
373 } else {
374 Err("memory_budget is auto, or looks like 6g or 6144m".into())
375 }
376 }
377 "limits.cpus" => {
378 let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0)
379 && raw.chars().all(|c| c.is_ascii_digit() || c == '.');
380 if ok {
381 Ok(Value::from(raw))
382 } else {
383 Err("cpus is a positive number such as 2 or 1.5".into())
384 }
385 }
386 "limits.pids" => int_in(raw, 1, 4_194_304, "pids"),
387 "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"),
388 "images.keep_days" => int_in(raw, 0, 3650, "keep_days"),
389 "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"),
390 _ => Err("this field cannot be changed from the forge".into()),
391 }
392}
393
394/// Facts a runner reports about itself on a claim or heartbeat. A field the runner did not send is
395/// `None` and leaves the stored value alone.
396#[derive(Debug, Clone, Default, PartialEq, Eq)]
397pub struct RunnerReport {
398 /// The concurrency the runner is applying right now.
399 pub concurrency: Option<u32>,
400 pub version: Option<String>,
401 pub cpus: Option<u32>,
402 pub memory_bytes: Option<u64>,
403 /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`.
404 pub build: Option<String>,
405 /// Random per process start. A change means the runner restarted.
406 pub boot_id: Option<String>,
407 /// Features the runner says it has. The crate version never changes between builds, so the
408 /// forge gates features on these and not on the version.
409 pub capabilities: Vec<String>,
410 /// The runner's memory budget for jobs, in bytes.
411 pub memory_budget: Option<u64>,
412 /// Budget minus what running jobs reserved, as of the runner's last claim.
413 pub memory_free: Option<u64>,
414 /// What the runner reserves for a job that declares no `memory`.
415 pub memory_reserve: Option<u64>,
416}
417
418impl RunnerReport {
419 /// Memory the running jobs reserved, when the runner reports a budget.
420 pub fn memory_reserved(&self) -> Option<u64> {
421 Some(self.memory_budget?.saturating_sub(self.memory_free?))
422 }
423}
424
425/// How long a queued job that does not fit a runner may wait before smaller jobs stop passing it.
426/// See [`pick_by_memory`].
427pub const STARVE_AFTER_SECS: u64 = 300;
428
429/// What a runner can admit right now, from its claim.
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431pub struct MemoryOffer {
432 /// Budget minus what running jobs reserved, in bytes.
433 pub free: u64,
434 /// The runner's whole budget. A job that reserves more than this is treated as reserving the
435 /// whole budget, so it still runs when the runner is idle instead of waiting forever.
436 pub budget: Option<u64>,
437 /// The reservation of a job that declares no `memory`.
438 pub default_reserve: u64,
439}
440
441impl MemoryOffer {
442 /// What a job reserves on this runner: its declared memory or the default, capped at the
443 /// budget.
444 pub fn reservation(&self, declared: Option<u64>) -> u64 {
445 let want = declared.unwrap_or(self.default_reserve);
446 self.budget.map_or(want, |budget| want.min(budget))
447 }
448
449 /// True when a job with this declared memory fits in the free memory.
450 pub fn fits(&self, declared: Option<u64>) -> bool {
451 self.reservation(declared) <= self.free
452 }
453}
454
455/// Picks which of the label-compatible queued jobs, oldest first, a runner with `offer` takes.
456/// Each candidate is `(declared memory, seconds waited)`. Returns the index of the first job that
457/// fits. A job that does not fit is skipped so smaller jobs behind it can run, but only while it
458/// has waited less than `starve_after` seconds. Once an unfit job has waited that long, nothing
459/// behind it is handed out: the runner drains its running jobs until the old job fits.
460pub fn pick_by_memory(
461 candidates: &[(Option<u64>, u64)],
462 offer: &MemoryOffer,
463 starve_after: u64,
464) -> Option<usize> {
465 for (i, (declared, waited)) in candidates.iter().enumerate() {
466 if offer.fits(*declared) {
467 return Some(i);
468 }
469 if *waited >= starve_after {
470 return None;
471 }
472 }
473 None
474}
475
476fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool {
477 forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n))
478}
479
480/// The capability of a runner that restarts when the forge asks.
481pub const CAP_RESTART: &str = "restart";
482
483impl CiRunner {
484 /// True when the runner advertises that it honours a restart request.
485 pub fn supports_restart(&self) -> bool {
486 self.reported.capabilities.iter().any(|c| c == CAP_RESTART)
487 }
488}
489
490/// The smallest and largest concurrency an admin may set.
491pub const MIN_RUNNER_CONCURRENCY: u32 = 1;
492pub const MAX_RUNNER_CONCURRENCY: u32 = 64;
493
494/// One run of the workflow for a commit.
495#[derive(Debug, Clone, PartialEq, Eq)]
496pub struct CiRun {
497 pub id: String,
498 pub repo_id: String,
499 pub number: i64,
500 /// `push`, `tag`, `pull_request` or `manual`.
501 pub trigger: String,
502 pub git_ref: String,
503 pub commit_oid: String,
504 pub pull_number: Option<i64>,
505 pub actor_id: String,
506 pub state: RunState,
507 pub config_error: Option<String>,
508 pub created_at: String,
509 pub finished_at: Option<String>,
510}
511
512/// One job of a run. `spec_json` is the JobSpec as JSON text.
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct CiJob {
515 pub id: String,
516 pub run_id: String,
517 pub name: String,
518 pub spec_json: String,
519 pub state: JobState,
520 pub runner_id: Option<String>,
521 pub exit_code: Option<i64>,
522 pub message: Option<String>,
523 pub queued_at: Option<String>,
524 pub started_at: Option<String>,
525 pub finished_at: Option<String>,
526 pub heartbeat_at: Option<String>,
527 pub cancel_requested: bool,
528 pub log_bytes: i64,
529 /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the
530 /// runner did not say (an older runner) or nothing was killed.
531 pub oom_kills: Option<u32>,
532}
533
534/// An artifact uploaded by a job. The file itself is stored outside the database.
535#[derive(Debug, Clone, PartialEq, Eq)]
536pub struct CiArtifact {
537 pub id: String,
538 pub job_id: String,
539 pub name: String,
540 pub size: i64,
541 pub sha256: String,
542 pub created_at: String,
543}
544
545/// A job to create with a run. `needs` must match the `needs` in `spec_json`.
546#[derive(Debug, Clone, Copy)]
547pub struct NewJob<'a> {
548 pub name: &'a str,
549 pub spec_json: &'a str,
550 pub needs: &'a [String],
551}
552
553#[cfg(test)]
554mod memory_tests {
555 use super::*;
556
557 const GIB: u64 = 1 << 30;
558
559 fn offer(free: u64) -> MemoryOffer {
560 MemoryOffer {
561 free: free * GIB,
562 budget: Some(6 * GIB),
563 default_reserve: GIB,
564 }
565 }
566
567 #[test]
568 fn the_first_job_that_fits_is_picked() {
569 let queue = [(Some(4 * GIB), 10), (Some(GIB), 5), (None, 1)];
570 assert_eq!(pick_by_memory(&queue, &offer(6), 300), Some(0));
571 assert_eq!(pick_by_memory(&queue, &offer(2), 300), Some(1));
572 assert_eq!(pick_by_memory(&queue, &offer(1), 300), Some(1));
573 assert_eq!(pick_by_memory(&queue, &offer(0), 300), None);
574 assert_eq!(pick_by_memory(&[], &offer(6), 300), None);
575 }
576
577 #[test]
578 fn a_job_without_memory_reserves_the_runners_default() {
579 let queue = [(None, 0)];
580 assert_eq!(pick_by_memory(&queue, &offer(1), 300), Some(0));
581 let big_default = MemoryOffer {
582 default_reserve: 2 * GIB,
583 ..offer(1)
584 };
585 assert_eq!(pick_by_memory(&queue, &big_default, 300), None);
586 }
587
588 #[test]
589 fn an_oversized_job_counts_as_the_whole_budget() {
590 let queue = [(Some(64 * GIB), 0)];
591 assert_eq!(pick_by_memory(&queue, &offer(6), 300), Some(0));
592 assert_eq!(pick_by_memory(&queue, &offer(5), 300), None);
593 }
594
595 #[test]
596 fn a_waiting_job_is_passed_only_until_the_threshold() {
597 let young = [(Some(4 * GIB), 299), (Some(GIB), 0)];
598 assert_eq!(pick_by_memory(&young, &offer(2), 300), Some(1));
599 let old = [(Some(4 * GIB), 300), (Some(GIB), 0)];
600 assert_eq!(pick_by_memory(&old, &offer(2), 300), None);
601 assert_eq!(pick_by_memory(&old, &offer(4), 300), Some(0));
602 }
603
604 #[test]
605 fn memory_fields_are_validated() {
606 for ok in ["1g", "512m", "2G"] {
607 assert!(validate_runner_field("limits.reserve_memory", ok).is_ok());
608 }
609 for bad in ["", "0", "lots", "1k", "2t"] {
610 assert!(validate_runner_field("limits.reserve_memory", bad).is_err());
611 }
612 for ok in ["auto", "6g", "6144m"] {
613 assert!(validate_runner_field("limits.memory_budget", ok).is_ok());
614 }
615 for bad in ["", "0", "-1", "big"] {
616 assert!(validate_runner_field("limits.memory_budget", bad).is_err());
617 }
618 assert_eq!(
619 runner_field("limits.memory_budget").map(|f| f.kind),
620 Some(FieldKind::Live)
621 );
622 }
623}