Line data Source code
1 : #![recursion_limit = "300"]
2 :
3 : //! Main entry point for the Page Server executable.
4 :
5 : use std::env;
6 : use std::env::{var, VarError};
7 : use std::io::Read;
8 : use std::str::FromStr;
9 : use std::sync::Arc;
10 : use std::time::Duration;
11 :
12 : use anyhow::{anyhow, Context};
13 : use camino::Utf8Path;
14 : use clap::{Arg, ArgAction, Command};
15 :
16 : use metrics::launch_timestamp::{set_launch_timestamp_metric, LaunchTimestamp};
17 : use pageserver::config::PageserverIdentity;
18 : use pageserver::controller_upcall_client::ControllerUpcallClient;
19 : use pageserver::disk_usage_eviction_task::{self, launch_disk_usage_global_eviction_task};
20 : use pageserver::metrics::{STARTUP_DURATION, STARTUP_IS_LOADING};
21 : use pageserver::task_mgr::{COMPUTE_REQUEST_RUNTIME, WALRECEIVER_RUNTIME};
22 : use pageserver::tenant::{secondary, TenantSharedResources};
23 : use pageserver::{CancellableTask, ConsumptionMetricsTasks, HttpEndpointListener};
24 : use remote_storage::GenericRemoteStorage;
25 : use tokio::signal::unix::SignalKind;
26 : use tokio::time::Instant;
27 : use tokio_util::sync::CancellationToken;
28 : use tracing::*;
29 :
30 : use metrics::set_build_info_metric;
31 : use pageserver::{
32 : config::PageServerConf,
33 : deletion_queue::DeletionQueue,
34 : http, page_cache, page_service, task_mgr,
35 : task_mgr::{BACKGROUND_RUNTIME, MGMT_REQUEST_RUNTIME},
36 : tenant::mgr,
37 : virtual_file,
38 : };
39 : use postgres_backend::AuthType;
40 : use utils::crashsafe::syncfs;
41 : use utils::failpoint_support;
42 : use utils::logging::TracingErrorLayerEnablement;
43 : use utils::{
44 : auth::{JwtAuth, SwappableJwtAuth},
45 : logging, project_build_tag, project_git_version,
46 : sentry_init::init_sentry,
47 : tcp_listener,
48 : };
49 :
50 : project_git_version!(GIT_VERSION);
51 : project_build_tag!(BUILD_TAG);
52 :
53 : #[global_allocator]
54 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
55 :
56 : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
57 : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
58 : /// performance-sensitive code will avoid allocations as far as possible anyway.
59 : #[allow(non_upper_case_globals)]
60 : #[export_name = "malloc_conf"]
61 : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
62 :
63 : const PID_FILE_NAME: &str = "pageserver.pid";
64 :
65 : const FEATURES: &[&str] = &[
66 : #[cfg(feature = "testing")]
67 : "testing",
68 : ];
69 :
70 4 : fn version() -> String {
71 4 : format!(
72 4 : "{GIT_VERSION} failpoints: {}, features: {:?}",
73 4 : fail::has_failpoints(),
74 4 : FEATURES,
75 4 : )
76 4 : }
77 :
78 0 : fn main() -> anyhow::Result<()> {
79 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
80 0 :
81 0 : let arg_matches = cli().get_matches();
82 0 :
83 0 : if arg_matches.get_flag("enabled-features") {
84 0 : println!("{{\"features\": {FEATURES:?} }}");
85 0 : return Ok(());
86 0 : }
87 0 :
88 0 : let workdir = arg_matches
89 0 : .get_one::<String>("workdir")
90 0 : .map(Utf8Path::new)
91 0 : .unwrap_or_else(|| Utf8Path::new(".neon"));
92 0 : let workdir = workdir
93 0 : .canonicalize_utf8()
94 0 : .with_context(|| format!("Error opening workdir '{workdir}'"))?;
95 :
96 0 : let cfg_file_path = workdir.join("pageserver.toml");
97 0 : let identity_file_path = workdir.join("identity.toml");
98 0 :
99 0 : // Set CWD to workdir for non-daemon modes
100 0 : env::set_current_dir(&workdir)
101 0 : .with_context(|| format!("Failed to set application's current dir to '{workdir}'"))?;
102 :
103 0 : let conf = initialize_config(&identity_file_path, &cfg_file_path, &workdir)?;
104 :
105 : // Initialize logging.
106 : //
107 : // It must be initialized before the custom panic hook is installed below.
108 : //
109 : // Regarding tracing_error enablement: at this time, we only use the
110 : // tracing_error crate to debug_assert that log spans contain tenant and timeline ids.
111 : // See `debug_assert_current_span_has_tenant_and_timeline_id` in the timeline module
112 0 : let tracing_error_layer_enablement = if cfg!(debug_assertions) {
113 0 : TracingErrorLayerEnablement::EnableWithRustLogFilter
114 : } else {
115 0 : TracingErrorLayerEnablement::Disabled
116 : };
117 0 : logging::init(
118 0 : conf.log_format,
119 0 : tracing_error_layer_enablement,
120 0 : logging::Output::Stdout,
121 0 : )?;
122 :
123 : // mind the order required here: 1. logging, 2. panic_hook, 3. sentry.
124 : // disarming this hook on pageserver, because we never tear down tracing.
125 0 : logging::replace_panic_hook_with_tracing_panic_hook().forget();
126 0 :
127 0 : // initialize sentry if SENTRY_DSN is provided
128 0 : let _sentry_guard = init_sentry(
129 0 : Some(GIT_VERSION.into()),
130 0 : &[("node_id", &conf.id.to_string())],
131 0 : );
132 0 :
133 0 : // after setting up logging, log the effective IO engine choice and read path implementations
134 0 : info!(?conf.virtual_file_io_engine, "starting with virtual_file IO engine");
135 0 : info!(?conf.virtual_file_io_mode, "starting with virtual_file IO mode");
136 0 : info!(?conf.wal_receiver_protocol, "starting with WAL receiver protocol");
137 0 : info!(?conf.validate_wal_contiguity, "starting with WAL contiguity validation");
138 0 : info!(?conf.page_service_pipelining, "starting with page service pipelining config");
139 0 : info!(?conf.get_vectored_concurrent_io, "starting with get_vectored IO concurrency config");
140 :
141 : // The tenants directory contains all the pageserver local disk state.
142 : // Create if not exists and make sure all the contents are durable before proceeding.
143 : // Ensuring durability eliminates a whole bug class where we come up after an unclean shutdown.
144 : // After unclea shutdown, we don't know if all the filesystem content we can read via syscalls is actually durable or not.
145 : // Examples for that: OOM kill, systemd killing us during shutdown, self abort due to unrecoverable IO error.
146 0 : let tenants_path = conf.tenants_path();
147 0 : {
148 0 : let open = || {
149 0 : nix::dir::Dir::open(
150 0 : tenants_path.as_std_path(),
151 0 : nix::fcntl::OFlag::O_DIRECTORY | nix::fcntl::OFlag::O_RDONLY,
152 0 : nix::sys::stat::Mode::empty(),
153 0 : )
154 0 : };
155 0 : let dirfd = match open() {
156 0 : Ok(dirfd) => dirfd,
157 0 : Err(e) => match e {
158 : nix::errno::Errno::ENOENT => {
159 0 : utils::crashsafe::create_dir_all(&tenants_path).with_context(|| {
160 0 : format!("Failed to create tenants root dir at '{tenants_path}'")
161 0 : })?;
162 0 : open().context("open tenants dir after creating it")?
163 : }
164 0 : e => anyhow::bail!(e),
165 : },
166 : };
167 :
168 0 : if conf.no_sync {
169 0 : info!("Skipping syncfs on startup");
170 : } else {
171 0 : let started = Instant::now();
172 0 : syncfs(dirfd)?;
173 0 : let elapsed = started.elapsed();
174 0 : info!(
175 0 : elapsed_ms = elapsed.as_millis(),
176 0 : "made tenant directory contents durable"
177 : );
178 : }
179 : }
180 :
181 : // Initialize up failpoints support
182 0 : let scenario = failpoint_support::init();
183 0 :
184 0 : // Basic initialization of things that don't change after startup
185 0 : tracing::info!("Initializing virtual_file...");
186 : virtual_file::init(
187 0 : conf.max_file_descriptors,
188 0 : conf.virtual_file_io_engine,
189 0 : conf.virtual_file_io_mode,
190 0 : if conf.no_sync {
191 0 : virtual_file::SyncMode::UnsafeNoSync
192 : } else {
193 0 : virtual_file::SyncMode::Sync
194 : },
195 : );
196 0 : tracing::info!("Initializing page_cache...");
197 0 : page_cache::init(conf.page_cache_size);
198 0 :
199 0 : start_pageserver(launch_ts, conf).context("Failed to start pageserver")?;
200 :
201 0 : scenario.teardown();
202 0 : Ok(())
203 0 : }
204 :
205 0 : fn initialize_config(
206 0 : identity_file_path: &Utf8Path,
207 0 : cfg_file_path: &Utf8Path,
208 0 : workdir: &Utf8Path,
209 0 : ) -> anyhow::Result<&'static PageServerConf> {
210 : // The deployment orchestrator writes out an indentity file containing the node id
211 : // for all pageservers. This file is the source of truth for the node id. In order
212 : // to allow for rolling back pageserver releases, the node id is also included in
213 : // the pageserver config that the deployment orchestrator writes to disk for the pageserver.
214 : // A rolled back version of the pageserver will get the node id from the pageserver.toml
215 : // config file.
216 0 : let identity = match std::fs::File::open(identity_file_path) {
217 0 : Ok(mut f) => {
218 0 : let md = f.metadata().context("stat config file")?;
219 0 : if !md.is_file() {
220 0 : anyhow::bail!("Pageserver found identity file but it is a dir entry: {identity_file_path}. Aborting start up ...");
221 0 : }
222 0 :
223 0 : let mut s = String::new();
224 0 : f.read_to_string(&mut s).context("read identity file")?;
225 0 : toml_edit::de::from_str::<PageserverIdentity>(&s)?
226 : }
227 0 : Err(e) => {
228 0 : anyhow::bail!("Pageserver could not read identity file: {identity_file_path}: {e}. Aborting start up ...");
229 : }
230 : };
231 :
232 0 : let config_file_contents =
233 0 : std::fs::read_to_string(cfg_file_path).context("read config file from filesystem")?;
234 0 : let config_toml = serde_path_to_error::deserialize(
235 0 : toml_edit::de::Deserializer::from_str(&config_file_contents)
236 0 : .context("build toml deserializer")?,
237 : )
238 0 : .context("deserialize config toml")?;
239 0 : let conf = PageServerConf::parse_and_validate(identity.id, config_toml, workdir)
240 0 : .context("runtime-validation of config toml")?;
241 :
242 0 : Ok(Box::leak(Box::new(conf)))
243 0 : }
244 :
245 : struct WaitForPhaseResult<F: std::future::Future + Unpin> {
246 : timeout_remaining: Duration,
247 : skipped: Option<F>,
248 : }
249 :
250 : /// During startup, we apply a timeout to our waits for readiness, to avoid
251 : /// stalling the whole service if one Tenant experiences some problem. Each
252 : /// phase may consume some of the timeout: this function returns the updated
253 : /// timeout for use in the next call.
254 0 : async fn wait_for_phase<F>(phase: &str, mut fut: F, timeout: Duration) -> WaitForPhaseResult<F>
255 0 : where
256 0 : F: std::future::Future + Unpin,
257 0 : {
258 0 : let initial_t = Instant::now();
259 0 : let skipped = match tokio::time::timeout(timeout, &mut fut).await {
260 0 : Ok(_) => None,
261 : Err(_) => {
262 0 : tracing::info!(
263 0 : timeout_millis = timeout.as_millis(),
264 0 : %phase,
265 0 : "Startup phase timed out, proceeding anyway"
266 : );
267 0 : Some(fut)
268 : }
269 : };
270 :
271 0 : WaitForPhaseResult {
272 0 : timeout_remaining: timeout
273 0 : .checked_sub(Instant::now().duration_since(initial_t))
274 0 : .unwrap_or(Duration::ZERO),
275 0 : skipped,
276 0 : }
277 0 : }
278 :
279 0 : fn startup_checkpoint(started_at: Instant, phase: &str, human_phase: &str) {
280 0 : let elapsed = started_at.elapsed();
281 0 : let secs = elapsed.as_secs_f64();
282 0 : STARTUP_DURATION.with_label_values(&[phase]).set(secs);
283 0 :
284 0 : info!(
285 0 : elapsed_ms = elapsed.as_millis(),
286 0 : "{human_phase} ({secs:.3}s since start)"
287 : )
288 0 : }
289 :
290 0 : fn start_pageserver(
291 0 : launch_ts: &'static LaunchTimestamp,
292 0 : conf: &'static PageServerConf,
293 0 : ) -> anyhow::Result<()> {
294 0 : // Monotonic time for later calculating startup duration
295 0 : let started_startup_at = Instant::now();
296 0 :
297 0 : // Print version and launch timestamp to the log,
298 0 : // and expose them as prometheus metrics.
299 0 : // A changed version string indicates changed software.
300 0 : // A changed launch timestamp indicates a pageserver restart.
301 0 : info!(
302 0 : "version: {} launch_timestamp: {} build_tag: {}",
303 0 : version(),
304 0 : launch_ts.to_string(),
305 : BUILD_TAG,
306 : );
307 0 : set_build_info_metric(GIT_VERSION, BUILD_TAG);
308 0 : set_launch_timestamp_metric(launch_ts);
309 0 : #[cfg(target_os = "linux")]
310 0 : metrics::register_internal(Box::new(metrics::more_process_metrics::Collector::new())).unwrap();
311 0 : metrics::register_internal(Box::new(
312 0 : pageserver::metrics::tokio_epoll_uring::Collector::new(),
313 0 : ))
314 0 : .unwrap();
315 0 : pageserver::preinitialize_metrics(conf);
316 0 :
317 0 : // If any failpoints were set from FAILPOINTS environment variable,
318 0 : // print them to the log for debugging purposes
319 0 : let failpoints = fail::list();
320 0 : if !failpoints.is_empty() {
321 0 : info!(
322 0 : "started with failpoints: {}",
323 0 : failpoints
324 0 : .iter()
325 0 : .map(|(name, actions)| format!("{name}={actions}"))
326 0 : .collect::<Vec<String>>()
327 0 : .join(";")
328 : )
329 0 : }
330 :
331 : // Create and lock PID file. This ensures that there cannot be more than one
332 : // pageserver process running at the same time.
333 0 : let lock_file_path = conf.workdir.join(PID_FILE_NAME);
334 0 : info!("Claiming pid file at {lock_file_path:?}...");
335 0 : let lock_file =
336 0 : utils::pid_file::claim_for_current_process(&lock_file_path).context("claim pid file")?;
337 0 : info!("Claimed pid file at {lock_file_path:?}");
338 :
339 : // Ensure that the lock file is held even if the main thread of the process panics.
340 : // We need to release the lock file only when the process exits.
341 0 : std::mem::forget(lock_file);
342 0 :
343 0 : // Bind the HTTP and libpq ports early, so that if they are in use by some other
344 0 : // process, we error out early.
345 0 : let http_addr = &conf.listen_http_addr;
346 0 : info!("Starting pageserver http handler on {http_addr}");
347 0 : let http_listener = tcp_listener::bind(http_addr)?;
348 :
349 0 : let pg_addr = &conf.listen_pg_addr;
350 0 :
351 0 : info!("Starting pageserver pg protocol handler on {pg_addr}");
352 0 : let pageserver_listener = tcp_listener::bind(pg_addr)?;
353 :
354 : // Launch broker client
355 : // The storage_broker::connect call needs to happen inside a tokio runtime thread.
356 0 : let broker_client = WALRECEIVER_RUNTIME
357 0 : .block_on(async {
358 0 : // Note: we do not attempt connecting here (but validate endpoints sanity).
359 0 : storage_broker::connect(conf.broker_endpoint.clone(), conf.broker_keepalive_interval)
360 0 : })
361 0 : .with_context(|| {
362 0 : format!(
363 0 : "create broker client for uri={:?} keepalive_interval={:?}",
364 0 : &conf.broker_endpoint, conf.broker_keepalive_interval,
365 0 : )
366 0 : })?;
367 :
368 : // Initialize authentication for incoming connections
369 : let http_auth;
370 : let pg_auth;
371 0 : if conf.http_auth_type == AuthType::NeonJWT || conf.pg_auth_type == AuthType::NeonJWT {
372 : // unwrap is ok because check is performed when creating config, so path is set and exists
373 0 : let key_path = conf.auth_validation_public_key_path.as_ref().unwrap();
374 0 : info!("Loading public key(s) for verifying JWT tokens from {key_path:?}");
375 :
376 0 : let jwt_auth = JwtAuth::from_key_path(key_path)?;
377 0 : let auth: Arc<SwappableJwtAuth> = Arc::new(SwappableJwtAuth::new(jwt_auth));
378 :
379 0 : http_auth = match &conf.http_auth_type {
380 0 : AuthType::Trust => None,
381 0 : AuthType::NeonJWT => Some(auth.clone()),
382 : };
383 0 : pg_auth = match &conf.pg_auth_type {
384 0 : AuthType::Trust => None,
385 0 : AuthType::NeonJWT => Some(auth),
386 : };
387 0 : } else {
388 0 : http_auth = None;
389 0 : pg_auth = None;
390 0 : }
391 0 : info!("Using auth for http API: {:#?}", conf.http_auth_type);
392 0 : info!("Using auth for pg connections: {:#?}", conf.pg_auth_type);
393 :
394 0 : match var("NEON_AUTH_TOKEN") {
395 0 : Ok(v) => {
396 0 : info!("Loaded JWT token for authentication with Safekeeper");
397 0 : pageserver::config::SAFEKEEPER_AUTH_TOKEN
398 0 : .set(Arc::new(v))
399 0 : .map_err(|_| anyhow!("Could not initialize SAFEKEEPER_AUTH_TOKEN"))?;
400 : }
401 : Err(VarError::NotPresent) => {
402 0 : info!("No JWT token for authentication with Safekeeper detected");
403 : }
404 0 : Err(e) => {
405 0 : return Err(e).with_context(|| {
406 0 : "Failed to either load to detect non-present NEON_AUTH_TOKEN environment variable"
407 0 : })
408 : }
409 : };
410 :
411 : // Top-level cancellation token for the process
412 0 : let shutdown_pageserver = tokio_util::sync::CancellationToken::new();
413 :
414 : // Set up remote storage client
415 0 : let remote_storage = BACKGROUND_RUNTIME.block_on(create_remote_storage_client(conf))?;
416 :
417 : // Set up deletion queue
418 0 : let (deletion_queue, deletion_workers) = DeletionQueue::new(
419 0 : remote_storage.clone(),
420 0 : ControllerUpcallClient::new(conf, &shutdown_pageserver),
421 0 : conf,
422 0 : );
423 0 : deletion_workers.spawn_with(BACKGROUND_RUNTIME.handle());
424 0 :
425 0 : // Up to this point no significant I/O has been done: this should have been fast. Record
426 0 : // duration prior to starting I/O intensive phase of startup.
427 0 : startup_checkpoint(started_startup_at, "initial", "Starting loading tenants");
428 0 : STARTUP_IS_LOADING.set(1);
429 0 :
430 0 : // Startup staging or optimizing:
431 0 : //
432 0 : // We want to minimize downtime for `page_service` connections, and trying not to overload
433 0 : // BACKGROUND_RUNTIME by doing initial compactions and initial logical sizes at the same time.
434 0 : //
435 0 : // init_done_rx will notify when all initial load operations have completed.
436 0 : //
437 0 : // background_jobs_can_start (same name used to hold off background jobs from starting at
438 0 : // consumer side) will be dropped once we can start the background jobs. Currently it is behind
439 0 : // completing all initial logical size calculations (init_logical_size_done_rx) and a timeout
440 0 : // (background_task_maximum_delay).
441 0 : let (init_remote_done_tx, init_remote_done_rx) = utils::completion::channel();
442 0 : let (init_done_tx, init_done_rx) = utils::completion::channel();
443 0 :
444 0 : let (background_jobs_can_start, background_jobs_barrier) = utils::completion::channel();
445 0 :
446 0 : let order = pageserver::InitializationOrder {
447 0 : initial_tenant_load_remote: Some(init_done_tx),
448 0 : initial_tenant_load: Some(init_remote_done_tx),
449 0 : background_jobs_can_start: background_jobs_barrier.clone(),
450 0 : };
451 0 :
452 0 : info!(config=?conf.l0_flush, "using l0_flush config");
453 0 : let l0_flush_global_state =
454 0 : pageserver::l0_flush::L0FlushGlobalState::new(conf.l0_flush.clone());
455 0 :
456 0 : // Scan the local 'tenants/' directory and start loading the tenants
457 0 : let deletion_queue_client = deletion_queue.new_client();
458 0 : let background_purges = mgr::BackgroundPurges::default();
459 0 : let tenant_manager = BACKGROUND_RUNTIME.block_on(mgr::init_tenant_mgr(
460 0 : conf,
461 0 : background_purges.clone(),
462 0 : TenantSharedResources {
463 0 : broker_client: broker_client.clone(),
464 0 : remote_storage: remote_storage.clone(),
465 0 : deletion_queue_client,
466 0 : l0_flush_global_state,
467 0 : },
468 0 : order,
469 0 : shutdown_pageserver.clone(),
470 0 : ))?;
471 0 : let tenant_manager = Arc::new(tenant_manager);
472 0 :
473 0 : BACKGROUND_RUNTIME.spawn({
474 0 : let shutdown_pageserver = shutdown_pageserver.clone();
475 0 : let drive_init = async move {
476 0 : // NOTE: unlike many futures in pageserver, this one is cancellation-safe
477 0 : let guard = scopeguard::guard_on_success((), |_| {
478 0 : tracing::info!("Cancelled before initial load completed")
479 0 : });
480 0 :
481 0 : let timeout = conf.background_task_maximum_delay;
482 0 :
483 0 : let init_remote_done = std::pin::pin!(async {
484 0 : init_remote_done_rx.wait().await;
485 0 : startup_checkpoint(
486 0 : started_startup_at,
487 0 : "initial_tenant_load_remote",
488 0 : "Remote part of initial load completed",
489 0 : );
490 0 : });
491 :
492 : let WaitForPhaseResult {
493 0 : timeout_remaining: timeout,
494 0 : skipped: init_remote_skipped,
495 0 : } = wait_for_phase("initial_tenant_load_remote", init_remote_done, timeout).await;
496 :
497 0 : let init_load_done = std::pin::pin!(async {
498 0 : init_done_rx.wait().await;
499 0 : startup_checkpoint(
500 0 : started_startup_at,
501 0 : "initial_tenant_load",
502 0 : "Initial load completed",
503 0 : );
504 0 : STARTUP_IS_LOADING.set(0);
505 0 : });
506 :
507 : let WaitForPhaseResult {
508 0 : timeout_remaining: _timeout,
509 0 : skipped: init_load_skipped,
510 0 : } = wait_for_phase("initial_tenant_load", init_load_done, timeout).await;
511 :
512 : // initial logical sizes can now start, as they were waiting on init_done_rx.
513 :
514 0 : scopeguard::ScopeGuard::into_inner(guard);
515 0 :
516 0 : // allow background jobs to start: we either completed prior stages, or they reached timeout
517 0 : // and were skipped. It is important that we do not let them block background jobs indefinitely,
518 0 : // because things like consumption metrics for billing are blocked by this barrier.
519 0 : drop(background_jobs_can_start);
520 0 : startup_checkpoint(
521 0 : started_startup_at,
522 0 : "background_jobs_can_start",
523 0 : "Starting background jobs",
524 0 : );
525 0 :
526 0 : // We are done. If we skipped any phases due to timeout, run them to completion here so that
527 0 : // they will eventually update their startup_checkpoint, and so that we do not declare the
528 0 : // 'complete' stage until all the other stages are really done.
529 0 : let guard = scopeguard::guard_on_success((), |_| {
530 0 : tracing::info!("Cancelled before waiting for skipped phases done")
531 0 : });
532 0 : if let Some(f) = init_remote_skipped {
533 0 : f.await;
534 0 : }
535 0 : if let Some(f) = init_load_skipped {
536 0 : f.await;
537 0 : }
538 0 : scopeguard::ScopeGuard::into_inner(guard);
539 0 :
540 0 : startup_checkpoint(started_startup_at, "complete", "Startup complete");
541 0 : };
542 0 :
543 0 : async move {
544 0 : let mut drive_init = std::pin::pin!(drive_init);
545 0 : // just race these tasks
546 0 : tokio::select! {
547 0 : _ = shutdown_pageserver.cancelled() => {},
548 0 : _ = &mut drive_init => {},
549 : }
550 0 : }
551 0 : });
552 0 :
553 0 : let (secondary_controller, secondary_controller_tasks) = secondary::spawn_tasks(
554 0 : tenant_manager.clone(),
555 0 : remote_storage.clone(),
556 0 : background_jobs_barrier.clone(),
557 0 : shutdown_pageserver.clone(),
558 0 : );
559 0 :
560 0 : // shared state between the disk-usage backed eviction background task and the http endpoint
561 0 : // that allows triggering disk-usage based eviction manually. note that the http endpoint
562 0 : // is still accessible even if background task is not configured as long as remote storage has
563 0 : // been configured.
564 0 : let disk_usage_eviction_state: Arc<disk_usage_eviction_task::State> = Arc::default();
565 0 :
566 0 : let disk_usage_eviction_task = launch_disk_usage_global_eviction_task(
567 0 : conf,
568 0 : remote_storage.clone(),
569 0 : disk_usage_eviction_state.clone(),
570 0 : tenant_manager.clone(),
571 0 : background_jobs_barrier.clone(),
572 0 : );
573 :
574 : // Start up the service to handle HTTP mgmt API request. We created the
575 : // listener earlier already.
576 0 : let http_endpoint_listener = {
577 0 : let _rt_guard = MGMT_REQUEST_RUNTIME.enter(); // for hyper
578 0 : let cancel = CancellationToken::new();
579 :
580 0 : let router_state = Arc::new(
581 0 : http::routes::State::new(
582 0 : conf,
583 0 : tenant_manager.clone(),
584 0 : http_auth.clone(),
585 0 : remote_storage.clone(),
586 0 : broker_client.clone(),
587 0 : disk_usage_eviction_state,
588 0 : deletion_queue.new_client(),
589 0 : secondary_controller,
590 0 : )
591 0 : .context("Failed to initialize router state")?,
592 : );
593 0 : let router = http::make_router(router_state, launch_ts, http_auth.clone())?
594 0 : .build()
595 0 : .map_err(|err| anyhow!(err))?;
596 0 : let service = http_utils::RouterService::new(router).unwrap();
597 0 : let server = hyper0::Server::from_tcp(http_listener)?
598 0 : .serve(service)
599 0 : .with_graceful_shutdown({
600 0 : let cancel = cancel.clone();
601 0 : async move { cancel.clone().cancelled().await }
602 0 : });
603 0 :
604 0 : let task = MGMT_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
605 0 : "http endpoint listener",
606 0 : server,
607 0 : ));
608 0 : HttpEndpointListener(CancellableTask { task, cancel })
609 0 : };
610 0 :
611 0 : let consumption_metrics_tasks = {
612 0 : let cancel = shutdown_pageserver.child_token();
613 0 : let task = crate::BACKGROUND_RUNTIME.spawn({
614 0 : let tenant_manager = tenant_manager.clone();
615 0 : let cancel = cancel.clone();
616 0 : async move {
617 0 : // first wait until background jobs are cleared to launch.
618 0 : //
619 0 : // this is because we only process active tenants and timelines, and the
620 0 : // Timeline::get_current_logical_size will spawn the logical size calculation,
621 0 : // which will not be rate-limited.
622 0 : tokio::select! {
623 0 : _ = cancel.cancelled() => { return; },
624 0 : _ = background_jobs_barrier.wait() => {}
625 0 : };
626 0 :
627 0 : pageserver::consumption_metrics::run(conf, tenant_manager, cancel).await;
628 0 : }
629 0 : });
630 0 : ConsumptionMetricsTasks(CancellableTask { task, cancel })
631 : };
632 :
633 : // Spawn a task to listen for libpq connections. It will spawn further tasks
634 : // for each connection. We created the listener earlier already.
635 0 : let page_service = page_service::spawn(conf, tenant_manager.clone(), pg_auth, {
636 0 : let _entered = COMPUTE_REQUEST_RUNTIME.enter(); // TcpListener::from_std requires it
637 0 : pageserver_listener
638 0 : .set_nonblocking(true)
639 0 : .context("set listener to nonblocking")?;
640 0 : tokio::net::TcpListener::from_std(pageserver_listener).context("create tokio listener")?
641 : });
642 :
643 : // All started up! Now just sit and wait for shutdown signal.
644 0 : BACKGROUND_RUNTIME.block_on(async move {
645 0 : let signal_token = CancellationToken::new();
646 0 : let signal_cancel = signal_token.child_token();
647 0 :
648 0 : // Spawn signal handlers. Runs in a loop since we want to be responsive to multiple signals
649 0 : // even after triggering shutdown (e.g. a SIGQUIT after a slow SIGTERM shutdown). See:
650 0 : // https://github.com/neondatabase/neon/issues/9740.
651 0 : tokio::spawn(async move {
652 0 : let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt()).unwrap();
653 0 : let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate()).unwrap();
654 0 : let mut sigquit = tokio::signal::unix::signal(SignalKind::quit()).unwrap();
655 :
656 : loop {
657 0 : let signal = tokio::select! {
658 0 : _ = sigquit.recv() => {
659 0 : info!("Got signal SIGQUIT. Terminating in immediate shutdown mode.");
660 0 : std::process::exit(111);
661 : }
662 0 : _ = sigint.recv() => "SIGINT",
663 0 : _ = sigterm.recv() => "SIGTERM",
664 : };
665 :
666 0 : if !signal_token.is_cancelled() {
667 0 : info!("Got signal {signal}. Terminating gracefully in fast shutdown mode.");
668 0 : signal_token.cancel();
669 : } else {
670 0 : info!("Got signal {signal}. Already shutting down.");
671 : }
672 : }
673 0 : });
674 0 :
675 0 : // Wait for cancellation signal and shut down the pageserver.
676 0 : //
677 0 : // This cancels the `shutdown_pageserver` cancellation tree. Right now that tree doesn't
678 0 : // reach very far, and `task_mgr` is used instead. The plan is to change that over time.
679 0 : signal_cancel.cancelled().await;
680 :
681 0 : shutdown_pageserver.cancel();
682 0 : pageserver::shutdown_pageserver(
683 0 : http_endpoint_listener,
684 0 : page_service,
685 0 : consumption_metrics_tasks,
686 0 : disk_usage_eviction_task,
687 0 : &tenant_manager,
688 0 : background_purges,
689 0 : deletion_queue.clone(),
690 0 : secondary_controller_tasks,
691 0 : 0,
692 0 : )
693 0 : .await;
694 0 : unreachable!();
695 0 : })
696 0 : }
697 :
698 0 : async fn create_remote_storage_client(
699 0 : conf: &'static PageServerConf,
700 0 : ) -> anyhow::Result<GenericRemoteStorage> {
701 0 : let config = if let Some(config) = &conf.remote_storage_config {
702 0 : config
703 : } else {
704 0 : anyhow::bail!("no remote storage configured, this is a deprecated configuration");
705 : };
706 :
707 : // Create the client
708 0 : let mut remote_storage = GenericRemoteStorage::from_config(config).await?;
709 :
710 : // If `test_remote_failures` is non-zero, wrap the client with a
711 : // wrapper that simulates failures.
712 0 : if conf.test_remote_failures > 0 {
713 0 : if !cfg!(feature = "testing") {
714 0 : anyhow::bail!("test_remote_failures option is not available because pageserver was compiled without the 'testing' feature");
715 0 : }
716 0 : info!(
717 0 : "Simulating remote failures for first {} attempts of each op",
718 : conf.test_remote_failures
719 : );
720 0 : remote_storage =
721 0 : GenericRemoteStorage::unreliable_wrapper(remote_storage, conf.test_remote_failures);
722 0 : }
723 :
724 0 : Ok(remote_storage)
725 0 : }
726 :
727 4 : fn cli() -> Command {
728 4 : Command::new("Neon page server")
729 4 : .about("Materializes WAL stream to pages and serves them to the postgres")
730 4 : .version(version())
731 4 : .arg(
732 4 : Arg::new("workdir")
733 4 : .short('D')
734 4 : .long("workdir")
735 4 : .help("Working directory for the pageserver"),
736 4 : )
737 4 : .arg(
738 4 : Arg::new("enabled-features")
739 4 : .long("enabled-features")
740 4 : .action(ArgAction::SetTrue)
741 4 : .help("Show enabled compile time features"),
742 4 : )
743 4 : }
744 :
745 : #[test]
746 4 : fn verify_cli() {
747 4 : cli().debug_assert();
748 4 : }
|