summaryrefslogtreecommitdiffstats
path: root/src/pipeline/steps.rs
blob: 9703d546c85ee4c02d79deb863b951c5aa357cf5 (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
use std::path::Path;

use crate::db::{
    self, builds,
    model::{Recipe, SourceDigest, WorldMember},
};
use crate::error::{Error, Guard, Result, WorldGap};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
use crate::sandbox::Cmd;
use crate::watch::sources;

pub(crate) fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> {
    match step {
        "materialize" => materialize(ctx),
        "plan" => plan(ctx),
        "chroot" => provision(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}"))),
    }
}

fn materialize(ctx: &Ctx) -> Result<StepResult> {
    let mirror = ctx
        .pb
        .mirror_path
        .as_ref()
        .map(Path::new)
        .map_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name), std::path::Path::to_path_buf);
    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 computed = sources::recipe_hash(&mirror, &ctx.src.aur_commit)?;
    if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash {
        return Err(Error::fail_closed(Guard::HashMismatch {
            what: "recipe_hash",
            approved: ctx.src.recipe_hash.clone(),
            computed,
        }));
    }
    ctx.log_line(&format!(
        "    materialized {} at {} (recipe_hash {})",
        ctx.pb.name,
        short(&ctx.src.aur_commit),
        short(&computed)
    ));
    Ok(StepResult::Done(Some(computed)))
}

fn short(s: &str) -> String {
    s.chars().take(12).collect()
}

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;
        }
        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)))
}

fn provision(ctx: &Ctx) -> Result<StepResult> {
    let lease = lease_manifest(ctx)?;
    if lease.is_empty() {
        return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into()));
    }
    let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) };
    for e in &lease {
        let path = ctx.cfg.store_path(&e.digest);
        let (digest, _) = crate::hash::digest_file(&path)?;
        if digest != e.digest {
            return Err(Error::fail_closed(Guard::DigestMismatch {
                url: format!("{}-{}", e.name, e.version),
                expected: e.digest.clone(),
                found: digest,
            }));
        }
        let mut f = std::fs::File::open(&path)?;
        sbx.put(&e.digest, &mut f)?;
    }
    let mut argv = vec![ctx.cfg.pacman_bin.clone(), "-U".into(), "--noconfirm".into()];
    argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest)));
    let out = sbx.run(&Cmd::new(argv), &mut |_| {})?;
    if !out.success() {
        return Err(Error::world_mismatch(format!(
            "{} -U refused the lease set: {}",
            ctx.cfg.pacman_bin,
            tail(&out.stderr)
        )));
    }
    let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?;
    if !q.success() {
        return Err(Error::fail_closed(format!("{} -Q failed: {}", ctx.cfg.pacman_bin, tail(&q.stderr))));
    }
    let installed: std::collections::BTreeSet<(String, String)> = String::from_utf8_lossy(&q.stdout)
        .lines()
        .filter_map(|l| {
            let mut it = l.split_whitespace();
            let (name, ver) = (it.next()?, it.next()?);
            Some((name.to_string(), ver.to_string()))
        })
        .collect();
    for e in &lease {
        if !installed.contains(&(e.name.clone(), e.version.clone())) {
            return Err(Error::world_mismatch(WorldGap::MissingPin { package: format!("{}-{}", e.name, e.version) }));
        }
    }
    ctx.log_line(&format!(
        "    provisioned {} pinned package(s): {}",
        lease.len(),
        lease.iter().map(|e| format!("{}-{}", e.name, e.version)).collect::<Vec<_>>().join(", ")
    ));
    let world: Vec<(&str, &str)> = lease.iter().map(|e| (e.name.as_str(), e.version.as_str())).collect();
    Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?)))
}

fn sandbox_or_wait(ctx: &Ctx) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> {
    match ctx.sandbox() {
        Ok(s) => Ok(Some(s)),
        Err(e) if e.is_pool_exhausted() => {
            ctx.log_line("    blocked: no sandbox available in the pool");
            Ok(None)
        }
        Err(e) => Err(e),
    }
}

#[derive(Debug, Clone)]
struct LeasePkg {
    name: String,
    version: String,
    digest: String,
}

fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> {
    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 mut out = Vec::new();
    for dep in wanted {
        if dep == ctx.pb.name || recipe.pkgnames.contains(&dep) {
            continue;
        }
        if let Some((version, digest)) = db::index_artifact(&ctx.db, &dep)? {
            out.push(LeasePkg { name: dep, version, digest });
        }
    }
    Ok(out)
}

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() {
            "local" => verified += 1,
            "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1,
            _ => {
                sources::verify_cached(&ctx.cfg, &ctx.db, &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))))
}

fn pkgver(ctx: &Ctx) -> Result<StepResult> {
    let recipe = recipe_at(&ctx.srcdir)?;
    let has_vcs = recipe.source_entries.iter().any(super::super::db::model::SourceEntry::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 cmd = vec![ctx.cfg.makepkg_bin.clone(), "--vercheck".to_string()];
    let sbx = ctx.sandbox()?;
    let out = sbx.run(&Cmd::new(cmd).in_dir(&ctx.srcdir), &mut |_| {})?;
    if !out.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)))
}

fn build(ctx: &Ctx) -> Result<StepResult> {
    let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()];
    let Some(sbx) = sandbox_or_wait(ctx)? else { return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])) };
    if let Some(parent) = ctx.log.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    use std::io::Write;
    let mut log_file = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log).ok();
    let mut on_log = move |bytes: &[u8]| {
        if let Some(f) = log_file.as_mut() {
            let _ = f.write_all(bytes);
        }
    };
    let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?;
    drop(on_log);
    if !out.success() {
        return Err(Error::Subprocess { cmd: ctx.cfg.makepkg_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(" | ")
}

fn collect(ctx: &Ctx) -> Result<StepResult> {
    let mut pkgs = Vec::new();
    let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)?
        .filter_map(std::result::Result::ok)
        .map(|e| e.path())
        .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst"))
        .collect();
    entries.sort();
    let staging_root = ctx.staging.canonicalize()?;
    for path in entries {
        if std::fs::symlink_metadata(&path).map_or(true, |m| m.file_type().is_symlink()) {
            return Err(Error::fail_closed(format!(
                "{} is a symlink; a build may not smuggle bytes in from outside its own staging dir",
                path.display()
            )));
        }
        let resolved = path.canonicalize()?;
        if !resolved.starts_with(&staging_root) {
            return Err(Error::fail_closed(format!(
                "{} resolves outside this build's staging dir ({}); refusing to ingest it",
                path.display(),
                staging_root.display()
            )));
        }
        let path = resolved;
        let bytes = std::fs::read(&path)?;
        let (digest, size) = crate::hash::digest_file(&path)?;
        let pkginfo =
            crate::pkginfo::pkginfo_text(&bytes).map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
        let meta = crate::pkginfo::parse_pkginfo(&pkginfo);
        let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default();
        let sig = path.with_extension("pkg.tar.zst.sig");
        pkgs.push(CollectedPkg {
            name: meta.name.clone(),
            version: meta.version.clone(),
            arch: if meta.arch.is_empty() { ctx.cfg.arch.clone() } else { meta.arch.clone() },
            path: path.display().to_string(),
            digest,
            size,
            signature_path: sig.exists().then(|| sig.display().to_string()),
            depends: meta.depends.clone(),
            makedepends: meta.makedepends.clone(),
            provides: meta.provides.clone(),
            conflicts: meta.conflicts.clone(),
            installed: crate::pkginfo::parse_installed(&buildinfo).into_iter().map(|i| (i.name, i.version)).collect(),
        });
    }
    if pkgs.is_empty() {
        return Err(Error::invalid("build produced no packages"));
    }
    let collect = Collect { packages: pkgs.clone() };
    collect.save(&ctx.collect_path)?;
    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)?))))
}

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 crate::pkgver::is_downgrade(&db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), &p.version)
        {
            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<_>>(),
    )?))))
}

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 !ctx.cfg.signing_key_id.is_empty() {
            let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest));
            if !sigdest.exists() {
                crate::pipeline::publish::sign_to(&ctx.cfg, Path::new(&p.path), &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 {
            db::insert_artifact_in(
                tx,
                &db::NewArtifact {
                    digest: &p.digest,
                    size: p.size as i64,
                    path: &p.path,
                    signature_path: p.signature_path.as_deref(),
                    build_log_path: Some(&log_path),
                    build_id: &build_id,
                    at: &at,
                },
            )?;
        }
        Ok(())
    })?;

    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())))))
}

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;

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(std::result::Result::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)
}