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