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

Generated by: LCOV version 2.1-beta