Skip to main content

autoconnect/
main.rs

1#![warn(rust_2018_idioms)]
2
3#[global_allocator]
4static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
5
6#[macro_use]
7extern crate slog_scope;
8
9use std::{env, time::Duration, vec::Vec};
10
11use actix_http::HttpService;
12use actix_server::Server;
13use actix_service::map_config;
14use actix_web::dev::AppConfig;
15use docopt::Docopt;
16use serde::Deserialize;
17
18use autoconnect_settings::{AppState, Settings};
19use autoconnect_web::{build_app, config, config_router};
20use autopush_common::{
21    db::spawn_pool_periodic_reporter,
22    errors::{ApcErrorKind, Result},
23    logging,
24};
25
26const USAGE: &str = "
27Usage: autoconnect [options]
28
29Options:
30    -h, --help                          Show this message.
31    -c, --config=CONFIGFILE             Connection configuration file path.
32";
33
34#[derive(Debug, Deserialize)]
35struct Args {
36    flag_config: Option<String>,
37}
38
39#[actix_web::main]
40async fn main() -> Result<()> {
41    // Must run before any TLS use. reqwest (e.g. the megaphone/remote-settings
42    // HTTPS fetch on the actix arbiter threads) builds its rustls config via the
43    // default provider and panics if none is installed when multiple providers
44    // are compiled in; tonic/bigtable adopts whatever we install here.
45    autopush_common::tls::install_crypto_provider();
46    env_logger::init();
47    let args: Args = Docopt::new(USAGE)
48        .and_then(|d| d.deserialize())
49        .unwrap_or_else(|e| e.exit());
50    let mut filenames = Vec::new();
51    if let Some(config_filename) = args.flag_config {
52        filenames.push(config_filename);
53    }
54    let settings =
55        Settings::with_env_and_config_files(&filenames).map_err(ApcErrorKind::ConfigError)?;
56    logging::init_logging(
57        !settings.human_logs,
58        env!("CARGO_PKG_NAME"),
59        env!("CARGO_PKG_VERSION"),
60    )
61    .expect("Logging failed to initialize");
62    debug!("Starting up autoconnect...");
63
64    // Sentry requires the environment variable "SENTRY_DSN".
65    if env::var("SENTRY_DSN")
66        .unwrap_or_else(|_| "".to_owned())
67        .is_empty()
68    {
69        print!("SENTRY_DSN not set. Logging disabled.");
70    }
71
72    let _guard = sentry::init(sentry::ClientOptions {
73        release: sentry::release_name!(),
74        session_mode: sentry::SessionMode::Request, // new session per request
75        auto_session_tracking: true,
76        ..autopush_common::sentry::client_options()
77    });
78
79    let port = settings.port;
80    let router_port = settings.router_port;
81    let actix_max_connections = settings.actix_max_connections;
82    let actix_workers = settings.actix_workers;
83    let app_state = AppState::from_settings(settings)?;
84    app_state.init_and_spawn_megaphone_updater().await?;
85    spawn_pool_periodic_reporter(
86        Duration::from_secs(10),
87        app_state.db.clone(),
88        app_state.metrics.clone(),
89    );
90
91    info!(
92        "Starting autoconnect on port: {} router_port: {} ({})",
93        port,
94        router_port,
95        logging::parallelism_banner()
96    );
97
98    let router_app_state = app_state.clone();
99    let mut builder = Server::build()
100        .bind("autoconnect", ("0.0.0.0", port), move || {
101            let app = build_app!(app_state, config);
102            HttpService::build()
103                // XXX: AppConfig::default() does *not* have correct values
104                // https://github.com/actix/actix-web/issues/3180
105                .finish(map_config(app, |_| AppConfig::default()))
106                .tcp()
107        })?
108        .bind("autoconnect-router", ("0.0.0.0", router_port), move || {
109            let app = build_app!(router_app_state, config_router);
110            HttpService::build()
111                // XXX:
112                .finish(map_config(app, |_| AppConfig::default()))
113                .tcp()
114        })?;
115    if let Some(max_connections) = actix_max_connections {
116        builder = builder.max_concurrent_connections(max_connections);
117    }
118    if let Some(workers) = actix_workers {
119        builder = builder.workers(workers);
120    }
121    builder.run().await?;
122
123    info!("Shutting down autoconnect");
124    Ok(())
125}