LCOV - code coverage report
Current view: top level - pageserver/src - config.rs (source / functions) Coverage Total Hit
Test: a2f0f8a80fbf1089336086fa360ce27fa555cb1a.info Lines: 82.0 % 261 214
Test Date: 2024-11-20 17:59:39 Functions: 46.7 % 45 21

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

Generated by: LCOV version 2.1-beta