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