Line data Source code
1 : use std::num::NonZeroU32;
2 : use std::path::PathBuf;
3 : use std::sync::Arc;
4 : use std::time::Duration;
5 :
6 : use anyhow::{Context, anyhow};
7 : use clap::Parser;
8 : use hyper0::Uri;
9 : use metrics::BuildInfo;
10 : use metrics::launch_timestamp::LaunchTimestamp;
11 : use storage_controller::http::make_router;
12 : use storage_controller::metrics::preinitialize_metrics;
13 : use storage_controller::persistence::Persistence;
14 : use storage_controller::service::chaos_injector::ChaosInjector;
15 : use storage_controller::service::{
16 : Config, HEARTBEAT_INTERVAL_DEFAULT, LONG_RECONCILE_THRESHOLD_DEFAULT,
17 : MAX_OFFLINE_INTERVAL_DEFAULT, MAX_WARMING_UP_INTERVAL_DEFAULT,
18 : PRIORITY_RECONCILER_CONCURRENCY_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT, Service,
19 : };
20 : use tokio::signal::unix::SignalKind;
21 : use tokio_util::sync::CancellationToken;
22 : use tracing::Instrument;
23 : use utils::auth::{JwtAuth, SwappableJwtAuth};
24 : use utils::logging::{self, LogFormat};
25 : use utils::sentry_init::init_sentry;
26 : use utils::{project_build_tag, project_git_version, tcp_listener};
27 :
28 : project_git_version!(GIT_VERSION);
29 : project_build_tag!(BUILD_TAG);
30 :
31 : #[global_allocator]
32 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
33 :
34 : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
35 : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
36 : /// performance-sensitive code will avoid allocations as far as possible anyway.
37 : #[allow(non_upper_case_globals)]
38 : #[unsafe(export_name = "malloc_conf")]
39 : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
40 :
41 : #[derive(Parser)]
42 : #[command(author, version, about, long_about = None)]
43 : #[command(arg_required_else_help(true))]
44 : struct Cli {
45 : /// Host and port to listen on, like `127.0.0.1:1234`
46 : #[arg(short, long)]
47 0 : listen: std::net::SocketAddr,
48 :
49 : /// Public key for JWT authentication of clients
50 : #[arg(long)]
51 : public_key: Option<String>,
52 :
53 : /// Token for authenticating this service with the pageservers it controls
54 : #[arg(long)]
55 : jwt_token: Option<String>,
56 :
57 : /// Token for authenticating this service with the safekeepers it controls
58 : #[arg(long)]
59 : safekeeper_jwt_token: Option<String>,
60 :
61 : /// Token for authenticating this service with the control plane, when calling
62 : /// the compute notification endpoint
63 : #[arg(long)]
64 : control_plane_jwt_token: Option<String>,
65 :
66 : #[arg(long)]
67 : peer_jwt_token: Option<String>,
68 :
69 : /// URL to control plane compute notification endpoint
70 : #[arg(long)]
71 : compute_hook_url: Option<String>,
72 :
73 : /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
74 : #[arg(long)]
75 : database_url: Option<String>,
76 :
77 : /// Flag to enable dev mode, which permits running without auth
78 : #[arg(long, default_value = "false")]
79 0 : dev: bool,
80 :
81 : /// Grace period before marking unresponsive pageserver offline
82 : #[arg(long)]
83 : max_offline_interval: Option<humantime::Duration>,
84 :
85 : /// More tolerant grace period before marking unresponsive pagserver offline used
86 : /// around pageserver restarts
87 : #[arg(long)]
88 : max_warming_up_interval: Option<humantime::Duration>,
89 :
90 : /// Size threshold for automatically splitting shards (disabled by default)
91 : #[arg(long)]
92 : split_threshold: Option<u64>,
93 :
94 : /// Maximum number of normal-priority reconcilers that may run in parallel
95 : #[arg(long)]
96 : reconciler_concurrency: Option<usize>,
97 :
98 : /// Maximum number of high-priority reconcilers that may run in parallel
99 : #[arg(long)]
100 : priority_reconciler_concurrency: Option<usize>,
101 :
102 : /// Tenant API rate limit, as requests per second per tenant.
103 : #[arg(long, default_value = "10")]
104 0 : tenant_rate_limit: NonZeroU32,
105 :
106 : /// How long to wait for the initial database connection to be available.
107 : #[arg(long, default_value = "5s")]
108 0 : db_connect_timeout: humantime::Duration,
109 :
110 : #[arg(long, default_value = "false")]
111 0 : start_as_candidate: bool,
112 :
113 : // TODO: make this mandatory once the helm chart gets updated
114 : #[arg(long)]
115 : address_for_peers: Option<Uri>,
116 :
117 : /// `neon_local` sets this to the path of the neon_local repo dir.
118 : /// Only relevant for testing.
119 : // TODO: make `cfg(feature = "testing")`
120 : #[arg(long)]
121 : neon_local_repo_dir: Option<PathBuf>,
122 :
123 : /// Chaos testing: exercise tenant migrations
124 : #[arg(long)]
125 : chaos_interval: Option<humantime::Duration>,
126 :
127 : /// Chaos testing: exercise an immediate exit
128 : #[arg(long)]
129 : chaos_exit_crontab: Option<cron::Schedule>,
130 :
131 : // Maximum acceptable lag for the secondary location while draining
132 : // a pageserver
133 : #[arg(long)]
134 : max_secondary_lag_bytes: Option<u64>,
135 :
136 : // Period with which to send heartbeats to registered nodes
137 : #[arg(long)]
138 : heartbeat_interval: Option<humantime::Duration>,
139 :
140 : #[arg(long)]
141 : long_reconcile_threshold: Option<humantime::Duration>,
142 :
143 : // Flag to use https for requests to pageserver API.
144 : #[arg(long, default_value = "false")]
145 0 : use_https_pageserver_api: bool,
146 :
147 : /// Whether to load safekeeprs from the database and heartbeat them
148 : #[arg(long, default_value = "false")]
149 0 : load_safekeepers: bool,
150 : }
151 :
152 : enum StrictMode {
153 : /// In strict mode, we will require that all secrets are loaded, i.e. security features
154 : /// may not be implicitly turned off by omitting secrets in the environment.
155 : Strict,
156 : /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
157 : /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
158 : /// requests, no public key -> don't authenticate incoming requests).
159 : Dev,
160 : }
161 :
162 : impl Default for StrictMode {
163 0 : fn default() -> Self {
164 0 : Self::Strict
165 0 : }
166 : }
167 :
168 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
169 : /// type encapsulates the logic to decide which and do the loading.
170 : struct Secrets {
171 : database_url: String,
172 : public_key: Option<JwtAuth>,
173 : pageserver_jwt_token: Option<String>,
174 : safekeeper_jwt_token: Option<String>,
175 : control_plane_jwt_token: Option<String>,
176 : peer_jwt_token: Option<String>,
177 : }
178 :
179 : impl Secrets {
180 : const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
181 : const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
182 : const SAFEKEEPER_JWT_TOKEN_ENV: &'static str = "SAFEKEEPER_JWT_TOKEN";
183 : const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
184 : const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
185 : const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
186 :
187 : /// Load secrets from, in order of preference:
188 : /// - CLI args if database URL is provided on the CLI
189 : /// - Environment variables if DATABASE_URL is set.
190 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
191 0 : let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
192 : else {
193 0 : anyhow::bail!(
194 0 : "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
195 0 : )
196 : };
197 :
198 0 : let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
199 0 : Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
200 0 : None => None,
201 : };
202 :
203 0 : let this = Self {
204 0 : database_url,
205 0 : public_key,
206 0 : pageserver_jwt_token: Self::load_secret(
207 0 : &args.jwt_token,
208 0 : Self::PAGESERVER_JWT_TOKEN_ENV,
209 0 : ),
210 0 : safekeeper_jwt_token: Self::load_secret(
211 0 : &args.safekeeper_jwt_token,
212 0 : Self::SAFEKEEPER_JWT_TOKEN_ENV,
213 0 : ),
214 0 : control_plane_jwt_token: Self::load_secret(
215 0 : &args.control_plane_jwt_token,
216 0 : Self::CONTROL_PLANE_JWT_TOKEN_ENV,
217 0 : ),
218 0 : peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
219 0 : };
220 0 :
221 0 : Ok(this)
222 0 : }
223 :
224 0 : fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
225 0 : if let Some(v) = cli {
226 0 : Some(v.clone())
227 0 : } else if let Ok(v) = std::env::var(env_name) {
228 0 : Some(v)
229 : } else {
230 0 : None
231 : }
232 0 : }
233 : }
234 :
235 0 : fn main() -> anyhow::Result<()> {
236 0 : logging::init(
237 0 : LogFormat::Plain,
238 0 : logging::TracingErrorLayerEnablement::Disabled,
239 0 : logging::Output::Stdout,
240 0 : )?;
241 :
242 : // log using tracing so we don't get confused output by default hook writing to stderr
243 0 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
244 0 :
245 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
246 0 :
247 0 : let hook = std::panic::take_hook();
248 0 : std::panic::set_hook(Box::new(move |info| {
249 0 : // let sentry send a message (and flush)
250 0 : // and trace the error
251 0 : hook(info);
252 0 :
253 0 : std::process::exit(1);
254 0 : }));
255 0 :
256 0 : tokio::runtime::Builder::new_current_thread()
257 0 : // We use spawn_blocking for database operations, so require approximately
258 0 : // as many blocking threads as we will open database connections.
259 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
260 0 : .enable_all()
261 0 : .build()
262 0 : .unwrap()
263 0 : .block_on(async_main())
264 0 : }
265 :
266 0 : async fn async_main() -> anyhow::Result<()> {
267 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
268 0 :
269 0 : preinitialize_metrics();
270 0 :
271 0 : let args = Cli::parse();
272 0 : tracing::info!(
273 0 : "version: {}, launch_timestamp: {}, build_tag {}, listening on {}",
274 0 : GIT_VERSION,
275 0 : launch_ts.to_string(),
276 : BUILD_TAG,
277 : args.listen
278 : );
279 :
280 0 : let build_info = BuildInfo {
281 0 : revision: GIT_VERSION,
282 0 : build_tag: BUILD_TAG,
283 0 : };
284 :
285 0 : let strict_mode = if args.dev {
286 0 : StrictMode::Dev
287 : } else {
288 0 : StrictMode::Strict
289 : };
290 :
291 0 : let secrets = Secrets::load(&args).await?;
292 :
293 : // TODO: once we've rolled out the safekeeper JWT token everywhere, put it into the validation code below
294 0 : tracing::info!(
295 0 : "safekeeper_jwt_token set: {:?}",
296 0 : secrets.safekeeper_jwt_token.is_some()
297 : );
298 :
299 : // Validate required secrets and arguments are provided in strict mode
300 0 : match strict_mode {
301 : StrictMode::Strict
302 0 : if (secrets.public_key.is_none()
303 0 : || secrets.pageserver_jwt_token.is_none()
304 0 : || secrets.control_plane_jwt_token.is_none()) =>
305 0 : {
306 0 : // Production systems should always have secrets configured: if public_key was not set
307 0 : // then we would implicitly disable auth.
308 0 : anyhow::bail!(
309 0 : "Insecure config! One or more secrets is not set. This is only permitted in `--dev` mode"
310 0 : );
311 : }
312 0 : StrictMode::Strict if args.compute_hook_url.is_none() => {
313 0 : // Production systems should always have a compute hook set, to prevent falling
314 0 : // back to trying to use neon_local.
315 0 : anyhow::bail!(
316 0 : "`--compute-hook-url` is not set: this is only permitted in `--dev` mode"
317 0 : );
318 : }
319 : StrictMode::Strict => {
320 0 : tracing::info!("Starting in strict mode: configuration is OK.")
321 : }
322 : StrictMode::Dev => {
323 0 : tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
324 : }
325 : }
326 :
327 0 : let config = Config {
328 0 : pageserver_jwt_token: secrets.pageserver_jwt_token,
329 0 : safekeeper_jwt_token: secrets.safekeeper_jwt_token,
330 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
331 0 : peer_jwt_token: secrets.peer_jwt_token,
332 0 : compute_hook_url: args.compute_hook_url,
333 0 : max_offline_interval: args
334 0 : .max_offline_interval
335 0 : .map(humantime::Duration::into)
336 0 : .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
337 0 : max_warming_up_interval: args
338 0 : .max_warming_up_interval
339 0 : .map(humantime::Duration::into)
340 0 : .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
341 0 : reconciler_concurrency: args
342 0 : .reconciler_concurrency
343 0 : .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
344 0 : priority_reconciler_concurrency: args
345 0 : .priority_reconciler_concurrency
346 0 : .unwrap_or(PRIORITY_RECONCILER_CONCURRENCY_DEFAULT),
347 0 : tenant_rate_limit: args.tenant_rate_limit,
348 0 : split_threshold: args.split_threshold,
349 0 : neon_local_repo_dir: args.neon_local_repo_dir,
350 0 : max_secondary_lag_bytes: args.max_secondary_lag_bytes,
351 0 : heartbeat_interval: args
352 0 : .heartbeat_interval
353 0 : .map(humantime::Duration::into)
354 0 : .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
355 0 : long_reconcile_threshold: args
356 0 : .long_reconcile_threshold
357 0 : .map(humantime::Duration::into)
358 0 : .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
359 0 : address_for_peers: args.address_for_peers,
360 0 : start_as_candidate: args.start_as_candidate,
361 0 : http_service_port: args.listen.port() as i32,
362 0 : use_https_pageserver_api: args.use_https_pageserver_api,
363 0 : load_safekeepers: args.load_safekeepers,
364 0 : };
365 0 :
366 0 : // Validate that we can connect to the database
367 0 : Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
368 :
369 0 : let persistence = Arc::new(Persistence::new(secrets.database_url).await);
370 :
371 0 : let service = Service::spawn(config, persistence.clone()).await?;
372 :
373 0 : let http_listener = tcp_listener::bind(args.listen)?;
374 :
375 0 : let auth = secrets
376 0 : .public_key
377 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
378 0 : let router = make_router(service.clone(), auth, build_info)
379 0 : .build()
380 0 : .map_err(|err| anyhow!(err))?;
381 0 : let router_service = http_utils::RouterService::new(router).unwrap();
382 0 :
383 0 : // Start HTTP server
384 0 : let server_shutdown = CancellationToken::new();
385 0 : let server = hyper0::Server::from_tcp(http_listener)?
386 0 : .serve(router_service)
387 0 : .with_graceful_shutdown({
388 0 : let server_shutdown = server_shutdown.clone();
389 0 : async move {
390 0 : server_shutdown.cancelled().await;
391 0 : }
392 0 : });
393 0 : tracing::info!("Serving on {0}", args.listen);
394 0 : let server_task = tokio::task::spawn(server);
395 0 :
396 0 : let chaos_task = args.chaos_interval.map(|interval| {
397 0 : let service = service.clone();
398 0 : let cancel = CancellationToken::new();
399 0 : let cancel_bg = cancel.clone();
400 0 : let chaos_exit_crontab = args.chaos_exit_crontab;
401 0 : (
402 0 : tokio::task::spawn(
403 0 : async move {
404 0 : let mut chaos_injector =
405 0 : ChaosInjector::new(service, interval.into(), chaos_exit_crontab);
406 0 : chaos_injector.run(cancel_bg).await
407 0 : }
408 0 : .instrument(tracing::info_span!("chaos_injector")),
409 : ),
410 0 : cancel,
411 0 : )
412 0 : });
413 :
414 : // Wait until we receive a signal
415 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
416 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
417 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
418 0 : tokio::select! {
419 0 : _ = sigint.recv() => {},
420 0 : _ = sigterm.recv() => {},
421 0 : _ = sigquit.recv() => {},
422 : }
423 0 : tracing::info!("Terminating on signal");
424 :
425 : // Stop HTTP server first, so that we don't have to service requests
426 : // while shutting down Service.
427 0 : server_shutdown.cancel();
428 0 : match tokio::time::timeout(Duration::from_secs(5), server_task).await {
429 : Ok(Ok(_)) => {
430 0 : tracing::info!("Joined HTTP server task");
431 : }
432 0 : Ok(Err(e)) => {
433 0 : tracing::error!("Error joining HTTP server task: {e}")
434 : }
435 : Err(_) => {
436 0 : tracing::warn!("Timed out joining HTTP server task");
437 : // We will fall through and shut down the service anyway, any request handlers
438 : // in flight will experience cancellation & their clients will see a torn connection.
439 : }
440 : }
441 :
442 : // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
443 0 : if let Some((chaos_jh, chaos_cancel)) = chaos_task {
444 0 : chaos_cancel.cancel();
445 0 : chaos_jh.await.ok();
446 0 : }
447 :
448 0 : service.shutdown().await;
449 0 : tracing::info!("Service shutdown complete");
450 :
451 0 : std::process::exit(0);
452 0 : }
|