summaryrefslogtreecommitdiffstats
path: root/src/pipeline/publish.rs
blob: 7340e53111cc9d22e152771e42a998fc092b26f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;

use crate::config::Config;
use crate::db::{self, builds, candidates, CandidateState, Db, WorldMember};
use crate::error::{Error, Result};
use crate::pipeline::{Collect, Ctx};
use crate::time;

/// One writer to the served repo at a time — *the* serialization guarantee for
/// the index (§8.2, §9, I4). A publish renders a new database in scratch space,
/// commits the DB, then renames over the live one; a second writer interleaving
/// anywhere in that sequence produces an index matching neither DB state. Held by
/// [`publish`] and [`withdraw_package`] for the whole sequence; [`reconcile`] skips
/// it because it runs before the dispatcher exists.
///
/// A panic while holding it is recovered rather than propagated: atomic publish
/// means a poisoned lock cannot have left a half-written database.
static REPO_LOCK: Mutex<()> = Mutex::new(());

fn lock_repo() -> std::sync::MutexGuard<'static, ()> {
    match REPO_LOCK.lock() {
        Ok(g) => g,
        Err(p) => p.into_inner(),
    }
}

/// The world a build is admitted against: every pkgbase's accepted version.
pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> {
    let rels = db::all_published_releases(db)?;
    let mut out = Vec::new();
    for r in rels {
        let pb = db::get_pkgbase_by_id(db, r.pkgbase_id)?;
        if let Some(pb) = pb {
            out.push(WorldMember { pkgbase: pb.name, version: r.version() });
        }
    }
    Ok(out)
}

/// Package files that belong in the served index right now, plus the extra ones
/// being published (not in the DB yet when the new index is rendered).
fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut out: Vec<PathBuf> = Vec::new();
    for p in db::index_packages(db)? {
        if let Some(aid) = p.artifact_id {
            if let Some(p) = db::artifact_path(db, aid)?.map(PathBuf::from).filter(|p| p.exists()) {
                out.push(p);
            }
        }
    }
    out.extend(extra.iter().cloned());
    Ok(out)
}

/// Publish the collected artifacts of a build. Returns the new release id.
///
/// Serialized against every other writer of the index by [`REPO_LOCK`].
pub fn publish(ctx: &Ctx) -> Result<i64> {
    let _guard = lock_repo();
    let collect = Collect::load(&ctx.collect_path)?;
    if collect.packages.is_empty() {
        return Err(Error::invalid("nothing to publish"));
    }
    let repo_row = repo_for(&ctx.db)?;
    let arch_dir = ctx.cfg.repo_arch_dir();
    std::fs::create_dir_all(&arch_dir)?;

    // Artifacts are copied into the served tree under their real filenames.
    let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new();
    // Set once the render starts, so the failure path can sweep the scratch
    // directory even if the publish died after repo-add returned.
    let mut scratch_dir: Option<PathBuf> = None;
    // Files this publish created that were not there before: if the publish does
    // not land they are orphans no index names (§6 m-16).
    let mut fresh: Vec<PathBuf> = Vec::new();
    for p in &collect.packages {
        let from = PathBuf::from(&p.path);
        let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch);
        let dest = arch_dir.join(&filename);
        let sig_dest = arch_dir.join(format!("{filename}.sig"));
        let existed = dest.exists();
        std::fs::copy(&from, &dest)?;
        if let Some(sig) = &p.signature_path {
            let s = PathBuf::from(sig);
            if s.exists() {
                std::fs::copy(&s, &sig_dest)?;
            }
        }
        if !existed {
            fresh.push(dest.clone());
            if sig_dest.exists() {
                fresh.push(sig_dest.clone());
            }
        }
        staged.push((dest, from));
    }

    let outcome = (|| -> Result<i64> {
        // 1. render the new database; the live one is untouched until step 3.
        let db_name = ctx.cfg.repo_db_name();
        let final_db = arch_dir.join(format!("{db_name}.tar.gz"));
        let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?;
        pkgs = dedupe_by_name(pkgs);
        let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?;

        // Fault injection so I4 can be tested for real (§6 M-9).
        #[cfg(feature = "test-support")]
        if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") {
            return Err(Error::other("injected fault: before-rename"));
        }

        // 2. commit the DB: release + package rows + the accepted pointer, in
        //    one transaction, with the pointer moved by compare-and-swap.
        let release_id = commit_release(ctx, &collect)?;

        // 3. atomic swap: rename over the real database, then sign the new bytes.
        rendered.swap_into(&final_db)?;
        sign(&ctx.cfg, &final_db)?;

        // 4. a publish can unblock builds waiting on a dependency we just added.
        let unblocked = builds::requeue_blocked(&ctx.db)?;
        db::audit_system(
            &ctx.db.writer,
            "publish",
            "repo",
            &repo_row,
            serde_json::json!({
                "release": release_id,
                "packages": collect.packages.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>(),
                "unblocked_builds": unblocked,
            }),
        )?;
        #[cfg(feature = "test-support")]
        if ctx.cfg.hooks.publish_fault.as_deref() == Some("after-rename") {
            return Err(Error::other("injected fault: after-rename"));
        }
        Ok(release_id)
    })();

    if outcome.is_err() {
        // Nothing in the served tree may look like a publish that did not land
        // (m-16); files already there belong to the release still served.
        for p in &fresh {
            let _ = std::fs::remove_file(p);
        }
        if let Some(s) = &scratch_dir {
            let _ = std::fs::remove_dir_all(s);
        }
    }
    outcome
}

