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