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 camino::Utf8PathBuf;
9 : use clap::Parser;
10 : use futures::future::Either;
11 : use tokio::net::TcpListener;
12 : use tokio::sync::Notify;
13 : use tokio::task::JoinSet;
14 : use tokio_util::sync::CancellationToken;
15 : use tracing::{debug, error, info};
16 : use utils::sentry_init::init_sentry;
17 : use utils::{pid_file, project_build_tag, project_git_version};
18 :
19 : use crate::auth::backend::jwt::JwkCache;
20 : use crate::auth::backend::local::LocalBackend;
21 : use crate::auth::{self};
22 : use crate::cancellation::CancellationHandler;
23 : use crate::config::{
24 : self, AuthenticationConfig, ComputeConfig, HttpConfig, ProxyConfig, RetryConfig,
25 : refresh_config_loop,
26 : };
27 : use crate::control_plane::locks::ApiLocks;
28 : use crate::http::health_server::AppMetrics;
29 : use crate::metrics::{Metrics, ThreadPoolMetrics};
30 : use crate::rate_limiter::{EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo};
31 : use crate::scram::threadpool::ThreadPool;
32 : use crate::serverless::cancel_set::CancelSet;
33 : use crate::serverless::{self, GlobalConnPoolOptions};
34 : use crate::tls::client_config::compute_client_config_with_root_certs;
35 : use crate::url::ApiUrl;
36 :
37 : project_git_version!(GIT_VERSION);
38 : project_build_tag!(BUILD_TAG);
39 :
40 : /// Neon proxy/router
41 : #[derive(Parser)]
42 : #[command(version = GIT_VERSION, about)]
43 : struct LocalProxyCliArgs {
44 : /// listen for incoming metrics connections on ip:port
45 : #[clap(long, default_value = "127.0.0.1:7001")]
46 : metrics: String,
47 : /// listen for incoming http connections on ip:port
48 : #[clap(long)]
49 : http: String,
50 : /// timeout for the TLS handshake
51 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
52 : handshake_timeout: tokio::time::Duration,
53 : /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
54 : #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
55 : connect_compute_lock: String,
56 : #[clap(flatten)]
57 : sql_over_http: SqlOverHttpArgs,
58 : /// User rate limiter max number of requests per second.
59 : ///
60 : /// Provided in the form `<Requests Per Second>@<Bucket Duration Size>`.
61 : /// Can be given multiple times for different bucket sizes.
62 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
63 : user_rps_limit: Vec<RateBucketInfo>,
64 : /// Whether to retry the connection to the compute node
65 : #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
66 : connect_to_compute_retry: String,
67 : /// Address of the postgres server
68 : #[clap(long, default_value = "127.0.0.1:5432")]
69 : postgres: SocketAddr,
70 : /// Address of the internal compute-ctl api service
71 : #[clap(long, default_value = "http://127.0.0.1:3081/")]
72 : compute_ctl: ApiUrl,
73 : /// Path of the local proxy config file
74 : #[clap(long, default_value = "./local_proxy.json")]
75 : config_path: Utf8PathBuf,
76 : /// Path of the local proxy PID file
77 : #[clap(long, default_value = "./local_proxy.pid")]
78 : pid_path: Utf8PathBuf,
79 : /// Disable pg_session_jwt extension installation
80 : /// This is useful for testing the local proxy with vanilla postgres.
81 : #[clap(long, default_value = "false")]
82 : #[cfg(feature = "testing")]
83 : disable_pg_session_jwt: bool,
84 : }
85 :
86 : #[derive(clap::Args, Clone, Copy, Debug)]
87 : struct SqlOverHttpArgs {
88 : /// How many connections to pool for each endpoint. Excess connections are discarded
89 : #[clap(long, default_value_t = 200)]
90 : sql_over_http_pool_max_total_conns: usize,
91 :
92 : /// How long pooled connections should remain idle for before closing
93 : #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
94 : sql_over_http_idle_timeout: tokio::time::Duration,
95 :
96 : #[clap(long, default_value_t = 100)]
97 : sql_over_http_client_conn_threshold: u64,
98 :
99 : #[clap(long, default_value_t = 16)]
100 : sql_over_http_cancel_set_shards: usize,
101 :
102 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
103 : sql_over_http_max_request_size_bytes: usize,
104 :
105 : #[clap(long, default_value_t = 10 * 1024 * 1024)] // 10 MiB
106 : sql_over_http_max_response_size_bytes: usize,
107 : }
108 :
109 0 : pub async fn run() -> anyhow::Result<()> {
110 0 : let _logging_guard = crate::logging::init_local_proxy()?;
111 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
112 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
113 :
114 0 : Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
115 :
116 : // TODO: refactor these to use labels
117 0 : debug!("Version: {GIT_VERSION}");
118 0 : debug!("Build_tag: {BUILD_TAG}");
119 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
120 0 : revision: GIT_VERSION,
121 0 : build_tag: BUILD_TAG,
122 0 : });
123 :
124 0 : let jemalloc = match crate::jemalloc::MetricRecorder::new() {
125 0 : Ok(t) => Some(t),
126 0 : Err(e) => {
127 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
128 0 : None
129 : }
130 : };
131 :
132 0 : let args = LocalProxyCliArgs::parse();
133 0 : let config = build_config(&args)?;
134 0 : let auth_backend = build_auth_backend(&args);
135 :
136 : // before we bind to any ports, write the process ID to a file
137 : // so that compute-ctl can find our process later
138 : // in order to trigger the appropriate SIGHUP on config change.
139 : //
140 : // This also claims a "lock" that makes sure only one instance
141 : // of local_proxy runs at a time.
142 0 : let _process_guard = loop {
143 0 : match pid_file::claim_for_current_process(&args.pid_path) {
144 0 : Ok(guard) => break guard,
145 0 : Err(e) => {
146 : // compute-ctl might have tried to read the pid-file to let us
147 : // know about some config change. We should try again.
148 0 : error!(path=?args.pid_path, "could not claim PID file guard: {e:?}");
149 0 : tokio::time::sleep(Duration::from_secs(1)).await;
150 : }
151 : }
152 : };
153 :
154 0 : let metrics_listener = TcpListener::bind(args.metrics).await?.into_std()?;
155 0 : let http_listener = TcpListener::bind(args.http).await?;
156 0 : let shutdown = CancellationToken::new();
157 :
158 : // todo: should scale with CU
159 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
160 0 : LeakyBucketConfig {
161 0 : rps: 10.0,
162 0 : max: 100.0,
163 0 : },
164 : 16,
165 : ));
166 :
167 0 : let mut maintenance_tasks = JoinSet::new();
168 :
169 0 : let refresh_config_notify = Arc::new(Notify::new());
170 0 : maintenance_tasks.spawn(crate::signals::handle(shutdown.clone(), {
171 0 : let refresh_config_notify = Arc::clone(&refresh_config_notify);
172 0 : move || {
173 0 : refresh_config_notify.notify_one();
174 0 : }
175 : }));
176 :
177 : // trigger the first config load **after** setting up the signal hook
178 : // to avoid the race condition where:
179 : // 1. No config file registered when local_proxy starts up
180 : // 2. The config file is written but the signal hook is not yet received
181 : // 3. local_proxy completes startup but has no config loaded, despite there being a registerd config.
182 0 : refresh_config_notify.notify_one();
183 0 : tokio::spawn(refresh_config_loop(
184 0 : config,
185 0 : args.config_path,
186 0 : refresh_config_notify,
187 : ));
188 :
189 0 : maintenance_tasks.spawn(crate::http::health_server::task_main(
190 0 : metrics_listener,
191 0 : AppMetrics {
192 0 : jemalloc,
193 0 : neon_metrics,
194 0 : proxy: crate::metrics::Metrics::get(),
195 0 : },
196 : ));
197 :
198 0 : let task = serverless::task_main(
199 0 : config,
200 0 : auth_backend,
201 0 : http_listener,
202 0 : shutdown.clone(),
203 0 : Arc::new(CancellationHandler::new(&config.connect_to_compute)),
204 0 : endpoint_rate_limiter,
205 : );
206 :
207 0 : match futures::future::select(pin!(maintenance_tasks.join_next()), pin!(task)).await {
208 : // exit immediately on maintenance task completion
209 0 : Either::Left((Some(res), _)) => match crate::error::flatten_err(res)? {},
210 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
211 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
212 : // exit immediately on client task error
213 0 : Either::Right((res, _)) => res?,
214 : }
215 :
216 0 : Ok(())
217 0 : }
218 :
219 : /// ProxyConfig is created at proxy startup, and lives forever.
220 0 : fn build_config(args: &LocalProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
221 : let config::ConcurrencyLockOptions {
222 0 : shards,
223 0 : limiter,
224 0 : epoch,
225 0 : timeout,
226 0 : } = args.connect_compute_lock.parse()?;
227 0 : info!(
228 : ?limiter,
229 : shards,
230 : ?epoch,
231 0 : "Using NodeLocks (connect_compute)"
232 : );
233 0 : let connect_compute_locks = ApiLocks::new(
234 : "connect_compute_lock",
235 0 : limiter,
236 0 : shards,
237 0 : timeout,
238 0 : epoch,
239 0 : &Metrics::get().proxy.connect_compute_lock,
240 : );
241 :
242 0 : let http_config = HttpConfig {
243 0 : accept_websockets: false,
244 0 : pool_options: GlobalConnPoolOptions {
245 0 : gc_epoch: Duration::from_secs(60),
246 0 : pool_shards: 2,
247 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
248 0 : opt_in: false,
249 0 :
250 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_total_conns,
251 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
252 0 : },
253 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
254 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
255 0 : max_request_size_bytes: args.sql_over_http.sql_over_http_max_request_size_bytes,
256 0 : max_response_size_bytes: args.sql_over_http.sql_over_http_max_response_size_bytes,
257 0 : };
258 :
259 0 : let compute_config = ComputeConfig {
260 0 : retry: RetryConfig::parse(RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)?,
261 0 : tls: Arc::new(compute_client_config_with_root_certs()?),
262 0 : timeout: Duration::from_secs(2),
263 : };
264 :
265 0 : Ok(Box::leak(Box::new(ProxyConfig {
266 0 : tls_config: ArcSwapOption::from(None),
267 0 : metric_collection: None,
268 0 : http_config,
269 0 : authentication_config: AuthenticationConfig {
270 0 : jwks_cache: JwkCache::default(),
271 0 : thread_pool: ThreadPool::new(0),
272 0 : scram_protocol_timeout: Duration::from_secs(10),
273 0 : ip_allowlist_check_enabled: true,
274 0 : is_vpc_acccess_proxy: false,
275 0 : is_auth_broker: false,
276 0 : accept_jwts: true,
277 0 : console_redirect_confirmation_timeout: Duration::ZERO,
278 0 : },
279 0 : proxy_protocol_v2: config::ProxyProtocolV2::Rejected,
280 0 : handshake_timeout: Duration::from_secs(10),
281 0 : wake_compute_retry_config: RetryConfig::parse(RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)?,
282 0 : connect_compute_locks,
283 0 : connect_to_compute: compute_config,
284 : #[cfg(feature = "testing")]
285 0 : disable_pg_session_jwt: args.disable_pg_session_jwt,
286 : })))
287 0 : }
288 :
289 : /// auth::Backend is created at proxy startup, and lives forever.
290 0 : fn build_auth_backend(args: &LocalProxyCliArgs) -> &'static auth::Backend<'static, ()> {
291 0 : let auth_backend = crate::auth::Backend::Local(crate::auth::backend::MaybeOwned::Owned(
292 0 : LocalBackend::new(args.postgres, args.compute_ctl.clone()),
293 0 : ));
294 :
295 0 : Box::leak(Box::new(auth_backend))
296 0 : }
|