diff options
Diffstat (limited to 'src/pipeline/steps.rs')
| -rw-r--r-- | src/pipeline/steps.rs | 456 |
1 files changed, 456 insertions, 0 deletions
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs new file mode 100644 index 0000000..b925afb --- /dev/null +++ b/src/pipeline/steps.rs @@ -0,0 +1,456 @@ +//! The ten pipeline steps (§8.1). +//! +//! Every step is idempotent and records its result in one short transaction; +//! the long-running child process happens outside any transaction (§11a). + +use std::path::Path; +use std::process::Command; + +use crate::db::{self, builds, model::*}; +use crate::error::{Error, Result}; +use crate::git; +use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult}; +use crate::watch::digests::cached_path; + +pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> { + match step { + "materialize" => materialize(ctx), + "plan" => plan(ctx), + "chroot" => chroot(ctx), + "sources" => sources(ctx), + "pkgver" => pkgver(ctx), + "build" => build(ctx), + "collect" => collect(ctx), + "verify" => verify(ctx), + "ingest" => ingest(ctx), + "publish" => publish(ctx), + other => Err(Error::invalid(format!("unknown step {other}"))), + } +} + +/// Step 0 — materialize from the local mirror only, never the network, and +/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no +/// path from "AUR moved since the review" to "we built it anyway". +fn materialize(ctx: &Ctx) -> Result<StepResult> { + let mirror = ctx + .pb + .mirror_path + .as_ref() + .map(Path::new) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name)); + if !mirror.exists() { + return Err(Error::fail_closed(format!( + "mirror {} missing; refusing to fetch a recipe from the network at build time", + mirror.display() + ))); + } + if ctx.src.aur_commit.is_empty() { + return Err(Error::fail_closed("no aur_commit on the source identity")); + } + let _ = std::fs::remove_dir_all(&ctx.srcdir); + git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?; + let tree = crate::watch::mirror::read_tree(&mirror, &ctx.src.aur_commit)?; + let computed = tree.recipe_hash(); + if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash { + return Err(Error::fail_closed(format!( + "recipe_hash mismatch: approved {}, materialized {}", + ctx.src.recipe_hash, computed + ))); + } + ctx.log_line(&format!( + " materialized {} at {} (recipe_hash {})", + ctx.pb.name, + short(&ctx.src.aur_commit), + short(&computed) + )); + Ok(StepResult::Done(Some(computed))) +} + +/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny. +fn short(s: &str) -> String { + s.chars().take(12).collect() +} + +/// Step 1 — resolve dependencies against the current accepted index and compute +/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have +/// not published yet": block and wait, do not fail (§10.4). +fn plan(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let mut wanted: Vec<String> = Vec::new(); + for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] { + wanted.extend(crate::pkgver::dep_names(list)); + } + wanted.sort(); + wanted.dedup(); + + let ours = db::our_package_names(&ctx.db)?; + let mut missing = Vec::new(); + let mut official = 0; + for dep in &wanted { + if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) { + continue; // satisfied by our own index, or by this very build + } + // Anything else is only a problem if we are supposed to be publishing it. + if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() { + missing.push(dep.clone()); + } else { + official += 1; + } + } + if !missing.is_empty() { + builds::set_blocked_on(&ctx.db, &ctx.build.id, &missing)?; + return Ok(StepResult::Blocked(missing)); + } + let world = crate::pipeline::publish::index_world(&ctx.db)?; + let hash = crate::hash::canonical_json(&world); + ctx.log_line(&format!( + " deps: {} ours/official, {} from official repos, world {}", + wanted.len() - official, + official, + short(&hash) + )); + Ok(StepResult::Done(Some(hash))) +} + +/// Step 2 — warm chroot seed, created once per profile and never mutated; each +/// build gets a copy-on-write snapshot from it (§8.3). +fn chroot(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + if !seed.exists() { + std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?; + let mut cmd = Command::new(&ctx.cfg.mkarchroot_bin); + cmd.args(["-N", &seed.display().to_string()]); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.mkarchroot_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + ctx.log_line(&format!(" created chroot seed {}", seed.display())); + } + Ok(StepResult::Done(Some(seed.display().to_string()))) +} + +/// Step 3 — make sure every source we reviewed is on disk and hashes to what the +/// candidate recorded. For a `SKIP` source this is the only verification that +/// exists, and it closes the window between "we hashed it at review time" and +/// "makepkg downloaded something else just now" (§8.1). +fn sources(ctx: &Ctx) -> Result<StepResult> { + let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default(); + let mut verified = 0; + for d in &digests { + match d.kind.as_str() { + // Already materialized from the mirror at the pinned commit. + "local" => verified += 1, + // VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time + // is deferred to P1 (§20); the pkgver assertion is the interim guard. + "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1, + _ => { + let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) { + Some(p) => crate::hash::digest_file(&p)?, + None => crate::watch::digests::download_and_cache(&ctx.cfg, &ctx.db, &d.url)?, + }; + if digest != d.digest { + return Err(Error::fail_closed(format!( + "source {} hashed to {digest} but the candidate recorded {}", + d.url, d.digest + ))); + } + verified += 1; + } + } + } + ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str( + &ctx.src.source_digests_json, + )))) +} + +/// Step 4 — the belt-and-braces assertion that what we build is what was +/// approved. If upstream moved between approval and build, fail with both +/// versions instead of silently shipping the new one (§8.1). +fn pkgver(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); + if !has_vcs { + let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone()); + let got = (recipe.pkgver.clone(), recipe.pkgrel.clone()); + if want != got { + return Err(Error::fail_closed(format!( + "approved {}-{} but the recipe says {}-{}", + want.0, want.1, got.0, got.1 + ))); + } + return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into())); + } + let mut cmd = Command::new(&ctx.cfg.makepkg_bin); + cmd.current_dir(&ctx.srcdir).arg("--vercheck"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makepkg_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let (got_ver, got_rel) = match text.rsplit_once('-') { + Some((v, r)) => (v.to_string(), r.to_string()), + None => (text.clone(), "1".into()), + }; + if got_ver != ctx.src.pkgver || got_rel != ctx.src.pkgrel { + return Err(Error::fail_closed(format!( + "approved {}-{}, upstream now resolves to {got_ver}-{got_rel}", + ctx.src.pkgver, ctx.src.pkgrel + ))); + } + ctx.log_line(&format!(" pkgver resolves as approved: {text}")); + Ok(StepResult::Done(Some(text))) +} + +/// Step 5 — `makechrootpkg -c -r <chroot> -- -si<key> -f`, with the log going to +/// the file the SSE tail reads. +fn build(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + let mut cmd = Command::new(&ctx.cfg.makechrootpkg_bin); + cmd.current_dir(&ctx.srcdir); + cmd.args(["-c", "-r", &seed.display().to_string(), "--"]); + if !ctx.cfg.signing_key_id.is_empty() { + cmd.arg(format!("-si{}", ctx.cfg.signing_key_id)); + } + cmd.arg("-f"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + // Capture the child's output into the build log regardless of outcome. + if let Some(parent) = ctx.log.parent() { + let _ = std::fs::create_dir_all(parent); + } + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log) { + let _ = f.write_all(&out.stdout); + let _ = f.write_all(&out.stderr); + } + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makechrootpkg_bin.clone(), + detail: tail(&out.stderr), + }); + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "build:{}", + ctx.build.id + ))))) +} + +fn tail(b: &[u8]) -> String { + let s = String::from_utf8_lossy(b).trim().to_string(); + let lines: Vec<&str> = s.lines().collect(); + lines[lines.len().saturating_sub(6)..].join(" | ") +} + +/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1: +/// plain text in a tar, no libalpm needed). +fn collect(ctx: &Ctx) -> Result<StepResult> { + let mut pkgs = Vec::new(); + let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) + .collect(); + entries.sort(); + for path in entries { + let bytes = std::fs::read(&path)?; + let (digest, size) = crate::hash::digest_file(&path)?; + let pkginfo = crate::shims::read_pkginfo(&bytes) + .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; + let buildinfo = crate::shims::read_buildinfo(&bytes).unwrap_or_default(); + let meta = parse_pkginfo(&pkginfo); + let sig = path.with_extension("pkg.tar.zst.sig"); + pkgs.push(CollectedPkg { + name: meta.get("pkgname").cloned().unwrap_or_default(), + version: meta.get("pkgver").cloned().unwrap_or_default(), + arch: meta.get("pkgarch").cloned().unwrap_or_else(|| ctx.cfg.arch.clone()), + path: path.display().to_string(), + digest, + size, + signature_path: sig.exists().then(|| sig.display().to_string()), + depends: meta_multi(&pkginfo, "depend"), + makedepends: meta_multi(&pkginfo, "makedepend"), + provides: meta_multi(&pkginfo, "provides"), + conflicts: meta_multi(&pkginfo, "conflict"), + installed: parse_installed(&buildinfo), + }); + } + if pkgs.is_empty() { + return Err(Error::invalid("build produced no packages")); + } + let collect = Collect { packages: pkgs.clone() }; + collect.save(&ctx.collect_path)?; + // A split pkgbase is one approval and N index entries (§3). + ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", "))); + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) +} + +/// Step 7 — signature present, dependencies satisfiable, no downgrade. +fn verify(ctx: &Ctx) -> Result<StepResult> { + let collect = Collect::load(&ctx.collect_path)?; + let ours = db::our_package_names(&ctx.db)?; + for p in &collect.packages { + if p.signature_path.is_none() && !ctx.cfg.signing_key_id.is_empty() { + return Err(Error::fail_closed(format!("{} has no signature", p.name))); + } + if crate::pkgver::is_downgrade( + &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), + &p.version, + ) { + // Downgrades are allowed but flagged (§16); the review already shows it. + ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name)); + } + let mut provided: std::collections::BTreeSet<String> = ours.clone(); + provided.extend(collect.packages.iter().map(|q| q.name.clone())); + provided.extend(p.provides.iter().flat_map(|v| crate::pkgver::dep_names(std::slice::from_ref(v)))); + for dep in crate::pkgver::dep_names(&p.depends) { + if !provided.contains(&dep) && db::get_pkgbase(&ctx.db, &dep)?.is_some() { + return Err(Error::fail_closed(format!( + "{} depends on {dep}, which is not satisfiable in the target repo", + p.name + ))); + } + } + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string( + &collect.packages.iter().map(|p| (&p.name, &p.version)).collect::<Vec<_>>(), + )?)))) +} + +/// Step 8 — move artifacts into the content-addressed store and record rows. +/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2). +fn ingest(ctx: &Ctx) -> Result<StepResult> { + let mut collect = Collect::load(&ctx.collect_path)?; + for p in &mut collect.packages { + let from = Path::new(&p.path); + let dest = ctx.cfg.store_path(&p.digest); + if !dest.exists() { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::copy(from, &dest)?; + } + p.path = dest.display().to_string(); + if let Some(sig) = p.signature_path.clone() { + let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest)); + if !sigdest.exists() && Path::new(&sig).exists() { + std::fs::copy(&sig, &sigdest)?; + } + p.signature_path = Some(sigdest.display().to_string()); + } + } + collect.save(&ctx.collect_path)?; + + let at = crate::time::now(); + let packages = collect.packages.clone(); + let packages_for_db = packages.clone(); + let build_id = ctx.build.id.clone(); + let log_path = ctx.log.display().to_string(); + ctx.db.writer.tx(move |tx| { + for p in &packages_for_db { + tx.execute( + "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at) + VALUES (?1,?2,?3,?4,?5,?6,?7) + ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id", + rusqlite::params![p.digest, p.size as i64, p.path, p.signature_path, log_path, build_id, at], + )?; + } + Ok(()) + })?; + + // §10.1: the world snapshot is the build's installed set INTERSECTED with our + // own packages, filtered at ingest time, not at query time. Left unfiltered, + // every package would be permanently stale because Arch never stops moving. + let ours = db::our_package_names(&ctx.db)?; + let mut members: Vec<WorldMember> = Vec::new(); + for p in &collect.packages { + for (name, version) in &p.installed { + if ours.contains(name) { + members.push(WorldMember { pkgbase: name.clone(), version: version.clone() }); + } + } + } + let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?; + builds::set_world(&ctx.db, &ctx.build.id, world_id)?; + ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "ingest:{}", + packages.len() + ))))) +} + +/// Step 9 — the only externally visible step, serialized per repo (§9). +fn publish(ctx: &Ctx) -> Result<StepResult> { + let release_id = crate::pipeline::publish::publish(ctx)?; + Ok(StepResult::Done(Some(format!("release:{release_id}")))) +} + +// ---------------------------------------------------------------- helpers -- + +use std::path::PathBuf; + +/// Read the recipe from a materialized tree, preferring `.SRCINFO`. +pub fn recipe_at(dir: &Path) -> Result<Recipe> { + let mut files = std::collections::BTreeMap::new(); + for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) { + let p = entry.path(); + if !p.is_file() { + continue; + } + let rel = p.strip_prefix(dir).unwrap_or(p).display().to_string(); + if let Ok(body) = std::fs::read_to_string(p) { + files.insert(rel, body); + } + } + crate::recipe::recipe_from_tree(&files) +} + +fn parse_pkginfo(text: &str) -> std::collections::HashMap<String, String> { + let mut m = std::collections::HashMap::new(); + for line in text.lines() { + if let Some((k, v)) = line.split_once('=') { + m.insert(k.trim().to_string(), v.trim().to_string()); + } + } + m +} + +fn meta_multi(text: &str, key: &str) -> Vec<String> { + text.lines() + .filter_map(|l| l.split_once('=')) + .filter(|(k, _)| k.trim() == key) + .map(|(_, v)| v.trim().to_string()) + .collect() +} + +/// `.BUILDINFO` `installed =` block: ` name version arch sig` per line. +fn parse_installed(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut in_block = false; + for line in text.lines() { + if line.trim_start().starts_with("installed") { + in_block = true; + continue; + } + if in_block { + if !line.starts_with(' ') && !line.starts_with('\t') { + in_block = false; + continue; + } + let mut it = line.split_whitespace(); + if let (Some(name), Some(version)) = (it.next(), it.next()) { + out.push((name.to_string(), version.to_string())); + } + } + } + out +} |
