LCOV - code coverage report
Current view: top level - proxy/src/bin - local_proxy.rs (source / functions) Coverage Total Hit
Test: 2e3a7638747e564a4f6d1af1cc0c3b3438fbb740.info Lines: 0.0 % 275 0
Test Date: 2024-11-20 01:36:58 Functions: 0.0 % 82 0

            Line data    Source code
       1              : use std::net::SocketAddr;
       2              : use std::pin::pin;
       3              : use std::str::FromStr;
       4              : use std::sync::Arc;
       5              : use std::time::Duration;
       6              : 
       7              : use anyhow::{bail, ensure, Context};
       8              : use camino::{Utf8Path, Utf8PathBuf};
       9              : use compute_api::spec::LocalProxySpec;
      10              : use dashmap::DashMap;
      11              : use futures::future::Either;
      12              : use proxy::auth::backend::jwt::JwkCache;
      13              : use proxy::auth::backend::local::{LocalBackend, JWKS_ROLE_MAP};
      14              : use proxy::auth::{self};
      15              : use proxy::cancellation::CancellationHandlerMain;
      16              : use proxy::config::{self, AuthenticationConfig, HttpConfig, ProxyConfig, RetryConfig};
      17              : use proxy::control_plane::locks::ApiLocks;
      18              : use proxy::control_plane::messages::{EndpointJwksResponse, JwksSettings};
      19              : use proxy::http::health_server::AppMetrics;
      20              : use proxy::intern::RoleNameInt;
      21              : use proxy::metrics::{Metrics, ThreadPoolMetrics};
      22              : use proxy::rate_limiter::{
      23              :     BucketRateLimiter, EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo,
      24              : };
      25              : use proxy::scram::threadpool::ThreadPool;
      26              : use proxy::serverless::cancel_set::CancelSet;
      27              : use proxy::serverless::{self, GlobalConnPoolOptions};
      28              : use proxy::types::RoleName;
      29              : use proxy::url::ApiUrl;
      30              : 
      31              : project_git_version!(GIT_VERSION);
      32              : project_build_tag!(BUILD_TAG);
      33              : 
      34              : use clap::Parser;
      35              : use thiserror::Error;
      36              : use tokio::net::TcpListener;
      37              : use tokio::sync::Notify;
      38              : use tokio::task::JoinSet;
      39              : use tokio_util::sync::CancellationToken;
      40              : use tracing::{debug, error, info, warn};
      41              : use utils::sentry_init::init_sentry;
      42              : use utils::{pid_file, project_build_tag, project_git_version};
      43              : 
      44              : #[global_allocator]
      45              : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
      46              : 
      47              : /// Neon proxy/router
      48            0 : #[derive(Parser)]
      49              : #[command(version = GIT_VERSION, about)]
      50              : struct LocalProxyCliArgs {
      51              :     /// listen for incoming metrics connections on ip:port
      52              :     #[clap(long, default_value = "127.0.0.1:7001")]
      53            0 :     metrics: String,
      54              :     /// listen for incoming http connections on ip:port
      55              :     #[clap(long)]
      56            0 :     http: String,
      57              :     /// timeout for the TLS handshake
      58              :     #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
      59            0 :     handshake_timeout: tokio::time::Duration,
      60              :     /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
      61              :     #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
      62            0 :     connect_compute_lock: String,
      63              :     #[clap(flatten)]
      64              :     sql_over_http: SqlOverHttpArgs,
      65              :     /// User rate limiter max number of requests per second.
      66              :     ///
      67              :     /// Provided in the form `<Requests Per Second>@<Bucket Duration Size>`.
      68              :     /// Can be given multiple times for different bucket sizes.
      69            0 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
      70            0 :     user_rps_limit: Vec<RateBucketInfo>,
      71              :     /// Whether the auth rate limiter actually takes effect (for testing)
      72            0 :     #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
      73            0 :     auth_rate_limit_enabled: bool,
      74              :     /// Authentication rate limiter max number of hashes per second.
      75            0 :     #[clap(long, default_values_t = RateBucketInfo::DEFAULT_AUTH_SET)]
      76            0 :     auth_rate_limit: Vec<RateBucketInfo>,
      77              :     /// The IP subnet to use when considering whether two IP addresses are considered the same.
      78            0 :     #[clap(long, default_value_t = 64)]
      79            0 :     auth_rate_limit_ip_subnet: u8,
      80              :     /// Whether to retry the connection to the compute node
      81              :     #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
      82            0 :     connect_to_compute_retry: String,
      83              :     /// Address of the postgres server
      84              :     #[clap(long, default_value = "127.0.0.1:5432")]
      85            0 :     postgres: SocketAddr,
      86              :     /// Address of the compute-ctl api service
      87              :     #[clap(long, default_value = "http://127.0.0.1:3080/")]
      88            0 :     compute_ctl: ApiUrl,
      89              :     /// Path of the local proxy config file
      90              :     #[clap(long, default_value = "./local_proxy.json")]
      91            0 :     config_path: Utf8PathBuf,
      92              :     /// Path of the local proxy PID file
      93              :     #[clap(long, default_value = "./local_proxy.pid")]
      94            0 :     pid_path: Utf8PathBuf,
      95              : }
      96              : 
      97            0 : #[derive(clap::Args, Clone, Copy, Debug)]
      98              : struct SqlOverHttpArgs {
      99              :     /// How many connections to pool for each endpoint. Excess connections are discarded
     100            0 :     #[clap(long, default_value_t = 200)]
     101            0 :     sql_over_http_pool_max_total_conns: usize,
     102              : 
     103              :     /// How long pooled connections should remain idle for before closing
     104              :     #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
     105            0 :     sql_over_http_idle_timeout: tokio::time::Duration,
     106              : 
     107            0 :     #[clap(long, default_value_t = 100)]
     108            0 :     sql_over_http_client_conn_threshold: u64,
     109              : 
     110            0 :     #[clap(long, default_value_t = 16)]
     111            0 :     sql_over_http_cancel_set_shards: usize,
     112              : 
     113            0 :     #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
     114            0 :     sql_over_http_max_request_size_bytes: u64,
     115              : 
     116            0 :     #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
     117            0 :     sql_over_http_max_response_size_bytes: usize,
     118              : }
     119              : 
     120              : #[tokio::main]
     121            0 : async fn main() -> anyhow::Result<()> {
     122            0 :     let _logging_guard = proxy::logging::init_local_proxy()?;
     123            0 :     let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
     124            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
     125            0 : 
     126            0 :     Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
     127            0 : 
     128            0 :     debug!("Version: {GIT_VERSION}");
     129            0 :     debug!("Build_tag: {BUILD_TAG}");
     130            0 :     let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
     131            0 :         revision: GIT_VERSION,
     132            0 :         build_tag: BUILD_TAG,
     133            0 :     });
     134            0 : 
     135            0 :     let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
     136            0 :         Ok(t) => Some(t),
     137            0 :         Err(e) => {
     138            0 :             tracing::error!(error = ?e, "could not start jemalloc metrics loop");
     139            0 :             None
     140            0 :         }
     141            0 :     };
     142            0 : 
     143            0 :     let args = LocalProxyCliArgs::parse();
     144            0 :     let config = build_config(&args)?;
     145            0 :     let auth_backend = build_auth_backend(&args)?;
     146            0 : 
     147            0 :     // before we bind to any ports, write the process ID to a file
     148            0 :     // so that compute-ctl can find our process later
     149            0 :     // in order to trigger the appropriate SIGHUP on config change.
     150            0 :     //
     151            0 :     // This also claims a "lock" that makes sure only one instance
     152            0 :     // of local_proxy runs at a time.
     153            0 :     let _process_guard = loop {
     154            0 :         match pid_file::claim_for_current_process(&args.pid_path) {
     155            0 :             Ok(guard) => break guard,
     156            0 :             Err(e) => {
     157            0 :                 // compute-ctl might have tried to read the pid-file to let us
     158            0 :                 // know about some config change. We should try again.
     159            0 :                 error!(path=?args.pid_path, "could not claim PID file guard: {e:?}");
     160            0 :                 tokio::time::sleep(Duration::from_secs(1)).await;
     161            0 :             }
     162            0 :         }
     163            0 :     };
     164            0 : 
     165            0 :     let metrics_listener = TcpListener::bind(args.metrics).await?.into_std()?;
     166            0 :     let http_listener = TcpListener::bind(args.http).await?;
     167            0 :     let shutdown = CancellationToken::new();
     168            0 : 
     169            0 :     // todo: should scale with CU
     170            0 :     let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     171            0 :         LeakyBucketConfig {
     172            0 :             rps: 10.0,
     173            0 :             max: 100.0,
     174            0 :         },
     175            0 :         16,
     176            0 :     ));
     177            0 : 
     178            0 :     let mut maintenance_tasks = JoinSet::new();
     179            0 : 
     180            0 :     let refresh_config_notify = Arc::new(Notify::new());
     181            0 :     maintenance_tasks.spawn(proxy::signals::handle(shutdown.clone(), {
     182            0 :         let refresh_config_notify = Arc::clone(&refresh_config_notify);
     183            0 :         move || {
     184            0 :             refresh_config_notify.notify_one();
     185            0 :         }
     186            0 :     }));
     187            0 : 
     188            0 :     // trigger the first config load **after** setting up the signal hook
     189            0 :     // to avoid the race condition where:
     190            0 :     // 1. No config file registered when local_proxy starts up
     191            0 :     // 2. The config file is written but the signal hook is not yet received
     192            0 :     // 3. local_proxy completes startup but has no config loaded, despite there being a registerd config.
     193            0 :     refresh_config_notify.notify_one();
     194            0 :     tokio::spawn(refresh_config_loop(args.config_path, refresh_config_notify));
     195            0 : 
     196            0 :     maintenance_tasks.spawn(proxy::http::health_server::task_main(
     197            0 :         metrics_listener,
     198            0 :         AppMetrics {
     199            0 :             jemalloc,
     200            0 :             neon_metrics,
     201            0 :             proxy: proxy::metrics::Metrics::get(),
     202            0 :         },
     203            0 :     ));
     204            0 : 
     205            0 :     let task = serverless::task_main(
     206            0 :         config,
     207            0 :         auth_backend,
     208            0 :         http_listener,
     209            0 :         shutdown.clone(),
     210            0 :         Arc::new(CancellationHandlerMain::new(
     211            0 :             Arc::new(DashMap::new()),
     212            0 :             None,
     213            0 :             proxy::metrics::CancellationSource::Local,
     214            0 :         )),
     215            0 :         endpoint_rate_limiter,
     216            0 :     );
     217            0 : 
     218            0 :     match futures::future::select(pin!(maintenance_tasks.join_next()), pin!(task)).await {
     219            0 :         // exit immediately on maintenance task completion
     220            0 :         Either::Left((Some(res), _)) => match proxy::error::flatten_err(res)? {},
     221            0 :         // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
     222            0 :         Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
     223            0 :         // exit immediately on client task error
     224            0 :         Either::Right((res, _)) => res?,
     225            0 :     }
     226            0 : 
     227            0 :     Ok(())
     228            0 : }
     229              : 
     230              : /// ProxyConfig is created at proxy startup, and lives forever.
     231            0 : fn build_config(args: &LocalProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
     232              :     let config::ConcurrencyLockOptions {
     233            0 :         shards,
     234            0 :         limiter,
     235            0 :         epoch,
     236            0 :         timeout,
     237            0 :     } = args.connect_compute_lock.parse()?;
     238            0 :     info!(
     239              :         ?limiter,
     240              :         shards,
     241              :         ?epoch,
     242            0 :         "Using NodeLocks (connect_compute)"
     243              :     );
     244            0 :     let connect_compute_locks = ApiLocks::new(
     245            0 :         "connect_compute_lock",
     246            0 :         limiter,
     247            0 :         shards,
     248            0 :         timeout,
     249            0 :         epoch,
     250            0 :         &Metrics::get().proxy.connect_compute_lock,
     251            0 :     )?;
     252              : 
     253            0 :     let http_config = HttpConfig {
     254            0 :         accept_websockets: false,
     255            0 :         pool_options: GlobalConnPoolOptions {
     256            0 :             gc_epoch: Duration::from_secs(60),
     257            0 :             pool_shards: 2,
     258            0 :             idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
     259            0 :             opt_in: false,
     260            0 : 
     261            0 :             max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_total_conns,
     262            0 :             max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
     263            0 :         },
     264            0 :         cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
     265            0 :         client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
     266            0 :         max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
     267            0 :         max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
     268            0 :     };
     269            0 : 
     270            0 :     Ok(Box::leak(Box::new(ProxyConfig {
     271            0 :         tls_config: None,
     272            0 :         metric_collection: None,
     273            0 :         allow_self_signed_compute: false,
     274            0 :         http_config,
     275            0 :         authentication_config: AuthenticationConfig {
     276            0 :             jwks_cache: JwkCache::default(),
     277            0 :             thread_pool: ThreadPool::new(0),
     278            0 :             scram_protocol_timeout: Duration::from_secs(10),
     279            0 :             rate_limiter_enabled: false,
     280            0 :             rate_limiter: BucketRateLimiter::new(vec![]),
     281            0 :             rate_limit_ip_subnet: 64,
     282            0 :             ip_allowlist_check_enabled: true,
     283            0 :             is_auth_broker: false,
     284            0 :             accept_jwts: true,
     285            0 :             console_redirect_confirmation_timeout: Duration::ZERO,
     286            0 :         },
     287            0 :         proxy_protocol_v2: config::ProxyProtocolV2::Rejected,
     288            0 :         handshake_timeout: Duration::from_secs(10),
     289            0 :         region: "local".into(),
     290            0 :         wake_compute_retry_config: RetryConfig::parse(RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)?,
     291            0 :         connect_compute_locks,
     292            0 :         connect_to_compute_retry_config: RetryConfig::parse(
     293            0 :             RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES,
     294            0 :         )?,
     295              :     })))
     296            0 : }
     297              : 
     298              : /// auth::Backend is created at proxy startup, and lives forever.
     299            0 : fn build_auth_backend(
     300            0 :     args: &LocalProxyCliArgs,
     301            0 : ) -> anyhow::Result<&'static auth::Backend<'static, ()>> {
     302            0 :     let auth_backend = proxy::auth::Backend::Local(proxy::auth::backend::MaybeOwned::Owned(
     303            0 :         LocalBackend::new(args.postgres, args.compute_ctl.clone()),
     304            0 :     ));
     305            0 : 
     306            0 :     Ok(Box::leak(Box::new(auth_backend)))
     307            0 : }
     308              : 
     309            0 : #[derive(Error, Debug)]
     310              : enum RefreshConfigError {
     311              :     #[error(transparent)]
     312              :     Read(#[from] std::io::Error),
     313              :     #[error(transparent)]
     314              :     Parse(#[from] serde_json::Error),
     315              :     #[error(transparent)]
     316              :     Validate(anyhow::Error),
     317              : }
     318              : 
     319            0 : async fn refresh_config_loop(path: Utf8PathBuf, rx: Arc<Notify>) {
     320            0 :     let mut init = true;
     321              :     loop {
     322            0 :         rx.notified().await;
     323              : 
     324            0 :         match refresh_config_inner(&path).await {
     325            0 :             Ok(()) => {}
     326              :             // don't log for file not found errors if this is the first time we are checking
     327              :             // for computes that don't use local_proxy, this is not an error.
     328            0 :             Err(RefreshConfigError::Read(e))
     329            0 :                 if init && e.kind() == std::io::ErrorKind::NotFound =>
     330            0 :             {
     331            0 :                 debug!(error=?e, ?path, "could not read config file");
     332              :             }
     333            0 :             Err(e) => {
     334            0 :                 error!(error=?e, ?path, "could not read config file");
     335              :             }
     336              :         }
     337              : 
     338            0 :         init = false;
     339              :     }
     340              : }
     341              : 
     342            0 : async fn refresh_config_inner(path: &Utf8Path) -> Result<(), RefreshConfigError> {
     343            0 :     let bytes = tokio::fs::read(&path).await?;
     344            0 :     let data: LocalProxySpec = serde_json::from_slice(&bytes)?;
     345              : 
     346            0 :     let mut jwks_set = vec![];
     347              : 
     348            0 :     fn parse_jwks_settings(jwks: compute_api::spec::JwksSettings) -> anyhow::Result<JwksSettings> {
     349            0 :         let mut jwks_url = url::Url::from_str(&jwks.jwks_url).context("parsing JWKS url")?;
     350              : 
     351            0 :         ensure!(
     352            0 :             jwks_url.has_authority()
     353            0 :                 && (jwks_url.scheme() == "http" || jwks_url.scheme() == "https"),
     354            0 :             "Invalid JWKS url. Must be HTTP",
     355              :         );
     356              : 
     357            0 :         ensure!(
     358            0 :             jwks_url.host().is_some_and(|h| h != url::Host::Domain("")),
     359            0 :             "Invalid JWKS url. No domain listed",
     360              :         );
     361              : 
     362              :         // clear username, password and ports
     363            0 :         jwks_url
     364            0 :             .set_username("")
     365            0 :             .expect("url can be a base and has a valid host and is not a file. should not error");
     366            0 :         jwks_url
     367            0 :             .set_password(None)
     368            0 :             .expect("url can be a base and has a valid host and is not a file. should not error");
     369            0 :         // local testing is hard if we need to have a specific restricted port
     370            0 :         if cfg!(not(feature = "testing")) {
     371            0 :             jwks_url.set_port(None).expect(
     372            0 :                 "url can be a base and has a valid host and is not a file. should not error",
     373            0 :             );
     374            0 :         }
     375              : 
     376              :         // clear query params
     377            0 :         jwks_url.set_fragment(None);
     378            0 :         jwks_url.query_pairs_mut().clear().finish();
     379            0 : 
     380            0 :         if jwks_url.scheme() != "https" {
     381              :             // local testing is hard if we need to set up https support.
     382            0 :             if cfg!(not(feature = "testing")) {
     383            0 :                 jwks_url
     384            0 :                     .set_scheme("https")
     385            0 :                     .expect("should not error to set the scheme to https if it was http");
     386            0 :             } else {
     387            0 :                 warn!(scheme = jwks_url.scheme(), "JWKS url is not HTTPS");
     388              :             }
     389            0 :         }
     390              : 
     391            0 :         Ok(JwksSettings {
     392            0 :             id: jwks.id,
     393            0 :             jwks_url,
     394            0 :             provider_name: jwks.provider_name,
     395            0 :             jwt_audience: jwks.jwt_audience,
     396            0 :             role_names: jwks
     397            0 :                 .role_names
     398            0 :                 .into_iter()
     399            0 :                 .map(RoleName::from)
     400            0 :                 .map(|s| RoleNameInt::from(&s))
     401            0 :                 .collect(),
     402            0 :         })
     403            0 :     }
     404              : 
     405            0 :     for jwks in data.jwks.into_iter().flatten() {
     406            0 :         jwks_set.push(parse_jwks_settings(jwks).map_err(RefreshConfigError::Validate)?);
     407              :     }
     408              : 
     409            0 :     info!("successfully loaded new config");
     410            0 :     JWKS_ROLE_MAP.store(Some(Arc::new(EndpointJwksResponse { jwks: jwks_set })));
     411            0 : 
     412            0 :     Ok(())
     413            0 : }
        

Generated by: LCOV version 2.1-beta