| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::collections::BTreeMap; |
| 8 | use std::str::FromStr; |
| 9 | |
| 10 | use crate::error::{Error, Result}; |
| 11 | |
| 12 | |
| 13 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 14 | pub enum RunState { |
| 15 | WaitingApproval, |
| 16 | Queued, |
| 17 | Running, |
| 18 | Success, |
| 19 | Failure, |
| 20 | Cancelled, |
| 21 | Error, |
| 22 | } |
| 23 | |
| 24 | impl 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 | |
| 38 | pub fn is_terminal(self) -> bool { |
| 39 | matches!( |
| 40 | self, |
| 41 | RunState::Success | RunState::Failure | RunState::Cancelled | RunState::Error |
| 42 | ) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl 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 | |
| 64 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 65 | pub enum JobState { |
| 66 | Blocked, |
| 67 | Queued, |
| 68 | Running, |
| 69 | Success, |
| 70 | Failure, |
| 71 | Cancelled, |
| 72 | Error, |
| 73 | Skipped, |
| 74 | } |
| 75 | |
| 76 | impl 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 | |
| 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 | |
| 103 | impl 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 | |
| 122 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 123 | pub 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 | |
| 131 | |
| 132 | pub concurrency_override: Option<u32>, |
| 133 | |
| 134 | pub reported: RunnerReport, |
| 135 | |
| 136 | pub running_jobs: u32, |
| 137 | |
| 138 | pub reported_config: BTreeMap<String, serde_json::Value>, |
| 139 | |
| 140 | pub restart: Option<RunnerRestart>, |
| 141 | |
| 142 | pub config_overrides: BTreeMap<String, serde_json::Value>, |
| 143 | } |
| 144 | |
| 145 | |
| 146 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 147 | pub enum RestartMode { |
| 148 | |
| 149 | Drain, |
| 150 | |
| 151 | Now, |
| 152 | } |
| 153 | |
| 154 | impl RestartMode { |
| 155 | pub fn as_str(self) -> &'static str { |
| 156 | match self { |
| 157 | Self::Drain => "drain", |
| 158 | Self::Now => "now", |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl 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 | |
| 175 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 176 | pub struct RunnerRestart { |
| 177 | pub mode: RestartMode, |
| 178 | pub requested_at: String, |
| 179 | } |
| 180 | |
| 181 | |
| 182 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 183 | pub enum FieldKind { |
| 184 | |
| 185 | Live, |
| 186 | |
| 187 | Restart, |
| 188 | |
| 189 | ReadOnly, |
| 190 | } |
| 191 | |
| 192 | |
| 193 | #[derive(Debug, Clone, Copy)] |
| 194 | pub struct RunnerField { |
| 195 | pub key: &'static str, |
| 196 | pub kind: FieldKind, |
| 197 | } |
| 198 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | pub 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 | |
| 283 | pub fn runner_field(key: &str) -> Option<&'static RunnerField> { |
| 284 | RUNNER_FIELDS.iter().find(|f| f.key == key) |
| 285 | } |
| 286 | |
| 287 | fn 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 | |
| 300 | |
| 301 | pub 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 | |
| 395 | |
| 396 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 397 | pub struct RunnerReport { |
| 398 | |
| 399 | pub concurrency: Option<u32>, |
| 400 | pub version: Option<String>, |
| 401 | pub cpus: Option<u32>, |
| 402 | pub memory_bytes: Option<u64>, |
| 403 | |
| 404 | pub build: Option<String>, |
| 405 | |
| 406 | pub boot_id: Option<String>, |
| 407 | |
| 408 | |
| 409 | pub capabilities: Vec<String>, |
| 410 | |
| 411 | pub memory_budget: Option<u64>, |
| 412 | |
| 413 | pub memory_free: Option<u64>, |
| 414 | |
| 415 | pub memory_reserve: Option<u64>, |
| 416 | } |
| 417 | |
| 418 | impl RunnerReport { |
| 419 | |
| 420 | pub fn memory_reserved(&self) -> Option<u64> { |
| 421 | Some(self.memory_budget?.saturating_sub(self.memory_free?)) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | |
| 426 | |
| 427 | pub const STARVE_AFTER_SECS: u64 = 300; |
| 428 | |
| 429 | |
| 430 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 431 | pub struct MemoryOffer { |
| 432 | |
| 433 | pub free: u64, |
| 434 | |
| 435 | |
| 436 | pub budget: Option<u64>, |
| 437 | |
| 438 | pub default_reserve: u64, |
| 439 | } |
| 440 | |
| 441 | impl MemoryOffer { |
| 442 | |
| 443 | |
| 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 | |
| 450 | pub fn fits(&self, declared: Option<u64>) -> bool { |
| 451 | self.reservation(declared) <= self.free |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | pub 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 | |
| 476 | fn 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 | |
| 481 | pub const CAP_RESTART: &str = "restart"; |
| 482 | |
| 483 | impl CiRunner { |
| 484 | |
| 485 | pub fn supports_restart(&self) -> bool { |
| 486 | self.reported.capabilities.iter().any(|c| c == CAP_RESTART) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | |
| 491 | pub const MIN_RUNNER_CONCURRENCY: u32 = 1; |
| 492 | pub const MAX_RUNNER_CONCURRENCY: u32 = 64; |
| 493 | |
| 494 | |
| 495 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 496 | pub struct CiRun { |
| 497 | pub id: String, |
| 498 | pub repo_id: String, |
| 499 | pub number: i64, |
| 500 | |
| 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 | |
| 513 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 514 | pub 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 | |
| 530 | |
| 531 | pub oom_kills: Option<u32>, |
| 532 | } |
| 533 | |
| 534 | |
| 535 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 536 | pub 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 | |
| 546 | #[derive(Debug, Clone, Copy)] |
| 547 | pub struct NewJob<'a> { |
| 548 | pub name: &'a str, |
| 549 | pub spec_json: &'a str, |
| 550 | pub needs: &'a [String], |
| 551 | } |
| 552 | |
| 553 | #[cfg(test)] |
| 554 | mod 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 | } |