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

Generated by: LCOV version 2.1-beta