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