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 camino::Utf8PathBuf;
8 :
9 : use clap::{ArgAction, Parser};
10 : use futures::future::OptionFuture;
11 : use http_utils::tls_certs::ReloadingCertificateResolver;
12 : use hyper0::Uri;
13 : use metrics::BuildInfo;
14 : use metrics::launch_timestamp::LaunchTimestamp;
15 : use pageserver_api::config::PostHogConfig;
16 : use reqwest::Certificate;
17 : use storage_controller::http::make_router;
18 : use storage_controller::metrics::preinitialize_metrics;
19 : use storage_controller::persistence::Persistence;
20 : use storage_controller::service::chaos_injector::ChaosInjector;
21 : use storage_controller::service::feature_flag::FeatureFlagService;
22 : use storage_controller::service::{
23 : Config, HEARTBEAT_INTERVAL_DEFAULT, LONG_RECONCILE_THRESHOLD_DEFAULT,
24 : MAX_OFFLINE_INTERVAL_DEFAULT, MAX_WARMING_UP_INTERVAL_DEFAULT,
25 : PRIORITY_RECONCILER_CONCURRENCY_DEFAULT, RECONCILER_CONCURRENCY_DEFAULT,
26 : SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT, Service,
27 : };
28 : use tokio::signal::unix::SignalKind;
29 : use tokio_util::sync::CancellationToken;
30 : use tracing::Instrument;
31 : use utils::auth::{JwtAuth, SwappableJwtAuth};
32 : use utils::logging::{self, LogFormat};
33 : use utils::sentry_init::init_sentry;
34 : use utils::{project_build_tag, project_git_version, tcp_listener};
35 :
36 : project_git_version!(GIT_VERSION);
37 : project_build_tag!(BUILD_TAG);
38 :
39 : #[global_allocator]
40 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
41 :
42 : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
43 : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
44 : /// performance-sensitive code will avoid allocations as far as possible anyway.
45 : #[allow(non_upper_case_globals)]
46 : #[unsafe(export_name = "malloc_conf")]
47 : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
48 :
49 : const DEFAULT_SSL_KEY_FILE: &str = "server.key";
50 : const DEFAULT_SSL_CERT_FILE: &str = "server.crt";
51 : const DEFAULT_SSL_CERT_RELOAD_PERIOD: &str = "60s";
52 :
53 : #[derive(Parser)]
54 : #[command(author, version, about, long_about = None)]
55 : #[command(arg_required_else_help(true))]
56 : #[clap(group(
57 : clap::ArgGroup::new("listen-addresses")
58 : .required(true)
59 : .multiple(true)
60 : .args(&["listen", "listen_https"]),
61 : ))]
62 : struct Cli {
63 : /// Host and port to listen HTTP on, like `127.0.0.1:1234`.
64 : /// At least one of ["listen", "listen_https"] should be specified.
65 : // TODO: Make this option dev-only when https is out everywhere.
66 : #[arg(short, long)]
67 : listen: Option<std::net::SocketAddr>,
68 : /// Host and port to listen HTTPS on, like `127.0.0.1:1234`.
69 : /// At least one of ["listen", "listen_https"] should be specified.
70 : #[arg(long)]
71 : listen_https: Option<std::net::SocketAddr>,
72 :
73 : /// Public key for JWT authentication of clients
74 : #[arg(long)]
75 : public_key: Option<String>,
76 :
77 : /// Token for authenticating this service with the pageservers it controls
78 : #[arg(long)]
79 : jwt_token: Option<String>,
80 :
81 : /// Token for authenticating this service with the safekeepers it controls
82 : #[arg(long)]
83 : safekeeper_jwt_token: Option<String>,
84 :
85 : /// Token for authenticating this service with the control plane, when calling
86 : /// the compute notification endpoint
87 : #[arg(long)]
88 : control_plane_jwt_token: Option<String>,
89 :
90 : #[arg(long)]
91 : peer_jwt_token: Option<String>,
92 :
93 : /// URL to control plane storage API prefix
94 : #[arg(long)]
95 : control_plane_url: Option<String>,
96 :
97 : /// URL to connect to postgres, like postgresql://localhost:1234/storage_controller
98 : #[arg(long)]
99 : database_url: Option<String>,
100 :
101 : /// Flag to enable dev mode, which permits running without auth
102 : #[arg(long, default_value = "false")]
103 : dev: bool,
104 :
105 : /// Grace period before marking unresponsive pageserver offline
106 : #[arg(long)]
107 : max_offline_interval: Option<humantime::Duration>,
108 :
109 : /// More tolerant grace period before marking unresponsive pagserver offline used
110 : /// around pageserver restarts
111 : #[arg(long)]
112 : max_warming_up_interval: Option<humantime::Duration>,
113 :
114 : /// Size threshold for automatically splitting shards (disabled by default)
115 : #[arg(long)]
116 : split_threshold: Option<u64>,
117 :
118 : /// Maximum number of shards during autosplits. 0 disables autosplits. Defaults
119 : /// to 16 as a safety to avoid too many shards by accident.
120 : #[arg(long, default_value = "16")]
121 : max_split_shards: u8,
122 :
123 : /// Size threshold for initial shard splits of unsharded tenants. 0 disables initial splits.
124 : #[arg(long)]
125 : initial_split_threshold: Option<u64>,
126 :
127 : /// Number of target shards for initial splits. 0 or 1 disables initial splits. Defaults to 2.
128 : #[arg(long, default_value = "2")]
129 : initial_split_shards: u8,
130 :
131 : /// Maximum number of normal-priority reconcilers that may run in parallel
132 : #[arg(long)]
133 : reconciler_concurrency: Option<usize>,
134 :
135 : /// Maximum number of high-priority reconcilers that may run in parallel
136 : #[arg(long)]
137 : priority_reconciler_concurrency: Option<usize>,
138 :
139 : /// Maximum number of safekeeper reconciliations that may run in parallel (per safekeeper)
140 : #[arg(long)]
141 : safekeeper_reconciler_concurrency: Option<usize>,
142 :
143 : /// Tenant API rate limit, as requests per second per tenant.
144 : #[arg(long, default_value = "10")]
145 : tenant_rate_limit: NonZeroU32,
146 :
147 : /// How long to wait for the initial database connection to be available.
148 : #[arg(long, default_value = "5s")]
149 : db_connect_timeout: humantime::Duration,
150 :
151 : #[arg(long, default_value = "false")]
152 : start_as_candidate: bool,
153 :
154 : // TODO: make this mandatory once the helm chart gets updated
155 : #[arg(long)]
156 : address_for_peers: Option<Uri>,
157 :
158 : /// `neon_local` sets this to the path of the neon_local repo dir.
159 : /// Only relevant for testing.
160 : // TODO: make `cfg(feature = "testing")`
161 : #[arg(long)]
162 : neon_local_repo_dir: Option<PathBuf>,
163 :
164 : /// Chaos testing: exercise tenant migrations
165 : #[arg(long)]
166 : chaos_interval: Option<humantime::Duration>,
167 :
168 : /// Chaos testing: exercise an immediate exit
169 : #[arg(long)]
170 : chaos_exit_crontab: Option<cron::Schedule>,
171 :
172 : /// Maximum acceptable lag for the secondary location while draining
173 : /// a pageserver
174 : #[arg(long)]
175 : max_secondary_lag_bytes: Option<u64>,
176 :
177 : /// Period with which to send heartbeats to registered nodes
178 : #[arg(long)]
179 : heartbeat_interval: Option<humantime::Duration>,
180 :
181 : #[arg(long)]
182 : long_reconcile_threshold: Option<humantime::Duration>,
183 :
184 : /// Flag to use https for requests to pageserver API.
185 : #[arg(long, default_value = "false")]
186 : use_https_pageserver_api: bool,
187 :
188 : // Whether to put timelines onto safekeepers
189 : #[arg(long, default_value = "false")]
190 : timelines_onto_safekeepers: bool,
191 :
192 : /// Flag to use https for requests to safekeeper API.
193 : #[arg(long, default_value = "false")]
194 : use_https_safekeeper_api: bool,
195 :
196 : /// Path to a file with certificate's private key for https API.
197 : #[arg(long, default_value = DEFAULT_SSL_KEY_FILE)]
198 : ssl_key_file: Utf8PathBuf,
199 : /// Path to a file with a X509 certificate for https API.
200 : #[arg(long, default_value = DEFAULT_SSL_CERT_FILE)]
201 : ssl_cert_file: Utf8PathBuf,
202 : /// Period to reload certificate and private key from files.
203 : #[arg(long, default_value = DEFAULT_SSL_CERT_RELOAD_PERIOD)]
204 : ssl_cert_reload_period: humantime::Duration,
205 : /// Trusted root CA certificates to use in https APIs.
206 : #[arg(long)]
207 : ssl_ca_file: Option<Utf8PathBuf>,
208 :
209 : /// Neon local specific flag. When set, ignore [`Cli::control_plane_url`] and deliver
210 : /// the compute notification directly (instead of via control plane).
211 : #[arg(long, default_value = "false")]
212 : use_local_compute_notifications: bool,
213 :
214 : /// Number of safekeepers to choose for a timeline when creating it.
215 : /// Safekeepers will be choosen from different availability zones.
216 : /// This option exists primarily for testing purposes.
217 : #[arg(long, default_value = "3", value_parser = clap::builder::RangedU64ValueParser::<usize>::new().range(1..))]
218 : timeline_safekeeper_count: usize,
219 :
220 : /// When set, actively checks and initiates heatmap downloads/uploads during reconciliation.
221 : /// This speed up migrations by avoiding the default wait for the heatmap download interval.
222 : /// Primarily useful for testing to reduce test execution time.
223 : #[arg(long, default_value = "false", action=ArgAction::Set)]
224 : kick_secondary_downloads: bool,
225 :
226 : #[arg(long)]
227 : shard_split_request_timeout: Option<humantime::Duration>,
228 : }
229 :
230 : enum StrictMode {
231 : /// In strict mode, we will require that all secrets are loaded, i.e. security features
232 : /// may not be implicitly turned off by omitting secrets in the environment.
233 : Strict,
234 : /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
235 : /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
236 : /// requests, no public key -> don't authenticate incoming requests).
237 : Dev,
238 : }
239 :
240 : impl Default for StrictMode {
241 0 : fn default() -> Self {
242 0 : Self::Strict
243 0 : }
244 : }
245 :
246 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
247 : /// type encapsulates the logic to decide which and do the loading.
248 : struct Secrets {
249 : database_url: String,
250 : public_key: Option<JwtAuth>,
251 : pageserver_jwt_token: Option<String>,
252 : safekeeper_jwt_token: Option<String>,
253 : control_plane_jwt_token: Option<String>,
254 : peer_jwt_token: Option<String>,
255 : }
256 :
257 : const POSTHOG_CONFIG_ENV: &str = "POSTHOG_CONFIG";
258 :
259 : impl Secrets {
260 : const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
261 : const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
262 : const SAFEKEEPER_JWT_TOKEN_ENV: &'static str = "SAFEKEEPER_JWT_TOKEN";
263 : const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
264 : const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
265 : const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
266 :
267 : /// Load secrets from, in order of preference:
268 : /// - CLI args if database URL is provided on the CLI
269 : /// - Environment variables if DATABASE_URL is set.
270 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
271 0 : let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
272 : else {
273 0 : anyhow::bail!(
274 0 : "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
275 : )
276 : };
277 :
278 0 : let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
279 0 : Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
280 0 : None => None,
281 : };
282 :
283 0 : let this = Self {
284 0 : database_url,
285 0 : public_key,
286 0 : pageserver_jwt_token: Self::load_secret(
287 0 : &args.jwt_token,
288 0 : Self::PAGESERVER_JWT_TOKEN_ENV,
289 0 : ),
290 0 : safekeeper_jwt_token: Self::load_secret(
291 0 : &args.safekeeper_jwt_token,
292 0 : Self::SAFEKEEPER_JWT_TOKEN_ENV,
293 0 : ),
294 0 : control_plane_jwt_token: Self::load_secret(
295 0 : &args.control_plane_jwt_token,
296 0 : Self::CONTROL_PLANE_JWT_TOKEN_ENV,
297 0 : ),
298 0 : peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
299 0 : };
300 :
301 0 : Ok(this)
302 0 : }
303 :
304 0 : fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
305 0 : if let Some(v) = cli {
306 0 : Some(v.clone())
307 : } else {
308 0 : std::env::var(env_name).ok()
309 : }
310 0 : }
311 : }
312 :
313 0 : fn main() -> anyhow::Result<()> {
314 0 : logging::init(
315 0 : LogFormat::Plain,
316 0 : logging::TracingErrorLayerEnablement::Disabled,
317 0 : logging::Output::Stdout,
318 0 : )?;
319 :
320 : // log using tracing so we don't get confused output by default hook writing to stderr
321 0 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
322 :
323 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
324 :
325 0 : let hook = std::panic::take_hook();
326 0 : std::panic::set_hook(Box::new(move |info| {
327 : // let sentry send a message (and flush)
328 : // and trace the error
329 0 : hook(info);
330 :
331 0 : std::process::exit(1);
332 : }));
333 :
334 0 : tokio::runtime::Builder::new_current_thread()
335 0 : // We use spawn_blocking for database operations, so require approximately
336 0 : // as many blocking threads as we will open database connections.
337 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
338 0 : .enable_all()
339 0 : .build()
340 0 : .unwrap()
341 0 : .block_on(async_main())
342 0 : }
343 :
344 0 : async fn async_main() -> anyhow::Result<()> {
345 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
346 :
347 0 : preinitialize_metrics();
348 :
349 0 : let args = Cli::parse();
350 0 : tracing::info!(
351 0 : "version: {}, launch_timestamp: {}, build_tag {}",
352 : GIT_VERSION,
353 0 : launch_ts.to_string(),
354 : BUILD_TAG,
355 : );
356 :
357 0 : let build_info = BuildInfo {
358 0 : revision: GIT_VERSION,
359 0 : build_tag: BUILD_TAG,
360 0 : };
361 :
362 0 : let strict_mode = if args.dev {
363 0 : StrictMode::Dev
364 : } else {
365 0 : StrictMode::Strict
366 : };
367 :
368 0 : let secrets = Secrets::load(&args).await?;
369 :
370 : // Validate required secrets and arguments are provided in strict mode
371 0 : match strict_mode {
372 : StrictMode::Strict
373 0 : if (secrets.public_key.is_none()
374 0 : || secrets.pageserver_jwt_token.is_none()
375 0 : || secrets.control_plane_jwt_token.is_none()
376 0 : || secrets.safekeeper_jwt_token.is_none()) =>
377 : {
378 : // Production systems should always have secrets configured: if public_key was not set
379 : // then we would implicitly disable auth.
380 0 : anyhow::bail!(
381 0 : "Insecure config! One or more secrets is not set. This is only permitted in `--dev` mode"
382 : );
383 : }
384 0 : StrictMode::Strict if args.control_plane_url.is_none() => {
385 : // Production systems should always have a control plane URL set, to prevent falling
386 : // back to trying to use neon_local.
387 0 : anyhow::bail!(
388 0 : "`--control-plane-url` is not set: this is only permitted in `--dev` mode"
389 : );
390 : }
391 0 : StrictMode::Strict if args.use_local_compute_notifications => {
392 0 : anyhow::bail!("`--use-local-compute-notifications` is only permitted in `--dev` mode");
393 : }
394 0 : StrictMode::Strict if args.timeline_safekeeper_count < 3 => {
395 0 : anyhow::bail!(
396 0 : "Running with less than 3 safekeepers per timeline is only permitted in `--dev` mode"
397 : );
398 : }
399 : StrictMode::Strict => {
400 0 : tracing::info!("Starting in strict mode: configuration is OK.")
401 : }
402 : StrictMode::Dev => {
403 0 : tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
404 : }
405 : }
406 :
407 0 : let ssl_ca_certs = match args.ssl_ca_file.as_ref() {
408 0 : Some(ssl_ca_file) => {
409 0 : tracing::info!("Using ssl root CA file: {ssl_ca_file:?}");
410 0 : let buf = tokio::fs::read(ssl_ca_file).await?;
411 0 : Certificate::from_pem_bundle(&buf)?
412 : }
413 0 : None => Vec::new(),
414 : };
415 :
416 0 : let posthog_config = if let Ok(json) = std::env::var(POSTHOG_CONFIG_ENV) {
417 0 : let res: Result<PostHogConfig, _> = serde_json::from_str(&json);
418 0 : if let Ok(config) = res {
419 0 : Some(config)
420 : } else {
421 0 : tracing::warn!("Invalid posthog config: {json}");
422 0 : None
423 : }
424 : } else {
425 0 : None
426 : };
427 :
428 0 : let config = Config {
429 0 : pageserver_jwt_token: secrets.pageserver_jwt_token,
430 0 : safekeeper_jwt_token: secrets.safekeeper_jwt_token,
431 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
432 0 : peer_jwt_token: secrets.peer_jwt_token,
433 0 : control_plane_url: args.control_plane_url,
434 0 : max_offline_interval: args
435 0 : .max_offline_interval
436 0 : .map(humantime::Duration::into)
437 0 : .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
438 0 : max_warming_up_interval: args
439 0 : .max_warming_up_interval
440 0 : .map(humantime::Duration::into)
441 0 : .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
442 0 : reconciler_concurrency: args
443 0 : .reconciler_concurrency
444 0 : .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
445 0 : priority_reconciler_concurrency: args
446 0 : .priority_reconciler_concurrency
447 0 : .unwrap_or(PRIORITY_RECONCILER_CONCURRENCY_DEFAULT),
448 0 : safekeeper_reconciler_concurrency: args
449 0 : .safekeeper_reconciler_concurrency
450 0 : .unwrap_or(SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT),
451 0 : tenant_rate_limit: args.tenant_rate_limit,
452 0 : split_threshold: args.split_threshold,
453 0 : max_split_shards: args.max_split_shards,
454 0 : initial_split_threshold: args.initial_split_threshold,
455 0 : initial_split_shards: args.initial_split_shards,
456 0 : neon_local_repo_dir: args.neon_local_repo_dir,
457 0 : max_secondary_lag_bytes: args.max_secondary_lag_bytes,
458 0 : heartbeat_interval: args
459 0 : .heartbeat_interval
460 0 : .map(humantime::Duration::into)
461 0 : .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
462 0 : long_reconcile_threshold: args
463 0 : .long_reconcile_threshold
464 0 : .map(humantime::Duration::into)
465 0 : .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
466 0 : address_for_peers: args.address_for_peers,
467 0 : start_as_candidate: args.start_as_candidate,
468 0 : use_https_pageserver_api: args.use_https_pageserver_api,
469 0 : use_https_safekeeper_api: args.use_https_safekeeper_api,
470 0 : ssl_ca_certs,
471 0 : timelines_onto_safekeepers: args.timelines_onto_safekeepers,
472 0 : use_local_compute_notifications: args.use_local_compute_notifications,
473 0 : timeline_safekeeper_count: args.timeline_safekeeper_count,
474 0 : posthog_config: posthog_config.clone(),
475 0 : kick_secondary_downloads: args.kick_secondary_downloads,
476 0 : shard_split_request_timeout: args
477 0 : .shard_split_request_timeout
478 0 : .map(humantime::Duration::into)
479 0 : .unwrap_or(Duration::MAX),
480 0 : };
481 :
482 : // Validate that we can connect to the database
483 0 : Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
484 :
485 0 : let persistence = Arc::new(Persistence::new(secrets.database_url).await);
486 :
487 0 : let service = Service::spawn(config, persistence.clone()).await?;
488 :
489 0 : let auth = secrets
490 0 : .public_key
491 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
492 0 : let router = make_router(service.clone(), auth, build_info)
493 0 : .build()
494 0 : .map_err(|err| anyhow!(err))?;
495 0 : let http_service =
496 0 : Arc::new(http_utils::RequestServiceBuilder::new(router).map_err(|err| anyhow!(err))?);
497 :
498 0 : let api_shutdown = CancellationToken::new();
499 :
500 : // Start HTTP server
501 0 : let http_server_task: OptionFuture<_> = match args.listen {
502 0 : Some(http_addr) => {
503 0 : let http_listener = tcp_listener::bind(http_addr)?;
504 0 : let http_server =
505 0 : http_utils::server::Server::new(Arc::clone(&http_service), http_listener, None)?;
506 :
507 0 : tracing::info!("Serving HTTP on {}", http_addr);
508 0 : Some(tokio::task::spawn(http_server.serve(api_shutdown.clone())))
509 : }
510 0 : None => None,
511 : }
512 0 : .into();
513 :
514 : // Start HTTPS server
515 0 : let https_server_task: OptionFuture<_> = match args.listen_https {
516 0 : Some(https_addr) => {
517 0 : let https_listener = tcp_listener::bind(https_addr)?;
518 :
519 0 : let resolver = ReloadingCertificateResolver::new(
520 0 : "main",
521 0 : &args.ssl_key_file,
522 0 : &args.ssl_cert_file,
523 0 : *args.ssl_cert_reload_period,
524 0 : )
525 0 : .await?;
526 :
527 0 : let server_config = rustls::ServerConfig::builder()
528 0 : .with_no_client_auth()
529 0 : .with_cert_resolver(resolver);
530 :
531 0 : let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
532 0 : let https_server =
533 0 : http_utils::server::Server::new(http_service, https_listener, Some(tls_acceptor))?;
534 :
535 0 : tracing::info!("Serving HTTPS on {}", https_addr);
536 0 : Some(tokio::task::spawn(https_server.serve(api_shutdown.clone())))
537 : }
538 0 : None => None,
539 : }
540 0 : .into();
541 :
542 0 : let chaos_task = args.chaos_interval.map(|interval| {
543 0 : let service = service.clone();
544 0 : let cancel = CancellationToken::new();
545 0 : let cancel_bg = cancel.clone();
546 0 : let chaos_exit_crontab = args.chaos_exit_crontab;
547 : (
548 0 : tokio::task::spawn(
549 0 : async move {
550 0 : let mut chaos_injector =
551 0 : ChaosInjector::new(service, interval.into(), chaos_exit_crontab);
552 0 : chaos_injector.run(cancel_bg).await
553 0 : }
554 0 : .instrument(tracing::info_span!("chaos_injector")),
555 : ),
556 0 : cancel,
557 : )
558 0 : });
559 :
560 0 : let feature_flag_task = if let Some(posthog_config) = posthog_config {
561 0 : let service = service.clone();
562 0 : let cancel = CancellationToken::new();
563 0 : let cancel_bg = cancel.clone();
564 0 : let task = tokio::task::spawn(
565 0 : async move {
566 0 : match FeatureFlagService::new(service, posthog_config) {
567 0 : Ok(feature_flag_service) => {
568 0 : let feature_flag_service = Arc::new(feature_flag_service);
569 0 : feature_flag_service.run(cancel_bg).await
570 : }
571 0 : Err(e) => {
572 0 : tracing::warn!("Failed to create feature flag service: {}", e);
573 : }
574 : };
575 0 : }
576 0 : .instrument(tracing::info_span!("feature_flag_service")),
577 : );
578 0 : Some((task, cancel))
579 : } else {
580 0 : None
581 : };
582 :
583 : // Wait until we receive a signal
584 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
585 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
586 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
587 0 : tokio::pin!(http_server_task, https_server_task);
588 0 : tokio::select! {
589 0 : _ = sigint.recv() => {},
590 0 : _ = sigterm.recv() => {},
591 0 : _ = sigquit.recv() => {},
592 0 : Some(err) = &mut http_server_task => {
593 0 : panic!("HTTP server task failed: {err:#?}");
594 : }
595 0 : Some(err) = &mut https_server_task => {
596 0 : panic!("HTTPS server task failed: {err:#?}");
597 : }
598 : }
599 0 : tracing::info!("Terminating on signal");
600 :
601 : // Stop HTTP and HTTPS servers first, so that we don't have to service requests
602 : // while shutting down Service.
603 0 : api_shutdown.cancel();
604 :
605 : // If the deadline is exceeded, we will fall through and shut down the service anyway,
606 : // any request handlers in flight will experience cancellation & their clients will
607 : // see a torn connection.
608 0 : let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
609 :
610 0 : match tokio::time::timeout_at(deadline, http_server_task).await {
611 0 : Ok(Some(Ok(_))) => tracing::info!("Joined HTTP server task"),
612 0 : Ok(Some(Err(e))) => tracing::error!("Error joining HTTP server task: {e}"),
613 0 : Ok(None) => {} // HTTP is disabled.
614 0 : Err(_) => tracing::warn!("Timed out joining HTTP server task"),
615 : }
616 :
617 0 : match tokio::time::timeout_at(deadline, https_server_task).await {
618 0 : Ok(Some(Ok(_))) => tracing::info!("Joined HTTPS server task"),
619 0 : Ok(Some(Err(e))) => tracing::error!("Error joining HTTPS server task: {e}"),
620 0 : Ok(None) => {} // HTTPS is disabled.
621 0 : Err(_) => tracing::warn!("Timed out joining HTTPS server task"),
622 : }
623 :
624 : // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
625 0 : if let Some((chaos_jh, chaos_cancel)) = chaos_task {
626 0 : chaos_cancel.cancel();
627 0 : chaos_jh.await.ok();
628 0 : }
629 :
630 : // If we were running the feature flag service, stop that so that we're not calling into Service while it shuts down
631 0 : if let Some((feature_flag_task, feature_flag_cancel)) = feature_flag_task {
632 0 : feature_flag_cancel.cancel();
633 0 : feature_flag_task.await.ok();
634 0 : }
635 :
636 0 : service.shutdown().await;
637 0 : tracing::info!("Service shutdown complete");
638 :
639 0 : std::process::exit(0);
640 0 : }
|