fn repo_for(db: &Db) -> Result<String> {
    let id = db::repo_id(db)?;
    Ok(id.to_string())
}

/// Insert the release and its package rows, and move the accepted pointer.
fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> {
    let at = time::now();
    let pkgbase_id = ctx.pb.id;
    let candidate_id = ctx.build.candidate_id;
    let approval_id: Option<i64> = match candidate_id {
        Some(cid) => crate::review::approve::approval_for(&ctx.db, cid)?.map(|(id, _)| id),
        None => None,
    };
    // I1: nothing publishes without an approval. A manual rebuild inherits the
    // approval of the release it rebuilds.
    let inherited = match ctx.build.kind.as_str() {
        "manual_rebuild" => ctx
            .build
            .release_id
            .and_then(|rid| db::release_by_id(&ctx.db, rid).ok().flatten())
            .and_then(|r| r.approval_id),
        _ => None,
    };
    let approval_id = approval_id.or(inherited).ok_or_else(|| {
        Error::fail_closed(format!(
            "refusing to publish a {} build with no approval behind it",
            ctx.build.kind
        ))
    })?;

    let build_id = ctx.build.id.clone();
    let packages = collect.packages.clone();
    let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect();
    let src = ctx.src.clone();
    let world_id = builds::get(&ctx.db, &build_id)
        .ok()
        .flatten()
        .and_then(|b| b.world_snapshot_id);
    let repo_id = db::repo_id(&ctx.db)?;
    // The compare-and-swap baseline is the release the *approval* was taken
    // against, not whatever the pointer says now.
    let expected_base: Option<i64> = match ctx.build.kind.as_str() {
        "manual_rebuild" => ctx.build.release_id,
        _ => ctx
            .build
            .candidate_id
            .and_then(|cid| crate::review::candidates::candidate_by_id(&ctx.db, cid).ok().flatten())
            .and_then(|c| c.base_release_id),
    };

    ctx.db.writer.tx(move |tx| {
        // Compare-and-swap inside the write transaction (I4).
        let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?;
        if actual_base != expected_base {
            return Err(Error::conflict(
                "accepted pointer moved while this build was running; refusing to publish",
            ));
        }
        // The index holds exactly the accepted pointer, so what it held for these
        // names goes before the new rows go in.
        db::remove_index_packages_in(tx, &names)?;
        let release_id = db::insert_release_in(
            tx,
            &db::NewRelease {
                pkgbase_id,
                candidate_id,
                approval_id: Some(approval_id),
                aur_commit: &src.aur_commit,
                recipe_hash: &src.recipe_hash,
                upstream_pins_json: &src.upstream_pins_json,
                source_digests_json: &src.source_digests_json,
                epoch: &src.epoch,
                pkgver: &src.pkgver,
                pkgrel: &src.pkgrel,
                world_snapshot_id: world_id,
                build_id: &build_id,
            },
            &at,
        )?;
        for p in &packages {
            db::insert_package_in(tx, repo_id, release_id, &p.name, &p.arch, &p.version, &p.digest)?;
        }
        if !db::cas_accepted_release_in(tx, pkgbase_id, release_id, expected_base)? {
            return Err(Error::conflict(
                "accepted pointer moved while this build was running; refusing to publish",
            ));
        }
        builds::set_release_in(tx, &build_id, release_id)?;
        if let Some(cid) = candidate_id {
            candidates::resolve_in(tx, cid, CandidateState::Approved, &at)?;
        }
        Ok(release_id)
    })
}

