Line data Source code
1 : use std::net::SocketAddr;
2 : use std::pin::pin;
3 : use std::str::FromStr;
4 : use std::sync::Arc;
5 : use std::time::Duration;
6 :
7 : use anyhow::{bail, ensure, Context};
8 : use camino::{Utf8Path, Utf8PathBuf};
9 : use compute_api::spec::LocalProxySpec;
10 : use futures::future::Either;
11 : use proxy::auth::backend::jwt::JwkCache;
12 : use proxy::auth::backend::local::{LocalBackend, JWKS_ROLE_MAP};
13 : use proxy::auth::{self};
14 : use proxy::cancellation::CancellationHandler;
15 : use proxy::config::{
16 : self, AuthenticationConfig, ComputeConfig, HttpConfig, ProxyConfig, RetryConfig,
17 : };
18 : use proxy::control_plane::locks::ApiLocks;
19 : use proxy::control_plane::messages::{EndpointJwksResponse, JwksSettings};
20 : use proxy::http::health_server::AppMetrics;
21 : use proxy::intern::RoleNameInt;
22 : use proxy::metrics::{Metrics, ThreadPoolMetrics};
23 : use proxy::rate_limiter::{
24 : BucketRateLimiter, EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo,
25 : };
26 : use proxy::scram::threadpool::ThreadPool;
27 : use proxy::serverless::cancel_set::CancelSet;
28 : use proxy::serverless::{self, GlobalConnPoolOptions};
29 : use proxy::tls::client_config::compute_client_config_with_root_certs;
30 : use proxy::types::RoleName;
31 : use proxy::url::ApiUrl;
32 :
33 : project_git_version!(GIT_VERSION);
34 : project_build_tag!(BUILD_TAG);
35 :
36 : use clap::Parser;
37 : use thiserror::Error;
38 : use tokio::net::TcpListener;
39 : use tokio::sync::Notify;
40 : use tokio::task::JoinSet;
41 : use tokio_util::sync::CancellationToken;
42 : use tracing::{debug, error, info, warn};
43 : use utils::sentry_init::init_sentry;
44 : use utils::{pid_file, project_build_tag, project_git_version};
45 :
46 : #[global_allocator]
47 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
48 :
49 : /// Neon proxy/router
50 : #[derive(Parser)]
51 : #[command(version = GIT_VERSION, about)]
52 : struct LocalProxyCliArgs {
53 : /// listen for incoming metrics connections on ip:port
54 : #[clap(long, default_value = "127.0.0.1:7001")]
55 0 : metrics: String,
56 : /// listen for incoming http connections on ip:port
57 : #[clap(long)]
58 0 : http: String,
59 : /// timeout for the TLS handshake
60 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
61 0 : handshake_timeout: tokio::time::Duration,
62 : /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
63 : #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
64 0 : connect_compute_lock: String,
65 : #[clap(flatten)]
66 : sql_over_http: SqlOverHttpArgs,
67 : /// User rate limiter max number of requests per second.
68 : ///
69 : /// Provided in the form `<Requests Per Second>@<Bucket Duration Size>`.
70 : /// Can be given multiple times for different bucket sizes.
71 0 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
72 0 : user_rps_limit: Vec<RateBucketInfo>,
73 : /// Whether the auth rate limiter actually takes effect (for testing)
74 0 : #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
75 0 : auth_rate_limit_enabled: bool,
76 : /// Authentication rate limiter max number of hashes per second.
77 0 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_AUTH_SET)]
78 0 : auth_rate_limit: Vec<RateBucketInfo>,
79 : /// The IP subnet to use when considering whether two IP addresses are considered the same.
80 0 : #[clap(long, default_value_t = 64)]
81 0 : auth_rate_limit_ip_subnet: u8,
82 : /// Whether to retry the connection to the compute node
83 : #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
84 0 : connect_to_compute_retry: String,
85 : /// Address of the postgres server
86 : #[clap(long, default_value = "127.0.0.1:5432")]
87 0 : postgres: SocketAddr,
88 : /// Address of the compute-ctl api service
89 : #[clap(long, default_value = "http://127.0.0.1:3080/")]
90 0 : compute_ctl: ApiUrl,
91 : /// Path of the local proxy config file
92 : #[clap(long, default_value = "./local_proxy.json")]
93 0 : config_path: Utf8PathBuf,
94 : /// Path of the local proxy PID file
95 : #[clap(long, default_value = "./local_proxy.pid")]
96 0 : pid_path: Utf8PathBuf,
97 : }
98 :
99 : #[derive(clap::Args, Clone, Copy, Debug)]
100 : struct SqlOverHttpArgs {
101 : /// How many connections to pool for each endpoint. Excess connections are discarded
102 0 : #[clap(long, default_value_t = 200)]
103 0 : sql_over_http_pool_max_total_conns: usize,
104 :
105 : /// How long pooled connections should remain idle for before closing
106 : #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
107 0 : sql_over_http_idle_timeout: tokio::time::Duration,
108 :
109 0 : #[clap(long, default_value_t = 100)]
110 0 : sql_over_http_client_conn_threshold: u64,
111 :
112 0 : #[clap(long, default_value_t = 16)]
113 0 : sql_over_http_cancel_set_shards: usize,
114 :
115 0 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
116 0 : sql_over_http_max_request_size_bytes: usize,
117 :
118 0 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
119 0 : sql_over_http_max_response_size_bytes: usize,
120 : }
121 :
122 : #[tokio::main]
123 0 : async fn main() -> anyhow::Result<()> {
124 0 : let _logging_guard = proxy::logging::init_local_proxy()?;
125 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
126 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
127 0 :
128 0 : Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
129 0 :
130 0 : // TODO: refactor these to use labels
131 0 : debug!("Version: {GIT_VERSION}");
132 0 : debug!("Build_tag: {BUILD_TAG}");
133 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
134 0 : revision: GIT_VERSION,
135 0 : build_tag: BUILD_TAG,
136 0 : });
137 0 :
138 0 : let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
139 0 : Ok(t) => Some(t),
140 0 : Err(e) => {
141 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
142 0 : None
143 0 : }
144 0 : };
145 0 :
146 0 : let args = LocalProxyCliArgs::parse();
147 0 : let config = build_config(&args)?;
148 0 : let auth_backend = build_auth_backend(&args)?;
149 0 :
150 0 : // before we bind to any ports, write the process ID to a file
151 0 : // so that compute-ctl can find our process later
152 0 : // in order to trigger the appropriate SIGHUP on config change.
153 0 : //
154 0 : // This also claims a "lock" that makes sure only one instance
155 0 : // of local_proxy runs at a time.
156 0 : let _process_guard = loop {
157 0 : match pid_file::claim_for_current_process(&args.pid_path) {
158 0 : Ok(guard) => break guard,
159 0 : Err(e) => {
160 0 : // compute-ctl might have tried to read the pid-file to let us
161 0 : // know about some config change. We should try again.
162 0 : error!(path=?args.pid_path, "could not claim PID file guard: {e:?}");
163 0 : tokio::time::sleep(Duration::from_secs(1)).await;
164 0 : }
165 0 : }
166 0 : };
167 0 :
168 0 : let metrics_listener = TcpListener::bind(args.metrics).await?.into_std()?;
169 0 : let http_listener = TcpListener::bind(args.http).await?;
170 0 : let shutdown = CancellationToken::new();
171 0 :
172 0 : // todo: should scale with CU
173 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
174 0 : LeakyBucketConfig {
175 0 : rps: 10.0,
176 0 : max: 100.0,
177 0 : },
178 0 : 16,
179 0 : ));
180 0 :
181 0 : let mut maintenance_tasks = JoinSet::new();
182 0 :
183 0 : let refresh_config_notify = Arc::new(Notify::new());
184 0 : maintenance_tasks.spawn(proxy::signals::handle(shutdown.clone(), {
185 0 : let refresh_config_notify = Arc::clone(&refresh_config_notify);
186 0 : move || {
187 0 : refresh_config_notify.notify_one();
188 0 : }
189 0 : }));
190 0 :
191 0 : // trigger the first config load **after** setting up the signal hook
192 0 : // to avoid the race condition where:
193 0 : // 1. No config file registered when local_proxy starts up
194 0 : // 2. The config file is written but the signal hook is not yet received
195 0 : // 3. local_proxy completes startup but has no config loaded, despite there being a registerd config.
196 0 : refresh_config_notify.notify_one();
197 0 : tokio::spawn(refresh_config_loop(args.config_path, refresh_config_notify));
198 0 :
199 0 : maintenance_tasks.spawn(proxy::http::health_server::task_main(
200 0 : metrics_listener,
201 0 : AppMetrics {
202 0 : jemalloc,
203 0 : neon_metrics,
204 0 : proxy: proxy::metrics::Metrics::get(),
205 0 : },
206 0 : ));
207 0 :
208 0 : let task = serverless::task_main(
209 0 : config,
210 0 : auth_backend,
211 0 : http_listener,
212 0 : shutdown.clone(),
213 0 : Arc::new(CancellationHandler::new(&config.connect_to_compute, None)),
214 0 : endpoint_rate_limiter,
215 0 : );
216 0 :
217 0 : match futures::future::select(pin!(maintenance_tasks.join_next()), pin!(task)).await {
218 0 : // exit immediately on maintenance task completion
219 0 : Either::Left((Some(res), _)) => match proxy::error::flatten_err(res)? {},
220 0 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
221 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
222 0 : // exit immediately on client task error
223 0 : Either::Right((res, _)) => res?,
224 0 : }
225 0 :
226 0 : Ok(())
227 0 : }
228 :
229 : /// ProxyConfig is created at proxy startup, and lives forever.
230 0 : fn build_config(args: &LocalProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
231 : let config::ConcurrencyLockOptions {
232 0 : shards,
233 0 : limiter,
234 0 : epoch,
235 0 : timeout,
236 0 : } = args.connect_compute_lock.parse()?;
237 0 : info!(
238 : ?limiter,
239 : shards,
240 : ?epoch,
241 0 : "Using NodeLocks (connect_compute)"
242 : );
243 0 : let connect_compute_locks = ApiLocks::new(
244 0 : "connect_compute_lock",
245 0 : limiter,
246 0 : shards,
247 0 : timeout,
248 0 : epoch,
249 0 : &Metrics::get().proxy.connect_compute_lock,
250 0 : )?;
251 :
252 0 : let http_config = HttpConfig {
253 0 : accept_websockets: false,
254 0 : pool_options: GlobalConnPoolOptions {
255 0 : gc_epoch: Duration::from_secs(60),
256 0 : pool_shards: 2,
257 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
258 0 : opt_in: false,
259 0 :
260 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_total_conns,
261 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
262 0 : },
263 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
264 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
265 0 : max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
266 0 : max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
267 0 : };
268 :
269 0 : let compute_config = ComputeConfig {
270 0 : retry: RetryConfig::parse(RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)?,
271 0 : tls: Arc::new(compute_client_config_with_root_certs()?),
272 0 : timeout: Duration::from_secs(2),
273 0 : };
274 0 :
275 0 : Ok(Box::leak(Box::new(ProxyConfig {
276 0 : tls_config: None,
277 0 : metric_collection: None,
278 0 : http_config,
279 0 : authentication_config: AuthenticationConfig {
280 0 : jwks_cache: JwkCache::default(),
281 0 : thread_pool: ThreadPool::new(0),
282 0 : scram_protocol_timeout: Duration::from_secs(10),
283 0 : rate_limiter_enabled: false,
284 0 : rate_limiter: BucketRateLimiter::new(vec![]),
285 0 : rate_limit_ip_subnet: 64,
286 0 : ip_allowlist_check_enabled: true,
287 0 : is_auth_broker: false,
288 0 : accept_jwts: true,
289 0 : console_redirect_confirmation_timeout: Duration::ZERO,
290 0 : },
291 0 : proxy_protocol_v2: config::ProxyProtocolV2::Rejected,
292 0 : handshake_timeout: Duration::from_secs(10),
293 0 : region: "local".into(),
294 0 : wake_compute_retry_config: RetryConfig::parse(RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)?,
295 0 : connect_compute_locks,
296 0 : connect_to_compute: compute_config,
297 : })))
298 0 : }
299 :
300 : /// auth::Backend is created at proxy startup, and lives forever.
301 0 : fn build_auth_backend(
302 0 : args: &LocalProxyCliArgs,
303 0 : ) -> anyhow::Result<&'static auth::Backend<'static, ()>> {
304 0 : let auth_backend = proxy::auth::Backend::Local(proxy::auth::backend::MaybeOwned::Owned(
305 0 : LocalBackend::new(args.postgres, args.compute_ctl.clone()),
306 0 : ));
307 0 :
308 0 : Ok(Box::leak(Box::new(auth_backend)))
309 0 : }
310 :
311 : #[derive(Error, Debug)]
312 : enum RefreshConfigError {
313 : #[error(transparent)]
314 : Read(#[from] std::io::Error),
315 : #[error(transparent)]
316 : Parse(#[from] serde_json::Error),
317 : #[error(transparent)]
318 : Validate(anyhow::Error),
319 : }
320 :
321 0 : async fn refresh_config_loop(path: Utf8PathBuf, rx: Arc<Notify>) {
322 0 : let mut init = true;
323 : loop {
324 0 : rx.notified().await;
325 :
326 0 : match refresh_config_inner(&path).await {
327 0 : Ok(()) => {}
328 : // don't log for file not found errors if this is the first time we are checking
329 : // for computes that don't use local_proxy, this is not an error.
330 0 : Err(RefreshConfigError::Read(e))
331 0 : if init && e.kind() == std::io::ErrorKind::NotFound =>
332 0 : {
333 0 : debug!(error=?e, ?path, "could not read config file");
334 : }
335 0 : Err(e) => {
336 0 : error!(error=?e, ?path, "could not read config file");
337 : }
338 : }
339 :
340 0 : init = false;
341 : }
342 : }
343 :
344 0 : async fn refresh_config_inner(path: &Utf8Path) -> Result<(), RefreshConfigError> {
345 0 : let bytes = tokio::fs::read(&path).await?;
346 0 : let data: LocalProxySpec = serde_json::from_slice(&bytes)?;
347 :
348 0 : let mut jwks_set = vec![];
349 :
350 0 : fn parse_jwks_settings(jwks: compute_api::spec::JwksSettings) -> anyhow::Result<JwksSettings> {
351 0 : let mut jwks_url = url::Url::from_str(&jwks.jwks_url).context("parsing JWKS url")?;
352 :
353 0 : ensure!(
354 0 : jwks_url.has_authority()
355 0 : && (jwks_url.scheme() == "http" || jwks_url.scheme() == "https"),
356 0 : "Invalid JWKS url. Must be HTTP",
357 : );
358 :
359 0 : ensure!(
360 0 : jwks_url.host().is_some_and(|h| h != url::Host::Domain("")),
361 0 : "Invalid JWKS url. No domain listed",
362 : );
363 :
364 : // clear username, password and ports
365 0 : jwks_url
366 0 : .set_username("")
367 0 : .expect("url can be a base and has a valid host and is not a file. should not error");
368 0 : jwks_url
369 0 : .set_password(None)
370 0 : .expect("url can be a base and has a valid host and is not a file. should not error");
371 0 : // local testing is hard if we need to have a specific restricted port
372 0 : if cfg!(not(feature = "testing")) {
373 0 : jwks_url.set_port(None).expect(
374 0 : "url can be a base and has a valid host and is not a file. should not error",
375 0 : );
376 0 : }
377 :
378 : // clear query params
379 0 : jwks_url.set_fragment(None);
380 0 : jwks_url.query_pairs_mut().clear().finish();
381 0 :
382 0 : if jwks_url.scheme() != "https" {
383 : // local testing is hard if we need to set up https support.
384 0 : if cfg!(not(feature = "testing")) {
385 0 : jwks_url
386 0 : .set_scheme("https")
387 0 : .expect("should not error to set the scheme to https if it was http");
388 0 : } else {
389 0 : warn!(scheme = jwks_url.scheme(), "JWKS url is not HTTPS");
390 : }
391 0 : }
392 :
393 0 : Ok(JwksSettings {
394 0 : id: jwks.id,
395 0 : jwks_url,
396 0 : provider_name: jwks.provider_name,
397 0 : jwt_audience: jwks.jwt_audience,
398 0 : role_names: jwks
399 0 : .role_names
400 0 : .into_iter()
401 0 : .map(RoleName::from)
402 0 : .map(|s| RoleNameInt::from(&s))
403 0 : .collect(),
404 0 : })
405 0 : }
406 :
407 0 : for jwks in data.jwks.into_iter().flatten() {
408 0 : jwks_set.push(parse_jwks_settings(jwks).map_err(RefreshConfigError::Validate)?);
409 : }
410 :
411 0 : info!("successfully loaded new config");
412 0 : JWKS_ROLE_MAP.store(Some(Arc::new(EndpointJwksResponse { jwks: jwks_set })));
413 0 :
414 0 : Ok(())
415 0 : }
|