Runner memory is one box (RAM minus kept-for-host) shared by all jobs, swap left to the OS, concurrency the only gate
Browse files at this commitd75b65da75b156318b86a4cd073bcb3dd9afb023Parent: 5736671All checks have passed
Show checks
ci/buildSucceededDetails
- refactor
- runner memory is one box (RAM minus kept-for-host) shared by all jobs, swap left to the OS, concurrency the only gate
- drops reservations, pressure parking and requeue. Fixes: log upload retries transient failures instead of dropping the rest of the log, running jobs spin and their live step pulses, wiki hides its empty page rail
25 changed files +210 -2594
- crates/forge-ci/src/config.rs +7 -0
- crates/forge-ci/src/config/job.rs +1 -5
- crates/forge-ci/src/config/memory.rs +5 -7
- crates/forge-ci/src/proto.rs +0 -27
- crates/forge-core/src/ci.rs +0 -139
- crates/forge-core/src/store/ci.rs +22 -292
- crates/forge-runner/src/cache.rs +0 -1
- crates/forge-runner/src/cli.rs +6 -14
- crates/forge-runner/src/client.rs +9 -53
- crates/forge-runner/src/config.rs +32 -165
- crates/forge-runner/src/executor.rs +6 -31
- crates/forge-runner/src/logs.rs +13 -2
- crates/forge-runner/src/memory.rs +15 -245
- crates/forge-runner/src/pressure.rs +12 -1050
- crates/forge-runner/src/runner.rs +3 -103
- crates/forge-runner/src/sandbox/spec.rs +14 -48
- crates/forge-runner/tests/integration/builtin.rs +0 -3
- crates/forge-runner/tests/integration/flow.rs +0 -1
- crates/forge-web-app/src/ci/api.rs +15 -115
- crates/forge-web-app/src/ci/api_tests.rs +4 -139
- crates/forge-web-pages/src/pages/admin_runners.rs +4 -65
- crates/forge-web-pages/src/pages/wiki.rs +4 -1
- crates/forge-web/src/routes.snap +0 -1
- docs/ci.md +11 -86
- style/_one.scss +27 -1
crates/forge-ci/src/config.rsmodified+7 -0
| @@ -72,6 +72,13 @@ pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> { | |||
| 72 | .map_err(|e| ConfigError::Toml(e.to_string()))?; | 72 | .map_err(|e| ConfigError::Toml(e.to_string()))?; |
| 73 | config.expand_matrices()?; | 73 | config.expand_matrices()?; |
| 74 | config.validate()?; | 74 | config.validate()?; |
| 75 | + for (name, job) in &config.jobs { | ||
| 76 | + if job.memory.is_some() { | ||
| 77 | + warnings.push(format!( | ||
| 78 | + "jobs.{name}.memory is no longer used, the runner shares its memory between jobs" | ||
| 79 | + )); | ||
| 80 | + } | ||
| 81 | + } | ||
| 75 | config.warnings = warnings; | 82 | config.warnings = warnings; |
| 76 | Ok(config) | 83 | Ok(config) |
| 77 | } | 84 | } |
crates/forge-ci/src/config/job.rsmodified+1 -5
| @@ -32,11 +32,7 @@ pub struct JobSpec { | |||
| 32 | pub timeout_minutes: u32, | 32 | pub timeout_minutes: u32, |
| 33 | #[serde(default = "default_network")] | 33 | #[serde(default = "default_network")] |
| 34 | pub network: bool, | 34 | pub network: bool, |
| 35 | - #[serde( | 35 | + #[serde(default, deserialize_with = "deserialize_memory", skip_serializing)] |
| 36 | - default, | ||
| 37 | - deserialize_with = "deserialize_memory", | ||
| 38 | - skip_serializing_if = "Option::is_none" | ||
| 39 | - )] | ||
| 40 | pub memory: Option<u64>, | 36 | pub memory: Option<u64>, |
| 41 | #[serde(default, skip_serializing_if = "Option::is_none")] | 37 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 42 | pub matrix: Option<MatrixSpec>, | 38 | pub matrix: Option<MatrixSpec>, |
crates/forge-ci/src/config/memory.rsmodified+5 -7
| @@ -36,13 +36,11 @@ mod tests { | |||
| 36 | parse_config(&job_toml("")).unwrap().jobs["build"].memory, | 36 | parse_config(&job_toml("")).unwrap().jobs["build"].memory, |
| 37 | None | 37 | None |
| 38 | ); | 38 | ); |
| 39 | - let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"]; | 39 | + let cfg = parse_config(&job_toml("memory = \"4g\"")).unwrap(); |
| 40 | - let json = serde_json::to_string(job).unwrap(); | 40 | + assert_eq!(cfg.warnings.len(), 1, "{:?}", cfg.warnings); |
| 41 | - assert!(json.contains("\"memory\":4294967296"), "{json}"); | 41 | + let json = serde_json::to_string(&cfg.jobs["build"]).unwrap(); |
| 42 | - let back: JobSpec = serde_json::from_str(&json).unwrap(); | 42 | + assert!(!json.contains("memory"), "{json}"); |
| 43 | - assert_eq!(back.memory, Some(4 << 30)); | 43 | + serde_json::from_str::<JobSpec>(&json).unwrap(); |
| 44 | - let old = json.replace(",\"memory\":4294967296", ""); | ||
| 45 | - assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None); | ||
| 46 | } | 44 | } |
| 47 | 45 | ||
| 48 | #[test] | 46 | #[test] |
crates/forge-ci/src/proto.rsmodified+0 -27
| @@ -54,23 +54,10 @@ pub struct ClaimRequest { | |||
| 54 | pub boot_id: Option<String>, | 54 | pub boot_id: Option<String>, |
| 55 | #[serde(default, skip_serializing_if = "Vec::is_empty")] | 55 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 56 | pub capabilities: Vec<String>, | 56 | pub capabilities: Vec<String>, |
| 57 | - #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 58 | - pub free_memory_bytes: Option<u64>, | ||
| 59 | - #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 60 | - pub memory_budget_bytes: Option<u64>, | ||
| 61 | - #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 62 | - pub reserve_memory_bytes: Option<u64>, | ||
| 63 | } | 57 | } |
| 64 | 58 | ||
| 65 | pub const CAP_RESTART: &str = "restart"; | 59 | pub const CAP_RESTART: &str = "restart"; |
| 66 | 60 | ||
| 67 | -pub const CAP_REQUEUE: &str = "requeue"; | ||
| 68 | - | ||
| 69 | -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | ||
| 70 | -pub struct RequeueRequest { | ||
| 71 | - pub reason: String, | ||
| 72 | -} | ||
| 73 | - | ||
| 74 | pub const CAP_RUNNER_LOG: &str = "runner_log"; | 61 | pub const CAP_RUNNER_LOG: &str = "runner_log"; |
| 75 | 62 | ||
| 76 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | 63 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -157,10 +144,6 @@ pub const BUILD_HEADER: &str = "Forge-Runner-Build"; | |||
| 157 | 144 | ||
| 158 | pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; | 145 | pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency"; |
| 159 | 146 | ||
| 160 | -pub const MEMORY_BUDGET_HEADER: &str = "Forge-Runner-Memory-Budget"; | ||
| 161 | - | ||
| 162 | -pub const RESERVE_MEMORY_HEADER: &str = "Forge-Runner-Reserve-Memory"; | ||
| 163 | - | ||
| 164 | pub const MIN_CONCURRENCY: u32 = 1; | 147 | pub const MIN_CONCURRENCY: u32 = 1; |
| 165 | pub const MAX_CONCURRENCY: u32 = 64; | 148 | pub const MAX_CONCURRENCY: u32 = 64; |
| 166 | 149 | ||
| @@ -186,8 +169,6 @@ pub struct JobAssignment { | |||
| 186 | pub cache_key: String, | 169 | pub cache_key: String, |
| 187 | #[serde(default, skip_serializing_if = "Vec::is_empty")] | 170 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 188 | pub cache_restore_keys: Vec<String>, | 171 | pub cache_restore_keys: Vec<String>, |
| 189 | - #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 190 | - pub memory_bytes: Option<u64>, | ||
| 191 | } | 172 | } |
| 192 | 173 | ||
| 193 | impl fmt::Debug for JobAssignment { | 174 | impl fmt::Debug for JobAssignment { |
| @@ -210,7 +191,6 @@ impl fmt::Debug for JobAssignment { | |||
| 210 | .field("cache", &self.cache) | 191 | .field("cache", &self.cache) |
| 211 | .field("cache_key", &self.cache_key) | 192 | .field("cache_key", &self.cache_key) |
| 212 | .field("cache_restore_keys", &self.cache_restore_keys) | 193 | .field("cache_restore_keys", &self.cache_restore_keys) |
| 213 | - .field("memory_bytes", &self.memory_bytes) | ||
| 214 | .finish() | 194 | .finish() |
| 215 | } | 195 | } |
| 216 | } | 196 | } |
| @@ -269,8 +249,6 @@ mod tests { | |||
| 269 | fn old_and_new_claim_and_heartbeat_bodies_parse() { | 249 | fn old_and_new_claim_and_heartbeat_bodies_parse() { |
| 270 | let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); | 250 | let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap(); |
| 271 | assert_eq!(old.concurrency, None); | 251 | assert_eq!(old.concurrency, None); |
| 272 | - assert_eq!(old.free_memory_bytes, None); | ||
| 273 | - assert_eq!(old.reserve_memory_bytes, None); | ||
| 274 | let json = serde_json::to_string(&old).unwrap(); | 252 | let json = serde_json::to_string(&old).unwrap(); |
| 275 | assert!(!json.contains("memory"), "{json}"); | 253 | assert!(!json.contains("memory"), "{json}"); |
| 276 | let new = ClaimRequest { | 254 | let new = ClaimRequest { |
| @@ -282,9 +260,6 @@ mod tests { | |||
| 282 | capabilities: vec![CAP_RESTART.into()], | 260 | capabilities: vec![CAP_RESTART.into()], |
| 283 | memory_bytes: Some(1 << 33), | 261 | memory_bytes: Some(1 << 33), |
| 284 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 262 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 285 | - free_memory_bytes: Some(6 << 30), | ||
| 286 | - memory_budget_bytes: Some(6 << 30), | ||
| 287 | - reserve_memory_bytes: Some(1 << 30), | ||
| 288 | }; | 263 | }; |
| 289 | let back: ClaimRequest = | 264 | let back: ClaimRequest = |
| 290 | serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap(); | 265 | serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap(); |
| @@ -348,7 +323,6 @@ mod tests { | |||
| 348 | cache: vec![], | 323 | cache: vec![], |
| 349 | cache_key: String::new(), | 324 | cache_key: String::new(), |
| 350 | cache_restore_keys: vec![], | 325 | cache_restore_keys: vec![], |
| 351 | - memory_bytes: None, | ||
| 352 | }; | 326 | }; |
| 353 | let json = serde_json::to_string(&job).unwrap(); | 327 | let json = serde_json::to_string(&job).unwrap(); |
| 354 | assert!(!json.contains("cache"), "{json}"); | 328 | assert!(!json.contains("cache"), "{json}"); |
| @@ -378,7 +352,6 @@ mod tests { | |||
| 378 | cache: vec![], | 352 | cache: vec![], |
| 379 | cache_key: String::new(), | 353 | cache_key: String::new(), |
| 380 | cache_restore_keys: vec![], | 354 | cache_restore_keys: vec![], |
| 381 | - memory_bytes: None, | ||
| 382 | }; | 355 | }; |
| 383 | let dbg = format!("{job:?}"); | 356 | let dbg = format!("{job:?}"); |
| 384 | assert!(!dbg.contains("hunter2-value")); | 357 | assert!(!dbg.contains("hunter2-value")); |
crates/forge-core/src/ci.rsmodified+0 -139
| @@ -127,26 +127,10 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[ | |||
| 127 | key: "work_dir", | 127 | key: "work_dir", |
| 128 | kind: FieldKind::Restart, | 128 | kind: FieldKind::Restart, |
| 129 | }, | 129 | }, |
| 130 | - RunnerField { | ||
| 131 | - key: "limits.memory", | ||
| 132 | - kind: FieldKind::Restart, | ||
| 133 | - }, | ||
| 134 | - RunnerField { | ||
| 135 | - key: "limits.reserve_memory", | ||
| 136 | - kind: FieldKind::Live, | ||
| 137 | - }, | ||
| 138 | - RunnerField { | ||
| 139 | - key: "limits.memory_budget", | ||
| 140 | - kind: FieldKind::Live, | ||
| 141 | - }, | ||
| 142 | RunnerField { | 130 | RunnerField { |
| 143 | key: "limits.memory_headroom", | 131 | key: "limits.memory_headroom", |
| 144 | kind: FieldKind::Restart, | 132 | kind: FieldKind::Restart, |
| 145 | }, | 133 | }, |
| 146 | - RunnerField { | ||
| 147 | - key: "limits.budget_swap_percent", | ||
| 148 | - kind: FieldKind::Restart, | ||
| 149 | - }, | ||
| 150 | RunnerField { | 134 | RunnerField { |
| 151 | key: "limits.cpus", | 135 | key: "limits.cpus", |
| 152 | kind: FieldKind::Restart, | 136 | kind: FieldKind::Restart, |
| @@ -267,35 +251,6 @@ pub fn validate_runner_field( | |||
| 267 | Err("work_dir must be an absolute path".into()) | 251 | Err("work_dir must be an absolute path".into()) |
| 268 | } | 252 | } |
| 269 | } | 253 | } |
| 270 | - "limits.memory" => { | ||
| 271 | - let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic()); | ||
| 272 | - let unit = &raw[digits.len()..]; | ||
| 273 | - let ok = !digits.is_empty() | ||
| 274 | - && digits.chars().all(|c| c.is_ascii_digit()) | ||
| 275 | - && matches!( | ||
| 276 | - unit.to_ascii_lowercase().as_str(), | ||
| 277 | - "" | "b" | "k" | "m" | "g" | "t" | "kb" | "mb" | "gb" | "tb" | ||
| 278 | - ); | ||
| 279 | - if ok { | ||
| 280 | - Ok(Value::from(raw)) | ||
| 281 | - } else { | ||
| 282 | - Err("memory looks like 4g, 512m or a byte count".into()) | ||
| 283 | - } | ||
| 284 | - } | ||
| 285 | - "limits.reserve_memory" => { | ||
| 286 | - if size_in_range(raw, 64 << 20, 1 << 40) { | ||
| 287 | - Ok(Value::from(raw)) | ||
| 288 | - } else { | ||
| 289 | - Err("reserve_memory looks like 1g or 512m, from 64m to 1024g".into()) | ||
| 290 | - } | ||
| 291 | - } | ||
| 292 | - "limits.memory_budget" => { | ||
| 293 | - if raw == "auto" || size_in_range(raw, 256 << 20, 1 << 50) { | ||
| 294 | - Ok(Value::from(raw)) | ||
| 295 | - } else { | ||
| 296 | - Err("memory_budget is auto, or looks like 6g or 6144m".into()) | ||
| 297 | - } | ||
| 298 | - } | ||
| 299 | "limits.memory_headroom" => { | 254 | "limits.memory_headroom" => { |
| 300 | if size_in_range(raw, 0, 1 << 50) { | 255 | if size_in_range(raw, 0, 1 << 50) { |
| 301 | Ok(Value::from(raw)) | 256 | Ok(Value::from(raw)) |
| @@ -303,7 +258,6 @@ pub fn validate_runner_field( | |||
| 303 | Err("memory_headroom looks like 1g or 512m".into()) | 258 | Err("memory_headroom looks like 1g or 512m".into()) |
| 304 | } | 259 | } |
| 305 | } | 260 | } |
| 306 | - "limits.budget_swap_percent" => int_in(raw, 0, 100, "budget_swap_percent"), | ||
| 307 | "limits.cpus" => { | 261 | "limits.cpus" => { |
| 308 | let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0) | 262 | let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0) |
| 309 | && raw.chars().all(|c| c.is_ascii_digit() || c == '.'); | 263 | && raw.chars().all(|c| c.is_ascii_digit() || c == '.'); |
| @@ -331,51 +285,6 @@ pub struct RunnerReport { | |||
| 331 | pub build: Option<String>, | 285 | pub build: Option<String>, |
| 332 | pub boot_id: Option<String>, | 286 | pub boot_id: Option<String>, |
| 333 | pub capabilities: Vec<String>, | 287 | pub capabilities: Vec<String>, |
| 334 | - pub memory_budget: Option<u64>, | ||
| 335 | - pub memory_free: Option<u64>, | ||
| 336 | - pub memory_reserve: Option<u64>, | ||
| 337 | -} | ||
| 338 | - | ||
| 339 | -impl RunnerReport { | ||
| 340 | - pub fn memory_reserved(&self) -> Option<u64> { | ||
| 341 | - Some(self.memory_budget?.saturating_sub(self.memory_free?)) | ||
| 342 | - } | ||
| 343 | -} | ||
| 344 | - | ||
| 345 | -pub const STARVE_AFTER_SECS: u64 = 300; | ||
| 346 | - | ||
| 347 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 348 | -pub struct MemoryOffer { | ||
| 349 | - pub free: u64, | ||
| 350 | - pub budget: Option<u64>, | ||
| 351 | - pub default_reserve: u64, | ||
| 352 | -} | ||
| 353 | - | ||
| 354 | -impl MemoryOffer { | ||
| 355 | - pub fn reservation(&self, declared: Option<u64>) -> u64 { | ||
| 356 | - let want = declared.unwrap_or(self.default_reserve); | ||
| 357 | - self.budget.map_or(want, |budget| want.min(budget)) | ||
| 358 | - } | ||
| 359 | - | ||
| 360 | - pub fn fits(&self, declared: Option<u64>) -> bool { | ||
| 361 | - self.reservation(declared) <= self.free | ||
| 362 | - } | ||
| 363 | -} | ||
| 364 | - | ||
| 365 | -pub fn pick_by_memory( | ||
| 366 | - candidates: &[(Option<u64>, u64)], | ||
| 367 | - offer: &MemoryOffer, | ||
| 368 | - starve_after: u64, | ||
| 369 | -) -> Option<usize> { | ||
| 370 | - for (i, (declared, waited)) in candidates.iter().enumerate() { | ||
| 371 | - if offer.fits(*declared) { | ||
| 372 | - return Some(i); | ||
| 373 | - } | ||
| 374 | - if *waited >= starve_after { | ||
| 375 | - return None; | ||
| 376 | - } | ||
| 377 | - } | ||
| 378 | - None | ||
| 379 | } | 288 | } |
| 380 | 289 | ||
| 381 | #[derive(Debug, Clone, Default, PartialEq, Eq)] | 290 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| @@ -383,10 +292,6 @@ pub struct QueueSkips { | |||
| 383 | pub queued: usize, | 292 | pub queued: usize, |
| 384 | pub lacking_labels: usize, | 293 | pub lacking_labels: usize, |
| 385 | pub missing_labels: Vec<String>, | 294 | pub missing_labels: Vec<String>, |
| 386 | - pub too_big: usize, | ||
| 387 | - pub smallest_need: Option<u64>, | ||
| 388 | - pub held_behind: usize, | ||
| 389 | - pub starved_need: Option<u64>, | ||
| 390 | } | 295 | } |
| 391 | 296 | ||
| 392 | fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { | 297 | fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool { |
| @@ -523,47 +428,3 @@ pub struct NewRun<'a> { | |||
| 523 | pub needs_approval: bool, | 428 | pub needs_approval: bool, |
| 524 | pub config_error: Option<&'a str>, | 429 | pub config_error: Option<&'a str>, |
| 525 | } | 430 | } |
| 526 | - | ||
| 527 | -#[cfg(test)] | ||
| 528 | -mod memory_tests { | ||
| 529 | - use super::*; | ||
| 530 | - | ||
| 531 | - const GIB: u64 = 1 << 30; | ||
| 532 | - | ||
| 533 | - fn offer(free: u64) -> MemoryOffer { | ||
| 534 | - MemoryOffer { | ||
| 535 | - free: free * GIB, | ||
| 536 | - budget: Some(6 * GIB), | ||
| 537 | - default_reserve: GIB, | ||
| 538 | - } | ||
| 539 | - } | ||
| 540 | - | ||
| 541 | - #[test] | ||
| 542 | - fn a_waiting_job_is_passed_only_until_the_threshold() { | ||
| 543 | - let young = [(Some(4 * GIB), 299), (Some(GIB), 0)]; | ||
| 544 | - assert_eq!(pick_by_memory(&young, &offer(2), 300), Some(1)); | ||
| 545 | - let old = [(Some(4 * GIB), 300), (Some(GIB), 0)]; | ||
| 546 | - assert_eq!(pick_by_memory(&old, &offer(2), 300), None); | ||
| 547 | - assert_eq!(pick_by_memory(&old, &offer(4), 300), Some(0)); | ||
| 548 | - } | ||
| 549 | - | ||
| 550 | - #[test] | ||
| 551 | - fn memory_fields_are_validated() { | ||
| 552 | - for ok in ["1g", "512m", "2G"] { | ||
| 553 | - assert!(validate_runner_field("limits.reserve_memory", ok).is_ok()); | ||
| 554 | - } | ||
| 555 | - for bad in ["", "0", "lots", "1k", "2t"] { | ||
| 556 | - assert!(validate_runner_field("limits.reserve_memory", bad).is_err()); | ||
| 557 | - } | ||
| 558 | - for ok in ["auto", "6g", "6144m"] { | ||
| 559 | - assert!(validate_runner_field("limits.memory_budget", ok).is_ok()); | ||
| 560 | - } | ||
| 561 | - for bad in ["", "0", "-1", "big"] { | ||
| 562 | - assert!(validate_runner_field("limits.memory_budget", bad).is_err()); | ||
| 563 | - } | ||
| 564 | - assert_eq!( | ||
| 565 | - runner_field("limits.memory_budget").map(|f| f.kind), | ||
| 566 | - Some(FieldKind::Live) | ||
| 567 | - ); | ||
| 568 | - } | ||
| 569 | -} | ||
crates/forge-core/src/store/ci.rsmodified+22 -292
| @@ -9,9 +9,9 @@ use super::{ | |||
| 9 | fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, | 9 | fetch_opt, finish, insert_err, missing_row, new_id, opt_int_value, opt_text, text, |
| 10 | }; | 10 | }; |
| 11 | use crate::ci::{ | 11 | use crate::ci::{ |
| 12 | - CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep, MemoryOffer, | 12 | + CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep, NewJob, NewRun, |
| 13 | - NewJob, NewRun, QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport, RunnerRestart, | 13 | + QueueSkips, RestartMode, RunState, RunnerJob, RunnerReport, RunnerRestart, StepSample, |
| 14 | - STARVE_AFTER_SECS, StepSample, pick_by_memory, validate_runner_field, | 14 | + validate_runner_field, |
| 15 | }; | 15 | }; |
| 16 | use crate::error::{Error, Result}; | 16 | use crate::error::{Error, Result}; |
| 17 | use crate::secret; | 17 | use crate::secret; |
| @@ -29,7 +29,7 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, | |||
| 29 | reported_memory_bytes, reported_config, config_overrides, \ | 29 | reported_memory_bytes, reported_config, config_overrides, \ |
| 30 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ | 30 | (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \ |
| 31 | reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ | 31 | reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \ |
| 32 | - reported_memory_budget, reported_memory_free, reported_memory_reserve, stopped_at"; | 32 | + stopped_at"; |
| 33 | const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ | 33 | const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \ |
| 34 | j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ | 34 | j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \ |
| 35 | j.log_bytes, j.oom_kills, r.number, u.username, p.name"; | 35 | j.log_bytes, j.oom_kills, r.number, u.username, p.name"; |
| @@ -50,7 +50,7 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | |||
| 50 | labels, | 50 | labels, |
| 51 | created_at: col_text(row, 3)?, | 51 | created_at: col_text(row, 3)?, |
| 52 | last_seen_at: col_opt_text(row, 4)?, | 52 | last_seen_at: col_opt_text(row, 4)?, |
| 53 | - stopped_at: col_opt_text(row, 22)?, | 53 | + stopped_at: col_opt_text(row, 19)?, |
| 54 | disabled: col_bool(row, 5)?, | 54 | disabled: col_bool(row, 5)?, |
| 55 | concurrency_override: opt_u32(row, 6)?, | 55 | concurrency_override: opt_u32(row, 6)?, |
| 56 | reported: RunnerReport { | 56 | reported: RunnerReport { |
| @@ -68,9 +68,6 @@ fn map_runner(row: &Row) -> Result<CiRunner> { | |||
| 68 | .collect() | 68 | .collect() |
| 69 | }) | 69 | }) |
| 70 | .unwrap_or_default(), | 70 | .unwrap_or_default(), |
| 71 | - memory_budget: col_opt_int(row, 19)?.and_then(|n| u64::try_from(n).ok()), | ||
| 72 | - memory_free: col_opt_int(row, 20)?.and_then(|n| u64::try_from(n).ok()), | ||
| 73 | - memory_reserve: col_opt_int(row, 21)?.and_then(|n| u64::try_from(n).ok()), | ||
| 74 | }, | 71 | }, |
| 75 | restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { | 72 | restart: match (col_opt_text(row, 16)?, col_opt_text(row, 17)?) { |
| 76 | (Some(mode), Some(requested_at)) => { | 73 | (Some(mode), Some(requested_at)) => { |
| @@ -177,13 +174,6 @@ fn spec_needs(spec: &str) -> Vec<String> { | |||
| 177 | .unwrap_or_default() | 174 | .unwrap_or_default() |
| 178 | } | 175 | } |
| 179 | 176 | ||
| 180 | -fn declared_memory(spec: &str) -> Option<u64> { | ||
| 181 | - serde_json::from_str::<serde_json::Value>(spec) | ||
| 182 | - .ok()? | ||
| 183 | - .get("memory")? | ||
| 184 | - .as_u64() | ||
| 185 | -} | ||
| 186 | - | ||
| 187 | fn runs_on_covered(spec: &str, labels: &[String]) -> bool { | 177 | fn runs_on_covered(spec: &str, labels: &[String]) -> bool { |
| 188 | let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else { | 178 | let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else { |
| 189 | return false; | 179 | return false; |
| @@ -388,12 +378,6 @@ fn recent_done_scope(repo_id: &str, git_refs: &[String]) -> (Vec<Value>, String) | |||
| 388 | (params, scope) | 378 | (params, scope) |
| 389 | } | 379 | } |
| 390 | 380 | ||
| 391 | -fn waited_secs(queued_at: Option<&str>, now: i64) -> u64 { | ||
| 392 | - queued_at | ||
| 393 | - .and_then(stamp_to_unix) | ||
| 394 | - .map_or(0, |at| u64::try_from(now - at).unwrap_or(0)) | ||
| 395 | -} | ||
| 396 | - | ||
| 397 | async fn cancel_open_jobs(conn: &Connection, run_id: &str, now: &str) -> Result<()> { | 381 | async fn cancel_open_jobs(conn: &Connection, run_id: &str, now: &str) -> Result<()> { |
| 398 | conn.execute( | 382 | conn.execute( |
| 399 | "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ | 383 | "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ |
| @@ -818,9 +802,6 @@ impl Store { | |||
| 818 | } else { | 802 | } else { |
| 819 | report.capabilities.clone() | 803 | report.capabilities.clone() |
| 820 | }, | 804 | }, |
| 821 | - memory_budget: report.memory_budget.or(current.reported.memory_budget), | ||
| 822 | - memory_free: report.memory_free.or(current.reported.memory_free), | ||
| 823 | - memory_reserve: report.memory_reserve.or(current.reported.memory_reserve), | ||
| 824 | }; | 805 | }; |
| 825 | if merged == current.reported { | 806 | if merged == current.reported { |
| 826 | return Ok(false); | 807 | return Ok(false); |
| @@ -837,8 +818,7 @@ impl Store { | |||
| 837 | conn.execute( | 818 | conn.execute( |
| 838 | "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ | 819 | "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \ |
| 839 | reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \ | 820 | reported_cpus = ?4, reported_memory_bytes = ?5, reported_build = ?6, \ |
| 840 | - reported_boot_id = ?7, reported_capabilities = ?8, reported_memory_budget = ?9, \ | 821 | + reported_boot_id = ?7, reported_capabilities = ?8 WHERE id = ?1", |
| 841 | - reported_memory_free = ?10, reported_memory_reserve = ?11 WHERE id = ?1", | ||
| 842 | ( | 822 | ( |
| 843 | id.to_string(), | 823 | id.to_string(), |
| 844 | opt_int_value(merged.concurrency.map(i64::from)), | 824 | opt_int_value(merged.concurrency.map(i64::from)), |
| @@ -848,9 +828,6 @@ impl Store { | |||
| 848 | opt_text(merged.build.as_deref()), | 828 | opt_text(merged.build.as_deref()), |
| 849 | opt_text(merged.boot_id.as_deref()), | 829 | opt_text(merged.boot_id.as_deref()), |
| 850 | merged.capabilities.join(","), | 830 | merged.capabilities.join(","), |
| 851 | - opt_int_value(merged.memory_budget.and_then(|n| i64::try_from(n).ok())), | ||
| 852 | - opt_int_value(merged.memory_free.and_then(|n| i64::try_from(n).ok())), | ||
| 853 | - opt_int_value(merged.memory_reserve.and_then(|n| i64::try_from(n).ok())), | ||
| 854 | ), | 831 | ), |
| 855 | ) | 832 | ) |
| 856 | .await | 833 | .await |
| @@ -1009,14 +986,6 @@ impl Store { | |||
| 1009 | } | 986 | } |
| 1010 | 987 | ||
| 1011 | pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> { | 988 | pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> { |
| 1012 | - self.claim_job_fitting(runner, None).await | ||
| 1013 | - } | ||
| 1014 | - | ||
| 1015 | - pub async fn claim_job_fitting( | ||
| 1016 | - &self, | ||
| 1017 | - runner: &CiRunner, | ||
| 1018 | - offer: Option<MemoryOffer>, | ||
| 1019 | - ) -> Result<Option<(CiJob, CiRun, String)>> { | ||
| 1020 | if runner.disabled { | 989 | if runner.disabled { |
| 1021 | return Ok(None); | 990 | return Ok(None); |
| 1022 | } | 991 | } |
| @@ -1034,27 +1003,10 @@ impl Store { | |||
| 1034 | |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_opt_text(row, 2)?)), | 1003 | |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_opt_text(row, 2)?)), |
| 1035 | ) | 1004 | ) |
| 1036 | .await?; | 1005 | .await?; |
| 1037 | - let mut compatible: Vec<(String, String, Option<String>)> = queued | 1006 | + for (job_id, spec, _) in queued { |
| 1038 | - .into_iter() | 1007 | + if !runs_on_covered(&spec, &runner.labels) { |
| 1039 | - .filter(|(_, spec, _)| runs_on_covered(spec, &runner.labels)) | 1008 | + continue; |
| 1040 | - .collect(); | 1009 | + } |
| 1041 | - if let Some(offer) = offer { | ||
| 1042 | - let now = stamp_to_unix(&now).unwrap_or(0); | ||
| 1043 | - let candidates: Vec<(Option<u64>, u64)> = compatible | ||
| 1044 | - .iter() | ||
| 1045 | - .map(|(_, spec, queued_at)| { | ||
| 1046 | - ( | ||
| 1047 | - declared_memory(spec), | ||
| 1048 | - waited_secs(queued_at.as_deref(), now), | ||
| 1049 | - ) | ||
| 1050 | - }) | ||
| 1051 | - .collect(); | ||
| 1052 | - compatible = pick_by_memory(&candidates, &offer, STARVE_AFTER_SECS) | ||
| 1053 | - .map(|i| compatible.swap_remove(i)) | ||
| 1054 | - .into_iter() | ||
| 1055 | - .collect(); | ||
| 1056 | - } | ||
| 1057 | - for (job_id, _spec, _) in compatible { | ||
| 1058 | let won = tx | 1010 | let won = tx |
| 1059 | .execute( | 1011 | .execute( |
| 1060 | "UPDATE ci_jobs SET state = 'running', runner_id = ?2, job_token_hash = ?3, \ | 1012 | "UPDATE ci_jobs SET state = 'running', runner_id = ?2, job_token_hash = ?3, \ |
| @@ -1088,52 +1040,26 @@ impl Store { | |||
| 1088 | Ok(claimed.map(|(job, run)| (job, run, token))) | 1040 | Ok(claimed.map(|(job, run)| (job, run, token))) |
| 1089 | } | 1041 | } |
| 1090 | 1042 | ||
| 1091 | - pub async fn queue_skips( | 1043 | + pub async fn queue_skips(&self, runner: &CiRunner) -> Result<QueueSkips> { |
| 1092 | - &self, | 1044 | + let queued: Vec<String> = { |
| 1093 | - runner: &CiRunner, | ||
| 1094 | - offer: Option<MemoryOffer>, | ||
| 1095 | - ) -> Result<QueueSkips> { | ||
| 1096 | - let queued: Vec<(String, Option<String>)> = { | ||
| 1097 | let conn = self.read_conn().await; | 1045 | let conn = self.read_conn().await; |
| 1098 | fetch_all( | 1046 | fetch_all( |
| 1099 | &conn, | 1047 | &conn, |
| 1100 | - "SELECT spec, queued_at FROM ci_jobs WHERE state = 'queued' ORDER BY queued_at, id", | 1048 | + "SELECT spec FROM ci_jobs WHERE state = 'queued' ORDER BY queued_at, id", |
| 1101 | (), | 1049 | (), |
| 1102 | - |row| Ok((col_text(row, 0)?, col_opt_text(row, 1)?)), | 1050 | + |row| col_text(row, 0), |
| 1103 | ) | 1051 | ) |
| 1104 | .await? | 1052 | .await? |
| 1105 | }; | 1053 | }; |
| 1106 | - let now = stamp_to_unix(&now_stamp()).unwrap_or(0); | ||
| 1107 | let mut skips = QueueSkips { | 1054 | let mut skips = QueueSkips { |
| 1108 | queued: queued.len(), | 1055 | queued: queued.len(), |
| 1109 | ..QueueSkips::default() | 1056 | ..QueueSkips::default() |
| 1110 | }; | 1057 | }; |
| 1111 | let mut missing = BTreeSet::new(); | 1058 | let mut missing = BTreeSet::new(); |
| 1112 | - for (spec, queued_at) in &queued { | 1059 | + for spec in &queued { |
| 1113 | if !runs_on_covered(spec, &runner.labels) { | 1060 | if !runs_on_covered(spec, &runner.labels) { |
| 1114 | skips.lacking_labels += 1; | 1061 | skips.lacking_labels += 1; |
| 1115 | missing.extend(runs_on_missing(spec, &runner.labels)); | 1062 | missing.extend(runs_on_missing(spec, &runner.labels)); |
| 1116 | - continue; | ||
| 1117 | - } | ||
| 1118 | - let Some(offer) = offer else { | ||
| 1119 | - continue; | ||
| 1120 | - }; | ||
| 1121 | - let declared = declared_memory(spec); | ||
| 1122 | - if skips.starved_need.is_some() { | ||
| 1123 | - if offer.fits(declared) { | ||
| 1124 | - skips.held_behind += 1; | ||
| 1125 | - } else { | ||
| 1126 | - skips.too_big += 1; | ||
| 1127 | - } | ||
| 1128 | - continue; | ||
| 1129 | - } | ||
| 1130 | - if !offer.fits(declared) { | ||
| 1131 | - let need = offer.reservation(declared); | ||
| 1132 | - skips.too_big += 1; | ||
| 1133 | - skips.smallest_need = Some(skips.smallest_need.map_or(need, |n| n.min(need))); | ||
| 1134 | - if waited_secs(queued_at.as_deref(), now) >= STARVE_AFTER_SECS { | ||
| 1135 | - skips.starved_need = Some(need); | ||
| 1136 | - } | ||
| 1137 | } | 1063 | } |
| 1138 | } | 1064 | } |
| 1139 | skips.missing_labels = missing.into_iter().collect(); | 1065 | skips.missing_labels = missing.into_iter().collect(); |
| @@ -2368,7 +2294,7 @@ mod tests { | |||
| 2368 | let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; | 2294 | let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await; |
| 2369 | let reported: BTreeMap<String, serde_json::Value> = [ | 2295 | let reported: BTreeMap<String, serde_json::Value> = [ |
| 2370 | ("labels".to_owned(), serde_json::json!(["linux"])), | 2296 | ("labels".to_owned(), serde_json::json!(["linux"])), |
| 2371 | - ("limits.memory".to_owned(), serde_json::json!("4g")), | 2297 | + ("limits.pids".to_owned(), serde_json::json!("4")), |
| 2372 | ] | 2298 | ] |
| 2373 | .into(); | 2299 | .into(); |
| 2374 | assert!( | 2300 | assert!( |
| @@ -2385,11 +2311,11 @@ mod tests { | |||
| 2385 | ); | 2311 | ); |
| 2386 | 2312 | ||
| 2387 | fx.store | 2313 | fx.store |
| 2388 | - .set_runner_field(&runner.id, "limits.memory", Some("8g")) | 2314 | + .set_runner_field(&runner.id, "limits.pids", Some("8")) |
| 2389 | .await | 2315 | .await |
| 2390 | .unwrap(); | 2316 | .unwrap(); |
| 2391 | for (key, bad) in [ | 2317 | for (key, bad) in [ |
| 2392 | - ("limits.memory", "lots"), | 2318 | + ("limits.memory", "4g"), |
| 2393 | ("limits.pids", "0"), | 2319 | ("limits.pids", "0"), |
| 2394 | ("executor", "docker"), | 2320 | ("executor", "docker"), |
| 2395 | ("work_dir", "relative/path"), | 2321 | ("work_dir", "relative/path"), |
| @@ -2406,8 +2332,8 @@ mod tests { | |||
| 2406 | ); | 2332 | ); |
| 2407 | } | 2333 | } |
| 2408 | let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap(); | 2334 | let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap(); |
| 2409 | - assert_eq!(found.config_overrides["limits.memory"], "8g"); | 2335 | + assert_eq!(found.config_overrides["limits.pids"], 8); |
| 2410 | - assert_eq!(found.reported_config["limits.memory"], "4g"); | 2336 | + assert_eq!(found.reported_config["limits.pids"], "4"); |
| 2411 | 2337 | ||
| 2412 | fx.store | 2338 | fx.store |
| 2413 | .set_runner_field(&runner.id, "labels", Some("linux, arm")) | 2339 | .set_runner_field(&runner.id, "labels", Some("linux, arm")) |
| @@ -2420,7 +2346,7 @@ mod tests { | |||
| 2420 | .await | 2346 | .await |
| 2421 | .unwrap(); | 2347 | .unwrap(); |
| 2422 | fx.store | 2348 | fx.store |
| 2423 | - .set_runner_field(&runner.id, "limits.memory", None) | 2349 | + .set_runner_field(&runner.id, "limits.pids", None) |
| 2424 | .await | 2350 | .await |
| 2425 | .unwrap(); | 2351 | .unwrap(); |
| 2426 | let after = fx.store.list_runners().await.unwrap().remove(0); | 2352 | let after = fx.store.list_runners().await.unwrap().remove(0); |
| @@ -2551,11 +2477,7 @@ mod tests { | |||
| 2551 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), | 2477 | build: Some("0.1.0 (cf8e648, 2026-10-20)".into()), |
| 2552 | boot_id: Some("boot-1".into()), | 2478 | boot_id: Some("boot-1".into()), |
| 2553 | capabilities: vec!["restart".into()], | 2479 | capabilities: vec!["restart".into()], |
| 2554 | - memory_budget: Some(6 << 30), | ||
| 2555 | - memory_free: Some(2 << 30), | ||
| 2556 | - memory_reserve: Some(1 << 30), | ||
| 2557 | }; | 2480 | }; |
| 2558 | - assert_eq!(full.memory_reserved(), Some(4 << 30)); | ||
| 2559 | assert!( | 2481 | assert!( |
| 2560 | fx.store | 2482 | fx.store |
| 2561 | .record_runner_report(&runner.id, &full) | 2483 | .record_runner_report(&runner.id, &full) |
| @@ -2803,193 +2725,6 @@ mod tests { | |||
| 2803 | )); | 2725 | )); |
| 2804 | } | 2726 | } |
| 2805 | 2727 | ||
| 2806 | - async fn create_ordered( | ||
| 2807 | - store: &Store, | ||
| 2808 | - repo_id: &str, | ||
| 2809 | - actor: &str, | ||
| 2810 | - jobs: &[Job], | ||
| 2811 | - approval: bool, | ||
| 2812 | - ) -> CiRun { | ||
| 2813 | - let run = create(store, repo_id, actor, jobs, approval).await; | ||
| 2814 | - let conn = store.inner.conn.lock().await; | ||
| 2815 | - for (i, j) in jobs.iter().enumerate() { | ||
| 2816 | - let at = crate::time::stamp_ago(Duration::from_secs(10 - i as u64)); | ||
| 2817 | - conn.execute( | ||
| 2818 | - "UPDATE ci_jobs SET queued_at = ?1 WHERE name = ?2", | ||
| 2819 | - (at, j.name.clone()), | ||
| 2820 | - ) | ||
| 2821 | - .await | ||
| 2822 | - .unwrap(); | ||
| 2823 | - } | ||
| 2824 | - run | ||
| 2825 | - } | ||
| 2826 | - | ||
| 2827 | - fn mem_job(name: &str, memory: Option<u64>) -> Job { | ||
| 2828 | - let mut spec = serde_json::json!({ | ||
| 2829 | - "image": "alpine", "run": "true", "needs": [], "runs_on": [], | ||
| 2830 | - }); | ||
| 2831 | - if let Some(bytes) = memory { | ||
| 2832 | - spec["memory"] = bytes.into(); | ||
| 2833 | - } | ||
| 2834 | - Job { | ||
| 2835 | - name: name.to_string(), | ||
| 2836 | - spec: spec.to_string(), | ||
| 2837 | - needs: Vec::new(), | ||
| 2838 | - } | ||
| 2839 | - } | ||
| 2840 | - | ||
| 2841 | - fn offer(free_gib: u64) -> Option<MemoryOffer> { | ||
| 2842 | - Some(MemoryOffer { | ||
| 2843 | - free: free_gib << 30, | ||
| 2844 | - budget: Some(6 << 30), | ||
| 2845 | - default_reserve: 1 << 30, | ||
| 2846 | - }) | ||
| 2847 | - } | ||
| 2848 | - | ||
| 2849 | - #[tokio::test] | ||
| 2850 | - async fn claim_picks_the_first_job_that_fits_the_free_memory() { | ||
| 2851 | - let fx = fixture().await; | ||
| 2852 | - create_ordered( | ||
| 2853 | - &fx.store, | ||
| 2854 | - &fx.repo.id, | ||
| 2855 | - &fx.tahinli.id, | ||
| 2856 | - &[ | ||
| 2857 | - mem_job("big", Some(4 << 30)), | ||
| 2858 | - mem_job("small", Some(1 << 30)), | ||
| 2859 | - mem_job("plain", None), | ||
| 2860 | - ], | ||
| 2861 | - false, | ||
| 2862 | - ) | ||
| 2863 | - .await; | ||
| 2864 | - let runner = bare_runner(&["linux"]); | ||
| 2865 | - let first = fx | ||
| 2866 | - .store | ||
| 2867 | - .claim_job_fitting(&runner, offer(2)) | ||
| 2868 | - .await | ||
| 2869 | - .unwrap() | ||
| 2870 | - .unwrap(); | ||
| 2871 | - assert_eq!(first.0.name, "small"); | ||
| 2872 | - let second = fx | ||
| 2873 | - .store | ||
| 2874 | - .claim_job_fitting(&runner, offer(1)) | ||
| 2875 | - .await | ||
| 2876 | - .unwrap() | ||
| 2877 | - .unwrap(); | ||
| 2878 | - assert_eq!(second.0.name, "plain"); | ||
| 2879 | - assert!( | ||
| 2880 | - fx.store | ||
| 2881 | - .claim_job_fitting(&runner, offer(0)) | ||
| 2882 | - .await | ||
| 2883 | - .unwrap() | ||
| 2884 | - .is_none() | ||
| 2885 | - ); | ||
| 2886 | - let big = fx | ||
| 2887 | - .store | ||
| 2888 | - .claim_job_fitting(&runner, offer(6)) | ||
| 2889 | - .await | ||
| 2890 | - .unwrap() | ||
| 2891 | - .unwrap(); | ||
| 2892 | - assert_eq!(big.0.name, "big"); | ||
| 2893 | - } | ||
| 2894 | - | ||
| 2895 | - #[tokio::test] | ||
| 2896 | - async fn a_runner_without_an_offer_gets_the_oldest_job_as_before() { | ||
| 2897 | - let fx = fixture().await; | ||
| 2898 | - create_ordered( | ||
| 2899 | - &fx.store, | ||
| 2900 | - &fx.repo.id, | ||
| 2901 | - &fx.tahinli.id, | ||
| 2902 | - &[mem_job("big", Some(64 << 30)), mem_job("small", None)], | ||
| 2903 | - false, | ||
| 2904 | - ) | ||
| 2905 | - .await; | ||
| 2906 | - let claimed = fx | ||
| 2907 | - .store | ||
| 2908 | - .claim_job(&bare_runner(&["linux"])) | ||
| 2909 | - .await | ||
| 2910 | - .unwrap() | ||
| 2911 | - .unwrap(); | ||
| 2912 | - assert_eq!(claimed.0.name, "big"); | ||
| 2913 | - } | ||
| 2914 | - | ||
| 2915 | - #[tokio::test] | ||
| 2916 | - async fn a_job_bigger_than_the_budget_runs_when_the_runner_is_idle() { | ||
| 2917 | - let fx = fixture().await; | ||
| 2918 | - create_ordered( | ||
| 2919 | - &fx.store, | ||
| 2920 | - &fx.repo.id, | ||
| 2921 | - &fx.tahinli.id, | ||
| 2922 | - &[mem_job("huge", Some(64 << 30))], | ||
| 2923 | - false, | ||
| 2924 | - ) | ||
| 2925 | - .await; | ||
| 2926 | - let runner = bare_runner(&["linux"]); | ||
| 2927 | - assert!( | ||
| 2928 | - fx.store | ||
| 2929 | - .claim_job_fitting(&runner, offer(3)) | ||
| 2930 | - .await | ||
| 2931 | - .unwrap() | ||
| 2932 | - .is_none(), | ||
| 2933 | - "not while something else holds memory" | ||
| 2934 | - ); | ||
| 2935 | - let claimed = fx | ||
| 2936 | - .store | ||
| 2937 | - .claim_job_fitting(&runner, offer(6)) | ||
| 2938 | - .await | ||
| 2939 | - .unwrap() | ||
| 2940 | - .unwrap(); | ||
| 2941 | - assert_eq!(claimed.0.name, "huge"); | ||
| 2942 | - } | ||
| 2943 | - | ||
| 2944 | - #[tokio::test] | ||
| 2945 | - async fn a_job_that_waited_too_long_stops_smaller_jobs_passing_it() { | ||
| 2946 | - let fx = fixture().await; | ||
| 2947 | - create_ordered( | ||
| 2948 | - &fx.store, | ||
| 2949 | - &fx.repo.id, | ||
| 2950 | - &fx.tahinli.id, | ||
| 2951 | - &[ | ||
| 2952 | - mem_job("big", Some(4 << 30)), | ||
| 2953 | - mem_job("small", Some(1 << 30)), | ||
| 2954 | - ], | ||
| 2955 | - false, | ||
| 2956 | - ) | ||
| 2957 | - .await; | ||
| 2958 | - let old = crate::time::stamp_ago(Duration::from_secs(STARVE_AFTER_SECS + 60)); | ||
| 2959 | - { | ||
| 2960 | - let conn = fx.store.inner.conn.lock().await; | ||
| 2961 | - conn.execute( | ||
| 2962 | - "UPDATE ci_jobs SET queued_at = ?1 WHERE name = 'big'", | ||
| 2963 | - (old,), | ||
| 2964 | - ) | ||
| 2965 | - .await | ||
| 2966 | - .unwrap(); | ||
| 2967 | - } | ||
| 2968 | - let runner = bare_runner(&["linux"]); | ||
| 2969 | - assert!( | ||
| 2970 | - fx.store | ||
| 2971 | - .claim_job_fitting(&runner, offer(2)) | ||
| 2972 | - .await | ||
| 2973 | - .unwrap() | ||
| 2974 | - .is_none(), | ||
| 2975 | - "the old big job holds the line" | ||
| 2976 | - ); | ||
| 2977 | - let claimed = fx | ||
| 2978 | - .store | ||
| 2979 | - .claim_job_fitting(&runner, offer(5)) | ||
| 2980 | - .await | ||
| 2981 | - .unwrap() | ||
| 2982 | - .unwrap(); | ||
| 2983 | - assert_eq!(claimed.0.name, "big"); | ||
| 2984 | - let next = fx | ||
| 2985 | - .store | ||
| 2986 | - .claim_job_fitting(&runner, offer(2)) | ||
| 2987 | - .await | ||
| 2988 | - .unwrap() | ||
| 2989 | - .unwrap(); | ||
| 2990 | - assert_eq!(next.0.name, "small"); | ||
| 2991 | - } | ||
| 2992 | - | ||
| 2993 | #[tokio::test] | 2728 | #[tokio::test] |
| 2994 | async fn requeue_hands_a_running_job_back_with_its_place() { | 2729 | async fn requeue_hands_a_running_job_back_with_its_place() { |
| 2995 | let fx = fixture().await; | 2730 | let fx = fixture().await; |
| @@ -3016,12 +2751,7 @@ mod tests { | |||
| 3016 | assert_eq!(run.state, RunState::Running); | 2751 | assert_eq!(run.state, RunState::Running); |
| 3017 | assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); | 2752 | assert!(!fx.store.requeue_job(&claimed.id).await.unwrap()); |
| 3018 | assert!(!fx.store.requeue_job("missing").await.unwrap()); | 2753 | assert!(!fx.store.requeue_job("missing").await.unwrap()); |
| 3019 | - let (again, _, token) = fx | 2754 | + let (again, _, token) = fx.store.claim_job(&runner).await.unwrap().unwrap(); |
| 3020 | - .store | ||
| 3021 | - .claim_job_fitting(&runner, None) | ||
| 3022 | - .await | ||
| 3023 | - .unwrap() | ||
| 3024 | - .unwrap(); | ||
| 3025 | assert_eq!(again.id, claimed.id); | 2755 | assert_eq!(again.id, claimed.id); |
| 3026 | assert!( | 2756 | assert!( |
| 3027 | fx.store | 2757 | fx.store |
crates/forge-runner/src/cache.rsmodified+0 -1
| @@ -791,7 +791,6 @@ mod tests { | |||
| 791 | cache: cache.iter().map(|s| (*s).to_owned()).collect(), | 791 | cache: cache.iter().map(|s| (*s).to_owned()).collect(), |
| 792 | cache_key: key.to_owned(), | 792 | cache_key: key.to_owned(), |
| 793 | cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), | 793 | cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), |
| 794 | - memory_bytes: None, | ||
| 795 | } | 794 | } |
| 796 | } | 795 | } |
| 797 | 796 | ||
crates/forge-runner/src/cli.rsmodified+6 -14
| @@ -16,7 +16,6 @@ use crate::client::ForgeClient; | |||
| 16 | use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; | 16 | use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; |
| 17 | use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; | 17 | use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; |
| 18 | use crate::oci::ImageStore; | 18 | use crate::oci::ImageStore; |
| 19 | -use crate::pressure::Pressure; | ||
| 20 | use crate::runner::{RunEnd, RunOptions, Runner}; | 19 | use crate::runner::{RunEnd, RunOptions, Runner}; |
| 21 | use crate::sandbox::idmap::IdMap; | 20 | use crate::sandbox::idmap::IdMap; |
| 22 | use crate::selflog; | 21 | use crate::selflog; |
| @@ -207,17 +206,11 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 207 | let mut cfg = config::load(&path)?; | 206 | let mut cfg = config::load(&path)?; |
| 208 | sync_config_with_forge(&mut cfg).await; | 207 | sync_config_with_forge(&mut cfg).await; |
| 209 | let shutdown = CancellationToken::new(); | 208 | let shutdown = CancellationToken::new(); |
| 210 | - let pressure = match cfg.executor { | 209 | + if let ExecutorKind::Builtin = cfg.executor |
| 211 | - ExecutorKind::Builtin => { | 210 | + && let Err(e) = crate::pressure::start_box(crate::memory::box_size(&cfg.limits)) |
| 212 | - let budget = crate::memory::MemoryGate::for_host(&cfg.limits).ram_budget(); | 211 | + { |
| 213 | - let pressure = Pressure::start(budget, shutdown.clone()).await; | 212 | + tracing::warn!("no memory box, builtin jobs run without one: {e}"); |
| 214 | - if let Some(p) = &pressure { | 213 | + } |
| 215 | - cfg.limits.memory = p.budget().to_string(); | ||
| 216 | - } | ||
| 217 | - pressure | ||
| 218 | - } | ||
| 219 | - ExecutorKind::Podman => None, | ||
| 220 | - }; | ||
| 221 | let cache_root = cfg.work_dir.join(".cache"); | 214 | let cache_root = cfg.work_dir.join(".cache"); |
| 222 | let cache_cap = cfg.cache_max_gib; | 215 | let cache_cap = cfg.cache_max_gib; |
| 223 | let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor { | 216 | let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor { |
| @@ -251,8 +244,7 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 251 | }; | 244 | }; |
| 252 | let stop_url = cfg.url.clone(); | 245 | let stop_url = cfg.url.clone(); |
| 253 | let stop_secret = cfg.runner_secret.clone(); | 246 | let stop_secret = cfg.runner_secret.clone(); |
| 254 | - let mut runner = | 247 | + let mut runner = Runner::new(cfg, executor, RunOptions::default())?; |
| 255 | - Runner::new(cfg, executor, RunOptions::default())?.with_pressure(pressure); | ||
| 256 | if cache_cap > 0 { | 248 | if cache_cap > 0 { |
| 257 | let cache = | 249 | let cache = |
| 258 | CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); | 250 | CacheStore::new(cache_root, gib(cache_cap), map, std::env::current_exe()?); |
crates/forge-runner/src/client.rsmodified+9 -53
| @@ -2,11 +2,10 @@ use std::path::Path; | |||
| 2 | use std::time::Duration; | 2 | use std::time::Duration; |
| 3 | 3 | ||
| 4 | use forge_ci::proto::{ | 4 | use forge_ci::proto::{ |
| 5 | - BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CAP_RUNNER_LOG, CAP_RUNNER_METRICS, CONCURRENCY_HEADER, | 5 | + BUILD_HEADER, CAP_RESTART, CAP_RUNNER_LOG, CAP_RUNNER_METRICS, CONCURRENCY_HEADER, |
| 6 | - ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, | 6 | + ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, RESTART_HEADER, RegisterRequest, |
| 7 | - RESERVE_MEMORY_HEADER, RESTART_HEADER, RegisterRequest, RegisterResponse, RequeueRequest, | 7 | + RegisterResponse, RestartMode, RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, |
| 8 | - RestartMode, RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, | 8 | + RunnerLogBatch, RunnerMetricsBatch, |
| 9 | - RunnerMetricsBatch, | ||
| 10 | }; | 9 | }; |
| 11 | use reqwest::StatusCode; | 10 | use reqwest::StatusCode; |
| 12 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; | 11 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; |
| @@ -52,15 +51,6 @@ pub struct ClaimReply { | |||
| 52 | pub binary_sha256: Option<String>, | 51 | pub binary_sha256: Option<String>, |
| 53 | pub concurrency: Option<u32>, | 52 | pub concurrency: Option<u32>, |
| 54 | pub restart: Option<RestartMode>, | 53 | pub restart: Option<RestartMode>, |
| 55 | - pub memory_budget: Option<String>, | ||
| 56 | - pub reserve_memory: Option<String>, | ||
| 57 | -} | ||
| 58 | - | ||
| 59 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 60 | -pub struct MemoryClaim { | ||
| 61 | - pub free: u64, | ||
| 62 | - pub budget: u64, | ||
| 63 | - pub reserve: u64, | ||
| 64 | } | 54 | } |
| 65 | 55 | ||
| 66 | #[derive(Clone, Debug)] | 56 | #[derive(Clone, Debug)] |
| @@ -101,7 +91,7 @@ impl ForgeClient { | |||
| 101 | runner_secret: &str, | 91 | runner_secret: &str, |
| 102 | labels: &[String], | 92 | labels: &[String], |
| 103 | ) -> Result<ClaimReply, ClientError> { | 93 | ) -> Result<ClaimReply, ClientError> { |
| 104 | - self.claim_with(runner_secret, labels, None, None).await | 94 | + self.claim_with(runner_secret, labels, None).await |
| 105 | } | 95 | } |
| 106 | 96 | ||
| 107 | pub async fn claim_with( | 97 | pub async fn claim_with( |
| @@ -109,7 +99,6 @@ impl ForgeClient { | |||
| 109 | runner_secret: &str, | 99 | runner_secret: &str, |
| 110 | labels: &[String], | 100 | labels: &[String], |
| 111 | concurrency: Option<usize>, | 101 | concurrency: Option<usize>, |
| 112 | - memory: Option<MemoryClaim>, | ||
| 113 | ) -> Result<ClaimReply, ClientError> { | 102 | ) -> Result<ClaimReply, ClientError> { |
| 114 | let host = host_facts(); | 103 | let host = host_facts(); |
| 115 | let req = ClaimRequest { | 104 | let req = ClaimRequest { |
| @@ -122,13 +111,9 @@ impl ForgeClient { | |||
| 122 | boot_id: Some(crate::restart::boot_id().to_owned()), | 111 | boot_id: Some(crate::restart::boot_id().to_owned()), |
| 123 | capabilities: vec![ | 112 | capabilities: vec![ |
| 124 | CAP_RESTART.to_owned(), | 113 | CAP_RESTART.to_owned(), |
| 125 | - CAP_REQUEUE.to_owned(), | ||
| 126 | CAP_RUNNER_LOG.to_owned(), | 114 | CAP_RUNNER_LOG.to_owned(), |
| 127 | CAP_RUNNER_METRICS.to_owned(), | 115 | CAP_RUNNER_METRICS.to_owned(), |
| 128 | ], | 116 | ], |
| 129 | - free_memory_bytes: memory.map(|m| m.free), | ||
| 130 | - memory_budget_bytes: memory.map(|m| m.budget), | ||
| 131 | - reserve_memory_bytes: memory.map(|m| m.reserve), | ||
| 132 | }; | 117 | }; |
| 133 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); | 118 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); |
| 134 | let resp = self | 119 | let resp = self |
| @@ -146,8 +131,6 @@ impl ForgeClient { | |||
| 146 | binary_sha256, | 131 | binary_sha256, |
| 147 | concurrency: advertised_concurrency(resp.headers()), | 132 | concurrency: advertised_concurrency(resp.headers()), |
| 148 | restart: advertised_restart(resp.headers()), | 133 | restart: advertised_restart(resp.headers()), |
| 149 | - memory_budget: header_text(resp.headers(), MEMORY_BUDGET_HEADER), | ||
| 150 | - reserve_memory: header_text(resp.headers(), RESERVE_MEMORY_HEADER), | ||
| 151 | }; | 134 | }; |
| 152 | match resp.status() { | 135 | match resp.status() { |
| 153 | StatusCode::NO_CONTENT => Ok(reply), | 136 | StatusCode::NO_CONTENT => Ok(reply), |
| @@ -366,25 +349,6 @@ impl ForgeClient { | |||
| 366 | .await?; | 349 | .await?; |
| 367 | empty_or_error(resp).await | 350 | empty_or_error(resp).await |
| 368 | } | 351 | } |
| 369 | - | ||
| 370 | - pub async fn requeue( | ||
| 371 | - &self, | ||
| 372 | - job_id: &str, | ||
| 373 | - job_token: &str, | ||
| 374 | - reason: &str, | ||
| 375 | - ) -> Result<(), ClientError> { | ||
| 376 | - let resp = self | ||
| 377 | - .http | ||
| 378 | - .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/requeue"))) | ||
| 379 | - .bearer_auth(job_token) | ||
| 380 | - .json(&RequeueRequest { | ||
| 381 | - reason: reason.to_owned(), | ||
| 382 | - }) | ||
| 383 | - .timeout(REQUEST_TIMEOUT) | ||
| 384 | - .send() | ||
| 385 | - .await?; | ||
| 386 | - empty_or_error(resp).await | ||
| 387 | - } | ||
| 388 | } | 352 | } |
| 389 | 353 | ||
| 390 | fn advertised_sha256(headers: &HeaderMap) -> Option<String> { | 354 | fn advertised_sha256(headers: &HeaderMap) -> Option<String> { |
| @@ -415,22 +379,14 @@ struct HostFacts { | |||
| 415 | memory_bytes: Option<u64>, | 379 | memory_bytes: Option<u64>, |
| 416 | } | 380 | } |
| 417 | 381 | ||
| 418 | -fn header_text(headers: &HeaderMap, name: &str) -> Option<String> { | ||
| 419 | - headers | ||
| 420 | - .get(name) | ||
| 421 | - .and_then(|v| v.to_str().ok()) | ||
| 422 | - .map(|v| v.trim().to_owned()) | ||
| 423 | - .filter(|v| !v.is_empty() && v.len() <= 32) | ||
| 424 | -} | ||
| 425 | - | ||
| 426 | fn host_facts() -> HostFacts { | 382 | fn host_facts() -> HostFacts { |
| 427 | let cpus = std::thread::available_parallelism() | 383 | let cpus = std::thread::available_parallelism() |
| 428 | .ok() | 384 | .ok() |
| 429 | .and_then(|n| u32::try_from(n.get()).ok()); | 385 | .and_then(|n| u32::try_from(n.get()).ok()); |
| 430 | - let memory_bytes = std::fs::read_to_string("/proc/meminfo") | 386 | + HostFacts { |
| 431 | - .ok() | 387 | + cpus, |
| 432 | - .and_then(|text| crate::memory::meminfo(&text).total); | 388 | + memory_bytes: crate::memory::host_total(), |
| 433 | - HostFacts { cpus, memory_bytes } | 389 | + } |
| 434 | } | 390 | } |
| 435 | 391 | ||
| 436 | async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> { | 392 | async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> { |
crates/forge-runner/src/config.rsmodified+32 -165
| @@ -30,28 +30,22 @@ pub enum ConfigError { | |||
| 30 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | 30 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 31 | #[serde(deny_unknown_fields)] | 31 | #[serde(deny_unknown_fields)] |
| 32 | pub struct Limits { | 32 | pub struct Limits { |
| 33 | - pub memory: String, | ||
| 34 | pub cpus: String, | 33 | pub cpus: String, |
| 35 | pub pids: u32, | 34 | pub pids: u32, |
| 36 | #[serde(default = "default_image_max_gb")] | 35 | #[serde(default = "default_image_max_gb")] |
| 37 | pub image_max_gb: u64, | 36 | pub image_max_gb: u64, |
| 38 | #[serde(default = "default_job_disk_gb")] | 37 | #[serde(default = "default_job_disk_gb")] |
| 39 | pub job_disk_gb: u64, | 38 | pub job_disk_gb: u64, |
| 40 | - #[serde(default = "default_reserve_memory")] | ||
| 41 | - pub reserve_memory: String, | ||
| 42 | - #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 43 | - pub memory_budget: Option<String>, | ||
| 44 | #[serde(default = "default_memory_headroom")] | 39 | #[serde(default = "default_memory_headroom")] |
| 45 | pub memory_headroom: String, | 40 | pub memory_headroom: String, |
| 46 | - #[serde(default)] | ||
| 47 | - pub budget_swap_percent: u32, | ||
| 48 | - #[serde(skip)] | ||
| 49 | - pub swap: u64, | ||
| 50 | } | 41 | } |
| 51 | 42 | ||
| 52 | -fn default_reserve_memory() -> String { | 43 | +const RETIRED_LIMITS: [&str; 4] = [ |
| 53 | - "1g".to_owned() | 44 | + "memory", |
| 54 | -} | 45 | + "reserve_memory", |
| 46 | + "memory_budget", | ||
| 47 | + "budget_swap_percent", | ||
| 48 | +]; | ||
| 55 | 49 | ||
| 56 | fn default_memory_headroom() -> String { | 50 | fn default_memory_headroom() -> String { |
| 57 | "1g".to_owned() | 51 | "1g".to_owned() |
| @@ -60,58 +54,13 @@ fn default_memory_headroom() -> String { | |||
| 60 | impl Default for Limits { | 54 | impl Default for Limits { |
| 61 | fn default() -> Self { | 55 | fn default() -> Self { |
| 62 | Self { | 56 | Self { |
| 63 | - memory: "4g".to_owned(), | ||
| 64 | cpus: "2".to_owned(), | 57 | cpus: "2".to_owned(), |
| 65 | pids: 4096, | 58 | pids: 4096, |
| 66 | image_max_gb: default_image_max_gb(), | 59 | image_max_gb: default_image_max_gb(), |
| 67 | job_disk_gb: default_job_disk_gb(), | 60 | job_disk_gb: default_job_disk_gb(), |
| 68 | - reserve_memory: default_reserve_memory(), | ||
| 69 | - memory_budget: None, | ||
| 70 | memory_headroom: default_memory_headroom(), | 61 | memory_headroom: default_memory_headroom(), |
| 71 | - budget_swap_percent: 0, | ||
| 72 | - swap: 0, | ||
| 73 | - } | ||
| 74 | - } | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -impl Limits { | ||
| 78 | - pub fn for_job(&self, declared: Option<u64>) -> Limits { | ||
| 79 | - let mut limits = self.clone(); | ||
| 80 | - let configured = forge_ci::size::parse_size(&self.memory); | ||
| 81 | - match self.job_memory_limit(declared) { | ||
| 82 | - Some(bytes) if declared.is_some() || Some(bytes) != configured => { | ||
| 83 | - limits.memory = bytes.to_string(); | ||
| 84 | - } | ||
| 85 | - _ => {} | ||
| 86 | } | 62 | } |
| 87 | - limits | ||
| 88 | } | 63 | } |
| 89 | - | ||
| 90 | - pub fn for_builtin_job(&self, declared: Option<u64>, budget: Option<u64>, swap: u64) -> Limits { | ||
| 91 | - match (declared, budget) { | ||
| 92 | - (None, Some(budget)) => { | ||
| 93 | - let reserve = forge_ci::size::parse_size(&self.reserve_memory).unwrap_or(0); | ||
| 94 | - let mut limits = self.clone(); | ||
| 95 | - limits.memory = budget.max(reserve).max(1).to_string(); | ||
| 96 | - limits.swap = swap; | ||
| 97 | - limits | ||
| 98 | - } | ||
| 99 | - _ => self.for_job(declared), | ||
| 100 | - } | ||
| 101 | - } | ||
| 102 | - | ||
| 103 | - pub fn job_memory_limit(&self, declared: Option<u64>) -> Option<u64> { | ||
| 104 | - if let Some(declared) = declared { | ||
| 105 | - return Some(declared.saturating_add(memory_slack(declared))); | ||
| 106 | - } | ||
| 107 | - let memory = forge_ci::size::parse_size(&self.memory)?; | ||
| 108 | - let reserve = forge_ci::size::parse_size(&self.reserve_memory).unwrap_or(0); | ||
| 109 | - Some(memory.max(reserve)) | ||
| 110 | - } | ||
| 111 | -} | ||
| 112 | - | ||
| 113 | -pub fn memory_slack(declared: u64) -> u64 { | ||
| 114 | - (declared / 16).max(256 << 20) | ||
| 115 | } | 64 | } |
| 116 | 65 | ||
| 117 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] | 66 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -283,23 +232,10 @@ impl RunnerConfig { | |||
| 283 | json!(self.work_dir.display().to_string()), | 232 | json!(self.work_dir.display().to_string()), |
| 284 | ); | 233 | ); |
| 285 | m.insert("concurrency".into(), json!(self.concurrency)); | 234 | m.insert("concurrency".into(), json!(self.concurrency)); |
| 286 | - m.insert("limits.memory".into(), json!(self.limits.memory)); | ||
| 287 | - m.insert( | ||
| 288 | - "limits.reserve_memory".into(), | ||
| 289 | - json!(self.limits.reserve_memory), | ||
| 290 | - ); | ||
| 291 | - m.insert( | ||
| 292 | - "limits.memory_budget".into(), | ||
| 293 | - json!(self.limits.memory_budget.as_deref().unwrap_or("auto")), | ||
| 294 | - ); | ||
| 295 | m.insert( | 235 | m.insert( |
| 296 | "limits.memory_headroom".into(), | 236 | "limits.memory_headroom".into(), |
| 297 | json!(self.limits.memory_headroom), | 237 | json!(self.limits.memory_headroom), |
| 298 | ); | 238 | ); |
| 299 | - m.insert( | ||
| 300 | - "limits.budget_swap_percent".into(), | ||
| 301 | - json!(self.limits.budget_swap_percent), | ||
| 302 | - ); | ||
| 303 | m.insert("limits.cpus".into(), json!(self.limits.cpus)); | 239 | m.insert("limits.cpus".into(), json!(self.limits.cpus)); |
| 304 | m.insert("limits.pids".into(), json!(self.limits.pids)); | 240 | m.insert("limits.pids".into(), json!(self.limits.pids)); |
| 305 | m.insert( | 241 | m.insert( |
| @@ -334,33 +270,11 @@ impl RunnerConfig { | |||
| 334 | .as_str() | 270 | .as_str() |
| 335 | .map(|v| self.work_dir = PathBuf::from(v)) | 271 | .map(|v| self.work_dir = PathBuf::from(v)) |
| 336 | .is_some(), | 272 | .is_some(), |
| 337 | - "limits.memory" => value | ||
| 338 | - .as_str() | ||
| 339 | - .map(|v| self.limits.memory = v.to_owned()) | ||
| 340 | - .is_some(), | ||
| 341 | - "limits.reserve_memory" => value | ||
| 342 | - .as_str() | ||
| 343 | - .filter(|v| forge_ci::size::parse_size(v).is_some()) | ||
| 344 | - .map(|v| self.limits.reserve_memory = v.to_owned()) | ||
| 345 | - .is_some(), | ||
| 346 | - "limits.memory_budget" => value | ||
| 347 | - .as_str() | ||
| 348 | - .filter(|v| *v == "auto" || forge_ci::size::parse_size(v).is_some()) | ||
| 349 | - .map(|v| { | ||
| 350 | - self.limits.memory_budget = (v != "auto").then(|| v.to_owned()); | ||
| 351 | - }) | ||
| 352 | - .is_some(), | ||
| 353 | "limits.memory_headroom" => value | 273 | "limits.memory_headroom" => value |
| 354 | .as_str() | 274 | .as_str() |
| 355 | .filter(|v| forge_ci::size::parse_size(v).is_some()) | 275 | .filter(|v| forge_ci::size::parse_size(v).is_some()) |
| 356 | .map(|v| self.limits.memory_headroom = v.to_owned()) | 276 | .map(|v| self.limits.memory_headroom = v.to_owned()) |
| 357 | .is_some(), | 277 | .is_some(), |
| 358 | - "limits.budget_swap_percent" => value | ||
| 359 | - .as_u64() | ||
| 360 | - .and_then(|v| u32::try_from(v).ok()) | ||
| 361 | - .filter(|v| *v <= 100) | ||
| 362 | - .map(|v| self.limits.budget_swap_percent = v) | ||
| 363 | - .is_some(), | ||
| 364 | "limits.cpus" => value | 278 | "limits.cpus" => value |
| 365 | .as_str() | 279 | .as_str() |
| 366 | .map(|v| self.limits.cpus = v.to_owned()) | 280 | .map(|v| self.limits.cpus = v.to_owned()) |
| @@ -433,7 +347,15 @@ pub fn load(path: &Path) -> Result<RunnerConfig, ConfigError> { | |||
| 433 | path: path.to_owned(), | 347 | path: path.to_owned(), |
| 434 | source, | 348 | source, |
| 435 | })?; | 349 | })?; |
| 436 | - let config: RunnerConfig = toml::from_str(&text)?; | 350 | + let mut doc: toml::Value = toml::from_str(&text)?; |
| 351 | + if let Some(limits) = doc.get_mut("limits").and_then(toml::Value::as_table_mut) { | ||
| 352 | + for key in RETIRED_LIMITS { | ||
| 353 | + if limits.remove(key).is_some() { | ||
| 354 | + tracing::warn!("runner.toml: [limits] {key} is no longer used, ignoring it"); | ||
| 355 | + } | ||
| 356 | + } | ||
| 357 | + } | ||
| 358 | + let config: RunnerConfig = doc.try_into()?; | ||
| 437 | config.validate()?; | 359 | config.validate()?; |
| 438 | Ok(config) | 360 | Ok(config) |
| 439 | } | 361 | } |
| @@ -479,7 +401,7 @@ mod tests { | |||
| 479 | assert!(!text.contains(&config.runner_secret)); | 401 | assert!(!text.contains(&config.runner_secret)); |
| 480 | assert!(!text.contains("hunter2-pass")); | 402 | assert!(!text.contains("hunter2-pass")); |
| 481 | assert!(text.contains("ghcr.io (tahinli)")); | 403 | assert!(text.contains("ghcr.io (tahinli)")); |
| 482 | - assert!(text.contains("limits.memory")); | 404 | + assert!(text.contains("limits.cpus")); |
| 483 | } | 405 | } |
| 484 | 406 | ||
| 485 | #[test] | 407 | #[test] |
| @@ -487,11 +409,11 @@ mod tests { | |||
| 487 | let dir = tempfile::tempdir().expect("tempdir"); | 409 | let dir = tempfile::tempdir().expect("tempdir"); |
| 488 | let mut config = sample(dir.path()); | 410 | let mut config = sample(dir.path()); |
| 489 | let mut ov = BTreeMap::new(); | 411 | let mut ov = BTreeMap::new(); |
| 490 | - ov.insert("limits.memory".to_owned(), serde_json::json!("8g")); | 412 | + ov.insert("limits.cpus".to_owned(), serde_json::json!("4")); |
| 491 | ov.insert("cache_max_gib".to_owned(), serde_json::json!(5)); | 413 | ov.insert("cache_max_gib".to_owned(), serde_json::json!(5)); |
| 492 | ov.insert("concurrency".to_owned(), serde_json::json!(9)); | 414 | ov.insert("concurrency".to_owned(), serde_json::json!(9)); |
| 493 | let lines = config.apply_overrides(&ov); | 415 | let lines = config.apply_overrides(&ov); |
| 494 | - assert_eq!(config.limits.memory, "8g"); | 416 | + assert_eq!(config.limits.cpus, "4"); |
| 495 | assert_eq!(config.cache_max_gib, 5); | 417 | assert_eq!(config.cache_max_gib, 5); |
| 496 | assert_ne!( | 418 | assert_ne!( |
| 497 | config.concurrency, 9, | 419 | config.concurrency, 9, |
| @@ -599,75 +521,21 @@ mod tests { | |||
| 599 | } | 521 | } |
| 600 | 522 | ||
| 601 | #[test] | 523 | #[test] |
| 602 | - fn cgroup_memory_is_the_declared_memory_plus_slack() { | 524 | + fn retired_limits_keys_are_dropped_on_load() { |
| 603 | - let limits = Limits::default(); | ||
| 604 | - let gib = 1u64 << 30; | ||
| 605 | - assert_eq!( | ||
| 606 | - limits.job_memory_limit(Some(4 * gib)), | ||
| 607 | - Some(4 * gib + (256 << 20)) | ||
| 608 | - ); | ||
| 609 | - assert_eq!(memory_slack(32 * gib), 2 * gib); | ||
| 610 | - assert_eq!(memory_slack(512 << 20), 256 << 20); | ||
| 611 | - let small = Limits { | ||
| 612 | - memory: "8g".into(), | ||
| 613 | - ..Limits::default() | ||
| 614 | - }; | ||
| 615 | - assert_eq!(small.job_memory_limit(Some(gib)), Some(gib + (256 << 20))); | ||
| 616 | - assert_eq!( | ||
| 617 | - small.for_job(Some(gib)).memory, | ||
| 618 | - (gib + (256 << 20)).to_string() | ||
| 619 | - ); | ||
| 620 | - } | ||
| 621 | - | ||
| 622 | - #[test] | ||
| 623 | - fn cgroup_memory_without_a_declaration_is_the_larger_of_limit_and_reserve() { | ||
| 624 | - let gib = 1u64 << 30; | ||
| 625 | - let limits = Limits::default(); | ||
| 626 | - assert_eq!(limits.job_memory_limit(None), Some(4 * gib)); | ||
| 627 | - assert_eq!(limits.for_job(None).memory, "4g"); | ||
| 628 | - let big_reserve = Limits { | ||
| 629 | - reserve_memory: "6g".into(), | ||
| 630 | - ..Limits::default() | ||
| 631 | - }; | ||
| 632 | - assert_eq!(big_reserve.job_memory_limit(None), Some(6 * gib)); | ||
| 633 | - assert_eq!(big_reserve.for_job(None).memory, (6 * gib).to_string()); | ||
| 634 | - let bad = Limits { | ||
| 635 | - memory: "lots".into(), | ||
| 636 | - ..Limits::default() | ||
| 637 | - }; | ||
| 638 | - assert_eq!(bad.job_memory_limit(None), None); | ||
| 639 | - assert_eq!(bad.for_job(None).memory, "lots"); | ||
| 640 | - assert_eq!( | ||
| 641 | - limits.for_builtin_job(None, Some(6 * gib), 0).memory, | ||
| 642 | - (6 * gib).to_string() | ||
| 643 | - ); | ||
| 644 | - assert_eq!( | ||
| 645 | - limits.for_builtin_job(Some(gib), Some(6 * gib), 0).memory, | ||
| 646 | - limits.for_job(Some(gib)).memory | ||
| 647 | - ); | ||
| 648 | - } | ||
| 649 | - | ||
| 650 | - #[test] | ||
| 651 | - fn memory_settings_are_reported_and_overridable() { | ||
| 652 | let dir = tempfile::tempdir().expect("tempdir"); | 525 | let dir = tempfile::tempdir().expect("tempdir"); |
| 653 | - let mut config = sample(dir.path()); | 526 | + let path = dir.path().join("runner.toml"); |
| 654 | - let report = config.report(); | 527 | + std::fs::write( |
| 655 | - assert_eq!(report["limits.reserve_memory"], "1g"); | 528 | + &path, |
| 656 | - assert_eq!(report["limits.memory_budget"], "auto"); | 529 | + "url = \"https://f\"\nrunner_id = \"r\"\nrunner_secret = \"s\"\nname = \"n\"\n\ |
| 657 | - let mut ov = BTreeMap::new(); | 530 | + work_dir = \"/w\"\n[limits]\nmemory = \"1g\"\nreserve_memory = \"1g\"\n\ |
| 658 | - ov.insert("limits.reserve_memory".to_owned(), serde_json::json!("2g")); | 531 | + memory_budget = \"auto\"\nbudget_swap_percent = 10\ncpus = \"1\"\npids = 100\n", |
| 659 | - ov.insert("limits.memory_budget".to_owned(), serde_json::json!("6g")); | 532 | + ) |
| 660 | - config.apply_overrides(&ov); | 533 | + .expect("write"); |
| 661 | - assert_eq!(config.limits.reserve_memory, "2g"); | 534 | + let config = load(&path).expect("load"); |
| 662 | - assert_eq!(config.limits.memory_budget.as_deref(), Some("6g")); | 535 | + assert_eq!(config.limits.cpus, "1"); |
| 663 | - ov.insert("limits.memory_budget".to_owned(), serde_json::json!("auto")); | 536 | + save(&path, &config).expect("save"); |
| 664 | - ov.insert( | 537 | + let text = std::fs::read_to_string(&path).expect("read"); |
| 665 | - "limits.reserve_memory".to_owned(), | 538 | + assert!(!text.contains("reserve_memory") && !text.contains("memory =")); |
| 666 | - serde_json::json!("nope"), | ||
| 667 | - ); | ||
| 668 | - config.apply_overrides(&ov); | ||
| 669 | - assert_eq!(config.limits.memory_budget, None); | ||
| 670 | - assert_eq!(config.limits.reserve_memory, "2g", "a bad value is skipped"); | ||
| 671 | } | 539 | } |
| 672 | 540 | ||
| 673 | #[test] | 541 | #[test] |
| @@ -703,7 +571,6 @@ mod tests { | |||
| 703 | let config = load(&path).expect("load"); | 571 | let config = load(&path).expect("load"); |
| 704 | assert_eq!(config.executor, ExecutorKind::Podman); | 572 | assert_eq!(config.executor, ExecutorKind::Podman); |
| 705 | assert_eq!(config.limits.image_max_gb, 5); | 573 | assert_eq!(config.limits.image_max_gb, 5); |
| 706 | - assert_eq!(config.limits.memory, "1g"); | ||
| 707 | assert_eq!(config.images.keep_days, 3); | 574 | assert_eq!(config.images.keep_days, 3); |
| 708 | assert_eq!(config.registries.len(), 1); | 575 | assert_eq!(config.registries.len(), 1); |
| 709 | assert_eq!(config.registries[0].host, "ghcr.io"); | 576 | assert_eq!(config.registries[0].host, "ghcr.io"); |
crates/forge-runner/src/executor.rsmodified+6 -31
| @@ -35,8 +35,6 @@ pub struct ExecRequest<'a> { | |||
| 35 | pub logs: mpsc::Sender<Vec<u8>>, | 35 | pub logs: mpsc::Sender<Vec<u8>>, |
| 36 | pub cancel: CancellationToken, | 36 | pub cancel: CancellationToken, |
| 37 | pub oom: OomSink, | 37 | pub oom: OomSink, |
| 38 | - pub memory_budget: Option<u64>, | ||
| 39 | - pub memory_swap: u64, | ||
| 40 | } | 38 | } |
| 41 | 39 | ||
| 42 | #[derive(Clone, Debug, PartialEq, Eq)] | 40 | #[derive(Clone, Debug, PartialEq, Eq)] |
| @@ -100,8 +98,7 @@ pub fn job_env_with_defaults( | |||
| 100 | ("FORGE_CPUS", n.to_string()), | 98 | ("FORGE_CPUS", n.to_string()), |
| 101 | ( | 99 | ( |
| 102 | "FORGE_MEMORY_BYTES", | 100 | "FORGE_MEMORY_BYTES", |
| 103 | - crate::sandbox::spec::parse_bytes(&limits.memory) | 101 | + crate::memory::box_size(limits).to_string(), |
| 104 | - .map_or_else(|_| "0".to_owned(), |b| b.to_string()), | ||
| 105 | ), | 102 | ), |
| 106 | ("CARGO_BUILD_JOBS", n.to_string()), | 103 | ("CARGO_BUILD_JOBS", n.to_string()), |
| 107 | ("MAKEFLAGS", format!("-j{n}")), | 104 | ("MAKEFLAGS", format!("-j{n}")), |
| @@ -149,9 +146,8 @@ pub fn podman_invocation( | |||
| 149 | ) -> Result<PodmanInvocation, ExecError> { | 146 | ) -> Result<PodmanInvocation, ExecError> { |
| 150 | validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?; | 147 | validate_job_id(&job.job_id).map_err(|e| ExecError::Invalid(e.to_string()))?; |
| 151 | check_image(&job.image)?; | 148 | check_image(&job.image)?; |
| 152 | - let limits = &limits.for_job(job.memory_bytes); | ||
| 153 | - check_limit(&limits.memory, "memory")?; | ||
| 154 | check_limit(&limits.cpus, "cpus")?; | 149 | check_limit(&limits.cpus, "cpus")?; |
| 150 | + let memory = crate::memory::box_size(limits).to_string(); | ||
| 155 | let ws = workspace | 151 | let ws = workspace |
| 156 | .to_str() | 152 | .to_str() |
| 157 | .filter(|s| !s.contains(':') && !s.contains(',')) | 153 | .filter(|s| !s.contains(':') && !s.contains(',')) |
| @@ -169,9 +165,7 @@ pub fn podman_invocation( | |||
| 169 | "--pull=newer", | 165 | "--pull=newer", |
| 170 | &format!("--network={network}"), | 166 | &format!("--network={network}"), |
| 171 | "--memory", | 167 | "--memory", |
| 172 | - &limits.memory, | 168 | + &memory, |
| 173 | - "--memory-swap", | ||
| 174 | - &limits.memory, | ||
| 175 | "--cpus", | 169 | "--cpus", |
| 176 | &limits.cpus, | 170 | &limits.cpus, |
| 177 | "--pids-limit", | 171 | "--pids-limit", |
| @@ -581,12 +575,8 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 581 | logs, | 575 | logs, |
| 582 | cancel, | 576 | cancel, |
| 583 | oom: oom_sink, | 577 | oom: oom_sink, |
| 584 | - memory_budget, | ||
| 585 | - memory_swap, | ||
| 586 | } = req; | 578 | } = req; |
| 587 | - let limits = self | 579 | + let limits = self.limits.clone(); |
| 588 | - .limits | ||
| 589 | - .for_builtin_job(job.memory_bytes, memory_budget, memory_swap); | ||
| 590 | let disk_gb = limits.job_disk_gb; | 580 | let disk_gb = limits.job_disk_gb; |
| 591 | if let Err(e) = validate_job_id(&job.job_id) { | 581 | if let Err(e) = validate_job_id(&job.job_id) { |
| 592 | return error_result(e.to_string()); | 582 | return error_result(e.to_string()); |
| @@ -942,7 +932,6 @@ mod tests { | |||
| 942 | cache: Vec::new(), | 932 | cache: Vec::new(), |
| 943 | cache_key: String::new(), | 933 | cache_key: String::new(), |
| 944 | cache_restore_keys: Vec::new(), | 934 | cache_restore_keys: Vec::new(), |
| 945 | - memory_bytes: None, | ||
| 946 | } | 935 | } |
| 947 | } | 936 | } |
| 948 | 937 | ||
| @@ -989,7 +978,8 @@ mod tests { | |||
| 989 | let joined = inv.args.join(" "); | 978 | let joined = inv.args.join(" "); |
| 990 | assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer")); | 979 | assert!(joined.starts_with("run --rm --name forge-job-job_01 --pull=newer")); |
| 991 | assert!(joined.contains("--network=none")); | 980 | assert!(joined.contains("--network=none")); |
| 992 | - assert!(joined.contains("--memory 4g --memory-swap 4g --cpus 2 --pids-limit 4096")); | 981 | + let memory = crate::memory::box_size(&Limits::default()); |
| 982 | + assert!(joined.contains(&format!("--memory {memory} --cpus 2 --pids-limit 4096"))); | ||
| 993 | assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL")); | 983 | assert!(joined.contains("--security-opt no-new-privileges --cap-drop ALL")); |
| 994 | assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace")); | 984 | assert!(joined.contains("-v /work/job_01:/workspace:Z -w /workspace")); |
| 995 | assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true")); | 985 | assert!(joined.ends_with("docker.io/library/alpine:3 sh -eu -c true")); |
| @@ -1003,19 +993,6 @@ mod tests { | |||
| 1003 | assert!(inv.args.contains(&"--network=slirp4netns".to_owned())); | 993 | assert!(inv.args.contains(&"--network=slirp4netns".to_owned())); |
| 1004 | } | 994 | } |
| 1005 | 995 | ||
| 1006 | - #[test] | ||
| 1007 | - fn a_declared_memory_sets_the_podman_limit() { | ||
| 1008 | - let mut job = fixture_job("true"); | ||
| 1009 | - job.memory_bytes = Some(4 << 30); | ||
| 1010 | - let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); | ||
| 1011 | - let joined = inv.args.join(" "); | ||
| 1012 | - let limit = (4u64 << 30) + (256 << 20); | ||
| 1013 | - assert!( | ||
| 1014 | - joined.contains(&format!("--memory {limit} --memory-swap {limit}")), | ||
| 1015 | - "{joined}" | ||
| 1016 | - ); | ||
| 1017 | - } | ||
| 1018 | - | ||
| 1019 | #[test] | 996 | #[test] |
| 1020 | fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { | 997 | fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { |
| 1021 | let mut job = fixture_job("true"); | 998 | let mut job = fixture_job("true"); |
| @@ -1084,8 +1061,6 @@ mod tests { | |||
| 1084 | logs: tx, | 1061 | logs: tx, |
| 1085 | cancel: CancellationToken::new(), | 1062 | cancel: CancellationToken::new(), |
| 1086 | oom: OomSink::default(), | 1063 | oom: OomSink::default(), |
| 1087 | - memory_budget: None, | ||
| 1088 | - memory_swap: 0, | ||
| 1089 | }) | 1064 | }) |
| 1090 | .await; | 1065 | .await; |
| 1091 | assert_eq!(result.outcome, Outcome::Success, "{result:?}"); | 1066 | assert_eq!(result.outcome, Outcome::Success, "{result:?}"); |
crates/forge-runner/src/logs.rsmodified+13 -2
| @@ -11,6 +11,7 @@ use crate::client::{ClientError, ForgeClient, LogAck}; | |||
| 11 | pub const MAX_BATCH: usize = 64 * 1024; | 11 | pub const MAX_BATCH: usize = 64 * 1024; |
| 12 | const MAX_LINE: usize = 16 * 1024; | 12 | const MAX_LINE: usize = 16 * 1024; |
| 13 | const MAX_RESYNCS: u32 = 3; | 13 | const MAX_RESYNCS: u32 = 3; |
| 14 | +const MAX_RETRY_DELAY: Duration = Duration::from_secs(30); | ||
| 14 | 15 | ||
| 15 | #[derive(Debug, thiserror::Error)] | 16 | #[derive(Debug, thiserror::Error)] |
| 16 | pub enum LogError { | 17 | pub enum LogError { |
| @@ -227,17 +228,27 @@ async fn send( | |||
| 227 | } | 228 | } |
| 228 | Err(e) => { | 229 | Err(e) => { |
| 229 | failures += 1; | 230 | failures += 1; |
| 230 | - if failures > cfg.retries { | 231 | + if !passing(&e) && failures > cfg.retries { |
| 231 | return Err(e.into()); | 232 | return Err(e.into()); |
| 232 | } | 233 | } |
| 233 | tracing::warn!(error = %e, failures, "log upload failed, retrying"); | 234 | tracing::warn!(error = %e, failures, "log upload failed, retrying"); |
| 234 | - tokio::time::sleep(cfg.retry_delay * failures).await; | 235 | + tokio::time::sleep((cfg.retry_delay * failures.min(15)).min(MAX_RETRY_DELAY)).await; |
| 235 | } | 236 | } |
| 236 | } | 237 | } |
| 237 | } | 238 | } |
| 238 | Ok(()) | 239 | Ok(()) |
| 239 | } | 240 | } |
| 240 | 241 | ||
| 242 | +fn passing(e: &ClientError) -> bool { | ||
| 243 | + match e { | ||
| 244 | + ClientError::Http(_) => true, | ||
| 245 | + ClientError::Status { status, .. } => { | ||
| 246 | + status.is_server_error() || *status == reqwest::StatusCode::TOO_MANY_REQUESTS | ||
| 247 | + } | ||
| 248 | + ClientError::Io(_) | ClientError::Protocol(_) => false, | ||
| 249 | + } | ||
| 250 | +} | ||
| 251 | + | ||
| 241 | pub async fn forward_lines<R>(reader: R, tx: mpsc::Sender<Vec<u8>>) | 252 | pub async fn forward_lines<R>(reader: R, tx: mpsc::Sender<Vec<u8>>) |
| 242 | where | 253 | where |
| 243 | R: AsyncRead + Unpin, | 254 | R: AsyncRead + Unpin, |
crates/forge-runner/src/memory.rsmodified+15 -245
| @@ -1,28 +1,14 @@ | |||
| 1 | -use std::sync::{Arc, Mutex, PoisonError}; | 1 | +use forge_ci::size::parse_size; |
| 2 | - | ||
| 3 | -use forge_ci::size::{format_size, parse_size}; | ||
| 4 | 2 | ||
| 5 | use crate::config::Limits; | 3 | use crate::config::Limits; |
| 6 | 4 | ||
| 7 | -const FALLBACK_RESERVE: u64 = 1 << 30; | 5 | +const MIN_BOX: u64 = 512 << 20; |
| 8 | -const MIN_BUDGET: u64 = 256 << 20; | 6 | +const FALLBACK_TOTAL: u64 = 8 << 30; |
| 9 | - | ||
| 10 | -pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 { | ||
| 11 | - declared.unwrap_or(default_reserve).min(budget).max(1) | ||
| 12 | -} | ||
| 13 | - | ||
| 14 | -pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: u32) -> u64 { | ||
| 15 | - let keep = headroom.max(mem_total / 10); | ||
| 16 | - let ram = mem_total.saturating_sub(keep).max(mem_total / 2); | ||
| 17 | - let swap = (u128::from(swap_total) * u128::from(swap_percent.min(100)) / 100) as u64; | ||
| 18 | - ram.saturating_add(swap).max(MIN_BUDGET) | ||
| 19 | -} | ||
| 20 | 7 | ||
| 21 | #[derive(Default)] | 8 | #[derive(Default)] |
| 22 | pub struct Meminfo { | 9 | pub struct Meminfo { |
| 23 | pub total: Option<u64>, | 10 | pub total: Option<u64>, |
| 24 | pub available: Option<u64>, | 11 | pub available: Option<u64>, |
| 25 | - pub swap_total: Option<u64>, | ||
| 26 | } | 12 | } |
| 27 | 13 | ||
| 28 | pub fn meminfo(text: &str) -> Meminfo { | 14 | pub fn meminfo(text: &str) -> Meminfo { |
| @@ -34,158 +20,22 @@ pub fn meminfo(text: &str) -> Meminfo { | |||
| 34 | Meminfo { | 20 | Meminfo { |
| 35 | total: find("MemTotal:"), | 21 | total: find("MemTotal:"), |
| 36 | available: find("MemAvailable:"), | 22 | available: find("MemAvailable:"), |
| 37 | - swap_total: find("SwapTotal:"), | ||
| 38 | } | 23 | } |
| 39 | } | 24 | } |
| 40 | 25 | ||
| 41 | -fn host_memory() -> Meminfo { | 26 | +pub fn host_total() -> Option<u64> { |
| 42 | std::fs::read_to_string("/proc/meminfo") | 27 | std::fs::read_to_string("/proc/meminfo") |
| 43 | - .map(|t| meminfo(&t)) | 28 | + .ok() |
| 44 | - .unwrap_or_default() | 29 | + .and_then(|t| meminfo(&t).total) |
| 45 | -} | ||
| 46 | - | ||
| 47 | -fn fixed_budget(limits: &Limits) -> Option<u64> { | ||
| 48 | - limits.memory_budget.as_deref().and_then(parse_size) | ||
| 49 | -} | ||
| 50 | - | ||
| 51 | -fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 { | ||
| 52 | - fixed_budget(limits).map_or_else( | ||
| 53 | - || { | ||
| 54 | - let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); | ||
| 55 | - auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) | ||
| 56 | - }, | ||
| 57 | - |n| n.max(MIN_BUDGET), | ||
| 58 | - ) | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -struct State { | ||
| 62 | - budget: u64, | ||
| 63 | - swap: u64, | ||
| 64 | - reserve: u64, | ||
| 65 | - reserved: u64, | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -fn swap_share(limits: &Limits, swap_total: u64) -> u64 { | ||
| 69 | - if fixed_budget(limits).is_some() { | ||
| 70 | - return 0; | ||
| 71 | - } | ||
| 72 | - (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64 | ||
| 73 | } | 30 | } |
| 74 | 31 | ||
| 75 | -pub struct MemoryGate { | 32 | +pub fn box_size_of(mem_total: u64, headroom: u64) -> u64 { |
| 76 | - limits: Limits, | 33 | + mem_total.saturating_sub(headroom).max(MIN_BOX) |
| 77 | - mem_total: u64, | ||
| 78 | - swap_total: u64, | ||
| 79 | - state: Mutex<State>, | ||
| 80 | } | 34 | } |
| 81 | 35 | ||
| 82 | -pub struct Reservation { | 36 | +pub fn box_size(limits: &Limits) -> u64 { |
| 83 | - bytes: u64, | 37 | + let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); |
| 84 | - gate: Arc<MemoryGate>, | 38 | + box_size_of(host_total().unwrap_or(FALLBACK_TOTAL), headroom) |
| 85 | -} | ||
| 86 | - | ||
| 87 | -impl Drop for Reservation { | ||
| 88 | - fn drop(&mut self) { | ||
| 89 | - let mut state = self.gate.lock(); | ||
| 90 | - state.reserved = state.reserved.saturating_sub(self.bytes); | ||
| 91 | - } | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -impl MemoryGate { | ||
| 95 | - pub fn for_host(limits: &Limits) -> Arc<Self> { | ||
| 96 | - let host = host_memory(); | ||
| 97 | - Self::new( | ||
| 98 | - limits, | ||
| 99 | - host.total.unwrap_or(8 << 30), | ||
| 100 | - host.swap_total.unwrap_or(0), | ||
| 101 | - ) | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | - pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc<Self> { | ||
| 105 | - let budget = configured_budget(limits, mem_total, swap_total); | ||
| 106 | - let reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE); | ||
| 107 | - Arc::new(Self { | ||
| 108 | - limits: limits.clone(), | ||
| 109 | - mem_total, | ||
| 110 | - swap_total, | ||
| 111 | - state: Mutex::new(State { | ||
| 112 | - budget, | ||
| 113 | - swap: swap_share(limits, swap_total), | ||
| 114 | - reserve, | ||
| 115 | - reserved: 0, | ||
| 116 | - }), | ||
| 117 | - }) | ||
| 118 | - } | ||
| 119 | - | ||
| 120 | - fn lock(&self) -> std::sync::MutexGuard<'_, State> { | ||
| 121 | - self.state.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 122 | - } | ||
| 123 | - | ||
| 124 | - pub fn budget(&self) -> u64 { | ||
| 125 | - self.lock().budget | ||
| 126 | - } | ||
| 127 | - | ||
| 128 | - pub fn swap(&self) -> u64 { | ||
| 129 | - self.lock().swap | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - pub fn ram_budget(&self) -> u64 { | ||
| 133 | - let state = self.lock(); | ||
| 134 | - state.budget.saturating_sub(state.swap).max(MIN_BUDGET) | ||
| 135 | - } | ||
| 136 | - | ||
| 137 | - pub fn default_reserve(&self) -> u64 { | ||
| 138 | - self.lock().reserve | ||
| 139 | - } | ||
| 140 | - | ||
| 141 | - pub fn free(&self) -> u64 { | ||
| 142 | - let state = self.lock(); | ||
| 143 | - state.budget.saturating_sub(state.reserved) | ||
| 144 | - } | ||
| 145 | - | ||
| 146 | - pub fn reserve(self: &Arc<Self>, declared: Option<u64>) -> Reservation { | ||
| 147 | - let mut state = self.lock(); | ||
| 148 | - let bytes = reservation(declared, state.reserve, state.budget); | ||
| 149 | - state.reserved = state.reserved.saturating_add(bytes); | ||
| 150 | - Reservation { | ||
| 151 | - bytes, | ||
| 152 | - gate: self.clone(), | ||
| 153 | - } | ||
| 154 | - } | ||
| 155 | - | ||
| 156 | - pub fn apply(&self, budget: Option<&str>, reserve: Option<&str>) -> Option<String> { | ||
| 157 | - let mut limits = self.limits.clone(); | ||
| 158 | - if let Some(text) = budget.filter(|t| *t == "auto" || parse_size(t).is_some()) { | ||
| 159 | - limits.memory_budget = (text != "auto").then(|| text.to_owned()); | ||
| 160 | - } | ||
| 161 | - if let Some(text) = reserve.filter(|t| parse_size(t).is_some()) { | ||
| 162 | - limits.reserve_memory = text.to_owned(); | ||
| 163 | - } | ||
| 164 | - let new_budget = configured_budget(&limits, self.mem_total, self.swap_total); | ||
| 165 | - let new_reserve = parse_size(&limits.reserve_memory).unwrap_or(FALLBACK_RESERVE); | ||
| 166 | - let new_swap = swap_share(&limits, self.swap_total); | ||
| 167 | - let mut state = self.lock(); | ||
| 168 | - if (state.budget, state.reserve) == (new_budget, new_reserve) { | ||
| 169 | - return None; | ||
| 170 | - } | ||
| 171 | - let line = format!( | ||
| 172 | - "runner: memory budget {} -> {}, default reservation {} -> {}", | ||
| 173 | - format_size(state.budget), | ||
| 174 | - format_size(new_budget), | ||
| 175 | - format_size(state.reserve), | ||
| 176 | - format_size(new_reserve), | ||
| 177 | - ); | ||
| 178 | - state.budget = new_budget; | ||
| 179 | - state.swap = new_swap; | ||
| 180 | - state.reserve = new_reserve; | ||
| 181 | - Some(line) | ||
| 182 | - } | ||
| 183 | - | ||
| 184 | - pub fn apply_logged(&self, budget: Option<&str>, reserve: Option<&str>) { | ||
| 185 | - if let Some(line) = self.apply(budget, reserve) { | ||
| 186 | - tracing::info!("{line}"); | ||
| 187 | - } | ||
| 188 | - } | ||
| 189 | } | 39 | } |
| 190 | 40 | ||
| 191 | #[cfg(test)] | 41 | #[cfg(test)] |
| @@ -195,97 +45,17 @@ mod tests { | |||
| 195 | const GIB: u64 = 1 << 30; | 45 | const GIB: u64 = 1 << 30; |
| 196 | 46 | ||
| 197 | #[test] | 47 | #[test] |
| 198 | - fn the_swap_share_is_kept_apart_from_ram() { | 48 | + fn box_is_host_memory_minus_headroom_with_a_floor() { |
| 199 | - let limits = Limits { | 49 | + assert_eq!(box_size_of(8 * GIB, GIB), 7 * GIB); |
| 200 | - budget_swap_percent: 50, | 50 | + assert_eq!(box_size_of(GIB, 2 * GIB), MIN_BOX); |
| 201 | - ..Limits::default() | ||
| 202 | - }; | ||
| 203 | - let gate = MemoryGate::new(&limits, 8 * GIB, 8 * GIB); | ||
| 204 | - assert_eq!(gate.swap(), 4 * GIB); | ||
| 205 | - assert_eq!(gate.ram_budget(), gate.budget() - 4 * GIB); | ||
| 206 | - let set = Limits { | ||
| 207 | - memory_budget: Some("6g".into()), | ||
| 208 | - ..limits | ||
| 209 | - }; | ||
| 210 | - assert_eq!(MemoryGate::new(&set, 8 * GIB, 8 * GIB).swap(), 0); | ||
| 211 | - } | ||
| 212 | - | ||
| 213 | - #[test] | ||
| 214 | - fn a_job_without_memory_reserves_the_default() { | ||
| 215 | - assert_eq!(reservation(None, GIB, 6 * GIB), GIB); | ||
| 216 | - assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB); | ||
| 217 | - assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB); | ||
| 218 | - } | ||
| 219 | - | ||
| 220 | - #[test] | ||
| 221 | - fn auto_budget_is_mem_total_minus_headroom() { | ||
| 222 | - let total = 7 * GIB + 6 * GIB / 10; | ||
| 223 | - let budget = auto_budget(total, 8 * GIB, GIB, 0); | ||
| 224 | - assert_eq!(budget, total - GIB); | ||
| 225 | - assert!(budget > 6 * GIB && budget < 7 * GIB); | ||
| 226 | - assert_eq!(auto_budget(64 * GIB, 0, GIB, 0), 64 * GIB - 64 * GIB / 10); | ||
| 227 | - assert_eq!(auto_budget(total, 8 * GIB, GIB, 50), total - GIB + 4 * GIB); | ||
| 228 | - assert_eq!(auto_budget(GIB, 0, 2 * GIB, 0), GIB / 2); | ||
| 229 | } | 51 | } |
| 230 | 52 | ||
| 231 | #[test] | 53 | #[test] |
| 232 | fn meminfo_is_parsed() { | 54 | fn meminfo_is_parsed() { |
| 233 | - let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\nSwapTotal: 8388604 kB\n"; | 55 | + let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\n"; |
| 234 | let m = meminfo(text); | 56 | let m = meminfo(text); |
| 235 | assert_eq!(m.total, Some(7_971_680 * 1024)); | 57 | assert_eq!(m.total, Some(7_971_680 * 1024)); |
| 236 | assert_eq!(m.available, Some(4_000_000 * 1024)); | 58 | assert_eq!(m.available, Some(4_000_000 * 1024)); |
| 237 | - assert_eq!(m.swap_total, Some(8_388_604 * 1024)); | ||
| 238 | assert_eq!(meminfo("").total, None); | 59 | assert_eq!(meminfo("").total, None); |
| 239 | } | 60 | } |
| 240 | - | ||
| 241 | - #[test] | ||
| 242 | - fn the_gate_tracks_reservations() { | ||
| 243 | - let limits = Limits { | ||
| 244 | - memory_budget: Some("6g".into()), | ||
| 245 | - ..Limits::default() | ||
| 246 | - }; | ||
| 247 | - let gate = MemoryGate::new(&limits, 8 * GIB, 0); | ||
| 248 | - assert_eq!(gate.budget(), 6 * GIB); | ||
| 249 | - assert_eq!(gate.free(), 6 * GIB); | ||
| 250 | - let heavy = gate.reserve(Some(4 * GIB)); | ||
| 251 | - assert_eq!(gate.free(), 2 * GIB); | ||
| 252 | - let light = gate.reserve(None); | ||
| 253 | - assert_eq!(gate.free(), GIB); | ||
| 254 | - drop(heavy); | ||
| 255 | - assert_eq!(gate.free(), 5 * GIB); | ||
| 256 | - drop(light); | ||
| 257 | - assert_eq!(gate.free(), 6 * GIB); | ||
| 258 | - } | ||
| 259 | - | ||
| 260 | - #[test] | ||
| 261 | - fn an_old_forge_cannot_push_free_below_zero() { | ||
| 262 | - let limits = Limits { | ||
| 263 | - memory_budget: Some("2g".into()), | ||
| 264 | - ..Limits::default() | ||
| 265 | - }; | ||
| 266 | - let gate = MemoryGate::new(&limits, 8 * GIB, 0); | ||
| 267 | - let a = gate.reserve(Some(2 * GIB)); | ||
| 268 | - let b = gate.reserve(Some(2 * GIB)); | ||
| 269 | - assert_eq!(gate.free(), 0); | ||
| 270 | - drop(a); | ||
| 271 | - assert_eq!(gate.free(), 0); | ||
| 272 | - drop(b); | ||
| 273 | - assert_eq!(gate.free(), 2 * GIB); | ||
| 274 | - } | ||
| 275 | - | ||
| 276 | - #[test] | ||
| 277 | - fn the_forge_can_change_budget_and_reserve_live() { | ||
| 278 | - let gate = MemoryGate::new(&Limits::default(), 8 * GIB, 0); | ||
| 279 | - assert_eq!(gate.budget(), 7 * GIB); | ||
| 280 | - let line = gate.apply(Some("5g"), Some("2g")); | ||
| 281 | - assert!(line.is_some()); | ||
| 282 | - assert_eq!(gate.budget(), 5 * GIB); | ||
| 283 | - assert_eq!(gate.default_reserve(), 2 * GIB); | ||
| 284 | - assert_eq!(gate.apply(Some("5g"), Some("2g")), None, "no change"); | ||
| 285 | - gate.apply(None, None); | ||
| 286 | - assert_eq!(gate.default_reserve(), GIB); | ||
| 287 | - assert_ne!(gate.budget(), 5 * GIB); | ||
| 288 | - gate.apply(Some("lots"), Some("0")); | ||
| 289 | - assert_eq!(gate.default_reserve(), GIB); | ||
| 290 | - } | ||
| 291 | } | 61 | } |
crates/forge-runner/src/pressure.rsmodified+12 -1050
| @@ -1,547 +1,23 @@ | |||
| 1 | -use std::fs::{self, File, OpenOptions}; | 1 | +use std::fs; |
| 2 | -use std::io::{self, Write}; | 2 | +use std::io; |
| 3 | -use std::os::fd::{AsFd, OwnedFd}; | ||
| 4 | -use std::os::unix::fs::OpenOptionsExt; | ||
| 5 | use std::path::{Path, PathBuf}; | 3 | use std::path::{Path, PathBuf}; |
| 6 | -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | 4 | +use std::time::Duration; |
| 7 | -use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; | ||
| 8 | -use std::time::{Duration, Instant}; | ||
| 9 | - | ||
| 10 | -use nix::errno::Errno; | ||
| 11 | -use nix::poll::{PollFd, PollFlags, PollTimeout, poll}; | ||
| 12 | -use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; | ||
| 13 | -use nix::unistd::pipe; | ||
| 14 | -use tokio::sync::{Notify, mpsc}; | ||
| 15 | -use tokio_util::sync::CancellationToken; | ||
| 16 | 5 | ||
| 17 | use crate::executor::kill_cgroup; | 6 | use crate::executor::kill_cgroup; |
| 18 | use crate::sandbox::{BOX_NAME, job_cgroup_base}; | 7 | use crate::sandbox::{BOX_NAME, job_cgroup_base}; |
| 19 | 8 | ||
| 20 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; | 9 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; |
| 21 | const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"]; | 10 | const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"]; |
| 22 | -const PSI_TRIGGER: &str = "some 150000 2000000"; | ||
| 23 | -const HIGH_MARGIN_MIN: u64 = 512 << 20; | ||
| 24 | -const SWAPPINESS: u32 = 200; | ||
| 25 | -const RECLAIM_ATTEMPTS: u32 = 4; | ||
| 26 | const LEFTOVER_POLLS: u32 = 50; | 11 | const LEFTOVER_POLLS: u32 = 50; |
| 27 | const LEFTOVER_POLL: Duration = Duration::from_millis(100); | 12 | const LEFTOVER_POLL: Duration = Duration::from_millis(100); |
| 28 | -const PRESSURE_COOLDOWN: Duration = Duration::from_secs(10); | ||
| 29 | - | ||
| 30 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 31 | -pub enum Cause { | ||
| 32 | - Pressure, | ||
| 33 | - Jobs, | ||
| 34 | -} | ||
| 35 | - | ||
| 36 | -fn field_u64(text: &str, key: &str) -> Option<u64> { | ||
| 37 | - text.lines().find_map(|line| { | ||
| 38 | - let (k, v) = line.split_once(' ')?; | ||
| 39 | - (k == key).then(|| v.trim().parse().ok())? | ||
| 40 | - }) | ||
| 41 | -} | ||
| 42 | - | ||
| 43 | -pub fn parse_high(text: &str) -> u64 { | ||
| 44 | - field_u64(text, "high").unwrap_or(0) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> { | ||
| 48 | - if unfrozen < 2 { | ||
| 49 | - return None; | ||
| 50 | - } | ||
| 51 | - let margin = HIGH_MARGIN_MIN.max(budget / 20); | ||
| 52 | - Some(budget.saturating_sub(margin).max(budget / 2)) | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -pub fn pick_victim(seqs: &[u64]) -> Option<usize> { | ||
| 56 | - if seqs.len() < 2 { | ||
| 57 | - return None; | ||
| 58 | - } | ||
| 59 | - seqs.iter() | ||
| 60 | - .enumerate() | ||
| 61 | - .max_by_key(|(_, seq)| **seq) | ||
| 62 | - .map(|(i, _)| i) | ||
| 63 | -} | ||
| 64 | - | ||
| 65 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 66 | -pub struct Parked { | ||
| 67 | - pub seq: u64, | ||
| 68 | - pub swap: u64, | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> { | ||
| 72 | - let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?; | ||
| 73 | - (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index) | ||
| 74 | -} | ||
| 75 | - | ||
| 76 | -pub fn hot_after(cause: Cause, over_high: bool, jobs: usize) -> bool { | ||
| 77 | - jobs > 0 && (cause == Cause::Pressure || over_high) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | ||
| 81 | -pub struct Gate { | ||
| 82 | - pub frozen: usize, | ||
| 83 | - pub hot: bool, | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -impl Gate { | ||
| 87 | - pub fn open(&self) -> bool { | ||
| 88 | - self.frozen == 0 && !self.hot | ||
| 89 | - } | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -#[derive(Default)] | ||
| 93 | -struct PauseClock { | ||
| 94 | - total: Duration, | ||
| 95 | - since: Option<Instant>, | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -pub struct JobHandle { | ||
| 99 | - id: String, | ||
| 100 | - name: String, | ||
| 101 | - log: Mutex<Option<mpsc::Sender<Vec<u8>>>>, | ||
| 102 | - requeued: AtomicBool, | ||
| 103 | - clock: Mutex<PauseClock>, | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -impl JobHandle { | ||
| 107 | - fn log_line(&self, line: &str) { | ||
| 108 | - let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner); | ||
| 109 | - if let Some(tx) = guard.as_ref() { | ||
| 110 | - let mut bytes = format!("runner: {line}").into_bytes(); | ||
| 111 | - bytes.push(b'\n'); | ||
| 112 | - let _ = tx.try_send(bytes); | ||
| 113 | - } | ||
| 114 | - } | ||
| 115 | - | ||
| 116 | - pub fn paused(&self) -> Duration { | ||
| 117 | - let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); | ||
| 118 | - clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default() | ||
| 119 | - } | ||
| 120 | - | ||
| 121 | - fn pause(&self) { | ||
| 122 | - let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); | ||
| 123 | - clock.since.get_or_insert_with(Instant::now); | ||
| 124 | - } | ||
| 125 | - | ||
| 126 | - fn resume(&self) -> Duration { | ||
| 127 | - let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner); | ||
| 128 | - let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default(); | ||
| 129 | - clock.total += lasted; | ||
| 130 | - lasted | ||
| 131 | - } | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -pub struct Registration { | ||
| 135 | - handle: Arc<JobHandle>, | ||
| 136 | - owner: Arc<Pressure>, | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | -impl Registration { | ||
| 140 | - pub fn requeued(&self) -> bool { | ||
| 141 | - self.handle.requeued.load(Ordering::SeqCst) | ||
| 142 | - } | ||
| 143 | - | ||
| 144 | - pub fn pause_clock(&self) -> Arc<JobHandle> { | ||
| 145 | - self.handle.clone() | ||
| 146 | - } | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | -impl Drop for Registration { | ||
| 150 | - fn drop(&mut self) { | ||
| 151 | - *self | ||
| 152 | - .handle | ||
| 153 | - .log | ||
| 154 | - .lock() | ||
| 155 | - .unwrap_or_else(PoisonError::into_inner) = None; | ||
| 156 | - self.owner.remove(&self.handle); | ||
| 157 | - } | ||
| 158 | -} | ||
| 159 | - | ||
| 160 | -struct Entry { | ||
| 161 | - handle: Arc<JobHandle>, | ||
| 162 | - seq: u64, | ||
| 163 | - dir: Option<PathBuf>, | ||
| 164 | - frozen: Option<Frozen>, | ||
| 165 | -} | ||
| 166 | - | ||
| 167 | -struct Frozen { | ||
| 168 | - swap: u64, | ||
| 169 | -} | ||
| 170 | - | ||
| 171 | -#[derive(Default)] | ||
| 172 | -struct State { | ||
| 173 | - entries: Vec<Entry>, | ||
| 174 | - gate: Gate, | ||
| 175 | - high: Option<Option<u64>>, | ||
| 176 | -} | ||
| 177 | - | ||
| 178 | -pub struct Pressure { | ||
| 179 | - dir: PathBuf, | ||
| 180 | - budget: AtomicU64, | ||
| 181 | - state: Mutex<State>, | ||
| 182 | - seq: AtomicU64, | ||
| 183 | - kick: Notify, | ||
| 184 | - changed: Notify, | ||
| 185 | -} | ||
| 186 | - | ||
| 187 | -impl Pressure { | ||
| 188 | - pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> { | ||
| 189 | - let setup = tokio::task::spawn_blocking(move || { | ||
| 190 | - let base = job_cgroup_base().map_err(|e| e.to_string())?; | ||
| 191 | - let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); | ||
| 192 | - create_box(&parent, budget) | ||
| 193 | - }) | ||
| 194 | - .await; | ||
| 195 | - let dir = match setup.map_err(|e| e.to_string()).and_then(|r| r) { | ||
| 196 | - Ok(dir) => dir, | ||
| 197 | - Err(e) => { | ||
| 198 | - tracing::warn!("memory control is off: {e}"); | ||
| 199 | - return None; | ||
| 200 | - } | ||
| 201 | - }; | ||
| 202 | - let this = Arc::new(Self::at(dir, budget)); | ||
| 203 | - match Watcher::open(&this.dir) { | ||
| 204 | - Ok(watcher) => { | ||
| 205 | - let psi = watcher.psi_armed; | ||
| 206 | - tokio::spawn(this.clone().watch(watcher, shutdown)); | ||
| 207 | - tracing::info!( | ||
| 208 | - box_dir = %this.dir.display(), | ||
| 209 | - budget = %forge_ci::size::format_size(budget), | ||
| 210 | - psi, | ||
| 211 | - "memory control is on" | ||
| 212 | - ); | ||
| 213 | - Some(this) | ||
| 214 | - } | ||
| 215 | - Err(e) => { | ||
| 216 | - tracing::warn!("memory control is off, cannot watch the box: {e}"); | ||
| 217 | - None | ||
| 218 | - } | ||
| 219 | - } | ||
| 220 | - } | ||
| 221 | - | ||
| 222 | - fn at(dir: PathBuf, budget: u64) -> Self { | ||
| 223 | - Self { | ||
| 224 | - dir, | ||
| 225 | - budget: AtomicU64::new(budget), | ||
| 226 | - state: Mutex::new(State::default()), | ||
| 227 | - seq: AtomicU64::new(0), | ||
| 228 | - kick: Notify::new(), | ||
| 229 | - changed: Notify::new(), | ||
| 230 | - } | ||
| 231 | - } | ||
| 232 | - | ||
| 233 | - pub fn budget(&self) -> u64 { | ||
| 234 | - self.budget.load(Ordering::SeqCst) | ||
| 235 | - } | ||
| 236 | - | ||
| 237 | - pub fn resize(&self, budget: u64) { | ||
| 238 | - if self.budget.swap(budget, Ordering::SeqCst) == budget { | ||
| 239 | - return; | ||
| 240 | - } | ||
| 241 | - for file in ["memory.max", "memory.swap.max"] { | ||
| 242 | - if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) { | ||
| 243 | - tracing::warn!("cannot resize {file} of the box: {e}"); | ||
| 244 | - } | ||
| 245 | - } | ||
| 246 | - self.lock().high = None; | ||
| 247 | - self.kick.notify_one(); | ||
| 248 | - tracing::info!( | ||
| 249 | - budget = %forge_ci::size::format_size(budget), | ||
| 250 | - "memory box resized" | ||
| 251 | - ); | ||
| 252 | - } | ||
| 253 | - | ||
| 254 | - fn lock(&self) -> MutexGuard<'_, State> { | ||
| 255 | - self.state.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 256 | - } | ||
| 257 | - | ||
| 258 | - pub fn register( | ||
| 259 | - self: &Arc<Self>, | ||
| 260 | - job_id: &str, | ||
| 261 | - job_name: &str, | ||
| 262 | - log: mpsc::Sender<Vec<u8>>, | ||
| 263 | - ) -> Registration { | ||
| 264 | - let handle = Arc::new(JobHandle { | ||
| 265 | - id: job_id.to_owned(), | ||
| 266 | - name: job_name.to_owned(), | ||
| 267 | - log: Mutex::new(Some(log)), | ||
| 268 | - requeued: AtomicBool::new(false), | ||
| 269 | - clock: Mutex::new(PauseClock::default()), | ||
| 270 | - }); | ||
| 271 | - self.lock().entries.push(Entry { | ||
| 272 | - handle: handle.clone(), | ||
| 273 | - seq: self.seq.fetch_add(1, Ordering::SeqCst), | ||
| 274 | - dir: None, | ||
| 275 | - frozen: None, | ||
| 276 | - }); | ||
| 277 | - self.kick.notify_one(); | ||
| 278 | - Registration { | ||
| 279 | - handle, | ||
| 280 | - owner: self.clone(), | ||
| 281 | - } | ||
| 282 | - } | ||
| 283 | - | ||
| 284 | - fn remove(&self, handle: &Arc<JobHandle>) { | ||
| 285 | - self.lock() | ||
| 286 | - .entries | ||
| 287 | - .retain(|e| !Arc::ptr_eq(&e.handle, handle)); | ||
| 288 | - self.kick.notify_one(); | ||
| 289 | - } | ||
| 290 | - | ||
| 291 | - pub fn headroom(&self) -> Option<u64> { | ||
| 292 | - let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget()); | ||
| 293 | - Some(max.saturating_sub(box_usage(&self.dir)?)) | ||
| 294 | - } | ||
| 295 | - | ||
| 296 | - pub fn gate(&self) -> Gate { | ||
| 297 | - self.lock().gate | ||
| 298 | - } | ||
| 299 | - | ||
| 300 | - pub async fn wait_open(&self) { | ||
| 301 | - loop { | ||
| 302 | - let notified = self.changed.notified(); | ||
| 303 | - tokio::pin!(notified); | ||
| 304 | - notified.as_mut().enable(); | ||
| 305 | - if self.lock().gate.open() { | ||
| 306 | - return; | ||
| 307 | - } | ||
| 308 | - notified.await; | ||
| 309 | - } | ||
| 310 | - } | ||
| 311 | 13 | ||
| 312 | - async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) { | 14 | +pub fn start_box(size: u64) -> Result<PathBuf, String> { |
| 313 | - let mut recheck: Option<tokio::time::Instant> = None; | 15 | + let base = job_cgroup_base().map_err(|e| e.to_string())?; |
| 314 | - loop { | 16 | + let parent = Path::new(CGROUP_ROOT).join(base.strip_prefix("/").unwrap_or(&base)); |
| 315 | - let cause = tokio::select! { | 17 | + create_box(&parent, size) |
| 316 | - () = shutdown.cancelled() => return, | ||
| 317 | - () = tokio::time::sleep_until(recheck.unwrap_or_else(tokio::time::Instant::now)), | ||
| 318 | - if recheck.is_some() => Cause::Jobs, | ||
| 319 | - cause = watcher.rx.recv() => { | ||
| 320 | - let Some(cause) = cause else { | ||
| 321 | - tracing::warn!("memory control stopped, the watcher thread ended"); | ||
| 322 | - return; | ||
| 323 | - }; | ||
| 324 | - cause | ||
| 325 | - } | ||
| 326 | - () = self.kick.notified() => Cause::Jobs, | ||
| 327 | - }; | ||
| 328 | - let this = self.clone(); | ||
| 329 | - if let Err(e) = tokio::task::spawn_blocking(move || this.settle(cause)).await { | ||
| 330 | - tracing::error!("memory control pass panicked: {e}"); | ||
| 331 | - } | ||
| 332 | - recheck = self | ||
| 333 | - .lock() | ||
| 334 | - .gate | ||
| 335 | - .hot | ||
| 336 | - .then(|| tokio::time::Instant::now() + PRESSURE_COOLDOWN); | ||
| 337 | - } | ||
| 338 | - } | ||
| 339 | - | ||
| 340 | - fn settle(&self, cause: Cause) { | ||
| 341 | - let mut state = self.lock(); | ||
| 342 | - let mut taken: Vec<PathBuf> = state.entries.iter().filter_map(|e| e.dir.clone()).collect(); | ||
| 343 | - for entry in &mut state.entries { | ||
| 344 | - if entry.dir.is_none() | ||
| 345 | - && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id, &taken) | ||
| 346 | - { | ||
| 347 | - taken.push(dir.clone()); | ||
| 348 | - let _ = fs::write(dir.join("memory.oom.group"), "1"); | ||
| 349 | - entry.dir = Some(dir); | ||
| 350 | - } | ||
| 351 | - } | ||
| 352 | - let mut parked_now = false; | ||
| 353 | - if cause == Cause::Pressure { | ||
| 354 | - let live: Vec<usize> = (0..state.entries.len()) | ||
| 355 | - .filter(|&i| is_live(&state.entries[i])) | ||
| 356 | - .collect(); | ||
| 357 | - let seqs: Vec<u64> = live.iter().map(|&i| state.entries[i].seq).collect(); | ||
| 358 | - if let Some(pick) = pick_victim(&seqs) { | ||
| 359 | - let victim = live[pick]; | ||
| 360 | - let waiting_for = live | ||
| 361 | - .iter() | ||
| 362 | - .filter(|&&i| i != victim) | ||
| 363 | - .min_by_key(|&&i| state.entries[i].seq) | ||
| 364 | - .map(|&i| state.entries[i].handle.name.clone()) | ||
| 365 | - .unwrap_or_default(); | ||
| 366 | - park(&mut state.entries[victim], &waiting_for); | ||
| 367 | - parked_now = true; | ||
| 368 | - } | ||
| 369 | - } | ||
| 370 | - if !parked_now { | ||
| 371 | - self.thaw_one(&mut state); | ||
| 372 | - } | ||
| 373 | - let unfrozen = state.entries.iter().filter(|e| is_live(e)).count(); | ||
| 374 | - let high = high_value(unfrozen, self.budget()); | ||
| 375 | - if state.high != Some(high) { | ||
| 376 | - let text = high.map_or_else(|| "max".to_owned(), |b| b.to_string()); | ||
| 377 | - match fs::write(self.dir.join("memory.high"), text) { | ||
| 378 | - Ok(()) => state.high = Some(high), | ||
| 379 | - Err(e) => tracing::warn!("cannot set memory.high of the box: {e}"), | ||
| 380 | - } | ||
| 381 | - } | ||
| 382 | - let over_high = high.is_some_and(|h| box_usage(&self.dir).is_some_and(|u| u >= h)); | ||
| 383 | - state.gate = Gate { | ||
| 384 | - frozen: state.entries.iter().filter(|e| e.frozen.is_some()).count(), | ||
| 385 | - hot: hot_after(cause, over_high, state.entries.len()), | ||
| 386 | - }; | ||
| 387 | - drop(state); | ||
| 388 | - self.changed.notify_waiters(); | ||
| 389 | - } | ||
| 390 | - | ||
| 391 | - fn thaw_one(&self, state: &mut State) { | ||
| 392 | - let parked: Vec<(usize, Parked)> = state | ||
| 393 | - .entries | ||
| 394 | - .iter() | ||
| 395 | - .enumerate() | ||
| 396 | - .filter_map(|(i, e)| { | ||
| 397 | - let frozen = e.frozen.as_ref()?; | ||
| 398 | - let swap = e.dir.as_deref().and_then(job_swap).unwrap_or(frozen.swap); | ||
| 399 | - Some((i, Parked { seq: e.seq, swap })) | ||
| 400 | - }) | ||
| 401 | - .collect(); | ||
| 402 | - let running = state.entries.iter().filter(|e| is_live(e)).count(); | ||
| 403 | - let below_high = high_value(running + 1, self.budget()).unwrap_or(0); | ||
| 404 | - let headroom = box_usage(&self.dir) | ||
| 405 | - .map_or(0, |usage| below_high.saturating_sub(usage)) | ||
| 406 | - .saturating_sub(HIGH_MARGIN_MIN); | ||
| 407 | - let list: Vec<Parked> = parked.iter().map(|(_, p)| *p).collect(); | ||
| 408 | - let Some(pick) = pick_thaw(&list, running, headroom) else { | ||
| 409 | - return; | ||
| 410 | - }; | ||
| 411 | - let entry = &mut state.entries[parked[pick].0]; | ||
| 412 | - let Some(dir) = entry.dir.clone() else { | ||
| 413 | - return; | ||
| 414 | - }; | ||
| 415 | - let _ = fs::write(dir.join("memory.swap.max"), "0"); | ||
| 416 | - if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") { | ||
| 417 | - tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}"); | ||
| 418 | - return; | ||
| 419 | - } | ||
| 420 | - entry.frozen = None; | ||
| 421 | - let lasted = entry.handle.resume(); | ||
| 422 | - entry | ||
| 423 | - .handle | ||
| 424 | - .log_line(&format!("resumed after {}", format_duration(lasted))); | ||
| 425 | - tracing::info!(job_id = %entry.handle.id, "job resumed"); | ||
| 426 | - } | ||
| 427 | } | 18 | } |
| 428 | 19 | ||
| 429 | -fn is_live(entry: &Entry) -> bool { | 20 | +pub fn create_box(parent: &Path, size: u64) -> Result<PathBuf, String> { |
| 430 | - entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst) | ||
| 431 | -} | ||
| 432 | - | ||
| 433 | -fn park(entry: &mut Entry, waiting_for: &str) { | ||
| 434 | - let Some(dir) = entry.dir.clone() else { | ||
| 435 | - return; | ||
| 436 | - }; | ||
| 437 | - let handle = entry.handle.clone(); | ||
| 438 | - let before = read_u64(&dir, "memory.current").unwrap_or(0); | ||
| 439 | - let anon = stat_field(&dir, "anon").unwrap_or(before); | ||
| 440 | - let swap_free = swap_free_bytes(); | ||
| 441 | - if swap_free.is_some_and(|free| free < anon) { | ||
| 442 | - give_back(entry, "the host has no swap room for it"); | ||
| 443 | - return; | ||
| 444 | - } | ||
| 445 | - let _ = fs::write(dir.join("memory.swap.max"), "max"); | ||
| 446 | - if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") { | ||
| 447 | - tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}"); | ||
| 448 | - give_back(entry, "it cannot be frozen"); | ||
| 449 | - return; | ||
| 450 | - } | ||
| 451 | - handle.pause(); | ||
| 452 | - handle.log_line(&format!( | ||
| 453 | - "paused: memory pressure, waiting for {waiting_for}" | ||
| 454 | - )); | ||
| 455 | - let mut after = before; | ||
| 456 | - for _ in 0..RECLAIM_ATTEMPTS { | ||
| 457 | - reclaim(&dir, before); | ||
| 458 | - after = read_u64(&dir, "memory.current").unwrap_or(before); | ||
| 459 | - if after <= before / 2 { | ||
| 460 | - break; | ||
| 461 | - } | ||
| 462 | - } | ||
| 463 | - if after > before / 2 { | ||
| 464 | - let _ = fs::write(dir.join("cgroup.freeze"), "0"); | ||
| 465 | - handle.resume(); | ||
| 466 | - give_back(entry, "its memory would not go to swap"); | ||
| 467 | - return; | ||
| 468 | - } | ||
| 469 | - let swap = job_swap(&dir).unwrap_or(0); | ||
| 470 | - handle.log_line(&format!("parked {} MiB in swap", swap >> 20)); | ||
| 471 | - tracing::info!(job_id = %handle.id, swap, "job parked in swap"); | ||
| 472 | - entry.frozen = Some(Frozen { swap }); | ||
| 473 | -} | ||
| 474 | - | ||
| 475 | -fn reclaim(dir: &Path, bytes: u64) { | ||
| 476 | - let file = dir.join("memory.reclaim"); | ||
| 477 | - match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) { | ||
| 478 | - Err(e) if e.kind() == io::ErrorKind::InvalidInput => { | ||
| 479 | - let _ = fs::write(&file, bytes.to_string()); | ||
| 480 | - } | ||
| 481 | - _ => {} | ||
| 482 | - } | ||
| 483 | -} | ||
| 484 | - | ||
| 485 | -fn give_back(entry: &mut Entry, why: &str) { | ||
| 486 | - entry.handle.requeued.store(true, Ordering::SeqCst); | ||
| 487 | - entry.handle.log_line(&format!( | ||
| 488 | - "memory pressure and {why}: stopping this job to run it again later" | ||
| 489 | - )); | ||
| 490 | - tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it"); | ||
| 491 | - if let Some(dir) = &entry.dir { | ||
| 492 | - let _ = fs::write(dir.join("cgroup.freeze"), "0"); | ||
| 493 | - kill_cgroup(dir); | ||
| 494 | - } | ||
| 495 | -} | ||
| 496 | - | ||
| 497 | -fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathBuf> { | ||
| 498 | - let prefix = format!("forge-job-{job_id}-"); | ||
| 499 | - fs::read_dir(box_dir) | ||
| 500 | - .ok()? | ||
| 501 | - .flatten() | ||
| 502 | - .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix)) | ||
| 503 | - .map(|e| e.path()) | ||
| 504 | - .find(|path| !taken.contains(path)) | ||
| 505 | -} | ||
| 506 | - | ||
| 507 | -fn read_u64(dir: &Path, file: &str) -> Option<u64> { | ||
| 508 | - fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok() | ||
| 509 | -} | ||
| 510 | - | ||
| 511 | -fn stat_field(dir: &Path, key: &str) -> Option<u64> { | ||
| 512 | - let text = fs::read_to_string(dir.join("memory.stat")).ok()?; | ||
| 513 | - field_u64(&text, key) | ||
| 514 | -} | ||
| 515 | - | ||
| 516 | -fn job_swap(dir: &Path) -> Option<u64> { | ||
| 517 | - read_u64(dir, "memory.swap.current") | ||
| 518 | -} | ||
| 519 | - | ||
| 520 | -fn box_usage(dir: &Path) -> Option<u64> { | ||
| 521 | - let current = read_u64(dir, "memory.current")?; | ||
| 522 | - Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0))) | ||
| 523 | -} | ||
| 524 | - | ||
| 525 | -fn swap_free_bytes() -> Option<u64> { | ||
| 526 | - let text = fs::read_to_string("/proc/meminfo").ok()?; | ||
| 527 | - let line = text.lines().find(|l| l.starts_with("SwapFree:"))?; | ||
| 528 | - line.split_whitespace() | ||
| 529 | - .nth(1)? | ||
| 530 | - .parse::<u64>() | ||
| 531 | - .ok()? | ||
| 532 | - .checked_mul(1024) | ||
| 533 | -} | ||
| 534 | - | ||
| 535 | -fn format_duration(d: Duration) -> String { | ||
| 536 | - let secs = d.as_secs(); | ||
| 537 | - if secs >= 60 { | ||
| 538 | - format!("{}m {}s", secs / 60, secs % 60) | ||
| 539 | - } else { | ||
| 540 | - format!("{secs}s") | ||
| 541 | - } | ||
| 542 | -} | ||
| 543 | - | ||
| 544 | -pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> { | ||
| 545 | let dir = parent.join(BOX_NAME); | 21 | let dir = parent.join(BOX_NAME); |
| 546 | match fs::create_dir(&dir) { | 22 | match fs::create_dir(&dir) { |
| 547 | Ok(()) => {} | 23 | Ok(()) => {} |
| @@ -551,12 +27,10 @@ pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> { | |||
| 551 | remove_leftovers(&dir); | 27 | remove_leftovers(&dir); |
| 552 | enable_controllers(parent)?; | 28 | enable_controllers(parent)?; |
| 553 | enable_controllers(&dir)?; | 29 | enable_controllers(&dir)?; |
| 554 | - let set = |file: &str, value: String| { | 30 | + let _ = fs::write(dir.join("memory.high"), "max"); |
| 555 | - fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}")) | 31 | + let _ = fs::write(dir.join("memory.swap.max"), "max"); |
| 556 | - }; | 32 | + fs::write(dir.join("memory.max"), size.to_string()) |
| 557 | - set("memory.max", budget.to_string())?; | 33 | + .map_err(|e| format!("cannot set memory.max on the box: {e}"))?; |
| 558 | - set("memory.swap.max", budget.to_string())?; | ||
| 559 | - set("memory.high", "max".to_owned())?; | ||
| 560 | Ok(dir) | 34 | Ok(dir) |
| 561 | } | 35 | } |
| 562 | 36 | ||
| @@ -569,7 +43,6 @@ fn remove_leftovers(box_dir: &Path) { | |||
| 569 | if !path.is_dir() { | 43 | if !path.is_dir() { |
| 570 | continue; | 44 | continue; |
| 571 | } | 45 | } |
| 572 | - let _ = fs::write(path.join("cgroup.freeze"), "0"); | ||
| 573 | kill_cgroup(&path); | 46 | kill_cgroup(&path); |
| 574 | for _ in 0..LEFTOVER_POLLS { | 47 | for _ in 0..LEFTOVER_POLLS { |
| 575 | if fs::remove_dir(&path).is_ok() || !path.exists() { | 48 | if fs::remove_dir(&path).is_ok() || !path.exists() { |
| @@ -601,312 +74,12 @@ fn enable_controllers(dir: &Path) -> Result<(), String> { | |||
| 601 | }) | 74 | }) |
| 602 | } | 75 | } |
| 603 | 76 | ||
| 604 | -struct Watcher { | ||
| 605 | - rx: mpsc::UnboundedReceiver<Cause>, | ||
| 606 | - psi_armed: bool, | ||
| 607 | - _stop: OwnedFd, | ||
| 608 | -} | ||
| 609 | - | ||
| 610 | -impl Watcher { | ||
| 611 | - fn open(box_dir: &Path) -> Result<Self, String> { | ||
| 612 | - let inotify = Inotify::init(InitFlags::IN_NONBLOCK | InitFlags::IN_CLOEXEC) | ||
| 613 | - .map_err(|e| format!("inotify: {e}"))?; | ||
| 614 | - inotify | ||
| 615 | - .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY) | ||
| 616 | - .map_err(|e| format!("watching memory.events: {e}"))?; | ||
| 617 | - inotify | ||
| 618 | - .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE) | ||
| 619 | - .map_err(|e| format!("watching the box: {e}"))?; | ||
| 620 | - let psi = match arm_psi(box_dir) { | ||
| 621 | - Ok(file) => Some(file), | ||
| 622 | - Err(e) => { | ||
| 623 | - tracing::warn!("no PSI trigger on the box, using memory.events only: {e}"); | ||
| 624 | - None | ||
| 625 | - } | ||
| 626 | - }; | ||
| 627 | - let psi_armed = psi.is_some(); | ||
| 628 | - let (stop_rx, stop_tx) = pipe().map_err(|e| format!("stop pipe: {e}"))?; | ||
| 629 | - let (tx, rx) = mpsc::unbounded_channel(); | ||
| 630 | - let events_path = box_dir.join("memory.events"); | ||
| 631 | - std::thread::Builder::new() | ||
| 632 | - .name("forge-memory-watch".to_owned()) | ||
| 633 | - .spawn(move || watch_thread(&inotify, psi, &stop_rx, &events_path, &tx)) | ||
| 634 | - .map_err(|e| format!("watcher thread: {e}"))?; | ||
| 635 | - Ok(Self { | ||
| 636 | - rx, | ||
| 637 | - psi_armed, | ||
| 638 | - _stop: stop_tx, | ||
| 639 | - }) | ||
| 640 | - } | ||
| 641 | -} | ||
| 642 | - | ||
| 643 | -fn watch_thread( | ||
| 644 | - inotify: &Inotify, | ||
| 645 | - mut psi: Option<File>, | ||
| 646 | - stop: &OwnedFd, | ||
| 647 | - events_path: &Path, | ||
| 648 | - tx: &mpsc::UnboundedSender<Cause>, | ||
| 649 | -) { | ||
| 650 | - let read_high = || fs::read_to_string(events_path).map(|t| parse_high(&t)).ok(); | ||
| 651 | - let mut last_high = read_high().unwrap_or(0); | ||
| 652 | - loop { | ||
| 653 | - let (stopped, inotify_ready, psi_ready, psi_broken) = { | ||
| 654 | - let mut fds = vec![ | ||
| 655 | - PollFd::new(inotify.as_fd(), PollFlags::POLLIN), | ||
| 656 | - PollFd::new(stop.as_fd(), PollFlags::POLLIN), | ||
| 657 | - ]; | ||
| 658 | - if let Some(file) = &psi { | ||
| 659 | - fds.push(PollFd::new(file.as_fd(), PollFlags::POLLPRI)); | ||
| 660 | - } | ||
| 661 | - match poll(&mut fds, PollTimeout::NONE) { | ||
| 662 | - Ok(_) => {} | ||
| 663 | - Err(Errno::EINTR) => continue, | ||
| 664 | - Err(e) => { | ||
| 665 | - tracing::warn!("memory control stopped, poll failed: {e}"); | ||
| 666 | - return; | ||
| 667 | - } | ||
| 668 | - } | ||
| 669 | - let flags = |i: usize| { | ||
| 670 | - fds.get(i) | ||
| 671 | - .and_then(PollFd::revents) | ||
| 672 | - .unwrap_or_else(PollFlags::empty) | ||
| 673 | - }; | ||
| 674 | - ( | ||
| 675 | - !flags(1).is_empty(), | ||
| 676 | - flags(0).contains(PollFlags::POLLIN), | ||
| 677 | - flags(2).contains(PollFlags::POLLPRI), | ||
| 678 | - flags(2).intersects(PollFlags::POLLERR | PollFlags::POLLNVAL), | ||
| 679 | - ) | ||
| 680 | - }; | ||
| 681 | - if stopped { | ||
| 682 | - return; | ||
| 683 | - } | ||
| 684 | - let mut cause = None; | ||
| 685 | - if inotify_ready { | ||
| 686 | - let mut modified = false; | ||
| 687 | - loop { | ||
| 688 | - match inotify.read_events() { | ||
| 689 | - Ok(batch) => { | ||
| 690 | - modified |= batch | ||
| 691 | - .iter() | ||
| 692 | - .any(|e| e.mask.contains(AddWatchFlags::IN_MODIFY)); | ||
| 693 | - } | ||
| 694 | - Err(Errno::EAGAIN) => break, | ||
| 695 | - Err(e) => { | ||
| 696 | - tracing::warn!("cannot read inotify events: {e}"); | ||
| 697 | - break; | ||
| 698 | - } | ||
| 699 | - } | ||
| 700 | - } | ||
| 701 | - let high = read_high().unwrap_or(last_high); | ||
| 702 | - let moved = modified && high > last_high; | ||
| 703 | - last_high = high; | ||
| 704 | - cause = Some(if moved { Cause::Pressure } else { Cause::Jobs }); | ||
| 705 | - } | ||
| 706 | - if psi_broken { | ||
| 707 | - tracing::warn!("memory pressure trigger failed, using memory.events only"); | ||
| 708 | - psi = None; | ||
| 709 | - } else if psi_ready { | ||
| 710 | - cause = Some(Cause::Pressure); | ||
| 711 | - } | ||
| 712 | - if let Some(cause) = cause | ||
| 713 | - && tx.send(cause).is_err() | ||
| 714 | - { | ||
| 715 | - return; | ||
| 716 | - } | ||
| 717 | - } | ||
| 718 | -} | ||
| 719 | - | ||
| 720 | -fn arm_psi(box_dir: &Path) -> io::Result<File> { | ||
| 721 | - let mut file = OpenOptions::new() | ||
| 722 | - .read(true) | ||
| 723 | - .write(true) | ||
| 724 | - .custom_flags(nix::libc::O_NONBLOCK) | ||
| 725 | - .open(box_dir.join("memory.pressure"))?; | ||
| 726 | - file.write_all(format!("{PSI_TRIGGER}\0").as_bytes())?; | ||
| 727 | - Ok(file) | ||
| 728 | -} | ||
| 729 | - | ||
| 730 | #[cfg(test)] | 77 | #[cfg(test)] |
| 731 | mod tests { | 78 | mod tests { |
| 732 | use super::*; | 79 | use super::*; |
| 733 | 80 | ||
| 734 | const GIB: u64 = 1 << 30; | 81 | const GIB: u64 = 1 << 30; |
| 735 | 82 | ||
| 736 | - #[test] | ||
| 737 | - fn parses_the_high_counter() { | ||
| 738 | - let text = "low 0\nhigh 8\nmax 0\noom 0\noom_kill 0\n"; | ||
| 739 | - assert_eq!(parse_high(text), 8); | ||
| 740 | - assert_eq!(parse_high("low 0\nmax 1\n"), 0); | ||
| 741 | - assert_eq!(parse_high(""), 0); | ||
| 742 | - assert_eq!(parse_high("high x\n"), 0); | ||
| 743 | - } | ||
| 744 | - | ||
| 745 | - #[test] | ||
| 746 | - fn resize_follows_a_changed_budget() { | ||
| 747 | - let (_tmp, pressure) = fake_box(2 * GIB); | ||
| 748 | - fs::write(pressure.dir.join("memory.swap.max"), "0").expect("swap"); | ||
| 749 | - pressure.resize(3 * GIB); | ||
| 750 | - assert_eq!(pressure.budget(), 3 * GIB); | ||
| 751 | - assert_eq!(read_u64(&pressure.dir, "memory.max"), Some(3 * GIB)); | ||
| 752 | - assert_eq!(read_u64(&pressure.dir, "memory.swap.max"), Some(3 * GIB)); | ||
| 753 | - assert_eq!(pressure.lock().high, None); | ||
| 754 | - } | ||
| 755 | - | ||
| 756 | - #[test] | ||
| 757 | - fn high_applies_only_to_two_or_more_unfrozen_jobs() { | ||
| 758 | - assert_eq!(high_value(0, 6 * GIB), None); | ||
| 759 | - assert_eq!(high_value(1, 6 * GIB), None); | ||
| 760 | - assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); | ||
| 761 | - assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); | ||
| 762 | - assert_eq!(high_value(2, 256 << 20), Some(128 << 20)); | ||
| 763 | - } | ||
| 764 | - | ||
| 765 | - #[test] | ||
| 766 | - fn victim_is_the_youngest_with_a_partner() { | ||
| 767 | - assert_eq!(pick_victim(&[]), None); | ||
| 768 | - assert_eq!(pick_victim(&[1]), None); | ||
| 769 | - assert_eq!(pick_victim(&[1, 2]), Some(1)); | ||
| 770 | - assert_eq!(pick_victim(&[5, 2, 9]), Some(2)); | ||
| 771 | - } | ||
| 772 | - | ||
| 773 | - #[test] | ||
| 774 | - fn thaw_is_the_oldest_when_there_is_room_or_nothing_runs() { | ||
| 775 | - let parked = [ | ||
| 776 | - Parked { seq: 7, swap: GIB }, | ||
| 777 | - Parked { | ||
| 778 | - seq: 3, | ||
| 779 | - swap: 2 * GIB, | ||
| 780 | - }, | ||
| 781 | - ]; | ||
| 782 | - assert_eq!(pick_thaw(&[], 0, 10 * GIB), None); | ||
| 783 | - assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1)); | ||
| 784 | - assert_eq!(pick_thaw(&parked, 1, GIB), None); | ||
| 785 | - assert_eq!(pick_thaw(&parked, 0, 0), Some(1)); | ||
| 786 | - } | ||
| 787 | - | ||
| 788 | - #[test] | ||
| 789 | - fn gate_closes_for_parked_jobs_and_pressure() { | ||
| 790 | - assert!(Gate::default().open()); | ||
| 791 | - assert!( | ||
| 792 | - !Gate { | ||
| 793 | - frozen: 1, | ||
| 794 | - hot: false | ||
| 795 | - } | ||
| 796 | - .open() | ||
| 797 | - ); | ||
| 798 | - assert!( | ||
| 799 | - !Gate { | ||
| 800 | - frozen: 0, | ||
| 801 | - hot: true | ||
| 802 | - } | ||
| 803 | - .open() | ||
| 804 | - ); | ||
| 805 | - assert!(hot_after(Cause::Pressure, false, 1)); | ||
| 806 | - assert!(!hot_after(Cause::Jobs, false, 1)); | ||
| 807 | - assert!(hot_after(Cause::Jobs, true, 1)); | ||
| 808 | - assert!(!hot_after(Cause::Pressure, false, 0)); | ||
| 809 | - } | ||
| 810 | - | ||
| 811 | - fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) { | ||
| 812 | - let tmp = tempfile::tempdir().expect("tempdir"); | ||
| 813 | - let dir = tmp.path().to_path_buf(); | ||
| 814 | - fs::write(dir.join("memory.max"), budget.to_string()).expect("max"); | ||
| 815 | - fs::write(dir.join("memory.current"), "0").expect("current"); | ||
| 816 | - (tmp, Arc::new(Pressure::at(dir, budget))) | ||
| 817 | - } | ||
| 818 | - | ||
| 819 | - fn fake_job(box_dir: &Path, id: &str, current: u64) -> PathBuf { | ||
| 820 | - let dir = box_dir.join(format!("forge-job-{id}-1")); | ||
| 821 | - fs::create_dir(&dir).expect("job dir"); | ||
| 822 | - fs::write(dir.join("memory.current"), current.to_string()).expect("current"); | ||
| 823 | - fs::write(dir.join("memory.stat"), format!("anon {current}\n")).expect("stat"); | ||
| 824 | - dir | ||
| 825 | - } | ||
| 826 | - | ||
| 827 | - #[test] | ||
| 828 | - fn settle_sets_high_for_two_jobs_and_relaxes_it_for_one() { | ||
| 829 | - let (tmp, pressure) = fake_box(6 * GIB); | ||
| 830 | - let (tx, _rx) = mpsc::channel(8); | ||
| 831 | - let a = pressure.register("a", "build", tx.clone()); | ||
| 832 | - let b = pressure.register("b", "test", tx); | ||
| 833 | - fake_job(tmp.path(), "a", GIB); | ||
| 834 | - fake_job(tmp.path(), "b", GIB); | ||
| 835 | - pressure.settle(Cause::Jobs); | ||
| 836 | - let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); | ||
| 837 | - assert_eq!(high, (6 * GIB - HIGH_MARGIN_MIN).to_string()); | ||
| 838 | - drop(b); | ||
| 839 | - pressure.settle(Cause::Jobs); | ||
| 840 | - let high = fs::read_to_string(tmp.path().join("memory.high")).expect("high"); | ||
| 841 | - assert_eq!(high, "max"); | ||
| 842 | - assert!(!a.requeued()); | ||
| 843 | - } | ||
| 844 | - | ||
| 845 | - #[test] | ||
| 846 | - fn pressure_with_a_lone_job_does_nothing_but_close_the_gate() { | ||
| 847 | - let (tmp, pressure) = fake_box(6 * GIB); | ||
| 848 | - let (tx, mut rx) = mpsc::channel(8); | ||
| 849 | - let a = pressure.register("a", "build", tx); | ||
| 850 | - let dir = fake_job(tmp.path(), "a", GIB); | ||
| 851 | - pressure.settle(Cause::Pressure); | ||
| 852 | - assert!(!a.requeued()); | ||
| 853 | - assert!(!dir.join("cgroup.freeze").exists()); | ||
| 854 | - assert!(rx.try_recv().is_err()); | ||
| 855 | - assert!(!pressure.lock().gate.open()); | ||
| 856 | - drop(a); | ||
| 857 | - pressure.settle(Cause::Jobs); | ||
| 858 | - assert!(pressure.lock().gate.open()); | ||
| 859 | - } | ||
| 860 | - | ||
| 861 | - #[test] | ||
| 862 | - fn a_job_that_cannot_be_parked_is_killed_for_requeue() { | ||
| 863 | - let (tmp, pressure) = fake_box(6 * GIB); | ||
| 864 | - let (tx_a, _rx_a) = mpsc::channel(8); | ||
| 865 | - let (tx_b, mut rx_b) = mpsc::channel(8); | ||
| 866 | - let a = pressure.register("a", "build", tx_a); | ||
| 867 | - let b = pressure.register("b", "test", tx_b); | ||
| 868 | - fake_job(tmp.path(), "a", 2 * GIB); | ||
| 869 | - let dir_b = fake_job(tmp.path(), "b", 2 * GIB); | ||
| 870 | - fs::write(dir_b.join("memory.stat"), "anon 0\n").expect("stat"); | ||
| 871 | - pressure.settle(Cause::Jobs); | ||
| 872 | - pressure.settle(Cause::Pressure); | ||
| 873 | - assert!(b.requeued()); | ||
| 874 | - assert!(!a.requeued()); | ||
| 875 | - assert_eq!( | ||
| 876 | - fs::read_to_string(dir_b.join("cgroup.kill")).expect("kill"), | ||
| 877 | - "1" | ||
| 878 | - ); | ||
| 879 | - let mut lines = String::new(); | ||
| 880 | - while let Ok(bytes) = rx_b.try_recv() { | ||
| 881 | - lines.push_str(&String::from_utf8_lossy(&bytes)); | ||
| 882 | - } | ||
| 883 | - assert!(lines.contains("paused: memory pressure, waiting for build")); | ||
| 884 | - assert!(lines.contains("run it again later")); | ||
| 885 | - assert_eq!( | ||
| 886 | - fs::read_to_string(tmp.path().join("memory.high")).expect("high"), | ||
| 887 | - "max" | ||
| 888 | - ); | ||
| 889 | - } | ||
| 890 | - | ||
| 891 | - #[test] | ||
| 892 | - fn a_registration_tracks_pause_time_and_drops_its_log() { | ||
| 893 | - let (_tmp, pressure) = fake_box(GIB); | ||
| 894 | - let (tx, mut rx) = mpsc::channel(8); | ||
| 895 | - let reg = pressure.register("a", "build", tx); | ||
| 896 | - assert_eq!(reg.handle.paused(), Duration::ZERO); | ||
| 897 | - reg.handle.pause(); | ||
| 898 | - std::thread::sleep(Duration::from_millis(5)); | ||
| 899 | - assert!(reg.handle.paused() > Duration::ZERO); | ||
| 900 | - let lasted = reg.handle.resume(); | ||
| 901 | - assert!(lasted > Duration::ZERO); | ||
| 902 | - assert!(reg.handle.paused() >= lasted); | ||
| 903 | - drop(reg); | ||
| 904 | - assert!(matches!( | ||
| 905 | - rx.try_recv(), | ||
| 906 | - Err(mpsc::error::TryRecvError::Disconnected) | ||
| 907 | - )); | ||
| 908 | - } | ||
| 909 | - | ||
| 910 | #[test] | 83 | #[test] |
| 911 | fn create_box_enables_controllers_and_sets_limits() { | 84 | fn create_box_enables_controllers_and_sets_limits() { |
| 912 | let tmp = tempfile::tempdir().expect("tempdir"); | 85 | let tmp = tempfile::tempdir().expect("tempdir"); |
| @@ -920,221 +93,10 @@ mod tests { | |||
| 920 | fs::read_to_string(dir.join("memory.max")).expect("max"), | 93 | fs::read_to_string(dir.join("memory.max")).expect("max"), |
| 921 | (4 * GIB).to_string() | 94 | (4 * GIB).to_string() |
| 922 | ); | 95 | ); |
| 923 | - assert_eq!( | ||
| 924 | - fs::read_to_string(dir.join("memory.swap.max")).expect("swap"), | ||
| 925 | - (4 * GIB).to_string() | ||
| 926 | - ); | ||
| 927 | - assert_eq!( | ||
| 928 | - fs::read_to_string(dir.join("memory.high")).expect("high"), | ||
| 929 | - "max" | ||
| 930 | - ); | ||
| 931 | assert_eq!( | 96 | assert_eq!( |
| 932 | fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"), | 97 | fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"), |
| 933 | "+cpu" | 98 | "+cpu" |
| 934 | ); | 99 | ); |
| 935 | assert!(create_box(parent, 4 * GIB).is_ok()); | 100 | assert!(create_box(parent, 4 * GIB).is_ok()); |
| 936 | } | 101 | } |
| 937 | - | ||
| 938 | - #[tokio::test] | ||
| 939 | - async fn wait_open_returns_at_once_on_an_open_gate_and_wakes_on_change() { | ||
| 940 | - let (_tmp, pressure) = fake_box(GIB); | ||
| 941 | - pressure.wait_open().await; | ||
| 942 | - pressure.lock().gate.hot = true; | ||
| 943 | - let waiter = { | ||
| 944 | - let p = pressure.clone(); | ||
| 945 | - tokio::spawn(async move { p.wait_open().await }) | ||
| 946 | - }; | ||
| 947 | - tokio::task::yield_now().await; | ||
| 948 | - assert!(!waiter.is_finished()); | ||
| 949 | - pressure.lock().gate.hot = false; | ||
| 950 | - pressure.changed.notify_waiters(); | ||
| 951 | - tokio::time::timeout(Duration::from_secs(5), waiter) | ||
| 952 | - .await | ||
| 953 | - .expect("woken") | ||
| 954 | - .expect("join"); | ||
| 955 | - } | ||
| 956 | - | ||
| 957 | - #[tokio::test] | ||
| 958 | - #[ignore = "needs delegated cgroup v2 controllers"] | ||
| 959 | - async fn real_box_starts_and_reports_headroom() { | ||
| 960 | - let shutdown = CancellationToken::new(); | ||
| 961 | - let Some(pressure) = Pressure::start(2 * GIB, shutdown.clone()).await else { | ||
| 962 | - eprintln!("no delegated memory controller, skipping"); | ||
| 963 | - return; | ||
| 964 | - }; | ||
| 965 | - assert!(pressure.headroom().is_some()); | ||
| 966 | - pressure.wait_open().await; | ||
| 967 | - shutdown.cancel(); | ||
| 968 | - tokio::time::sleep(Duration::from_millis(100)).await; | ||
| 969 | - let _ = fs::remove_dir(&pressure.dir); | ||
| 970 | - } | ||
| 971 | - | ||
| 972 | - const ALLOCATOR: &str = r#" | ||
| 973 | -import sys, time, hashlib | ||
| 974 | -mib = int(sys.argv[1]); step = 50 | ||
| 975 | -sys.stdin.readline() | ||
| 976 | -chunks = []; sums = [] | ||
| 977 | -done = 0 | ||
| 978 | -while done < mib: | ||
| 979 | - n = min(step, mib - done) | ||
| 980 | - pat = bytes(((done + j * 7) % 251) for j in range(4096)) | ||
| 981 | - c = bytearray(pat * (n * 256)) | ||
| 982 | - chunks.append(c); sums.append(hashlib.sha256(c).hexdigest()) | ||
| 983 | - done += n | ||
| 984 | - time.sleep(0.25) | ||
| 985 | -# hold the memory for a while, then verify every chunk | ||
| 986 | -time.sleep(float(sys.argv[2])) | ||
| 987 | -for c, s in zip(chunks, sums): | ||
| 988 | - if hashlib.sha256(c).hexdigest() != s: | ||
| 989 | - print("CHECKSUM MISMATCH"); sys.exit(3) | ||
| 990 | -print("ok") | ||
| 991 | -"#; | ||
| 992 | - | ||
| 993 | - fn mib(bytes: Option<u64>) -> u64 { | ||
| 994 | - bytes.unwrap_or(0) >> 20 | ||
| 995 | - } | ||
| 996 | - | ||
| 997 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 998 | - #[ignore = "needs delegated cgroup v2 controllers, swap and python3"] | ||
| 999 | - async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() { | ||
| 1000 | - use std::process::Stdio; | ||
| 1001 | - use tokio::io::AsyncWriteExt; | ||
| 1002 | - use tokio::process::Command; | ||
| 1003 | - | ||
| 1004 | - let started = Instant::now(); | ||
| 1005 | - let shutdown = CancellationToken::new(); | ||
| 1006 | - let Some(pressure) = Pressure::start(GIB, shutdown.clone()).await else { | ||
| 1007 | - eprintln!("no delegated memory controller, skipping"); | ||
| 1008 | - return; | ||
| 1009 | - }; | ||
| 1010 | - let probe = Watcher::open(&pressure.dir).expect("watcher"); | ||
| 1011 | - let psi_armed = probe.psi_armed; | ||
| 1012 | - drop(probe); | ||
| 1013 | - eprintln!("PSI trigger armed: {psi_armed}"); | ||
| 1014 | - assert!(psi_armed, "PSI trigger must arm on this host"); | ||
| 1015 | - | ||
| 1016 | - let mut jobs = Vec::new(); | ||
| 1017 | - for (id, hold) in [("e2e1", "6"), ("e2e2", "1")] { | ||
| 1018 | - let (tx, mut rx) = mpsc::channel::<Vec<u8>>(64); | ||
| 1019 | - tokio::spawn(async move { | ||
| 1020 | - while let Some(line) = rx.recv().await { | ||
| 1021 | - eprint!("[log] {}", String::from_utf8_lossy(&line)); | ||
| 1022 | - } | ||
| 1023 | - }); | ||
| 1024 | - let registration = pressure.register(id, id, tx); | ||
| 1025 | - let dir = pressure.dir.join(format!("forge-job-{id}-1")); | ||
| 1026 | - fs::create_dir(&dir).expect("job cgroup"); | ||
| 1027 | - fs::write(dir.join("memory.swap.max"), "0").expect("swap.max"); | ||
| 1028 | - let mut child = Command::new("python3") | ||
| 1029 | - .args(["-I", "-c", ALLOCATOR, "700", hold]) | ||
| 1030 | - .stdin(Stdio::piped()) | ||
| 1031 | - .stdout(Stdio::piped()) | ||
| 1032 | - .kill_on_drop(true) | ||
| 1033 | - .spawn() | ||
| 1034 | - .expect("python3"); | ||
| 1035 | - let pid = child.id().expect("pid"); | ||
| 1036 | - fs::write(dir.join("cgroup.procs"), pid.to_string()).expect("join cgroup"); | ||
| 1037 | - let mut stdin = child.stdin.take().expect("stdin"); | ||
| 1038 | - stdin.write_all(b"go\n").await.expect("go"); | ||
| 1039 | - jobs.push((id, dir, child, Some(registration), stdin)); | ||
| 1040 | - tokio::time::sleep(Duration::from_secs(2)).await; | ||
| 1041 | - } | ||
| 1042 | - | ||
| 1043 | - let mut parked_seen = false; | ||
| 1044 | - let mut before_park = 0; | ||
| 1045 | - let mut at_park = (0, 0); | ||
| 1046 | - let mut park_at = None; | ||
| 1047 | - let mut thaw_at = None; | ||
| 1048 | - let mut peak_box = 0; | ||
| 1049 | - let mut results: Vec<Option<std::process::ExitStatus>> = vec![None, None]; | ||
| 1050 | - let deadline = Instant::now() + Duration::from_secs(150); | ||
| 1051 | - while results.iter().any(Option::is_none) { | ||
| 1052 | - assert!(Instant::now() < deadline, "jobs did not finish in time"); | ||
| 1053 | - let box_cur = read_u64(&pressure.dir, "memory.current").unwrap_or(0); | ||
| 1054 | - peak_box = peak_box.max(box_cur); | ||
| 1055 | - for (i, (id, dir, child, registration, _)) in jobs.iter_mut().enumerate() { | ||
| 1056 | - if results[i].is_none() | ||
| 1057 | - && let Some(status) = child.try_wait().expect("wait") | ||
| 1058 | - { | ||
| 1059 | - eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs()); | ||
| 1060 | - results[i] = Some(status); | ||
| 1061 | - drop(registration.take()); | ||
| 1062 | - } | ||
| 1063 | - if i == 1 && results[i].is_none() { | ||
| 1064 | - let frozen = fs::read_to_string(dir.join("cgroup.events")) | ||
| 1065 | - .is_ok_and(|t| t.contains("frozen 1")); | ||
| 1066 | - let cur = read_u64(dir, "memory.current"); | ||
| 1067 | - if frozen && !parked_seen && mib(cur) < 350 { | ||
| 1068 | - parked_seen = true; | ||
| 1069 | - park_at = Some(Instant::now()); | ||
| 1070 | - at_park = (mib(cur), mib(job_swap(dir))); | ||
| 1071 | - eprintln!( | ||
| 1072 | - "{}s job2 parked: memory.current {} MiB, swap {} MiB (was {} MiB)", | ||
| 1073 | - started.elapsed().as_secs(), | ||
| 1074 | - at_park.0, | ||
| 1075 | - at_park.1, | ||
| 1076 | - before_park | ||
| 1077 | - ); | ||
| 1078 | - } | ||
| 1079 | - if !frozen && parked_seen && thaw_at.is_none() { | ||
| 1080 | - thaw_at = Some(Instant::now()); | ||
| 1081 | - eprintln!("{}s job2 thawed", started.elapsed().as_secs()); | ||
| 1082 | - } | ||
| 1083 | - if !frozen && !parked_seen { | ||
| 1084 | - before_park = before_park.max(mib(cur)); | ||
| 1085 | - } | ||
| 1086 | - } | ||
| 1087 | - } | ||
| 1088 | - tokio::time::sleep(Duration::from_millis(100)).await; | ||
| 1089 | - } | ||
| 1090 | - eprintln!( | ||
| 1091 | - "peak box memory.current {} MiB, parked for {:?}", | ||
| 1092 | - peak_box >> 20, | ||
| 1093 | - park_at.zip(thaw_at).map(|(a, b)| b - a) | ||
| 1094 | - ); | ||
| 1095 | - | ||
| 1096 | - let mut oom = Vec::new(); | ||
| 1097 | - for (id, dir, _, _, _) in &jobs { | ||
| 1098 | - let events = fs::read_to_string(dir.join("memory.events")).unwrap_or_default(); | ||
| 1099 | - eprintln!("job {id} memory.events: {}", events.replace('\n', " ")); | ||
| 1100 | - if events | ||
| 1101 | - .lines() | ||
| 1102 | - .any(|l| l.starts_with("oom_kill ") && !l.ends_with(" 0")) | ||
| 1103 | - { | ||
| 1104 | - oom.push(id.to_string()); | ||
| 1105 | - } | ||
| 1106 | - } | ||
| 1107 | - let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default(); | ||
| 1108 | - eprintln!("box memory.events: {}", box_events.replace('\n', " ")); | ||
| 1109 | - | ||
| 1110 | - shutdown.cancel(); | ||
| 1111 | - for (_, dir, mut child, registration, _) in jobs { | ||
| 1112 | - let _ = child.start_kill(); | ||
| 1113 | - let _ = child.wait().await; | ||
| 1114 | - drop(registration); | ||
| 1115 | - for _ in 0..50 { | ||
| 1116 | - if fs::remove_dir(&dir).is_ok() { | ||
| 1117 | - break; | ||
| 1118 | - } | ||
| 1119 | - tokio::time::sleep(Duration::from_millis(50)).await; | ||
| 1120 | - } | ||
| 1121 | - } | ||
| 1122 | - tokio::time::sleep(Duration::from_millis(200)).await; | ||
| 1123 | - let _ = fs::remove_dir(&pressure.dir); | ||
| 1124 | - | ||
| 1125 | - assert!(oom.is_empty(), "oom_kill in {oom:?}"); | ||
| 1126 | - assert!(parked_seen, "the youngest job was never parked in swap"); | ||
| 1127 | - assert!( | ||
| 1128 | - at_park.1 > 100, | ||
| 1129 | - "parked job holds {} MiB in swap", | ||
| 1130 | - at_park.1 | ||
| 1131 | - ); | ||
| 1132 | - assert!(thaw_at.is_some(), "the parked job never thawed"); | ||
| 1133 | - for r in results { | ||
| 1134 | - assert!( | ||
| 1135 | - r.expect("exited").success(), | ||
| 1136 | - "a job failed or its checksum broke" | ||
| 1137 | - ); | ||
| 1138 | - } | ||
| 1139 | - } | ||
| 1140 | } | 102 | } |
crates/forge-runner/src/runner.rsmodified+3 -103
| @@ -11,16 +11,13 @@ use tokio_util::sync::CancellationToken; | |||
| 11 | 11 | ||
| 12 | use crate::artifacts; | 12 | use crate::artifacts; |
| 13 | use crate::cache::CacheStore; | 13 | use crate::cache::CacheStore; |
| 14 | -use crate::client::MemoryClaim; | ||
| 15 | use crate::client::{ClientError, ForgeClient}; | 14 | use crate::client::{ClientError, ForgeClient}; |
| 16 | use crate::config::RunnerConfig; | 15 | use crate::config::RunnerConfig; |
| 17 | use crate::executor::{ExecRequest, ExecResult, Executor}; | 16 | use crate::executor::{ExecRequest, ExecResult, Executor}; |
| 18 | use crate::limiter::Limiter; | 17 | use crate::limiter::Limiter; |
| 19 | use crate::logs::{self, PumpConfig}; | 18 | use crate::logs::{self, PumpConfig}; |
| 20 | -use crate::memory::MemoryGate; | ||
| 21 | use crate::metrics; | 19 | use crate::metrics; |
| 22 | use crate::oom::OomSink; | 20 | use crate::oom::OomSink; |
| 23 | -use crate::pressure::Pressure; | ||
| 24 | use crate::restart::{self, RestartState, Step}; | 21 | use crate::restart::{self, RestartState, Step}; |
| 25 | use crate::selflog; | 22 | use crate::selflog; |
| 26 | use crate::update::{self, Installed, UpdateState}; | 23 | use crate::update::{self, Installed, UpdateState}; |
| @@ -65,9 +62,7 @@ pub struct Runner { | |||
| 65 | options: RunOptions, | 62 | options: RunOptions, |
| 66 | cache: Option<Arc<CacheStore>>, | 63 | cache: Option<Arc<CacheStore>>, |
| 67 | limiter: Arc<Limiter>, | 64 | limiter: Arc<Limiter>, |
| 68 | - memory: Arc<MemoryGate>, | ||
| 69 | restart: Arc<RestartState>, | 65 | restart: Arc<RestartState>, |
| 70 | - pressure: Option<Arc<Pressure>>, | ||
| 71 | } | 66 | } |
| 72 | 67 | ||
| 73 | impl Runner { | 68 | impl Runner { |
| @@ -78,7 +73,6 @@ impl Runner { | |||
| 78 | ) -> Result<Self, ClientError> { | 73 | ) -> Result<Self, ClientError> { |
| 79 | let client = ForgeClient::new(&config.url)?; | 74 | let client = ForgeClient::new(&config.url)?; |
| 80 | let limiter = Limiter::new(config.concurrency); | 75 | let limiter = Limiter::new(config.concurrency); |
| 81 | - let memory = MemoryGate::for_host(&config.limits); | ||
| 82 | Ok(Self { | 76 | Ok(Self { |
| 83 | client, | 77 | client, |
| 84 | config: Arc::new(config), | 78 | config: Arc::new(config), |
| @@ -86,17 +80,10 @@ impl Runner { | |||
| 86 | options, | 80 | options, |
| 87 | cache: None, | 81 | cache: None, |
| 88 | limiter, | 82 | limiter, |
| 89 | - memory, | ||
| 90 | restart: Arc::new(RestartState::default()), | 83 | restart: Arc::new(RestartState::default()), |
| 91 | - pressure: None, | ||
| 92 | }) | 84 | }) |
| 93 | } | 85 | } |
| 94 | 86 | ||
| 95 | - pub fn with_pressure(mut self, pressure: Option<Arc<Pressure>>) -> Self { | ||
| 96 | - self.pressure = pressure; | ||
| 97 | - self | ||
| 98 | - } | ||
| 99 | - | ||
| 100 | pub fn with_cache(mut self, cache: CacheStore) -> Self { | 87 | pub fn with_cache(mut self, cache: CacheStore) -> Self { |
| 101 | self.cache = Some(Arc::new(cache)); | 88 | self.cache = Some(Arc::new(cache)); |
| 102 | self | 89 | self |
| @@ -126,8 +113,6 @@ impl Runner { | |||
| 126 | tracing::info!( | 113 | tracing::info!( |
| 127 | name = %self.config.name, | 114 | name = %self.config.name, |
| 128 | concurrency = self.limiter.current(), | 115 | concurrency = self.limiter.current(), |
| 129 | - memory_budget = %forge_ci::size::format_size(self.memory.budget()), | ||
| 130 | - reserve_memory = %forge_ci::size::format_size(self.memory.default_reserve()), | ||
| 131 | auto_update = updates.enabled(), | 116 | auto_update = updates.enabled(), |
| 132 | "runner started" | 117 | "runner started" |
| 133 | ); | 118 | ); |
| @@ -213,21 +198,6 @@ impl Runner { | |||
| 213 | continue; | 198 | continue; |
| 214 | } | 199 | } |
| 215 | 200 | ||
| 216 | - if let Some(pressure) = &self.pressure { | ||
| 217 | - let gate = pressure.gate(); | ||
| 218 | - if !gate.open() { | ||
| 219 | - let hot = if gate.hot { ", box under pressure" } else { "" }; | ||
| 220 | - not_claiming( | ||
| 221 | - &mut blocked, | ||
| 222 | - format!("memory pressure, {} job(s) parked{hot}", gate.frozen), | ||
| 223 | - ); | ||
| 224 | - } | ||
| 225 | - tokio::select! { | ||
| 226 | - _ = shutdown.cancelled() => break RunEnd::Stopped, | ||
| 227 | - () = self.restart.changed() => continue, | ||
| 228 | - () = pressure.wait_open() => {} | ||
| 229 | - } | ||
| 230 | - } | ||
| 231 | if self.limiter.free_slots() == 0 { | 201 | if self.limiter.free_slots() == 0 { |
| 232 | let limit = self.limiter.current(); | 202 | let limit = self.limiter.current(); |
| 233 | not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); | 203 | not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); |
| @@ -251,31 +221,11 @@ impl Runner { | |||
| 251 | &self.config.runner_secret, | 221 | &self.config.runner_secret, |
| 252 | &self.config.labels, | 222 | &self.config.labels, |
| 253 | Some(self.limiter.current()), | 223 | Some(self.limiter.current()), |
| 254 | - Some(MemoryClaim { | ||
| 255 | - free: self | ||
| 256 | - .pressure | ||
| 257 | - .as_ref() | ||
| 258 | - .and_then(|p| p.headroom()) | ||
| 259 | - .unwrap_or_else(|| self.memory.free()), | ||
| 260 | - budget: self.memory.budget(), | ||
| 261 | - reserve: self.memory.default_reserve(), | ||
| 262 | - }), | ||
| 263 | ) => r, | 224 | ) => r, |
| 264 | }; | 225 | }; |
| 265 | match claimed { | 226 | match claimed { |
| 266 | Ok(reply) => { | 227 | Ok(reply) => { |
| 267 | self.limiter.apply_logged(reply.concurrency); | 228 | self.limiter.apply_logged(reply.concurrency); |
| 268 | - self.memory.apply_logged( | ||
| 269 | - reply.memory_budget.as_deref(), | ||
| 270 | - reply.reserve_memory.as_deref(), | ||
| 271 | - ); | ||
| 272 | - if let Some(pressure) = &self.pressure | ||
| 273 | - && pressure.budget() != self.memory.ram_budget() | ||
| 274 | - { | ||
| 275 | - let pressure = pressure.clone(); | ||
| 276 | - let budget = self.memory.ram_budget(); | ||
| 277 | - let _ = tokio::task::spawn_blocking(move || pressure.resize(budget)).await; | ||
| 278 | - } | ||
| 279 | self.restart.observe(reply.restart); | 229 | self.restart.observe(reply.restart); |
| 280 | if updates.observe(reply.binary_sha256.as_deref()) | 230 | if updates.observe(reply.binary_sha256.as_deref()) |
| 281 | && let Some(sha) = updates.pending() | 231 | && let Some(sha) = updates.pending() |
| @@ -292,10 +242,8 @@ impl Runner { | |||
| 292 | ); | 242 | ); |
| 293 | let runner = self.clone(); | 243 | let runner = self.clone(); |
| 294 | let cancel = jobs_cancel.child_token(); | 244 | let cancel = jobs_cancel.child_token(); |
| 295 | - let reservation = self.memory.reserve(job.memory_bytes); | ||
| 296 | jobs.spawn(async move { | 245 | jobs.spawn(async move { |
| 297 | let _permit = permit; | 246 | let _permit = permit; |
| 298 | - let _reservation = reservation; | ||
| 299 | runner.process(job, cancel).await; | 247 | runner.process(job, cancel).await; |
| 300 | }); | 248 | }); |
| 301 | } | 249 | } |
| @@ -361,25 +309,11 @@ impl Runner { | |||
| 361 | let job_cancel = shutdown.child_token(); | 309 | let job_cancel = shutdown.child_token(); |
| 362 | let timed_out = Arc::new(AtomicBool::new(false)); | 310 | let timed_out = Arc::new(AtomicBool::new(false)); |
| 363 | let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone()); | 311 | let heartbeat = self.spawn_heartbeat(&job, job_cancel.clone()); |
| 364 | - let registration = self | ||
| 365 | - .pressure | ||
| 366 | - .as_ref() | ||
| 367 | - .map(|p| p.register(&job.job_id, &job.job_name, tx.clone())); | ||
| 368 | let timer = { | 312 | let timer = { |
| 369 | let cancel = job_cancel.clone(); | 313 | let cancel = job_cancel.clone(); |
| 370 | let flag = timed_out.clone(); | 314 | let flag = timed_out.clone(); |
| 371 | - let pause = registration.as_ref().map(|r| r.pause_clock()); | ||
| 372 | tokio::spawn(async move { | 315 | tokio::spawn(async move { |
| 373 | - let started = Instant::now(); | 316 | + tokio::time::sleep(timeout).await; |
| 374 | - loop { | ||
| 375 | - let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); | ||
| 376 | - let due = timeout + paused; | ||
| 377 | - let elapsed = started.elapsed(); | ||
| 378 | - if elapsed >= due { | ||
| 379 | - break; | ||
| 380 | - } | ||
| 381 | - tokio::time::sleep(due - elapsed).await; | ||
| 382 | - } | ||
| 383 | flag.store(true, Ordering::SeqCst); | 317 | flag.store(true, Ordering::SeqCst); |
| 384 | cancel.cancel(); | 318 | cancel.cancel(); |
| 385 | }) | 319 | }) |
| @@ -403,8 +337,6 @@ impl Runner { | |||
| 403 | logs: tx.clone(), | 337 | logs: tx.clone(), |
| 404 | cancel: job_cancel.clone(), | 338 | cancel: job_cancel.clone(), |
| 405 | oom: oom.clone(), | 339 | oom: oom.clone(), |
| 406 | - memory_budget: Some(self.memory.ram_budget()), | ||
| 407 | - memory_swap: self.memory.swap(), | ||
| 408 | }) | 340 | }) |
| 409 | .await; | 341 | .await; |
| 410 | workspace_dir = Some(dir); | 342 | workspace_dir = Some(dir); |
| @@ -417,37 +349,6 @@ impl Runner { | |||
| 417 | }, | 349 | }, |
| 418 | }; | 350 | }; |
| 419 | 351 | ||
| 420 | - if registration.as_ref().is_some_and(|r| r.requeued()) { | ||
| 421 | - heartbeat.abort(); | ||
| 422 | - timer.abort(); | ||
| 423 | - drop(registration); | ||
| 424 | - drop(tx); | ||
| 425 | - let _ = pump.await; | ||
| 426 | - if let Some(dir) = workspace_dir.take() | ||
| 427 | - && let Err(e) = workspace::cleanup(&dir).await | ||
| 428 | - { | ||
| 429 | - tracing::warn!(job_id = %job.job_id, error = %e, "workspace cleanup failed"); | ||
| 430 | - } | ||
| 431 | - let reason = "killed under memory pressure on the runner"; | ||
| 432 | - if let Err(e) = self | ||
| 433 | - .client | ||
| 434 | - .requeue(&job.job_id, &job.job_token, reason) | ||
| 435 | - .await | ||
| 436 | - { | ||
| 437 | - tracing::warn!(job_id = %job.job_id, error = %e, "requeue failed, failing the job"); | ||
| 438 | - let failed = ExecResult { | ||
| 439 | - outcome: Outcome::Error, | ||
| 440 | - exit_code: None, | ||
| 441 | - message: Some(format!( | ||
| 442 | - "out of memory, and the forge could not requeue it: {e}" | ||
| 443 | - )), | ||
| 444 | - }; | ||
| 445 | - self.finish(&job, &failed, None).await; | ||
| 446 | - } | ||
| 447 | - tracing::info!(job_id = %job.job_id, "job requeued after memory pressure"); | ||
| 448 | - return Outcome::Cancelled; | ||
| 449 | - } | ||
| 450 | - | ||
| 451 | let upload_error = match workspace_dir.as_deref() { | 352 | let upload_error = match workspace_dir.as_deref() { |
| 452 | Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { | 353 | Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { |
| 453 | self.upload_artifacts(&job, dir).await.err() | 354 | self.upload_artifacts(&job, dir).await.err() |
| @@ -464,7 +365,6 @@ impl Runner { | |||
| 464 | 365 | ||
| 465 | heartbeat.abort(); | 366 | heartbeat.abort(); |
| 466 | timer.abort(); | 367 | timer.abort(); |
| 467 | - drop(registration); | ||
| 468 | if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { | 368 | if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { |
| 469 | result = ExecResult { | 369 | result = ExecResult { |
| 470 | outcome: Outcome::Failure, | 370 | outcome: Outcome::Failure, |
| @@ -494,8 +394,8 @@ impl Runner { | |||
| 494 | send_line( | 394 | send_line( |
| 495 | &tx, | 395 | &tx, |
| 496 | format!( | 396 | format!( |
| 497 | - "runner: the out of memory killer killed {kills} process(es) in this job; \ | 397 | + "runner: out of memory, the job ran out of the runner's memory and the \ |
| 498 | - the job's memory is limited to its `memory` plus a little slack, see docs/ci.md" | 398 | + out of memory killer stopped it ({kills} process(es))" |
| 499 | ), | 399 | ), |
| 500 | ) | 400 | ) |
| 501 | .await; | 401 | .await; |
crates/forge-runner/src/sandbox/spec.rsmodified+14 -48
| @@ -1,11 +1,11 @@ | |||
| 1 | -use std::collections::HashSet; | 1 | +use std::collections::{HashMap, HashSet}; |
| 2 | use std::path::{Path, PathBuf}; | 2 | use std::path::{Path, PathBuf}; |
| 3 | 3 | ||
| 4 | use oci_spec::runtime::{ | 4 | use oci_spec::runtime::{ |
| 5 | Capability, LinuxBuilder, LinuxCapabilitiesBuilder, LinuxCpuBuilder, LinuxIdMappingBuilder, | 5 | Capability, LinuxBuilder, LinuxCapabilitiesBuilder, LinuxCpuBuilder, LinuxIdMappingBuilder, |
| 6 | - LinuxMemoryBuilder, LinuxNamespaceBuilder, LinuxNamespaceType, LinuxPidsBuilder, | 6 | + LinuxNamespaceBuilder, LinuxNamespaceType, LinuxPidsBuilder, LinuxResourcesBuilder, Mount, |
| 7 | - LinuxResourcesBuilder, Mount, MountBuilder, PosixRlimitBuilder, PosixRlimitType, | 7 | + MountBuilder, PosixRlimitBuilder, PosixRlimitType, ProcessBuilder, RootBuilder, Spec, |
| 8 | - ProcessBuilder, RootBuilder, Spec, SpecBuilder, UserBuilder, | 8 | + SpecBuilder, UserBuilder, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | use super::{SandboxError, SandboxRequest}; | 11 | use super::{SandboxError, SandboxRequest}; |
| @@ -226,17 +226,13 @@ fn ns(typ: LinuxNamespaceType) -> Result<oci_spec::runtime::LinuxNamespace, Sand | |||
| 226 | } | 226 | } |
| 227 | 227 | ||
| 228 | fn build_resources(limits: &Limits) -> Result<oci_spec::runtime::LinuxResources, SandboxError> { | 228 | fn build_resources(limits: &Limits) -> Result<oci_spec::runtime::LinuxResources, SandboxError> { |
| 229 | - let memory = parse_bytes(&limits.memory)?; | ||
| 230 | let cpus = parse_cpus(&limits.cpus)?; | 229 | let cpus = parse_cpus(&limits.cpus)?; |
| 231 | let quota = (cpus * CPU_PERIOD_US as f64).round() as i64; | 230 | let quota = (cpus * CPU_PERIOD_US as f64).round() as i64; |
| 232 | LinuxResourcesBuilder::default() | 231 | LinuxResourcesBuilder::default() |
| 233 | - .memory( | 232 | + .unified(HashMap::from([( |
| 234 | - LinuxMemoryBuilder::default() | 233 | + "memory.oom.group".to_owned(), |
| 235 | - .limit(memory) | 234 | + "1".to_owned(), |
| 236 | - .swap(memory.saturating_add(i64::try_from(limits.swap).unwrap_or(i64::MAX))) | 235 | + )])) |
| 237 | - .build() | ||
| 238 | - .map_err(spec_err)?, | ||
| 239 | - ) | ||
| 240 | .cpu( | 236 | .cpu( |
| 241 | LinuxCpuBuilder::default() | 237 | LinuxCpuBuilder::default() |
| 242 | .quota(quota) | 238 | .quota(quota) |
| @@ -254,24 +250,6 @@ fn build_resources(limits: &Limits) -> Result<oci_spec::runtime::LinuxResources, | |||
| 254 | .map_err(spec_err) | 250 | .map_err(spec_err) |
| 255 | } | 251 | } |
| 256 | 252 | ||
| 257 | -pub fn parse_bytes(text: &str) -> Result<i64, SandboxError> { | ||
| 258 | - let bad = || SandboxError::Invalid(format!("bad memory limit {text:?}")); | ||
| 259 | - let lower = text.trim().to_ascii_lowercase(); | ||
| 260 | - let (digits, multiplier) = match lower.chars().last() { | ||
| 261 | - Some('k') => (&lower[..lower.len() - 1], 1024_i64), | ||
| 262 | - Some('m') => (&lower[..lower.len() - 1], 1024 * 1024), | ||
| 263 | - Some('g') => (&lower[..lower.len() - 1], 1024 * 1024 * 1024), | ||
| 264 | - Some('b') => (&lower[..lower.len() - 1], 1), | ||
| 265 | - _ => (lower.as_str(), 1), | ||
| 266 | - }; | ||
| 267 | - let n: i64 = digits.parse().map_err(|_| bad())?; | ||
| 268 | - let bytes = n.checked_mul(multiplier).ok_or_else(bad)?; | ||
| 269 | - if bytes <= 0 { | ||
| 270 | - return Err(bad()); | ||
| 271 | - } | ||
| 272 | - Ok(bytes) | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | pub fn parse_cpus(text: &str) -> Result<f64, SandboxError> { | 253 | pub fn parse_cpus(text: &str) -> Result<f64, SandboxError> { |
| 276 | let value: f64 = text | 254 | let value: f64 = text |
| 277 | .trim() | 255 | .trim() |
| @@ -404,7 +382,6 @@ mod tests { | |||
| 404 | network, | 382 | network, |
| 405 | pasta: None, | 383 | pasta: None, |
| 406 | limits: Limits { | 384 | limits: Limits { |
| 407 | - memory: "2g".to_owned(), | ||
| 408 | cpus: "1.5".to_owned(), | 385 | cpus: "1.5".to_owned(), |
| 409 | pids: 512, | 386 | pids: 512, |
| 410 | image_max_gb: 20, | 387 | image_max_gb: 20, |
| @@ -574,13 +551,13 @@ mod tests { | |||
| 574 | .as_ref() | 551 | .as_ref() |
| 575 | .and_then(|l| l.resources().clone()) | 552 | .and_then(|l| l.resources().clone()) |
| 576 | .expect("resources"); | 553 | .expect("resources"); |
| 554 | + assert!(res.memory().is_none()); | ||
| 577 | assert_eq!( | 555 | assert_eq!( |
| 578 | - res.memory().as_ref().and_then(|m| m.limit()), | 556 | + res.unified() |
| 579 | - Some(2 * 1024 * 1024 * 1024) | 557 | + .as_ref() |
| 580 | - ); | 558 | + .and_then(|u| u.get("memory.oom.group")) |
| 581 | - assert_eq!( | 559 | + .map(String::as_str), |
| 582 | - res.memory().as_ref().and_then(|m| m.swap()), | 560 | + Some("1") |
| 583 | - Some(2 * 1024 * 1024 * 1024) | ||
| 584 | ); | 561 | ); |
| 585 | let cpu = res.cpu().as_ref().expect("cpu"); | 562 | let cpu = res.cpu().as_ref().expect("cpu"); |
| 586 | assert_eq!(cpu.period(), Some(CPU_PERIOD_US)); | 563 | assert_eq!(cpu.period(), Some(CPU_PERIOD_US)); |
| @@ -671,17 +648,6 @@ mod tests { | |||
| 671 | assert!(ro.iter().any(|p| p == "/proc/sys")); | 648 | assert!(ro.iter().any(|p| p == "/proc/sys")); |
| 672 | } | 649 | } |
| 673 | 650 | ||
| 674 | - #[test] | ||
| 675 | - fn parse_bytes_accepts_suffixes_and_rejects_junk() { | ||
| 676 | - assert_eq!(parse_bytes("4g").expect("g"), 4 * 1024 * 1024 * 1024); | ||
| 677 | - assert_eq!(parse_bytes("512M").expect("m"), 512 * 1024 * 1024); | ||
| 678 | - assert_eq!(parse_bytes("64k").expect("k"), 64 * 1024); | ||
| 679 | - assert_eq!(parse_bytes("1024").expect("plain"), 1024); | ||
| 680 | - assert!(parse_bytes("lots").is_err()); | ||
| 681 | - assert!(parse_bytes("0g").is_err()); | ||
| 682 | - assert!(parse_bytes("-1").is_err()); | ||
| 683 | - } | ||
| 684 | - | ||
| 685 | #[test] | 651 | #[test] |
| 686 | fn parse_cpus_rejects_zero_and_junk() { | 652 | fn parse_cpus_rejects_zero_and_junk() { |
| 687 | assert_eq!(parse_cpus("2").expect("2"), 2.0); | 653 | assert_eq!(parse_cpus("2").expect("2"), 2.0); |
crates/forge-runner/tests/integration/builtin.rsmodified+0 -3
| @@ -58,7 +58,6 @@ fn job(run: &str) -> JobAssignment { | |||
| 58 | cache: Vec::new(), | 58 | cache: Vec::new(), |
| 59 | cache_key: String::new(), | 59 | cache_key: String::new(), |
| 60 | cache_restore_keys: Vec::new(), | 60 | cache_restore_keys: Vec::new(), |
| 61 | - memory_bytes: None, | ||
| 62 | } | 61 | } |
| 63 | } | 62 | } |
| 64 | 63 | ||
| @@ -98,8 +97,6 @@ async fn run_job( | |||
| 98 | logs: tx, | 97 | logs: tx, |
| 99 | cancel, | 98 | cancel, |
| 100 | oom: forge_runner::oom::OomSink::default(), | 99 | oom: forge_runner::oom::OomSink::default(), |
| 101 | - memory_budget: None, | ||
| 102 | - memory_swap: 0, | ||
| 103 | }) | 100 | }) |
| 104 | .await; | 101 | .await; |
| 105 | let logs = collector.await.expect("log collector"); | 102 | let logs = collector.await.expect("log collector"); |
crates/forge-runner/tests/integration/flow.rsmodified+0 -1
| @@ -292,7 +292,6 @@ fn job(job_id: &str, commit: &str, clone_url: &str, run: &str) -> JobAssignment | |||
| 292 | cache: Vec::new(), | 292 | cache: Vec::new(), |
| 293 | cache_key: String::new(), | 293 | cache_key: String::new(), |
| 294 | cache_restore_keys: Vec::new(), | 294 | cache_restore_keys: Vec::new(), |
| 295 | - memory_bytes: None, | ||
| 296 | } | 295 | } |
| 297 | } | 296 | } |
| 298 | 297 | ||
crates/forge-web-app/src/ci/api.rsmodified+15 -115
| @@ -2,13 +2,12 @@ use forge_ci::config::JobSpec; | |||
| 2 | use forge_ci::mask::{MaskStream, Masker}; | 2 | use forge_ci::mask::{MaskStream, Masker}; |
| 3 | use forge_ci::proto::{ | 3 | use forge_ci::proto::{ |
| 4 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, | 4 | BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, |
| 5 | - JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER, | 5 | + JobAssignment, Outcome, RESTART_HEADER, RegisterRequest, RegisterResponse, |
| 6 | - RegisterRequest, RegisterResponse, RequeueRequest, RunnerConfigOverrides, RunnerConfigReport, | 6 | + RunnerConfigOverrides, RunnerConfigReport, RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, |
| 7 | - RunnerLogAck, RunnerLogBatch, RunnerMetricsBatch, | ||
| 8 | }; | 7 | }; |
| 9 | use forge_core::Error as CoreError; | 8 | use forge_core::Error as CoreError; |
| 10 | use forge_core::ci::{ | 9 | use forge_core::ci::{ |
| 11 | - CiJob, CiRun, CiRunner, JobState, MemoryOffer, QueueSkips, RestartMode, RunState, RunnerReport, | 10 | + CiJob, CiRun, CiRunner, JobState, QueueSkips, RestartMode, RunState, RunnerReport, |
| 12 | }; | 11 | }; |
| 13 | use forge_core::pulls::PullRequest; | 12 | use forge_core::pulls::PullRequest; |
| 14 | use futures_util::StreamExt; | 13 | use futures_util::StreamExt; |
| @@ -22,10 +21,9 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route}; | |||
| 22 | 21 | ||
| 23 | use crate::api::{self, Refusal}; | 22 | use crate::api::{self, Refusal}; |
| 24 | use crate::ci::{artifact_key, log_path}; | 23 | use crate::ci::{artifact_key, log_path}; |
| 25 | -use crate::i18n::Lang; | ||
| 26 | use crate::self_update; | 24 | use crate::self_update; |
| 27 | use crate::state::AppState; | 25 | use crate::state::AppState; |
| 28 | -use crate::views::{https_clone_url, human_size}; | 26 | +use crate::views::https_clone_url; |
| 29 | 27 | ||
| 30 | path_param!(job_id); | 28 | path_param!(job_id); |
| 31 | path_param!(artifact_name); | 29 | path_param!(artifact_name); |
| @@ -38,7 +36,6 @@ const MAX_JSON_BODY: usize = 64 * 1024; | |||
| 38 | const MAX_LOG_BATCH: usize = 1024 * 1024; | 36 | const MAX_LOG_BATCH: usize = 1024 * 1024; |
| 39 | const MAX_METRICS_BATCH: usize = 256 * 1024; | 37 | const MAX_METRICS_BATCH: usize = 256 * 1024; |
| 40 | const MAX_METRICS_SAMPLES: usize = 400; | 38 | const MAX_METRICS_SAMPLES: usize = 400; |
| 41 | -const DEFAULT_RESERVE: u64 = 1 << 30; | ||
| 42 | const MAX_NAME_BYTES: usize = 64; | 39 | const MAX_NAME_BYTES: usize = 64; |
| 43 | const MAX_LABELS: usize = 32; | 40 | const MAX_LABELS: usize = 32; |
| 44 | const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n"; | 41 | const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n"; |
| @@ -171,18 +168,10 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 171 | Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), | 168 | Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), |
| 172 | Err(_) => ClaimRequest::default(), | 169 | Err(_) => ClaimRequest::default(), |
| 173 | }; | 170 | }; |
| 174 | - let offer = request.free_memory_bytes.map(|free| MemoryOffer { | ||
| 175 | - free, | ||
| 176 | - budget: request.memory_budget_bytes, | ||
| 177 | - default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE), | ||
| 178 | - }); | ||
| 179 | note_report( | 171 | note_report( |
| 180 | state, | 172 | state, |
| 181 | &runner.id, | 173 | &runner.id, |
| 182 | &RunnerReport { | 174 | &RunnerReport { |
| 183 | - memory_budget: request.memory_budget_bytes, | ||
| 184 | - memory_free: request.free_memory_bytes, | ||
| 185 | - memory_reserve: request.reserve_memory_bytes, | ||
| 186 | concurrency: request.concurrency, | 175 | concurrency: request.concurrency, |
| 187 | version: request.version.filter(|v| v.len() <= 64), | 176 | version: request.version.filter(|v| v.len() <= 64), |
| 188 | cpus: request.cpus, | 177 | cpus: request.cpus, |
| @@ -198,7 +187,7 @@ async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 198 | }, | 187 | }, |
| 199 | ) | 188 | ) |
| 200 | .await; | 189 | .await; |
| 201 | - let mut res = claim_work(state, &runner, offer).await?; | 190 | + let mut res = claim_work(state, &runner).await?; |
| 202 | set_claim_headers(state, &runner.id, &mut res).await; | 191 | set_claim_headers(state, &runner.id, &mut res).await; |
| 203 | self_update::advertise(state, headers(cx), &mut res); | 192 | self_update::advertise(state, headers(cx), &mut res); |
| 204 | Ok(res) | 193 | Ok(res) |
| @@ -240,22 +229,6 @@ async fn set_claim_headers(state: &AppState, runner_id: &str, res: &mut Response | |||
| 240 | { | 229 | { |
| 241 | res.headers_mut().insert(CONCURRENCY_HEADER, value); | 230 | res.headers_mut().insert(CONCURRENCY_HEADER, value); |
| 242 | } | 231 | } |
| 243 | - if let Ok(Some(text)) = state | ||
| 244 | - .store | ||
| 245 | - .runner_field_override(runner_id, "limits.memory_budget") | ||
| 246 | - .await | ||
| 247 | - && let Ok(value) = HeaderValue::from_str(&text) | ||
| 248 | - { | ||
| 249 | - res.headers_mut().insert(MEMORY_BUDGET_HEADER, value); | ||
| 250 | - } | ||
| 251 | - if let Ok(Some(text)) = state | ||
| 252 | - .store | ||
| 253 | - .runner_field_override(runner_id, "limits.reserve_memory") | ||
| 254 | - .await | ||
| 255 | - && let Ok(value) = HeaderValue::from_str(&text) | ||
| 256 | - { | ||
| 257 | - res.headers_mut().insert(RESERVE_MEMORY_HEADER, value); | ||
| 258 | - } | ||
| 259 | if let Some(mode) = pending_restart(state, runner_id).await { | 232 | if let Some(mode) = pending_restart(state, runner_id).await { |
| 260 | res.headers_mut() | 233 | res.headers_mut() |
| 261 | .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str())); | 234 | .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str())); |
| @@ -355,11 +328,7 @@ fn overrides_response(runner: &CiRunner) -> Response { | |||
| 355 | ) | 328 | ) |
| 356 | } | 329 | } |
| 357 | 330 | ||
| 358 | -async fn claim_work( | 331 | +async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Response> { |
| 359 | - state: &AppState, | ||
| 360 | - runner: &CiRunner, | ||
| 361 | - offer: Option<MemoryOffer>, | ||
| 362 | -) -> topcoat::Result<Response> { | ||
| 363 | let waker = state.ci_waker.clone(); | 332 | let waker = state.ci_waker.clone(); |
| 364 | let wait = std::time::Duration::from_millis(state.config.ci.claim_wait_ms); | 333 | let wait = std::time::Duration::from_millis(state.config.ci.claim_wait_ms); |
| 365 | let deadline = tokio::time::Instant::now() + wait; | 334 | let deadline = tokio::time::Instant::now() + wait; |
| @@ -371,7 +340,7 @@ async fn claim_work( | |||
| 371 | note_restart_pending(state, runner).await; | 340 | note_restart_pending(state, runner).await; |
| 372 | return Ok(empty(StatusCode::NO_CONTENT)); | 341 | return Ok(empty(StatusCode::NO_CONTENT)); |
| 373 | } | 342 | } |
| 374 | - match try_claim(state, runner, offer).await { | 343 | + match try_claim(state, runner).await { |
| 375 | Ok(Some(assignment)) => return Ok(api::json(StatusCode::OK, &assignment)), | 344 | Ok(Some(assignment)) => return Ok(api::json(StatusCode::OK, &assignment)), |
| 376 | Ok(None) => {} | 345 | Ok(None) => {} |
| 377 | Err(res) => return Ok(*res), | 346 | Err(res) => return Ok(*res), |
| @@ -380,14 +349,14 @@ async fn claim_work( | |||
| 380 | .await | 349 | .await |
| 381 | .is_err() | 350 | .is_err() |
| 382 | { | 351 | { |
| 383 | - note_idle(state, runner, offer).await; | 352 | + note_idle(state, runner).await; |
| 384 | return Ok(empty(StatusCode::NO_CONTENT)); | 353 | return Ok(empty(StatusCode::NO_CONTENT)); |
| 385 | } | 354 | } |
| 386 | } | 355 | } |
| 387 | } | 356 | } |
| 388 | 357 | ||
| 389 | async fn note_restart_pending(state: &AppState, runner: &CiRunner) { | 358 | async fn note_restart_pending(state: &AppState, runner: &CiRunner) { |
| 390 | - let Ok(skips) = state.store.queue_skips(runner, None).await else { | 359 | + let Ok(skips) = state.store.queue_skips(runner).await else { |
| 391 | return; | 360 | return; |
| 392 | }; | 361 | }; |
| 393 | if skips.queued > 0 { | 362 | if skips.queued > 0 { |
| @@ -399,15 +368,15 @@ async fn note_restart_pending(state: &AppState, runner: &CiRunner) { | |||
| 399 | } | 368 | } |
| 400 | } | 369 | } |
| 401 | 370 | ||
| 402 | -async fn note_idle(state: &AppState, runner: &CiRunner, offer: Option<MemoryOffer>) { | 371 | +async fn note_idle(state: &AppState, runner: &CiRunner) { |
| 403 | - let skips = match state.store.queue_skips(runner, offer).await { | 372 | + let skips = match state.store.queue_skips(runner).await { |
| 404 | Ok(skips) => skips, | 373 | Ok(skips) => skips, |
| 405 | Err(e) => { | 374 | Err(e) => { |
| 406 | tracing::warn!(error = %e, "ci: counting the queued jobs failed"); | 375 | tracing::warn!(error = %e, "ci: counting the queued jobs failed"); |
| 407 | return; | 376 | return; |
| 408 | } | 377 | } |
| 409 | }; | 378 | }; |
| 410 | - if let Some(text) = idle_text(&skips, offer.map(|o| o.free)) { | 379 | + if let Some(text) = idle_text(&skips) { |
| 411 | note_runner(state, &runner.id, &text); | 380 | note_runner(state, &runner.id, &text); |
| 412 | } | 381 | } |
| 413 | } | 382 | } |
| @@ -418,7 +387,7 @@ fn note_runner(state: &AppState, runner_id: &str, text: &str) { | |||
| 418 | } | 387 | } |
| 419 | } | 388 | } |
| 420 | 389 | ||
| 421 | -fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> { | 390 | +fn idle_text(skips: &QueueSkips) -> Option<String> { |
| 422 | if skips.queued == 0 { | 391 | if skips.queued == 0 { |
| 423 | return None; | 392 | return None; |
| 424 | } | 393 | } |
| @@ -434,24 +403,6 @@ fn idle_text(skips: &QueueSkips, free: Option<u64>) -> Option<String> { | |||
| 434 | skips.missing_labels.join(", ") | 403 | skips.missing_labels.join(", ") |
| 435 | )); | 404 | )); |
| 436 | } | 405 | } |
| 437 | - if let (true, Some(need), Some(free)) = (skips.too_big > 0, skips.smallest_need, free) { | ||
| 438 | - parts.push(format!( | ||
| 439 | - "{} waiting for memory: smallest needs {}, {} free", | ||
| 440 | - skips.too_big, | ||
| 441 | - human_size(Lang::En, need), | ||
| 442 | - human_size(Lang::En, free) | ||
| 443 | - )); | ||
| 444 | - } | ||
| 445 | - if let (Some(need), Some(free)) = (skips.starved_need, free) { | ||
| 446 | - parts.push(format!( | ||
| 447 | - "{} held back: a job queued over {} min ago needs {}, {} free, so no smaller job \ | ||
| 448 | - starts until running jobs finish and it fits", | ||
| 449 | - skips.held_behind, | ||
| 450 | - forge_core::ci::STARVE_AFTER_SECS / 60, | ||
| 451 | - human_size(Lang::En, need), | ||
| 452 | - human_size(Lang::En, free) | ||
| 453 | - )); | ||
| 454 | - } | ||
| 455 | Some(parts.join("; ")) | 406 | Some(parts.join("; ")) |
| 456 | } | 407 | } |
| 457 | 408 | ||
| @@ -563,16 +514,8 @@ fn empty(status: StatusCode) -> Response { | |||
| 563 | res | 514 | res |
| 564 | } | 515 | } |
| 565 | 516 | ||
| 566 | -async fn try_claim( | 517 | +async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssignment>, Refusal> { |
| 567 | - state: &AppState, | 518 | + let Some((job, run, job_token)) = state.store.claim_job(runner).await.map_err(api::internal)? |
| 568 | - runner: &CiRunner, | ||
| 569 | - offer: Option<MemoryOffer>, | ||
| 570 | -) -> Result<Option<JobAssignment>, Refusal> { | ||
| 571 | - let Some((job, run, job_token)) = state | ||
| 572 | - .store | ||
| 573 | - .claim_job_fitting(runner, offer) | ||
| 574 | - .await | ||
| 575 | - .map_err(api::internal)? | ||
| 576 | else { | 519 | else { |
| 577 | return Ok(None); | 520 | return Ok(None); |
| 578 | }; | 521 | }; |
| @@ -648,7 +591,6 @@ async fn build_assignment( | |||
| 648 | cache: spec.cache, | 591 | cache: spec.cache, |
| 649 | cache_key, | 592 | cache_key, |
| 650 | cache_restore_keys, | 593 | cache_restore_keys, |
| 651 | - memory_bytes: spec.memory, | ||
| 652 | }) | 594 | }) |
| 653 | } | 595 | } |
| 654 | 596 | ||
| @@ -1146,48 +1088,6 @@ async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |||
| 1146 | } | 1088 | } |
| 1147 | } | 1089 | } |
| 1148 | 1090 | ||
| 1149 | -#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")] | ||
| 1150 | -async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 1151 | - let state = context::<AppState>(cx); | ||
| 1152 | - let job = match job_from(state, headers(cx), job_id(cx)).await { | ||
| 1153 | - Ok(job) => job, | ||
| 1154 | - Err(res) => return Ok(*res), | ||
| 1155 | - }; | ||
| 1156 | - let request: RequeueRequest = match json_body(body, MAX_JSON_BODY).await { | ||
| 1157 | - Ok(request) => request, | ||
| 1158 | - Err(res) => return Ok(*res), | ||
| 1159 | - }; | ||
| 1160 | - match state.store.requeue_job(&job.id).await { | ||
| 1161 | - Ok(true) => {} | ||
| 1162 | - Ok(false) => { | ||
| 1163 | - return Ok(api::error(StatusCode::CONFLICT, "the job is not running")); | ||
| 1164 | - } | ||
| 1165 | - Err(e) => return Ok(*api::internal(e)), | ||
| 1166 | - } | ||
| 1167 | - let path = log_path(&state.config.data_dir, &job.id); | ||
| 1168 | - let reason = request.reason.replace(['\r', '\n'], " "); | ||
| 1169 | - let note = format!("requeued: {reason}. It will start again\n"); | ||
| 1170 | - if let Some(parent) = path.parent() | ||
| 1171 | - && let Err(e) = tokio::fs::create_dir_all(parent).await | ||
| 1172 | - { | ||
| 1173 | - tracing::warn!(error = %e, "ci: log directory not created"); | ||
| 1174 | - } | ||
| 1175 | - if let Err(e) = tokio::fs::write(&path, note).await { | ||
| 1176 | - tracing::warn!(error = %e, "ci: requeue log note not written"); | ||
| 1177 | - } | ||
| 1178 | - state.ci_live.bump_job(&job.id); | ||
| 1179 | - state.ci_live.bump_run(&job.run_id); | ||
| 1180 | - state.ci_live.bump_runners(); | ||
| 1181 | - if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await { | ||
| 1182 | - state.ci_live.bump_repo(&run.repo_id); | ||
| 1183 | - if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await { | ||
| 1184 | - crate::ci::sync_status(state, &run, &fresh).await; | ||
| 1185 | - } | ||
| 1186 | - } | ||
| 1187 | - state.ci_waker.notify_waiters(); | ||
| 1188 | - Ok(api::json(StatusCode::OK, &json!({ "state": "queued" }))) | ||
| 1189 | -} | ||
| 1190 | - | ||
| 1191 | async fn finish_job( | 1091 | async fn finish_job( |
| 1192 | state: &AppState, | 1092 | state: &AppState, |
| 1193 | job: &CiJob, | 1093 | job: &CiJob, |
crates/forge-web-app/src/ci/api_tests.rsmodified+4 -139
| @@ -496,116 +496,6 @@ async fn claim_and_heartbeat_carry_the_concurrency_round_trip() { | |||
| 496 | assert!(beat.json().get("concurrency").is_none()); | 496 | assert!(beat.json().get("concurrency").is_none()); |
| 497 | } | 497 | } |
| 498 | 498 | ||
| 499 | -fn spec_with_memory(bytes: u64) -> String { | ||
| 500 | - let mut value: Value = serde_json::from_str(&spec(&[], &[])).unwrap(); | ||
| 501 | - value["memory"] = bytes.into(); | ||
| 502 | - value.to_string() | ||
| 503 | -} | ||
| 504 | - | ||
| 505 | -async fn claim_with_memory(router: &Router, secret: &str, free_gib: u64) -> Sent { | ||
| 506 | - let body = json!({ | ||
| 507 | - "labels": [], | ||
| 508 | - "free_memory_bytes": free_gib << 30, | ||
| 509 | - "memory_budget_bytes": 6u64 << 30, | ||
| 510 | - "reserve_memory_bytes": 1u64 << 30, | ||
| 511 | - }); | ||
| 512 | - send( | ||
| 513 | - router, | ||
| 514 | - "POST", | ||
| 515 | - "/api/v1/ci/runners/claim", | ||
| 516 | - &[bearer(secret)], | ||
| 517 | - json_body(&body), | ||
| 518 | - ) | ||
| 519 | - .await | ||
| 520 | -} | ||
| 521 | - | ||
| 522 | -#[tokio::test] | ||
| 523 | -async fn claim_hands_out_only_a_job_that_fits_the_free_memory() { | ||
| 524 | - let env = bare(|_| {}).await; | ||
| 525 | - let (runner, secret) = runner(&env, &[]).await; | ||
| 526 | - make_run( | ||
| 527 | - &env, | ||
| 528 | - "push", | ||
| 529 | - None, | ||
| 530 | - COMMIT, | ||
| 531 | - &[ | ||
| 532 | - job("big", spec_with_memory(4 << 30)), | ||
| 533 | - job("small", spec_with_memory(1 << 30)), | ||
| 534 | - ], | ||
| 535 | - ) | ||
| 536 | - .await; | ||
| 537 | - | ||
| 538 | - let sent = claim_with_memory(&env.router, &secret, 2).await; | ||
| 539 | - assert_eq!(sent.status, 200); | ||
| 540 | - assert_eq!(sent.json()["job_name"], "small"); | ||
| 541 | - assert_eq!(sent.json()["memory_bytes"], 1u64 << 30); | ||
| 542 | - let sent = claim_with_memory(&env.router, &secret, 1).await; | ||
| 543 | - assert_eq!(sent.status, 204); | ||
| 544 | - let listed = env.store.list_runners().await.unwrap().remove(0); | ||
| 545 | - assert_eq!(listed.id, runner.id); | ||
| 546 | - assert_eq!(listed.reported.memory_budget, Some(6 << 30)); | ||
| 547 | - assert_eq!(listed.reported.memory_free, Some(1 << 30)); | ||
| 548 | - assert_eq!(listed.reported.memory_reserve, Some(1 << 30)); | ||
| 549 | - assert_eq!(listed.reported.memory_reserved(), Some(5 << 30)); | ||
| 550 | - let sent = claim_with_memory(&env.router, &secret, 5).await; | ||
| 551 | - assert_eq!(sent.json()["job_name"], "big"); | ||
| 552 | - assert_eq!(sent.json()["memory_bytes"], 4u64 << 30); | ||
| 553 | - | ||
| 554 | - let sent = claim_with_memory(&env.router, &secret, 6).await; | ||
| 555 | - assert!(sent.headers.get("Forge-Runner-Memory-Budget").is_none()); | ||
| 556 | - assert!(sent.headers.get("Forge-Runner-Reserve-Memory").is_none()); | ||
| 557 | - env.store | ||
| 558 | - .set_runner_field(&runner.id, "limits.memory_budget", Some("5g")) | ||
| 559 | - .await | ||
| 560 | - .unwrap(); | ||
| 561 | - env.store | ||
| 562 | - .set_runner_field(&runner.id, "limits.reserve_memory", Some("2g")) | ||
| 563 | - .await | ||
| 564 | - .unwrap(); | ||
| 565 | - let sent = claim_with_memory(&env.router, &secret, 6).await; | ||
| 566 | - assert_eq!( | ||
| 567 | - sent.headers.get("Forge-Runner-Memory-Budget").unwrap(), | ||
| 568 | - "5g" | ||
| 569 | - ); | ||
| 570 | - assert_eq!( | ||
| 571 | - sent.headers.get("Forge-Runner-Reserve-Memory").unwrap(), | ||
| 572 | - "2g" | ||
| 573 | - ); | ||
| 574 | -} | ||
| 575 | - | ||
| 576 | -#[tokio::test] | ||
| 577 | -async fn an_old_runner_without_memory_fields_still_gets_jobs() { | ||
| 578 | - let env = bare(|_| {}).await; | ||
| 579 | - let (_runner, secret) = runner(&env, &[]).await; | ||
| 580 | - make_run( | ||
| 581 | - &env, | ||
| 582 | - "push", | ||
| 583 | - None, | ||
| 584 | - COMMIT, | ||
| 585 | - &[ | ||
| 586 | - job("big", spec_with_memory(64 << 30)), | ||
| 587 | - job("plain", spec(&[], &[])), | ||
| 588 | - ], | ||
| 589 | - ) | ||
| 590 | - .await; | ||
| 591 | - let first = claim(&env.router, &secret).await; | ||
| 592 | - let second = claim(&env.router, &secret).await; | ||
| 593 | - assert_eq!((first.status, second.status), (200, 200)); | ||
| 594 | - let mut names = [first.json(), second.json()].map(|j| { | ||
| 595 | - ( | ||
| 596 | - j["job_name"].as_str().unwrap().to_owned(), | ||
| 597 | - j.get("memory_bytes").is_none(), | ||
| 598 | - ) | ||
| 599 | - }); | ||
| 600 | - names.sort(); | ||
| 601 | - assert_eq!( | ||
| 602 | - names, | ||
| 603 | - [("big".to_owned(), false), ("plain".to_owned(), true)] | ||
| 604 | - ); | ||
| 605 | - let listed = env.store.list_runners().await.unwrap().remove(0); | ||
| 606 | - assert_eq!(listed.reported.memory_budget, None); | ||
| 607 | -} | ||
| 608 | - | ||
| 609 | async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent { | 499 | async fn post_claim(router: &Router, secret: &str, boot: &str) -> Sent { |
| 610 | let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] }); | 500 | let body = serde_json::json!({ "labels": [], "boot_id": boot, "capabilities": ["restart"] }); |
| 611 | send( | 501 | send( |
| @@ -684,11 +574,11 @@ async fn runner_config_report_and_overrides_round_trip() { | |||
| 684 | assert_eq!(sent.json()["overrides"], serde_json::json!({})); | 574 | assert_eq!(sent.json()["overrides"], serde_json::json!({})); |
| 685 | 575 | ||
| 686 | env.store | 576 | env.store |
| 687 | - .set_runner_field(&runner.id, "limits.memory", Some("8g")) | 577 | + .set_runner_field(&runner.id, "limits.pids", Some("8")) |
| 688 | .await | 578 | .await |
| 689 | .unwrap(); | 579 | .unwrap(); |
| 690 | let report = serde_json::json!({ "config": { | 580 | let report = serde_json::json!({ "config": { |
| 691 | - "limits.memory": "4g", "runner_secret": "leaked", "bogus.key": 1, "concurrency": 1 | 581 | + "limits.pids": "4", "runner_secret": "leaked", "bogus.key": 1, "concurrency": 1 |
| 692 | }}); | 582 | }}); |
| 693 | let sent = send( | 583 | let sent = send( |
| 694 | &env.router, | 584 | &env.router, |
| @@ -699,9 +589,9 @@ async fn runner_config_report_and_overrides_round_trip() { | |||
| 699 | ) | 589 | ) |
| 700 | .await; | 590 | .await; |
| 701 | assert_eq!(sent.status, 200); | 591 | assert_eq!(sent.status, 200); |
| 702 | - assert_eq!(sent.json()["overrides"]["limits.memory"], "8g"); | 592 | + assert_eq!(sent.json()["overrides"]["limits.pids"], 8); |
| 703 | let stored = env.store.list_runners().await.unwrap().remove(0); | 593 | let stored = env.store.list_runners().await.unwrap().remove(0); |
| 704 | - assert_eq!(stored.reported_config["limits.memory"], "4g"); | 594 | + assert_eq!(stored.reported_config["limits.pids"], "4"); |
| 705 | assert_eq!(stored.reported_config["runner_secret"], "<redacted>"); | 595 | assert_eq!(stored.reported_config["runner_secret"], "<redacted>"); |
| 706 | assert!(!stored.reported_config.contains_key("bogus.key")); | 596 | assert!(!stored.reported_config.contains_key("bogus.key")); |
| 707 | 597 | ||
| @@ -808,31 +698,6 @@ async fn finish_with(env: &Bare, secret: &str, body: Value) -> (String, Value) { | |||
| 808 | (id, sent.json()) | 698 | (id, sent.json()) |
| 809 | } | 699 | } |
| 810 | 700 | ||
| 811 | -#[tokio::test] | ||
| 812 | -async fn requeue_hands_the_job_back_and_it_can_be_claimed_again() { | ||
| 813 | - let env = bare(|_| {}).await; | ||
| 814 | - let (_runner, secret) = runner(&env, &[]).await; | ||
| 815 | - make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; | ||
| 816 | - let first = claim_job(&env.router, &secret).await; | ||
| 817 | - let id = first["job_id"].as_str().unwrap().to_owned(); | ||
| 818 | - let token = first["job_token"].as_str().unwrap().to_owned(); | ||
| 819 | - let uri = format!("/api/v1/ci/jobs/{id}/requeue"); | ||
| 820 | - let body = json_body(&json!({ "reason": "the runner paused this job for memory" })); | ||
| 821 | - let wrong = send(&env.router, "POST", &uri, &[bearer("nope")], body.clone()).await; | ||
| 822 | - assert_eq!(wrong.status, 401); | ||
| 823 | - let sent = send(&env.router, "POST", &uri, &[bearer(&token)], body.clone()).await; | ||
| 824 | - assert_eq!(sent.status, 200, "{}", sent.json()); | ||
| 825 | - let stored = env.store.job_by_id(&id).await.unwrap().unwrap(); | ||
| 826 | - assert_eq!(stored.state, JobState::Queued); | ||
| 827 | - let log = std::fs::read_to_string(log_path(&env.data_dir, &id)).unwrap(); | ||
| 828 | - assert!(log.starts_with("requeued: "), "{log}"); | ||
| 829 | - let again = send(&env.router, "POST", &uri, &[bearer(&token)], body).await; | ||
| 830 | - assert_eq!(again.status, 401); | ||
| 831 | - let second = claim_job(&env.router, &secret).await; | ||
| 832 | - assert_eq!(second["job_id"], first["job_id"]); | ||
| 833 | - assert_ne!(second["job_token"], first["job_token"]); | ||
| 834 | -} | ||
| 835 | - | ||
| 836 | #[tokio::test] | 701 | #[tokio::test] |
| 837 | async fn finish_stores_oom_kills_and_old_bodies_leave_them_empty() { | 702 | async fn finish_stores_oom_kills_and_old_bodies_leave_them_empty() { |
| 838 | let env = bare(|_| {}).await; | 703 | let env = bare(|_| {}).await; |
crates/forge-web-pages/src/pages/admin_runners.rsmodified+4 -65
| @@ -655,15 +655,7 @@ const TABS: [(&str, &[&str]); 8] = [ | |||
| 655 | ("jobs", &[]), | 655 | ("jobs", &[]), |
| 656 | ( | 656 | ( |
| 657 | "limits", | 657 | "limits", |
| 658 | - &[ | 658 | + &["limits.memory_headroom", "limits.cpus", "limits.pids"], |
| 659 | - "limits.memory_budget", | ||
| 660 | - "limits.memory_headroom", | ||
| 661 | - "limits.budget_swap_percent", | ||
| 662 | - "limits.cpus", | ||
| 663 | - "limits.pids", | ||
| 664 | - "limits.reserve_memory", | ||
| 665 | - "limits.memory", | ||
| 666 | - ], | ||
| 667 | ), | 659 | ), |
| 668 | ( | 660 | ( |
| 669 | "storage", | 661 | "storage", |
| @@ -716,11 +708,7 @@ fn field_text(lang: Lang, key: &str) -> &'static str { | |||
| 716 | "labels" => s(lang, "Labels", "Etiketler"), | 708 | "labels" => s(lang, "Labels", "Etiketler"), |
| 717 | "executor" => s(lang, "Executor", "Yürütücü"), | 709 | "executor" => s(lang, "Executor", "Yürütücü"), |
| 718 | "auto_update" => s(lang, "Auto update", "Otomatik güncelleme"), | 710 | "auto_update" => s(lang, "Auto update", "Otomatik güncelleme"), |
| 719 | - "limits.memory" => s(lang, "Memory per job (podman)", "İş başına bellek (podman)"), | ||
| 720 | - "limits.reserve_memory" => s(lang, "Assumed job size", "Varsayılan iş boyutu"), | ||
| 721 | - "limits.memory_budget" => s(lang, "Memory for jobs", "İşler için bellek"), | ||
| 722 | "limits.memory_headroom" => s(lang, "Kept for the host", "Sunucuya ayrılan"), | 711 | "limits.memory_headroom" => s(lang, "Kept for the host", "Sunucuya ayrılan"), |
| 723 | - "limits.budget_swap_percent" => s(lang, "Swap for jobs (%)", "İşler için takas (%)"), | ||
| 724 | "limits.cpus" => s(lang, "CPUs per job", "İş başına CPU"), | 712 | "limits.cpus" => s(lang, "CPUs per job", "İş başına CPU"), |
| 725 | "limits.pids" => s(lang, "Processes per job", "İş başına işlem"), | 713 | "limits.pids" => s(lang, "Processes per job", "İş başına işlem"), |
| 726 | "work_dir" => s(lang, "Work directory", "Çalışma dizini"), | 714 | "work_dir" => s(lang, "Work directory", "Çalışma dizini"), |
| @@ -770,21 +758,9 @@ struct DetailField { | |||
| 770 | options: Vec<Choice>, | 758 | options: Vec<Choice>, |
| 771 | } | 759 | } |
| 772 | 760 | ||
| 773 | -fn field_applies(key: &str, fields: &[FieldRow]) -> bool { | ||
| 774 | - let value = |k: &str| fields.iter().find(|f| f.key == k).map(|f| f.value.as_str()); | ||
| 775 | - match key { | ||
| 776 | - "limits.memory" => value("executor") == Some("podman"), | ||
| 777 | - "limits.reserve_memory" => value("concurrency") | ||
| 778 | - .and_then(|v| v.parse::<u32>().ok()) | ||
| 779 | - .is_some_and(|n| n > 1), | ||
| 780 | - _ => true, | ||
| 781 | - } | ||
| 782 | -} | ||
| 783 | - | ||
| 784 | fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> { | 761 | fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> { |
| 785 | tab_keys(tab) | 762 | tab_keys(tab) |
| 786 | .into_iter() | 763 | .into_iter() |
| 787 | - .filter(|key| field_applies(key, fields)) | ||
| 788 | .filter_map(|key| fields.iter().find(|f| f.key == key)) | 764 | .filter_map(|key| fields.iter().find(|f| f.key == key)) |
| 789 | .map(|f| { | 765 | .map(|f| { |
| 790 | let label = field_text(lang, f.key); | 766 | let label = field_text(lang, f.key); |
| @@ -807,7 +783,6 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> | |||
| 807 | let is_number = matches!( | 783 | let is_number = matches!( |
| 808 | f.key, | 784 | f.key, |
| 809 | "limits.pids" | 785 | "limits.pids" |
| 810 | - | "limits.budget_swap_percent" | ||
| 811 | | "limits.image_max_gb" | 786 | | "limits.image_max_gb" |
| 812 | | "limits.job_disk_gb" | 787 | | "limits.job_disk_gb" |
| 813 | | "images.keep_days" | 788 | | "images.keep_days" |
| @@ -838,7 +813,6 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> | |||
| 838 | min: if f.key == "concurrency" { "1" } else { "0" }, | 813 | min: if f.key == "concurrency" { "1" } else { "0" }, |
| 839 | max: match f.key { | 814 | max: match f.key { |
| 840 | "concurrency" => Some("64"), | 815 | "concurrency" => Some("64"), |
| 841 | - "limits.budget_swap_percent" => Some("100"), | ||
| 842 | _ => None, | 816 | _ => None, |
| 843 | }, | 817 | }, |
| 844 | options: if choices.is_empty() { | 818 | options: if choices.is_empty() { |
| @@ -1305,25 +1279,6 @@ async fn runner_detail_view( | |||
| 1305 | .map(|b| human_size(lang, b)) | 1279 | .map(|b| human_size(lang, b)) |
| 1306 | .unwrap_or_default(), | 1280 | .unwrap_or_default(), |
| 1307 | ); | 1281 | ); |
| 1308 | - let reported = &runner.reported; | ||
| 1309 | - let budget_text = or_dash( | ||
| 1310 | - reported | ||
| 1311 | - .memory_budget | ||
| 1312 | - .map(|b| human_size(lang, b)) | ||
| 1313 | - .unwrap_or_default(), | ||
| 1314 | - ); | ||
| 1315 | - let reserved_text = or_dash( | ||
| 1316 | - reported | ||
| 1317 | - .memory_reserved() | ||
| 1318 | - .map(|b| human_size(lang, b)) | ||
| 1319 | - .unwrap_or_default(), | ||
| 1320 | - ); | ||
| 1321 | - let free_text = or_dash( | ||
| 1322 | - reported | ||
| 1323 | - .memory_free | ||
| 1324 | - .map(|b| human_size(lang, b)) | ||
| 1325 | - .unwrap_or_default(), | ||
| 1326 | - ); | ||
| 1327 | let in_use = if row.concurrency.is_empty() { | 1282 | let in_use = if row.concurrency.is_empty() { |
| 1328 | row.running.to_string() | 1283 | row.running.to_string() |
| 1329 | } else { | 1284 | } else { |
| @@ -1345,17 +1300,7 @@ async fn runner_detail_view( | |||
| 1345 | let save_action = format!("{}/settings", row.detail_href); | 1300 | let save_action = format!("{}/settings", row.detail_href); |
| 1346 | let reset_action = row.config_action.clone(); | 1301 | let reset_action = row.config_action.clone(); |
| 1347 | let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU")); | 1302 | let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU")); |
| 1348 | - let budget_facts = format!( | 1303 | + let mem_facts = if metrics.empty { memory } else { String::new() }; |
| 1349 | - "{} {budget_text} · {} {reserved_text} · {} {free_text}", | ||
| 1350 | - s(lang, "Budget", "Bütçe"), | ||
| 1351 | - s(lang, "Reserved", "Ayrılan"), | ||
| 1352 | - s(lang, "Free to admit", "Alınabilir"), | ||
| 1353 | - ); | ||
| 1354 | - let mem_facts = if metrics.empty { | ||
| 1355 | - format!("{memory} · {budget_facts}") | ||
| 1356 | - } else { | ||
| 1357 | - budget_facts | ||
| 1358 | - }; | ||
| 1359 | let facts = [cpu_facts, mem_facts, String::new(), String::new()]; | 1304 | let facts = [cpu_facts, mem_facts, String::new(), String::new()]; |
| 1360 | let has_host = !metrics.empty || runner.reported.cpus.is_some(); | 1305 | let has_host = !metrics.empty || runner.reported.cpus.is_some(); |
| 1361 | Ok(view! { | 1306 | Ok(view! { |
| @@ -1475,9 +1420,6 @@ async fn runner_detail_view( | |||
| 1475 | </section> | 1420 | </section> |
| 1476 | } else if editing { | 1421 | } else if editing { |
| 1477 | <section class="sec"> | 1422 | <section class="sec"> |
| 1478 | - if tab == "limits" { | ||
| 1479 | - <p class="state">(s(lang, "Jobs may use now", "İşlerin kullanabileceği")) " " (budget_text.as_str())</p> | ||
| 1480 | - } | ||
| 1481 | <form method="post" action=(save_action.as_str()) class="fields"> | 1423 | <form method="post" action=(save_action.as_str()) class="fields"> |
| 1482 | <input type="hidden" name="csrf" value=(csrf.as_str())> | 1424 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 1483 | <input type="hidden" name="tab" value=(tab)> | 1425 | <input type="hidden" name="tab" value=(tab)> |
| @@ -2225,7 +2167,7 @@ mod tests { | |||
| 2225 | "POST", | 2167 | "POST", |
| 2226 | &settings, | 2168 | &settings, |
| 2227 | Some(USER_TOKEN), | 2169 | Some(USER_TOKEN), |
| 2228 | - csrf_form("&tab=limits&limits.memory=1g"), | 2170 | + csrf_form("&tab=limits&limits.pids=1"), |
| 2229 | ) | 2171 | ) |
| 2230 | .await; | 2172 | .await; |
| 2231 | assert_eq!(status, 404); | 2173 | assert_eq!(status, 404); |
| @@ -2255,10 +2197,7 @@ mod tests { | |||
| 2255 | .await; | 2197 | .await; |
| 2256 | assert_eq!(status, 200); | 2198 | assert_eq!(status, 200); |
| 2257 | assert!(page.contains("CPUs per job")); | 2199 | assert!(page.contains("CPUs per job")); |
| 2258 | - assert!( | 2200 | + assert!(!page.contains("Assumed job size")); |
| 2259 | - !page.contains("Memory per job (podman)"), | ||
| 2260 | - "builtin runners hide it" | ||
| 2261 | - ); | ||
| 2262 | assert!(page.contains("Reset to runner.toml")); | 2201 | assert!(page.contains("Reset to runner.toml")); |
| 2263 | 2202 | ||
| 2264 | let (status, _) = send( | 2203 | let (status, _) = send( |
crates/forge-web-pages/src/pages/wiki.rsmodified+4 -1
| @@ -175,8 +175,11 @@ async fn wiki_rail( | |||
| 175 | val: String::new(), | 175 | val: String::new(), |
| 176 | }) | 176 | }) |
| 177 | .collect(); | 177 | .collect(); |
| 178 | + let has_pages = !items.is_empty(); | ||
| 178 | Ok(view! { | 179 | Ok(view! { |
| 179 | - rail(label: g::t(lang, K::PageNav), items: items) | 180 | + if has_pages { |
| 181 | + rail(label: g::t(lang, K::PageNav), items: items) | ||
| 182 | + } | ||
| 180 | }) | 183 | }) |
| 181 | } | 184 | } |
| 182 | 185 | ||
crates/forge-web/src/routes.snapmodified+0 -1
| @@ -235,7 +235,6 @@ route /api/v1/ci/jobs/{job_id}/artifacts/{artifact_name} Only([PUT]) | |||
| 235 | route /api/v1/ci/jobs/{job_id}/finish Only([POST]) | 235 | route /api/v1/ci/jobs/{job_id}/finish Only([POST]) |
| 236 | route /api/v1/ci/jobs/{job_id}/heartbeat Only([POST]) | 236 | route /api/v1/ci/jobs/{job_id}/heartbeat Only([POST]) |
| 237 | route /api/v1/ci/jobs/{job_id}/logs Only([POST]) | 237 | route /api/v1/ci/jobs/{job_id}/logs Only([POST]) |
| 238 | -route /api/v1/ci/jobs/{job_id}/requeue Only([POST]) | ||
| 239 | route /api/v1/ci/runners/binary Only([GET]) | 238 | route /api/v1/ci/runners/binary Only([GET]) |
| 240 | route /api/v1/ci/runners/claim Only([POST]) | 239 | route /api/v1/ci/runners/claim Only([POST]) |
| 241 | route /api/v1/ci/runners/config Only([GET]) | 240 | route /api/v1/ci/runners/config Only([GET]) |
docs/ci.mdmodified+11 -86
| @@ -56,7 +56,6 @@ There must be at least one job, and at most 20. | |||
| 56 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. Every runner also has its arch, OS and `<arch>-<os>` as labels, such as `x86_64`, `linux` and `x86_64-linux`. | | 56 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. Every runner also has its arch, OS and `<arch>-<os>` as labels, such as `x86_64`, `linux` and `x86_64-linux`. | |
| 57 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | | 57 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | |
| 58 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | 58 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | |
| 59 | -| `memory` | string | none | The job's expected peak memory, such as `4g` or `512m`. 64m to 1024g. See [Memory](#memory). | | ||
| 60 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | | 59 | | `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | |
| 61 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` gives it internet access, isolated through `pasta` when it is installed. Read [the caveats](#builtin-executor-caveats). | | 60 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` gives it internet access, isolated through `pasta` when it is installed. Read [the caveats](#builtin-executor-caveats). | |
| 62 | 61 | ||
| @@ -76,52 +75,10 @@ on a big one. A job that sets one of these in its `env` keeps its own value. Oth | |||
| 76 | 75 | ||
| 77 | ### Memory | 76 | ### Memory |
| 78 | 77 | ||
| 79 | -`memory` is optional. You do not need it: the runner reacts to real memory use instead of trusting a | 78 | +Jobs share one memory box on the runner, sized to the host's RAM minus `limits.memory_headroom` |
| 80 | -number. When you set it, it is a hint for admission and an explicit cap for the job. | 79 | +("Kept for the host"). Swap is left to the OS, and concurrency is the only gate. A job the kernel |
| 81 | - | 80 | +kills for memory fails with an out-of-memory message. A `memory` key in `ci.toml` is no longer |
| 82 | -```toml | 81 | +used: the forge accepts it and warns. |
| 83 | -[jobs.build] | ||
| 84 | -image = "docker.io/library/rust:1" | ||
| 85 | -run = "cargo build --release" | ||
| 86 | -memory = "4g" # optional | ||
| 87 | -``` | ||
| 88 | - | ||
| 89 | -What the runner does without it: | ||
| 90 | - | ||
| 91 | -- Optimistic admission. A job without `memory` reserves the runner's default (`limits.reserve_memory`, | ||
| 92 | - 1g unless an admin changed it) and may use up to the whole memory budget of the runner. The | ||
| 93 | - runner tells the forge how much memory its box has left with every claim, and the forge hands out | ||
| 94 | - the first queued job whose reservation fits. A smaller job may run before a bigger one that has | ||
| 95 | - to wait. To keep the big job from starving, a job that does not fit and has waited 5 minutes | ||
| 96 | - stops smaller jobs from passing it on that runner. A job that asks for more than the runner's | ||
| 97 | - whole budget runs alone. | ||
| 98 | -- Pause and park. The runner puts all job cgroups in one box (`forge-jobs`) capped at the memory | ||
| 99 | - budget. When two or more jobs run and the box nears its cap, the runner freezes the youngest | ||
| 100 | - job and pushes its memory to swap, and logs `runner: paused: memory pressure, waiting for <job>` | ||
| 101 | - and `runner: parked <n> MiB in swap` in that job. The older job keeps its RAM and finishes. The | ||
| 102 | - parked job thaws when the box has room for what is in its swap or nothing else runs, and logs | ||
| 103 | - `runner: resumed after <time>`. The time a job spent frozen does not count toward its | ||
| 104 | - `timeout_minutes`. While a job is parked the runner claims no new job. | ||
| 105 | -- Requeue. If the parked job's memory does not go to swap (the host has no free swap, or the | ||
| 106 | - kernel refuses), the runner kills it and gives it back to the queue, keeping its place. It is | ||
| 107 | - not reported as failed. | ||
| 108 | -- A lone job is never paused. It may use the whole box, and if it runs out of memory it is | ||
| 109 | - OOM-killed and reported as below. | ||
| 110 | - | ||
| 111 | -With `memory` set: | ||
| 112 | - | ||
| 113 | -- The job's cgroup `memory.max` (podman `--memory`) is `memory` plus slack (1/16, at least | ||
| 114 | - 256 MiB), and swap is off for the job (`memory.swap.max` is 0) while it runs. A job that goes over | ||
| 115 | - is OOM-killed inside its own cgroup. Without `memory`, the limit is the box budget. Podman | ||
| 116 | - jobs keep the larger of the runner's `limits.memory` and `limits.reserve_memory`. | ||
| 117 | -- The reservation is `memory` instead of the default, which keeps a job that you know is heavy from | ||
| 118 | - being started next to another one. | ||
| 119 | -- It is the same for every job in a matrix. | ||
| 120 | - | ||
| 121 | -Host requirements for pausing: swap must be present (a parked job lives in swap), and the user the | ||
| 122 | -runner runs as needs the `memory`, `cpu` and `pids` cgroup v2 controllers delegated (see | ||
| 123 | -[Check the host](#1-check-the-host)). Without delegated controllers, or on the podman executor, the runner | ||
| 124 | -works as before: no box, no pausing. | ||
| 125 | 82 | ||
| 126 | OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's `memory.events` | 83 | OOM kills are reported. When a job ends, the builtin executor reads the job cgroup's `memory.events` |
| 127 | before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills` in the finish | 84 | before the cgroup is deleted, and the runner sends `oom_killed` and `oom_kills` in the finish |
| @@ -132,9 +89,6 @@ cgroup killed by any OOM killer, a host-wide one included, since Linux 4.13) and | |||
| 132 | hit its own limit). A process killed outside the job's cgroup is not counted. The podman executor | 89 | hit its own limit). A process killed outside the job's cgroup is not counted. The podman executor |
| 133 | does not report this. | 90 | does not report this. |
| 134 | 91 | ||
| 135 | -A forge that predates requeue answers the runner's requeue call with an error. The runner then | ||
| 136 | -fails that job instead. | ||
| 137 | - | ||
| 138 | ### Example | 92 | ### Example |
| 139 | 93 | ||
| 140 | ```toml | 94 | ```toml |
| @@ -616,11 +570,7 @@ executor = "builtin" # or "podman" | |||
| 616 | auto_update = true # replace the runner binary with the forge's when idle | 570 | auto_update = true # replace the runner binary with the forge's when idle |
| 617 | 571 | ||
| 618 | [limits] | 572 | [limits] |
| 619 | -memory = "4g" # the job cgroup's memory.max when the job declares no `memory`, or podman --memory | 573 | +memory_headroom = "1g" # kept for the host, the larger of this and 10% of MemTotal |
| 620 | -reserve_memory = "1g" # what a job without `memory` reserves, and the floor of its cgroup limit (live) | ||
| 621 | -memory_budget = "auto" # all running jobs together may reserve this much (live), or a size like "6g" | ||
| 622 | -memory_headroom = "1g" # in auto mode: kept for the host, the larger of this and 10% of MemTotal | ||
| 623 | -budget_swap_percent = 0 # in auto mode: percent of swap that counts toward the budget | ||
| 624 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus | 574 | cpus = "2" # the job cgroup's cpu.max, or podman --cpus |
| 625 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit | 575 | pids = 4096 # the job cgroup's pids.max, or podman --pids-limit |
| 626 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) | 576 | image_max_gb = 20 # cap on the unpacked size of one image (builtin) |
| @@ -661,32 +611,13 @@ second Rust build alongside the first needs several more GB even with `CARGO_BUI | |||
| 661 | capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp | 611 | capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp |
| 662 | profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`. | 612 | profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`. |
| 663 | 613 | ||
| 664 | -Memory-aware admission. Concurrency only counts jobs, and several Rust compiles at once can need | ||
| 665 | -more RAM than the host has, which ends in the kernel's OOM killer picking a victim, often `rustc` | ||
| 666 | -in the middle of a build. So a runner also has a memory budget. By default the budget is the | ||
| 667 | -host's `MemTotal` minus a headroom, the larger of `memory_headroom` and 10%: a 7.6 GiB host gets | ||
| 668 | -about 6.6 GiB. Swap does not count unless `budget_swap_percent` says so, because a build that | ||
| 669 | -runs in swap is slower than one that waits. The swap share is swap, not RAM: the box and a job | ||
| 670 | -without `memory` may hold the rest of the budget in RAM, and that job may also swap up to the share. | ||
| 671 | -So on a host where one build needs more than its RAM, such as forge's own on 8 GB, set | ||
| 672 | -`budget_swap_percent` (for example 50) with zram or a swap file, and the build swaps instead of | ||
| 673 | -being OOM-killed. Each running job holds a reservation (its `memory` | ||
| 674 | -from `ci.toml`, see [Memory](#memory), or `reserve_memory`), and a job starts only when the | ||
| 675 | -reservations of the running jobs plus its own fit the budget. `concurrency` stays as a second cap, so | ||
| 676 | -both must have room. The runner page shows the budget, what is reserved and what is free to admit. | ||
| 677 | -The budget and `reserve_memory` are live: an admin can change them on the runner's Limits tab and | ||
| 678 | -the runner applies them on its next claim, logging `runner: memory budget ...`. Reservations are | ||
| 679 | -promises and nothing measures real use; the per-job cgroup limit is what holds a job to its word. | ||
| 680 | - | ||
| 681 | Every `runner.toml` field is visible on the runner's page (`/admin/runners/<id>`), with its value and | 614 | Every `runner.toml` field is visible on the runner's page (`/admin/runners/<id>`), with its value and |
| 682 | whether it comes from `runner.toml` or the UI. The runner reports its effective config when it | 615 | whether it comes from `runner.toml` or the UI. The runner reports its effective config when it |
| 683 | starts, with the secret and registry passwords left out. Fields come in three kinds: | 616 | starts, with the secret and registry passwords left out. Fields come in three kinds: |
| 684 | 617 | ||
| 685 | -- Live: `concurrency`, `labels`, `limits.reserve_memory` and `limits.memory_budget`, applied on the | 618 | +- Live: `concurrency`, `labels` and `name`, applied on the runner's next check-in. |
| 686 | - runner's next check-in. | ||
| 687 | - Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the other `limits.*` values | 619 | - Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the other `limits.*` values |
| 688 | - (`memory_headroom` and `budget_swap_percent` included), | 620 | + (`memory_headroom` included), `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to |
| 689 | - `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to | ||
| 690 | its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says | 621 | its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says |
| 691 | "restart needed" until the runner has started with it. | 622 | "restart needed" until the runner has started with it. |
| 692 | - Read-only: `name`, `url`, `runner_id`, `runner_secret` and `registry`, because changing them from the | 623 | - Read-only: `name`, `url`, `runner_id`, `runner_secret` and `registry`, because changing them from the |
| @@ -796,8 +727,7 @@ or a pull request. Two jobs never share a cache, and two repos never do either. | |||
| 796 | base branch's cache, then the default branch's cache. A pull request never writes a branch cache, | 727 | base branch's cache, then the default branch's cache. A pull request never writes a branch cache, |
| 797 | so a change under review cannot leave a cache that a later build of `main` will use. | 728 | so a change under review cannot leave a cache that a later build of `main` will use. |
| 798 | - A run gets a copy of its cache, so several runs can use one cache at once. A job that succeeds | 729 | - A run gets a copy of its cache, so several runs can use one cache at once. A job that succeeds |
| 799 | - or fails replaces the cache with its own. A job that is cancelled, errors or is requeued leaves | 730 | + or fails replaces the cache with its own. A job that is cancelled or errors leaves it as it was. |
| 800 | - it as it was. | ||
| 801 | - The runner caps the total size of its caches. When the cap is reached, the least recently used | 731 | - The runner caps the total size of its caches. When the cap is reached, the least recently used |
| 802 | entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`. | 732 | entries are evicted first. The cap is the runner config key `cache_max_gib`, default `20`. |
| 803 | 733 | ||
| @@ -860,21 +790,16 @@ The runner talks to the forge only over HTTPS. JSON bodies are defined in `forge | |||
| 860 | | `POST /api/v1/ci/jobs/{id}/heartbeat` | `Bearer` job token | Sent every 10 s. The reply says whether the job was cancelled. | | 790 | | `POST /api/v1/ci/jobs/{id}/heartbeat` | `Bearer` job token | Sent every 10 s. The reply says whether the job was cancelled. | |
| 861 | | `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` | `Bearer` job token | Upload one artifact as a raw body. | | 791 | | `PUT /api/v1/ci/jobs/{id}/artifacts/{name}` | `Bearer` job token | Upload one artifact as a raw body. | |
| 862 | | `POST /api/v1/ci/jobs/{id}/finish` | `Bearer` job token | Report `success`, `failure`, `cancelled` or `error`, with the exit code and an optional message. | | 792 | | `POST /api/v1/ci/jobs/{id}/finish` | `Bearer` job token | Report `success`, `failure`, `cancelled` or `error`, with the exit code and an optional message. | |
| 863 | -| `POST /api/v1/ci/jobs/{id}/requeue` | `Bearer` job token | Hand a running job back to the queue with a `reason` (runners advertise the `requeue` capability). The job keeps its `queued_at`, its log is cleared and starts with a line saying why, and the job token stops working. 409 when the job is not running. | | ||
| 864 | 793 | ||
| 865 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, | 794 | The claim response (`JobAssignment`) carries the repository, the commit, the job's run script, |
| 866 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull | 795 | image, env, secrets, artifact globs, timeout and network setting. Secrets are empty for fork pull |
| 867 | -request runs, and `memory_bytes` when the job declares `memory`. | 796 | +request runs. |
| 868 | 797 | ||
| 869 | The finish request (`outcome`, `exit_code`, `message`) may also carry `oom_killed` and `oom_kills`, | 798 | The finish request (`outcome`, `exit_code`, `message`) may also carry `oom_killed` and `oom_kills`, |
| 870 | see [Memory](#memory). Both are optional and left out by an older runner. | 799 | see [Memory](#memory). Both are optional and left out by an older runner. |
| 871 | 800 | ||
| 872 | -A claim body also carries the runner's host facts and, for memory-aware admission, | 801 | +A claim body also carries the runner's host facts. The forge takes the oldest queued job whose |
| 873 | -`free_memory_bytes` (budget minus the running jobs' reservations), `memory_budget_bytes` and | 802 | +labels match. |
| 874 | -`reserve_memory_bytes`. All of these are optional. Without `free_memory_bytes` the forge takes the | ||
| 875 | -oldest queued job whose labels match, as before. The claim response may carry the headers | ||
| 876 | -`Forge-Runner-Memory-Budget` and `Forge-Runner-Reserve-Memory` when an admin changed those | ||
| 877 | -settings. | ||
| 878 | 803 | ||
| 879 | For the workspace, the runner runs `git fetch --depth=1` on the clone URL with the job token, then | 804 | For the workspace, the runner runs `git fetch --depth=1` on the clone URL with the job token, then |
| 880 | `git checkout --detach <commit>`. The token goes in an HTTP header, never on the command line. | 805 | `git checkout --detach <commit>`. The token goes in an HTTP header, never on the command line. |
style/_one.scssmodified+27 -1
| @@ -1838,7 +1838,10 @@ button.corner-link.link-button, | |||
| 1838 | } | 1838 | } |
| 1839 | 1839 | ||
| 1840 | &.live { | 1840 | &.live { |
| 1841 | - box-shadow: inset 0 0 0 5px var(--accent); | 1841 | + box-shadow: none; |
| 1842 | + border: 2.5px solid var(--accent); | ||
| 1843 | + border-right-color: transparent; | ||
| 1844 | + animation: tick-spin 0.9s linear infinite; | ||
| 1842 | } | 1845 | } |
| 1843 | 1846 | ||
| 1844 | &.on { | 1847 | &.on { |
| @@ -2360,6 +2363,29 @@ main > .diff-section, | |||
| 2360 | display: none; | 2363 | display: none; |
| 2361 | } | 2364 | } |
| 2362 | 2365 | ||
| 2366 | +.seg.live .bar { | ||
| 2367 | + animation: seg-pulse 1.6s ease-in-out infinite; | ||
| 2368 | +} | ||
| 2369 | + | ||
| 2370 | +@keyframes tick-spin { | ||
| 2371 | + to { | ||
| 2372 | + transform: rotate(360deg); | ||
| 2373 | + } | ||
| 2374 | +} | ||
| 2375 | + | ||
| 2376 | +@keyframes seg-pulse { | ||
| 2377 | + 50% { | ||
| 2378 | + opacity: 0.55; | ||
| 2379 | + } | ||
| 2380 | +} | ||
| 2381 | + | ||
| 2382 | +@media (prefers-reduced-motion: reduce) { | ||
| 2383 | + .tick.live, | ||
| 2384 | + .seg.live .bar { | ||
| 2385 | + animation: none; | ||
| 2386 | + } | ||
| 2387 | +} | ||
| 2388 | + | ||
| 2363 | .seg.live .bar progress { | 2389 | .seg.live .bar progress { |
| 2364 | position: absolute; | 2390 | position: absolute; |
| 2365 | inset: 0; | 2391 | inset: 0; |