OXYGENHUB
◆ oh-comment-body-file oxygenhub / crates / hub / src / main.rs
15.4 KiB · Rust · last changed A stop no longer waits on blocking work past the drain 19 days ago source blame history raw
1
//! `oxygenhub`: `init`, `serve`, `admin`, `check` (hub spec §17.3).
2
3
use clap::{Parser, Subcommand};
4
use hub_api::Visibility;
5
use oxygenhub::config::Config;
6
use oxygenhub::repos::RepoName;
7
use oxygenhub::{db, keys};
8
use std::path::PathBuf;
9
10
#[derive(Parser)]
11
#[command(name = "oxygenhub", version, about = "A forge for Oxygen repositories")]
12
struct Cli {
13
    /// The data directory (hub spec §3.2)
14
    #[arg(long, global = true, env = "OXYHUB_DATA", default_value = "data")]
15
    data: PathBuf,
16
    #[command(subcommand)]
17
    cmd: Cmd,
18
}
19
20
#[derive(Subcommand)]
21
enum Cmd {
22
    /// Create the data directory, keys, database and a default hub.toml
23
    Init {
24
        /// What links and clone URLs start with
25
        #[arg(long)]
26
        base_url: Option<String>,
27
        /// Generate a self-signed TLS certificate (developer edition)
28
        #[arg(long)]
29
        self_signed: bool,
30
    },
31
    /// Run the hub
32
    Serve,
33
    /// Offline administration
34
    Admin {
35
        #[command(subcommand)]
36
        cmd: AdminCmd,
37
    },
38
    /// Verify every repository's objects and signatures
39
    Check,
40
    /// Garbage-collect every repository now, as the nightly job does
41
    Gc,
42
}
43
44
#[derive(Subcommand)]
45
enum AdminCmd {
46
    /// Repositories
47
    Repo {
48
        #[command(subcommand)]
49
        cmd: RepoCmd,
50
    },
51
    /// Accounts
52
    User {
53
        #[command(subcommand)]
54
        cmd: UserCmd,
55
    },
56
    /// Backups (docs/backups.md)
57
    Backup {
58
        #[command(subcommand)]
59
        cmd: BackupCmd,
60
    },
61
    /// Copy a SQLite hub's records into this hub's empty PostgreSQL
62
    /// database, to move a hub (docs/postgres.md)
63
    #[cfg(feature = "postgres")]
64
    CopyDb {
65
        /// The old hub's `hub.db`, from a stopped hub (or a copy of one)
66
        #[arg(long)]
67
        from: PathBuf,
68
        /// Empty this database's tables first (a fresh hub's, a rehearsal's)
69
        #[arg(long)]
70
        replace: bool,
71
    },
72
}
73
74
#[derive(Subcommand)]
75
enum BackupCmd {
76
    /// Back up a user's or organisation's repositories now, as its settings say
77
    Run { owner: String },
78
    /// Restore every repository of a whole run from a backup directory
79
    /// (the one holding LATEST, runs/ and blobs/) into this hub
80
    Restore {
81
        #[arg(long)]
82
        from: std::path::PathBuf,
83
        /// The run (runs/<RUN>); the latest whole one when not given
84
        #[arg(long)]
85
        run: Option<String>,
86
    },
87
}
88
89
#[derive(Subcommand)]
90
enum UserCmd {
91
    /// Create an account with a generated password, printed once
92
    Create {
93
        username: String,
94
        #[arg(long, default_value = "")]
95
        email: String,
96
        /// Make it a site administrator
97
        #[arg(long)]
98
        admin: bool,
99
    },
100
    /// Reset an account's password to a new generated one, printed once
101
    ResetPassword { username: String },
102
    /// List accounts
103
    List,
104
}
105
106
#[derive(Subcommand)]
107
enum RepoCmd {
108
    /// Create an empty repository OWNER/NAME
109
    Create {
110
        slug: String,
111
        #[arg(long, default_value = "")]
112
        description: String,
113
        #[arg(long, default_value = "public")]
114
        visibility: String,
115
        /// Bind to this repository id now (32 hex characters, from `.oxy/id`);
116
        /// otherwise the first push binds it
117
        #[arg(long)]
118
        id: Option<String>,
119
    },
120
    /// List repositories
121
    List,
122
    /// Move a repository to the trash
123
    Delete { slug: String },
124
    /// Change the description, default bookmark or visibility
125
    Set {
126
        slug: String,
127
        #[arg(long)]
128
        description: Option<String>,
129
        #[arg(long)]
130
        default_bookmark: Option<String>,
131
        #[arg(long)]
132
        visibility: Option<String>,
133
    },
134
}
135
136
fn main() -> anyhow::Result<()> {
137
    tune_allocator();
138
    let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
139
    rt.spawn(return_freed_memory());
140
    let out = rt.block_on(run());
141
    oxygenhub::shutdown::finish(rt);
142
    out
143
}
144
145
/// glibc's allocator gives each thread that allocates an arena of its own
146
/// and keeps what is freed in it: under the hub's worker threads, loaded
147
/// states that the cache had let go still held their pages, and the hub
148
/// grew to 12 GB with its state cache capped at 3 GiB (oxygenhub#117).
149
/// Two arenas, as oxy found for its own threads; MALLOC_ARENA_MAX in the
150
/// environment still has the last word. Called before any thread starts.
151
fn tune_allocator() {
152
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
153
    if std::env::var_os("MALLOC_ARENA_MAX").is_none() {
154
        // SAFETY: mallopt is called once, before any other thread exists.
155
        unsafe {
156
            libc::mallopt(libc::M_ARENA_MAX, 2);
157
        }
158
    }
159
}
160
161
/// Hand freed memory back to the system every minute, so the hub's size
162
/// follows what it holds rather than its peak (oxygenhub#117).
163
async fn return_freed_memory() {
164
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
165
    loop {
166
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
167
        // SAFETY: malloc_trim only releases free pages.
168
        let _ = tokio::task::spawn_blocking(|| unsafe { libc::malloc_trim(0) }).await;
169
    }
170
}
171
172
async fn run() -> anyhow::Result<()> {
173
    tracing_subscriber::fmt()
174
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env().add_directive("oxygenhub=info".parse()?))
175
        .init();
