LCOV - code coverage report
Current view: top level - storage_controller/src - main.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 0.0 % 194 0
Test Date: 2024-11-13 18:23:39 Functions: 0.0 % 30 0

            Line data    Source code
       1              : use anyhow::{anyhow, Context};
       2              : use clap::Parser;
       3              : use hyper0::Uri;
       4              : use metrics::launch_timestamp::LaunchTimestamp;
       5              : use metrics::BuildInfo;
       6              : use std::path::PathBuf;
       7              : use std::sync::Arc;
       8              : use std::time::Duration;
       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::chaos_injector::ChaosInjector;
      13              : use storage_controller::service::{
      14              :     Config, Service, HEARTBEAT_INTERVAL_DEFAULT, LONG_RECONCILE_THRESHOLD_DEFAULT,
      15              :     MAX_OFFLINE_INTERVAL_DEFAULT, MAX_WARMING_UP_INTERVAL_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
      16              : };
      17              : use tokio::signal::unix::SignalKind;
      18              : use tokio_util::sync::CancellationToken;
      19              : use tracing::Instrument;
      20              : use utils::auth::{JwtAuth, SwappableJwtAuth};
      21              : use utils::logging::{self, LogFormat};
      22              : 
      23              : use utils::sentry_init::init_sentry;
      24              : use utils::{project_build_tag, project_git_version, tcp_listener};
      25              : 
      26              : project_git_version!(GIT_VERSION);
      27              : project_build_tag!(BUILD_TAG);
      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              :     #[arg(long)]
      51              :     peer_jwt_token: Option<String>,
      52              : 
      53              :     /// URL to control plane compute notification endpoint
      54              :     #[arg(long)]
      55              :     compute_hook_url: Option<String>,
      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_offline_interval: Option<humantime::Duration>,
      68              : 
      69              :     /// More tolerant grace period before marking unresponsive pagserver offline used
      70              :     /// around pageserver restarts
      71              :     #[arg(long)]
      72              :     max_warming_up_interval: Option<humantime::Duration>,
      73              : 
      74              :     /// Size threshold for automatically splitting shards (disabled by default)
      75              :     #[arg(long)]
      76              :     split_threshold: Option<u64>,
      77              : 
      78              :     /// Maximum number of reconcilers that may run in parallel
      79              :     #[arg(long)]
      80              :     reconciler_concurrency: Option<usize>,
      81              : 
      82              :     /// How long to wait for the initial database connection to be available.
      83              :     #[arg(long, default_value = "5s")]
      84            0 :     db_connect_timeout: humantime::Duration,
      85              : 
      86              :     #[arg(long, default_value = "false")]
      87            0 :     start_as_candidate: bool,
      88              : 
      89              :     // TODO: make this mandatory once the helm chart gets updated
      90              :     #[arg(long)]
      91              :     address_for_peers: Option<Uri>,
      92              : 
      93              :     /// `neon_local` sets this to the path of the neon_local repo dir.
      94              :     /// Only relevant for testing.
      95              :     // TODO: make `cfg(feature = "testing")`
      96              :     #[arg(long)]
      97              :     neon_local_repo_dir: Option<PathBuf>,
      98              : 
      99              :     /// Chaos testing
     100              :     #[arg(long)]
     101              :     chaos_interval: Option<humantime::Duration>,
     102              : 
     103              :     // Maximum acceptable lag for the secondary location while draining
     104              :     // a pageserver
     105              :     #[arg(long)]
     106              :     max_secondary_lag_bytes: Option<u64>,
     107              : 
     108              :     // Period with which to send heartbeats to registered nodes
     109              :     #[arg(long)]
     110              :     heartbeat_interval: Option<humantime::Duration>,
     111              : 
     112              :     #[arg(long)]
     113              :     long_reconcile_threshold: Option<humantime::Duration>,
     114              : }
     115              : 
     116              : enum StrictMode {
     117              :     /// In strict mode, we will require that all secrets are loaded, i.e. security features
     118              :     /// may not be implicitly turned off by omitting secrets in the environment.
     119              :     Strict,
     120              :     /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
     121              :     /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
     122              :     /// requests, no public key -> don't authenticate incoming requests).
     123              :     Dev,
     124              : }
     125              : 
     126              : impl Default for StrictMode {
     127            0 :     fn default() -> Self {
     128            0 :         Self::Strict
     129            0 :     }
     130              : }
     131              : 
     132              : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
     133              : /// type encapsulates the logic to decide which and do the loading.
     134              : struct Secrets {
     135              :     database_url: String,
     136              :     public_key: Option<JwtAuth>,
     137              :     jwt_token: Option<String>,
     138              :     control_plane_jwt_token: Option<String>,
     139              :     peer_jwt_token: Option<String>,
     140              : }
     141              : 
     142              : impl Secrets {
     143              :     const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
     144              :     const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
     145              :     const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
     146              :     const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
     147              :     const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
     148              : 
     149              :     /// Load secrets from, in order of preference:
     150              :     /// - CLI args if database URL is provided on the CLI
     151              :     /// - Environment variables if DATABASE_URL is set.
     152            0 :     async fn load(args: &Cli) -> anyhow::Result<Self> {
     153            0 :         let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
     154              :         else {
     155            0 :             anyhow::bail!(
     156            0 :                 "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
     157            0 :             )
     158              :         };
     159              : 
     160            0 :         let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
     161            0 :             Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
     162            0 :             None => None,
     163              :         };
     164              : 
     165            0 :         let this = Self {
     166            0 :             database_url,
     167            0 :             public_key,
     168            0 :             jwt_token: Self::load_secret(&args.jwt_token, Self::PAGESERVER_JWT_TOKEN_ENV),
     169            0 :             control_plane_jwt_token: Self::load_secret(
     170            0 :                 &args.control_plane_jwt_token,
     171            0 :                 Self::CONTROL_PLANE_JWT_TOKEN_ENV,
     172            0 :             ),
     173            0 :             peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
     174            0 :         };
     175            0 : 
     176            0 :         Ok(this)
     177            0 :     }
     178              : 
     179            0 :     fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
     180            0 :         if let Some(v) = cli {
     181            0 :             Some(v.clone())
     182            0 :         } else if let Ok(v) = std::env::var(env_name) {
     183            0 :             Some(v)
     184              :         } else {
     185            0 :             None
     186              :         }
     187            0 :     }
     188              : }
     189              : 
     190            0 : fn main() -> anyhow::Result<()> {
     191            0 :     logging::init(
     192            0 :         LogFormat::Plain,
     193            0 :         logging::TracingErrorLayerEnablement::Disabled,
     194            0 :         logging::Output::Stdout,
     195            0 :     )?;
     196              : 
     197              :     // log using tracing so we don't get confused output by default hook writing to stderr
     198            0 :     utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
     199            0 : 
     200            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     201            0 : 
     202            0 :     let hook = std::panic::take_hook();
     203            0 :     std::panic::set_hook(Box::new(move |info| {
     204            0 :         // let sentry send a message (and flush)
     205            0 :         // and trace the error
     206            0 :         hook(info);
     207            0 : 
     208            0 :         std::process::exit(1);
     209            0 :     }));
     210            0 : 
     211            0 :     tokio::runtime::Builder::new_current_thread()
     212            0 :         // We use spawn_blocking for database operations, so require approximately
     213            0 :         // as many blocking threads as we will open database connections.
     214            0 :         .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
     215            0 :         .enable_all()
     216            0 :         .build()
     217            0 :         .unwrap()
     218            0 :         .block_on(async_main())
     219            0 : }
     220              : 
     221            0 : async fn async_main() -> anyhow::Result<()> {
     222            0 :     let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
     223            0 : 
     224            0 :     preinitialize_metrics();
     225            0 : 
     226            0 :     let args = Cli::parse();
     227            0 :     tracing::info!(
     228            0 :         "version: {}, launch_timestamp: {}, build_tag {}, listening on {}",
     229            0 :         GIT_VERSION,
     230            0 :         launch_ts.to_string(),
     231              :         BUILD_TAG,
     232              :         args.listen
     233              :     );
     234              : 
     235            0 :     let build_info = BuildInfo {
     236            0 :         revision: GIT_VERSION,
     237            0 :         build_tag: BUILD_TAG,
     238            0 :     };
     239              : 
     240            0 :     let strict_mode = if args.dev {
     241            0 :         StrictMode::Dev
     242              :     } else {
     243            0 :         StrictMode::Strict
     244              :     };
     245              : 
     246            0 :     let secrets = Secrets::load(&args).await?;
     247              : 
     248              :     // Validate required secrets and arguments are provided in strict mode
     249            0 :     match strict_mode {
     250              :         StrictMode::Strict
     251            0 :             if (secrets.public_key.is_none()
     252            0 :                 || secrets.jwt_token.is_none()
     253            0 :                 || secrets.control_plane_jwt_token.is_none()) =>
     254            0 :         {
     255            0 :             // Production systems should always have secrets configured: if public_key was not set
     256            0 :             // then we would implicitly disable auth.
     257            0 :             anyhow::bail!(
     258            0 :                     "Insecure config!  One or more secrets is not set.  This is only permitted in `--dev` mode"
     259            0 :                 );
     260              :         }
     261            0 :         StrictMode::Strict if args.compute_hook_url.is_none() => {
     262            0 :             // Production systems should always have a compute hook set, to prevent falling
     263            0 :             // back to trying to use neon_local.
     264            0 :             anyhow::bail!(
     265            0 :                 "`--compute-hook-url` is not set: this is only permitted in `--dev` mode"
     266            0 :             );
     267              :         }
     268              :         StrictMode::Strict => {
     269            0 :             tracing::info!("Starting in strict mode: configuration is OK.")
     270              :         }
     271              :         StrictMode::Dev => {
     272            0 :             tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
     273              :         }
     274              :     }
     275              : 
     276            0 :     let config = Config {
     277            0 :         jwt_token: secrets.jwt_token,
     278            0 :         control_plane_jwt_token: secrets.control_plane_jwt_token,
     279            0 :         peer_jwt_token: secrets.peer_jwt_token,
     280            0 :         compute_hook_url: args.compute_hook_url,
     281            0 :         max_offline_interval: args
     282            0 :             .max_offline_interval
     283            0 :             .map(humantime::Duration::into)
     284            0 :             .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
     285            0 :         max_warming_up_interval: args
     286            0 :             .max_warming_up_interval
     287            0 :             .map(humantime::Duration::into)
     288            0 :             .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
     289            0 :         reconciler_concurrency: args
     290            0 :             .reconciler_concurrency
     291            0 :             .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
     292            0 :         split_threshold: args.split_threshold,
     293            0 :         neon_local_repo_dir: args.neon_local_repo_dir,
     294            0 :         max_secondary_lag_bytes: args.max_secondary_lag_bytes,
     295            0 :         heartbeat_interval: args
     296            0 :             .heartbeat_interval
     297            0 :             .map(humantime::Duration::into)
     298            0 :             .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
     299            0 :         long_reconcile_threshold: args
     300            0 :             .long_reconcile_threshold
     301            0 :             .map(humantime::Duration::into)
     302            0 :             .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
     303            0 :         address_for_peers: args.address_for_peers,
     304            0 :         start_as_candidate: args.start_as_candidate,
     305            0 :         http_service_port: args.listen.port() as i32,
     306            0 :     };
     307            0 : 
     308            0 :     // Validate that we can connect to the database
     309            0 :     Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
     310              : 
     311            0 :     let persistence = Arc::new(Persistence::new(secrets.database_url));
     312              : 
     313            0 :     let service = Service::spawn(config, persistence.clone()).await?;
     314              : 
     315            0 :     let http_listener = tcp_listener::bind(args.listen)?;
     316              : 
     317            0 :     let auth = secrets
     318            0 :         .public_key
     319            0 :         .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
     320            0 :     let router = make_router(service.clone(), auth, build_info)
     321            0 :         .build()
     322            0 :         .map_err(|err| anyhow!(err))?;
     323            0 :     let router_service = utils::http::RouterService::new(router).unwrap();
     324            0 : 
     325            0 :     // Start HTTP server
     326            0 :     let server_shutdown = CancellationToken::new();
     327            0 :     let server = hyper0::Server::from_tcp(http_listener)?
     328            0 :         .serve(router_service)
     329            0 :         .with_graceful_shutdown({
     330            0 :             let server_shutdown = server_shutdown.clone();
     331            0 :             async move {
     332            0 :                 server_shutdown.cancelled().await;
     333            0 :             }
     334            0 :         });
     335            0 :     tracing::info!("Serving on {0}", args.listen);
     336            0 :     let server_task = tokio::task::spawn(server);
     337            0 : 
     338            0 :     let chaos_task = args.chaos_interval.map(|interval| {
     339            0 :         let service = service.clone();
     340            0 :         let cancel = CancellationToken::new();
     341            0 :         let cancel_bg = cancel.clone();
     342            0 :         (
     343            0 :             tokio::task::spawn(
     344            0 :                 async move {
     345            0 :                     let mut chaos_injector = ChaosInjector::new(service, interval.into());
     346            0 :                     chaos_injector.run(cancel_bg).await
     347            0 :                 }
     348            0 :                 .instrument(tracing::info_span!("chaos_injector")),
     349              :             ),
     350            0 :             cancel,
     351            0 :         )
     352            0 :     });
     353              : 
     354              :     // Wait until we receive a signal
     355            0 :     let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
     356            0 :     let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
     357            0 :     let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
     358            0 :     tokio::select! {
     359            0 :         _ = sigint.recv() => {},
     360            0 :         _ = sigterm.recv() => {},
     361            0 :         _ = sigquit.recv() => {},
     362              :     }
     363            0 :     tracing::info!("Terminating on signal");
     364              : 
     365              :     // Stop HTTP server first, so that we don't have to service requests
     366              :     // while shutting down Service.
     367            0 :     server_shutdown.cancel();
     368            0 :     match tokio::time::timeout(Duration::from_secs(5), server_task).await {
     369              :         Ok(Ok(_)) => {
     370            0 :             tracing::info!("Joined HTTP server task");
     371              :         }
     372            0 :         Ok(Err(e)) => {
     373            0 :             tracing::error!("Error joining HTTP server task: {e}")
     374              :         }
     375              :         Err(_) => {
     376            0 :             tracing::warn!("Timed out joining HTTP server task");
     377              :             // We will fall through and shut down the service anyway, any request handlers
     378              :             // in flight will experience cancellation & their clients will see a torn connection.
     379              :         }
     380              :     }
     381              : 
     382              :     // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
     383            0 :     if let Some((chaos_jh, chaos_cancel)) = chaos_task {
     384            0 :         chaos_cancel.cancel();
     385            0 :         chaos_jh.await.ok();
     386            0 :     }
     387              : 
     388            0 :     service.shutdown().await;
     389            0 :     tracing::info!("Service shutdown complete");
     390              : 
     391            0 :     std::process::exit(0);
     392            0 : }
        

Generated by: LCOV version 2.1-beta