use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::JoinHandle; use crossbeam_channel::{bounded, Sender}; use crate::config::Config; use crate::db::{self, builds, Db}; use crate::pipeline::{self, Outcome}; pub struct Pool { // Read only by `shutdown`, which is compiled for the test tier: a release // build starts the dispatcher and runs it until the process exits, so in // that build these two fields are stored and never read. #[cfg_attr(not(feature = "test-support"), allow(dead_code))] stop: Arc, #[cfg_attr(not(feature = "test-support"), allow(dead_code))] handles: Vec>, } impl Pool { pub fn spawn(cfg: Arc, db: Db) -> Pool { let stop = Arc::new(AtomicBool::new(false)); let workers = cfg.max_concurrent_builds.max(1); let (tx, rx) = bounded::(workers); let mut handles = Vec::new(); for n in 0..workers { let cfg = cfg.clone(); let db = db.clone(); let stop = stop.clone(); let rx = rx.clone(); handles.push( std::thread::Builder::new() .name(format!("worker-{n}")) .spawn(crate::time::inherit(move || worker(cfg, db, rx, stop))) .expect("spawn worker"), ); } drop(rx); let cfg2 = cfg.clone(); let db2 = db.clone(); let stop2 = stop.clone(); handles.push( std::thread::Builder::new() .name("dispatcher".into()) .spawn(crate::time::inherit(move || dispatcher(cfg2, db2, stop2, tx))) .expect("spawn dispatcher"), ); Pool { stop, handles } } /// Stop the dispatcher threads and join them. /// /// Production runs the pool until the process exits; nothing asks it to /// stop. A test needs the join, because it asserts on the pool's effects /// and cannot do that while the threads are still running. #[cfg(feature = "test-support")] pub fn shutdown(self) { self.stop.store(true, Ordering::SeqCst); for h in self.handles { let _ = h.join(); } } } fn dispatcher(cfg: Arc, db: Db, stop: Arc, tx: Sender) { while !stop.load(Ordering::SeqCst) { dispatch_once(&cfg, &db, &tx); if !crate::time::wait( std::time::Duration::from_secs(cfg.dispatch_tick_secs), std::time::Duration::from_millis(200), &stop, ) { break; } } } /// The scheduler loop calls it; a test drives single ticks and needs it directly. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender) -> Vec { dispatch_once_impl(cfg, db, tx) } #[cfg(not(feature = "test-support"))] pub(crate) fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender) -> Vec { dispatch_once_impl(cfg, db, tx) } fn dispatch_once_impl(cfg: &Config, db: &Db, tx: &Sender) -> Vec { let reaped = builds::reap_expired(db).unwrap_or(0); if reaped > 0 { db::audit_system( &db.writer, "build.reaped", "build", "*", serde_json::json!({"requeued": reaped}), ) .ok(); } let _ = builds::requeue_blocked(db); let _ = builds::cancel_superseded(db); let room = admissible(cfg, db); if room == 0 { return Vec::new(); } let owner = format!("worker-{}", std::process::id()); let ids = builds::claim_batch(db, &owner, room, cfg.lease_secs).unwrap_or_default(); for id in &ids { if tx.send(id.clone()).is_err() { let _ = builds::requeue_transient(db, id); } } ids } /// Production reaches this through `dispatch_once`, which is the only thing that acts on the answer. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn admissible(cfg: &Config, db: &Db) -> usize { admissible_impl(cfg, db) } #[cfg(not(feature = "test-support"))] pub(crate) fn admissible(cfg: &Config, db: &Db) -> usize { admissible_impl(cfg, db) } fn admissible_impl(cfg: &Config, db: &Db) -> usize { let in_flight = builds::in_flight(db).unwrap_or(0) as usize; let slots = cfg.max_concurrent_builds.saturating_sub(in_flight); if slots == 0 { return 0; } let free = free_disk_mb(&cfg.root); if free < cfg.min_free_disk_mb { return 0; } slots } /// Production reaches this through `admissible`, which is the only thing that acts on the number. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn free_disk_mb(path: &std::path::Path) -> u64 { free_disk_mb_impl(path) } #[cfg(not(feature = "test-support"))] pub(crate) fn free_disk_mb(path: &std::path::Path) -> u64 { free_disk_mb_impl(path) } fn free_disk_mb_impl(path: &std::path::Path) -> u64 { use std::ffi::CString; let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) { Ok(c) => c, Err(_) => return u64::MAX, }; let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) }; if rc != 0 { return u64::MAX; } let bsize = stat.f_frsize as u64; let avail = stat.f_bavail as u64; avail * bsize / (1024 * 1024) } fn worker(cfg: Arc, db: Db, rx: crossbeam_channel::Receiver, stop: Arc) { for id in rx.iter() { if stop.load(Ordering::SeqCst) { let _ = builds::requeue_transient(&db, &id); continue; } let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1); match pipeline::run(&cfg, &db, &id) { Ok(Outcome::Failed { transient, .. }) => { if transient && attempt < cfg.max_transient_attempts { let _ = builds::requeue_transient(&db, &id); db::audit_system( &db.writer, "build.retry", "build", &id, serde_json::json!({"attempt": attempt, "max": cfg.max_transient_attempts}), ) .ok(); } } Ok(Outcome::Cancelled) => {} Ok(Outcome::Blocked { .. }) | Ok(Outcome::Succeeded { .. }) | Err(_) => {} } if stop.load(Ordering::SeqCst) { break; } } }