summaryrefslogtreecommitdiffstats
path: root/src/pipeline/mod.rs
blob: 3e63a69a24e75718e781c2b738d804629deffda5 (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
pub mod publish;
pub mod dispatch;
mod steps;

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use crate::config::Config;
use crate::db::{self, builds, Db, Pkgbase};
use crate::db::model::*;
use crate::db::SnapshotRow;
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<String>,
    pub depends: Vec<String>,
    pub makedepends: Vec<String>,
    pub provides: Vec<String>,
    pub conflicts: Vec<String>,
    pub installed: Vec<(String, String)>,
}

#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct Collect {
    pub packages: Vec<CollectedPkg>,
}

impl Collect {
    pub fn load(path: &std::path::Path) -> Result<Self> {
        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<dyn SandboxBackend>,
}

impl Ctx {
    pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> {
        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 = match build.candidate_id {
            Some(cid) => {
                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)
            }
            None => {
                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<Arc<dyn Sandbox>> {
        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<String> },
    Cancelled,
}

pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result<Outcome> {
    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<Outcome> {
    run_with_impl(ctx)
}

#[cfg(not(feature = "test-support"))]
fn run_with(ctx: &Ctx) -> Result<Outcome> {
    run_with_impl(ctx)
}

fn run_with_impl(ctx: &Ctx) -> Result<Outcome> {
    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<i64> {
        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<String> {
    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<String> {
    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<String>),
    Skipped(String),
    Blocked(Vec<String>),
}