176
    let cli = Cli::parse();
177
    match cli.cmd {
178
        Cmd::Init { base_url, self_signed } => init(&cli.data, base_url, self_signed).await,
179
        Cmd::Serve => {
180
            let config = Config::load(&cli.data)?;
181
            let app = oxygenhub::build(config).await?;
182
            oxygenhub::serve(app).await
183
        }
184
        Cmd::Admin { cmd: AdminCmd::Repo { cmd } } => {
185
            let config = Config::load(&cli.data)?;
186
            let app = oxygenhub::build(config).await?;
187
            repo_admin(&app, cmd).await
188
        }
189
        Cmd::Admin { cmd: AdminCmd::Backup { cmd } } => {
190
            let config = Config::load(&cli.data)?;
191
            let app = oxygenhub::build(config).await?;
192
            match cmd {
193
                BackupCmd::Run { owner } => {
194
                    let r = oxygenhub::backups::run(&app, &owner, "now").await?;
195
                    println!(
196
                        "{} {}: {} repositories, {} of {} files sent ({} KiB){}",
197
                        r.status,
198
                        r.at,
199
                        r.repos,
200
                        r.sent,
201
                        r.files,
202
                        r.bytes / 1024,
203
                        if r.detail.is_empty() { String::new() } else { format!(": {}", r.detail) }
204
                    );
205
                    if r.status == "failed" {
206
                        std::process::exit(1);
207
                    }
208
                    Ok(())
209
                }
210
                BackupCmd::Restore { from, run } => {
211
                    let dest: std::sync::Arc<dyn oxygenhub::backups::Destination> =
212
                        std::sync::Arc::new(oxygenhub::backups::Directory { root: from });
213
                    for d in oxygenhub::backups::restore_into_hub(&app, dest, run).await? {
214
                        println!("restored {d}");
215
                    }
216
                    Ok(())
217
                }
218
            }
219
        }
220
        #[cfg(feature = "postgres")]
221
        Cmd::Admin { cmd: AdminCmd::CopyDb { from, replace } } => {
222
            let config = Config::load(&cli.data)?;
223
            let pool = db::open(&config).await?;
224
            let copied = db::copy::from_sqlite(&pool, &from, replace).await?;
225
            for (table, n) in &copied {
226
                println!("{n:>9}  {table}");
227
            }
228
            println!("copied {} rows in {} tables", copied.iter().map(|(_, n)| n).sum::<i64>(), copied.len());
229
            Ok(())
230
        }
231
        Cmd::Admin { cmd: AdminCmd::User { cmd } } => {
232
            let config = Config::load(&cli.data)?;
233
            let app = oxygenhub::build(config).await?;
234
            user_admin(&app, cmd).await
235
        }
236
        Cmd::Check => {
237
            let config = Config::load(&cli.data)?;
238
            let app = oxygenhub::build(config).await?;
239
            check(&app).await
240
        }
241
        Cmd::Gc => {
242
            let config = Config::load(&cli.data)?;
243
            let app = oxygenhub::build(config).await?;
244
            let done = oxygenhub::maintenance::gc_all(&app).await;
245
            for d in &done {
246
                println!("{d}");
247
            }
248
            if done.iter().any(|d| d.failed) {
249
                anyhow::bail!("a repository could not be garbage collected");
250
            }
251
            Ok(())
252
        }
253
    }
