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