forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

main.rs114 lines, 3.7 KiBHistoryRawDownload
1//! The `im` binary: the command line, logging and the process lifetime.
2//!
3//! `im [--config <path>] [serve]` runs the server; a bare `im` does the same. `im client ...` manages the
4//! OpenID Connect clients (`cli.rs`). `im admin ...` is the operator command line, which is not built yet. The configuration file is the `--config` path,
5//! then `IM_CONFIG`, then `config/im.toml`. Exit status 0 is success, 1 a failure, 2 a usage error.
6
7mod api;
8mod assets;
9mod audit;
10mod auth;
11mod backchannel;
12mod backups;
13mod boot;
14mod cli;
15mod client_ip;
16mod health;
17mod i18n;
18mod live;
19mod mail;
20mod oidc;
21mod pages;
22mod security;
23mod service_probe;
24mod state;
25mod sweeper;
26mod throttle;
27mod views;
28
29use std::path::{Path, PathBuf};
30use std::process::ExitCode;
31
32use tracing_subscriber::EnvFilter;
33
34/// Printed with a usage error.
35const USAGE: &str = "usage: im [--config <path>] [serve | client <add|list|disable> ... | backup now | restore --from <set> | fsck | keys rotate]";
36
37/// The configuration file when neither `--config` nor `IM_CONFIG` names one.
38const DEFAULT_CONFIG: &str = "config/im.toml";
39
40/// The environment variable that names the configuration file.
41const CONFIG_ENV: &str = "IM_CONFIG";
42
43/// The parsed command line: the `--config` path and the positional words.
44struct Cli {
45 config: Option<PathBuf>,
46 words: Vec<String>,
47}
48
49/// Splits the arguments into the `--config <path>` pair and the positional words.
50fn parse_args(args: impl Iterator<Item = String>) -> Result<Cli, String> {
51 let mut config = None;
52 let mut words = Vec::new();
53 let mut args = args;
54 while let Some(arg) = args.next() {
55 if arg == "--config" {
56 let path = args.next().ok_or("--config needs a path")?;
57 config = Some(PathBuf::from(path));
58 } else {
59 words.push(arg);
60 }
61 }
62 Ok(Cli { config, words })
63}
64
65/// The configuration path: the flag, else `IM_CONFIG`, else the default.
66fn config_path(flag: Option<PathBuf>) -> PathBuf {
67 flag.or_else(|| std::env::var_os(CONFIG_ENV).map(PathBuf::from))
68 .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG))
69}
70
71/// Logs to stderr. The level comes from `RUST_LOG`, and defaults to `info`.
72fn init_logging() {
73 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
74 tracing_subscriber::fmt()
75 .with_env_filter(filter)
76 .with_writer(std::io::stderr)
77 .init();
78}
79
80/// Runs the server and maps its outcome to an exit status.
81async fn serve(config: &Path) -> ExitCode {
82 match boot::serve(config).await {
83 Ok(()) => ExitCode::SUCCESS,
84 Err(error) => {
85 tracing::error!(error = %error, "im stopped with an error");
86 ExitCode::FAILURE
87 }
88 }
89}
90
91#[tokio::main]
92async fn main() -> ExitCode {
93 init_logging();
94 let cli = match parse_args(std::env::args().skip(1)) {
95 Ok(cli) => cli,
96 Err(message) => {
97 eprintln!("im: {message}\n{USAGE}");
98 return ExitCode::from(2);
99 }
100 };
101 let words: Vec<&str> = cli.words.iter().map(String::as_str).collect();
102 match words.as_slice() {
103 [] | ["serve"] => serve(&config_path(cli.config)).await,
104 ["client", ..] => cli::client(&config_path(cli.config), &cli.words[1..]).await,
105 ["backup", ..] => cli::backup(&config_path(cli.config), &cli.words[1..]).await,
106 ["restore", ..] => cli::restore(&config_path(cli.config), &cli.words[1..]).await,
107 ["fsck"] => cli::fsck(&config_path(cli.config)).await,
108 ["keys", ..] => cli::keys(&config_path(cli.config), &cli.words[1..]).await,
109 _ => {
110 eprintln!("im: unknown command\n{USAGE}");
111 ExitCode::from(2)
112 }
113 }
114}