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