Line data Source code
1 : #[cfg(any(test, feature = "testing"))]
2 : use std::env;
3 : use std::net::SocketAddr;
4 : use std::path::PathBuf;
5 : use std::pin::pin;
6 : use std::sync::Arc;
7 : use std::time::Duration;
8 :
9 : #[cfg(any(test, feature = "testing"))]
10 : use anyhow::Context;
11 : use anyhow::{bail, ensure};
12 : use arc_swap::ArcSwapOption;
13 : use futures::future::Either;
14 : use remote_storage::RemoteStorageConfig;
15 : use tokio::net::TcpListener;
16 : use tokio::task::JoinSet;
17 : use tokio_util::sync::CancellationToken;
18 : use tracing::{Instrument, info, warn};
19 : use utils::sentry_init::init_sentry;
20 : use utils::{project_build_tag, project_git_version};
21 :
22 : use crate::auth::backend::jwt::JwkCache;
23 : use crate::auth::backend::{AuthRateLimiter, ConsoleRedirectBackend, MaybeOwned};
24 : use crate::cancellation::{CancellationHandler, handle_cancel_messages};
25 : use crate::config::{
26 : self, AuthenticationConfig, CacheOptions, ComputeConfig, HttpConfig, ProjectInfoCacheOptions,
27 : ProxyConfig, ProxyProtocolV2, remote_storage_from_toml,
28 : };
29 : use crate::context::parquet::ParquetUploadArgs;
30 : use crate::http::health_server::AppMetrics;
31 : use crate::metrics::Metrics;
32 : use crate::rate_limiter::{
33 : EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo, WakeComputeRateLimiter,
34 : };
35 : use crate::redis::connection_with_credentials_provider::ConnectionWithCredentialsProvider;
36 : use crate::redis::kv_ops::RedisKVClient;
37 : use crate::redis::{elasticache, notifications};
38 : use crate::scram::threadpool::ThreadPool;
39 : use crate::serverless::GlobalConnPoolOptions;
40 : use crate::serverless::cancel_set::CancelSet;
41 : use crate::tls::client_config::compute_client_config_with_root_certs;
42 : #[cfg(any(test, feature = "testing"))]
43 : use crate::url::ApiUrl;
44 : use crate::{auth, control_plane, http, serverless, usage_metrics};
45 :
46 : project_git_version!(GIT_VERSION);
47 : project_build_tag!(BUILD_TAG);
48 :
49 : use clap::{Parser, ValueEnum};
50 :
51 : #[derive(Clone, Debug, ValueEnum)]
52 : #[clap(rename_all = "kebab-case")]
53 : enum AuthBackendType {
54 : #[clap(alias("cplane-v1"))]
55 : ControlPlane,
56 :
57 : #[clap(alias("link"))]
58 : ConsoleRedirect,
59 :
60 : #[cfg(any(test, feature = "testing"))]
61 : Postgres,
62 : }
63 :
64 : /// Neon proxy/router
65 : #[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: SocketAddr,
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: SocketAddr,
79 : /// listen for incoming http connections (metrics, etc) on ip:port
80 : #[clap(long, default_value = "127.0.0.1:7001")]
81 0 : http: SocketAddr,
82 : /// listen for incoming wss connections on ip:port
83 : #[clap(long)]
84 : wss: Option<SocketAddr>,
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<PathBuf>,
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<PathBuf>,
116 : /// Allow writing TLS session keys to the given file pointed to by the environment variable `SSLKEYLOGFILE`.
117 : #[clap(long, alias = "allow-ssl-keylogfile")]
118 0 : allow_tls_keylogfile: bool,
119 : /// path to directory with TLS certificates for client postgres connections
120 : #[clap(long)]
121 : certs_dir: Option<PathBuf>,
122 : /// timeout for the TLS handshake
123 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
124 0 : handshake_timeout: tokio::time::Duration,
125 : /// http endpoint to receive periodic metric updates
126 : #[clap(long)]
127 : metric_collection_endpoint: Option<String>,
128 : /// how often metrics should be sent to a collection endpoint
129 : #[clap(long)]
130 : metric_collection_interval: Option<String>,
131 : /// cache for `wake_compute` api method (use `size=0` to disable)
132 : #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
133 0 : wake_compute_cache: String,
134 : /// lock for `wake_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_WAKE_COMPUTE_LOCK)]
136 0 : wake_compute_lock: String,
137 : /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
138 : #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
139 0 : connect_compute_lock: String,
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 4 : #[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 4 : #[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 4 : #[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 3 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_REDIS_SET)]
168 1 : redis_rps_limit: Vec<RateBucketInfo>,
169 : /// Cancellation channel size (max queue size for redis kv client)
170 1 : #[clap(long, default_value_t = 1024)]
171 0 : cancellation_ch_size: usize,
172 : /// Cancellation ops batch size for redis
173 1 : #[clap(long, default_value_t = 8)]
174 0 : cancellation_batch_size: usize,
175 : /// cache for `allowed_ips` (use `size=0` to disable)
176 : #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
177 0 : allowed_ips_cache: String,
178 : /// cache for `role_secret` (use `size=0` to disable)
179 : #[clap(long, default_value = config::CacheOptions::CACHE_DEFAULT_OPTIONS)]
180 0 : role_secret_cache: String,
181 : /// redis url for notifications (if empty, redis_host:port will be used for both notifications and streaming connections)
182 : #[clap(long)]
183 : redis_notifications: Option<String>,
184 : /// what from the available authentications type to use for the regional redis we have. Supported are "irsa" and "plain".
185 : #[clap(long, default_value = "irsa")]
186 0 : redis_auth_type: String,
187 : /// redis host for streaming connections (might be different from the notifications host)
188 : #[clap(long)]
189 : redis_host: Option<String>,
190 : /// redis port for streaming connections (might be different from the notifications host)
191 : #[clap(long)]
192 : redis_port: Option<u16>,
193 : /// redis cluster name, used in aws elasticache
194 : #[clap(long)]
195 : redis_cluster_name: Option<String>,
196 : /// redis user_id, used in aws elasticache
197 : #[clap(long)]
198 : redis_user_id: Option<String>,
199 : /// aws region to retrieve credentials
200 1 : #[clap(long, default_value_t = String::new())]
201 0 : aws_region: String,
202 : /// cache for `project_info` (use `size=0` to disable)
203 : #[clap(long, default_value = config::ProjectInfoCacheOptions::CACHE_DEFAULT_OPTIONS)]
204 0 : project_info_cache: String,
205 : /// cache for all valid endpoints
206 : #[clap(long, default_value = config::EndpointCacheConfig::CACHE_DEFAULT_OPTIONS)]
207 0 : endpoint_cache_config: String,
208 : #[clap(flatten)]
209 : parquet_upload: ParquetUploadArgs,
210 :
211 : /// interval for backup metric collection
212 : #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
213 0 : metric_backup_collection_interval: std::time::Duration,
214 : /// remote storage configuration for backup metric collection
215 : /// Encoded as toml (same format as pageservers), eg
216 : /// `{bucket_name='the-bucket',bucket_region='us-east-1',prefix_in_bucket='proxy',endpoint='http://minio:9000'}`
217 : #[clap(long, value_parser = remote_storage_from_toml)]
218 : metric_backup_collection_remote_storage: Option<RemoteStorageConfig>,
219 : /// chunk size for backup metric collection
220 : /// Size of each event is no more than 400 bytes, so 2**22 is about 200MB before the compression.
221 : #[clap(long, default_value = "4194304")]
222 0 : metric_backup_collection_chunk_size: usize,
223 : /// Whether to retry the connection to the compute node
224 : #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
225 0 : connect_to_compute_retry: String,
226 : /// Whether to retry the wake_compute request
227 : #[clap(long, default_value = config::RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)]
228 0 : wake_compute_retry: String,
229 :
230 : /// Configure if this is a private access proxy for the POC: In that case the proxy will ignore the IP allowlist
231 1 : #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
232 0 : is_private_access_proxy: bool,
233 :
234 : /// Configure whether all incoming requests have a Proxy Protocol V2 packet.
235 : // TODO(conradludgate): switch default to rejected or required once we've updated all deployments
236 1 : #[clap(value_enum, long, default_value_t = ProxyProtocolV2::Supported)]
237 0 : proxy_protocol_v2: ProxyProtocolV2,
238 :
239 : /// Time the proxy waits for the webauth session to be confirmed by the control plane.
240 : // TODO: rename to `console_redirect_confirmation_timeout`.
241 : #[clap(long, default_value = "2m", value_parser = humantime::parse_duration)]
242 0 : webauth_confirmation_timeout: std::time::Duration,
243 :
244 : #[clap(flatten)]
245 : pg_sni_router: PgSniRouterArgs,
246 : }
247 :
248 : #[derive(clap::Args, Clone, Copy, Debug)]
249 : struct SqlOverHttpArgs {
250 : /// timeout for http connection requests
251 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
252 0 : sql_over_http_timeout: tokio::time::Duration,
253 :
254 : /// Whether the SQL over http pool is opt-in
255 1 : #[clap(long, default_value_t = true, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
256 0 : sql_over_http_pool_opt_in: bool,
257 :
258 : /// How many connections to pool for each endpoint. Excess connections are discarded
259 1 : #[clap(long, default_value_t = 20)]
260 0 : sql_over_http_pool_max_conns_per_endpoint: usize,
261 :
262 : /// How many connections to pool for each endpoint. Excess connections are discarded
263 1 : #[clap(long, default_value_t = 20000)]
264 0 : sql_over_http_pool_max_total_conns: usize,
265 :
266 : /// How long pooled connections should remain idle for before closing
267 : #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
268 0 : sql_over_http_idle_timeout: tokio::time::Duration,
269 :
270 : /// Duration each shard will wait on average before a GC sweep.
271 : /// A longer time will causes sweeps to take longer but will interfere less frequently.
272 : #[clap(long, default_value = "10m", value_parser = humantime::parse_duration)]
273 0 : sql_over_http_pool_gc_epoch: tokio::time::Duration,
274 :
275 : /// How many shards should the global pool have. Must be a power of two.
276 : /// More shards will introduce less contention for pool operations, but can
277 : /// increase memory used by the pool
278 1 : #[clap(long, default_value_t = 128)]
279 0 : sql_over_http_pool_shards: usize,
280 :
281 1 : #[clap(long, default_value_t = 10000)]
282 0 : sql_over_http_client_conn_threshold: u64,
283 :
284 1 : #[clap(long, default_value_t = 64)]
285 0 : sql_over_http_cancel_set_shards: usize,
286 :
287 1 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
288 0 : sql_over_http_max_request_size_bytes: usize,
289 :
290 1 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
291 0 : sql_over_http_max_response_size_bytes: usize,
292 : }
293 :
294 : #[derive(clap::Args, Clone, Debug)]
295 : struct PgSniRouterArgs {
296 : /// listen for incoming client connections on ip:port
297 : #[clap(id = "sni-router-listen", long, default_value = "127.0.0.1:4432")]
298 0 : listen: SocketAddr,
299 : /// listen for incoming client connections on ip:port, requiring TLS to compute
300 : #[clap(id = "sni-router-listen-tls", long, default_value = "127.0.0.1:4433")]
301 0 : listen_tls: SocketAddr,
302 : /// path to TLS key for client postgres connections
303 : #[clap(id = "sni-router-tls-key", long)]
304 : tls_key: Option<PathBuf>,
305 : /// path to TLS cert for client postgres connections
306 : #[clap(id = "sni-router-tls-cert", long)]
307 : tls_cert: Option<PathBuf>,
308 : /// append this domain zone to the SNI hostname to get the destination address
309 : #[clap(id = "sni-router-destination", long)]
310 : dest: Option<String>,
311 : }
312 :
313 0 : pub async fn run() -> anyhow::Result<()> {
314 0 : let _logging_guard = crate::logging::init().await?;
315 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
316 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
317 0 :
318 0 : // TODO: refactor these to use labels
319 0 : info!("Version: {GIT_VERSION}");
320 0 : info!("Build_tag: {BUILD_TAG}");
321 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
322 0 : revision: GIT_VERSION,
323 0 : build_tag: BUILD_TAG,
324 0 : });
325 :
326 0 : let jemalloc = match crate::jemalloc::MetricRecorder::new() {
327 0 : Ok(t) => Some(t),
328 0 : Err(e) => {
329 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
330 0 : None
331 : }
332 : };
333 :
334 0 : let args = ProxyCliArgs::parse();
335 0 : let config = build_config(&args)?;
336 0 : let auth_backend = build_auth_backend(&args)?;
337 :
338 0 : match auth_backend {
339 0 : Either::Left(auth_backend) => info!("Authentication backend: {auth_backend}"),
340 0 : Either::Right(auth_backend) => info!("Authentication backend: {auth_backend:?}"),
341 : }
342 0 : info!("Using region: {}", args.aws_region);
343 0 : let (regional_redis_client, redis_notifications_client) = configure_redis(&args).await?;
344 :
345 : // Check that we can bind to address before further initialization
346 0 : info!("Starting http on {}", args.http);
347 0 : let http_listener = TcpListener::bind(args.http).await?.into_std()?;
348 :
349 0 : info!("Starting mgmt on {}", args.mgmt);
350 0 : let mgmt_listener = TcpListener::bind(args.mgmt).await?;
351 :
352 0 : let proxy_listener = if args.is_auth_broker {
353 0 : None
354 : } else {
355 0 : info!("Starting proxy on {}", args.proxy);
356 0 : Some(TcpListener::bind(args.proxy).await?)
357 : };
358 :
359 0 : let sni_router_listeners = {
360 0 : let args = &args.pg_sni_router;
361 0 : if args.dest.is_some() {
362 0 : ensure!(
363 0 : args.tls_key.is_some(),
364 0 : "sni-router-tls-key must be provided"
365 : );
366 0 : ensure!(
367 0 : args.tls_cert.is_some(),
368 0 : "sni-router-tls-cert must be provided"
369 : );
370 :
371 0 : info!(
372 0 : "Starting pg-sni-router on {} and {}",
373 : args.listen, args.listen_tls
374 : );
375 :
376 : Some((
377 0 : TcpListener::bind(args.listen).await?,
378 0 : TcpListener::bind(args.listen_tls).await?,
379 : ))
380 : } else {
381 0 : None
382 : }
383 : };
384 :
385 : // TODO: rename the argument to something like serverless.
386 : // It now covers more than just websockets, it also covers SQL over HTTP.
387 0 : let serverless_listener = if let Some(serverless_address) = args.wss {
388 0 : info!("Starting wss on {serverless_address}");
389 0 : Some(TcpListener::bind(serverless_address).await?)
390 0 : } else if args.is_auth_broker {
391 0 : bail!("wss arg must be present for auth-broker")
392 : } else {
393 0 : None
394 : };
395 :
396 0 : let cancellation_token = CancellationToken::new();
397 0 :
398 0 : let redis_rps_limit = Vec::leak(args.redis_rps_limit.clone());
399 0 : RateBucketInfo::validate(redis_rps_limit)?;
400 :
401 0 : let redis_kv_client = regional_redis_client
402 0 : .as_ref()
403 0 : .map(|redis_publisher| RedisKVClient::new(redis_publisher.clone(), redis_rps_limit));
404 0 :
405 0 : // channel size should be higher than redis client limit to avoid blocking
406 0 : let cancel_ch_size = args.cancellation_ch_size;
407 0 : let (tx_cancel, rx_cancel) = tokio::sync::mpsc::channel(cancel_ch_size);
408 0 : let cancellation_handler = Arc::new(CancellationHandler::new(
409 0 : &config.connect_to_compute,
410 0 : Some(tx_cancel),
411 0 : ));
412 0 :
413 0 : // bit of a hack - find the min rps and max rps supported and turn it into
414 0 : // leaky bucket config instead
415 0 : let max = args
416 0 : .endpoint_rps_limit
417 0 : .iter()
418 0 : .map(|x| x.rps())
419 0 : .max_by(f64::total_cmp)
420 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.max);
421 0 : let rps = args
422 0 : .endpoint_rps_limit
423 0 : .iter()
424 0 : .map(|x| x.rps())
425 0 : .min_by(f64::total_cmp)
426 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.rps);
427 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
428 0 : LeakyBucketConfig { rps, max },
429 0 : 64,
430 0 : ));
431 0 :
432 0 : // client facing tasks. these will exit on error or on cancellation
433 0 : // cancellation returns Ok(())
434 0 : let mut client_tasks = JoinSet::new();
435 0 : match auth_backend {
436 0 : Either::Left(auth_backend) => {
437 0 : if let Some(proxy_listener) = proxy_listener {
438 0 : client_tasks.spawn(crate::proxy::task_main(
439 0 : config,
440 0 : auth_backend,
441 0 : proxy_listener,
442 0 : cancellation_token.clone(),
443 0 : cancellation_handler.clone(),
444 0 : endpoint_rate_limiter.clone(),
445 0 : ));
446 0 : }
447 :
448 0 : if let Some(serverless_listener) = serverless_listener {
449 0 : client_tasks.spawn(serverless::task_main(
450 0 : config,
451 0 : auth_backend,
452 0 : serverless_listener,
453 0 : cancellation_token.clone(),
454 0 : cancellation_handler.clone(),
455 0 : endpoint_rate_limiter.clone(),
456 0 : ));
457 0 : }
458 : }
459 0 : Either::Right(auth_backend) => {
460 0 : if let Some(proxy_listener) = proxy_listener {
461 0 : client_tasks.spawn(crate::console_redirect_proxy::task_main(
462 0 : config,
463 0 : auth_backend,
464 0 : proxy_listener,
465 0 : cancellation_token.clone(),
466 0 : cancellation_handler.clone(),
467 0 : ));
468 0 : }
469 : }
470 : }
471 :
472 : // spawn pg-sni-router mode.
473 0 : if let Some((listen, listen_tls)) = sni_router_listeners {
474 0 : let args = args.pg_sni_router;
475 0 : let dest = args.dest.expect("already asserted it is set");
476 0 : let key_path = args.tls_key.expect("already asserted it is set");
477 0 : let cert_path = args.tls_cert.expect("already asserted it is set");
478 :
479 0 : let (tls_config, tls_server_end_point) =
480 0 : super::pg_sni_router::parse_tls(&key_path, &cert_path)?;
481 :
482 0 : let dest = Arc::new(dest);
483 0 :
484 0 : client_tasks.spawn(super::pg_sni_router::task_main(
485 0 : dest.clone(),
486 0 : tls_config.clone(),
487 0 : None,
488 0 : tls_server_end_point,
489 0 : listen,
490 0 : cancellation_token.clone(),
491 0 : ));
492 0 :
493 0 : client_tasks.spawn(super::pg_sni_router::task_main(
494 0 : dest,
495 0 : tls_config,
496 0 : Some(config.connect_to_compute.tls.clone()),
497 0 : tls_server_end_point,
498 0 : listen_tls,
499 0 : cancellation_token.clone(),
500 0 : ));
501 0 : }
502 :
503 0 : client_tasks.spawn(crate::context::parquet::worker(
504 0 : cancellation_token.clone(),
505 0 : args.parquet_upload,
506 0 : ));
507 0 :
508 0 : // maintenance tasks. these never return unless there's an error
509 0 : let mut maintenance_tasks = JoinSet::new();
510 0 : maintenance_tasks.spawn(crate::signals::handle(cancellation_token.clone(), || {}));
511 0 : maintenance_tasks.spawn(http::health_server::task_main(
512 0 : http_listener,
513 0 : AppMetrics {
514 0 : jemalloc,
515 0 : neon_metrics,
516 0 : proxy: crate::metrics::Metrics::get(),
517 0 : },
518 0 : ));
519 0 : maintenance_tasks.spawn(control_plane::mgmt::task_main(mgmt_listener));
520 :
521 0 : if let Some(metrics_config) = &config.metric_collection {
522 0 : // TODO: Add gc regardles of the metric collection being enabled.
523 0 : maintenance_tasks.spawn(usage_metrics::task_main(metrics_config));
524 0 : }
525 :
526 : #[cfg_attr(not(any(test, feature = "testing")), expect(irrefutable_let_patterns))]
527 0 : if let Either::Left(auth::Backend::ControlPlane(api, ())) = &auth_backend {
528 0 : if let crate::control_plane::client::ControlPlaneClient::ProxyV1(api) = &**api {
529 0 : match (redis_notifications_client, regional_redis_client.clone()) {
530 0 : (None, None) => {}
531 0 : (client1, client2) => {
532 0 : let cache = api.caches.project_info.clone();
533 0 : if let Some(client) = client1 {
534 0 : maintenance_tasks.spawn(notifications::task_main(
535 0 : client,
536 0 : cache.clone(),
537 0 : args.region.clone(),
538 0 : ));
539 0 : }
540 0 : if let Some(client) = client2 {
541 0 : maintenance_tasks.spawn(notifications::task_main(
542 0 : client,
543 0 : cache.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 : }
550 :
551 0 : if let Some(mut redis_kv_client) = redis_kv_client {
552 0 : maintenance_tasks.spawn(async move {
553 0 : redis_kv_client.try_connect().await?;
554 0 : handle_cancel_messages(
555 0 : &mut redis_kv_client,
556 0 : rx_cancel,
557 0 : args.cancellation_batch_size,
558 0 : )
559 0 : .await?;
560 :
561 0 : drop(redis_kv_client);
562 0 :
563 0 : // `handle_cancel_messages` was terminated due to the tx_cancel
564 0 : // being dropped. this is not worthy of an error, and this task can only return `Err`,
565 0 : // so let's wait forever instead.
566 0 : std::future::pending().await
567 0 : });
568 0 : }
569 :
570 0 : if let Some(regional_redis_client) = regional_redis_client {
571 0 : let cache = api.caches.endpoints_cache.clone();
572 0 : let con = regional_redis_client;
573 0 : let span = tracing::info_span!("endpoints_cache");
574 0 : maintenance_tasks.spawn(
575 0 : async move { cache.do_read(con, cancellation_token.clone()).await }
576 0 : .instrument(span),
577 0 : );
578 0 : }
579 0 : }
580 0 : }
581 :
582 : let maintenance = loop {
583 : // get one complete task
584 0 : match futures::future::select(
585 0 : pin!(maintenance_tasks.join_next()),
586 0 : pin!(client_tasks.join_next()),
587 0 : )
588 0 : .await
589 : {
590 : // exit immediately on maintenance task completion
591 0 : Either::Left((Some(res), _)) => break crate::error::flatten_err(res)?,
592 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
593 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
594 : // exit immediately on client task error
595 0 : Either::Right((Some(res), _)) => crate::error::flatten_err(res)?,
596 : // exit if all our client tasks have shutdown gracefully
597 0 : Either::Right((None, _)) => return Ok(()),
598 : }
599 : };
600 :
601 : // maintenance tasks return Infallible success values, this is an impossible value
602 : // so this match statically ensures that there are no possibilities for that value
603 : match maintenance {}
604 0 : }
605 :
606 : /// ProxyConfig is created at proxy startup, and lives forever.
607 0 : fn build_config(args: &ProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
608 0 : let thread_pool = ThreadPool::new(args.scram_thread_pool_size);
609 0 : Metrics::install(thread_pool.metrics.clone());
610 :
611 0 : let tls_config = match (&args.tls_key, &args.tls_cert) {
612 0 : (Some(key_path), Some(cert_path)) => Some(config::configure_tls(
613 0 : key_path,
614 0 : cert_path,
615 0 : args.certs_dir.as_deref(),
616 0 : args.allow_tls_keylogfile,
617 0 : )?),
618 0 : (None, None) => None,
619 0 : _ => bail!("either both or neither tls-key and tls-cert must be specified"),
620 : };
621 0 : let tls_config = ArcSwapOption::from(tls_config.map(Arc::new));
622 0 :
623 0 : let backup_metric_collection_config = config::MetricBackupCollectionConfig {
624 0 : remote_storage_config: args.metric_backup_collection_remote_storage.clone(),
625 0 : chunk_size: args.metric_backup_collection_chunk_size,
626 0 : };
627 :
628 0 : let metric_collection = match (
629 0 : &args.metric_collection_endpoint,
630 0 : &args.metric_collection_interval,
631 : ) {
632 0 : (Some(endpoint), Some(interval)) => Some(config::MetricCollectionConfig {
633 0 : endpoint: endpoint.parse()?,
634 0 : interval: humantime::parse_duration(interval)?,
635 0 : backup_metric_collection_config,
636 : }),
637 0 : (None, None) => None,
638 0 : _ => bail!(
639 0 : "either both or neither metric-collection-endpoint \
640 0 : and metric-collection-interval must be specified"
641 0 : ),
642 : };
643 :
644 : let config::ConcurrencyLockOptions {
645 0 : shards,
646 0 : limiter,
647 0 : epoch,
648 0 : timeout,
649 0 : } = args.connect_compute_lock.parse()?;
650 0 : info!(
651 : ?limiter,
652 : shards,
653 : ?epoch,
654 0 : "Using NodeLocks (connect_compute)"
655 : );
656 0 : let connect_compute_locks = control_plane::locks::ApiLocks::new(
657 0 : "connect_compute_lock",
658 0 : limiter,
659 0 : shards,
660 0 : timeout,
661 0 : epoch,
662 0 : &Metrics::get().proxy.connect_compute_lock,
663 0 : );
664 0 :
665 0 : let http_config = HttpConfig {
666 0 : accept_websockets: !args.is_auth_broker,
667 0 : pool_options: GlobalConnPoolOptions {
668 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_conns_per_endpoint,
669 0 : gc_epoch: args.sql_over_http.sql_over_http_pool_gc_epoch,
670 0 : pool_shards: args.sql_over_http.sql_over_http_pool_shards,
671 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
672 0 : opt_in: args.sql_over_http.sql_over_http_pool_opt_in,
673 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
674 0 : },
675 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
676 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
677 0 : max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
678 0 : max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
679 0 : };
680 0 : let authentication_config = AuthenticationConfig {
681 0 : jwks_cache: JwkCache::default(),
682 0 : thread_pool,
683 0 : scram_protocol_timeout: args.scram_protocol_timeout,
684 0 : rate_limiter_enabled: args.auth_rate_limit_enabled,
685 0 : rate_limiter: AuthRateLimiter::new(args.auth_rate_limit.clone()),
686 0 : rate_limit_ip_subnet: args.auth_rate_limit_ip_subnet,
687 0 : ip_allowlist_check_enabled: !args.is_private_access_proxy,
688 0 : is_vpc_acccess_proxy: args.is_private_access_proxy,
689 0 : is_auth_broker: args.is_auth_broker,
690 0 : accept_jwts: args.is_auth_broker,
691 0 : console_redirect_confirmation_timeout: args.webauth_confirmation_timeout,
692 0 : };
693 :
694 0 : let compute_config = ComputeConfig {
695 0 : retry: config::RetryConfig::parse(&args.connect_to_compute_retry)?,
696 0 : tls: Arc::new(compute_client_config_with_root_certs()?),
697 0 : timeout: Duration::from_secs(2),
698 : };
699 :
700 0 : let config = ProxyConfig {
701 0 : tls_config,
702 0 : metric_collection,
703 0 : http_config,
704 0 : authentication_config,
705 0 : proxy_protocol_v2: args.proxy_protocol_v2,
706 0 : handshake_timeout: args.handshake_timeout,
707 0 : region: args.region.clone(),
708 0 : wake_compute_retry_config: config::RetryConfig::parse(&args.wake_compute_retry)?,
709 0 : connect_compute_locks,
710 0 : connect_to_compute: compute_config,
711 0 : };
712 0 :
713 0 : let config = Box::leak(Box::new(config));
714 0 :
715 0 : tokio::spawn(config.connect_compute_locks.garbage_collect_worker());
716 0 :
717 0 : Ok(config)
718 0 : }
719 :
720 : /// auth::Backend is created at proxy startup, and lives forever.
721 0 : fn build_auth_backend(
722 0 : args: &ProxyCliArgs,
723 0 : ) -> anyhow::Result<Either<&'static auth::Backend<'static, ()>, &'static ConsoleRedirectBackend>> {
724 0 : match &args.auth_backend {
725 : AuthBackendType::ControlPlane => {
726 0 : let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
727 0 : let project_info_cache_config: ProjectInfoCacheOptions =
728 0 : args.project_info_cache.parse()?;
729 0 : let endpoint_cache_config: config::EndpointCacheConfig =
730 0 : args.endpoint_cache_config.parse()?;
731 :
732 0 : info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
733 0 : info!(
734 0 : "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
735 : );
736 0 : info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
737 0 : let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
738 0 : wake_compute_cache_config,
739 0 : project_info_cache_config,
740 0 : endpoint_cache_config,
741 0 : )));
742 :
743 : let config::ConcurrencyLockOptions {
744 0 : shards,
745 0 : limiter,
746 0 : epoch,
747 0 : timeout,
748 0 : } = args.wake_compute_lock.parse()?;
749 0 : info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
750 0 : let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
751 0 : "wake_compute_lock",
752 0 : limiter,
753 0 : shards,
754 0 : timeout,
755 0 : epoch,
756 0 : &Metrics::get().wake_compute_lock,
757 0 : )));
758 0 : tokio::spawn(locks.garbage_collect_worker());
759 :
760 0 : let url: crate::url::ApiUrl = args.auth_endpoint.parse()?;
761 :
762 0 : let endpoint = http::Endpoint::new(url, http::new_client());
763 0 :
764 0 : let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
765 0 : RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
766 0 : let wake_compute_endpoint_rate_limiter =
767 0 : Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
768 0 :
769 0 : let api = control_plane::client::cplane_proxy_v1::NeonControlPlaneClient::new(
770 0 : endpoint,
771 0 : args.control_plane_token.clone(),
772 0 : caches,
773 0 : locks,
774 0 : wake_compute_endpoint_rate_limiter,
775 0 : );
776 0 :
777 0 : let api = control_plane::client::ControlPlaneClient::ProxyV1(api);
778 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
779 0 : let config = Box::leak(Box::new(auth_backend));
780 0 :
781 0 : Ok(Either::Left(config))
782 : }
783 :
784 : #[cfg(any(test, feature = "testing"))]
785 : AuthBackendType::Postgres => {
786 0 : let mut url: ApiUrl = args.auth_endpoint.parse()?;
787 0 : if url.password().is_none() {
788 0 : let password = env::var("PGPASSWORD")
789 0 : .with_context(|| "auth-endpoint does not contain a password and environment variable `PGPASSWORD` is not set")?;
790 0 : url.set_password(Some(&password))
791 0 : .expect("Failed to set password");
792 0 : }
793 0 : let api = control_plane::client::mock::MockControlPlane::new(
794 0 : url,
795 0 : !args.is_private_access_proxy,
796 0 : );
797 0 : let api = control_plane::client::ControlPlaneClient::PostgresMock(api);
798 0 :
799 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
800 0 :
801 0 : let config = Box::leak(Box::new(auth_backend));
802 0 :
803 0 : Ok(Either::Left(config))
804 : }
805 :
806 : AuthBackendType::ConsoleRedirect => {
807 0 : let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
808 0 : let project_info_cache_config: ProjectInfoCacheOptions =
809 0 : args.project_info_cache.parse()?;
810 0 : let endpoint_cache_config: config::EndpointCacheConfig =
811 0 : args.endpoint_cache_config.parse()?;
812 :
813 0 : info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
814 0 : info!(
815 0 : "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
816 : );
817 0 : info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
818 0 : let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
819 0 : wake_compute_cache_config,
820 0 : project_info_cache_config,
821 0 : endpoint_cache_config,
822 0 : )));
823 :
824 : let config::ConcurrencyLockOptions {
825 0 : shards,
826 0 : limiter,
827 0 : epoch,
828 0 : timeout,
829 0 : } = args.wake_compute_lock.parse()?;
830 0 : info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
831 0 : let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
832 0 : "wake_compute_lock",
833 0 : limiter,
834 0 : shards,
835 0 : timeout,
836 0 : epoch,
837 0 : &Metrics::get().wake_compute_lock,
838 0 : )));
839 :
840 0 : let url = args.uri.clone().parse()?;
841 0 : let ep_url: crate::url::ApiUrl = args.auth_endpoint.parse()?;
842 0 : let endpoint = http::Endpoint::new(ep_url, http::new_client());
843 0 : let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
844 0 : RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
845 0 : let wake_compute_endpoint_rate_limiter =
846 0 : Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
847 0 :
848 0 : // Since we use only get_allowed_ips_and_secret() wake_compute_endpoint_rate_limiter
849 0 : // and locks are not used in ConsoleRedirectBackend,
850 0 : // but they are required by the NeonControlPlaneClient
851 0 : let api = control_plane::client::cplane_proxy_v1::NeonControlPlaneClient::new(
852 0 : endpoint,
853 0 : args.control_plane_token.clone(),
854 0 : caches,
855 0 : locks,
856 0 : wake_compute_endpoint_rate_limiter,
857 0 : );
858 0 :
859 0 : let backend = ConsoleRedirectBackend::new(url, api);
860 0 : let config = Box::leak(Box::new(backend));
861 0 :
862 0 : Ok(Either::Right(config))
863 : }
864 : }
865 0 : }
866 :
867 0 : async fn configure_redis(
868 0 : args: &ProxyCliArgs,
869 0 : ) -> anyhow::Result<(
870 0 : Option<ConnectionWithCredentialsProvider>,
871 0 : Option<ConnectionWithCredentialsProvider>,
872 0 : )> {
873 : // TODO: untangle the config args
874 0 : let regional_redis_client = match (args.redis_auth_type.as_str(), &args.redis_notifications) {
875 0 : ("plain", redis_url) => match redis_url {
876 : None => {
877 0 : bail!("plain auth requires redis_notifications to be set");
878 : }
879 0 : Some(url) => {
880 0 : Some(ConnectionWithCredentialsProvider::new_with_static_credentials(url.clone()))
881 : }
882 : },
883 0 : ("irsa", _) => match (&args.redis_host, args.redis_port) {
884 0 : (Some(host), Some(port)) => Some(
885 0 : ConnectionWithCredentialsProvider::new_with_credentials_provider(
886 0 : host.clone(),
887 0 : port,
888 0 : elasticache::CredentialsProvider::new(
889 0 : args.aws_region.clone(),
890 0 : args.redis_cluster_name.clone(),
891 0 : args.redis_user_id.clone(),
892 0 : )
893 0 : .await,
894 : ),
895 : ),
896 : (None, None) => {
897 : // todo: upgrade to error?
898 0 : warn!(
899 0 : "irsa auth requires redis-host and redis-port to be set, continuing without regional_redis_client"
900 : );
901 0 : None
902 : }
903 : _ => {
904 0 : bail!("redis-host and redis-port must be specified together");
905 : }
906 : },
907 : _ => {
908 0 : bail!("unknown auth type given");
909 : }
910 : };
911 :
912 0 : let redis_notifications_client = if let Some(url) = &args.redis_notifications {
913 0 : Some(ConnectionWithCredentialsProvider::new_with_static_credentials(&**url))
914 : } else {
915 0 : regional_redis_client.clone()
916 : };
917 :
918 0 : Ok((regional_redis_client, redis_notifications_client))
919 0 : }
920 :
921 : #[cfg(test)]
922 : mod tests {
923 : use std::time::Duration;
924 :
925 : use clap::Parser;
926 :
927 : use crate::rate_limiter::RateBucketInfo;
928 :
929 : #[test]
930 1 : fn parse_endpoint_rps_limit() {
931 1 : let config = super::ProxyCliArgs::parse_from([
932 1 : "proxy",
933 1 : "--endpoint-rps-limit",
934 1 : "100@1s",
935 1 : "--endpoint-rps-limit",
936 1 : "20@30s",
937 1 : ]);
938 1 :
939 1 : assert_eq!(
940 1 : config.endpoint_rps_limit,
941 1 : vec![
942 1 : RateBucketInfo::new(100, Duration::from_secs(1)),
943 1 : RateBucketInfo::new(20, Duration::from_secs(30)),
944 1 : ]
945 1 : );
946 1 : }
947 : }
|