Line data Source code
1 : use std::net::SocketAddr;
2 : use std::pin::pin;
3 : use std::sync::Arc;
4 :
5 : use anyhow::bail;
6 : use futures::future::Either;
7 : use proxy::auth::backend::jwt::JwkCache;
8 : use proxy::auth::backend::{AuthRateLimiter, ConsoleRedirectBackend, MaybeOwned};
9 : use proxy::cancellation::{CancelMap, CancellationHandler};
10 : use proxy::config::{
11 : self, remote_storage_from_toml, AuthenticationConfig, CacheOptions, HttpConfig,
12 : ProjectInfoCacheOptions, ProxyConfig, ProxyProtocolV2,
13 : };
14 : use proxy::context::parquet::ParquetUploadArgs;
15 : use proxy::http::health_server::AppMetrics;
16 : use proxy::metrics::Metrics;
17 : use proxy::rate_limiter::{
18 : EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo, WakeComputeRateLimiter,
19 : };
20 : use proxy::redis::cancellation_publisher::RedisPublisherClient;
21 : use proxy::redis::connection_with_credentials_provider::ConnectionWithCredentialsProvider;
22 : use proxy::redis::{elasticache, notifications};
23 : use proxy::scram::threadpool::ThreadPool;
24 : use proxy::serverless::cancel_set::CancelSet;
25 : use proxy::serverless::GlobalConnPoolOptions;
26 : use proxy::{auth, control_plane, http, serverless, usage_metrics};
27 : use remote_storage::RemoteStorageConfig;
28 : use tokio::net::TcpListener;
29 : use tokio::sync::Mutex;
30 : use tokio::task::JoinSet;
31 : use tokio_util::sync::CancellationToken;
32 : use tracing::{info, warn, Instrument};
33 : use utils::sentry_init::init_sentry;
34 : use utils::{project_build_tag, project_git_version};
35 :
36 : project_git_version!(GIT_VERSION);
37 : project_build_tag!(BUILD_TAG);
38 :
39 : use clap::{Parser, ValueEnum};
40 :
41 : #[global_allocator]
42 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
43 :
44 : #[derive(Clone, Debug, ValueEnum)]
45 : enum AuthBackendType {
46 : #[value(name("console"), alias("cplane"))]
47 : ControlPlane,
48 :
49 : #[value(name("cplane-v1"), alias("control-plane"))]
50 : ControlPlaneV1,
51 :
52 : #[value(name("link"), alias("control-redirect"))]
53 : ConsoleRedirect,
54 :
55 : #[cfg(feature = "testing")]
56 : Postgres,
57 : }
58 :
59 : /// Neon proxy/router
60 : #[derive(Parser)]
61 : #[command(version = GIT_VERSION, about)]
62 : struct ProxyCliArgs {
63 : /// Name of the region this proxy is deployed in
64 1 : #[clap(long, default_value_t = String::new())]
65 0 : region: String,
66 : /// listen for incoming client connections on ip:port
67 : #[clap(short, long, default_value = "127.0.0.1:4432")]
68 0 : proxy: String,
69 1 : #[clap(value_enum, long, default_value_t = AuthBackendType::ConsoleRedirect)]
70 0 : auth_backend: AuthBackendType,
71 : /// listen for management callback connection on ip:port
72 : #[clap(short, long, default_value = "127.0.0.1:7000")]
73 0 : mgmt: String,
74 : /// listen for incoming http connections (metrics, etc) on ip:port
75 : #[clap(long, default_value = "127.0.0.1:7001")]
76 0 : http: String,
77 : /// listen for incoming wss connections on ip:port
78 : #[clap(long)]
79 : wss: Option<String>,
80 : /// redirect unauthenticated users to the given uri in case of console redirect auth
81 : #[clap(short, long, default_value = "http://localhost:3000/psql_session/")]
82 0 : uri: String,
83 : /// cloud API endpoint for authenticating users
84 : #[clap(
85 : short,
86 : long,
87 : default_value = "http://localhost:3000/authenticate_proxy_request/"
88 : )]
89 0 : auth_endpoint: String,
90 : /// JWT used to connect to control plane.
91 : #[clap(
92 : long,
93 : value_name = "JWT",
94 : default_value = "",
95 : env = "NEON_PROXY_TO_CONTROLPLANE_TOKEN"
96 : )]
97 0 : control_plane_token: Arc<str>,
98 : /// if this is not local proxy, this toggles whether we accept jwt or passwords for http
99 1 : #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
100 0 : is_auth_broker: bool,
101 : /// path to TLS key for client postgres connections
102 : ///
103 : /// tls-key and tls-cert are for backwards compatibility, we can put all certs in one dir
104 : #[clap(short = 'k', long, alias = "ssl-key")]
105 : tls_key: Option<String>,
106 : /// path to TLS cert 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 = 'c', long, alias = "ssl-cert")]
110 : tls_cert: Option<String>,
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 : /// Allow self-signed certificates for compute nodes (for testing)
133 1 : #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
134 0 : allow_self_signed_compute: bool,
135 : #[clap(flatten)]
136 : sql_over_http: SqlOverHttpArgs,
137 : /// timeout for scram authentication protocol
138 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
139 0 : scram_protocol_timeout: tokio::time::Duration,
140 : /// size of the threadpool for password hashing
141 1 : #[clap(long, default_value_t = 4)]
142 0 : scram_thread_pool_size: u8,
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 4 : #[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 4 : #[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 4 : #[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 4 : #[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 : // 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 : #[tokio::main]
281 0 : async fn main() -> anyhow::Result<()> {
282 0 : let _logging_guard = proxy::logging::init().await?;
283 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
284 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
285 0 :
286 0 : // TODO: refactor these to use labels
287 0 : info!("Version: {GIT_VERSION}");
288 0 : info!("Build_tag: {BUILD_TAG}");
289 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
290 0 : revision: GIT_VERSION,
291 0 : build_tag: BUILD_TAG,
292 0 : });
293 0 :
294 0 : let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
295 0 : Ok(t) => Some(t),
296 0 : Err(e) => {
297 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
298 0 : None
299 0 : }
300 0 : };
301 0 :
302 0 : let args = ProxyCliArgs::parse();
303 0 : let config = build_config(&args)?;
304 0 : let auth_backend = build_auth_backend(&args)?;
305 0 :
306 0 : match auth_backend {
307 0 : Either::Left(auth_backend) => info!("Authentication backend: {auth_backend}"),
308 0 : Either::Right(auth_backend) => info!("Authentication backend: {auth_backend:?}"),
309 0 : };
310 0 : info!("Using region: {}", args.aws_region);
311 0 :
312 0 : // TODO: untangle the config args
313 0 : let regional_redis_client = match (args.redis_auth_type.as_str(), &args.redis_notifications) {
314 0 : ("plain", redis_url) => match redis_url {
315 0 : None => {
316 0 : bail!("plain auth requires redis_notifications to be set");
317 0 : }
318 0 : Some(url) => Some(
319 0 : ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()),
320 0 : ),
321 0 : },
322 0 : ("irsa", _) => match (&args.redis_host, args.redis_port) {
323 0 : (Some(host), Some(port)) => Some(
324 0 : ConnectionWithCredentialsProvider::new_with_credentials_provider(
325 0 : host.to_string(),
326 0 : port,
327 0 : elasticache::CredentialsProvider::new(
328 0 : args.aws_region,
329 0 : args.redis_cluster_name,
330 0 : args.redis_user_id,
331 0 : )
332 0 : .await,
333 0 : ),
334 0 : ),
335 0 : (None, None) => {
336 0 : warn!("irsa auth requires redis-host and redis-port to be set, continuing without regional_redis_client");
337 0 : None
338 0 : }
339 0 : _ => {
340 0 : bail!("redis-host and redis-port must be specified together");
341 0 : }
342 0 : },
343 0 : _ => {
344 0 : bail!("unknown auth type given");
345 0 : }
346 0 : };
347 0 :
348 0 : let redis_notifications_client = if let Some(url) = args.redis_notifications {
349 0 : Some(ConnectionWithCredentialsProvider::new_with_static_credentials(url.to_string()))
350 0 : } else {
351 0 : regional_redis_client.clone()
352 0 : };
353 0 :
354 0 : // Check that we can bind to address before further initialization
355 0 : let http_address: SocketAddr = args.http.parse()?;
356 0 : info!("Starting http on {http_address}");
357 0 : let http_listener = TcpListener::bind(http_address).await?.into_std()?;
358 0 :
359 0 : let mgmt_address: SocketAddr = args.mgmt.parse()?;
360 0 : info!("Starting mgmt on {mgmt_address}");
361 0 : let mgmt_listener = TcpListener::bind(mgmt_address).await?;
362 0 :
363 0 : let proxy_listener = if !args.is_auth_broker {
364 0 : let proxy_address: SocketAddr = args.proxy.parse()?;
365 0 : info!("Starting proxy on {proxy_address}");
366 0 :
367 0 : Some(TcpListener::bind(proxy_address).await?)
368 0 : } else {
369 0 : None
370 0 : };
371 0 :
372 0 : // TODO: rename the argument to something like serverless.
373 0 : // It now covers more than just websockets, it also covers SQL over HTTP.
374 0 : let serverless_listener = if let Some(serverless_address) = args.wss {
375 0 : let serverless_address: SocketAddr = serverless_address.parse()?;
376 0 : info!("Starting wss on {serverless_address}");
377 0 : Some(TcpListener::bind(serverless_address).await?)
378 0 : } else if args.is_auth_broker {
379 0 : bail!("wss arg must be present for auth-broker")
380 0 : } else {
381 0 : None
382 0 : };
383 0 :
384 0 : let cancellation_token = CancellationToken::new();
385 0 :
386 0 : let cancel_map = CancelMap::default();
387 0 :
388 0 : let redis_rps_limit = Vec::leak(args.redis_rps_limit.clone());
389 0 : RateBucketInfo::validate(redis_rps_limit)?;
390 0 :
391 0 : let redis_publisher = match ®ional_redis_client {
392 0 : Some(redis_publisher) => Some(Arc::new(Mutex::new(RedisPublisherClient::new(
393 0 : redis_publisher.clone(),
394 0 : args.region.clone(),
395 0 : redis_rps_limit,
396 0 : )?))),
397 0 : None => None,
398 0 : };
399 0 :
400 0 : let cancellation_handler = Arc::new(CancellationHandler::<
401 0 : Option<Arc<Mutex<RedisPublisherClient>>>,
402 0 : >::new(
403 0 : cancel_map.clone(),
404 0 : redis_publisher,
405 0 : proxy::metrics::CancellationSource::FromClient,
406 0 : ));
407 0 :
408 0 : // bit of a hack - find the min rps and max rps supported and turn it into
409 0 : // leaky bucket config instead
410 0 : let max = args
411 0 : .endpoint_rps_limit
412 0 : .iter()
413 0 : .map(|x| x.rps())
414 0 : .max_by(f64::total_cmp)
415 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.max);
416 0 : let rps = args
417 0 : .endpoint_rps_limit
418 0 : .iter()
419 0 : .map(|x| x.rps())
420 0 : .min_by(f64::total_cmp)
421 0 : .unwrap_or(EndpointRateLimiter::DEFAULT.rps);
422 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
423 0 : LeakyBucketConfig { rps, max },
424 0 : 64,
425 0 : ));
426 0 :
427 0 : // client facing tasks. these will exit on error or on cancellation
428 0 : // cancellation returns Ok(())
429 0 : let mut client_tasks = JoinSet::new();
430 0 : match auth_backend {
431 0 : Either::Left(auth_backend) => {
432 0 : if let Some(proxy_listener) = proxy_listener {
433 0 : client_tasks.spawn(proxy::proxy::task_main(
434 0 : config,
435 0 : auth_backend,
436 0 : proxy_listener,
437 0 : cancellation_token.clone(),
438 0 : cancellation_handler.clone(),
439 0 : endpoint_rate_limiter.clone(),
440 0 : ));
441 0 : }
442 0 :
443 0 : if let Some(serverless_listener) = serverless_listener {
444 0 : client_tasks.spawn(serverless::task_main(
445 0 : config,
446 0 : auth_backend,
447 0 : serverless_listener,
448 0 : cancellation_token.clone(),
449 0 : cancellation_handler.clone(),
450 0 : endpoint_rate_limiter.clone(),
451 0 : ));
452 0 : }
453 0 : }
454 0 : Either::Right(auth_backend) => {
455 0 : if let Some(proxy_listener) = proxy_listener {
456 0 : client_tasks.spawn(proxy::console_redirect_proxy::task_main(
457 0 : config,
458 0 : auth_backend,
459 0 : proxy_listener,
460 0 : cancellation_token.clone(),
461 0 : cancellation_handler.clone(),
462 0 : ));
463 0 : }
464 0 : }
465 0 : }
466 0 :
467 0 : client_tasks.spawn(proxy::context::parquet::worker(
468 0 : cancellation_token.clone(),
469 0 : args.parquet_upload,
470 0 : ));
471 0 :
472 0 : // maintenance tasks. these never return unless there's an error
473 0 : let mut maintenance_tasks = JoinSet::new();
474 0 : maintenance_tasks.spawn(proxy::signals::handle(cancellation_token.clone(), || {}));
475 0 : maintenance_tasks.spawn(http::health_server::task_main(
476 0 : http_listener,
477 0 : AppMetrics {
478 0 : jemalloc,
479 0 : neon_metrics,
480 0 : proxy: proxy::metrics::Metrics::get(),
481 0 : },
482 0 : ));
483 0 : maintenance_tasks.spawn(control_plane::mgmt::task_main(mgmt_listener));
484 0 :
485 0 : if let Some(metrics_config) = &config.metric_collection {
486 0 : // TODO: Add gc regardles of the metric collection being enabled.
487 0 : maintenance_tasks.spawn(usage_metrics::task_main(metrics_config));
488 0 : }
489 0 :
490 0 : if let Either::Left(auth::Backend::ControlPlane(api, _)) = &auth_backend {
491 0 : if let proxy::control_plane::client::ControlPlaneClient::Neon(api) = &**api {
492 0 : match (redis_notifications_client, regional_redis_client.clone()) {
493 0 : (None, None) => {}
494 0 : (client1, client2) => {
495 0 : let cache = api.caches.project_info.clone();
496 0 : if let Some(client) = client1 {
497 0 : maintenance_tasks.spawn(notifications::task_main(
498 0 : client,
499 0 : cache.clone(),
500 0 : cancel_map.clone(),
501 0 : args.region.clone(),
502 0 : ));
503 0 : }
504 0 : if let Some(client) = client2 {
505 0 : maintenance_tasks.spawn(notifications::task_main(
506 0 : client,
507 0 : cache.clone(),
508 0 : cancel_map.clone(),
509 0 : args.region.clone(),
510 0 : ));
511 0 : }
512 0 : maintenance_tasks.spawn(async move { cache.clone().gc_worker().await });
513 0 : }
514 0 : }
515 0 : if let Some(regional_redis_client) = regional_redis_client {
516 0 : let cache = api.caches.endpoints_cache.clone();
517 0 : let con = regional_redis_client;
518 0 : let span = tracing::info_span!("endpoints_cache");
519 0 : maintenance_tasks.spawn(
520 0 : async move { cache.do_read(con, cancellation_token.clone()).await }
521 0 : .instrument(span),
522 0 : );
523 0 : }
524 0 : } else if let proxy::control_plane::client::ControlPlaneClient::ProxyV1(api) = &**api {
525 0 : match (redis_notifications_client, regional_redis_client.clone()) {
526 0 : (None, None) => {}
527 0 : (client1, client2) => {
528 0 : let cache = api.caches.project_info.clone();
529 0 : if let Some(client) = client1 {
530 0 : maintenance_tasks.spawn(notifications::task_main(
531 0 : client,
532 0 : cache.clone(),
533 0 : cancel_map.clone(),
534 0 : args.region.clone(),
535 0 : ));
536 0 : }
537 0 : if let Some(client) = client2 {
538 0 : maintenance_tasks.spawn(notifications::task_main(
539 0 : client,
540 0 : cache.clone(),
541 0 : cancel_map.clone(),
542 0 : args.region.clone(),
543 0 : ));
544 0 : }
545 0 : maintenance_tasks.spawn(async move { cache.clone().gc_worker().await });
546 0 : }
547 0 : }
548 0 : if let Some(regional_redis_client) = regional_redis_client {
549 0 : let cache = api.caches.endpoints_cache.clone();
550 0 : let con = regional_redis_client;
551 0 : let span = tracing::info_span!("endpoints_cache");
552 0 : maintenance_tasks.spawn(
553 0 : async move { cache.do_read(con, cancellation_token.clone()).await }
554 0 : .instrument(span),
555 0 : );
556 0 : }
557 0 : }
558 0 : }
559 0 :
560 0 : let maintenance = loop {
561 0 : // get one complete task
562 0 : match futures::future::select(
563 0 : pin!(maintenance_tasks.join_next()),
564 0 : pin!(client_tasks.join_next()),
565 0 : )
566 0 : .await
567 0 : {
568 0 : // exit immediately on maintenance task completion
569 0 : Either::Left((Some(res), _)) => break proxy::error::flatten_err(res)?,
570 0 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
571 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
572 0 : // exit immediately on client task error
573 0 : Either::Right((Some(res), _)) => proxy::error::flatten_err(res)?,
574 0 : // exit if all our client tasks have shutdown gracefully
575 0 : Either::Right((None, _)) => return Ok(()),
576 0 : }
577 0 : };
578 0 :
579 0 : // maintenance tasks return Infallible success values, this is an impossible value
580 0 : // so this match statically ensures that there are no possibilities for that value
581 0 : match maintenance {}
582 0 : }
583 :
584 : /// ProxyConfig is created at proxy startup, and lives forever.
585 0 : fn build_config(args: &ProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
586 0 : let thread_pool = ThreadPool::new(args.scram_thread_pool_size);
587 0 : Metrics::install(thread_pool.metrics.clone());
588 :
589 0 : let tls_config = match (&args.tls_key, &args.tls_cert) {
590 0 : (Some(key_path), Some(cert_path)) => Some(config::configure_tls(
591 0 : key_path,
592 0 : cert_path,
593 0 : args.certs_dir.as_ref(),
594 0 : )?),
595 0 : (None, None) => None,
596 0 : _ => bail!("either both or neither tls-key and tls-cert must be specified"),
597 : };
598 :
599 0 : if args.allow_self_signed_compute {
600 0 : warn!("allowing self-signed compute certificates");
601 0 : }
602 0 : let backup_metric_collection_config = config::MetricBackupCollectionConfig {
603 0 : interval: args.metric_backup_collection_interval,
604 0 : remote_storage_config: args.metric_backup_collection_remote_storage.clone(),
605 0 : chunk_size: args.metric_backup_collection_chunk_size,
606 0 : };
607 :
608 0 : let metric_collection = match (
609 0 : &args.metric_collection_endpoint,
610 0 : &args.metric_collection_interval,
611 : ) {
612 0 : (Some(endpoint), Some(interval)) => Some(config::MetricCollectionConfig {
613 0 : endpoint: endpoint.parse()?,
614 0 : interval: humantime::parse_duration(interval)?,
615 0 : backup_metric_collection_config,
616 : }),
617 0 : (None, None) => None,
618 0 : _ => bail!(
619 0 : "either both or neither metric-collection-endpoint \
620 0 : and metric-collection-interval must be specified"
621 0 : ),
622 : };
623 :
624 : let config::ConcurrencyLockOptions {
625 0 : shards,
626 0 : limiter,
627 0 : epoch,
628 0 : timeout,
629 0 : } = args.connect_compute_lock.parse()?;
630 0 : info!(
631 : ?limiter,
632 : shards,
633 : ?epoch,
634 0 : "Using NodeLocks (connect_compute)"
635 : );
636 0 : let connect_compute_locks = control_plane::locks::ApiLocks::new(
637 0 : "connect_compute_lock",
638 0 : limiter,
639 0 : shards,
640 0 : timeout,
641 0 : epoch,
642 0 : &Metrics::get().proxy.connect_compute_lock,
643 0 : )?;
644 :
645 0 : let http_config = HttpConfig {
646 0 : accept_websockets: !args.is_auth_broker,
647 0 : pool_options: GlobalConnPoolOptions {
648 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_conns_per_endpoint,
649 0 : gc_epoch: args.sql_over_http.sql_over_http_pool_gc_epoch,
650 0 : pool_shards: args.sql_over_http.sql_over_http_pool_shards,
651 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
652 0 : opt_in: args.sql_over_http.sql_over_http_pool_opt_in,
653 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
654 0 : },
655 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
656 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
657 0 : max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
658 0 : max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
659 0 : };
660 0 : let authentication_config = AuthenticationConfig {
661 0 : jwks_cache: JwkCache::default(),
662 0 : thread_pool,
663 0 : scram_protocol_timeout: args.scram_protocol_timeout,
664 0 : rate_limiter_enabled: args.auth_rate_limit_enabled,
665 0 : rate_limiter: AuthRateLimiter::new(args.auth_rate_limit.clone()),
666 0 : rate_limit_ip_subnet: args.auth_rate_limit_ip_subnet,
667 0 : ip_allowlist_check_enabled: !args.is_private_access_proxy,
668 0 : is_auth_broker: args.is_auth_broker,
669 0 : accept_jwts: args.is_auth_broker,
670 0 : console_redirect_confirmation_timeout: args.webauth_confirmation_timeout,
671 0 : };
672 :
673 0 : let config = ProxyConfig {
674 0 : tls_config,
675 0 : metric_collection,
676 0 : allow_self_signed_compute: args.allow_self_signed_compute,
677 0 : http_config,
678 0 : authentication_config,
679 0 : proxy_protocol_v2: args.proxy_protocol_v2,
680 0 : handshake_timeout: args.handshake_timeout,
681 0 : region: args.region.clone(),
682 0 : wake_compute_retry_config: config::RetryConfig::parse(&args.wake_compute_retry)?,
683 0 : connect_compute_locks,
684 0 : connect_to_compute_retry_config: config::RetryConfig::parse(
685 0 : &args.connect_to_compute_retry,
686 0 : )?,
687 : };
688 :
689 0 : let config = Box::leak(Box::new(config));
690 0 :
691 0 : tokio::spawn(config.connect_compute_locks.garbage_collect_worker());
692 0 :
693 0 : Ok(config)
694 0 : }
695 :
696 : /// auth::Backend is created at proxy startup, and lives forever.
697 0 : fn build_auth_backend(
698 0 : args: &ProxyCliArgs,
699 0 : ) -> anyhow::Result<Either<&'static auth::Backend<'static, ()>, &'static ConsoleRedirectBackend>> {
700 0 : match &args.auth_backend {
701 : AuthBackendType::ControlPlaneV1 => {
702 0 : let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
703 0 : let project_info_cache_config: ProjectInfoCacheOptions =
704 0 : args.project_info_cache.parse()?;
705 0 : let endpoint_cache_config: config::EndpointCacheConfig =
706 0 : args.endpoint_cache_config.parse()?;
707 :
708 0 : info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
709 0 : info!(
710 0 : "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
711 : );
712 0 : info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
713 0 : let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
714 0 : wake_compute_cache_config,
715 0 : project_info_cache_config,
716 0 : endpoint_cache_config,
717 0 : )));
718 :
719 : let config::ConcurrencyLockOptions {
720 0 : shards,
721 0 : limiter,
722 0 : epoch,
723 0 : timeout,
724 0 : } = args.wake_compute_lock.parse()?;
725 0 : info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
726 0 : let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
727 0 : "wake_compute_lock",
728 0 : limiter,
729 0 : shards,
730 0 : timeout,
731 0 : epoch,
732 0 : &Metrics::get().wake_compute_lock,
733 0 : )?));
734 0 : tokio::spawn(locks.garbage_collect_worker());
735 :
736 0 : let url: proxy::url::ApiUrl = args.auth_endpoint.parse()?;
737 :
738 0 : let endpoint = http::Endpoint::new(url, http::new_client());
739 0 :
740 0 : let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
741 0 : RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
742 0 : let wake_compute_endpoint_rate_limiter =
743 0 : Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
744 0 :
745 0 : let api = control_plane::client::cplane_proxy_v1::NeonControlPlaneClient::new(
746 0 : endpoint,
747 0 : args.control_plane_token.clone(),
748 0 : caches,
749 0 : locks,
750 0 : wake_compute_endpoint_rate_limiter,
751 0 : );
752 0 :
753 0 : let api = control_plane::client::ControlPlaneClient::ProxyV1(api);
754 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
755 0 : let config = Box::leak(Box::new(auth_backend));
756 0 :
757 0 : Ok(Either::Left(config))
758 : }
759 :
760 : AuthBackendType::ControlPlane => {
761 0 : let wake_compute_cache_config: CacheOptions = args.wake_compute_cache.parse()?;
762 0 : let project_info_cache_config: ProjectInfoCacheOptions =
763 0 : args.project_info_cache.parse()?;
764 0 : let endpoint_cache_config: config::EndpointCacheConfig =
765 0 : args.endpoint_cache_config.parse()?;
766 :
767 0 : info!("Using NodeInfoCache (wake_compute) with options={wake_compute_cache_config:?}");
768 0 : info!(
769 0 : "Using AllowedIpsCache (wake_compute) with options={project_info_cache_config:?}"
770 : );
771 0 : info!("Using EndpointCacheConfig with options={endpoint_cache_config:?}");
772 0 : let caches = Box::leak(Box::new(control_plane::caches::ApiCaches::new(
773 0 : wake_compute_cache_config,
774 0 : project_info_cache_config,
775 0 : endpoint_cache_config,
776 0 : )));
777 :
778 : let config::ConcurrencyLockOptions {
779 0 : shards,
780 0 : limiter,
781 0 : epoch,
782 0 : timeout,
783 0 : } = args.wake_compute_lock.parse()?;
784 0 : info!(?limiter, shards, ?epoch, "Using NodeLocks (wake_compute)");
785 0 : let locks = Box::leak(Box::new(control_plane::locks::ApiLocks::new(
786 0 : "wake_compute_lock",
787 0 : limiter,
788 0 : shards,
789 0 : timeout,
790 0 : epoch,
791 0 : &Metrics::get().wake_compute_lock,
792 0 : )?));
793 0 : tokio::spawn(locks.garbage_collect_worker());
794 :
795 0 : let url: proxy::url::ApiUrl = args.auth_endpoint.parse()?;
796 :
797 0 : let endpoint = http::Endpoint::new(url, http::new_client());
798 0 :
799 0 : let mut wake_compute_rps_limit = args.wake_compute_limit.clone();
800 0 : RateBucketInfo::validate(&mut wake_compute_rps_limit)?;
801 0 : let wake_compute_endpoint_rate_limiter =
802 0 : Arc::new(WakeComputeRateLimiter::new(wake_compute_rps_limit));
803 0 :
804 0 : let api = control_plane::client::neon::NeonControlPlaneClient::new(
805 0 : endpoint,
806 0 : args.control_plane_token.clone(),
807 0 : caches,
808 0 : locks,
809 0 : wake_compute_endpoint_rate_limiter,
810 0 : );
811 0 : let api = control_plane::client::ControlPlaneClient::Neon(api);
812 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
813 0 :
814 0 : let config = Box::leak(Box::new(auth_backend));
815 0 :
816 0 : Ok(Either::Left(config))
817 : }
818 :
819 : #[cfg(feature = "testing")]
820 : AuthBackendType::Postgres => {
821 0 : let url = args.auth_endpoint.parse()?;
822 0 : let api = control_plane::client::mock::MockControlPlane::new(
823 0 : url,
824 0 : !args.is_private_access_proxy,
825 0 : );
826 0 : let api = control_plane::client::ControlPlaneClient::PostgresMock(api);
827 0 :
828 0 : let auth_backend = auth::Backend::ControlPlane(MaybeOwned::Owned(api), ());
829 0 :
830 0 : let config = Box::leak(Box::new(auth_backend));
831 0 :
832 0 : Ok(Either::Left(config))
833 : }
834 :
835 : AuthBackendType::ConsoleRedirect => {
836 0 : let url = args.uri.parse()?;
837 0 : let backend = ConsoleRedirectBackend::new(url);
838 0 :
839 0 : let config = Box::leak(Box::new(backend));
840 0 :
841 0 : Ok(Either::Right(config))
842 : }
843 : }
844 0 : }
845 :
846 : #[cfg(test)]
847 : mod tests {
848 : use std::time::Duration;
849 :
850 : use clap::Parser;
851 : use proxy::rate_limiter::RateBucketInfo;
852 :
853 : #[test]
854 1 : fn parse_endpoint_rps_limit() {
855 1 : let config = super::ProxyCliArgs::parse_from([
856 1 : "proxy",
857 1 : "--endpoint-rps-limit",
858 1 : "100@1s",
859 1 : "--endpoint-rps-limit",
860 1 : "20@30s",
861 1 : ]);
862 1 :
863 1 : assert_eq!(
864 1 : config.endpoint_rps_limit,
865 1 : vec![
866 1 : RateBucketInfo::new(100, Duration::from_secs(1)),
867 1 : RateBucketInfo::new(20, Duration::from_secs(30)),
868 1 : ]
869 1 : );
870 1 : }
871 : }
|