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 :
227 : enum StrictMode {
228 : /// In strict mode, we will require that all secrets are loaded, i.e. security features
229 : /// may not be implicitly turned off by omitting secrets in the environment.
230 : Strict,
231 : /// In dev mode, secrets are optional, and omitting a particular secret will implicitly
232 : /// disable the auth related to it (e.g. no pageserver jwt key -> send unauthenticated
233 : /// requests, no public key -> don't authenticate incoming requests).
234 : Dev,
235 : }
236 :
237 : impl Default for StrictMode {
238 0 : fn default() -> Self {
239 0 : Self::Strict
240 0 : }
241 : }
242 :
243 : /// Secrets may either be provided on the command line (for testing), or loaded from AWS SecretManager: this
244 : /// type encapsulates the logic to decide which and do the loading.
245 : struct Secrets {
246 : database_url: String,
247 : public_key: Option<JwtAuth>,
248 : pageserver_jwt_token: Option<String>,
249 : safekeeper_jwt_token: Option<String>,
250 : control_plane_jwt_token: Option<String>,
251 : peer_jwt_token: Option<String>,
252 : }
253 :
254 : const POSTHOG_CONFIG_ENV: &str = "POSTHOG_CONFIG";
255 :
256 : impl Secrets {
257 : const DATABASE_URL_ENV: &'static str = "DATABASE_URL";
258 : const PAGESERVER_JWT_TOKEN_ENV: &'static str = "PAGESERVER_JWT_TOKEN";
259 : const SAFEKEEPER_JWT_TOKEN_ENV: &'static str = "SAFEKEEPER_JWT_TOKEN";
260 : const CONTROL_PLANE_JWT_TOKEN_ENV: &'static str = "CONTROL_PLANE_JWT_TOKEN";
261 : const PEER_JWT_TOKEN_ENV: &'static str = "PEER_JWT_TOKEN";
262 : const PUBLIC_KEY_ENV: &'static str = "PUBLIC_KEY";
263 :
264 : /// Load secrets from, in order of preference:
265 : /// - CLI args if database URL is provided on the CLI
266 : /// - Environment variables if DATABASE_URL is set.
267 0 : async fn load(args: &Cli) -> anyhow::Result<Self> {
268 0 : let Some(database_url) = Self::load_secret(&args.database_url, Self::DATABASE_URL_ENV)
269 : else {
270 0 : anyhow::bail!(
271 0 : "Database URL is not set (set `--database-url`, or `DATABASE_URL` environment)"
272 : )
273 : };
274 :
275 0 : let public_key = match Self::load_secret(&args.public_key, Self::PUBLIC_KEY_ENV) {
276 0 : Some(v) => Some(JwtAuth::from_key(v).context("Loading public key")?),
277 0 : None => None,
278 : };
279 :
280 0 : let this = Self {
281 0 : database_url,
282 0 : public_key,
283 0 : pageserver_jwt_token: Self::load_secret(
284 0 : &args.jwt_token,
285 0 : Self::PAGESERVER_JWT_TOKEN_ENV,
286 0 : ),
287 0 : safekeeper_jwt_token: Self::load_secret(
288 0 : &args.safekeeper_jwt_token,
289 0 : Self::SAFEKEEPER_JWT_TOKEN_ENV,
290 0 : ),
291 0 : control_plane_jwt_token: Self::load_secret(
292 0 : &args.control_plane_jwt_token,
293 0 : Self::CONTROL_PLANE_JWT_TOKEN_ENV,
294 0 : ),
295 0 : peer_jwt_token: Self::load_secret(&args.peer_jwt_token, Self::PEER_JWT_TOKEN_ENV),
296 0 : };
297 :
298 0 : Ok(this)
299 0 : }
300 :
301 0 : fn load_secret(cli: &Option<String>, env_name: &str) -> Option<String> {
302 0 : if let Some(v) = cli {
303 0 : Some(v.clone())
304 : } else {
305 0 : std::env::var(env_name).ok()
306 : }
307 0 : }
308 : }
309 :
310 0 : fn main() -> anyhow::Result<()> {
311 0 : logging::init(
312 0 : LogFormat::Plain,
313 0 : logging::TracingErrorLayerEnablement::Disabled,
314 0 : logging::Output::Stdout,
315 0 : )?;
316 :
317 : // log using tracing so we don't get confused output by default hook writing to stderr
318 0 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
319 :
320 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
321 :
322 0 : let hook = std::panic::take_hook();
323 0 : std::panic::set_hook(Box::new(move |info| {
324 : // let sentry send a message (and flush)
325 : // and trace the error
326 0 : hook(info);
327 :
328 0 : std::process::exit(1);
329 : }));
330 :
331 0 : tokio::runtime::Builder::new_current_thread()
332 0 : // We use spawn_blocking for database operations, so require approximately
333 0 : // as many blocking threads as we will open database connections.
334 0 : .max_blocking_threads(Persistence::MAX_CONNECTIONS as usize)
335 0 : .enable_all()
336 0 : .build()
337 0 : .unwrap()
338 0 : .block_on(async_main())
339 0 : }
340 :
341 0 : async fn async_main() -> anyhow::Result<()> {
342 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
343 :
344 0 : preinitialize_metrics();
345 :
346 0 : let args = Cli::parse();
347 0 : tracing::info!(
348 0 : "version: {}, launch_timestamp: {}, build_tag {}",
349 : GIT_VERSION,
350 0 : launch_ts.to_string(),
351 : BUILD_TAG,
352 : );
353 :
354 0 : let build_info = BuildInfo {
355 0 : revision: GIT_VERSION,
356 0 : build_tag: BUILD_TAG,
357 0 : };
358 :
359 0 : let strict_mode = if args.dev {
360 0 : StrictMode::Dev
361 : } else {
362 0 : StrictMode::Strict
363 : };
364 :
365 0 : let secrets = Secrets::load(&args).await?;
366 :
367 : // Validate required secrets and arguments are provided in strict mode
368 0 : match strict_mode {
369 : StrictMode::Strict
370 0 : if (secrets.public_key.is_none()
371 0 : || secrets.pageserver_jwt_token.is_none()
372 0 : || secrets.control_plane_jwt_token.is_none()
373 0 : || secrets.safekeeper_jwt_token.is_none()) =>
374 : {
375 : // Production systems should always have secrets configured: if public_key was not set
376 : // then we would implicitly disable auth.
377 0 : anyhow::bail!(
378 0 : "Insecure config! One or more secrets is not set. This is only permitted in `--dev` mode"
379 : );
380 : }
381 0 : StrictMode::Strict if args.control_plane_url.is_none() => {
382 : // Production systems should always have a control plane URL set, to prevent falling
383 : // back to trying to use neon_local.
384 0 : anyhow::bail!(
385 0 : "`--control-plane-url` is not set: this is only permitted in `--dev` mode"
386 : );
387 : }
388 0 : StrictMode::Strict if args.use_local_compute_notifications => {
389 0 : anyhow::bail!("`--use-local-compute-notifications` is only permitted in `--dev` mode");
390 : }
391 0 : StrictMode::Strict if args.timeline_safekeeper_count < 3 => {
392 0 : anyhow::bail!(
393 0 : "Running with less than 3 safekeepers per timeline is only permitted in `--dev` mode"
394 : );
395 : }
396 : StrictMode::Strict => {
397 0 : tracing::info!("Starting in strict mode: configuration is OK.")
398 : }
399 : StrictMode::Dev => {
400 0 : tracing::warn!("Starting in dev mode: this may be an insecure configuration.")
401 : }
402 : }
403 :
404 0 : let ssl_ca_certs = match args.ssl_ca_file.as_ref() {
405 0 : Some(ssl_ca_file) => {
406 0 : tracing::info!("Using ssl root CA file: {ssl_ca_file:?}");
407 0 : let buf = tokio::fs::read(ssl_ca_file).await?;
408 0 : Certificate::from_pem_bundle(&buf)?
409 : }
410 0 : None => Vec::new(),
411 : };
412 :
413 0 : let posthog_config = if let Ok(json) = std::env::var(POSTHOG_CONFIG_ENV) {
414 0 : let res: Result<PostHogConfig, _> = serde_json::from_str(&json);
415 0 : if let Ok(config) = res {
416 0 : Some(config)
417 : } else {
418 0 : tracing::warn!("Invalid posthog config: {json}");
419 0 : None
420 : }
421 : } else {
422 0 : None
423 : };
424 :
425 0 : let config = Config {
426 0 : pageserver_jwt_token: secrets.pageserver_jwt_token,
427 0 : safekeeper_jwt_token: secrets.safekeeper_jwt_token,
428 0 : control_plane_jwt_token: secrets.control_plane_jwt_token,
429 0 : peer_jwt_token: secrets.peer_jwt_token,
430 0 : control_plane_url: args.control_plane_url,
431 0 : max_offline_interval: args
432 0 : .max_offline_interval
433 0 : .map(humantime::Duration::into)
434 0 : .unwrap_or(MAX_OFFLINE_INTERVAL_DEFAULT),
435 0 : max_warming_up_interval: args
436 0 : .max_warming_up_interval
437 0 : .map(humantime::Duration::into)
438 0 : .unwrap_or(MAX_WARMING_UP_INTERVAL_DEFAULT),
439 0 : reconciler_concurrency: args
440 0 : .reconciler_concurrency
441 0 : .unwrap_or(RECONCILER_CONCURRENCY_DEFAULT),
442 0 : priority_reconciler_concurrency: args
443 0 : .priority_reconciler_concurrency
444 0 : .unwrap_or(PRIORITY_RECONCILER_CONCURRENCY_DEFAULT),
445 0 : safekeeper_reconciler_concurrency: args
446 0 : .safekeeper_reconciler_concurrency
447 0 : .unwrap_or(SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT),
448 0 : tenant_rate_limit: args.tenant_rate_limit,
449 0 : split_threshold: args.split_threshold,
450 0 : max_split_shards: args.max_split_shards,
451 0 : initial_split_threshold: args.initial_split_threshold,
452 0 : initial_split_shards: args.initial_split_shards,
453 0 : neon_local_repo_dir: args.neon_local_repo_dir,
454 0 : max_secondary_lag_bytes: args.max_secondary_lag_bytes,
455 0 : heartbeat_interval: args
456 0 : .heartbeat_interval
457 0 : .map(humantime::Duration::into)
458 0 : .unwrap_or(HEARTBEAT_INTERVAL_DEFAULT),
459 0 : long_reconcile_threshold: args
460 0 : .long_reconcile_threshold
461 0 : .map(humantime::Duration::into)
462 0 : .unwrap_or(LONG_RECONCILE_THRESHOLD_DEFAULT),
463 0 : address_for_peers: args.address_for_peers,
464 0 : start_as_candidate: args.start_as_candidate,
465 0 : use_https_pageserver_api: args.use_https_pageserver_api,
466 0 : use_https_safekeeper_api: args.use_https_safekeeper_api,
467 0 : ssl_ca_certs,
468 0 : timelines_onto_safekeepers: args.timelines_onto_safekeepers,
469 0 : use_local_compute_notifications: args.use_local_compute_notifications,
470 0 : timeline_safekeeper_count: args.timeline_safekeeper_count,
471 0 : posthog_config: posthog_config.clone(),
472 0 : kick_secondary_downloads: args.kick_secondary_downloads,
473 0 : };
474 :
475 : // Validate that we can connect to the database
476 0 : Persistence::await_connection(&secrets.database_url, args.db_connect_timeout.into()).await?;
477 :
478 0 : let persistence = Arc::new(Persistence::new(secrets.database_url).await);
479 :
480 0 : let service = Service::spawn(config, persistence.clone()).await?;
481 :
482 0 : let auth = secrets
483 0 : .public_key
484 0 : .map(|jwt_auth| Arc::new(SwappableJwtAuth::new(jwt_auth)));
485 0 : let router = make_router(service.clone(), auth, build_info)
486 0 : .build()
487 0 : .map_err(|err| anyhow!(err))?;
488 0 : let http_service =
489 0 : Arc::new(http_utils::RequestServiceBuilder::new(router).map_err(|err| anyhow!(err))?);
490 :
491 0 : let api_shutdown = CancellationToken::new();
492 :
493 : // Start HTTP server
494 0 : let http_server_task: OptionFuture<_> = match args.listen {
495 0 : Some(http_addr) => {
496 0 : let http_listener = tcp_listener::bind(http_addr)?;
497 0 : let http_server =
498 0 : http_utils::server::Server::new(Arc::clone(&http_service), http_listener, None)?;
499 :
500 0 : tracing::info!("Serving HTTP on {}", http_addr);
501 0 : Some(tokio::task::spawn(http_server.serve(api_shutdown.clone())))
502 : }
503 0 : None => None,
504 : }
505 0 : .into();
506 :
507 : // Start HTTPS server
508 0 : let https_server_task: OptionFuture<_> = match args.listen_https {
509 0 : Some(https_addr) => {
510 0 : let https_listener = tcp_listener::bind(https_addr)?;
511 :
512 0 : let resolver = ReloadingCertificateResolver::new(
513 0 : "main",
514 0 : &args.ssl_key_file,
515 0 : &args.ssl_cert_file,
516 0 : *args.ssl_cert_reload_period,
517 0 : )
518 0 : .await?;
519 :
520 0 : let server_config = rustls::ServerConfig::builder()
521 0 : .with_no_client_auth()
522 0 : .with_cert_resolver(resolver);
523 :
524 0 : let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
525 0 : let https_server =
526 0 : http_utils::server::Server::new(http_service, https_listener, Some(tls_acceptor))?;
527 :
528 0 : tracing::info!("Serving HTTPS on {}", https_addr);
529 0 : Some(tokio::task::spawn(https_server.serve(api_shutdown.clone())))
530 : }
531 0 : None => None,
532 : }
533 0 : .into();
534 :
535 0 : let chaos_task = args.chaos_interval.map(|interval| {
536 0 : let service = service.clone();
537 0 : let cancel = CancellationToken::new();
538 0 : let cancel_bg = cancel.clone();
539 0 : let chaos_exit_crontab = args.chaos_exit_crontab;
540 : (
541 0 : tokio::task::spawn(
542 0 : async move {
543 0 : let mut chaos_injector =
544 0 : ChaosInjector::new(service, interval.into(), chaos_exit_crontab);
545 0 : chaos_injector.run(cancel_bg).await
546 0 : }
547 0 : .instrument(tracing::info_span!("chaos_injector")),
548 : ),
549 0 : cancel,
550 : )
551 0 : });
552 :
553 0 : let feature_flag_task = if let Some(posthog_config) = posthog_config {
554 0 : let service = service.clone();
555 0 : let cancel = CancellationToken::new();
556 0 : let cancel_bg = cancel.clone();
557 0 : let task = tokio::task::spawn(
558 0 : async move {
559 0 : match FeatureFlagService::new(service, posthog_config) {
560 0 : Ok(feature_flag_service) => {
561 0 : let feature_flag_service = Arc::new(feature_flag_service);
562 0 : feature_flag_service.run(cancel_bg).await
563 : }
564 0 : Err(e) => {
565 0 : tracing::warn!("Failed to create feature flag service: {}", e);
566 : }
567 : };
568 0 : }
569 0 : .instrument(tracing::info_span!("feature_flag_service")),
570 : );
571 0 : Some((task, cancel))
572 : } else {
573 0 : None
574 : };
575 :
576 : // Wait until we receive a signal
577 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt())?;
578 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit())?;
579 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;
580 0 : tokio::pin!(http_server_task, https_server_task);
581 0 : tokio::select! {
582 0 : _ = sigint.recv() => {},
583 0 : _ = sigterm.recv() => {},
584 0 : _ = sigquit.recv() => {},
585 0 : Some(err) = &mut http_server_task => {
586 0 : panic!("HTTP server task failed: {err:#?}");
587 : }
588 0 : Some(err) = &mut https_server_task => {
589 0 : panic!("HTTPS server task failed: {err:#?}");
590 : }
591 : }
592 0 : tracing::info!("Terminating on signal");
593 :
594 : // Stop HTTP and HTTPS servers first, so that we don't have to service requests
595 : // while shutting down Service.
596 0 : api_shutdown.cancel();
597 :
598 : // If the deadline is exceeded, we will fall through and shut down the service anyway,
599 : // any request handlers in flight will experience cancellation & their clients will
600 : // see a torn connection.
601 0 : let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
602 :
603 0 : match tokio::time::timeout_at(deadline, http_server_task).await {
604 0 : Ok(Some(Ok(_))) => tracing::info!("Joined HTTP server task"),
605 0 : Ok(Some(Err(e))) => tracing::error!("Error joining HTTP server task: {e}"),
606 0 : Ok(None) => {} // HTTP is disabled.
607 0 : Err(_) => tracing::warn!("Timed out joining HTTP server task"),
608 : }
609 :
610 0 : match tokio::time::timeout_at(deadline, https_server_task).await {
611 0 : Ok(Some(Ok(_))) => tracing::info!("Joined HTTPS server task"),
612 0 : Ok(Some(Err(e))) => tracing::error!("Error joining HTTPS server task: {e}"),
613 0 : Ok(None) => {} // HTTPS is disabled.
614 0 : Err(_) => tracing::warn!("Timed out joining HTTPS server task"),
615 : }
616 :
617 : // If we were injecting chaos, stop that so that we're not calling into Service while it shuts down
618 0 : if let Some((chaos_jh, chaos_cancel)) = chaos_task {
619 0 : chaos_cancel.cancel();
620 0 : chaos_jh.await.ok();
621 0 : }
622 :
623 : // If we were running the feature flag service, stop that so that we're not calling into Service while it shuts down
624 0 : if let Some((feature_flag_task, feature_flag_cancel)) = feature_flag_task {
625 0 : feature_flag_cancel.cancel();
626 0 : feature_flag_task.await.ok();
627 0 : }
628 :
629 0 : service.shutdown().await;
630 0 : tracing::info!("Service shutdown complete");
631 :
632 0 : std::process::exit(0);
633 0 : }
|