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