summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: b88e7576f20a8a1f761ebc5f32bc65a541c52dac (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
//! `aur-build` — the operator's command line (§7.2, §12).
//!
//! P0 ships the approval path as a CLI subcommand: the same code the web UI
//! will call in P2, so the invariant "we build exactly what was displayed, or
//! nothing" is enforced here too. `approve` renders the review, prints it, and
//! then approves with the hashes it just displayed — it cannot approve a diff it
//! did not show you.

use std::path::PathBuf;

use clap::{Parser, Subcommand};

use aur_build::config::Config;
use aur_build::db::{self, builds, model::*};
use aur_build::pipeline;
use aur_build::review::{approve as ap, candidates, diff};

#[derive(Parser)]
#[command(name = "aur-build", version, about = "AUR build server: nothing is published that a human did not approve")]
struct Cli {
    /// Server root (holds config.json, db, mirrors, repo).
    #[arg(short, long, env = "AUR_BUILD_ROOT", global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Create the root, config and database.
    Init {
        #[arg(long)]
        repo: Option<String>,
        #[arg(long)]
        signing_key: Option<String>,
    },
    /// Start watching a pkgbase.
    Subscribe {
        pkgbase: String,
        /// Override the AUR URL; a `file://` path is fine, which is how the
        /// test suite drives the real binary.
        #[arg(long)]
        url: Option<String>,
    },
    /// Stop watching a pkgbase.
    Unsubscribe { pkgbase: String },
    /// Poll AUR now (without this, detection runs on the watcher's schedule).
    Detect { pkgbase: Option<String> },
    /// List reviews.
    Reviews {
        #[arg(long)]
        all: bool,
    },
    /// Show one review: the diff panels and the two hashes an approval must echo.
    Show { candidate: i64 },
    /// Approve a review. Without --yes this only prints what would be approved.
    Approve {
        candidate: i64,
        #[arg(long)]
        yes: bool,
        #[arg(long)]
        note: Option<String>,
        /// Approve against hashes you were shown earlier instead of re-rendering.
        #[arg(long)]
        identity: Option<String>,
        #[arg(long)]
        diff: Option<String>,
    },
    /// Reject a review with a reason.
    Reject {
        candidate: i64,
        #[arg(long)]
        note: String,
    },
    /// Queue a build for a pending review.
    Build { candidate: i64 },
    /// Queue a rebuild of the currently accepted version (no new approval, I6).
    Rebuild { pkgbase: String },
    /// Run a queued build to completion in this process.
    Run { build: String },
    /// List builds.
    Builds,
    /// Show a build's step timeline.
    Status { build: String },
    /// Show the current index.
    Packages,
    /// Run the web server and the watcher until interrupted.
    Serve {
        /// Override the bind address, e.g. 127.0.0.1:8484.
        #[arg(long)]
        bind: Option<String>,
    },
    /// Show recent audit rows.
    Audit {
        #[arg(long, default_value_t = 30)]
        limit: i64,
    },
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    let cfg = match &cli.root {
        Some(r) => Config::load(r).unwrap_or_else(|_| Config {
            root: r.clone(),
            ..Config::default()
        }),
        None => Config::load(&Config::default().root)?,
    };
    if let Cmd::Serve { bind } = &cli.cmd {
        let mut cfg = cfg;
        if let Some(b) = bind {
            cfg.bind = b.clone();
        }
        cfg.ensure_dirs()?;
        db::migrate(&cfg.db_path())?;
        let db = db::Db::open_migrated(&cfg.db_path())?;
        db::ensure_repo(
            &db.writer,
            &cfg.repo_name,
            &cfg.repo_arch_dir().display().to_string(),
            &cfg.arch,
            &cfg.signing_key_id,
        )?;
        // Re-materialize the served index from the DB: if a crash left the file
        // behind the database, close the gap before anyone asks for it.
        let _ = pipeline::publish::reconcile(&cfg, &db);
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop);
        let _server = aur_build::http::spawn(cfg.clone(), db.clone())?;
        println!("serving on http://{} — ctrl-c to stop", cfg.bind);
        // Single process, thread per connection: the main thread has nothing to
        // do but wait to be killed.
        loop {
            std::thread::sleep(std::time::Duration::from_secs(3600));
        }
    }
    let ctx = Ctx::open(&cfg)?;
    match cli.cmd {
        // Handled above, before the CLI's own database context is opened.
        Cmd::Serve { .. } => Ok(()),
        Cmd::Init { repo, signing_key } => {
            let mut cfg = cfg;
            if let Some(r) = repo {
                cfg.repo_name = r;
            }
            if let Some(k) = signing_key {
                cfg.signing_key_id = k;
            }
            cfg.save()?;
            cfg.ensure_dirs()?;
            db::migrate(&cfg.db_path())?;
            let db = db::Db::open_migrated(&cfg.db_path())?;
            let rid = db::ensure_repo(
                &db.writer,
                &cfg.repo_name,
                &cfg.repo_arch_dir().display().to_string(),
                &cfg.arch,
                &cfg.signing_key_id,
            )?;
            println!("initialized {} (repo id {rid})", cfg.root.display());
            println!("add to pacman.conf:\n  [{}]\n  Server = {}/$repo/os/$arch", cfg.repo_name, cfg.base_url);
            Ok(())
        }
        Cmd::Subscribe { pkgbase, url } => {
            let rid = db::repo_id(&ctx.db)?;
            let url = url.unwrap_or_else(|| format!("https://aur.archlinux.org/{pkgbase}.git"));
            db::subscribe(&ctx.db.writer, rid, &pkgbase, &url)?;
            println!("subscribed {pkgbase} ({url})");
            Ok(())
        }
        Cmd::Unsubscribe { pkgbase } => {
            db::set_subscription_state(&ctx.db.writer, &pkgbase, subscription_state::REMOVED)?;
            println!("unsubscribed {pkgbase}");
            Ok(())
        }
        Cmd::Detect { pkgbase } => {
            let names: Vec<String> = match pkgbase {
                Some(n) => vec![n],
                None => db::list_subscriptions(&ctx.db)?
                    .into_iter()
                    .filter(|s| s.state == subscription_state::ACTIVE)
                    .map(|s| s.pkgbase)
                    .collect(),
            };
            for n in names {
                match aur_build::watch::detect::check_pkgbase(&cfg, &ctx.db, &n) {
                    Ok(r) => println!("{n}: {:?}", r.outcome),
                    Err(e) => eprintln!("{n}: {e}"),
                }
            }
            Ok(())
        }
        Cmd::Reviews { all } => {
            let rows = if all {
                candidates::all_candidates(&ctx.db)?
            } else {
                candidates::pending_candidates(&ctx.db)?
            };
            if rows.is_empty() {
                println!("nothing pending");
            }
            for c in rows {
                println!(
                    "#{:<5} {:<28} {:<16} {:<10} rev{} {}",
                    c.id,
                    c.pkgbase,
                    aur_build::pkgver::full_version(&c.epoch, &c.pkgver, &c.pkgrel),
                    c.kind,
                    c.revision,
                    c.state
                );
            }
            Ok(())
        }
        Cmd::Show { candidate } => {
            let c = need_candidate(&ctx.db, candidate)?;
            let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?;
            candidates::set_diff_digest(&ctx.db, c.id, &digest)?;
            candidates::mark_viewed(&ctx.db, c.id)?;
            println!("{text}");
            println!("---");
            println!("identity_hash: {}", c.identity_hash);
            println!("diff_digest:   {digest}");
            println!("approve with:  aur-build approve {} --yes", c.id);
            Ok(())
        }
        Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => {
            let c = need_candidate(&ctx.db, candidate)?;
            // Render first, always. The hashes we send are the hashes of what we
            // just rendered, unless the operator explicitly names older ones.
            let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?;
            candidates::set_diff_digest(&ctx.db, c.id, &digest)?;
            let identity = identity.unwrap_or_else(|| c.identity_hash.clone());
            let diff_arg = diff_arg.unwrap_or(digest);
            println!("{text}");
            println!("---");
            if !yes {
                println!("not approved: re-run with --yes to approve exactly this");
                return Ok(());
            }
            let who = whoami();
            match ap::approve(&ctx.db, &who, c.id, &identity, &diff_arg, note.as_deref()) {
                Ok(a) => {
                    println!("approved #{} (approval {})", c.id, a.id);
                    let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?;
                    println!("queued build {id}");
                    println!("run it with:  aur-build run {id}");
                    Ok(())
                }
                Err(stale) => {
                    eprintln!("refused: {stale}");
                    std::process::exit(2)
                }
            }
        }
        Cmd::Reject { candidate, note } => {
            let c = need_candidate(&ctx.db, candidate)?;
            let who = whoami();
            ap::reject(&ctx.db, &who, c.id, &note)?;
            println!("rejected #{}", c.id);
            Ok(())
        }
        Cmd::Build { candidate } => {
            let c = need_candidate(&ctx.db, candidate)?;
            let id = pipeline::enqueue_for_candidate(&cfg, &ctx.db, &c)?;
            println!("queued build {id}");
            Ok(())
        }
        Cmd::Rebuild { pkgbase } => {
            let id = pipeline::enqueue_manual_rebuild(&cfg, &ctx.db, &pkgbase)?;
            println!("queued rebuild {id}");
            Ok(())
        }
        Cmd::Run { build } => match pipeline::run(&cfg, &ctx.db, &build)? {
            pipeline::Outcome::Succeeded { release_id } => {
                println!("succeeded (release {release_id})");
                Ok(())
            }
            pipeline::Outcome::Blocked { on } => {
                println!("blocked on: {}", on.join(", "));
                std::process::exit(3)
            }
            pipeline::Outcome::Cancelled => {
                println!("cancelled");
                std::process::exit(0)
            }
            pipeline::Outcome::Failed { step, error, .. } => {
                eprintln!("failed at {step}: {error}");
                std::process::exit(1)
            }
        },
        Cmd::Builds => {
            for b in builds::list(&ctx.db, &[build_state::QUEUED, build_state::RUNNING, build_state::LEASED, build_state::BLOCKED_MISSING_DEP], 50)? {
                println!("{:<66} {:<20} {}", b.id, b.state, b.current_step.unwrap_or_default());
            }
            Ok(())
        }
        Cmd::Status { build } => {
            for s in builds::steps(&ctx.db, &build)? {
                println!("{:<12} {:<12} {}", s.step, s.status, s.error.unwrap_or_default());
            }
            Ok(())
        }
        Cmd::Packages => {
            for p in db::index_packages(&ctx.db)? {
                println!("{:<28} {:<16} {}", p.name, p.version, p.arch);
            }
            Ok(())
        }
        Cmd::Audit { limit } => {
            for a in db::list_audit(&ctx.db, limit)? {
                println!("{} [{}] {} {} {} {}", a.at, a.actor_kind, a.actor, a.action, a.entity_id, a.detail_json);
            }
            Ok(())
        }
    }
}

struct Ctx {
    db: db::Db,
}

impl Ctx {
    fn open(cfg: &Config) -> anyhow::Result<Self> {
        cfg.ensure_dirs()?;
        db::migrate(&cfg.db_path())?;
        let db = db::Db::open_migrated(&cfg.db_path())?;
        db::ensure_repo(
            &db.writer,
            &cfg.repo_name,
            &cfg.repo_arch_dir().display().to_string(),
            &cfg.arch,
            &cfg.signing_key_id,
        )?;
        Ok(Self { db })
    }
}

fn whoami() -> String {
    std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "cli".into())
}

fn need_candidate(db: &db::Db, id: i64) -> anyhow::Result<CandidateRow> {
    candidates::candidate_by_id(db, id)?
        .ok_or_else(|| anyhow::anyhow!("no candidate #{id}"))
}