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