summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/config.rs18
-rw-r--r--src/db/builds.rs62
-rw-r--r--src/main.rs6
-rw-r--r--src/pipeline/dispatch.rs203
-rw-r--r--src/pipeline/mod.rs1
-rw-r--r--src/pipeline/publish.rs13
6 files changed, 302 insertions, 1 deletions
diff --git a/src/config.rs b/src/config.rs
index 5bcb5aa..270c81e 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -55,6 +55,19 @@ pub struct Config {
pub publish_fault: Option<String>,
/// Test hook: the named shim must fail, e.g. `makechrootpkg`.
pub shim_fail: Option<String>,
+ /// How many builds may run at once (§8.2 backpressure). Default 1, which
+ /// also means the chroot pool only needs one warm root.
+ pub max_concurrent_builds: usize,
+ /// Seconds of lease a worker takes when it claims a build (§8.2).
+ pub lease_secs: i64,
+ /// A build is not admitted unless at least this much free space remains
+ /// on the filesystem holding `root` (§8.2 disk headroom).
+ pub min_free_disk_mb: u64,
+ /// Transient step failures are retried up to this many attempts; a
+ /// deterministic build failure is never retried (§8.4).
+ pub max_transient_attempts: i64,
+ /// Seconds between dispatcher passes.
+ pub dispatch_tick_secs: u64,
}
impl Default for Config {
@@ -80,6 +93,11 @@ impl Default for Config {
shim_dir: None,
publish_fault: None,
shim_fail: None,
+ max_concurrent_builds: 1,
+ lease_secs: 90,
+ min_free_disk_mb: 1024,
+ max_transient_attempts: 3,
+ dispatch_tick_secs: 2,
}
}
}
diff --git a/src/db/builds.rs b/src/db/builds.rs
index d251566..0a7013c 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -422,3 +422,65 @@ pub fn current_state(c: &Connection, id: &str) -> Result<String> {
.optional()?
.unwrap_or_default())
}
+
+/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and
+/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one
+/// writer the claim cannot race: the SELECT and the UPDATE are the same
+/// transaction, so no other claimer can see a row in between.
+pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+ let owner = owner.to_string();
+ let exp = time::secs_ahead(lease_secs);
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ let ids: Vec<String> = {
+ let mut stmt = tx.prepare(
+ "SELECT id FROM build WHERE state='queued'
+ ORDER BY priority DESC, created_at LIMIT ?1",
+ )?;
+ let rows = stmt.query_map(params![limit as i64], |r| r.get::<_, String>(0))?;
+ rows.filter_map(|r| r.ok()).collect()
+ };
+ for id in &ids {
+ tx.execute(
+ "UPDATE build SET state='leased', lease_owner=?1, lease_expires_at=?2,
+ attempt=attempt+1, updated_at=?3
+ WHERE id=?4 AND state='queued'",
+ params![owner, exp, at, id],
+ )?;
+ }
+ Ok(ids)
+ })
+}
+
+/// A newer approved release for the same pkgbase makes an in-flight build
+/// pointless (§8.2 cancellation). Workers notice at the next step boundary and
+/// stop; nothing is killed mid-step, which is what keeps the checkpoints honest.
+pub fn cancel_superseded(db: &Db) -> Result<usize> {
+ db.writer.tx(move |tx| {
+ let n = tx.execute(
+ "UPDATE build SET cancel_requested=1
+ WHERE state IN ('queued','leased','running')
+ AND candidate_id IN (SELECT id FROM candidate WHERE state='superseded')",
+ [],
+ )?;
+ Ok(n)
+ })
+}
+
+/// Put a build back on the queue after a transient failure, keeping the attempt
+/// count so the retry cap can bite (§8.4).
+pub fn requeue_transient(db: &Db, id: &str) -> Result<()> {
+ let id = id.to_string();
+ let at = time::now();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL,
+ error=NULL, updated_at=?1 WHERE id=?2",
+ params![at, id],
+ )?;
+ Ok(())
+ })
+}
diff --git a/src/main.rs b/src/main.rs
index b88e757..7297a96 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -125,8 +125,12 @@ fn main() -> anyhow::Result<()> {
// behind the database, close the gap before anyone asks for it.
let _ = pipeline::publish::reconcile(&cfg, &db);
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop);
+ aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone());
let _server = aur_build::http::spawn(cfg.clone(), db.clone())?;
+ // The dispatcher reaps expired leases before its first claim, so a
+ // restart recovers whatever a crash left leased without any special
+ // startup routine (§8.2).
+ let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone());
println!("serving on http://{} — ctrl-c to stop", cfg.bind);
// Single process, thread per connection: the main thread has nothing to
// do but wait to be killed.
diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs
new file mode 100644
index 0000000..62052fd
--- /dev/null
+++ b/src/pipeline/dispatch.rs
@@ -0,0 +1,203 @@
+//! The dispatcher actor, the worker pool and the reaper (§8.2).
+//!
+//! Shape: one dispatcher thread, N worker threads, one crossbeam channel
+//! between them. The dispatcher's loop is
+//!
+//! ```text
+//! reaper: expired leases -> queued, in-flight step -> interrupted
+//! cancel: superseded in-flight builds -> cancel_requested
+//! claim: BEGIN IMMEDIATE { SELECT queued LIMIT admissible; UPDATE leased }
+//! send: build_tx.send(id) for each
+//! ```
+//!
+//! Nothing lives only in a worker's memory. If the process is killed, the lease
+//! expires and the next dispatcher pass puts the build back; the step
+//! checkpoint decides where it resumes (I5). That is the whole crash-recovery
+//! story, and it is why there is no separate "recover on startup" routine — the
+//! reaper pass *is* the recovery, and it runs first in every loop.
+
+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};
+
+/// Handle on a running pool. Dropping without `shutdown` leaves the threads
+/// running; call `shutdown` to join them cleanly.
+pub struct Pool {
+ stop: Arc<AtomicBool>,
+ handles: Vec<JoinHandle<()>>,
+}
+
+impl Pool {
+ /// Start the dispatcher and `max_concurrent_builds` workers.
+ pub fn spawn(cfg: Arc<Config>, db: Db) -> Pool {
+ let stop = Arc::new(AtomicBool::new(false));
+ let workers = cfg.max_concurrent_builds.max(1);
+ // Bounded at the worker count: the dispatcher must not run ahead and
+ // lease builds that no worker has picked up yet, because a leased build
+ // whose worker never starts would sit until its lease expires.
+ let (tx, rx) = bounded::<String>(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(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(move || dispatcher(cfg2, db2, stop2, tx))
+ .expect("spawn dispatcher"),
+ );
+
+ Pool { stop, handles }
+ }
+
+ /// Ask the threads to stop and wait for them. A build that is mid-step will
+ /// finish that step, fail its lease, and be requeued by the next process's
+ /// reaper — which is the designed behaviour, not a bug to wait out.
+ pub fn shutdown(self) {
+ self.stop.store(true, Ordering::SeqCst);
+ for h in self.handles {
+ let _ = h.join();
+ }
+ }
+}
+
+fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) {
+ // The reaper pass runs first on every loop, including the very first one, so
+ // "recover from a crash" and "notice an expired lease" are the same code
+ // path. There is no special startup recovery to get wrong.
+ while !stop.load(Ordering::SeqCst) {
+ dispatch_once(&cfg, &db, &tx);
+ let mut slept = 0u64;
+ while slept < cfg.dispatch_tick_secs && !stop.load(Ordering::SeqCst) {
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ slept += 1;
+ }
+ }
+}
+
+/// One dispatcher pass. Returns the ids handed to workers. Public so a test can
+/// drive one pass deterministically instead of racing a thread.
+pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> {
+ 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();
+ }
+ // Blocked builds become eligible again when the blocking package arrives.
+ let _ = builds::requeue_blocked(db);
+ // A newer approval makes an in-flight build pointless (§8.2).
+ 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() {
+ // No worker to take it: give the lease back rather than let it
+ // expire with nobody holding it.
+ let _ = builds::requeue_transient(db, id);
+ }
+ }
+ ids
+}
+
+/// How many builds may be admitted right now (§8.2 backpressure):
+/// `min(max_concurrent - in_flight, disk headroom)`. A build that cannot fit on
+/// disk is not admitted — it stays queued rather than filling the filesystem
+/// halfway through a compile.
+pub fn admissible(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
+}
+
+/// Megabytes free on the filesystem holding `path`.
+pub fn free_disk_mb(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 {
+ // If we cannot find out, do not block the queue over a measurement
+ // problem; the pipeline's own disk guard is the backstop.
+ 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<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, stop: Arc<AtomicBool>) {
+ 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, .. }) => {
+ // §8.4: transient failures (network, mirror 5xx) retry with a
+ // bounded number of attempts. A deterministic build failure
+ // does NOT retry — the release stays approved_but_unbuilt and
+ // the UI says "index still serving v1". Retrying that would burn
+ // a chroot to produce the same failure.
+ 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;
+ }
+ }
+}
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 37aae77..459cea6 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -6,6 +6,7 @@
//! is serialized per repo (I4).
pub mod publish;
+pub mod dispatch;
mod steps;
use std::path::PathBuf;
diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs
index 5d03a06..d54314e 100644
--- a/src/pipeline/publish.rs
+++ b/src/pipeline/publish.rs
@@ -58,7 +58,20 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
}
/// Publish the collected artifacts of a build. Returns the new release id.
+/// One publish at a time per repo (§8.2, §9). With `max_concurrent_builds > 1`
+/// two workers could otherwise interleave the index rewrite; the critical
+/// section is the db file rewrite only, never a build.
+static PUBLISH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
pub fn publish(ctx: &Ctx) -> Result<i64> {
+ let _guard = match PUBLISH_LOCK.lock() {
+ Ok(g) => g,
+ // A previous publish panicked while holding it. The index on disk is
+ // still whatever was last renamed into place — atomic publish means a
+ // poisoned lock cannot have left a half-written db — so we clear the
+ // poison and continue rather than wedge the queue forever.
+ Err(p) => p.into_inner(),
+ };
let collect = Collect::load(&ctx.collect_path)?;
if collect.packages.is_empty() {
return Err(Error::invalid("nothing to publish"));