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