pub mod dispatch; pub mod publish; mod steps; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use crate::config::Config; use crate::db::model::{BuildState, CandidateRow, ReleaseRow, StepState}; use crate::db::SnapshotRow; use crate::db::{self, builds, Db, Pkgbase}; use crate::error::{Error, Missing, Result}; use crate::sandbox::{Sandbox, SandboxBackend}; #[derive(Debug, Clone)] pub(crate) struct SourceIdentity { pub aur_commit: String, pub recipe_hash: String, pub upstream_pins_json: String, pub source_digests_json: String, pub epoch: String, pub pkgver: String, pub pkgrel: String, } impl SourceIdentity { fn from_candidate(c: &CandidateRow, snapshot: &SnapshotRow) -> Self { Self { aur_commit: snapshot.aur_commit.clone(), recipe_hash: snapshot.recipe_hash.clone(), upstream_pins_json: c.upstream_pins_json.clone(), source_digests_json: c.source_digests_json.clone(), epoch: c.epoch.clone(), pkgver: c.pkgver.clone(), pkgrel: c.pkgrel.clone(), } } fn from_release(r: &ReleaseRow) -> Self { Self { aur_commit: r.aur_commit.clone(), recipe_hash: r.recipe_hash.clone(), upstream_pins_json: r.upstream_pins_json.clone(), source_digests_json: r.source_digests_json.clone(), epoch: r.epoch.clone(), pkgver: r.pkgver.clone(), pkgrel: r.pkgrel.clone(), } } pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct CollectedPkg { pub name: String, pub version: String, pub arch: String, pub path: String, pub digest: String, pub size: u64, pub signature_path: Option, pub depends: Vec, pub makedepends: Vec, pub provides: Vec, pub conflicts: Vec, pub installed: Vec<(String, String)>, } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] struct Collect { pub packages: Vec, } impl Collect { pub fn load(path: &std::path::Path) -> Result { if !path.exists() { return Ok(Self::default()); } Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) } pub fn save(&self, path: &std::path::Path) -> Result<()> { std::fs::write(path, serde_json::to_string_pretty(self)?)?; Ok(()) } } pub struct Ctx { pub cfg: Config, pub db: Db, pub build: builds::BuildRow, pub pb: Pkgbase, pub(crate) src: SourceIdentity, pub staging: PathBuf, pub srcdir: PathBuf, pub collect_path: PathBuf, pub log: PathBuf, pub profile: String, pub attempt: i64, pub backend: Arc, } impl Ctx { pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result { let build = builds::get(db, build_id)?.ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?; let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase for build"))?; let src = if let Some(cid) = build.candidate_id { let c = crate::review::reads::candidate(db, cid)?.ok_or_else(|| Error::not_found("candidate for build"))?; let snap = db::snapshot_by_id(db, c.snapshot_id)?.ok_or_else(|| Error::not_found("snapshot for candidate"))?; SourceIdentity::from_candidate(&c, &snap) } else { let rid = build.release_id.ok_or_else(|| Error::invalid("build has neither candidate nor release"))?; let r = db::release_by_id(db, rid)?.ok_or_else(|| Error::not_found("release for rebuild"))?; SourceIdentity::from_release(&r) }; let attempt = build.attempt; let profile = build.build_profile.clone(); let staging = cfg.staging_build_dir(build_id); let srcdir = staging.join("src"); let collect_path = staging.join("collect.json"); Ok(Self { cfg: cfg.clone(), db: db.clone(), build, pb, src, staging, srcdir, collect_path, log: cfg.build_log_path(build_id), profile, attempt, backend: crate::sandbox::backend_for(cfg)?, }) } pub fn sandbox(&self) -> Result> { let spec = crate::sandbox::SandboxSpec { profile: self.profile.clone(), task: self.build.id.clone(), ttl: Duration::from_secs(self.cfg.lease_secs.max(1) as u64), }; self.backend.acquire(&spec) } fn log_line(&self, line: &str) { use std::io::Write; if let Some(parent) = self.log.parent() { let _ = std::fs::create_dir_all(parent); } if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.log) { let _ = writeln!(f, "{line}"); } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { Succeeded { release_id: i64 }, Failed { step: String, error: String, transient: bool }, Blocked { on: Vec }, Cancelled, } pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result { let ctx = Ctx::new(cfg, db, build_id)?; db::audit_system( &db.writer, "build.start", "build", build_id, serde_json::json!({"pkgbase": ctx.pb.name, "version": ctx.src.version(), "attempt": ctx.attempt}), )?; run_with(&ctx) } /// Production calls `run`, which supplies the real sandbox; a test injects a fake, which is the point of the seam. /// /// 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 run_with(ctx: &Ctx) -> Result { run_with_impl(ctx) } #[cfg(not(feature = "test-support"))] fn run_with(ctx: &Ctx) -> Result { run_with_impl(ctx) } fn run_with_impl(ctx: &Ctx) -> Result { std::fs::create_dir_all(&ctx.staging)?; for step in crate::db::model::BUILD_STEPS { if crate::db::builds::cancel_requested(&ctx.db, &ctx.build.id)? { builds::set_state(&ctx.db, &ctx.build.id, BuildState::Cancelled, Some("cancelled"))?; return Ok(Outcome::Cancelled); } let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; if status.is_some_and(|s| s.is_done()) { continue; } builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::Running, None)?; ctx.log_line(&format!("==> step {step} (attempt {})", ctx.attempt)); match steps::run_step(ctx, step) { Ok(StepResult::Done(digest)) => { builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Succeeded, digest.as_deref(), None)?; builds::extend_lease(&ctx.db, &ctx.build.id, ctx.cfg.lease_secs)?; } Ok(StepResult::Skipped(why)) => { ctx.log_line(&format!(" skipped: {why}")); builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Skipped, None, None)?; } Ok(StepResult::Blocked(on)) => { builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Pending, None, Some("blocked"))?; builds::block_on(&ctx.db, &ctx.build.id, &on)?; ctx.log_line(&format!(" blocked on: {}", on.join(", "))); return Ok(Outcome::Blocked { on }); } Err(e) => { let transient = e.is_transient(); builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Failed, None, Some(&e.to_string()))?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::Failed, Some(&format!("{step}: {e}")))?; ctx.log_line(&format!("!! {step} failed: {e}")); return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); } } } let release_id = ctx.release_id().ok_or_else(|| Error::other("publish produced no release"))?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::Succeeded, None)?; db::audit_system( &ctx.db.writer, "build.succeeded", "build", &ctx.build.id, serde_json::json!({"release": release_id}), )?; Ok(Outcome::Succeeded { release_id }) } impl Ctx { fn release_id(&self) -> Option { builds::get(&self.db, &self.build.id).ok().flatten().and_then(|b| b.release_id) } } pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result { let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?.ok_or_else(|| Error::not_found("pkgbase"))?; let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile); let world_id = db::put_world_snapshot(&db.writer, &world)?; builds::enqueue(db, &id, pb.id, Some(c.id), "new_version", Some(world_id), &cfg.build_profile, 0)?; Ok(id) } pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result { let pb = db::get_pkgbase(db, pkgbase)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?; let rel = db::accepted_release(db, pkgbase)? .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; let identity = format!( "sha256:{}", crate::hash::hex( crate::hash::canonical_json(&serde_json::json!({ "aur_commit": rel.aur_commit, "recipe_hash": rel.recipe_hash, "upstream_pins": rel.pins(), "source_digests": rel.digests(), "requested": "manual_rebuild", }))? .as_bytes() ) ); let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; let id = builds::build_id(pkgbase, &identity, &world_hash, &cfg.build_profile); let world_id = db::put_world_snapshot(&db.writer, &world)?; builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?; let id_for_tx = id.clone(); let rid = rel.id; db.writer.tx(move |tx| builds::set_release_in(tx, &id_for_tx, rid))?; Ok(id) } enum StepResult { Done(Option), Skipped(String), Blocked(Vec), }