/// Remove scratch directories a crash left behind: the leading dot means nothing
/// a consumer asks for, and only a render creates one.
pub fn sweep_render_dirs(arch_dir: &Path) {
    let Ok(entries) = std::fs::read_dir(arch_dir) else {
        return;
    };
    for entry in entries.flatten() {
        if entry.file_name().to_string_lossy().starts_with(".render-") {
            let _ = std::fs::remove_dir_all(entry.path());
        }
    }
}

/// A database repo-add has rendered, and the scratch directory it rendered into.
struct Rendered {
    db: PathBuf,
    dir: PathBuf,
    arch_dir: PathBuf,
}

impl Rendered {
    /// The publish point: rename over the live database, fsync the directory
    /// entry, then drop the scratch directory.
    fn swap_into(self, final_db: &Path) -> Result<()> {
        std::fs::rename(&self.db, final_db)?;
        fsync_dir(&self.arch_dir)?;
        let _ = std::fs::remove_dir_all(&self.dir);
        Ok(())
    }
}

/// Render a fresh database with repo-add, ready to be renamed into place.
///
/// repo-add refuses any database argument that is not a name pacman itself would
/// accept, so the render happens in a scratch directory *under* the served
/// directory, under the exact name a consumer will download. Same filesystem, so
/// the caller's `rename` is still the atomic swap I4 requires.
///
/// `scratch` is filled in as soon as the directory exists, so the caller can sweep
/// it even if this function is never reached again.
fn render_db(
    cfg: &Config,
    arch_dir: &Path,
    tag: &str,
    pkgs: &[PathBuf],
    scratch: &mut Option<PathBuf>,
) -> Result<Rendered> {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dir = arch_dir.join(format!(".render-{}-{n}-{tag}", std::process::id()));
    std::fs::create_dir_all(&dir)?;
    *scratch = Some(dir.clone());
    let db = dir.join(format!("{}.tar.gz", cfg.repo_db_name()));
    let rendered = Rendered { db, dir, arch_dir: arch_dir.to_path_buf() };
    let attempt = (|| -> Result<()> {
        run_repo_add(cfg, &rendered.db, pkgs)?;
        fsync_file(&rendered.db)?;
        Ok(())
    })();
    if let Err(e) = attempt {
        let _ = std::fs::remove_dir_all(&rendered.dir);
        *scratch = None;
        return Err(e);
    }
    Ok(rendered)
}

/// `repo-add -R <db> <pkgs...>`, deliberately *not* `-s`: repo-add would sign into
/// scratch space that gets deleted. The hub signs the live file itself in [`sign`].
fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> {
    let mut cmd = Command::new(&cfg.repo_add_bin);
    cmd.arg("-R");
    cmd.arg(db_path);
    for p in pkgs {
        cmd.arg(p);
    }
    cfg.child_env(&mut cmd);
    let out = cmd.output()?;
    if !out.status.success() {
        return Err(Error::Subprocess {
            cmd: cfg.repo_add_bin.clone(),
            detail: String::from_utf8_lossy(&out.stderr).into_owned(),
        });
    }
    Ok(())
}

fn sign(cfg: &Config, path: &Path) -> Result<()> {
    if cfg.signing_key_id.is_empty() {
        return Ok(());
    }
    let sig = format!("{}.sig", path.display());
    sign_to(cfg, path, Path::new(&sig))
}

