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