LCOV - code coverage report
Current view: top level - storage_controller/src - main.rs (source / functions) Coverage Total Hit
Test: 4e30745f424539d3816b821c09fe7733c446c226.info Lines: 0.0 % 164 0
Test Date: 2024-06-19 13:20:49 Functions: 0.0 % 31 0

            Line data    Source code
       1              : use anyhow::{anyhow, Context};
       2              : use camino::Utf8PathBuf;
       3              : use clap::Parser;
       4              : use diesel::Connection;
       5              : use metrics::launch_timestamp::LaunchTimestamp;
       6              : use metrics::BuildInfo;
       7              : use std::sync::Arc;
       8              : use storage_controller::http::make_router;
       9              : use storage_controller::metrics::preinitialize_metrics;
      10              : use storage_controller::persistence::Persistence;
      11              : use storage_controller::service::{
      12              :     Config, Service, MAX_UNAVAILABLE_INTERVAL_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
      13              : };
      14              : use tokio::signal::unix::SignalKind;
      15              : use tokio_util::sync::CancellationToken;
      16              : use utils::auth::{JwtAuth, SwappableJwtAuth};
      17              : use utils::logging::{self, LogFormat};
      18              : 
      19              : use utils::sentry_init::init_sentry;
      20              : use utils::{project_build_tag, project_git_version, tcp_listener};
      21              : 
      22              : project_git_version!(GIT_VERSION);
      23              : project_build_tag!(BUILD_TAG);
      24              : 
      25              : use diesel_migrations::{embed_migrations, EmbeddedMigrations};
      26              : pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
      27              : 
      28            0 : #[derive(Parser)]
      29              : #[command(author, version, about, long_about = None)]
      30              : #[command(arg_required_else_help(true))]
      31              : struct Cli {
      32              :     /// Host and port to listen on, like `127.0.0.1:1234`
      33              :     #[arg(short, long)]
      34            0 :     listen: std::net::SocketAddr,
      35              : 
      36              :     /// Public key for JWT authentication of clients
      37              :     #[arg(long)]
      38              :     public_key: Option<String>,
      39              : 
      40              :     /// Token for authenticating this service with the pageservers it controls
      41              :     #[arg(long)]
      42              :     jwt_token: Option<String>,
      43              : 
      44              :     /// Token for authenticating this service with the control plane, when calling
      45              :     /// the compute notification endpoint
      46              :     #[arg(long)]
      47              :     control_plane_jwt_token: Option<String>,
      48              : 
      49              :     /// URL to control plane compute notification endpoint
      50              :     #[arg(long)]
      51              :     compute_hook_url: Option<String>,
      52              : 
      53              :     /// Path to the .json file to store state (will be created if it doesn't exist)
      54              :     #[arg(short, long)]
      55              :     path: Option<Utf8PathBuf>,
      56              : 
      57              :     /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
      58              :     #[arg(long)]
      59              :     database_url: Option<String>,
      60              : 
      61              :     /// Flag to enable dev mode, which permits running without auth
      62              :     #[arg(long, default_value = "false")]
      63            0 :     dev: bool,
      64              : 
      65              :     /// Grace period before marking unresponsive pageserver offline
      66              :     #[arg(long)]
      67              :     max_unavailable_interval: Option<humantime::Duration>,
      68              : 
      69              :     /// Size threshold for automatically splitting shards (disabled by default)
      70              :     #[arg(long)]
      71              :     split_threshold: Option<u64>,
      72              : 
      73              :     /// Maximum number of reconcilers that may run in parallel
      74              :     #[arg(long)]
      75              :     reconciler_concurrency: Option<usize>,
      76              : 
      77              :     /// How long to wait for the initial database connection to be available.
      78              :     #[arg(long, default_value = "5s")]
      79            0 :     db_connect_timeout: humantime::Duration,
      80              : }
      81              : 
      82              : enum StrictMode {
      83              :     /// In strict mode, we will require that all secrets are loaded, i.e. security features
      84              :     /// may not be implicitly turned off by omitting secrets in the environment.
      85              :     Strict,
      86              :     /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
      87              :     /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
      88              :     /// requests, no public key -> don't authenticate incoming requests).
      89              :     Dev,
      90              : }
      91              : 
      92              : impl Default for StrictMode {
      93            0 :     fn default() -> Self {
      94            0 :         Self::Strict
      95            0 :     }
      96              : }
      97              : 
      98              : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
      99              : /// type encapsulates the logic to decide which and do the loading.
     100              : struct Secrets {
     101              :     database_url: String,
     102              :     public_key: Option<JwtAuth>,
     103              :     jwt_token: Option<String>,
     104              :     control_plane_jwt_token: Option<String>,
     105              : }
     106              : 
     107              : impl Secrets {
     108              :     const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
     109              :     const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
     110              :     const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
     111              :     const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
     112              : 
     113              :     /// Load secrets from, in order of preference:
     114              :     /// - CLI args if database URL is provided on the CLI
     115              :     /// - Environment variables if DATABASE_URL is set.
     116              :     /// - AWS Secrets Manager secrets
     117            0 :     async fn load(args: &Cli) -> anyhow::Result<Self> {
     118            0 :         let Some(database_url) =
     119            0 :             Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV).await
     120              :         else {
     121            0 :             anyhow::bail!(
     122            0 :                 "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
     123            0 :             )
     124              :         };
     125              : 
     126            0 :         let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV).await {
     127            0 :             Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
     128            0 :             None => None,
     129              :         };
     130              : 
     131            0 :         let this = Self {
     132            0 :             database_url,
     133            0 :             public_key,
     134            0 :             jwt_token: Self::load_secret(&args.jwt_token, Self::PAGESERVER_JWT_TOKEN_ENV).await,
     135            0 :             control_plane_jwt_token: Self::load_secret(
     136            0 :                 &args.control_plane_jwt_token,
     137            0 :                 Self::CONTROL_PLANE_JWT_TOKEN_ENV,
     138            0 :             )
     139            0 :             .await,
     140              :         };
     141              : 
     142            0 :         Ok(this)
     143            0 :     }
     144              : 
     145            0 :     async fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
     146            0 :         if let Some(v) = cli {
     147            0 :             Some(v.clone())
     148            0 :         } else if let Ok(v) = std::env::var(env_name) {
     149            0 :             Some(v)
     150              :         } else {
     151            0 :             None
     152              :         }
     153            0 :     }
     154              : }
     155              : 
     156              : /// Execute the diesel migrations that are built into this binary
     157            0 : async fn migration_run(database_url: &str) -> anyhow::Result<()> {
     158              :     use diesel::PgConnection;
     159              :     use diesel_migrations::{HarnessWithOutput, MigrationHarness};
     160            0 :     let mut conn = PgConnection::establish(database_url)?;
     161              : 
     162            0 :     HarnessWithOutput::write_to_stdout(&mut conn)
     163            0 :         .run_pending_migrations(MIGRATIONS)
     164            0 :         .map(|_| ())
     165            0 :         .map_err(|e| anyhow::anyhow!(e))?;
     166              : 
     167            0 :     Ok(())
     168            0 : }
     169              : 
     170            0 : fn main() -> anyhow::Result<()> {
     171            0 :     let default_panic = std::panic::take_hook();
     172            0 :     std::panic::set_hook(Box::new(move |info| {
     173            0 :         default_panic(info);
     174            0 :         std::process::exit(1);
     175            0 :     }));
     176            0 : 
     177            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     178            0 : 
     179            0 :     tokio::runtime::Builder::new_current_thread()
     180            0 :         // We use spawn_blocking for database operations, so require approximately
     181            0 :         // as many blocking threads as we will open database connections.
     182            0 :         .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
     183            0 :         .enable_all()
     184            0 :         .build()
     185            0 :         .unwrap()
     186            0 :         .block_on(async_main())
     187            0 : }
     188              : 
     189            0 : async fn async_main() -> anyhow::Result<()> {
     190            0 :     let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
     191            0 : 
     192            0 :     logging::init(
     193            0 :         LogFormat::Plain,
     194            0 :         logging::TracingErrorLayerEnablement::Disabled,
     195            0 :         logging::Output::Stdout,
     196            0 :     )?;
     197              : 
     198            0 :     preinitialize_metrics();
     199            0 : 
     200            0 :     let args = Cli::parse();
     201            0 :     tracing::info!(
     202            0 :         "version: {}, launch_timestamp: {}, build_tag {}, state at {}, listening on {}",
     203            0 :         GIT_VERSION,
     204            0 :         launch_ts.to_string(),
     205            0 :         BUILD_TAG,
     206            0 :         args.path.as_ref().unwrap_or(&Utf8PathBuf::from("<none>")),
     207              :         args.listen
     208              :     );
     209              : 
     210            0 :     let build_info = BuildInfo {
     211            0 :         revision: GIT_VERSION,
     212            0 :         build_tag: BUILD_TAG,
     213            0 :     };
     214              : 
     215            0 :     let strict_mode = if args.dev {
     216            0 :         StrictMode::Dev
     217              :     } else {
     218            0 :         StrictMode::Strict
     219              :     };
     220              : 
     221            0 :     let secrets = Secrets::load(&args).await?;
     222              : 
     223              :     // Validate required secrets and arguments are provided in strict mode
     224            0 :     match strict_mode {
     225              :         StrictMode::Strict
     226            0 :             if (secrets.public_key.is_none()
     227            0 :                 || secrets.jwt_token.is_none()
     228            0 :                 || secrets.control_plane_jwt_token.is_none()) =>
     229            0 :         {
     230            0 :             // Production systems should always have secrets configured: if public_key was not set
     231            0 :             // then we would implicitly disable auth.
     232            0 :             anyhow::bail!(
     233            0 :                     "Insecure config!  One or more secrets is not set.  This is only permitted in `--dev` mode"
     234            0 :                 );
     235              :         }
     236            0 :         StrictMode::Strict if args.compute_hook_url.is_none() => {
     237            0 :             // Production systems should always have a compute hook set, to prevent falling
     238            0 :             // back to trying to use neon_local.
     239            0 :             anyhow::bail!(
     240            0 :                 "`--compute-hook-url` is not set: this is only permitted in `--dev` mode"
     241            0 :             );
     242              :         }
     243              :         StrictMode::Strict => {
     244            0 :             tracing::info!("Starting in strict mode: configuration is OK.")
     245              :         }
     246              :         StrictMode::Dev => {
     247            0 :             tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
     248              :         }
     249              :     }
     250              : 
     251            0 :     let config = Config {
     252            0 :         jwt_token: secrets.jwt_token,
     253            0 :         control_plane_jwt_token: secrets.control_plane_jwt_token,
     254            0 :         compute_hook_url: args.compute_hook_url,
     255            0 :         max_unavailable_interval: args
     256            0 :             .max_unavailable_interval
     257            0 :             .map(humantime::Duration::into)
     258            0 :             .unwrap_or(MAX_UNAVAILABLE_INTERVAL_DEFAULT),
     259            0 :         reconciler_concurrency: args
     260            0 :             .reconciler_concurrency
     261            0 :             .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
     262            0 :         split_threshold: args.split_threshold,
     263            0 :     };
     264            0 : 
     265            0 :     // After loading secrets & config, but before starting anything else, apply database migrations
     266            0 :     Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
     267              : 
     268            0 :     migration_run(&secrets.database_url)
     269            0 :         .await
     270            0 :         .context("Running database migrations")?;
     271              : 
     272            0 :     let json_path = args.path;
     273            0 :     let persistence = Arc::new(Persistence::new(secrets.database_url, json_path.clone()));
     274              : 
     275            0 :     let service = Service::spawn(config, persistence.clone()).await?;
     276              : 
     277            0 :     let http_listener = tcp_listener::bind(args.listen)?;
     278              : 
     279            0 :     let auth = secrets
     280            0 :         .public_key
     281            0 :         .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
     282            0 :     let router = make_router(service.clone(), auth, build_info)
     283            0 :         .build()
     284            0 :         .map_err(|err| anyhow!(err))?;
     285            0 :     let router_service = utils::http::RouterService::new(router).unwrap();
     286            0 : 
     287            0 :     // Start HTTP server
     288            0 :     let server_shutdown = CancellationToken::new();
     289            0 :     let server = hyper::Server::from_tcp(http_listener)?
     290            0 :         .serve(router_service)
     291            0 :         .with_graceful_shutdown({
     292            0 :             let server_shutdown = server_shutdown.clone();
     293            0 :             async move {
     294            0 :                 server_shutdown.cancelled().await;
     295            0 :             }
     296            0 :         });
     297            0 :     tracing::info!("Serving on {0}", args.listen);
     298            0 :     let server_task = tokio::task::spawn(server);
     299              : 
     300              :     // Wait until we receive a signal
     301            0 :     let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
     302            0 :     let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
     303            0 :     let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
     304              :     tokio::select! {
     305              :         _ = sigint.recv() => {},
     306              :         _ = sigterm.recv() => {},
     307              :         _ = sigquit.recv() => {},
     308              :     }
     309            0 :     tracing::info!("Terminating on signal");
     310              : 
     311            0 :     if json_path.is_some() {
     312              :         // Write out a JSON dump on shutdown: this is used in compat tests to avoid passing
     313              :         // full postgres dumps around.
     314            0 :         if let Err(e) = persistence.write_tenants_json().await {
     315            0 :             tracing::error!("Failed to write JSON on shutdown: {e}")
     316            0 :         }
     317            0 :     }
     318              : 
     319              :     // Stop HTTP server first, so that we don't have to service requests
     320              :     // while shutting down Service
     321            0 :     server_shutdown.cancel();
     322            0 :     if let Err(e) = server_task.await {
     323            0 :         tracing::error!("Error joining HTTP server task: {e}")
     324            0 :     }
     325            0 :     tracing::info!("Joined HTTP server task");
     326              : 
     327            0 :     service.shutdown().await;
     328            0 :     tracing::info!("Service shutdown complete");
     329              : 
     330            0 :     std::process::exit(0);
     331            0 : }
        

Generated by: LCOV version 2.1-beta