Line data Source code
1 : //! Functions for handling page server configuration options
2 : //!
3 : //! Configuration options can be set in the pageserver.toml configuration
4 : //! file, or on the command line.
5 : //! See also `settings.md` for better description on every parameter.
6 :
7 : pub mod ignored_fields;
8 :
9 : use std::env;
10 : use std::num::NonZeroUsize;
11 : use std::sync::Arc;
12 : use std::time::Duration;
13 :
14 : use anyhow::{Context, bail, ensure};
15 : use camino::{Utf8Path, Utf8PathBuf};
16 : use once_cell::sync::OnceCell;
17 : use pageserver_api::config::{DiskUsageEvictionTaskConfig, MaxVectoredReadBytes};
18 : use pageserver_api::models::ImageCompressionAlgorithm;
19 : use pageserver_api::shard::TenantShardId;
20 : use pem::Pem;
21 : use postgres_backend::AuthType;
22 : use remote_storage::{RemotePath, RemoteStorageConfig};
23 : use reqwest::Url;
24 : use storage_broker::Uri;
25 : use utils::id::{NodeId, TimelineId};
26 : use utils::logging::{LogFormat, SecretString};
27 : use utils::postgres_client::PostgresClientProtocol;
28 :
29 : use crate::tenant::storage_layer::inmemory_layer::IndexEntry;
30 : use crate::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME};
31 : use crate::virtual_file::io_engine;
32 : use crate::{TENANT_HEATMAP_BASENAME, TENANT_LOCATION_CONFIG_NAME, virtual_file};
33 :
34 : /// Global state of pageserver.
35 : ///
36 : /// It's mostly immutable configuration, but some semaphores and the
37 : /// like crept in over time and the name stuck.
38 : ///
39 : /// Instantiated by deserializing `pageserver.toml` into [`pageserver_api::config::ConfigToml`]
40 : /// and passing that to [`PageServerConf::parse_and_validate`].
41 : ///
42 : /// # Adding a New Field
43 : ///
44 : /// 1. Add the field to `pageserver_api::config::ConfigToml`.
45 : /// 2. Fix compiler errors (exhaustive destructuring will guide you).
46 : ///
47 : /// For fields that require additional validation or filling in of defaults at runtime,
48 : /// check for examples in the [`PageServerConf::parse_and_validate`] method.
49 : #[derive(Debug, Clone)]
50 : pub struct PageServerConf {
51 : // Identifier of that particular pageserver so e g safekeepers
52 : // can safely distinguish different pageservers
53 : pub id: NodeId,
54 :
55 : /// Example (default): 127.0.0.1:64000
56 : pub listen_pg_addr: String,
57 : /// Example (default): 127.0.0.1:9898
58 : pub listen_http_addr: String,
59 : /// Example: 127.0.0.1:9899
60 : pub listen_https_addr: Option<String>,
61 :
62 : /// Path to a file with certificate's private key for https API.
63 : /// Default: server.key
64 : pub ssl_key_file: Utf8PathBuf,
65 : /// Path to a file with a X509 certificate for https API.
66 : /// Default: server.crt
67 : pub ssl_cert_file: Utf8PathBuf,
68 : /// Period to reload certificate and private key from files.
69 : /// Default: 60s.
70 : pub ssl_cert_reload_period: Duration,
71 : /// Trusted root CA certificates to use in https APIs in PEM format.
72 : pub ssl_ca_certs: Vec<Pem>,
73 :
74 : /// Current availability zone. Used for traffic metrics.
75 : pub availability_zone: Option<String>,
76 :
77 : // Timeout when waiting for WAL receiver to catch up to an LSN given in a GetPage@LSN call.
78 : pub wait_lsn_timeout: Duration,
79 : // How long to wait for WAL redo to complete.
80 : pub wal_redo_timeout: Duration,
81 :
82 : pub superuser: String,
83 : pub locale: String,
84 :
85 : pub page_cache_size: usize,
86 : pub max_file_descriptors: usize,
87 :
88 : // Repository directory, relative to current working directory.
89 : // Normally, the page server changes the current working directory
90 : // to the repository, and 'workdir' is always '.'. But we don't do
91 : // that during unit testing, because the current directory is global
92 : // to the process but different unit tests work on different
93 : // repositories.
94 : pub workdir: Utf8PathBuf,
95 :
96 : pub pg_distrib_dir: Utf8PathBuf,
97 :
98 : // Authentication
99 : /// authentication method for the HTTP mgmt API
100 : pub http_auth_type: AuthType,
101 : /// authentication method for libpq connections from compute
102 : pub pg_auth_type: AuthType,
103 : /// Path to a file or directory containing public key(s) for verifying JWT tokens.
104 : /// Used for both mgmt and compute auth, if enabled.
105 : pub auth_validation_public_key_path: Option<Utf8PathBuf>,
106 :
107 : pub remote_storage_config: Option<RemoteStorageConfig>,
108 :
109 : pub default_tenant_conf: pageserver_api::config::TenantConfigToml,
110 :
111 : /// Storage broker endpoints to connect to.
112 : pub broker_endpoint: Uri,
113 : pub broker_keepalive_interval: Duration,
114 :
115 : pub log_format: LogFormat,
116 :
117 : /// Number of tenants which will be concurrently loaded from remote storage proactively on startup or attach.
118 : ///
119 : /// A lower value implicitly deprioritizes loading such tenants, vs. other work in the system.
120 : pub concurrent_tenant_warmup: ConfigurableSemaphore,
121 :
122 : /// Number of concurrent [`TenantShard::gather_size_inputs`](crate::tenant::TenantShard::gather_size_inputs) allowed.
123 : pub concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore,
124 : /// Limit of concurrent [`TenantShard::gather_size_inputs`] issued by module `eviction_task`.
125 : /// The number of permits is the same as `concurrent_tenant_size_logical_size_queries`.
126 : /// See the comment in `eviction_task` for details.
127 : ///
128 : /// [`TenantShard::gather_size_inputs`]: crate::tenant::TenantShard::gather_size_inputs
129 : pub eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore,
130 :
131 : // How often to collect metrics and send them to the metrics endpoint.
132 : pub metric_collection_interval: Duration,
133 : // How often to send unchanged cached metrics to the metrics endpoint.
134 : pub metric_collection_endpoint: Option<Url>,
135 : pub metric_collection_bucket: Option<RemoteStorageConfig>,
136 : pub synthetic_size_calculation_interval: Duration,
137 :
138 : pub disk_usage_based_eviction: Option<DiskUsageEvictionTaskConfig>,
139 :
140 : pub test_remote_failures: u64,
141 :
142 : pub ondemand_download_behavior_treat_error_as_warn: bool,
143 :
144 : /// How long will background tasks be delayed at most after initial load of tenants.
145 : ///
146 : /// Our largest initialization completions are in the range of 100-200s, so perhaps 10s works
147 : /// as we now isolate initial loading, initial logical size calculation and background tasks.
148 : /// Smaller nodes will have background tasks "not running" for this long unless every timeline
149 : /// has it's initial logical size calculated. Not running background tasks for some seconds is
150 : /// not terrible.
151 : pub background_task_maximum_delay: Duration,
152 :
153 : pub control_plane_api: Option<Url>,
154 :
155 : /// JWT token for use with the control plane API.
156 : pub control_plane_api_token: Option<SecretString>,
157 :
158 : pub import_pgdata_upcall_api: Option<Url>,
159 : pub import_pgdata_upcall_api_token: Option<SecretString>,
160 : pub import_pgdata_aws_endpoint_url: Option<Url>,
161 :
162 : /// If true, pageserver will make best-effort to operate without a control plane: only
163 : /// for use in major incidents.
164 : pub control_plane_emergency_mode: bool,
165 :
166 : /// How many heatmap uploads may be done concurrency: lower values implicitly deprioritize
167 : /// heatmap uploads vs. other remote storage operations.
168 : pub heatmap_upload_concurrency: usize,
169 :
170 : /// How many remote storage downloads may be done for secondary tenants concurrently. Implicitly
171 : /// deprioritises secondary downloads vs. remote storage operations for attached tenants.
172 : pub secondary_download_concurrency: usize,
173 :
174 : /// Maximum number of WAL records to be ingested and committed at the same time
175 : pub ingest_batch_size: u64,
176 :
177 : pub virtual_file_io_engine: virtual_file::IoEngineKind,
178 :
179 : pub max_vectored_read_bytes: MaxVectoredReadBytes,
180 :
181 : pub image_compression: ImageCompressionAlgorithm,
182 :
183 : /// Whether to offload archived timelines automatically
184 : pub timeline_offloading: bool,
185 :
186 : /// How many bytes of ephemeral layer content will we allow per kilobyte of RAM. When this
187 : /// is exceeded, we start proactively closing ephemeral layers to limit the total amount
188 : /// of ephemeral data.
189 : ///
190 : /// Setting this to zero disables limits on total ephemeral layer size.
191 : pub ephemeral_bytes_per_memory_kb: usize,
192 :
193 : pub l0_flush: crate::l0_flush::L0FlushConfig,
194 :
195 : /// Direct IO settings
196 : pub virtual_file_io_mode: virtual_file::IoMode,
197 :
198 : /// Optionally disable disk syncs (unsafe!)
199 : pub no_sync: bool,
200 :
201 : pub wal_receiver_protocol: PostgresClientProtocol,
202 :
203 : pub page_service_pipelining: pageserver_api::config::PageServicePipeliningConfig,
204 :
205 : pub get_vectored_concurrent_io: pageserver_api::config::GetVectoredConcurrentIo,
206 :
207 : /// Enable read path debugging. If enabled, read key errors will print a backtrace of the layer
208 : /// files read.
209 : pub enable_read_path_debugging: bool,
210 :
211 : /// Interpreted protocol feature: if enabled, validate that the logical WAL received from
212 : /// safekeepers does not have gaps.
213 : pub validate_wal_contiguity: bool,
214 :
215 : /// When set, the previously written to disk heatmap is loaded on tenant attach and used
216 : /// to avoid clobbering the heatmap from new, cold, attached locations.
217 : pub load_previous_heatmap: bool,
218 :
219 : /// When set, include visible layers in the next uploaded heatmaps of an unarchived timeline.
220 : pub generate_unarchival_heatmap: bool,
221 :
222 : pub tracing: Option<pageserver_api::config::Tracing>,
223 :
224 : /// Enable TLS in page service API.
225 : /// Does not force TLS: the client negotiates TLS usage during the handshake.
226 : /// Uses key and certificate from ssl_key_file/ssl_cert_file.
227 : pub enable_tls_page_service_api: bool,
228 : }
229 :
230 : /// Token for authentication to safekeepers
231 : ///
232 : /// We do not want to store this in a PageServerConf because the latter may be logged
233 : /// and/or serialized at a whim, while the token is secret. Currently this token is the
234 : /// same for accessing all tenants/timelines, but may become per-tenant/per-timeline in
235 : /// the future, more tokens and auth may arrive for storage broker, completely changing the logic.
236 : /// Hence, we resort to a global variable for now instead of passing the token from the
237 : /// startup code to the connection code through a dozen layers.
238 : pub static SAFEKEEPER_AUTH_TOKEN: OnceCell<Arc<String>> = OnceCell::new();
239 :
240 : impl PageServerConf {
241 : //
242 : // Repository paths, relative to workdir.
243 : //
244 :
245 47136 : pub fn tenants_path(&self) -> Utf8PathBuf {
246 47136 : self.workdir.join(TENANTS_SEGMENT_NAME)
247 47136 : }
248 :
249 432 : pub fn deletion_prefix(&self) -> Utf8PathBuf {
250 432 : self.workdir.join("deletion")
251 432 : }
252 :
253 0 : pub fn metadata_path(&self) -> Utf8PathBuf {
254 0 : self.workdir.join("metadata.json")
255 0 : }
256 :
257 168 : pub fn deletion_list_path(&self, sequence: u64) -> Utf8PathBuf {
258 : // Encode a version in the filename, so that if we ever switch away from JSON we can
259 : // increment this.
260 : const VERSION: u8 = 1;
261 :
262 168 : self.deletion_prefix()
263 168 : .join(format!("{sequence:016x}-{VERSION:02x}.list"))
264 168 : }
265 :
266 144 : pub fn deletion_header_path(&self) -> Utf8PathBuf {
267 : // Encode a version in the filename, so that if we ever switch away from JSON we can
268 : // increment this.
269 : const VERSION: u8 = 1;
270 :
271 144 : self.deletion_prefix().join(format!("header-{VERSION:02x}"))
272 144 : }
273 :
274 46812 : pub fn tenant_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
275 46812 : self.tenants_path().join(tenant_shard_id.to_string())
276 46812 : }
277 :
278 : /// Points to a place in pageserver's local directory,
279 : /// where certain tenant's LocationConf be stored.
280 0 : pub(crate) fn tenant_location_config_path(
281 0 : &self,
282 0 : tenant_shard_id: &TenantShardId,
283 0 : ) -> Utf8PathBuf {
284 0 : self.tenant_path(tenant_shard_id)
285 0 : .join(TENANT_LOCATION_CONFIG_NAME)
286 0 : }
287 :
288 1392 : pub(crate) fn tenant_heatmap_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
289 1392 : self.tenant_path(tenant_shard_id)
290 1392 : .join(TENANT_HEATMAP_BASENAME)
291 1392 : }
292 :
293 43992 : pub fn timelines_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
294 43992 : self.tenant_path(tenant_shard_id)
295 43992 : .join(TIMELINES_SEGMENT_NAME)
296 43992 : }
297 :
298 41172 : pub fn timeline_path(
299 41172 : &self,
300 41172 : tenant_shard_id: &TenantShardId,
301 41172 : timeline_id: &TimelineId,
302 41172 : ) -> Utf8PathBuf {
303 41172 : self.timelines_path(tenant_shard_id)
304 41172 : .join(timeline_id.to_string())
305 41172 : }
306 :
307 : /// Turns storage remote path of a file into its local path.
308 0 : pub fn local_path(&self, remote_path: &RemotePath) -> Utf8PathBuf {
309 0 : remote_path.with_base(&self.workdir)
310 0 : }
311 :
312 : //
313 : // Postgres distribution paths
314 : //
315 144 : pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
316 144 : let path = self.pg_distrib_dir.clone();
317 144 :
318 144 : #[allow(clippy::manual_range_patterns)]
319 144 : match pg_version {
320 144 : 14 | 15 | 16 | 17 => Ok(path.join(format!("v{pg_version}"))),
321 0 : _ => bail!("Unsupported postgres version: {}", pg_version),
322 : }
323 144 : }
324 :
325 72 : pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
326 72 : Ok(self.pg_distrib_dir(pg_version)?.join("bin"))
327 72 : }
328 72 : pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
329 72 : Ok(self.pg_distrib_dir(pg_version)?.join("lib"))
330 72 : }
331 :
332 : /// Parse a configuration file (pageserver.toml) into a PageServerConf struct,
333 : /// validating the input and failing on errors.
334 : ///
335 : /// This leaves any options not present in the file in the built-in defaults.
336 1500 : pub fn parse_and_validate(
337 1500 : id: NodeId,
338 1500 : config_toml: pageserver_api::config::ConfigToml,
339 1500 : workdir: &Utf8Path,
340 1500 : ) -> anyhow::Result<Self> {
341 1500 : let pageserver_api::config::ConfigToml {
342 1500 : listen_pg_addr,
343 1500 : listen_http_addr,
344 1500 : listen_https_addr,
345 1500 : ssl_key_file,
346 1500 : ssl_cert_file,
347 1500 : ssl_cert_reload_period,
348 1500 : ssl_ca_file,
349 1500 : availability_zone,
350 1500 : wait_lsn_timeout,
351 1500 : wal_redo_timeout,
352 1500 : superuser,
353 1500 : locale,
354 1500 : page_cache_size,
355 1500 : max_file_descriptors,
356 1500 : pg_distrib_dir,
357 1500 : http_auth_type,
358 1500 : pg_auth_type,
359 1500 : auth_validation_public_key_path,
360 1500 : remote_storage,
361 1500 : broker_endpoint,
362 1500 : broker_keepalive_interval,
363 1500 : log_format,
364 1500 : metric_collection_interval,
365 1500 : metric_collection_endpoint,
366 1500 : metric_collection_bucket,
367 1500 : synthetic_size_calculation_interval,
368 1500 : disk_usage_based_eviction,
369 1500 : test_remote_failures,
370 1500 : ondemand_download_behavior_treat_error_as_warn,
371 1500 : background_task_maximum_delay,
372 1500 : control_plane_api,
373 1500 : control_plane_api_token,
374 1500 : control_plane_emergency_mode,
375 1500 : import_pgdata_upcall_api,
376 1500 : import_pgdata_upcall_api_token,
377 1500 : import_pgdata_aws_endpoint_url,
378 1500 : heatmap_upload_concurrency,
379 1500 : secondary_download_concurrency,
380 1500 : ingest_batch_size,
381 1500 : max_vectored_read_bytes,
382 1500 : image_compression,
383 1500 : timeline_offloading,
384 1500 : ephemeral_bytes_per_memory_kb,
385 1500 : l0_flush,
386 1500 : virtual_file_io_mode,
387 1500 : concurrent_tenant_warmup,
388 1500 : concurrent_tenant_size_logical_size_queries,
389 1500 : virtual_file_io_engine,
390 1500 : tenant_config,
391 1500 : no_sync,
392 1500 : wal_receiver_protocol,
393 1500 : page_service_pipelining,
394 1500 : get_vectored_concurrent_io,
395 1500 : enable_read_path_debugging,
396 1500 : validate_wal_contiguity,
397 1500 : load_previous_heatmap,
398 1500 : generate_unarchival_heatmap,
399 1500 : tracing,
400 1500 : enable_tls_page_service_api,
401 1500 : } = config_toml;
402 :
403 1500 : let mut conf = PageServerConf {
404 : // ------------------------------------------------------------
405 : // fields that are already fully validated by the ConfigToml Deserialize impl
406 : // ------------------------------------------------------------
407 1500 : listen_pg_addr,
408 1500 : listen_http_addr,
409 1500 : listen_https_addr,
410 1500 : ssl_key_file,
411 1500 : ssl_cert_file,
412 1500 : ssl_cert_reload_period,
413 1500 : availability_zone,
414 1500 : wait_lsn_timeout,
415 1500 : wal_redo_timeout,
416 1500 : superuser,
417 1500 : locale,
418 1500 : page_cache_size,
419 1500 : max_file_descriptors,
420 1500 : http_auth_type,
421 1500 : pg_auth_type,
422 1500 : auth_validation_public_key_path,
423 1500 : remote_storage_config: remote_storage,
424 1500 : broker_endpoint,
425 1500 : broker_keepalive_interval,
426 1500 : log_format,
427 1500 : metric_collection_interval,
428 1500 : metric_collection_endpoint,
429 1500 : metric_collection_bucket,
430 1500 : synthetic_size_calculation_interval,
431 1500 : disk_usage_based_eviction,
432 1500 : test_remote_failures,
433 1500 : ondemand_download_behavior_treat_error_as_warn,
434 1500 : background_task_maximum_delay,
435 1500 : control_plane_api,
436 1500 : control_plane_emergency_mode,
437 1500 : heatmap_upload_concurrency,
438 1500 : secondary_download_concurrency,
439 1500 : ingest_batch_size,
440 1500 : max_vectored_read_bytes,
441 1500 : image_compression,
442 1500 : timeline_offloading,
443 1500 : ephemeral_bytes_per_memory_kb,
444 1500 : import_pgdata_upcall_api,
445 1500 : import_pgdata_upcall_api_token: import_pgdata_upcall_api_token.map(SecretString::from),
446 1500 : import_pgdata_aws_endpoint_url,
447 1500 : wal_receiver_protocol,
448 1500 : page_service_pipelining,
449 1500 : get_vectored_concurrent_io,
450 1500 : tracing,
451 1500 : enable_tls_page_service_api,
452 1500 :
453 1500 : // ------------------------------------------------------------
454 1500 : // fields that require additional validation or custom handling
455 1500 : // ------------------------------------------------------------
456 1500 : workdir: workdir.to_owned(),
457 1500 : pg_distrib_dir: pg_distrib_dir.unwrap_or_else(|| {
458 12 : std::env::current_dir()
459 12 : .expect("current_dir() failed")
460 12 : .try_into()
461 12 : .expect("current_dir() is not a valid Utf8Path")
462 1500 : }),
463 1500 : control_plane_api_token: control_plane_api_token.map(SecretString::from),
464 1500 : id,
465 1500 : default_tenant_conf: tenant_config,
466 1500 : concurrent_tenant_warmup: ConfigurableSemaphore::new(concurrent_tenant_warmup),
467 1500 : concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::new(
468 1500 : concurrent_tenant_size_logical_size_queries,
469 1500 : ),
470 1500 : eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore::new(
471 1500 : // re-use `concurrent_tenant_size_logical_size_queries`
472 1500 : concurrent_tenant_size_logical_size_queries,
473 1500 : ),
474 1500 : virtual_file_io_engine: match virtual_file_io_engine {
475 0 : Some(v) => v,
476 1500 : None => match crate::virtual_file::io_engine_feature_test()
477 1500 : .context("auto-detect virtual_file_io_engine")?
478 : {
479 1500 : io_engine::FeatureTestResult::PlatformPreferred(v) => v, // make no noise
480 0 : io_engine::FeatureTestResult::Worse { engine, remark } => {
481 0 : // TODO: bubble this up to the caller so we can tracing::warn! it.
482 0 : eprintln!(
483 0 : "auto-detected IO engine is not platform-preferred: engine={engine:?} remark={remark:?}"
484 0 : );
485 0 : engine
486 : }
487 : },
488 : },
489 1500 : l0_flush: l0_flush
490 1500 : .map(crate::l0_flush::L0FlushConfig::from)
491 1500 : .unwrap_or_default(),
492 1500 : virtual_file_io_mode: virtual_file_io_mode.unwrap_or(virtual_file::IoMode::preferred()),
493 1500 : no_sync: no_sync.unwrap_or(false),
494 1500 : enable_read_path_debugging: enable_read_path_debugging.unwrap_or(false),
495 1500 : validate_wal_contiguity: validate_wal_contiguity.unwrap_or(false),
496 1500 : load_previous_heatmap: load_previous_heatmap.unwrap_or(true),
497 1500 : generate_unarchival_heatmap: generate_unarchival_heatmap.unwrap_or(true),
498 1500 : ssl_ca_certs: match ssl_ca_file {
499 0 : Some(ssl_ca_file) => {
500 0 : let buf = std::fs::read(ssl_ca_file)?;
501 0 : pem::parse_many(&buf)?
502 0 : .into_iter()
503 0 : .filter(|pem| pem.tag() == "CERTIFICATE")
504 0 : .collect()
505 : }
506 1500 : None => Vec::new(),
507 : },
508 : };
509 :
510 : // ------------------------------------------------------------
511 : // custom validation code that covers more than one field in isolation
512 : // ------------------------------------------------------------
513 :
514 1500 : if conf.http_auth_type == AuthType::NeonJWT || conf.pg_auth_type == AuthType::NeonJWT {
515 0 : let auth_validation_public_key_path = conf
516 0 : .auth_validation_public_key_path
517 0 : .get_or_insert_with(|| workdir.join("auth_public_key.pem"));
518 0 : ensure!(
519 0 : auth_validation_public_key_path.exists(),
520 0 : format!(
521 0 : "Can't find auth_validation_public_key at '{auth_validation_public_key_path}'",
522 0 : )
523 : );
524 1500 : }
525 :
526 1500 : if let Some(tracing_config) = conf.tracing.as_ref() {
527 0 : let ratio = &tracing_config.sampling_ratio;
528 0 : ensure!(
529 0 : ratio.denominator != 0 && ratio.denominator >= ratio.numerator,
530 0 : format!(
531 0 : "Invalid sampling ratio: {}/{}",
532 0 : ratio.numerator, ratio.denominator
533 0 : )
534 : );
535 1500 : }
536 :
537 1500 : IndexEntry::validate_checkpoint_distance(conf.default_tenant_conf.checkpoint_distance)
538 1500 : .map_err(anyhow::Error::msg)
539 1500 : .with_context(|| {
540 0 : format!(
541 0 : "effective checkpoint distance is unsupported: {}",
542 0 : conf.default_tenant_conf.checkpoint_distance
543 0 : )
544 1500 : })?;
545 :
546 1500 : Ok(conf)
547 1500 : }
548 :
549 : #[cfg(test)]
550 1500 : pub fn test_repo_dir(test_name: &str) -> Utf8PathBuf {
551 1500 : let test_output_dir = std::env::var("TEST_OUTPUT").unwrap_or("../tmp_check".into());
552 1500 :
553 1500 : let test_id = uuid::Uuid::new_v4();
554 1500 : Utf8PathBuf::from(format!("{test_output_dir}/test_{test_name}_{test_id}"))
555 1500 : }
556 :
557 1488 : pub fn dummy_conf(repo_dir: Utf8PathBuf) -> Self {
558 1488 : let pg_distrib_dir = Utf8PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../pg_install");
559 1488 :
560 1488 : let config_toml = pageserver_api::config::ConfigToml {
561 1488 : wait_lsn_timeout: Duration::from_secs(60),
562 1488 : wal_redo_timeout: Duration::from_secs(60),
563 1488 : pg_distrib_dir: Some(pg_distrib_dir),
564 1488 : metric_collection_interval: Duration::from_secs(60),
565 1488 : synthetic_size_calculation_interval: Duration::from_secs(60),
566 1488 : background_task_maximum_delay: Duration::ZERO,
567 1488 : load_previous_heatmap: Some(true),
568 1488 : generate_unarchival_heatmap: Some(true),
569 1488 : ..Default::default()
570 1488 : };
571 1488 : PageServerConf::parse_and_validate(NodeId(0), config_toml, &repo_dir).unwrap()
572 1488 : }
573 : }
574 :
575 0 : #[derive(serde::Deserialize, serde::Serialize)]
576 : pub struct PageserverIdentity {
577 : pub id: NodeId,
578 : }
579 :
580 : /// Configurable semaphore permits setting.
581 : ///
582 : /// Does not allow semaphore permits to be zero, because at runtime initially zero permits and empty
583 : /// semaphore cannot be distinguished, leading any feature using these to await forever (or until
584 : /// new permits are added).
585 : #[derive(Debug, Clone)]
586 : pub struct ConfigurableSemaphore {
587 : initial_permits: NonZeroUsize,
588 : inner: std::sync::Arc<tokio::sync::Semaphore>,
589 : }
590 :
591 : impl ConfigurableSemaphore {
592 : /// Initializse using a non-zero amount of permits.
593 : ///
594 : /// Require a non-zero initial permits, because using permits == 0 is a crude way to disable a
595 : /// feature such as [`TenantShard::gather_size_inputs`]. Otherwise any semaphore using future will
596 : /// behave like [`futures::future::pending`], just waiting until new permits are added.
597 : ///
598 : /// [`TenantShard::gather_size_inputs`]: crate::tenant::TenantShard::gather_size_inputs
599 4500 : pub fn new(initial_permits: NonZeroUsize) -> Self {
600 4500 : ConfigurableSemaphore {
601 4500 : initial_permits,
602 4500 : inner: std::sync::Arc::new(tokio::sync::Semaphore::new(initial_permits.get())),
603 4500 : }
604 4500 : }
605 :
606 : /// Returns the configured amount of permits.
607 0 : pub fn initial_permits(&self) -> NonZeroUsize {
608 0 : self.initial_permits
609 0 : }
610 : }
611 :
612 : impl PartialEq for ConfigurableSemaphore {
613 0 : fn eq(&self, other: &Self) -> bool {
614 0 : // the number of permits can be increased at runtime, so we cannot really fulfill the
615 0 : // PartialEq value equality otherwise
616 0 : self.initial_permits == other.initial_permits
617 0 : }
618 : }
619 :
620 : impl Eq for ConfigurableSemaphore {}
621 :
622 : impl ConfigurableSemaphore {
623 0 : pub fn inner(&self) -> &std::sync::Arc<tokio::sync::Semaphore> {
624 0 : &self.inner
625 0 : }
626 : }
627 :
628 : #[cfg(test)]
629 : mod tests {
630 :
631 : use camino::Utf8PathBuf;
632 : use utils::id::NodeId;
633 :
634 : use super::PageServerConf;
635 :
636 : #[test]
637 12 : fn test_empty_config_toml_is_valid() {
638 12 : // we use Default impl of everything in this situation
639 12 : let input = r#"
640 12 : "#;
641 12 : let config_toml = toml_edit::de::from_str::<pageserver_api::config::ConfigToml>(input)
642 12 : .expect("empty config is valid");
643 12 : let workdir = Utf8PathBuf::from("/nonexistent");
644 12 : PageServerConf::parse_and_validate(NodeId(0), config_toml, &workdir)
645 12 : .expect("parse_and_validate");
646 12 : }
647 : }
|