LCOV - code coverage report
Current view: top level - storage_controller/src - main.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 0.0 % 262 0
Test Date: 2025-07-22 17:50:06 Functions: 0.0 % 14 0

            Line data    Source code
       1              : use std::num::NonZeroU32;
       2              : use std::path::PathBuf;
       3              : use std::sync::Arc;
       4              : use std::time::Duration;
       5              : 
       6              : use anyhow::{Context, anyhow};
       7              : use camino::Utf8PathBuf;
       8              : 
       9              : use clap::{ArgAction, Parser};
      10              : use futures::future::OptionFuture;
      11              : use http_utils::tls_certs::ReloadingCertificateResolver;
      12              : use hyper0::Uri;
      13              : use metrics::BuildInfo;
      14              : use metrics::launch_timestamp::LaunchTimestamp;
      15              : use pageserver_api::config::PostHogConfig;
      16              : use reqwest::Certificate;
      17              : use storage_controller::http::make_router;
      18              : use storage_controller::metrics::preinitialize_metrics;
      19              : use storage_controller::persistence::Persistence;
      20              : use storage_controller::service::chaos_injector::ChaosInjector;
      21              : use storage_controller::service::feature_flag::FeatureFlagService;
      22              : use storage_controller::service::{
      23              :     Config, HEARTBEAT_INTERVAL_DEFAULT, LONG_RECONCILE_THRESHOLD_DEFAULT,
      24              :     MAX_OFFLINE_INTERVAL_DEFAULT, MAX_WARMING_UP_INTERVAL_DEFAULT,
      25              :     PRIORITY_RECONCILER_CONCURRENCY_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
      26              :     SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT, Service,
      27              : };
      28              : use tokio::signal::unix::SignalKind;
      29              : use tokio_util::sync::CancellationToken;
      30              : use tracing::Instrument;
      31              : use utils::auth::{JwtAuth, SwappableJwtAuth};
      32              : use utils::logging::{self, LogFormat};
      33              : use utils::sentry_init::init_sentry;
      34              : use utils::{project_build_tag, project_git_version, tcp_listener};
      35              : 
      36              : project_git_version!(GIT_VERSION);
      37              : project_build_tag!(BUILD_TAG);
      38              : 
      39              : #[global_allocator]
      40              : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
      41              : 
      42              : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
      43              : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
      44              : /// performance-sensitive code will avoid allocations as far as possible anyway.
      45              : #[allow(non_upper_case_globals)]
      46              : #[unsafe(export_name = "malloc_conf")]
      47              : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
      48              : 
      49              : const DEFAULT_SSL_KEY_FILE: &str = "server.key";
      50              : const DEFAULT_SSL_CERT_FILE: &str = "server.crt";
      51              : const DEFAULT_SSL_CERT_RELOAD_PERIOD: &str = "60s";
      52              : 
      53              : #[derive(Parser)]
      54              : #[command(author, version, about, long_about = None)]
      55              : #[command(arg_required_else_help(true))]
      56              : #[clap(group(
      57              :     clap::ArgGroup::new("listen-addresses")
      58              :         .required(true)
      59              :         .multiple(true)
      60              :         .args(&["listen", "listen_https"]),
      61              : ))]
      62              : struct Cli {
      63              :     /// Host and port to listen HTTP on, like `127.0.0.1:1234`.
      64              :     /// At least one of ["listen", "listen_https"] should be specified.
      65              :     // TODO: Make this option dev-only when https is out everywhere.
      66              :     #[arg(short, long)]
      67              :     listen: Option<std::net::SocketAddr>,
      68              :     /// Host and port to listen HTTPS on, like `127.0.0.1:1234`.
      69              :     /// At least one of ["listen", "listen_https"] should be specified.
      70              :     #[arg(long)]
      71              :     listen_https: Option<std::net::SocketAddr>,
      72              : 
      73              :     /// Public key for JWT authentication of clients
      74              :     #[arg(long)]
      75              :     public_key: Option<String>,
      76              : 
      77              :     /// Token for authenticating this service with the pageservers it controls
      78              :     #[arg(long)]
      79              :     jwt_token: Option<String>,
      80              : 
      81              :     /// Token for authenticating this service with the safekeepers it controls
      82              :     #[arg(long)]
      83              :     safekeeper_jwt_token: Option<String>,
      84              : 
      85              :     /// Token for authenticating this service with the control plane, when calling
      86              :     /// the compute notification endpoint
      87              :     #[arg(long)]
      88              :     control_plane_jwt_token: Option<String>,
      89              : 
      90              :     #[arg(long)]
      91              :     peer_jwt_token: Option<String>,
      92              : 
      93              :     /// URL to control plane storage API prefix
      94              :     #[arg(long)]
      95              :     control_plane_url: Option<String>,
      96              : 
      97              :     /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
      98              :     #[arg(long)]
      99              :     database_url: Option<String>,
     100              : 
     101              :     /// Flag to enable dev mode, which permits running without auth
     102              :     #[arg(long, default_value = "false")]
     103              :     dev: bool,
     104              : 
     105              :     /// Grace period before marking unresponsive pageserver offline
     106              :     #[arg(long)]
     107              :     max_offline_interval: Option<humantime::Duration>,
     108              : 
     109              :     /// More tolerant grace period before marking unresponsive pagserver offline used
     110              :     /// around pageserver restarts
     111              :     #[arg(long)]
     112              :     max_warming_up_interval: Option<humantime::Duration>,
     113              : 
     114              :     /// Size threshold for automatically splitting shards (disabled by default)
     115              :     #[arg(long)]
     116              :     split_threshold: Option<u64>,
     117              : 
     118              :     /// Maximum number of shards during autosplits. 0 disables autosplits. Defaults
     119              :     /// to 16 as a safety to avoid too many shards by accident.
     120              :     #[arg(long, default_value = "16")]
     121              :     max_split_shards: u8,
     122              : 
     123              :     /// Size threshold for initial shard splits of unsharded tenants. 0 disables initial splits.
     124              :     #[arg(long)]
     125              :     initial_split_threshold: Option<u64>,
     126              : 
     127              :     /// Number of target shards for initial splits. 0 or 1 disables initial splits. Defaults to 2.
     128              :     #[arg(long, default_value = "2")]
     129              :     initial_split_shards: u8,
     130              : 
     131              :     /// Maximum number of normal-priority reconcilers that may run in parallel
     132              :     #[arg(long)]
     133              :     reconciler_concurrency: Option<usize>,
     134              : 
     135              :     /// Maximum number of high-priority reconcilers that may run in parallel
     136              :     #[arg(long)]
     137              :     priority_reconciler_concurrency: Option<usize>,
     138              : 
     139              :     /// Maximum number of safekeeper reconciliations that may run in parallel (per safekeeper)
     140              :     #[arg(long)]
     141              :     safekeeper_reconciler_concurrency: Option<usize>,
     142              : 
     143              :     /// Tenant API rate limit, as requests per second per tenant.
     144              :     #[arg(long, default_value = "10")]
     145              :     tenant_rate_limit: NonZeroU32,
     146              : 
     147              :     /// How long to wait for the initial database connection to be available.
     148              :     #[arg(long, default_value = "5s")]
     149              :     db_connect_timeout: humantime::Duration,
     150              : 
     151              :     #[arg(long, default_value = "false")]
     152              :     start_as_candidate: bool,
     153              : 
     154              :     // TODO: make this mandatory once the helm chart gets updated
     155              :     #[arg(long)]
     156              :     address_for_peers: Option<Uri>,
     157              : 
     158              :     /// `neon_local` sets this to the path of the neon_local repo dir.
     159              :     /// Only relevant for testing.
     160              :     // TODO: make `cfg(feature = "testing")`
     161              :     #[arg(long)]
     162              :     neon_local_repo_dir: Option<PathBuf>,
     163              : 
     164              :     /// Chaos testing: exercise tenant migrations
     165              :     #[arg(long)]
     166              :     chaos_interval: Option<humantime::Duration>,
     167              : 
     168              :     /// Chaos testing: exercise an immediate exit
     169              :     #[arg(long)]
     170              :     chaos_exit_crontab: Option<cron::Schedule>,
     171              : 
     172              :     /// Maximum acceptable lag for the secondary location while draining
     173              :     /// a pageserver
     174              :     #[arg(long)]
     175              :     max_secondary_lag_bytes: Option<u64>,
     176              : 
     177              :     /// Period with which to send heartbeats to registered nodes
     178              :     #[arg(long)]
     179              :     heartbeat_interval: Option<humantime::Duration>,
     180              : 
     181              :     #[arg(long)]
     182              :     long_reconcile_threshold: Option<humantime::Duration>,
     183              : 
     184              :     /// Flag to use https for requests to pageserver API.
     185              :     #[arg(long, default_value = "false")]
     186              :     use_https_pageserver_api: bool,
     187              : 
     188              :     // Whether to put timelines onto safekeepers
     189              :     #[arg(long, default_value = "false")]
     190              :     timelines_onto_safekeepers: bool,
     191              : 
     192              :     /// Flag to use https for requests to safekeeper API.
     193              :     #[arg(long, default_value = "false")]
     194              :     use_https_safekeeper_api: bool,
     195              : 
     196              :     /// Path to a file with certificate's private key for https API.
     197              :     #[arg(long, default_value = DEFAULT_SSL_KEY_FILE)]
     198              :     ssl_key_file: Utf8PathBuf,
     199              :     /// Path to a file with a X509 certificate for https API.
     200              :     #[arg(long, default_value = DEFAULT_SSL_CERT_FILE)]
     201              :     ssl_cert_file: Utf8PathBuf,
     202              :     /// Period to reload certificate and private key from files.
     203              :     #[arg(long, default_value = DEFAULT_SSL_CERT_RELOAD_PERIOD)]
     204              :     ssl_cert_reload_period: humantime::Duration,
     205              :     /// Trusted root CA certificates to use in https APIs.
     206              :     #[arg(long)]
     207              :     ssl_ca_file: Option<Utf8PathBuf>,
     208              : 
     209              :     /// Neon local specific flag. When set, ignore [`Cli::control_plane_url`] and deliver
     210              :     /// the compute notification directly (instead of via control plane).
     211              :     #[arg(long, default_value = "false")]
     212              :     use_local_compute_notifications: bool,
     213              : 
     214              :     /// Number of safekeepers to choose for a timeline when creating it.
     215              :     /// Safekeepers will be choosen from different availability zones.
     216              :     /// This option exists primarily for testing purposes.
     217              :     #[arg(long, default_value = "3", value_parser = clap::builder::RangedU64ValueParser::<usize>::new().range(1..))]
     218              :     timeline_safekeeper_count: usize,
     219              : 
     220              :     /// When set, actively checks and initiates heatmap downloads/uploads during reconciliation.
     221              :     /// This speed up migrations by avoiding the default wait for the heatmap download interval.
     222              :     /// Primarily useful for testing to reduce test execution time.
     223              :     #[arg(long, default_value = "false", action=ArgAction::Set)]
     224              :     kick_secondary_downloads: bool,
     225              : 
     226              :     #[arg(long)]
     227              :     shard_split_request_timeout: Option<humantime::Duration>,
     228              : 
     229              :     /// **Feature Flag** Whether the storage controller should act to rectify pageserver-reported local disk loss.
     230              :     #[arg(long, default_value = "false")]
     231              :     handle_ps_local_disk_loss: bool,
     232              : }
     233              : 
     234              : enum StrictMode {
     235              :     /// In strict mode, we will require that all secrets are loaded, i.e. security features
     236              :     /// may not be implicitly turned off by omitting secrets in the environment.
     237              :     Strict,
     238              :     /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
     239              :     /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
     240              :     /// requests, no public key -> don't authenticate incoming requests).
     241              :     Dev,
     242              : }
     243              : 
     244              : impl Default for StrictMode {
     245            0 :     fn default() -> Self {
     246            0 :         Self::Strict
     247            0 :     }
     248              : }
     249              : 
     250              : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
     251              : /// type encapsulates the logic to decide which and do the loading.
     252              : struct Secrets {
     253              :     database_url: String,
     254              :     public_key: Option<JwtAuth>,
     255              :     pageserver_jwt_token: Option<String>,
     256              :     safekeeper_jwt_token: Option<String>,
     257              :     control_plane_jwt_token: Option<String>,
     258              :     peer_jwt_token: Option<String>,
     259              : }
     260              : 
     261              : const POSTHOG_CONFIG_ENV: &str = "POSTHOG_CONFIG";
     262              : 
     263              : impl Secrets {
     264              :     const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
     265              :     const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
     266              :     const SAFEKEEPER_JWT_TOKEN_ENV: &'static str = "SAFEKEEPER_JWT_TOKEN";
     267              :     const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
     268              :     const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
     269              :     const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
     270              : 
     271              :     /// Load secrets from, in order of preference:
     272              :     /// - CLI args if database URL is provided on the CLI
     273              :     /// - Environment variables if DATABASE_URL is set.
     274            0 :     async fn load(args: &Cli) -> anyhow::Result<Self> {
     275            0 :         let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
     276              :         else {
     277            0 :             anyhow::bail!(
     278            0 :                 "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
     279              :             )
     280              :         };
     281              : 
     282            0 :         let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
     283            0 :             Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
     284            0 :             None => None,
     285              :         };
     286              : 
     287            0 :         let this = Self {
     288            0 :             database_url,
     289            0 :             public_key,
     290            0 :             pageserver_jwt_token: Self::load_secret(
     291            0 :                 &args.jwt_token,
     292            0 :                 Self::PAGESERVER_JWT_TOKEN_ENV,
     293            0 :             ),
     294            0 :             safekeeper_jwt_token: Self::load_secret(
     295            0 :                 &args.safekeeper_jwt_token,
     296            0 :                 Self::SAFEKEEPER_JWT_TOKEN_ENV,
     297            0 :             ),
     298            0 :             control_plane_jwt_token: Self::load_secret(
     299            0 :                 &args.control_plane_jwt_token,
     300            0 :                 Self::CONTROL_PLANE_JWT_TOKEN_ENV,
     301            0 :             ),
     302            0 :             peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
     303            0 :         };
     304              : 
     305            0 :         Ok(this)
     306            0 :     }
     307              : 
     308            0 :     fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
     309            0 :         if let Some(v) = cli {
     310            0 :             Some(v.clone())
     311              :         } else {
     312            0 :             std::env::var(env_name).ok()
     313              :         }
     314            0 :     }
     315              : }
     316              : 
     317            0 : fn main() -> anyhow::Result<()> {
     318            0 :     logging::init(
     319            0 :         LogFormat::Plain,
     320            0 :         logging::TracingErrorLayerEnablement::Disabled,
     321            0 :         logging::Output::Stdout,
     322            0 :     )?;
     323              : 
     324              :     // log using tracing so we don't get confused output by default hook writing to stderr
     325            0 :     utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
     326              : 
     327            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     328              : 
     329            0 :     let hook = std::panic::take_hook();
     330            0 :     std::panic::set_hook(Box::new(move |info| {
     331              :         // let sentry send a message (and flush)
     332              :         // and trace the error
     333            0 :         hook(info);
     334              : 
     335            0 :         std::process::exit(1);
     336              :     }));
     337              : 
     338            0 :     tokio::runtime::Builder::new_current_thread()
     339            0 :         // We use spawn_blocking for database operations, so require approximately
     340            0 :         // as many blocking threads as we will open database connections.
     341            0 :         .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
     342            0 :         .enable_all()
     343            0 :         .build()
     344            0 :         .unwrap()
     345            0 :         .block_on(async_main())
     346            0 : }
     347              : 
     348            0 : async fn async_main() -> anyhow::Result<()> {
     349            0 :     let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
     350              : 
     351            0 :     preinitialize_metrics();
     352              : 
     353            0 :     let args = Cli::parse();
     354            0 :     tracing::info!(
     355            0 :         "version: {}, launch_timestamp: {}, build_tag {}",
     356              :         GIT_VERSION,
     357            0 :         launch_ts.to_string(),
     358              :         BUILD_TAG,
     359              :     );
     360              : 
     361            0 :     let build_info = BuildInfo {
     362            0 :         revision: GIT_VERSION,
     363            0 :         build_tag: BUILD_TAG,
     364            0 :     };
     365              : 
     366            0 :     let strict_mode = if args.dev {
     367            0 :         StrictMode::Dev
     368              :     } else {
     369            0 :         StrictMode::Strict
     370              :     };
     371              : 
     372            0 :     let secrets = Secrets::load(&args).await?;
     373              : 
     374              :     // Validate required secrets and arguments are provided in strict mode
     375            0 :     match strict_mode {
     376              :         StrictMode::Strict
     377            0 :             if (secrets.public_key.is_none()
     378            0 :                 || secrets.pageserver_jwt_token.is_none()
     379            0 :                 || secrets.control_plane_jwt_token.is_none()
     380            0 :                 || secrets.safekeeper_jwt_token.is_none()) =>
     381              :         {
     382              :             // Production systems should always have secrets configured: if public_key was not set
     383              :             // then we would implicitly disable auth.
     384            0 :             anyhow::bail!(
     385            0 :                 "Insecure config!  One or more secrets is not set.  This is only permitted in `--dev` mode"
     386              :             );
     387              :         }
     388            0 :         StrictMode::Strict if args.control_plane_url.is_none() => {
     389              :             // Production systems should always have a control plane URL set, to prevent falling
     390              :             // back to trying to use neon_local.
     391            0 :             anyhow::bail!(
     392            0 :                 "`--control-plane-url` is not set: this is only permitted in `--dev` mode"
     393              :             );
     394              :         }
     395            0 :         StrictMode::Strict if args.use_local_compute_notifications => {
     396            0 :             anyhow::bail!("`--use-local-compute-notifications` is only permitted in `--dev` mode");
     397              :         }
     398            0 :         StrictMode::Strict if args.timeline_safekeeper_count < 3 => {
     399            0 :             anyhow::bail!(
     400            0 :                 "Running with less than 3 safekeepers per timeline is only permitted in `--dev` mode"
     401              :             );
     402              :         }
     403              :         StrictMode::Strict => {
     404            0 :             tracing::info!("Starting in strict mode: configuration is OK.")
     405              :         }
     406              :         StrictMode::Dev => {
     407            0 :             tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
     408              :         }
     409              :     }
     410              : 
     411            0 :     let ssl_ca_certs = match args.ssl_ca_file.as_ref() {
     412            0 :         Some(ssl_ca_file) => {
     413            0 :             tracing::info!("Using ssl root CA file: {ssl_ca_file:?}");
     414            0 :             let buf = tokio::fs::read(ssl_ca_file).await?;
     415            0 :             Certificate::from_pem_bundle(&buf)?
     416              :         }
     417            0 :         None => Vec::new(),
     418              :     };
     419              : 
     420            0 :     let posthog_config = if let Ok(json) = std::env::var(POSTHOG_CONFIG_ENV) {
     421            0 :         let res: Result<PostHogConfig, _> = serde_json::from_str(&json);
     422            0 :         if let Ok(config) = res {
     423            0 :             Some(config)
     424              :         } else {
     425            0 :             tracing::warn!("Invalid posthog config: {json}");
     426            0 :             None
     427              :         }
     428              :     } else {
     429            0 :         None
     430              :     };
     431              : 
     432            0 :     let config = Config {
     433            0 :         pageserver_jwt_token: secrets.pageserver_jwt_token,
     434            0 :         safekeeper_jwt_token: secrets.safekeeper_jwt_token,
     435            0 :         control_plane_jwt_token: secrets.control_plane_jwt_token,
     436            0 :         peer_jwt_token: secrets.peer_jwt_token,
     437            0 :         control_plane_url: args.control_plane_url,
     438            0 :         max_offline_interval: args
     439            0 :             .max_offline_interval
     440            0 :             .map(humantime::Duration::into)
     441            0 :             .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
     442            0 :         max_warming_up_interval: args
     443            0 :             .max_warming_up_interval
     444            0 :             .map(humantime::Duration::into)
     445            0 :             .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
     446            0 :         reconciler_concurrency: args
     447            0 :             .reconciler_concurrency
     448            0 :             .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
     449            0 :         priority_reconciler_concurrency: args
     450            0 :             .priority_reconciler_concurrency
     451            0 :             .unwrap_or(PRIORITY_RECONCILER_CONCURRENCY_DEFAULT),
     452            0 :         safekeeper_reconciler_concurrency: args
     453            0 :             .safekeeper_reconciler_concurrency
     454            0 :             .unwrap_or(SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT),
     455            0 :         tenant_rate_limit: args.tenant_rate_limit,
     456            0 :         split_threshold: args.split_threshold,
     457            0 :         max_split_shards: args.max_split_shards,
     458            0 :         initial_split_threshold: args.initial_split_threshold,
     459            0 :         initial_split_shards: args.initial_split_shards,
     460            0 :         neon_local_repo_dir: args.neon_local_repo_dir,
     461            0 :         max_secondary_lag_bytes: args.max_secondary_lag_bytes,
     462            0 :         heartbeat_interval: args
     463            0 :             .heartbeat_interval
     464            0 :             .map(humantime::Duration::into)
     465            0 :             .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
     466            0 :         long_reconcile_threshold: args
     467            0 :             .long_reconcile_threshold
     468            0 :             .map(humantime::Duration::into)
     469            0 :             .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
     470            0 :         address_for_peers: args.address_for_peers,
     471            0 :         start_as_candidate: args.start_as_candidate,
     472            0 :         use_https_pageserver_api: args.use_https_pageserver_api,
     473            0 :         use_https_safekeeper_api: args.use_https_safekeeper_api,
     474            0 :         ssl_ca_certs,
     475            0 :         timelines_onto_safekeepers: args.timelines_onto_safekeepers,
     476            0 :         use_local_compute_notifications: args.use_local_compute_notifications,
     477            0 :         timeline_safekeeper_count: args.timeline_safekeeper_count,
     478            0 :         posthog_config: posthog_config.clone(),
     479            0 :         kick_secondary_downloads: args.kick_secondary_downloads,
     480            0 :         shard_split_request_timeout: args
     481            0 :             .shard_split_request_timeout
     482            0 :             .map(humantime::Duration::into)
     483            0 :             .unwrap_or(Duration::MAX),
     484            0 :         handle_ps_local_disk_loss: args.handle_ps_local_disk_loss,
     485            0 :     };
     486              : 
     487              :     // Validate that we can connect to the database
     488            0 :     Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
     489              : 
     490            0 :     let persistence = Arc::new(Persistence::new(secrets.database_url).await);
     491              : 
     492            0 :     let service = Service::spawn(config, persistence.clone()).await?;
     493              : 
     494            0 :     let auth = secrets
     495            0 :         .public_key
     496            0 :         .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
     497            0 :     let router = make_router(service.clone(), auth, build_info)
     498            0 :         .build()
     499            0 :         .map_err(|err| anyhow!(err))?;
     500            0 :     let http_service =
     501            0 :         Arc::new(http_utils::RequestServiceBuilder::new(router).map_err(|err| anyhow!(err))?);
     502              : 
     503            0 :     let api_shutdown = CancellationToken::new();
     504              : 
     505              :     // Start HTTP server
     506            0 :     let http_server_task: OptionFuture<_> = match args.listen {
     507            0 :         Some(http_addr) => {
     508            0 :             let http_listener = tcp_listener::bind(http_addr)?;
     509            0 :             let http_server =
     510            0 :                 http_utils::server::Server::new(Arc::clone(&http_service), http_listener, None)?;
     511              : 
     512            0 :             tracing::info!("Serving HTTP on {}", http_addr);
     513            0 :             Some(tokio::task::spawn(http_server.serve(api_shutdown.clone())))
     514              :         }
     515            0 :         None => None,
     516              :     }
     517            0 :     .into();
     518              : 
     519              :     // Start HTTPS server
     520            0 :     let https_server_task: OptionFuture<_> = match args.listen_https {
     521            0 :         Some(https_addr) => {
     522            0 :             let https_listener = tcp_listener::bind(https_addr)?;
     523              : 
     524            0 :             let resolver = ReloadingCertificateResolver::new(
     525            0 :                 "main",
     526            0 :                 &args.ssl_key_file,
     527            0 :                 &args.ssl_cert_file,
     528            0 :                 *args.ssl_cert_reload_period,
     529            0 :             )
     530            0 :             .await?;
     531              : 
     532            0 :             let server_config = rustls::ServerConfig::builder()
     533            0 :                 .with_no_client_auth()
     534            0 :                 .with_cert_resolver(resolver);
     535              : 
     536            0 :             let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
     537            0 :             let https_server =
     538            0 :                 http_utils::server::Server::new(http_service, https_listener, Some(tls_acceptor))?;
     539              : 
     540            0 :             tracing::info!("Serving HTTPS on {}", https_addr);
     541            0 :             Some(tokio::task::spawn(https_server.serve(api_shutdown.clone())))
     542              :         }
     543            0 :         None => None,
     544              :     }
     545            0 :     .into();
     546              : 
     547            0 :     let chaos_task = args.chaos_interval.map(|interval| {
     548            0 :         let service = service.clone();
     549            0 :         let cancel = CancellationToken::new();
     550            0 :         let cancel_bg = cancel.clone();
     551            0 :         let chaos_exit_crontab = args.chaos_exit_crontab;
     552              :         (
     553            0 :             tokio::task::spawn(
     554            0 :                 async move {
     555            0 :                     let mut chaos_injector =
     556            0 :                         ChaosInjector::new(service, interval.into(), chaos_exit_crontab);
     557            0 :                     chaos_injector.run(cancel_bg).await
     558            0 :                 }
     559            0 :                 .instrument(tracing::info_span!("chaos_injector")),
     560              :             ),
     561            0 :             cancel,
     562              :         )
     563            0 :     });
     564              : 
     565            0 :     let feature_flag_task = if let Some(posthog_config) = posthog_config {
     566            0 :         let service = service.clone();
     567            0 :         let cancel = CancellationToken::new();
     568            0 :         let cancel_bg = cancel.clone();
     569            0 :         let task = tokio::task::spawn(
     570            0 :             async move {
     571            0 :                 match FeatureFlagService::new(service, posthog_config) {
     572            0 :                     Ok(feature_flag_service) => {
     573            0 :                         let feature_flag_service = Arc::new(feature_flag_service);
     574            0 :                         feature_flag_service.run(cancel_bg).await
     575              :                     }
     576            0 :                     Err(e) => {
     577            0 :                         tracing::warn!("Failed to create feature flag service: {}", e);
     578              :                     }
     579              :                 };
     580            0 :             }
     581            0 :             .instrument(tracing::info_span!("feature_flag_service")),
     582              :         );
     583            0 :         Some((task, cancel))
     584              :     } else {
     585            0 :         None
     586              :     };
     587              : 
     588              :     // Wait until we receive a signal
     589            0 :     let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
     590            0 :     let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
     591            0 :     let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
     592            0 :     tokio::pin!(http_server_task, https_server_task);
     593            0 :     tokio::select! {
     594            0 :         _ = sigint.recv() => {},
     595            0 :         _ = sigterm.recv() => {},
     596            0 :         _ = sigquit.recv() => {},
     597            0 :         Some(err) = &mut http_server_task => {
     598            0 :             panic!("HTTP server task failed: {err:#?}");
     599              :         }
     600            0 :         Some(err) = &mut https_server_task => {
     601            0 :             panic!("HTTPS server task failed: {err:#?}");
     602              :         }
     603              :     }
     604            0 :     tracing::info!("Terminating on signal");
     605              : 
     606              :     // Stop HTTP and HTTPS servers first, so that we don't have to service requests
     607              :     // while shutting down Service.
     608            0 :     api_shutdown.cancel();
     609              : 
     610              :     // If the deadline is exceeded, we will fall through and shut down the service anyway,
     611              :     // any request handlers in flight will experience cancellation & their clients will
     612              :     // see a torn connection.
     613            0 :     let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
     614              : 
     615            0 :     match tokio::time::timeout_at(deadline, http_server_task).await {
     616            0 :         Ok(Some(Ok(_))) => tracing::info!("Joined HTTP server task"),
     617            0 :         Ok(Some(Err(e))) => tracing::error!("Error joining HTTP server task: {e}"),
     618            0 :         Ok(None) => {} // HTTP is disabled.
     619            0 :         Err(_) => tracing::warn!("Timed out joining HTTP server task"),
     620              :     }
     621              : 
     622            0 :     match tokio::time::timeout_at(deadline, https_server_task).await {
     623            0 :         Ok(Some(Ok(_))) => tracing::info!("Joined HTTPS server task"),
     624            0 :         Ok(Some(Err(e))) => tracing::error!("Error joining HTTPS server task: {e}"),
     625            0 :         Ok(None) => {} // HTTPS is disabled.
     626            0 :         Err(_) => tracing::warn!("Timed out joining HTTPS server task"),
     627              :     }
     628              : 
     629              :     // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
     630            0 :     if let Some((chaos_jh, chaos_cancel)) = chaos_task {
     631            0 :         chaos_cancel.cancel();
     632            0 :         chaos_jh.await.ok();
     633            0 :     }
     634              : 
     635              :     // If we were running the feature flag service, stop that so that we're not calling into Service while it shuts down
     636            0 :     if let Some((feature_flag_task, feature_flag_cancel)) = feature_flag_task {
     637            0 :         feature_flag_cancel.cancel();
     638            0 :         feature_flag_task.await.ok();
     639            0 :     }
     640              : 
     641            0 :     service.shutdown().await;
     642            0 :     tracing::info!("Service shutdown complete");
     643              : 
     644            0 :     std::process::exit(0);
     645            0 : }
        

Generated by: LCOV version 2.1-beta