254
}
255
256
async fn init(data: &PathBuf, base_url: Option<String>, self_signed: bool) -> anyhow::Result<()> {
257
    std::fs::create_dir_all(data)?;
258
    let toml_path = data.join("hub.toml");
259
    if !toml_path.exists() {
260
        let base = base_url.clone().unwrap_or_else(|| "http://127.0.0.1:7300".into());
261
        let mut text = String::from("# OxygenHub configuration (docs/spec.md section 17.1)\n\n[site]\nname = \"OxygenHub\"\n\n[server]\nbind = \"127.0.0.1:7300\"\n");
262
        if self_signed {
263
            text.push_str("tls_bind = \"0.0.0.0:7343\"\n");
264
        }
265
        text.push_str(&format!("base_url = \"{base}\"\n\n[tls]\nself_signed = {self_signed}\n\n[auth]\n# Bearer tokens allowed to push until accounts exist.\npush_tokens = []\n"));
266
        std::fs::write(&toml_path, text)?;
267
        println!("wrote {}", toml_path.display());
268
    }
269
    let mut config = Config::load(data)?;
270
    if let Some(b) = base_url {
271
        config.server.base_url = b;
272
    }
273
    let app = oxygenhub::build(config).await?;
274
    println!("hub key {}", app.hub_key.key.to_hex());
275
    if (self_signed || app.config.tls.self_signed)
276
        && keys::ensure_self_signed(&app.config.tls_cert(), &app.config.tls_key(), app.config.base_url())?
277
    {
278
        println!("wrote self-signed certificate {}", app.config.tls_cert().display());
279
    }
280
    println!("data directory {} is ready", data.display());
281
    Ok(())
282
}
283
284
async fn repo_admin(app: &oxygenhub::Shared, cmd: RepoCmd) -> anyhow::Result<()> {
285
    match cmd {
286
        RepoCmd::Create { slug, description, visibility, id } => {
287
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
288
            let visibility = Visibility::parse(&visibility).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?;
289
            let id = match id {
290
                Some(h) => {
291
                    let bytes = hex::decode(h.trim()).ok().and_then(|v| <[u8; 16]>::try_from(v).ok());
292
                    Some(bytes.ok_or_else(|| anyhow::anyhow!("--id takes 32 hex characters"))?)
293
                }
294
                None => None,
295
            };
296
            if db::repos::get(&app.db, &name.owner, &name.name).await?.is_some() {
297
                anyhow::bail!("{name} already exists");
298
            }
299
            app.repos.create(&name, id)?;
300
            db::repos::create(&app.db, &name.owner, &name.name, &description, visibility).await?;
301
            println!("created {name}: oxy clone {}/{name}", app.config.base_url());
302
        }
303
        RepoCmd::List => {
304
            for r in db::repos::list(&app.db).await? {
305
                println!("{:<40} {:<8} {}", r.slug(), r.visibility, r.description);
306
            }
307
        }
308
        RepoCmd::Delete { slug } => {
309
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
310
            let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?;
311
            let dest = app.repos.trash(&name)?;
312
            db::repos::delete(&app.db, row.id).await?;
313
            println!("moved {name} to {}", dest.display());
314
        }
315
        RepoCmd::Set { slug, description, default_bookmark, visibility } => {
316
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
317
            let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?;
318
            if let Some(d) = description {
319
                db::repos::set_description(&app.db, row.id, &d).await?;
320
            }
321
            if let Some(b) = default_bookmark {
322
                db::repos::set_default_bookmark(&app.db, row.id, &b).await?;
323
            }
324
            if let Some(v) = visibility {
325
                let v = Visibility::parse(&v).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?;
326
                db::repos::set_visibility(&app.db, row.id, v).await?;
327
            }
328
            println!("updated {name}");
329
        }
330
    }
331
    Ok(())
332
}
333
334
async fn user_admin(app: &oxygenhub::Shared, cmd: UserCmd) -> anyhow::Result<()> {
335
    use oxygenhub::auth;
336
    use oxygenhub::db::accounts;
337
    match cmd {
338
        UserCmd::Create { username, email, admin } => {
339
            if !oxygenhub::repos::names::valid_owner(&username) {
340
                anyhow::bail!("{username:?} is not a valid username");
341
            }
342
            if accounts::account_by_name(&app.db, &username).await?.is_some() || accounts::org_by_name(&app.db, &username).await?.is_some()
343
            {
344
                anyhow::bail!("{username} is taken");
345
            }
346
            let password = auth::random_hex(12);
347
            let hash = auth::hash_password(&password)?;
348
            accounts::create_account(&app.db, &username, &email, &hash, &auth::random_hex(16), admin).await?;
349
            accounts::audit(&app.db, None, "admin.user.create", &username, if admin { "administrator" } else { "" }).await?;
350
            println!("created {username}{}; one-time password: {password}", if admin { " (administrator)" } else { "" });
351
            println!("sign in at {}/login and change it under Settings", app.config.base_url());
352
        }
353
        UserCmd::ResetPassword { username } => {
354
            let account = accounts::account_by_name(&app.db, &username).await?.ok_or_else(|| anyhow::anyhow!("no such account"))?;
355
            let password = auth::random_hex(12);
356
            let hash = auth::hash_password(&password)?;
357
            accounts::set_password(&app.db, account.id, &hash, &auth::random_hex(16)).await?;
358
            accounts::audit(&app.db, None, "admin.user.reset_password", &username, "").await?;
359
            println!("new one-time password for {username}: {password}");
360
        }
361
        UserCmd::List => {
362
            for a in accounts::accounts(&app.db).await? {
363
                println!(
364
                    "{:<24} {:<32} {}{}{}",
365
                    a.username,
366
                    a.email,
367
                    if a.is_admin { "admin " } else { "" },
368
                    if a.banned { "banned " } else { "" },
369
                    if a.disabled { "disabled" } else { "" }
370
                );
371
            }
372
        }
373
    }
374
    Ok(())
375
}
376
377
async fn check(app: &oxygenhub::Shared) -> anyhow::Result<()> {
378
    let mut problems = 0;
379
    for r in db::repos::list(&app.db).await? {
380
        let name = RepoName::new(&r.owner, &r.name).unwrap();
381
        let report = app.repos.read(&name, oxygenhub::repos::view::verification).await;
382
        match report {
383
            Ok(v) => {
384
                println!(
385
                    "{:<40} {} changes, {} signed, {} sealed, {} unsigned, {} invalid",
386
                    name,
387
                    v.total,
388
                    v.signed,
389
                    v.sealed,
390
                    v.unsigned,
391
                    v.invalid.len()
392
                );
393
                problems += v.invalid.len();
394
            }
395
            Err(e) => {
396
                println!("{name:<40} ERROR {e}");
397
                problems += 1;
398
            }
399
        }
400
    }
401
    if problems > 0 {
402
        anyhow::bail!("{problems} problem(s)");
403
    }
404
    Ok(())
405
}