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