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 : // TODO: refactor these to use labels
292 0 : info!("Version: {GIT_VERSION}");
293 0 : info!("Build_tag: {BUILD_TAG}");
294 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
295 0 : revision: GIT_VERSION,
296 0 : build_tag: BUILD_TAG,
297 0 : });
298 0 :
299 0 : let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
300 0 : Ok(t) => Some(t),
301 0 : Err(e) => {
302 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
303 0 : None
304 0 : }
305 0 : };
306 0 :
307 0 : let args = ProxyCliArgs::parse();
308 0 : let config = build_config(&args)?;
309 0 : let auth_backend = build_auth_backend(&args)?;
310 0 :
311 0 : match auth_backend {
312 0 : Either::Left(auth_backend) => info!("Authentication backend: {auth_backend}"),
313 0 : Either::Right(auth_backend) => info!("Authentication backend: {auth_backend:?}"),
314 0 : };
315 0 : info!("Using region: {}", args.aws_region);
316 0 :
317 0 : let region_provider =
318 0 : RegionProviderChain::default_provider().or_else(Region::new(args.aws_region.clone()));
319 0 : let provider_conf =
320 0 : ProviderConfig::without_region().with_region(region_provider.region().await);
321 0 : let aws_credentials_provider = {
322 0 : // uses "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"
323 0 : CredentialsProviderChain::first_try("env", EnvironmentVariableCredentialsProvider::new())
324 0 : // uses "AWS_PROFILE" / `aws sso login --profile <profile>`
325 0 : .or_else(
326 0 : "profile-sso",
327 0 : ProfileFileCredentialsProvider::builder()
328 0 : .configure(&provider_conf)
329 0 : .build(),
330 0 : )
331 0 : // uses "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME"
332 0 : // needed to access remote extensions bucket
333 0 : .or_else(
334 0 : "token",
335 0 : WebIdentityTokenCredentialsProvider::builder()
336 0 : .configure(&provider_conf)
337 0 : .build(),
338 0 : )
339 0 : // uses imds v2
340 0 : .or_else("imds", ImdsCredentialsProvider::builder().build())
341 0 : };
342 0 : let elasticache_credentials_provider = Arc::new(elasticache::CredentialsProvider::new(
343 0 : elasticache::AWSIRSAConfig::new(
344 0 : args.aws_region.clone(),
345 0 : args.redis_cluster_name,
346 0 : args.redis_user_id,
347 0 : ),
348 0 : aws_credentials_provider,
349 0 : ));
350 0 : let regional_redis_client = match (args.redis_auth_type.as_str(), &args.redis_notifications) {
351 0 : ("plain", redis_url) => match redis_url {
352 0 : None => {
353 0 : bail!("plain auth requires redis_notifications to be set");
354 0 : }
355 0 : Some(url) => Some(
356 0 : ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()),
357 0 : ),
358 0 : },
359 0 : ("irsa", _) => match (&args.redis_host, args.redis_port) {
360 0 : (Some(host), Some(port)) => Some(
361 0 : ConnectionWithCredentialsProvider::new_with_credentials_provider(
362 0 : host.to_string(),
363 0 : port,
364 0 : elasticache_credentials_provider.clone(),
365 0 : ),
366 0 : ),
367 0 : (None, None) => {
368 0 : warn!("irsa auth requires redis-host and redis-port to be set, continuing without regional_redis_client");
369 0 : None
370 0 : }
371 0 : _ => {
372 0 : bail!("redis-host and redis-port must be specified together");
373 0 : }
374 0 : },
375 0 : _ => {
376 0 : bail!("unknown auth type given");
377 0 : }
378 0 : };
379 0 :
380 0 : let redis_notifications_client = if let Some(url) = args.redis_notifications {
381 0 : Some(ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()))
382 0 : } else {
383 0 : regional_redis_client.clone()
384 0 : };
385 0 :
386 0 : // Check that we can bind to address before further initialization
387 0 : let http_address: SocketAddr = args.http.parse()?;
388 0 : info!("Starting http on {http_address}");
389 0 : let http_listener = TcpListener::bind(http_address).await?.into_std()?;
390 0 :
391 0 : let mgmt_address: SocketAddr = args.mgmt.parse()?;
392 0 : info!("Starting mgmt on {mgmt_address}");
393 0 : let mgmt_listener = TcpListener::bind(mgmt_address).await?;
394 0 :
395 0 : let proxy_listener = if !args.is_auth_broker {
396 0 : let proxy_address: SocketAddr = args.proxy.parse()?;
397 0 : info!("Starting proxy on {proxy_address}");
398 0 :
399 0 : Some(TcpListener::bind(proxy_address).await?)
400 0 : } else {
401 0 : None
402 0 : };
403 0 :
404 0 : // TODO: rename the argument to something like serverless.
405 0 : // It now covers more than just websockets, it also covers SQL over HTTP.
406 0 : let serverless_listener = if let Some(serverless_address) = args.wss {
407 0 : let serverless_address: SocketAddr = serverless_address.parse()?;
408 0 : info!("Starting wss on {serverless_address}");
409 0 : Some(TcpListener::bind(serverless_address).await?)
410 0 : } else if args.is_auth_broker {
411 0 : bail!("wss arg must be present for auth-broker")
412 0 : } else {
413 0 : None
414 0 : };
415 0 :
416 0 : let cancellation_token = CancellationToken::new();
417 0 :
418 0 : let cancel_map = CancelMap::default();
419 0 :
420 0 : let redis_rps_limit = Vec::leak(args.redis_rps_limit.clone());
421 0 : RateBucketInfo::validate(redis_rps_limit)?;
422 0 :
423 0 : let redis_publisher = match ®ional_redis_client {
424 0 : Some(redis_publisher) => Some(Arc::new(Mutex::new(RedisPublisherClient::new(
425 0 : redis_publisher.clone(),
426 0 : args.region.clone(),
427 0 : redis_rps_limit,
428 0 : )?))),
429 0 : None => None,
430 0 : };
431 0 : let cancellation_handler = Arc::new(CancellationHandler::<
432 0 : Option<Arc<tokio::sync::Mutex<RedisPublisherClient>>>,
433 0 : >::new(
434 0 : cancel_map.clone(),
435 0 : redis_publisher,
436 0 : proxy::metrics::CancellationSource::FromClient,
437 0 : ));
438 0 :
439 0 : // bit of a hack - find the min rps and max rps supported and turn it into
440 0 : // leaky bucket config instead
441 0 : let max = args
442 0 : .endpoint_rps_limit
443 0 : .iter()
444 0 : .map(|x| x.rps())
445 0 : .max_by(f64::total_cmp)
446 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.max);
447 0 : let rps = args
448 0 : .endpoint_rps_limit
449 0 : .iter()
450 0 : .map(|x| x.rps())
451 0 : .min_by(f64::total_cmp)
452 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.rps);
453 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
454 0 : LeakyBucketConfig { rps, max },
455 0 : 64,
456 0 : ));
457 0 :
458 0 : // client facing tasks. these will exit on error or on cancellation
459 0 : // cancellation returns Ok(())
460 0 : let mut client_tasks = JoinSet::new();
461 0 : match auth_backend {
462 0 : Either::Left(auth_backend) => {
463 0 : if let Some(proxy_listener) = proxy_listener {
464 0 : client_tasks.spawn(proxy::proxy::task_main(
465 0 : config,
466 0 : auth_backend,
467 0 : proxy_listener,
468 0 : cancellation_token.clone(),
469 0 : cancellation_handler.clone(),
470 0 : endpoint_rate_limiter.clone(),
471 0 : ));
472 0 : }
473 0 :
474 0 : if let Some(serverless_listener) = serverless_listener {
475 0 : client_tasks.spawn(serverless::task_main(
476 0 : config,
477 0 : auth_backend,
478 0 : serverless_listener,
479 0 : cancellation_token.clone(),
480 0 : cancellation_handler.clone(),
481 0 : endpoint_rate_limiter.clone(),
482 0 : ));
483 0 : }
484 0 : }
485 0 : Either::Right(auth_backend) => {
486 0 : if let Some(proxy_listener) = proxy_listener {
487 0 : client_tasks.spawn(proxy::console_redirect_proxy::task_main(
488 0 : config,
489 0 : auth_backend,
490 0 : proxy_listener,
491 0 : cancellation_token.clone(),
492 0 : cancellation_handler.clone(),
493 0 : ));
494 0 : }
495 0 : }
496 0 : }
497 0 :
498 0 : client_tasks.spawn(proxy::context::parquet::worker(
499 0 : cancellation_token.clone(),
500 0 : args.parquet_upload,
501 0 : ));
502 0 :
503 0 : // maintenance tasks. these never return unless there's an error
504 0 : let mut maintenance_tasks = JoinSet::new();
505 0 : maintenance_tasks.spawn(proxy::signals::handle(cancellation_token.clone(), || {}));
506 0 : maintenance_tasks.spawn(http::health_server::task_main(
507 0 : http_listener,
508 0 : AppMetrics {
509 0 : jemalloc,
510 0 : neon_metrics,
511 0 : proxy: proxy::metrics::Metrics::get(),
512 0 : },
513 0 : ));
514 0 : maintenance_tasks.spawn(control_plane::mgmt::task_main(mgmt_listener));
515 0 :
516 0 : if let Some(metrics_config) = &config.metric_collection {
517 0 : // TODO: Add gc regardles of the metric collection being enabled.
518 0 : maintenance_tasks.spawn(usage_metrics::task_main(metrics_config));
519 0 : client_tasks.spawn(usage_metrics::task_backup(
520 0 : &metrics_config.backup_metric_collection_config,
521 0 : cancellation_token.clone(),
522 0 : ));
523 0 : }
524 0 :
525 0 : if let Either::Left(auth::Backend::ControlPlane(api, _)) = &auth_backend {
526 0 : if let proxy::control_plane::client::ControlPlaneClient::Neon(api) = &**api {
527 0 : match (redis_notifications_client, regional_redis_client.clone()) {
528 0 : (None, None) => {}
529 0 : (client1, client2) => {
530 0 : let cache = api.caches.project_info.clone();
531 0 : if let Some(client) = client1 {
532 0 : maintenance_tasks.spawn(notifications::task_main(
533 0 : client,
534 0 : cache.clone(),
535 0 : cancel_map.clone(),
536 0 : args.region.clone(),
537 0 : ));
538 0 : }
539 0 : if let Some(client) = client2 {
540 0 : maintenance_tasks.spawn(notifications::task_main(
541 0 : client,
542 0 : cache.clone(),
543 0 : cancel_map.clone(),
544 0 : args.region.clone(),
545 0 : ));
546 0 : }
547 0 : maintenance_tasks.spawn(async move { cache.clone().gc_worker().await });
548 0 : }
549 0 : }
550 0 : if let Some(regional_redis_client) = regional_redis_client {
551 0 : let cache = api.caches.endpoints_cache.clone();
552 0 : let con = regional_redis_client;
553 0 : let span = tracing::info_span!("endpoints_cache");
554 0 : maintenance_tasks.spawn(
555 0 : async move { cache.do_read(con, cancellation_token.clone()).await }
556 0 : .instrument(span),
557 0 : );
558 0 : }
559 0 : }
560 0 : }
561 0 :
562 0 : let maintenance = loop {
563 0 : // get one complete task
564 0 : match futures::future::select(
565 0 : pin!(maintenance_tasks.join_next()),
566 0 : pin!(client_tasks.join_next()),
567 0 : )
568 0 : .await
569 0 : {
570 0 : // exit immediately on maintenance task completion
571 0 : Either::Left((Some(res), _)) => break proxy::error::flatten_err(res)?,
572 0 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
573 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
574 0 : // exit immediately on client task error
575 0 : Either::Right((Some(res), _)) => proxy::error::flatten_err(res)?,
576 0 : // exit if all our client tasks have shutdown gracefully
577 0 : Either::Right((None, _)) => return Ok(()),
578 0 : }
579 0 : };
580 0 :
581 0 : // maintenance tasks return Infallible success values, this is an impossible value
582 0 : // so this match statically ensures that there are no possibilities for that value
583 0 : match maintenance {}
584 0 : }
585 :
586 : /// ProxyConfig is created at proxy startup, and lives forever.
587 0 : fn build_config(args: &ProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
588 0 : let thread_pool = ThreadPool::new(args.scram_thread_pool_size);
589 0 : Metrics::install(thread_pool.metrics.clone());
590 :
591 0 : let tls_config = match (&args.tls_key, &args.tls_cert) {
592 0 : (Some(key_path), Some(cert_path)) => Some(config::configure_tls(
593 0 : key_path,
594 0 : cert_path,
595 0 : args.certs_dir.as_ref(),
596 0 : )?),
597 0 : (None, None) => None,
598 0 : _ => bail!("either both or neither tls-key and tls-cert must be specified"),
599 : };
600 :
601 0 : if args.allow_self_signed_compute {
602 0 : warn!("allowing self-signed compute certificates");
603 0 : }
604 0 : let backup_metric_collection_config = config::MetricBackupCollectionConfig {
605 0 : interval: args.metric_backup_collection_interval,
606 0 : remote_storage_config: args.metric_backup_collection_remote_storage.clone(),
607 0 : chunk_size: args.metric_backup_collection_chunk_size,
608 0 : };
609 :
610 0 : let metric_collection = match (
611 0 : &args.metric_collection_endpoint,
612 0 : &args.metric_collection_interval,
613 : ) {
614 0 : (Some(endpoint), Some(interval)) => Some(config::MetricCollectionConfig {
615 0 : endpoint: endpoint.parse()?,
616 0 : interval: humantime::parse_duration(interval)?,
617 0 : backup_metric_collection_config,
618 : }),
619 0 : (None, None) => None,
620 0 : _ => bail!(
621 0 : "either both or neither metric-collection-endpoint \
622 0 : and metric-collection-interval must be specified"
623 0 : ),
624 : };
625 :
626 : let config::ConcurrencyLockOptions {
627 0 : shards,
628 0 : limiter,
629 0 : epoch,
630 0 : timeout,
631 0 : } = args.connect_compute_lock.parse()?;
632 0 : info!(
633 : ?limiter,
634 : shards,
635 : ?epoch,
636 0 : "Using NodeLocks (connect_compute)"
637 : );
638 0 : let connect_compute_locks = control_plane::locks::ApiLocks::new(
639 0 : "connect_compute_lock",
640 0 : limiter,
641 0 : shards,
642 0 : timeout,
643 0 : epoch,
644 0 : &Metrics::get().proxy.connect_compute_lock,
645 0 : )?;
646 :
647 0 : let http_config = HttpConfig {
648 0 : accept_websockets: !args.is_auth_broker,
649 0 : pool_options: GlobalConnPoolOptions {
650 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_conns_per_endpoint,
651 0 : gc_epoch: args.sql_over_http.sql_over_http_pool_gc_epoch,
652 0 : pool_shards: args.sql_over_http.sql_over_http_pool_shards,
653 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
654 0 : opt_in: args.sql_over_http.sql_over_http_pool_opt_in,
655 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
656 0 : },
657 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
658 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
659 0 : max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
660 0 : max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
661 0 : };
662 0 : let authentication_config = AuthenticationConfig {
663 0 : jwks_cache: JwkCache::default(),
664 0 : thread_pool,
665 0 : scram_protocol_timeout: args.scram_protocol_timeout,
666 0 : rate_limiter_enabled: args.auth_rate_limit_enabled,
667 0 : rate_limiter: AuthRateLimiter::new(args.auth_rate_limit.clone()),
668 0 : rate_limit_ip_subnet: args.auth_rate_limit_ip_subnet,
669 0 : ip_allowlist_check_enabled: !args.is_private_access_proxy,
670 0 : is_auth_broker: args.is_auth_broker,
671 0 : accept_jwts: args.is_auth_broker,
672 0 : console_redirect_confirmation_timeout: args.webauth_confirmation_timeout,
673 0 : };
674 :
675 0 : let config = ProxyConfig {
676 0 : tls_config,
677 0 : metric_collection,
678 0 : allow_self_signed_compute: args.allow_self_signed_compute,
679 0 : http_config,
680 0 : authentication_config,
681 0 : proxy_protocol_v2: args.proxy_protocol_v2,
682 0 : handshake_timeout: args.handshake_timeout,
683 0 : region: args.region.clone(),
684 0 : wake_compute_retry_config: config::RetryConfig::parse(&args.wake_compute_retry)?,
685 0 : connect_compute_locks,
686 0 : connect_to_compute_retry_config: config::RetryConfig::parse(
687 0 : &args.connect_to_compute_retry,
688 0 : )?,
689 : };
690 :
691 0 : let config = Box::leak(Box::new(config));
692 0 :
693 0 : tokio::spawn(config.connect_compute_locks.garbage_collect_worker());
694 0 :
695 0 : Ok(config)
696 0 : }
697 :
698 : /// auth::Backend is created at proxy startup, and lives forever.
699 0 : fn build_auth_backend(
700 0 : args: &ProxyCliArgs,
701 0 : ) -> anyhow::Result<Either<&'static auth::Backend<'static, ()>, &'static ConsoleRedirectBackend>> {
702 0 : match &args.auth_backend {
703 : AuthBackendType::ControlPlane => {
704 0 : let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
705 0 : let project_info_cache_config: ProjectInfoCacheOptions =
706 0 : args.project_info_cache.parse()?;
707 0 : let endpoint_cache_config: config::EndpointCacheConfig =
708 0 : args.endpoint_cache_config.parse()?;
709 :
710 0 : info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
711 0 : info!(
712 0 : "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
713 : );
714 0 : info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
715 0 : let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
716 0 : wake_compute_cache_config,
717 0 : project_info_cache_config,
718 0 : endpoint_cache_config,
719 0 : )));
720 :
721 : let config::ConcurrencyLockOptions {
722 0 : shards,
723 0 : limiter,
724 0 : epoch,
725 0 : timeout,
726 0 : } = args.wake_compute_lock.parse()?;
727 0 : info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
728 0 : let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
729 0 : "wake_compute_lock",
730 0 : limiter,
731 0 : shards,
732 0 : timeout,
733 0 : epoch,
734 0 : &Metrics::get().wake_compute_lock,
735 0 : )?));
736 0 : tokio::spawn(locks.garbage_collect_worker());
737 :
738 0 : let url = args.auth_endpoint.parse()?;
739 0 : let endpoint = http::Endpoint::new(url, http::new_client());
740 0 :
741 0 : let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
742 0 : RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
743 0 : let wake_compute_endpoint_rate_limiter =
744 0 : Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
745 0 : let api = control_plane::client::neon::NeonControlPlaneClient::new(
746 0 : endpoint,
747 0 : args.control_plane_token.clone(),
748 0 : caches,
749 0 : locks,
750 0 : wake_compute_endpoint_rate_limiter,
751 0 : );
752 0 : let api = control_plane::client::ControlPlaneClient::Neon(api);
753 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
754 0 :
755 0 : let config = Box::leak(Box::new(auth_backend));
756 0 :
757 0 : Ok(Either::Left(config))
758 : }
759 :
760 : #[cfg(feature = "testing")]
761 : AuthBackendType::Postgres => {
762 0 : let url = args.auth_endpoint.parse()?;
763 0 : let api = control_plane::client::mock::MockControlPlane::new(
764 0 : url,
765 0 : !args.is_private_access_proxy,
766 0 : );
767 0 : let api = control_plane::client::ControlPlaneClient::PostgresMock(api);
768 0 :
769 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
770 0 :
771 0 : let config = Box::leak(Box::new(auth_backend));
772 0 :
773 0 : Ok(Either::Left(config))
774 : }
775 :
776 : AuthBackendType::ConsoleRedirect => {
777 0 : let url = args.uri.parse()?;
778 0 : let backend = ConsoleRedirectBackend::new(url);
779 0 :
780 0 : let config = Box::leak(Box::new(backend));
781 0 :
782 0 : Ok(Either::Right(config))
783 : }
784 : }
785 0 : }
786 :
787 : #[cfg(test)]
788 : mod tests {
789 : use std::time::Duration;
790 :
791 : use clap::Parser;
792 : use proxy::rate_limiter::RateBucketInfo;
793 :
794 : #[test]
795 1 : fn parse_endpoint_rps_limit() {
796 1 : let config = super::ProxyCliArgs::parse_from([
797 1 : "proxy",
798 1 : "--endpoint-rps-limit",
799 1 : "100@1s",
800 1 : "--endpoint-rps-limit",
801 1 : "20@30s",
802 1 : ]);
803 1 :
804 1 : assert_eq!(
805 1 : config.endpoint_rps_limit,
806 1 : vec![
807 1 : RateBucketInfo::new(100, Duration::from_secs(1)),
808 1 : RateBucketInfo::new(20, Duration::from_secs(30)),
809 1 : ]
810 1 : );
811 1 : }
812 : }
|