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