LCOV - code coverage report
Current view: top level - proxy/src/bin - proxy.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 8.3 % 551 46
Test Date: 2024-11-13 18:23:39 Functions: 13.6 % 132 18

            Line data    Source code
       1              : use std::net::SocketAddr;
       2              : use std::pin::pin;
       3              : use std::sync::Arc;
       4              : 
       5              : use anyhow::bail;
       6              : use aws_config::environment::EnvironmentVariableCredentialsProvider;
       7              : use aws_config::imds::credentials::ImdsCredentialsProvider;
       8              : use aws_config::meta::credentials::CredentialsProviderChain;
       9              : use aws_config::meta::region::RegionProviderChain;
      10              : use aws_config::profile::ProfileFileCredentialsProvider;
      11              : use aws_config::provider_config::ProviderConfig;
      12              : use aws_config::web_identity_token::WebIdentityTokenCredentialsProvider;
      13              : use aws_config::Region;
      14              : use futures::future::Either;
      15              : use proxy::auth::backend::jwt::JwkCache;
      16              : use proxy::auth::backend::{AuthRateLimiter, ConsoleRedirectBackend, MaybeOwned};
      17              : use proxy::cancellation::{CancelMap, CancellationHandler};
      18              : use proxy::config::{
      19              :     self, remote_storage_from_toml, AuthenticationConfig, CacheOptions, HttpConfig,
      20              :     ProjectInfoCacheOptions, ProxyConfig, ProxyProtocolV2,
      21              : };
      22              : use proxy::context::parquet::ParquetUploadArgs;
      23              : use proxy::http::health_server::AppMetrics;
      24              : use proxy::metrics::Metrics;
      25              : use proxy::rate_limiter::{
      26              :     EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo, WakeComputeRateLimiter,
      27              : };
      28              : use proxy::redis::cancellation_publisher::RedisPublisherClient;
      29              : use proxy::redis::connection_with_credentials_provider::ConnectionWithCredentialsProvider;
      30              : use proxy::redis::{elasticache, notifications};
      31              : use proxy::scram::threadpool::ThreadPool;
      32              : use proxy::serverless::cancel_set::CancelSet;
      33              : use proxy::serverless::GlobalConnPoolOptions;
      34              : use proxy::{auth, control_plane, http, serverless, usage_metrics};
      35              : use remote_storage::RemoteStorageConfig;
      36              : use tokio::net::TcpListener;
      37              : use tokio::sync::Mutex;
      38              : use tokio::task::JoinSet;
      39              : use tokio_util::sync::CancellationToken;
      40              : use tracing::{info, warn, Instrument};
      41              : use utils::sentry_init::init_sentry;
      42              : use utils::{project_build_tag, project_git_version};
      43              : 
      44              : project_git_version!(GIT_VERSION);
      45              : project_build_tag!(BUILD_TAG);
      46              : 
      47              : use clap::{Parser, ValueEnum};
      48              : 
      49              : #[global_allocator]
      50              : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
      51              : 
      52            8 : #[derive(Clone, Debug, ValueEnum)]
      53              : enum AuthBackendType {
      54              :     #[value(name("console"), alias("cplane"))]
      55              :     ControlPlane,
      56              : 
      57              :     #[value(name("link"), alias("control-redirect"))]
      58              :     ConsoleRedirect,
      59              : 
      60              :     #[cfg(feature = "testing")]
      61              :     Postgres,
      62              : }
      63              : 
      64              : /// Neon proxy/router
      65            2 : #[derive(Parser)]
      66              : #[command(version = GIT_VERSION, about)]
      67              : struct ProxyCliArgs {
      68              :     /// Name of the region this proxy is deployed in
      69            1 :     #[clap(long, default_value_t = String::new())]
      70            0 :     region: String,
      71              :     /// listen for incoming client connections on ip:port
      72              :     #[clap(short, long, default_value = "127.0.0.1:4432")]
      73            0 :     proxy: String,
      74            1 :     #[clap(value_enum, long, default_value_t = AuthBackendType::ConsoleRedirect)]
      75            0 :     auth_backend: AuthBackendType,
      76              :     /// listen for management callback connection on ip:port
      77              :     #[clap(short, long, default_value = "127.0.0.1:7000")]
      78            0 :     mgmt: String,
      79              :     /// listen for incoming http connections (metrics, etc) on ip:port
      80              :     #[clap(long, default_value = "127.0.0.1:7001")]
      81            0 :     http: String,
      82              :     /// listen for incoming wss connections on ip:port
      83              :     #[clap(long)]
      84              :     wss: Option<String>,
      85              :     /// redirect unauthenticated users to the given uri in case of console redirect auth
      86              :     #[clap(short, long, default_value = "http://localhost:3000/psql_session/")]
      87            0 :     uri: String,
      88              :     /// cloud API endpoint for authenticating users
      89              :     #[clap(
      90              :         short,
      91              :         long,
      92              :         default_value = "http://localhost:3000/authenticate_proxy_request/"
      93              :     )]
      94            0 :     auth_endpoint: String,
      95              :     /// JWT used to connect to control plane.
      96              :     #[clap(
      97              :         long,
      98              :         value_name = "JWT",
      99              :         default_value = "",
     100              :         env = "NEON_PROXY_TO_CONTROLPLANE_TOKEN"
     101              :     )]
     102            0 :     control_plane_token: Arc<str>,
     103              :     /// if this is not local proxy, this toggles whether we accept jwt or passwords for http
     104            1 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     105            0 :     is_auth_broker: bool,
     106              :     /// path to TLS key for client postgres connections
     107              :     ///
     108              :     /// tls-key and tls-cert are for backwards compatibility, we can put all certs in one dir
     109              :     #[clap(short = 'k', long, alias = "ssl-key")]
     110              :     tls_key: Option<String>,
     111              :     /// path to TLS cert for client postgres connections
     112              :     ///
     113              :     /// tls-key and tls-cert are for backwards compatibility, we can put all certs in one dir
     114              :     #[clap(short = 'c', long, alias = "ssl-cert")]
     115              :     tls_cert: Option<String>,
     116              :     /// path to directory with TLS certificates for client postgres connections
     117              :     #[clap(long)]
     118              :     certs_dir: Option<String>,
     119              :     /// timeout for the TLS handshake
     120              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     121            0 :     handshake_timeout: tokio::time::Duration,
     122              :     /// http endpoint to receive periodic metric updates
     123              :     #[clap(long)]
     124              :     metric_collection_endpoint: Option<String>,
     125              :     /// how often metrics should be sent to a collection endpoint
     126              :     #[clap(long)]
     127              :     metric_collection_interval: Option<String>,
     128              :     /// cache for `wake_compute` api method (use `size=0` to disable)
     129              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     130            0 :     wake_compute_cache: String,
     131              :     /// lock for `wake_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
     132              :     #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_WAKE_COMPUTE_LOCK)]
     133            0 :     wake_compute_lock: String,
     134              :     /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
     135              :     #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
     136            0 :     connect_compute_lock: String,
     137              :     /// Allow self-signed certificates for compute nodes (for testing)
     138            1 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     139            0 :     allow_self_signed_compute: bool,
     140              :     #[clap(flatten)]
     141              :     sql_over_http: SqlOverHttpArgs,
     142              :     /// timeout for scram authentication protocol
     143              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     144            0 :     scram_protocol_timeout: tokio::time::Duration,
     145              :     /// size of the threadpool for password hashing
     146            1 :     #[clap(long, default_value_t = 4)]
     147            0 :     scram_thread_pool_size: u8,
     148              :     /// Endpoint rate limiter max number of requests per second.
     149              :     ///
     150              :     /// Provided in the form `<Requests Per Second>@<Bucket Duration Size>`.
     151              :     /// Can be given multiple times for different bucket sizes.
     152            5 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
     153            1 :     endpoint_rps_limit: Vec<RateBucketInfo>,
     154              :     /// Wake compute rate limiter max number of requests per second.
     155            5 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_SET)]
     156            1 :     wake_compute_limit: Vec<RateBucketInfo>,
     157              :     /// Whether the auth rate limiter actually takes effect (for testing)
     158            1 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     159            0 :     auth_rate_limit_enabled: bool,
     160              :     /// Authentication rate limiter max number of hashes per second.
     161            5 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_AUTH_SET)]
     162            1 :     auth_rate_limit: Vec<RateBucketInfo>,
     163              :     /// The IP subnet to use when considering whether two IP addresses are considered the same.
     164            1 :     #[clap(long, default_value_t = 64)]
     165            0 :     auth_rate_limit_ip_subnet: u8,
     166              :     /// Redis rate limiter max number of requests per second.
     167            5 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_SET)]
     168            1 :     redis_rps_limit: Vec<RateBucketInfo>,
     169              :     /// cache for `allowed_ips` (use `size=0` to disable)
     170              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     171            0 :     allowed_ips_cache: String,
     172              :     /// cache for `role_secret` (use `size=0` to disable)
     173              :     #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
     174            0 :     role_secret_cache: String,
     175              :     /// redis url for notifications (if empty, redis_host:port will be used for both notifications and streaming connections)
     176              :     #[clap(long)]
     177              :     redis_notifications: Option<String>,
     178              :     /// what from the available authentications type to use for the regional redis we have. Supported are "irsa" and "plain".
     179              :     #[clap(long, default_value = "irsa")]
     180            0 :     redis_auth_type: String,
     181              :     /// redis host for streaming connections (might be different from the notifications host)
     182              :     #[clap(long)]
     183              :     redis_host: Option<String>,
     184              :     /// redis port for streaming connections (might be different from the notifications host)
     185              :     #[clap(long)]
     186              :     redis_port: Option<u16>,
     187              :     /// redis cluster name, used in aws elasticache
     188              :     #[clap(long)]
     189              :     redis_cluster_name: Option<String>,
     190              :     /// redis user_id, used in aws elasticache
     191              :     #[clap(long)]
     192              :     redis_user_id: Option<String>,
     193              :     /// aws region to retrieve credentials
     194            1 :     #[clap(long, default_value_t = String::new())]
     195            0 :     aws_region: String,
     196              :     /// cache for `project_info` (use `size=0` to disable)
     197              :     #[clap(long, default_value = config::ProjectInfoCacheOptions::CACHE_DEFAULT_OPTIONS)]
     198            0 :     project_info_cache: String,
     199              :     /// cache for all valid endpoints
     200              :     #[clap(long, default_value = config::EndpointCacheConfig::CACHE_DEFAULT_OPTIONS)]
     201            0 :     endpoint_cache_config: String,
     202              :     #[clap(flatten)]
     203              :     parquet_upload: ParquetUploadArgs,
     204              : 
     205              :     /// interval for backup metric collection
     206              :     #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
     207            0 :     metric_backup_collection_interval: std::time::Duration,
     208              :     /// remote storage configuration for backup metric collection
     209              :     /// Encoded as toml (same format as pageservers), eg
     210              :     /// `{bucket_name='the-bucket',bucket_region='us-east-1',prefix_in_bucket='proxy',endpoint='http://minio:9000'}`
     211              :     #[clap(long, value_parser = remote_storage_from_toml)]
     212              :     metric_backup_collection_remote_storage: Option<RemoteStorageConfig>,
     213              :     /// chunk size for backup metric collection
     214              :     /// Size of each event is no more than 400 bytes, so 2**22 is about 200MB before the compression.
     215              :     #[clap(long, default_value = "4194304")]
     216            0 :     metric_backup_collection_chunk_size: usize,
     217              :     /// Whether to retry the connection to the compute node
     218              :     #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
     219            0 :     connect_to_compute_retry: String,
     220              :     /// Whether to retry the wake_compute request
     221              :     #[clap(long, default_value = config::RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)]
     222            0 :     wake_compute_retry: String,
     223              : 
     224              :     /// Configure if this is a private access proxy for the POC: In that case the proxy will ignore the IP allowlist
     225            1 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     226            0 :     is_private_access_proxy: bool,
     227              : 
     228              :     /// Configure whether all incoming requests have a Proxy Protocol V2 packet.
     229              :     // TODO(conradludgate): switch default to rejected or required once we've updated all deployments
     230            1 :     #[clap(value_enum, long, default_value_t = ProxyProtocolV2::Supported)]
     231            0 :     proxy_protocol_v2: ProxyProtocolV2,
     232              : 
     233              :     /// Time the proxy waits for the webauth session to be confirmed by the control plane.
     234              :     // TODO: rename to `console_redirect_confirmation_timeout`.
     235              :     #[clap(long, default_value = "2m", value_parser = humantime::parse_duration)]
     236            0 :     webauth_confirmation_timeout: std::time::Duration,
     237              : }
     238              : 
     239            2 : #[derive(clap::Args, Clone, Copy, Debug)]
     240              : struct SqlOverHttpArgs {
     241              :     /// timeout for http connection requests
     242              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
     243            0 :     sql_over_http_timeout: tokio::time::Duration,
     244              : 
     245              :     /// Whether the SQL over http pool is opt-in
     246            1 :     #[clap(long, default_value_t = true, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
     247            0 :     sql_over_http_pool_opt_in: bool,
     248              : 
     249              :     /// How many connections to pool for each endpoint. Excess connections are discarded
     250            1 :     #[clap(long, default_value_t = 20)]
     251            0 :     sql_over_http_pool_max_conns_per_endpoint: usize,
     252              : 
     253              :     /// How many connections to pool for each endpoint. Excess connections are discarded
     254            1 :     #[clap(long, default_value_t = 20000)]
     255            0 :     sql_over_http_pool_max_total_conns: usize,
     256              : 
     257              :     /// How long pooled connections should remain idle for before closing
     258              :     #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
     259            0 :     sql_over_http_idle_timeout: tokio::time::Duration,
     260              : 
     261              :     /// Duration each shard will wait on average before a GC sweep.
     262              :     /// A longer time will causes sweeps to take longer but will interfere less frequently.
     263              :     #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
     264            0 :     sql_over_http_pool_gc_epoch: tokio::time::Duration,
     265              : 
     266              :     /// How many shards should the global pool have. Must be a power of two.
     267              :     /// More shards will introduce less contention for pool operations, but can
     268              :     /// increase memory used by the pool
     269            1 :     #[clap(long, default_value_t = 128)]
     270            0 :     sql_over_http_pool_shards: usize,
     271              : 
     272            1 :     #[clap(long, default_value_t = 10000)]
     273            0 :     sql_over_http_client_conn_threshold: u64,
     274              : 
     275            1 :     #[clap(long, default_value_t = 64)]
     276            0 :     sql_over_http_cancel_set_shards: usize,
     277              : 
     278            1 :     #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
     279            0 :     sql_over_http_max_request_size_bytes: u64,
     280              : 
     281            1 :     #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
     282            0 :     sql_over_http_max_response_size_bytes: usize,
     283              : }
     284              : 
     285              : #[tokio::main]
     286            0 : async fn main() -> anyhow::Result<()> {
     287            0 :     let _logging_guard = proxy::logging::init().await?;
     288            0 :     let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
     289            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     290            0 : 
     291            0 :     info!("Version: {GIT_VERSION}");
     292            0 :     info!("Build_tag: {BUILD_TAG}");
     293            0 :     let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
     294            0 :         revision: GIT_VERSION,
     295            0 :         build_tag: BUILD_TAG,
     296            0 :     });
     297            0 : 
     298            0 :     let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
     299            0 :         Ok(t) => Some(t),
     300            0 :         Err(e) => {
     301            0 :             tracing::error!(error = ?e, "could not start jemalloc metrics loop");
     302            0 :             None
     303            0 :         }
     304            0 :     };
     305            0 : 
     306            0 :     let args = ProxyCliArgs::parse();
     307            0 :     let config = build_config(&args)?;
     308            0 :     let auth_backend = build_auth_backend(&args)?;
     309            0 : 
     310            0 :     match auth_backend {
     311            0 :         Either::Left(auth_backend) => info!("Authentication backend: {auth_backend}"),
     312            0 :         Either::Right(auth_backend) => info!("Authentication backend: {auth_backend:?}"),
     313            0 :     };
     314            0 :     info!("Using region: {}", args.aws_region);
     315            0 : 
     316            0 :     let region_provider =
     317            0 :         RegionProviderChain::default_provider().or_else(Region::new(args.aws_region.clone()));
     318            0 :     let provider_conf =
     319            0 :         ProviderConfig::without_region().with_region(region_provider.region().await);
     320            0 :     let aws_credentials_provider = {
     321            0 :         // uses "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"
     322            0 :         CredentialsProviderChain::first_try("env", EnvironmentVariableCredentialsProvider::new())
     323            0 :             // uses "AWS_PROFILE" / `aws sso login --profile <profile>`
     324            0 :             .or_else(
     325            0 :                 "profile-sso",
     326            0 :                 ProfileFileCredentialsProvider::builder()
     327            0 :                     .configure(&provider_conf)
     328            0 :                     .build(),
     329            0 :             )
     330            0 :             // uses "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME"
     331            0 :             // needed to access remote extensions bucket
     332            0 :             .or_else(
     333            0 :                 "token",
     334            0 :                 WebIdentityTokenCredentialsProvider::builder()
     335            0 :                     .configure(&provider_conf)
     336            0 :                     .build(),
     337            0 :             )
     338            0 :             // uses imds v2
     339            0 :             .or_else("imds", ImdsCredentialsProvider::builder().build())
     340            0 :     };
     341            0 :     let elasticache_credentials_provider = Arc::new(elasticache::CredentialsProvider::new(
     342            0 :         elasticache::AWSIRSAConfig::new(
     343            0 :             args.aws_region.clone(),
     344            0 :             args.redis_cluster_name,
     345            0 :             args.redis_user_id,
     346            0 :         ),
     347            0 :         aws_credentials_provider,
     348            0 :     ));
     349            0 :     let regional_redis_client = match (args.redis_auth_type.as_str(), &args.redis_notifications) {
     350            0 :         ("plain", redis_url) => match redis_url {
     351            0 :             None => {
     352            0 :                 bail!("plain auth requires redis_notifications to be set");
     353            0 :             }
     354            0 :             Some(url) => Some(
     355            0 :                 ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()),
     356            0 :             ),
     357            0 :         },
     358            0 :         ("irsa", _) => match (&args.redis_host, args.redis_port) {
     359            0 :             (Some(host), Some(port)) => Some(
     360            0 :                 ConnectionWithCredentialsProvider::new_with_credentials_provider(
     361            0 :                     host.to_string(),
     362            0 :                     port,
     363            0 :                     elasticache_credentials_provider.clone(),
     364            0 :                 ),
     365            0 :             ),
     366            0 :             (None, None) => {
     367            0 :                 warn!("irsa auth requires redis-host and redis-port to be set, continuing without regional_redis_client");
     368            0 :                 None
     369            0 :             }
     370            0 :             _ => {
     371            0 :                 bail!("redis-host and redis-port must be specified together");
     372            0 :             }
     373            0 :         },
     374            0 :         _ => {
     375            0 :             bail!("unknown auth type given");
     376            0 :         }
     377            0 :     };
     378            0 : 
     379            0 :     let redis_notifications_client = if let Some(url) = args.redis_notifications {
     380            0 :         Some(ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()))
     381            0 :     } else {
     382            0 :         regional_redis_client.clone()
     383            0 :     };
     384            0 : 
     385            0 :     // Check that we can bind to address before further initialization
     386            0 :     let http_address: SocketAddr = args.http.parse()?;
     387            0 :     info!("Starting http on {http_address}");
     388            0 :     let http_listener = TcpListener::bind(http_address).await?.into_std()?;
     389            0 : 
     390            0 :     let mgmt_address: SocketAddr = args.mgmt.parse()?;
     391            0 :     info!("Starting mgmt on {mgmt_address}");
     392            0 :     let mgmt_listener = TcpListener::bind(mgmt_address).await?;
     393            0 : 
     394            0 :     let proxy_listener = if !args.is_auth_broker {
     395            0 :         let proxy_address: SocketAddr = args.proxy.parse()?;
     396            0 :         info!("Starting proxy on {proxy_address}");
     397            0 : 
     398            0 :         Some(TcpListener::bind(proxy_address).await?)
     399            0 :     } else {
     400            0 :         None
     401            0 :     };
     402            0 : 
     403            0 :     // TODO: rename the argument to something like serverless.
     404            0 :     // It now covers more than just websockets, it also covers SQL over HTTP.
     405            0 :     let serverless_listener = if let Some(serverless_address) = args.wss {
     406            0 :         let serverless_address: SocketAddr = serverless_address.parse()?;
     407            0 :         info!("Starting wss on {serverless_address}");
     408            0 :         Some(TcpListener::bind(serverless_address).await?)
     409            0 :     } else if args.is_auth_broker {
     410            0 :         bail!("wss arg must be present for auth-broker")
     411            0 :     } else {
     412            0 :         None
     413            0 :     };
     414            0 : 
     415            0 :     let cancellation_token = CancellationToken::new();
     416            0 : 
     417            0 :     let cancel_map = CancelMap::default();
     418            0 : 
     419            0 :     let redis_rps_limit = Vec::leak(args.redis_rps_limit.clone());
     420            0 :     RateBucketInfo::validate(redis_rps_limit)?;
     421            0 : 
     422            0 :     let redis_publisher = match &regional_redis_client {
     423            0 :         Some(redis_publisher) => Some(Arc::new(Mutex::new(RedisPublisherClient::new(
     424            0 :             redis_publisher.clone(),
     425            0 :             args.region.clone(),
     426            0 :             redis_rps_limit,
     427            0 :         )?))),
     428            0 :         None => None,
     429            0 :     };
     430            0 :     let cancellation_handler = Arc::new(CancellationHandler::<
     431            0 :         Option<Arc<tokio::sync::Mutex<RedisPublisherClient>>>,
     432            0 :     >::new(
     433            0 :         cancel_map.clone(),
     434            0 :         redis_publisher,
     435            0 :         proxy::metrics::CancellationSource::FromClient,
     436            0 :     ));
     437            0 : 
     438            0 :     // bit of a hack - find the min rps and max rps supported and turn it into
     439            0 :     // leaky bucket config instead
     440            0 :     let max = args
     441            0 :         .endpoint_rps_limit
     442            0 :         .iter()
     443            0 :         .map(|x| x.rps())
     444            0 :         .max_by(f64::total_cmp)
     445            0 :         .unwrap_or(EndpointRateLimiter::DEFAULT.max);
     446            0 :     let rps = args
     447            0 :         .endpoint_rps_limit
     448            0 :         .iter()
     449            0 :         .map(|x| x.rps())
     450            0 :         .min_by(f64::total_cmp)
     451            0 :         .unwrap_or(EndpointRateLimiter::DEFAULT.rps);
     452            0 :     let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     453            0 :         LeakyBucketConfig { rps, max },
     454            0 :         64,
     455            0 :     ));
     456            0 : 
     457            0 :     // client facing tasks. these will exit on error or on cancellation
     458            0 :     // cancellation returns Ok(())
     459            0 :     let mut client_tasks = JoinSet::new();
     460            0 :     match auth_backend {
     461            0 :         Either::Left(auth_backend) => {
     462            0 :             if let Some(proxy_listener) = proxy_listener {
     463            0 :                 client_tasks.spawn(proxy::proxy::task_main(
     464            0 :                     config,
     465            0 :                     auth_backend,
     466            0 :                     proxy_listener,
     467            0 :                     cancellation_token.clone(),
     468            0 :                     cancellation_handler.clone(),
     469            0 :                     endpoint_rate_limiter.clone(),
     470            0 :                 ));
     471            0 :             }
     472            0 : 
     473            0 :             if let Some(serverless_listener) = serverless_listener {
     474            0 :                 client_tasks.spawn(serverless::task_main(
     475            0 :                     config,
     476            0 :                     auth_backend,
     477            0 :                     serverless_listener,
     478            0 :                     cancellation_token.clone(),
     479            0 :                     cancellation_handler.clone(),
     480            0 :                     endpoint_rate_limiter.clone(),
     481            0 :                 ));
     482            0 :             }
     483            0 :         }
     484            0 :         Either::Right(auth_backend) => {
     485            0 :             if let Some(proxy_listener) = proxy_listener {
     486            0 :                 client_tasks.spawn(proxy::console_redirect_proxy::task_main(
     487            0 :                     config,
     488            0 :                     auth_backend,
     489            0 :                     proxy_listener,
     490            0 :                     cancellation_token.clone(),
     491            0 :                     cancellation_handler.clone(),
     492            0 :                 ));
     493            0 :             }
     494            0 :         }
     495            0 :     }
     496            0 : 
     497            0 :     client_tasks.spawn(proxy::context::parquet::worker(
     498            0 :         cancellation_token.clone(),
     499            0 :         args.parquet_upload,
     500            0 :     ));
     501            0 : 
     502            0 :     // maintenance tasks. these never return unless there's an error
     503            0 :     let mut maintenance_tasks = JoinSet::new();
     504            0 :     maintenance_tasks.spawn(proxy::signals::handle(cancellation_token.clone(), || {}));
     505            0 :     maintenance_tasks.spawn(http::health_server::task_main(
     506            0 :         http_listener,
     507            0 :         AppMetrics {
     508            0 :             jemalloc,
     509            0 :             neon_metrics,
     510            0 :             proxy: proxy::metrics::Metrics::get(),
     511            0 :         },
     512            0 :     ));
     513            0 :     maintenance_tasks.spawn(control_plane::mgmt::task_main(mgmt_listener));
     514            0 : 
     515            0 :     if let Some(metrics_config) = &config.metric_collection {
     516            0 :         // TODO: Add gc regardles of the metric collection being enabled.
     517            0 :         maintenance_tasks.spawn(usage_metrics::task_main(metrics_config));
     518            0 :         client_tasks.spawn(usage_metrics::task_backup(
     519            0 :             &metrics_config.backup_metric_collection_config,
     520            0 :             cancellation_token.clone(),
     521            0 :         ));
     522            0 :     }
     523            0 : 
     524            0 :     if let Either::Left(auth::Backend::ControlPlane(api, _)) = &auth_backend {
     525            0 :         if let proxy::control_plane::client::ControlPlaneClient::Neon(api) = &**api {
     526            0 :             match (redis_notifications_client, regional_redis_client.clone()) {
     527            0 :                 (None, None) => {}
     528            0 :                 (client1, client2) => {
     529            0 :                     let cache = api.caches.project_info.clone();
     530            0 :                     if let Some(client) = client1 {
     531            0 :                         maintenance_tasks.spawn(notifications::task_main(
     532            0 :                             client,
     533            0 :                             cache.clone(),
     534            0 :                             cancel_map.clone(),
     535            0 :                             args.region.clone(),
     536            0 :                         ));
     537            0 :                     }
     538            0 :                     if let Some(client) = client2 {
     539            0 :                         maintenance_tasks.spawn(notifications::task_main(
     540            0 :                             client,
     541            0 :                             cache.clone(),
     542            0 :                             cancel_map.clone(),
     543            0 :                             args.region.clone(),
     544            0 :                         ));
     545            0 :                     }
     546            0 :                     maintenance_tasks.spawn(async move { cache.clone().gc_worker().await });
     547            0 :                 }
     548            0 :             }
     549            0 :             if let Some(regional_redis_client) = regional_redis_client {
     550            0 :                 let cache = api.caches.endpoints_cache.clone();
     551            0 :                 let con = regional_redis_client;
     552            0 :                 let span = tracing::info_span!("endpoints_cache");
     553            0 :                 maintenance_tasks.spawn(
     554            0 :                     async move { cache.do_read(con, cancellation_token.clone()).await }
     555            0 :                         .instrument(span),
     556            0 :                 );
     557            0 :             }
     558            0 :         }
     559            0 :     }
     560            0 : 
     561            0 :     let maintenance = loop {
     562            0 :         // get one complete task
     563            0 :         match futures::future::select(
     564            0 :             pin!(maintenance_tasks.join_next()),
     565            0 :             pin!(client_tasks.join_next()),
     566            0 :         )
     567            0 :         .await
     568            0 :         {
     569            0 :             // exit immediately on maintenance task completion
     570            0 :             Either::Left((Some(res), _)) => break proxy::error::flatten_err(res)?,
     571            0 :             // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
     572            0 :             Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
     573            0 :             // exit immediately on client task error
     574            0 :             Either::Right((Some(res), _)) => proxy::error::flatten_err(res)?,
     575            0 :             // exit if all our client tasks have shutdown gracefully
     576            0 :             Either::Right((None, _)) => return Ok(()),
     577            0 :         }
     578            0 :     };
     579            0 : 
     580            0 :     // maintenance tasks return Infallible success values, this is an impossible value
     581            0 :     // so this match statically ensures that there are no possibilities for that value
     582            0 :     match maintenance {}
     583            0 : }
     584              : 
     585              : /// ProxyConfig is created at proxy startup, and lives forever.
     586            0 : fn build_config(args: &ProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
     587            0 :     let thread_pool = ThreadPool::new(args.scram_thread_pool_size);
     588            0 :     Metrics::install(thread_pool.metrics.clone());
     589              : 
     590            0 :     let tls_config = match (&args.tls_key, &args.tls_cert) {
     591            0 :         (Some(key_path), Some(cert_path)) => Some(config::configure_tls(
     592            0 :             key_path,
     593            0 :             cert_path,
     594            0 :             args.certs_dir.as_ref(),
     595            0 :         )?),
     596            0 :         (None, None) => None,
     597            0 :         _ => bail!("either both or neither tls-key and tls-cert must be specified"),
     598              :     };
     599              : 
     600            0 :     if args.allow_self_signed_compute {
     601            0 :         warn!("allowing self-signed compute certificates");
     602            0 :     }
     603            0 :     let backup_metric_collection_config = config::MetricBackupCollectionConfig {
     604            0 :         interval: args.metric_backup_collection_interval,
     605            0 :         remote_storage_config: args.metric_backup_collection_remote_storage.clone(),
     606            0 :         chunk_size: args.metric_backup_collection_chunk_size,
     607            0 :     };
     608              : 
     609            0 :     let metric_collection = match (
     610            0 :         &args.metric_collection_endpoint,
     611            0 :         &args.metric_collection_interval,
     612              :     ) {
     613            0 :         (Some(endpoint), Some(interval)) => Some(config::MetricCollectionConfig {
     614            0 :             endpoint: endpoint.parse()?,
     615            0 :             interval: humantime::parse_duration(interval)?,
     616            0 :             backup_metric_collection_config,
     617              :         }),
     618            0 :         (None, None) => None,
     619            0 :         _ => bail!(
     620            0 :             "either both or neither metric-collection-endpoint \
     621            0 :              and metric-collection-interval must be specified"
     622            0 :         ),
     623              :     };
     624              : 
     625              :     let config::ConcurrencyLockOptions {
     626            0 :         shards,
     627            0 :         limiter,
     628            0 :         epoch,
     629            0 :         timeout,
     630            0 :     } = args.connect_compute_lock.parse()?;
     631            0 :     info!(
     632              :         ?limiter,
     633              :         shards,
     634              :         ?epoch,
     635            0 :         "Using NodeLocks (connect_compute)"
     636              :     );
     637            0 :     let connect_compute_locks = control_plane::locks::ApiLocks::new(
     638            0 :         "connect_compute_lock",
     639            0 :         limiter,
     640            0 :         shards,
     641            0 :         timeout,
     642            0 :         epoch,
     643            0 :         &Metrics::get().proxy.connect_compute_lock,
     644            0 :     )?;
     645              : 
     646            0 :     let http_config = HttpConfig {
     647            0 :         accept_websockets: !args.is_auth_broker,
     648            0 :         pool_options: GlobalConnPoolOptions {
     649            0 :             max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_conns_per_endpoint,
     650            0 :             gc_epoch: args.sql_over_http.sql_over_http_pool_gc_epoch,
     651            0 :             pool_shards: args.sql_over_http.sql_over_http_pool_shards,
     652            0 :             idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
     653            0 :             opt_in: args.sql_over_http.sql_over_http_pool_opt_in,
     654            0 :             max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
     655            0 :         },
     656            0 :         cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
     657            0 :         client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
     658            0 :         max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
     659            0 :         max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
     660            0 :     };
     661            0 :     let authentication_config = AuthenticationConfig {
     662            0 :         jwks_cache: JwkCache::default(),
     663            0 :         thread_pool,
     664            0 :         scram_protocol_timeout: args.scram_protocol_timeout,
     665            0 :         rate_limiter_enabled: args.auth_rate_limit_enabled,
     666            0 :         rate_limiter: AuthRateLimiter::new(args.auth_rate_limit.clone()),
     667            0 :         rate_limit_ip_subnet: args.auth_rate_limit_ip_subnet,
     668            0 :         ip_allowlist_check_enabled: !args.is_private_access_proxy,
     669            0 :         is_auth_broker: args.is_auth_broker,
     670            0 :         accept_jwts: args.is_auth_broker,
     671            0 :         console_redirect_confirmation_timeout: args.webauth_confirmation_timeout,
     672            0 :     };
     673              : 
     674            0 :     let config = ProxyConfig {
     675            0 :         tls_config,
     676            0 :         metric_collection,
     677            0 :         allow_self_signed_compute: args.allow_self_signed_compute,
     678            0 :         http_config,
     679            0 :         authentication_config,
     680            0 :         proxy_protocol_v2: args.proxy_protocol_v2,
     681            0 :         handshake_timeout: args.handshake_timeout,
     682            0 :         region: args.region.clone(),
     683            0 :         wake_compute_retry_config: config::RetryConfig::parse(&args.wake_compute_retry)?,
     684            0 :         connect_compute_locks,
     685            0 :         connect_to_compute_retry_config: config::RetryConfig::parse(
     686            0 :             &args.connect_to_compute_retry,
     687            0 :         )?,
     688              :     };
     689              : 
     690            0 :     let config = Box::leak(Box::new(config));
     691            0 : 
     692            0 :     tokio::spawn(config.connect_compute_locks.garbage_collect_worker());
     693            0 : 
     694            0 :     Ok(config)
     695            0 : }
     696              : 
     697              : /// auth::Backend is created at proxy startup, and lives forever.
     698            0 : fn build_auth_backend(
     699            0 :     args: &ProxyCliArgs,
     700            0 : ) -> anyhow::Result<Either<&'static auth::Backend<'static, ()>, &'static ConsoleRedirectBackend>> {
     701            0 :     match &args.auth_backend {
     702              :         AuthBackendType::ControlPlane => {
     703            0 :             let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
     704            0 :             let project_info_cache_config: ProjectInfoCacheOptions =
     705            0 :                 args.project_info_cache.parse()?;
     706            0 :             let endpoint_cache_config: config::EndpointCacheConfig =
     707            0 :                 args.endpoint_cache_config.parse()?;
     708              : 
     709            0 :             info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
     710            0 :             info!(
     711            0 :                 "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
     712              :             );
     713            0 :             info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
     714            0 :             let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
     715            0 :                 wake_compute_cache_config,
     716            0 :                 project_info_cache_config,
     717            0 :                 endpoint_cache_config,
     718            0 :             )));
     719              : 
     720              :             let config::ConcurrencyLockOptions {
     721            0 :                 shards,
     722            0 :                 limiter,
     723            0 :                 epoch,
     724            0 :                 timeout,
     725            0 :             } = args.wake_compute_lock.parse()?;
     726            0 :             info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
     727            0 :             let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
     728            0 :                 "wake_compute_lock",
     729            0 :                 limiter,
     730            0 :                 shards,
     731            0 :                 timeout,
     732            0 :                 epoch,
     733            0 :                 &Metrics::get().wake_compute_lock,
     734            0 :             )?));
     735            0 :             tokio::spawn(locks.garbage_collect_worker());
     736              : 
     737            0 :             let url = args.auth_endpoint.parse()?;
     738            0 :             let endpoint = http::Endpoint::new(url, http::new_client());
     739            0 : 
     740            0 :             let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
     741            0 :             RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
     742            0 :             let wake_compute_endpoint_rate_limiter =
     743            0 :                 Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
     744            0 :             let api = control_plane::client::neon::NeonControlPlaneClient::new(
     745            0 :                 endpoint,
     746            0 :                 args.control_plane_token.clone(),
     747            0 :                 caches,
     748            0 :                 locks,
     749            0 :                 wake_compute_endpoint_rate_limiter,
     750            0 :             );
     751            0 :             let api = control_plane::client::ControlPlaneClient::Neon(api);
     752            0 :             let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
     753            0 : 
     754            0 :             let config = Box::leak(Box::new(auth_backend));
     755            0 : 
     756            0 :             Ok(Either::Left(config))
     757              :         }
     758              : 
     759              :         #[cfg(feature = "testing")]
     760              :         AuthBackendType::Postgres => {
     761            0 :             let url = args.auth_endpoint.parse()?;
     762            0 :             let api = control_plane::client::mock::MockControlPlane::new(
     763            0 :                 url,
     764            0 :                 !args.is_private_access_proxy,
     765            0 :             );
     766            0 :             let api = control_plane::client::ControlPlaneClient::PostgresMock(api);
     767            0 : 
     768            0 :             let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
     769            0 : 
     770            0 :             let config = Box::leak(Box::new(auth_backend));
     771            0 : 
     772            0 :             Ok(Either::Left(config))
     773              :         }
     774              : 
     775              :         AuthBackendType::ConsoleRedirect => {
     776            0 :             let url = args.uri.parse()?;
     777            0 :             let backend = ConsoleRedirectBackend::new(url);
     778            0 : 
     779            0 :             let config = Box::leak(Box::new(backend));
     780            0 : 
     781            0 :             Ok(Either::Right(config))
     782              :         }
     783              :     }
     784            0 : }
     785              : 
     786              : #[cfg(test)]
     787              : mod tests {
     788              :     use std::time::Duration;
     789              : 
     790              :     use clap::Parser;
     791              :     use proxy::rate_limiter::RateBucketInfo;
     792              : 
     793              :     #[test]
     794            1 :     fn parse_endpoint_rps_limit() {
     795            1 :         let config = super::ProxyCliArgs::parse_from([
     796            1 :             "proxy",
     797            1 :             "--endpoint-rps-limit",
     798            1 :             "100@1s",
     799            1 :             "--endpoint-rps-limit",
     800            1 :             "20@30s",
     801            1 :         ]);
     802            1 : 
     803            1 :         assert_eq!(
     804            1 :             config.endpoint_rps_limit,
     805            1 :             vec![
     806            1 :                 RateBucketInfo::new(100, Duration::from_secs(1)),
     807            1 :                 RateBucketInfo::new(20, Duration::from_secs(30)),
     808            1 :             ]
     809            1 :         );
     810            1 :     }
     811              : }
        

Generated by: LCOV version 2.1-beta