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