Line data Source code
1 : use std::{
2 : net::SocketAddr,
3 : path::{Path, PathBuf},
4 : pin::pin,
5 : sync::Arc,
6 : time::Duration,
7 : };
8 :
9 : use anyhow::{bail, ensure};
10 : use dashmap::DashMap;
11 : use futures::{future::Either, FutureExt};
12 : use proxy::{
13 : auth::backend::local::{JwksRoleSettings, LocalBackend, JWKS_ROLE_MAP},
14 : cancellation::CancellationHandlerMain,
15 : config::{self, AuthenticationConfig, HttpConfig, ProxyConfig, RetryConfig},
16 : console::{locks::ApiLocks, messages::JwksRoleMapping},
17 : http::health_server::AppMetrics,
18 : metrics::{Metrics, ThreadPoolMetrics},
19 : rate_limiter::{BucketRateLimiter, EndpointRateLimiter, LeakyBucketConfig, RateBucketInfo},
20 : scram::threadpool::ThreadPool,
21 : serverless::{self, cancel_set::CancelSet, GlobalConnPoolOptions},
22 : };
23 :
24 : project_git_version!(GIT_VERSION);
25 : project_build_tag!(BUILD_TAG);
26 :
27 : use clap::Parser;
28 : use tokio::{net::TcpListener, task::JoinSet};
29 : use tokio_util::sync::CancellationToken;
30 : use tracing::{error, info, warn};
31 : use utils::{project_build_tag, project_git_version, sentry_init::init_sentry};
32 :
33 : #[global_allocator]
34 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
35 :
36 : /// Neon proxy/router
37 0 : #[derive(Parser)]
38 : #[command(version = GIT_VERSION, about)]
39 : struct LocalProxyCliArgs {
40 : /// listen for incoming metrics connections on ip:port
41 : #[clap(long, default_value = "127.0.0.1:7001")]
42 0 : metrics: String,
43 : /// listen for incoming http connections on ip:port
44 : #[clap(long)]
45 0 : http: String,
46 : /// timeout for the TLS handshake
47 : #[clap(long, default_value = "15s", value_parser = humantime::parse_duration)]
48 0 : handshake_timeout: tokio::time::Duration,
49 : /// lock for `connect_compute` api method. example: "shards=32,permits=4,epoch=10m,timeout=1s". (use `permits=0` to disable).
50 : #[clap(long, default_value = config::ConcurrencyLockOptions::DEFAULT_OPTIONS_CONNECT_COMPUTE_LOCK)]
51 0 : connect_compute_lock: String,
52 : #[clap(flatten)]
53 : sql_over_http: SqlOverHttpArgs,
54 : /// User rate limiter max number of requests per second.
55 : ///
56 : /// Provided in the form `<Requests Per Second>@<Bucket Duration Size>`.
57 : /// Can be given multiple times for different bucket sizes.
58 0 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_ENDPOINT_SET)]
59 0 : user_rps_limit: Vec<RateBucketInfo>,
60 : /// Whether the auth rate limiter actually takes effect (for testing)
61 0 : #[clap(long, default_value_t = false, value_parser = clap::builder::BoolishValueParser::new(), action = clap::ArgAction::Set)]
62 0 : auth_rate_limit_enabled: bool,
63 : /// Authentication rate limiter max number of hashes per second.
64 0 : #[clap(long, default_values_t = RateBucketInfo::DEFAULT_AUTH_SET)]
65 0 : auth_rate_limit: Vec<RateBucketInfo>,
66 : /// The IP subnet to use when considering whether two IP addresses are considered the same.
67 0 : #[clap(long, default_value_t = 64)]
68 0 : auth_rate_limit_ip_subnet: u8,
69 : /// Whether to retry the connection to the compute node
70 : #[clap(long, default_value = config::RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES)]
71 0 : connect_to_compute_retry: String,
72 : /// Address of the postgres server
73 : #[clap(long, default_value = "127.0.0.1:5432")]
74 0 : compute: SocketAddr,
75 : /// File address of the local proxy config file
76 : #[clap(long, default_value = "./localproxy.json")]
77 0 : config_path: PathBuf,
78 : }
79 :
80 0 : #[derive(clap::Args, Clone, Copy, Debug)]
81 : struct SqlOverHttpArgs {
82 : /// How many connections to pool for each endpoint. Excess connections are discarded
83 0 : #[clap(long, default_value_t = 200)]
84 0 : sql_over_http_pool_max_total_conns: usize,
85 :
86 : /// How long pooled connections should remain idle for before closing
87 : #[clap(long, default_value = "5m", value_parser = humantime::parse_duration)]
88 0 : sql_over_http_idle_timeout: tokio::time::Duration,
89 :
90 0 : #[clap(long, default_value_t = 100)]
91 0 : sql_over_http_client_conn_threshold: u64,
92 :
93 0 : #[clap(long, default_value_t = 16)]
94 0 : sql_over_http_cancel_set_shards: usize,
95 : }
96 :
97 : #[tokio::main]
98 0 : async fn main() -> anyhow::Result<()> {
99 0 : let _logging_guard = proxy::logging::init().await?;
100 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
101 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
102 0 :
103 0 : Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
104 0 :
105 0 : info!("Version: {GIT_VERSION}");
106 0 : info!("Build_tag: {BUILD_TAG}");
107 0 : let neon_metrics = ::metrics::NeonMetrics::new(::metrics::BuildInfo {
108 0 : revision: GIT_VERSION,
109 0 : build_tag: BUILD_TAG,
110 0 : });
111 0 :
112 0 : let jemalloc = match proxy::jemalloc::MetricRecorder::new() {
113 0 : Ok(t) => Some(t),
114 0 : Err(e) => {
115 0 : tracing::error!(error = ?e, "could not start jemalloc metrics loop");
116 0 : None
117 0 : }
118 0 : };
119 0 :
120 0 : let args = LocalProxyCliArgs::parse();
121 0 : let config = build_config(&args)?;
122 0 :
123 0 : let metrics_listener = TcpListener::bind(args.metrics).await?.into_std()?;
124 0 : let http_listener = TcpListener::bind(args.http).await?;
125 0 : let shutdown = CancellationToken::new();
126 0 :
127 0 : // todo: should scale with CU
128 0 : let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
129 0 : LeakyBucketConfig {
130 0 : rps: 10.0,
131 0 : max: 100.0,
132 0 : },
133 0 : 16,
134 0 : ));
135 0 :
136 0 : refresh_config(args.config_path.clone()).await;
137 0 :
138 0 : let mut maintenance_tasks = JoinSet::new();
139 0 : maintenance_tasks.spawn(proxy::handle_signals(shutdown.clone(), move || {
140 0 : refresh_config(args.config_path.clone()).map(Ok)
141 0 : }));
142 0 : maintenance_tasks.spawn(proxy::http::health_server::task_main(
143 0 : metrics_listener,
144 0 : AppMetrics {
145 0 : jemalloc,
146 0 : neon_metrics,
147 0 : proxy: proxy::metrics::Metrics::get(),
148 0 : },
149 0 : ));
150 0 :
151 0 : let task = serverless::task_main(
152 0 : config,
153 0 : http_listener,
154 0 : shutdown.clone(),
155 0 : Arc::new(CancellationHandlerMain::new(
156 0 : Arc::new(DashMap::new()),
157 0 : None,
158 0 : proxy::metrics::CancellationSource::Local,
159 0 : )),
160 0 : endpoint_rate_limiter,
161 0 : );
162 0 :
163 0 : match futures::future::select(pin!(maintenance_tasks.join_next()), pin!(task)).await {
164 0 : // exit immediately on maintenance task completion
165 0 : Either::Left((Some(res), _)) => match proxy::flatten_err(res)? {},
166 0 : // exit with error immediately if all maintenance tasks have ceased (should be caught by branch above)
167 0 : Either::Left((None, _)) => bail!("no maintenance tasks running. invalid state"),
168 0 : // exit immediately on client task error
169 0 : Either::Right((res, _)) => res?,
170 0 : }
171 0 :
172 0 : Ok(())
173 0 : }
174 :
175 : /// ProxyConfig is created at proxy startup, and lives forever.
176 0 : fn build_config(args: &LocalProxyCliArgs) -> anyhow::Result<&'static ProxyConfig> {
177 : let config::ConcurrencyLockOptions {
178 0 : shards,
179 0 : limiter,
180 0 : epoch,
181 0 : timeout,
182 0 : } = args.connect_compute_lock.parse()?;
183 0 : info!(
184 : ?limiter,
185 : shards,
186 : ?epoch,
187 0 : "Using NodeLocks (connect_compute)"
188 : );
189 0 : let connect_compute_locks = ApiLocks::new(
190 0 : "connect_compute_lock",
191 0 : limiter,
192 0 : shards,
193 0 : timeout,
194 0 : epoch,
195 0 : &Metrics::get().proxy.connect_compute_lock,
196 0 : )?;
197 :
198 0 : let http_config = HttpConfig {
199 0 : accept_websockets: false,
200 0 : pool_options: GlobalConnPoolOptions {
201 0 : gc_epoch: Duration::from_secs(60),
202 0 : pool_shards: 2,
203 0 : idle_timeout: args.sql_over_http.sql_over_http_idle_timeout,
204 0 : opt_in: false,
205 0 :
206 0 : max_conns_per_endpoint: args.sql_over_http.sql_over_http_pool_max_total_conns,
207 0 : max_total_conns: args.sql_over_http.sql_over_http_pool_max_total_conns,
208 0 : },
209 0 : cancel_set: CancelSet::new(args.sql_over_http.sql_over_http_cancel_set_shards),
210 0 : client_conn_threshold: args.sql_over_http.sql_over_http_client_conn_threshold,
211 0 : };
212 0 :
213 0 : Ok(Box::leak(Box::new(ProxyConfig {
214 0 : tls_config: None,
215 0 : auth_backend: proxy::auth::Backend::Local(proxy::auth::backend::MaybeOwned::Owned(
216 0 : LocalBackend::new(args.compute),
217 0 : )),
218 0 : metric_collection: None,
219 0 : allow_self_signed_compute: false,
220 0 : http_config,
221 0 : authentication_config: AuthenticationConfig {
222 0 : thread_pool: ThreadPool::new(0),
223 0 : scram_protocol_timeout: Duration::from_secs(10),
224 0 : rate_limiter_enabled: false,
225 0 : rate_limiter: BucketRateLimiter::new(vec![]),
226 0 : rate_limit_ip_subnet: 64,
227 0 : ip_allowlist_check_enabled: true,
228 0 : },
229 0 : require_client_ip: false,
230 0 : handshake_timeout: Duration::from_secs(10),
231 0 : region: "local".into(),
232 0 : wake_compute_retry_config: RetryConfig::parse(RetryConfig::WAKE_COMPUTE_DEFAULT_VALUES)?,
233 0 : connect_compute_locks,
234 0 : connect_to_compute_retry_config: RetryConfig::parse(
235 0 : RetryConfig::CONNECT_TO_COMPUTE_DEFAULT_VALUES,
236 0 : )?,
237 : })))
238 0 : }
239 :
240 0 : async fn refresh_config(path: PathBuf) {
241 0 : match refresh_config_inner(&path).await {
242 0 : Ok(()) => {}
243 0 : Err(e) => {
244 0 : error!(error=?e, ?path, "could not read config file");
245 : }
246 : }
247 0 : }
248 :
249 0 : async fn refresh_config_inner(path: &Path) -> anyhow::Result<()> {
250 0 : let bytes = tokio::fs::read(&path).await?;
251 0 : let mut data: JwksRoleMapping = serde_json::from_slice(&bytes)?;
252 :
253 0 : let mut settings = None;
254 :
255 0 : for mapping in data.roles.values_mut() {
256 0 : for jwks in &mut mapping.jwks {
257 0 : ensure!(
258 0 : jwks.jwks_url.has_authority()
259 0 : && (jwks.jwks_url.scheme() == "http" || jwks.jwks_url.scheme() == "https"),
260 0 : "Invalid JWKS url. Must be HTTP",
261 : );
262 :
263 0 : ensure!(
264 0 : jwks.jwks_url
265 0 : .host()
266 0 : .is_some_and(|h| h != url::Host::Domain("")),
267 0 : "Invalid JWKS url. No domain listed",
268 : );
269 :
270 : // clear username, password and ports
271 0 : jwks.jwks_url.set_username("").expect(
272 0 : "url can be a base and has a valid host and is not a file. should not error",
273 0 : );
274 0 : jwks.jwks_url.set_password(None).expect(
275 0 : "url can be a base and has a valid host and is not a file. should not error",
276 0 : );
277 0 : // local testing is hard if we need to have a specific restricted port
278 0 : if cfg!(not(feature = "testing")) {
279 0 : jwks.jwks_url.set_port(None).expect(
280 0 : "url can be a base and has a valid host and is not a file. should not error",
281 0 : );
282 0 : }
283 :
284 : // clear query params
285 0 : jwks.jwks_url.set_fragment(None);
286 0 : jwks.jwks_url.query_pairs_mut().clear().finish();
287 0 :
288 0 : if jwks.jwks_url.scheme() != "https" {
289 : // local testing is hard if we need to set up https support.
290 0 : if cfg!(not(feature = "testing")) {
291 0 : jwks.jwks_url
292 0 : .set_scheme("https")
293 0 : .expect("should not error to set the scheme to https if it was http");
294 0 : } else {
295 0 : warn!(scheme = jwks.jwks_url.scheme(), "JWKS url is not HTTPS");
296 : }
297 0 : }
298 :
299 0 : let (pr, br) = settings.get_or_insert((jwks.project_id, jwks.branch_id));
300 0 : ensure!(
301 0 : *pr == jwks.project_id,
302 0 : "inconsistent project IDs configured"
303 : );
304 0 : ensure!(*br == jwks.branch_id, "inconsistent branch IDs configured");
305 : }
306 : }
307 :
308 0 : if let Some((project_id, branch_id)) = settings {
309 0 : JWKS_ROLE_MAP.store(Some(Arc::new(JwksRoleSettings {
310 0 : roles: data.roles,
311 0 : project_id,
312 0 : branch_id,
313 0 : })));
314 0 : }
315 :
316 0 : Ok(())
317 0 : }
|