/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. The key never
/// leaves the hub — a build sandbox signs nothing (§8).
pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> {
    if cfg.signing_key_id.is_empty() {
        return Ok(());
    }
    let mut cmd = Command::new(&cfg.gpg_bin);
    cmd.args(["--batch", "--yes", "--detach-sign", "--local-user", &cfg.signing_key_id]);
    cmd.arg("-o");
    let tmp = format!("{}.tmp", sig_out.display());
    cmd.arg(&tmp);
    cmd.arg(path);
    cfg.child_env(&mut cmd);
    let out = cmd.output()?;
    if !out.status.success() {
        return Err(Error::Subprocess {
            cmd: cfg.gpg_bin.clone(),
            detail: String::from_utf8_lossy(&out.stderr).into_owned(),
        });
    }
    std::fs::rename(&tmp, sig_out)?;
    Ok(())
}

/// fsync, and *say so* when it fails (m-7). Swallowing the error would make the
/// write-scratch-fsync-rename promise a comment rather than a guarantee.
fn fsync_file(p: &Path) -> Result<()> {
    let f = std::fs::File::open(p)
        .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?;
    f.sync_all()
        .map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?;
    Ok(())
}

fn fsync_dir(p: &Path) -> Result<()> {
    let d = std::fs::File::open(p)
        .map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?;
    d.sync_all()
        .map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?;
    Ok(())
}


/// Keep one entry per package name; the newest file wins. The name comes from
/// `.PKGINFO`, not the filename, because package names contain dashes.
fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut seen: BTreeSet<String> = BTreeSet::new();
    let mut out: Vec<PathBuf> = Vec::new();
    for p in paths.into_iter().rev() {
        let name = package_name(&p).unwrap_or_else(|| {
            p.file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_default()
        });
        if seen.insert(name) {
            out.push(p);
        }
    }
    out.reverse();
    out
}

/// The package name a built artifact declares, read from its own `.PKGINFO`.
///
/// The name that goes into the index must come from the same read of the bytes the
/// pipeline signs, so this uses the real parser (§6 M-4).
fn package_name(path: &Path) -> Option<String> {
    let bytes = std::fs::read(path).ok()?;
    let info = crate::pkginfo::pkginfo_text(&bytes).ok()?;
    let name = crate::pkginfo::parse_pkginfo(&info).name;
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// Re-materialize the served index from the DB. Run at startup: if a crash left
/// the DB ahead of the file, this closes the gap without inventing anything.
pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> {
    let pkgs = db::index_packages(db)?;
    let mut files = Vec::new();
    for p in &pkgs {
        if let Some(aid) = p.artifact_id {
            if let Some(path) = db::artifact_path(db, aid)?.map(PathBuf::from).filter(|p| p.exists()) {
                let arch_dir = cfg.repo_arch_dir();
                let _ = std::fs::create_dir_all(&arch_dir);
                let dest = arch_dir.join(format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch));
                if !dest.exists() {
                    let _ = std::fs::copy(&path, &dest);
                }
                files.push(dest);
            }
        }
    }
    if files.is_empty() {
        return Ok(0);
    }
    let arch_dir = cfg.repo_arch_dir();
    sweep_render_dirs(&arch_dir);
    let mut scratch = None;
    let rendered = render_db(cfg, &arch_dir, "reconcile", &dedupe_by_name(files.clone()), &mut scratch)?;
    rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?;
    Ok(files.len())
}

/// Remove a package from the served index (§9 withdrawal path).
pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> {
    let _guard = lock_repo();
    let rid = db::repo_id(db)?;
    let n = name.to_string();
    db.writer.tx(move |tx| db::remove_package_by_name_in(tx, rid, &n))?;
    let arch_dir = cfg.repo_arch_dir();
    let mut scratch = None;
    let files = index_artifacts(db, &[])?;
    let rendered = render_db(cfg, &arch_dir, "withdraw", &dedupe_by_name(files), &mut scratch)?;
    rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?;
    db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?;
    Ok(())
}