| d23464c0 Andy McCall ↶ |
1 |
|
| 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 |
|
| 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 |
|
| 23 |
Init { |
| 24 |
|
| 25 |
#[arg(long)] |
| 26 |
base_url: Option<String>, |
| 27 |
|
| 28 |
#[arg(long)] |
| 29 |
self_signed: bool, |
| 30 |
}, |
| 31 |
|
| e57765de Andy McCall ↶ |
32 |
Serve { |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
#[arg(long = "role", value_name = "ROLE", value_delimiter = ',')] |
| 38 |
roles: Vec<oxygenhub::config::Role>, |
| 39 |
}, |
| d23464c0 Andy McCall ↶ |
40 |
|
| 41 |
Admin { |
| 42 |
#[command(subcommand)] |
| 43 |
cmd: AdminCmd, |
| 44 |
}, |
| 45 |
|
| 46 |
Check, |
| 8a3334b7 Andy McCall ↶ |
47 |
|
| 48 |
Gc, |
| d23464c0 Andy McCall ↶ |
49 |
} |
| 50 |
|
| 51 |
#[derive(Subcommand)] |
| 52 |
enum AdminCmd { |
| 53 |
|
| 54 |
Repo { |
| 55 |
#[command(subcommand)] |
| 56 |
cmd: RepoCmd, |
| 57 |
}, |
| 19bb31ff Andy McCall ↶ |
58 |
|
| 59 |
User { |
| 60 |
#[command(subcommand)] |
| 61 |
cmd: UserCmd, |
| 62 |
}, |
| d7d18246 Andy McCall ↶ |
63 |
|
| 64 |
Backup { |
| 65 |
#[command(subcommand)] |
| 66 |
cmd: BackupCmd, |
| 67 |
}, |
| 4e2cad00 Andy McCall ↶ |
68 |
|
| 69 |
|
| 70 |
#[cfg(feature = "postgres")] |
| 71 |
CopyDb { |
| 72 |
|
| 73 |
#[arg(long)] |
| 74 |
from: PathBuf, |
| dc71378d Andy McCall ↶ |
75 |
|
| 76 |
#[arg(long)] |
| 77 |
replace: bool, |
| 4e2cad00 Andy McCall ↶ |
78 |
}, |
| d7d18246 Andy McCall ↶ |
79 |
} |
| 80 |
|
| 81 |
#[derive(Subcommand)] |
| 82 |
enum BackupCmd { |
| 83 |
|
| 84 |
Run { owner: String }, |
| 85 |
|
| 86 |
|
| 87 |
Restore { |
| 88 |
#[arg(long)] |
| 89 |
from: std::path::PathBuf, |
| 90 |
|
| 91 |
#[arg(long)] |
| 92 |
run: Option<String>, |
| 93 |
}, |
| d23464c0 Andy McCall ↶ |
94 |
} |
| 95 |
|
| 96 |
#[derive(Subcommand)] |
| 19bb31ff Andy McCall ↶ |
97 |
enum UserCmd { |
| 98 |
|
| 99 |
Create { |
| 100 |
username: String, |
| 101 |
#[arg(long, default_value = "")] |
| 102 |
email: String, |
| 103 |
|
| 104 |
#[arg(long)] |
| 105 |
admin: bool, |
| 106 |
}, |
| 107 |
|
| 108 |
ResetPassword { username: String }, |
| 109 |
|
| 110 |
List, |
| 111 |
} |
| 112 |
|
| 113 |
#[derive(Subcommand)] |
| d23464c0 Andy McCall ↶ |
114 |
enum RepoCmd { |
| 115 |
|
| 116 |
Create { |
| 117 |
slug: String, |
| 118 |
#[arg(long, default_value = "")] |
| 119 |
description: String, |
| 120 |
#[arg(long, default_value = "public")] |
| 121 |
visibility: String, |
| 122 |
|
| 123 |
|
| 124 |
#[arg(long)] |
| 125 |
id: Option<String>, |
| 126 |
}, |
| 127 |
|
| 128 |
List, |
| 129 |
|
| 130 |
Delete { slug: String }, |
| 131 |
|
| 132 |
Set { |
| 133 |
slug: String, |
| 134 |
#[arg(long)] |
| 135 |
description: Option<String>, |
| 136 |
#[arg(long)] |
| 137 |
default_bookmark: Option<String>, |
| 138 |
#[arg(long)] |
| 139 |
visibility: Option<String>, |
| 140 |
}, |
| 141 |
} |
| 142 |
|
| b2107275 Andy McCall ↶ |
143 |
fn main() -> anyhow::Result<()> { |
| 144 |
tune_allocator(); |
| 145 |
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; |
| 146 |
rt.spawn(return_freed_memory()); |
| 529c703d Andy McCall ↶ |
147 |
let out = rt.block_on(run()); |
| 148 |
oxygenhub::shutdown::finish(rt); |
| 149 |
out |
| b2107275 Andy McCall ↶ |
150 |
} |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
fn tune_allocator() { |
| 159 |
#[cfg(all(target_os = "linux", target_env = "gnu"))] |
| 160 |
if std::env::var_os("MALLOC_ARENA_MAX").is_none() { |
| 161 |
|
| 162 |
unsafe { |
| 163 |
libc::mallopt(libc::M_ARENA_MAX, 2); |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
async fn return_freed_memory() { |
| 171 |
#[cfg(all(target_os = "linux", target_env = "gnu"))] |
| 172 |
loop { |
| 173 |
tokio::time::sleep(std::time::Duration::from_secs(60)).await; |
| 174 |
|
| 175 |
let _ = tokio::task::spawn_blocking(|| unsafe { libc::malloc_trim(0) }).await; |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
async fn run() -> anyhow::Result<()> { |
| d23464c0 Andy McCall ↶ |
180 |
tracing_subscriber::fmt() |
| 181 |
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env().add_directive("oxygenhub=info".parse()?)) |
| 182 |
.init(); |
| 183 |
let cli = Cli::parse(); |
| 184 |
match cli.cmd { |
| 185 |
Cmd::Init { base_url, self_signed } => init(&cli.data, base_url, self_signed).await, |
| e57765de Andy McCall ↶ |
186 |
Cmd::Serve { roles } => { |
| 187 |
let mut config = Config::load(&cli.data)?; |
| 188 |
if !roles.is_empty() { |
| 189 |
config.server.roles = roles.iter().map(|r| r.name().to_string()).collect(); |
| 190 |
} |
| d23464c0 Andy McCall ↶ |
191 |
let app = oxygenhub::build(config).await?; |
| 192 |
oxygenhub::serve(app).await |
| 193 |
} |
| 194 |
Cmd::Admin { cmd: AdminCmd::Repo { cmd } } => { |
| 195 |
let config = Config::load(&cli.data)?; |
| 196 |
let app = oxygenhub::build(config).await?; |
| 197 |
repo_admin(&app, cmd).await |
| d7d18246 Andy McCall ↶ |
198 |
} |
| 199 |
Cmd::Admin { cmd: AdminCmd::Backup { cmd } } => { |
| 200 |
let config = Config::load(&cli.data)?; |
| 201 |
let app = oxygenhub::build(config).await?; |
| 202 |
match cmd { |
| 203 |
BackupCmd::Run { owner } => { |
| 204 |
let r = oxygenhub::backups::run(&app, &owner, "now").await?; |
| 205 |
println!( |
| 206 |
"{} {}: {} repositories, {} of {} files sent ({} KiB){}", |
| 207 |
r.status, |
| 208 |
r.at, |
| 209 |
r.repos, |
| 210 |
r.sent, |
| 211 |
r.files, |
| 212 |
r.bytes / 1024, |
| 213 |
if r.detail.is_empty() { String::new() } else { format!(": {}", r.detail) } |
| 214 |
); |
| 215 |
if r.status == "failed" { |
| 216 |
std::process::exit(1); |
| 217 |
} |
| 218 |
Ok(()) |
| 219 |
} |
| 220 |
BackupCmd::Restore { from, run } => { |
| 221 |
let dest: std::sync::Arc<dyn oxygenhub::backups::Destination> = |
| 222 |
std::sync::Arc::new(oxygenhub::backups::Directory { root: from }); |
| 223 |
for d in oxygenhub::backups::restore_into_hub(&app, dest, run).await? { |
| 224 |
println!("restored {d}"); |
| 225 |
} |
| 226 |
Ok(()) |
| 227 |
} |
| 4e2cad00 Andy McCall ↶ |
228 |
} |
| 229 |
} |
| 230 |
#[cfg(feature = "postgres")] |
| dc71378d Andy McCall ↶ |
231 |
Cmd::Admin { cmd: AdminCmd::CopyDb { from, replace } } => { |
| 4e2cad00 Andy McCall ↶ |
232 |
let config = Config::load(&cli.data)?; |
| 233 |
let pool = db::open(&config).await?; |
| dc71378d Andy McCall ↶ |
234 |
let copied = db::copy::from_sqlite(&pool, &from, replace).await?; |
| 4e2cad00 Andy McCall ↶ |
235 |
for (table, n) in &copied { |
| 236 |
println!("{n:>9} {table}"); |
| d7d18246 Andy McCall ↶ |
237 |
} |
| 4e2cad00 Andy McCall ↶ |
238 |
println!("copied {} rows in {} tables", copied.iter().map(|(_, n)| n).sum::<i64>(), copied.len()); |
| 239 |
Ok(()) |
| d23464c0 Andy McCall ↶ |
240 |
} |
| 19bb31ff Andy McCall ↶ |
241 |
Cmd::Admin { cmd: AdminCmd::User { cmd } } => { |
| 242 |
let config = Config::load(&cli.data)?; |
| 243 |
let app = oxygenhub::build(config).await?; |
| 244 |
user_admin(&app, cmd).await |
| 245 |
} |
| d23464c0 Andy McCall ↶ |
246 |
Cmd::Check => { |
| 247 |
let config = Config::load(&cli.data)?; |
| 248 |
let app = oxygenhub::build(config).await?; |
| 249 |
check(&app).await |
| 250 |
} |
| 8a3334b7 Andy McCall ↶ |
251 |
Cmd::Gc => { |
| 252 |
let config = Config::load(&cli.data)?; |
| 253 |
let app = oxygenhub::build(config).await?; |
| 254 |
let done = oxygenhub::maintenance::gc_all(&app).await; |
| 255 |
for d in &done { |
| 256 |
println!("{d}"); |
| 257 |
} |
| 258 |
if done.iter().any(|d| d.failed) { |
| 259 |
anyhow::bail!("a repository could not be garbage collected"); |
| 260 |
} |
| 261 |
Ok(()) |
| 262 |
} |
| d23464c0 Andy McCall ↶ |
263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
async fn init(data: &PathBuf, base_url: Option<String>, self_signed: bool) -> anyhow::Result<()> { |
| 267 |
std::fs::create_dir_all(data)?; |
| 268 |
let toml_path = data.join("hub.toml"); |
| 269 |
if !toml_path.exists() { |
| 270 |
let base = base_url.clone().unwrap_or_else(|| "http://127.0.0.1:7300".into()); |
| 8d2caf12 Andy McCall ↶ |
271 |
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 ↶ |
272 |
if self_signed { |
| 273 |
text.push_str("tls_bind = \"0.0.0.0:7343\"\n"); |
| 274 |
} |
| 275 |
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")); |
| 276 |
std::fs::write(&toml_path, text)?; |
| 277 |
println!("wrote {}", toml_path.display()); |
| 278 |
} |
| 279 |
let mut config = Config::load(data)?; |
| 280 |
if let Some(b) = base_url { |
| 281 |
config.server.base_url = b; |
| 282 |
} |
| 283 |
let app = oxygenhub::build(config).await?; |
| 284 |
println!("hub key {}", app.hub_key.key.to_hex()); |
| 285 |
if (self_signed || app.config.tls.self_signed) |
| 286 |
&& keys::ensure_self_signed(&app.config.tls_cert(), &app.config.tls_key(), app.config.base_url())? |
| 287 |
{ |
| 288 |
println!("wrote self-signed certificate {}", app.config.tls_cert().display()); |
| 289 |
} |
| 290 |
println!("data directory {} is ready", data.display()); |
| 291 |
Ok(()) |
| 292 |
} |
| 293 |
|
| 294 |
async fn repo_admin(app: &oxygenhub::Shared, cmd: RepoCmd) -> anyhow::Result<()> { |
| 295 |
match cmd { |
| 296 |
RepoCmd::Create { slug, description, visibility, id } => { |
| 297 |
let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?; |
| 298 |
let visibility = Visibility::parse(&visibility).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?; |
| 299 |
let id = match id { |
| 300 |
Some(h) => { |
| 301 |
let bytes = hex::decode(h.trim()).ok().and_then(|v| <[u8; 16]>::try_from(v).ok()); |
| 302 |
Some(bytes.ok_or_else(|| anyhow::anyhow!("--id takes 32 hex characters"))?) |
| 303 |
} |
| 304 |
None => None, |
| 305 |
}; |
| 306 |
if db::repos::get(&app.db, &name.owner, &name.name).await?.is_some() { |
| 307 |
anyhow::bail!("{name} already exists"); |
| 308 |
} |
| 309 |
app.repos.create(&name, id)?; |
| 310 |
db::repos::create(&app.db, &name.owner, &name.name, &description, visibility).await?; |
| 311 |
println!("created {name}: oxy clone {}/{name}", app.config.base_url()); |
| 312 |
} |
| 313 |
RepoCmd::List => { |
| 314 |
for r in db::repos::list(&app.db).await? { |
| 315 |
println!("{:<40} {:<8} {}", r.slug(), r.visibility, r.description); |
| 316 |
} |
| 317 |
} |
| 318 |
RepoCmd::Delete { slug } => { |
| 319 |
let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?; |
| 320 |
let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?; |
| 321 |
let dest = app.repos.trash(&name)?; |
| 322 |
db::repos::delete(&app.db, row.id).await?; |
| 323 |
println!("moved {name} to {}", dest.display()); |
| 324 |
} |
| 325 |
RepoCmd::Set { slug, description, default_bookmark, visibility } => { |
| 326 |
let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?; |
| 327 |
let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?; |
| 328 |
if let Some(d) = description { |
| 329 |
db::repos::set_description(&app.db, row.id, &d).await?; |
| 330 |
} |
| 331 |
if let Some(b) = default_bookmark { |
| 332 |
db::repos::set_default_bookmark(&app.db, row.id, &b).await?; |
| 333 |
} |
| 334 |
if let Some(v) = visibility { |
| 335 |
let v = Visibility::parse(&v).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?; |
| 336 |
db::repos::set_visibility(&app.db, row.id, v).await?; |
| 337 |
} |
| 338 |
println!("updated {name}"); |
| 339 |
} |
| 340 |
} |
| 341 |
Ok(()) |
| 342 |
} |
| 343 |
|
| 19bb31ff Andy McCall ↶ |
344 |
async fn user_admin(app: &oxygenhub::Shared, cmd: UserCmd) -> anyhow::Result<()> { |
| 345 |
use oxygenhub::auth; |
| 346 |
use oxygenhub::db::accounts; |
| 347 |
match cmd { |
| 348 |
UserCmd::Create { username, email, admin } => { |
| 349 |
if !oxygenhub::repos::names::valid_owner(&username) { |
| 350 |
anyhow::bail!("{username:?} is not a valid username"); |
| 351 |
} |
| 352 |
if accounts::account_by_name(&app.db, &username).await?.is_some() || accounts::org_by_name(&app.db, &username).await?.is_some() |
| 353 |
{ |
| 354 |
anyhow::bail!("{username} is taken"); |
| 355 |
} |
| 356 |
let password = auth::random_hex(12); |
| 357 |
let hash = auth::hash_password(&password)?; |
| 358 |
accounts::create_account(&app.db, &username, &email, &hash, &auth::random_hex(16), admin).await?; |
| 359 |
accounts::audit(&app.db, None, "admin.user.create", &username, if admin { "administrator" } else { "" }).await?; |
| 360 |
println!("created {username}{}; one-time password: {password}", if admin { " (administrator)" } else { "" }); |
| 361 |
println!("sign in at {}/login and change it under Settings", app.config.base_url()); |
| 362 |
} |
| 363 |
UserCmd::ResetPassword { username } => { |
| 364 |
let account = accounts::account_by_name(&app.db, &username).await?.ok_or_else(|| anyhow::anyhow!("no such account"))?; |
| 365 |
let password = auth::random_hex(12); |
| 366 |
let hash = auth::hash_password(&password)?; |
| 367 |
accounts::set_password(&app.db, account.id, &hash, &auth::random_hex(16)).await?; |
| 368 |
accounts::audit(&app.db, None, "admin.user.reset_password", &username, "").await?; |
| 369 |
println!("new one-time password for {username}: {password}"); |
| 370 |
} |
| 371 |
UserCmd::List => { |
| 372 |
for a in accounts::accounts(&app.db).await? { |
| 373 |
println!( |
| 6a178055 Andy McCall ↶ |
374 |
"{:<24} {:<32} {}{}{}", |
| 19bb31ff Andy McCall ↶ |
375 |
a.username, |
| 376 |
a.email, |
| 377 |
if a.is_admin { "admin " } else { "" }, |
| 6a178055 Andy McCall ↶ |
378 |
if a.banned { "banned " } else { "" }, |
| 379 |
if a.disabled { "disabled" } else { "" } |
| 19bb31ff Andy McCall ↶ |
380 |
); |
| 381 |
} |
| 382 |
} |
| 383 |
} |
| 384 |
Ok(()) |
| 385 |
} |
| 386 |
|
| d23464c0 Andy McCall ↶ |
387 |
async fn check(app: &oxygenhub::Shared) -> anyhow::Result<()> { |
| 388 |
let mut problems = 0; |
| 389 |
for r in db::repos::list(&app.db).await? { |
| 390 |
let name = RepoName::new(&r.owner, &r.name).unwrap(); |
| e1078e99 Andy McCall ↶ |
391 |
let report = app.repos.read(&name, oxygenhub::repos::view::verification).await; |
| d23464c0 Andy McCall ↶ |
392 |
match report { |
| 393 |
Ok(v) => { |
| 394 |
println!( |
| 395 |
"{:<40} {} changes, {} signed, {} sealed, {} unsigned, {} invalid", |
| 396 |
name, |
| 397 |
v.total, |
| 398 |
v.signed, |
| 399 |
v.sealed, |
| 400 |
v.unsigned, |
| 401 |
v.invalid.len() |
| 402 |
); |
| 403 |
problems += v.invalid.len(); |
| 404 |
} |
| 405 |
Err(e) => { |
| 406 |
println!("{name:<40} ERROR {e}"); |
| 407 |
problems += 1; |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
if problems > 0 { |
| 412 |
anyhow::bail!("{problems} problem(s)"); |
| 413 |
} |
| 414 |
Ok(()) |
| 415 |
} |