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

Generated by: LCOV version 2.1-beta