LCOV - code coverage report
Current view: top level - pageserver/src - config.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 78.7 % 980 771
Test Date: 2024-06-25 13:20:00 Functions: 56.3 % 126 71

            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::{anyhow, bail, ensure, Context, Result};
       8              : use pageserver_api::shard::TenantShardId;
       9              : use remote_storage::{RemotePath, RemoteStorageConfig};
      10              : use serde;
      11              : use serde::de::IntoDeserializer;
      12              : use std::env;
      13              : use storage_broker::Uri;
      14              : use utils::crashsafe::path_with_suffix_extension;
      15              : use utils::id::ConnectionId;
      16              : use utils::logging::SecretString;
      17              : 
      18              : use once_cell::sync::OnceCell;
      19              : use reqwest::Url;
      20              : use std::num::NonZeroUsize;
      21              : use std::str::FromStr;
      22              : use std::sync::Arc;
      23              : use std::time::Duration;
      24              : use toml_edit::{Document, Item};
      25              : 
      26              : use camino::{Utf8Path, Utf8PathBuf};
      27              : use postgres_backend::AuthType;
      28              : use utils::{
      29              :     id::{NodeId, TimelineId},
      30              :     logging::LogFormat,
      31              : };
      32              : 
      33              : use crate::tenant::timeline::GetVectoredImpl;
      34              : use crate::tenant::vectored_blob_io::MaxVectoredReadBytes;
      35              : use crate::tenant::{config::TenantConfOpt, timeline::GetImpl};
      36              : use crate::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME};
      37              : use crate::{disk_usage_eviction_task::DiskUsageEvictionTaskConfig, virtual_file::io_engine};
      38              : use crate::{tenant::config::TenantConf, virtual_file};
      39              : use crate::{
      40              :     TENANT_CONFIG_NAME, TENANT_HEATMAP_BASENAME, TENANT_LOCATION_CONFIG_NAME,
      41              :     TIMELINE_DELETE_MARK_SUFFIX,
      42              : };
      43              : 
      44              : use self::defaults::DEFAULT_CONCURRENT_TENANT_WARMUP;
      45              : 
      46              : use self::defaults::DEFAULT_VIRTUAL_FILE_IO_ENGINE;
      47              : 
      48              : pub mod defaults {
      49              :     use crate::tenant::config::defaults::*;
      50              :     use const_format::formatcp;
      51              : 
      52              :     pub use pageserver_api::config::{
      53              :         DEFAULT_HTTP_LISTEN_ADDR, DEFAULT_HTTP_LISTEN_PORT, DEFAULT_PG_LISTEN_ADDR,
      54              :         DEFAULT_PG_LISTEN_PORT,
      55              :     };
      56              :     pub use storage_broker::DEFAULT_ENDPOINT as BROKER_DEFAULT_ENDPOINT;
      57              : 
      58              :     pub const DEFAULT_WAIT_LSN_TIMEOUT: &str = "60 s";
      59              :     pub const DEFAULT_WAL_REDO_TIMEOUT: &str = "60 s";
      60              : 
      61              :     pub const DEFAULT_SUPERUSER: &str = "cloud_admin";
      62              : 
      63              :     pub const DEFAULT_PAGE_CACHE_SIZE: usize = 8192;
      64              :     pub const DEFAULT_MAX_FILE_DESCRIPTORS: usize = 100;
      65              : 
      66              :     pub const DEFAULT_LOG_FORMAT: &str = "plain";
      67              : 
      68              :     pub const DEFAULT_CONCURRENT_TENANT_WARMUP: usize = 8;
      69              : 
      70              :     pub const DEFAULT_CONCURRENT_TENANT_SIZE_LOGICAL_SIZE_QUERIES: usize =
      71              :         super::ConfigurableSemaphore::DEFAULT_INITIAL.get();
      72              : 
      73              :     pub const DEFAULT_METRIC_COLLECTION_INTERVAL: &str = "10 min";
      74              :     pub const DEFAULT_CACHED_METRIC_COLLECTION_INTERVAL: &str = "0s";
      75              :     pub const DEFAULT_METRIC_COLLECTION_ENDPOINT: Option<reqwest::Url> = None;
      76              :     pub const DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL: &str = "10 min";
      77              :     pub const DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY: &str = "10s";
      78              : 
      79              :     pub const DEFAULT_HEATMAP_UPLOAD_CONCURRENCY: usize = 8;
      80              :     pub const DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY: usize = 1;
      81              : 
      82              :     pub const DEFAULT_INGEST_BATCH_SIZE: u64 = 100;
      83              : 
      84              :     #[cfg(target_os = "linux")]
      85              :     pub const DEFAULT_VIRTUAL_FILE_IO_ENGINE: &str = "tokio-epoll-uring";
      86              : 
      87              :     #[cfg(not(target_os = "linux"))]
      88              :     pub const DEFAULT_VIRTUAL_FILE_IO_ENGINE: &str = "std-fs";
      89              : 
      90              :     pub const DEFAULT_GET_VECTORED_IMPL: &str = "sequential";
      91              : 
      92              :     pub const DEFAULT_GET_IMPL: &str = "legacy";
      93              : 
      94              :     pub const DEFAULT_MAX_VECTORED_READ_BYTES: usize = 128 * 1024; // 128 KiB
      95              : 
      96              :     pub const DEFAULT_VALIDATE_VECTORED_GET: bool = true;
      97              : 
      98              :     pub const DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB: usize = 0;
      99              : 
     100              :     ///
     101              :     /// Default built-in configuration file.
     102              :     ///
     103              :     pub const DEFAULT_CONFIG_FILE: &str = formatcp!(
     104              :         r#"
     105              : # Initial configuration file created by 'pageserver --init'
     106              : #listen_pg_addr = '{DEFAULT_PG_LISTEN_ADDR}'
     107              : #listen_http_addr = '{DEFAULT_HTTP_LISTEN_ADDR}'
     108              : 
     109              : #wait_lsn_timeout = '{DEFAULT_WAIT_LSN_TIMEOUT}'
     110              : #wal_redo_timeout = '{DEFAULT_WAL_REDO_TIMEOUT}'
     111              : 
     112              : #page_cache_size = {DEFAULT_PAGE_CACHE_SIZE}
     113              : #max_file_descriptors = {DEFAULT_MAX_FILE_DESCRIPTORS}
     114              : 
     115              : # initial superuser role name to use when creating a new tenant
     116              : #initial_superuser_name = '{DEFAULT_SUPERUSER}'
     117              : 
     118              : #broker_endpoint = '{BROKER_DEFAULT_ENDPOINT}'
     119              : 
     120              : #log_format = '{DEFAULT_LOG_FORMAT}'
     121              : 
     122              : #concurrent_tenant_size_logical_size_queries = '{DEFAULT_CONCURRENT_TENANT_SIZE_LOGICAL_SIZE_QUERIES}'
     123              : #concurrent_tenant_warmup = '{DEFAULT_CONCURRENT_TENANT_WARMUP}'
     124              : 
     125              : #metric_collection_interval = '{DEFAULT_METRIC_COLLECTION_INTERVAL}'
     126              : #cached_metric_collection_interval = '{DEFAULT_CACHED_METRIC_COLLECTION_INTERVAL}'
     127              : #synthetic_size_calculation_interval = '{DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL}'
     128              : 
     129              : #disk_usage_based_eviction = {{ max_usage_pct = .., min_avail_bytes = .., period = "10s"}}
     130              : 
     131              : #background_task_maximum_delay = '{DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY}'
     132              : 
     133              : #ingest_batch_size = {DEFAULT_INGEST_BATCH_SIZE}
     134              : 
     135              : #virtual_file_io_engine = '{DEFAULT_VIRTUAL_FILE_IO_ENGINE}'
     136              : 
     137              : #get_vectored_impl = '{DEFAULT_GET_VECTORED_IMPL}'
     138              : 
     139              : #get_impl = '{DEFAULT_GET_IMPL}'
     140              : 
     141              : #max_vectored_read_bytes = '{DEFAULT_MAX_VECTORED_READ_BYTES}'
     142              : 
     143              : #validate_vectored_get = '{DEFAULT_VALIDATE_VECTORED_GET}'
     144              : 
     145              : [tenant_config]
     146              : #checkpoint_distance = {DEFAULT_CHECKPOINT_DISTANCE} # in bytes
     147              : #checkpoint_timeout = {DEFAULT_CHECKPOINT_TIMEOUT}
     148              : #compaction_target_size = {DEFAULT_COMPACTION_TARGET_SIZE} # in bytes
     149              : #compaction_period = '{DEFAULT_COMPACTION_PERIOD}'
     150              : #compaction_threshold = {DEFAULT_COMPACTION_THRESHOLD}
     151              : 
     152              : #gc_period = '{DEFAULT_GC_PERIOD}'
     153              : #gc_horizon = {DEFAULT_GC_HORIZON}
     154              : #image_creation_threshold = {DEFAULT_IMAGE_CREATION_THRESHOLD}
     155              : #pitr_interval = '{DEFAULT_PITR_INTERVAL}'
     156              : 
     157              : #min_resident_size_override = .. # in bytes
     158              : #evictions_low_residence_duration_metric_threshold = '{DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD}'
     159              : 
     160              : #heatmap_upload_concurrency = {DEFAULT_HEATMAP_UPLOAD_CONCURRENCY}
     161              : #secondary_download_concurrency = {DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY}
     162              : 
     163              : #ephemeral_bytes_per_memory_kb = {DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB}
     164              : 
     165              : [remote_storage]
     166              : 
     167              : "#
     168              :     );
     169              : }
     170              : 
     171              : #[derive(Debug, Clone, PartialEq, Eq)]
     172              : pub struct PageServerConf {
     173              :     // Identifier of that particular pageserver so e g safekeepers
     174              :     // can safely distinguish different pageservers
     175              :     pub id: NodeId,
     176              : 
     177              :     /// Example (default): 127.0.0.1:64000
     178              :     pub listen_pg_addr: String,
     179              :     /// Example (default): 127.0.0.1:9898
     180              :     pub listen_http_addr: String,
     181              : 
     182              :     /// Current availability zone. Used for traffic metrics.
     183              :     pub availability_zone: Option<String>,
     184              : 
     185              :     // Timeout when waiting for WAL receiver to catch up to an LSN given in a GetPage@LSN call.
     186              :     pub wait_lsn_timeout: Duration,
     187              :     // How long to wait for WAL redo to complete.
     188              :     pub wal_redo_timeout: Duration,
     189              : 
     190              :     pub superuser: String,
     191              : 
     192              :     pub page_cache_size: usize,
     193              :     pub max_file_descriptors: usize,
     194              : 
     195              :     // Repository directory, relative to current working directory.
     196              :     // Normally, the page server changes the current working directory
     197              :     // to the repository, and 'workdir' is always '.'. But we don't do
     198              :     // that during unit testing, because the current directory is global
     199              :     // to the process but different unit tests work on different
     200              :     // repositories.
     201              :     pub workdir: Utf8PathBuf,
     202              : 
     203              :     pub pg_distrib_dir: Utf8PathBuf,
     204              : 
     205              :     // Authentication
     206              :     /// authentication method for the HTTP mgmt API
     207              :     pub http_auth_type: AuthType,
     208              :     /// authentication method for libpq connections from compute
     209              :     pub pg_auth_type: AuthType,
     210              :     /// Path to a file or directory containing public key(s) for verifying JWT tokens.
     211              :     /// Used for both mgmt and compute auth, if enabled.
     212              :     pub auth_validation_public_key_path: Option<Utf8PathBuf>,
     213              : 
     214              :     pub remote_storage_config: Option<RemoteStorageConfig>,
     215              : 
     216              :     pub default_tenant_conf: TenantConf,
     217              : 
     218              :     /// Storage broker endpoints to connect to.
     219              :     pub broker_endpoint: Uri,
     220              :     pub broker_keepalive_interval: Duration,
     221              : 
     222              :     pub log_format: LogFormat,
     223              : 
     224              :     /// Number of tenants which will be concurrently loaded from remote storage proactively on startup or attach.
     225              :     ///
     226              :     /// A lower value implicitly deprioritizes loading such tenants, vs. other work in the system.
     227              :     pub concurrent_tenant_warmup: ConfigurableSemaphore,
     228              : 
     229              :     /// Number of concurrent [`Tenant::gather_size_inputs`](crate::tenant::Tenant::gather_size_inputs) allowed.
     230              :     pub concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore,
     231              :     /// Limit of concurrent [`Tenant::gather_size_inputs`] issued by module `eviction_task`.
     232              :     /// The number of permits is the same as `concurrent_tenant_size_logical_size_queries`.
     233              :     /// See the comment in `eviction_task` for details.
     234              :     ///
     235              :     /// [`Tenant::gather_size_inputs`]: crate::tenant::Tenant::gather_size_inputs
     236              :     pub eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore,
     237              : 
     238              :     // How often to collect metrics and send them to the metrics endpoint.
     239              :     pub metric_collection_interval: Duration,
     240              :     // How often to send unchanged cached metrics to the metrics endpoint.
     241              :     pub cached_metric_collection_interval: Duration,
     242              :     pub metric_collection_endpoint: Option<Url>,
     243              :     pub metric_collection_bucket: Option<RemoteStorageConfig>,
     244              :     pub synthetic_size_calculation_interval: Duration,
     245              : 
     246              :     pub disk_usage_based_eviction: Option<DiskUsageEvictionTaskConfig>,
     247              : 
     248              :     pub test_remote_failures: u64,
     249              : 
     250              :     pub ondemand_download_behavior_treat_error_as_warn: bool,
     251              : 
     252              :     /// How long will background tasks be delayed at most after initial load of tenants.
     253              :     ///
     254              :     /// Our largest initialization completions are in the range of 100-200s, so perhaps 10s works
     255              :     /// as we now isolate initial loading, initial logical size calculation and background tasks.
     256              :     /// Smaller nodes will have background tasks "not running" for this long unless every timeline
     257              :     /// has it's initial logical size calculated. Not running background tasks for some seconds is
     258              :     /// not terrible.
     259              :     pub background_task_maximum_delay: Duration,
     260              : 
     261              :     pub control_plane_api: Option<Url>,
     262              : 
     263              :     /// JWT token for use with the control plane API.
     264              :     pub control_plane_api_token: Option<SecretString>,
     265              : 
     266              :     /// If true, pageserver will make best-effort to operate without a control plane: only
     267              :     /// for use in major incidents.
     268              :     pub control_plane_emergency_mode: bool,
     269              : 
     270              :     /// How many heatmap uploads may be done concurrency: lower values implicitly deprioritize
     271              :     /// heatmap uploads vs. other remote storage operations.
     272              :     pub heatmap_upload_concurrency: usize,
     273              : 
     274              :     /// How many remote storage downloads may be done for secondary tenants concurrently.  Implicitly
     275              :     /// deprioritises secondary downloads vs. remote storage operations for attached tenants.
     276              :     pub secondary_download_concurrency: usize,
     277              : 
     278              :     /// Maximum number of WAL records to be ingested and committed at the same time
     279              :     pub ingest_batch_size: u64,
     280              : 
     281              :     pub virtual_file_io_engine: virtual_file::IoEngineKind,
     282              : 
     283              :     pub get_vectored_impl: GetVectoredImpl,
     284              : 
     285              :     pub get_impl: GetImpl,
     286              : 
     287              :     pub max_vectored_read_bytes: MaxVectoredReadBytes,
     288              : 
     289              :     pub validate_vectored_get: bool,
     290              : 
     291              :     /// How many bytes of ephemeral layer content will we allow per kilobyte of RAM.  When this
     292              :     /// is exceeded, we start proactively closing ephemeral layers to limit the total amount
     293              :     /// of ephemeral data.
     294              :     ///
     295              :     /// Setting this to zero disables limits on total ephemeral layer size.
     296              :     pub ephemeral_bytes_per_memory_kb: usize,
     297              : }
     298              : 
     299              : /// We do not want to store this in a PageServerConf because the latter may be logged
     300              : /// and/or serialized at a whim, while the token is secret. Currently this token is the
     301              : /// same for accessing all tenants/timelines, but may become per-tenant/per-timeline in
     302              : /// the future, more tokens and auth may arrive for storage broker, completely changing the logic.
     303              : /// Hence, we resort to a global variable for now instead of passing the token from the
     304              : /// startup code to the connection code through a dozen layers.
     305              : pub static SAFEKEEPER_AUTH_TOKEN: OnceCell<Arc<String>> = OnceCell::new();
     306              : 
     307              : // use dedicated enum for builder to better indicate the intention
     308              : // and avoid possible confusion with nested options
     309              : #[derive(Clone, Default)]
     310              : pub enum BuilderValue<T> {
     311              :     Set(T),
     312              :     #[default]
     313              :     NotSet,
     314              : }
     315              : 
     316              : impl<T: Clone> BuilderValue<T> {
     317          738 :     pub fn ok_or(&self, field_name: &'static str, default: BuilderValue<T>) -> anyhow::Result<T> {
     318          738 :         match self {
     319          242 :             Self::Set(v) => Ok(v.clone()),
     320          496 :             Self::NotSet => match default {
     321          496 :                 BuilderValue::Set(v) => Ok(v.clone()),
     322              :                 BuilderValue::NotSet => {
     323            0 :                     anyhow::bail!("missing config value {field_name:?}")
     324              :                 }
     325              :             },
     326              :         }
     327          738 :     }
     328              : }
     329              : 
     330              : // needed to simplify config construction
     331              : #[derive(Default)]
     332              : struct PageServerConfigBuilder {
     333              :     listen_pg_addr: BuilderValue<String>,
     334              : 
     335              :     listen_http_addr: BuilderValue<String>,
     336              : 
     337              :     availability_zone: BuilderValue<Option<String>>,
     338              : 
     339              :     wait_lsn_timeout: BuilderValue<Duration>,
     340              :     wal_redo_timeout: BuilderValue<Duration>,
     341              : 
     342              :     superuser: BuilderValue<String>,
     343              : 
     344              :     page_cache_size: BuilderValue<usize>,
     345              :     max_file_descriptors: BuilderValue<usize>,
     346              : 
     347              :     workdir: BuilderValue<Utf8PathBuf>,
     348              : 
     349              :     pg_distrib_dir: BuilderValue<Utf8PathBuf>,
     350              : 
     351              :     http_auth_type: BuilderValue<AuthType>,
     352              :     pg_auth_type: BuilderValue<AuthType>,
     353              : 
     354              :     //
     355              :     auth_validation_public_key_path: BuilderValue<Option<Utf8PathBuf>>,
     356              :     remote_storage_config: BuilderValue<Option<RemoteStorageConfig>>,
     357              : 
     358              :     id: BuilderValue<NodeId>,
     359              : 
     360              :     broker_endpoint: BuilderValue<Uri>,
     361              :     broker_keepalive_interval: BuilderValue<Duration>,
     362              : 
     363              :     log_format: BuilderValue<LogFormat>,
     364              : 
     365              :     concurrent_tenant_warmup: BuilderValue<NonZeroUsize>,
     366              :     concurrent_tenant_size_logical_size_queries: BuilderValue<NonZeroUsize>,
     367              : 
     368              :     metric_collection_interval: BuilderValue<Duration>,
     369              :     cached_metric_collection_interval: BuilderValue<Duration>,
     370              :     metric_collection_endpoint: BuilderValue<Option<Url>>,
     371              :     synthetic_size_calculation_interval: BuilderValue<Duration>,
     372              :     metric_collection_bucket: BuilderValue<Option<RemoteStorageConfig>>,
     373              : 
     374              :     disk_usage_based_eviction: BuilderValue<Option<DiskUsageEvictionTaskConfig>>,
     375              : 
     376              :     test_remote_failures: BuilderValue<u64>,
     377              : 
     378              :     ondemand_download_behavior_treat_error_as_warn: BuilderValue<bool>,
     379              : 
     380              :     background_task_maximum_delay: BuilderValue<Duration>,
     381              : 
     382              :     control_plane_api: BuilderValue<Option<Url>>,
     383              :     control_plane_api_token: BuilderValue<Option<SecretString>>,
     384              :     control_plane_emergency_mode: BuilderValue<bool>,
     385              : 
     386              :     heatmap_upload_concurrency: BuilderValue<usize>,
     387              :     secondary_download_concurrency: BuilderValue<usize>,
     388              : 
     389              :     ingest_batch_size: BuilderValue<u64>,
     390              : 
     391              :     virtual_file_io_engine: BuilderValue<virtual_file::IoEngineKind>,
     392              : 
     393              :     get_vectored_impl: BuilderValue<GetVectoredImpl>,
     394              : 
     395              :     get_impl: BuilderValue<GetImpl>,
     396              : 
     397              :     max_vectored_read_bytes: BuilderValue<MaxVectoredReadBytes>,
     398              : 
     399              :     validate_vectored_get: BuilderValue<bool>,
     400              : 
     401              :     ephemeral_bytes_per_memory_kb: BuilderValue<usize>,
     402              : }
     403              : 
     404              : impl PageServerConfigBuilder {
     405              :     #[inline(always)]
     406           18 :     fn default_values() -> Self {
     407           18 :         use self::BuilderValue::*;
     408           18 :         use defaults::*;
     409           18 :         Self {
     410           18 :             listen_pg_addr: Set(DEFAULT_PG_LISTEN_ADDR.to_string()),
     411           18 :             listen_http_addr: Set(DEFAULT_HTTP_LISTEN_ADDR.to_string()),
     412           18 :             availability_zone: Set(None),
     413           18 :             wait_lsn_timeout: Set(humantime::parse_duration(DEFAULT_WAIT_LSN_TIMEOUT)
     414           18 :                 .expect("cannot parse default wait lsn timeout")),
     415           18 :             wal_redo_timeout: Set(humantime::parse_duration(DEFAULT_WAL_REDO_TIMEOUT)
     416           18 :                 .expect("cannot parse default wal redo timeout")),
     417           18 :             superuser: Set(DEFAULT_SUPERUSER.to_string()),
     418           18 :             page_cache_size: Set(DEFAULT_PAGE_CACHE_SIZE),
     419           18 :             max_file_descriptors: Set(DEFAULT_MAX_FILE_DESCRIPTORS),
     420           18 :             workdir: Set(Utf8PathBuf::new()),
     421           18 :             pg_distrib_dir: Set(Utf8PathBuf::from_path_buf(
     422           18 :                 env::current_dir().expect("cannot access current directory"),
     423           18 :             )
     424           18 :             .expect("non-Unicode path")
     425           18 :             .join("pg_install")),
     426           18 :             http_auth_type: Set(AuthType::Trust),
     427           18 :             pg_auth_type: Set(AuthType::Trust),
     428           18 :             auth_validation_public_key_path: Set(None),
     429           18 :             remote_storage_config: Set(None),
     430           18 :             id: NotSet,
     431           18 :             broker_endpoint: Set(storage_broker::DEFAULT_ENDPOINT
     432           18 :                 .parse()
     433           18 :                 .expect("failed to parse default broker endpoint")),
     434           18 :             broker_keepalive_interval: Set(humantime::parse_duration(
     435           18 :                 storage_broker::DEFAULT_KEEPALIVE_INTERVAL,
     436           18 :             )
     437           18 :             .expect("cannot parse default keepalive interval")),
     438           18 :             log_format: Set(LogFormat::from_str(DEFAULT_LOG_FORMAT).unwrap()),
     439           18 : 
     440           18 :             concurrent_tenant_warmup: Set(NonZeroUsize::new(DEFAULT_CONCURRENT_TENANT_WARMUP)
     441           18 :                 .expect("Invalid default constant")),
     442           18 :             concurrent_tenant_size_logical_size_queries: Set(
     443           18 :                 ConfigurableSemaphore::DEFAULT_INITIAL,
     444           18 :             ),
     445           18 :             metric_collection_interval: Set(humantime::parse_duration(
     446           18 :                 DEFAULT_METRIC_COLLECTION_INTERVAL,
     447           18 :             )
     448           18 :             .expect("cannot parse default metric collection interval")),
     449           18 :             cached_metric_collection_interval: Set(humantime::parse_duration(
     450           18 :                 DEFAULT_CACHED_METRIC_COLLECTION_INTERVAL,
     451           18 :             )
     452           18 :             .expect("cannot parse default cached_metric_collection_interval")),
     453           18 :             synthetic_size_calculation_interval: Set(humantime::parse_duration(
     454           18 :                 DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL,
     455           18 :             )
     456           18 :             .expect("cannot parse default synthetic size calculation interval")),
     457           18 :             metric_collection_endpoint: Set(DEFAULT_METRIC_COLLECTION_ENDPOINT),
     458           18 : 
     459           18 :             metric_collection_bucket: Set(None),
     460           18 : 
     461           18 :             disk_usage_based_eviction: Set(None),
     462           18 : 
     463           18 :             test_remote_failures: Set(0),
     464           18 : 
     465           18 :             ondemand_download_behavior_treat_error_as_warn: Set(false),
     466           18 : 
     467           18 :             background_task_maximum_delay: Set(humantime::parse_duration(
     468           18 :                 DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY,
     469           18 :             )
     470           18 :             .unwrap()),
     471           18 : 
     472           18 :             control_plane_api: Set(None),
     473           18 :             control_plane_api_token: Set(None),
     474           18 :             control_plane_emergency_mode: Set(false),
     475           18 : 
     476           18 :             heatmap_upload_concurrency: Set(DEFAULT_HEATMAP_UPLOAD_CONCURRENCY),
     477           18 :             secondary_download_concurrency: Set(DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY),
     478           18 : 
     479           18 :             ingest_batch_size: Set(DEFAULT_INGEST_BATCH_SIZE),
     480           18 : 
     481           18 :             virtual_file_io_engine: Set(DEFAULT_VIRTUAL_FILE_IO_ENGINE.parse().unwrap()),
     482           18 : 
     483           18 :             get_vectored_impl: Set(DEFAULT_GET_VECTORED_IMPL.parse().unwrap()),
     484           18 :             get_impl: Set(DEFAULT_GET_IMPL.parse().unwrap()),
     485           18 :             max_vectored_read_bytes: Set(MaxVectoredReadBytes(
     486           18 :                 NonZeroUsize::new(DEFAULT_MAX_VECTORED_READ_BYTES).unwrap(),
     487           18 :             )),
     488           18 :             validate_vectored_get: Set(DEFAULT_VALIDATE_VECTORED_GET),
     489           18 :             ephemeral_bytes_per_memory_kb: Set(DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB),
     490           18 :         }
     491           18 :     }
     492              : }
     493              : 
     494              : impl PageServerConfigBuilder {
     495           12 :     pub fn listen_pg_addr(&mut self, listen_pg_addr: String) {
     496           12 :         self.listen_pg_addr = BuilderValue::Set(listen_pg_addr)
     497           12 :     }
     498              : 
     499           12 :     pub fn listen_http_addr(&mut self, listen_http_addr: String) {
     500           12 :         self.listen_http_addr = BuilderValue::Set(listen_http_addr)
     501           12 :     }
     502              : 
     503            0 :     pub fn availability_zone(&mut self, availability_zone: Option<String>) {
     504            0 :         self.availability_zone = BuilderValue::Set(availability_zone)
     505            0 :     }
     506              : 
     507           12 :     pub fn wait_lsn_timeout(&mut self, wait_lsn_timeout: Duration) {
     508           12 :         self.wait_lsn_timeout = BuilderValue::Set(wait_lsn_timeout)
     509           12 :     }
     510              : 
     511           12 :     pub fn wal_redo_timeout(&mut self, wal_redo_timeout: Duration) {
     512           12 :         self.wal_redo_timeout = BuilderValue::Set(wal_redo_timeout)
     513           12 :     }
     514              : 
     515           12 :     pub fn superuser(&mut self, superuser: String) {
     516           12 :         self.superuser = BuilderValue::Set(superuser)
     517           12 :     }
     518              : 
     519           12 :     pub fn page_cache_size(&mut self, page_cache_size: usize) {
     520           12 :         self.page_cache_size = BuilderValue::Set(page_cache_size)
     521           12 :     }
     522              : 
     523           12 :     pub fn max_file_descriptors(&mut self, max_file_descriptors: usize) {
     524           12 :         self.max_file_descriptors = BuilderValue::Set(max_file_descriptors)
     525           12 :     }
     526              : 
     527           18 :     pub fn workdir(&mut self, workdir: Utf8PathBuf) {
     528           18 :         self.workdir = BuilderValue::Set(workdir)
     529           18 :     }
     530              : 
     531           18 :     pub fn pg_distrib_dir(&mut self, pg_distrib_dir: Utf8PathBuf) {
     532           18 :         self.pg_distrib_dir = BuilderValue::Set(pg_distrib_dir)
     533           18 :     }
     534              : 
     535            0 :     pub fn http_auth_type(&mut self, auth_type: AuthType) {
     536            0 :         self.http_auth_type = BuilderValue::Set(auth_type)
     537            0 :     }
     538              : 
     539            0 :     pub fn pg_auth_type(&mut self, auth_type: AuthType) {
     540            0 :         self.pg_auth_type = BuilderValue::Set(auth_type)
     541            0 :     }
     542              : 
     543            0 :     pub fn auth_validation_public_key_path(
     544            0 :         &mut self,
     545            0 :         auth_validation_public_key_path: Option<Utf8PathBuf>,
     546            0 :     ) {
     547            0 :         self.auth_validation_public_key_path = BuilderValue::Set(auth_validation_public_key_path)
     548            0 :     }
     549              : 
     550            8 :     pub fn remote_storage_config(&mut self, remote_storage_config: Option<RemoteStorageConfig>) {
     551            8 :         self.remote_storage_config = BuilderValue::Set(remote_storage_config)
     552            8 :     }
     553              : 
     554           14 :     pub fn broker_endpoint(&mut self, broker_endpoint: Uri) {
     555           14 :         self.broker_endpoint = BuilderValue::Set(broker_endpoint)
     556           14 :     }
     557              : 
     558            0 :     pub fn broker_keepalive_interval(&mut self, broker_keepalive_interval: Duration) {
     559            0 :         self.broker_keepalive_interval = BuilderValue::Set(broker_keepalive_interval)
     560            0 :     }
     561              : 
     562           18 :     pub fn id(&mut self, node_id: NodeId) {
     563           18 :         self.id = BuilderValue::Set(node_id)
     564           18 :     }
     565              : 
     566           12 :     pub fn log_format(&mut self, log_format: LogFormat) {
     567           12 :         self.log_format = BuilderValue::Set(log_format)
     568           12 :     }
     569              : 
     570            0 :     pub fn concurrent_tenant_warmup(&mut self, u: NonZeroUsize) {
     571            0 :         self.concurrent_tenant_warmup = BuilderValue::Set(u);
     572            0 :     }
     573              : 
     574            0 :     pub fn concurrent_tenant_size_logical_size_queries(&mut self, u: NonZeroUsize) {
     575            0 :         self.concurrent_tenant_size_logical_size_queries = BuilderValue::Set(u);
     576            0 :     }
     577              : 
     578           16 :     pub fn metric_collection_interval(&mut self, metric_collection_interval: Duration) {
     579           16 :         self.metric_collection_interval = BuilderValue::Set(metric_collection_interval)
     580           16 :     }
     581              : 
     582           12 :     pub fn cached_metric_collection_interval(
     583           12 :         &mut self,
     584           12 :         cached_metric_collection_interval: Duration,
     585           12 :     ) {
     586           12 :         self.cached_metric_collection_interval =
     587           12 :             BuilderValue::Set(cached_metric_collection_interval)
     588           12 :     }
     589              : 
     590           16 :     pub fn metric_collection_endpoint(&mut self, metric_collection_endpoint: Option<Url>) {
     591           16 :         self.metric_collection_endpoint = BuilderValue::Set(metric_collection_endpoint)
     592           16 :     }
     593              : 
     594            0 :     pub fn metric_collection_bucket(
     595            0 :         &mut self,
     596            0 :         metric_collection_bucket: Option<RemoteStorageConfig>,
     597            0 :     ) {
     598            0 :         self.metric_collection_bucket = BuilderValue::Set(metric_collection_bucket)
     599            0 :     }
     600              : 
     601           12 :     pub fn synthetic_size_calculation_interval(
     602           12 :         &mut self,
     603           12 :         synthetic_size_calculation_interval: Duration,
     604           12 :     ) {
     605           12 :         self.synthetic_size_calculation_interval =
     606           12 :             BuilderValue::Set(synthetic_size_calculation_interval)
     607           12 :     }
     608              : 
     609            0 :     pub fn test_remote_failures(&mut self, fail_first: u64) {
     610            0 :         self.test_remote_failures = BuilderValue::Set(fail_first);
     611            0 :     }
     612              : 
     613            2 :     pub fn disk_usage_based_eviction(&mut self, value: Option<DiskUsageEvictionTaskConfig>) {
     614            2 :         self.disk_usage_based_eviction = BuilderValue::Set(value);
     615            2 :     }
     616              : 
     617            0 :     pub fn ondemand_download_behavior_treat_error_as_warn(
     618            0 :         &mut self,
     619            0 :         ondemand_download_behavior_treat_error_as_warn: bool,
     620            0 :     ) {
     621            0 :         self.ondemand_download_behavior_treat_error_as_warn =
     622            0 :             BuilderValue::Set(ondemand_download_behavior_treat_error_as_warn);
     623            0 :     }
     624              : 
     625           12 :     pub fn background_task_maximum_delay(&mut self, delay: Duration) {
     626           12 :         self.background_task_maximum_delay = BuilderValue::Set(delay);
     627           12 :     }
     628              : 
     629            0 :     pub fn control_plane_api(&mut self, api: Option<Url>) {
     630            0 :         self.control_plane_api = BuilderValue::Set(api)
     631            0 :     }
     632              : 
     633            0 :     pub fn control_plane_api_token(&mut self, token: Option<SecretString>) {
     634            0 :         self.control_plane_api_token = BuilderValue::Set(token)
     635            0 :     }
     636              : 
     637            0 :     pub fn control_plane_emergency_mode(&mut self, enabled: bool) {
     638            0 :         self.control_plane_emergency_mode = BuilderValue::Set(enabled)
     639            0 :     }
     640              : 
     641            0 :     pub fn heatmap_upload_concurrency(&mut self, value: usize) {
     642            0 :         self.heatmap_upload_concurrency = BuilderValue::Set(value)
     643            0 :     }
     644              : 
     645            0 :     pub fn secondary_download_concurrency(&mut self, value: usize) {
     646            0 :         self.secondary_download_concurrency = BuilderValue::Set(value)
     647            0 :     }
     648              : 
     649            0 :     pub fn ingest_batch_size(&mut self, ingest_batch_size: u64) {
     650            0 :         self.ingest_batch_size = BuilderValue::Set(ingest_batch_size)
     651            0 :     }
     652              : 
     653            0 :     pub fn virtual_file_io_engine(&mut self, value: virtual_file::IoEngineKind) {
     654            0 :         self.virtual_file_io_engine = BuilderValue::Set(value);
     655            0 :     }
     656              : 
     657            0 :     pub fn get_vectored_impl(&mut self, value: GetVectoredImpl) {
     658            0 :         self.get_vectored_impl = BuilderValue::Set(value);
     659            0 :     }
     660              : 
     661            0 :     pub fn get_impl(&mut self, value: GetImpl) {
     662            0 :         self.get_impl = BuilderValue::Set(value);
     663            0 :     }
     664              : 
     665            0 :     pub fn get_max_vectored_read_bytes(&mut self, value: MaxVectoredReadBytes) {
     666            0 :         self.max_vectored_read_bytes = BuilderValue::Set(value);
     667            0 :     }
     668              : 
     669            0 :     pub fn get_validate_vectored_get(&mut self, value: bool) {
     670            0 :         self.validate_vectored_get = BuilderValue::Set(value);
     671            0 :     }
     672              : 
     673            0 :     pub fn get_ephemeral_bytes_per_memory_kb(&mut self, value: usize) {
     674            0 :         self.ephemeral_bytes_per_memory_kb = BuilderValue::Set(value);
     675            0 :     }
     676              : 
     677           18 :     pub fn build(self) -> anyhow::Result<PageServerConf> {
     678           18 :         let default = Self::default_values();
     679           18 : 
     680           18 :         macro_rules! conf {
     681           18 :             (USING DEFAULT { $($field:ident,)* } CUSTOM LOGIC { $($custom_field:ident : $custom_value:expr,)* } ) => {
     682           18 :                 PageServerConf {
     683           18 :                     $(
     684           18 :                         $field: self.$field.ok_or(stringify!($field), default.$field)?,
     685           18 :                     )*
     686           18 :                     $(
     687           18 :                         $custom_field: $custom_value,
     688           18 :                     )*
     689           18 :                 }
     690           18 :             };
     691           18 :         }
     692           18 : 
     693           18 :         Ok(conf!(
     694              :             USING DEFAULT
     695              :             {
     696              :                 listen_pg_addr,
     697              :                 listen_http_addr,
     698              :                 availability_zone,
     699              :                 wait_lsn_timeout,
     700              :                 wal_redo_timeout,
     701              :                 superuser,
     702              :                 page_cache_size,
     703              :                 max_file_descriptors,
     704              :                 workdir,
     705              :                 pg_distrib_dir,
     706              :                 http_auth_type,
     707              :                 pg_auth_type,
     708              :                 auth_validation_public_key_path,
     709              :                 remote_storage_config,
     710              :                 id,
     711              :                 broker_endpoint,
     712              :                 broker_keepalive_interval,
     713              :                 log_format,
     714              :                 metric_collection_interval,
     715              :                 cached_metric_collection_interval,
     716              :                 metric_collection_endpoint,
     717              :                 metric_collection_bucket,
     718              :                 synthetic_size_calculation_interval,
     719              :                 disk_usage_based_eviction,
     720              :                 test_remote_failures,
     721              :                 ondemand_download_behavior_treat_error_as_warn,
     722              :                 background_task_maximum_delay,
     723              :                 control_plane_api,
     724              :                 control_plane_api_token,
     725              :                 control_plane_emergency_mode,
     726              :                 heatmap_upload_concurrency,
     727              :                 secondary_download_concurrency,
     728              :                 ingest_batch_size,
     729              :                 get_vectored_impl,
     730              :                 get_impl,
     731              :                 max_vectored_read_bytes,
     732              :                 validate_vectored_get,
     733              :                 ephemeral_bytes_per_memory_kb,
     734              :             }
     735              :             CUSTOM LOGIC
     736              :             {
     737              :                 // TenantConf is handled separately
     738           18 :                 default_tenant_conf: TenantConf::default(),
     739           18 :                 concurrent_tenant_warmup: ConfigurableSemaphore::new({
     740           18 :                     self
     741           18 :                         .concurrent_tenant_warmup
     742           18 :                         .ok_or("concurrent_tenant_warmpup",
     743           18 :                                default.concurrent_tenant_warmup)?
     744              :                 }),
     745              :                 concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::new(
     746           18 :                     self
     747           18 :                         .concurrent_tenant_size_logical_size_queries
     748           18 :                         .ok_or("concurrent_tenant_size_logical_size_queries",
     749           18 :                                default.concurrent_tenant_size_logical_size_queries.clone())?
     750              :                 ),
     751              :                 eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore::new(
     752              :                     // re-use `concurrent_tenant_size_logical_size_queries`
     753           18 :                     self
     754           18 :                         .concurrent_tenant_size_logical_size_queries
     755           18 :                         .ok_or("eviction_task_immitated_concurrent_logical_size_queries",
     756           18 :                                default.concurrent_tenant_size_logical_size_queries.clone())?,
     757              :                 ),
     758           18 :                 virtual_file_io_engine: match self.virtual_file_io_engine {
     759            0 :                     BuilderValue::Set(v) => v,
     760           18 :                     BuilderValue::NotSet => match crate::virtual_file::io_engine_feature_test().context("auto-detect virtual_file_io_engine")? {
     761           18 :                         io_engine::FeatureTestResult::PlatformPreferred(v) => v, // make no noise
     762            0 :                         io_engine::FeatureTestResult::Worse { engine, remark } => {
     763            0 :                             // TODO: bubble this up to the caller so we can tracing::warn! it.
     764            0 :                             eprintln!("auto-detected IO engine is not platform-preferred: engine={engine:?} remark={remark:?}");
     765            0 :                             engine
     766              :                         }
     767              :                     },
     768              :                 },
     769              :             }
     770              :         ))
     771           18 :     }
     772              : }
     773              : 
     774              : impl PageServerConf {
     775              :     //
     776              :     // Repository paths, relative to workdir.
     777              :     //
     778              : 
     779         6417 :     pub fn tenants_path(&self) -> Utf8PathBuf {
     780         6417 :         self.workdir.join(TENANTS_SEGMENT_NAME)
     781         6417 :     }
     782              : 
     783           72 :     pub fn deletion_prefix(&self) -> Utf8PathBuf {
     784           72 :         self.workdir.join("deletion")
     785           72 :     }
     786              : 
     787            0 :     pub fn metadata_path(&self) -> Utf8PathBuf {
     788            0 :         self.workdir.join("metadata.json")
     789            0 :     }
     790              : 
     791           28 :     pub fn deletion_list_path(&self, sequence: u64) -> Utf8PathBuf {
     792           28 :         // Encode a version in the filename, so that if we ever switch away from JSON we can
     793           28 :         // increment this.
     794           28 :         const VERSION: u8 = 1;
     795           28 : 
     796           28 :         self.deletion_prefix()
     797           28 :             .join(format!("{sequence:016x}-{VERSION:02x}.list"))
     798           28 :     }
     799              : 
     800           24 :     pub fn deletion_header_path(&self) -> Utf8PathBuf {
     801           24 :         // Encode a version in the filename, so that if we ever switch away from JSON we can
     802           24 :         // increment this.
     803           24 :         const VERSION: u8 = 1;
     804           24 : 
     805           24 :         self.deletion_prefix().join(format!("header-{VERSION:02x}"))
     806           24 :     }
     807              : 
     808         6417 :     pub fn tenant_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     809         6417 :         self.tenants_path().join(tenant_shard_id.to_string())
     810         6417 :     }
     811              : 
     812              :     /// Points to a place in pageserver's local directory,
     813              :     /// where certain tenant's tenantconf file should be located.
     814              :     ///
     815              :     /// Legacy: superseded by tenant_location_config_path.  Eventually
     816              :     /// remove this function.
     817            0 :     pub fn tenant_config_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     818            0 :         self.tenant_path(tenant_shard_id).join(TENANT_CONFIG_NAME)
     819            0 :     }
     820              : 
     821            0 :     pub fn tenant_location_config_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     822            0 :         self.tenant_path(tenant_shard_id)
     823            0 :             .join(TENANT_LOCATION_CONFIG_NAME)
     824            0 :     }
     825              : 
     826            0 :     pub(crate) fn tenant_heatmap_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     827            0 :         self.tenant_path(tenant_shard_id)
     828            0 :             .join(TENANT_HEATMAP_BASENAME)
     829            0 :     }
     830              : 
     831         6254 :     pub fn timelines_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     832         6254 :         self.tenant_path(tenant_shard_id)
     833         6254 :             .join(TIMELINES_SEGMENT_NAME)
     834         6254 :     }
     835              : 
     836         5932 :     pub fn timeline_path(
     837         5932 :         &self,
     838         5932 :         tenant_shard_id: &TenantShardId,
     839         5932 :         timeline_id: &TimelineId,
     840         5932 :     ) -> Utf8PathBuf {
     841         5932 :         self.timelines_path(tenant_shard_id)
     842         5932 :             .join(timeline_id.to_string())
     843         5932 :     }
     844              : 
     845            0 :     pub(crate) fn timeline_delete_mark_file_path(
     846            0 :         &self,
     847            0 :         tenant_shard_id: TenantShardId,
     848            0 :         timeline_id: TimelineId,
     849            0 :     ) -> Utf8PathBuf {
     850            0 :         path_with_suffix_extension(
     851            0 :             self.timeline_path(&tenant_shard_id, &timeline_id),
     852            0 :             TIMELINE_DELETE_MARK_SUFFIX,
     853            0 :         )
     854            0 :     }
     855              : 
     856            0 :     pub fn traces_path(&self) -> Utf8PathBuf {
     857            0 :         self.workdir.join("traces")
     858            0 :     }
     859              : 
     860            0 :     pub fn trace_path(
     861            0 :         &self,
     862            0 :         tenant_shard_id: &TenantShardId,
     863            0 :         timeline_id: &TimelineId,
     864            0 :         connection_id: &ConnectionId,
     865            0 :     ) -> Utf8PathBuf {
     866            0 :         self.traces_path()
     867            0 :             .join(tenant_shard_id.to_string())
     868            0 :             .join(timeline_id.to_string())
     869            0 :             .join(connection_id.to_string())
     870            0 :     }
     871              : 
     872              :     /// Turns storage remote path of a file into its local path.
     873            0 :     pub fn local_path(&self, remote_path: &RemotePath) -> Utf8PathBuf {
     874            0 :         remote_path.with_base(&self.workdir)
     875            0 :     }
     876              : 
     877              :     //
     878              :     // Postgres distribution paths
     879              :     //
     880           16 :     pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     881           16 :         let path = self.pg_distrib_dir.clone();
     882           16 : 
     883           16 :         #[allow(clippy::manual_range_patterns)]
     884           16 :         match pg_version {
     885           16 :             14 | 15 | 16 => Ok(path.join(format!("v{pg_version}"))),
     886            0 :             _ => bail!("Unsupported postgres version: {}", pg_version),
     887              :         }
     888           16 :     }
     889              : 
     890            8 :     pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     891            8 :         Ok(self.pg_distrib_dir(pg_version)?.join("bin"))
     892            8 :     }
     893            8 :     pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     894            8 :         Ok(self.pg_distrib_dir(pg_version)?.join("lib"))
     895            8 :     }
     896              : 
     897              :     /// Parse a configuration file (pageserver.toml) into a PageServerConf struct,
     898              :     /// validating the input and failing on errors.
     899              :     ///
     900              :     /// This leaves any options not present in the file in the built-in defaults.
     901           18 :     pub fn parse_and_validate(toml: &Document, workdir: &Utf8Path) -> anyhow::Result<Self> {
     902           18 :         let mut builder = PageServerConfigBuilder::default();
     903           18 :         builder.workdir(workdir.to_owned());
     904           18 : 
     905           18 :         let mut t_conf = TenantConfOpt::default();
     906              : 
     907          230 :         for (key, item) in toml.iter() {
     908          230 :             match key {
     909          230 :                 "listen_pg_addr" => builder.listen_pg_addr(parse_toml_string(key, item)?),
     910          218 :                 "listen_http_addr" => builder.listen_http_addr(parse_toml_string(key, item)?),
     911          206 :                 "availability_zone" => builder.availability_zone(Some(parse_toml_string(key, item)?)),
     912          206 :                 "wait_lsn_timeout" => builder.wait_lsn_timeout(parse_toml_duration(key, item)?),
     913          194 :                 "wal_redo_timeout" => builder.wal_redo_timeout(parse_toml_duration(key, item)?),
     914          182 :                 "initial_superuser_name" => builder.superuser(parse_toml_string(key, item)?),
     915          170 :                 "page_cache_size" => builder.page_cache_size(parse_toml_u64(key, item)? as usize),
     916          158 :                 "max_file_descriptors" => {
     917           12 :                     builder.max_file_descriptors(parse_toml_u64(key, item)? as usize)
     918              :                 }
     919          146 :                 "pg_distrib_dir" => {
     920           18 :                     builder.pg_distrib_dir(Utf8PathBuf::from(parse_toml_string(key, item)?))
     921              :                 }
     922          128 :                 "auth_validation_public_key_path" => builder.auth_validation_public_key_path(Some(
     923            0 :                     Utf8PathBuf::from(parse_toml_string(key, item)?),
     924              :                 )),
     925          128 :                 "http_auth_type" => builder.http_auth_type(parse_toml_from_str(key, item)?),
     926          128 :                 "pg_auth_type" => builder.pg_auth_type(parse_toml_from_str(key, item)?),
     927          128 :                 "remote_storage" => {
     928            8 :                     builder.remote_storage_config(RemoteStorageConfig::from_toml(item)?)
     929              :                 }
     930          120 :                 "tenant_config" => {
     931            6 :                     t_conf = TenantConfOpt::try_from(item.to_owned()).context(format!("failed to parse: '{key}'"))?;
     932              :                 }
     933          114 :                 "id" => builder.id(NodeId(parse_toml_u64(key, item)?)),
     934           96 :                 "broker_endpoint" => builder.broker_endpoint(parse_toml_string(key, item)?.parse().context("failed to parse broker endpoint")?),
     935           82 :                 "broker_keepalive_interval" => builder.broker_keepalive_interval(parse_toml_duration(key, item)?),
     936           82 :                 "log_format" => builder.log_format(
     937           12 :                     LogFormat::from_config(&parse_toml_string(key, item)?)?
     938              :                 ),
     939           70 :                 "concurrent_tenant_warmup" => builder.concurrent_tenant_warmup({
     940            0 :                     let input = parse_toml_string(key, item)?;
     941            0 :                     let permits = input.parse::<usize>().context("expected a number of initial permits, not {s:?}")?;
     942            0 :                     NonZeroUsize::new(permits).context("initial semaphore permits out of range: 0, use other configuration to disable a feature")?
     943              :                 }),
     944           70 :                 "concurrent_tenant_size_logical_size_queries" => builder.concurrent_tenant_size_logical_size_queries({
     945            0 :                     let input = parse_toml_string(key, item)?;
     946            0 :                     let permits = input.parse::<usize>().context("expected a number of initial permits, not {s:?}")?;
     947            0 :                     NonZeroUsize::new(permits).context("initial semaphore permits out of range: 0, use other configuration to disable a feature")?
     948              :                 }),
     949           70 :                 "metric_collection_interval" => builder.metric_collection_interval(parse_toml_duration(key, item)?),
     950           54 :                 "cached_metric_collection_interval" => builder.cached_metric_collection_interval(parse_toml_duration(key, item)?),
     951           42 :                 "metric_collection_endpoint" => {
     952           16 :                     let endpoint = parse_toml_string(key, item)?.parse().context("failed to parse metric_collection_endpoint")?;
     953           16 :                     builder.metric_collection_endpoint(Some(endpoint));
     954              :                 },
     955           26 :                 "metric_collection_bucket" => {
     956            0 :                     builder.metric_collection_bucket(RemoteStorageConfig::from_toml(item)?)
     957              :                 }
     958           26 :                 "synthetic_size_calculation_interval" =>
     959           12 :                     builder.synthetic_size_calculation_interval(parse_toml_duration(key, item)?),
     960           14 :                 "test_remote_failures" => builder.test_remote_failures(parse_toml_u64(key, item)?),
     961           14 :                 "disk_usage_based_eviction" => {
     962            2 :                     tracing::info!("disk_usage_based_eviction: {:#?}", &item);
     963            2 :                     builder.disk_usage_based_eviction(
     964            2 :                         deserialize_from_item("disk_usage_based_eviction", item)
     965            2 :                             .context("parse disk_usage_based_eviction")?
     966              :                     )
     967              :                 },
     968           12 :                 "ondemand_download_behavior_treat_error_as_warn" => builder.ondemand_download_behavior_treat_error_as_warn(parse_toml_bool(key, item)?),
     969           12 :                 "background_task_maximum_delay" => builder.background_task_maximum_delay(parse_toml_duration(key, item)?),
     970            0 :                 "control_plane_api" => {
     971            0 :                     let parsed = parse_toml_string(key, item)?;
     972            0 :                     if parsed.is_empty() {
     973            0 :                         builder.control_plane_api(None)
     974              :                     } else {
     975            0 :                         builder.control_plane_api(Some(parsed.parse().context("failed to parse control plane URL")?))
     976              :                     }
     977              :                 },
     978            0 :                 "control_plane_api_token" => {
     979            0 :                     let parsed = parse_toml_string(key, item)?;
     980            0 :                     if parsed.is_empty() {
     981            0 :                         builder.control_plane_api_token(None)
     982              :                     } else {
     983            0 :                         builder.control_plane_api_token(Some(parsed.into()))
     984              :                     }
     985              :                 },
     986            0 :                 "control_plane_emergency_mode" => {
     987            0 :                     builder.control_plane_emergency_mode(parse_toml_bool(key, item)?)
     988              :                 },
     989            0 :                 "heatmap_upload_concurrency" => {
     990            0 :                     builder.heatmap_upload_concurrency(parse_toml_u64(key, item)? as usize)
     991              :                 },
     992            0 :                 "secondary_download_concurrency" => {
     993            0 :                     builder.secondary_download_concurrency(parse_toml_u64(key, item)? as usize)
     994              :                 },
     995            0 :                 "ingest_batch_size" => builder.ingest_batch_size(parse_toml_u64(key, item)?),
     996            0 :                 "virtual_file_io_engine" => {
     997            0 :                     builder.virtual_file_io_engine(parse_toml_from_str("virtual_file_io_engine", item)?)
     998              :                 }
     999            0 :                 "get_vectored_impl" => {
    1000            0 :                     builder.get_vectored_impl(parse_toml_from_str("get_vectored_impl", item)?)
    1001              :                 }
    1002            0 :                 "get_impl" => {
    1003            0 :                     builder.get_impl(parse_toml_from_str("get_impl", item)?)
    1004              :                 }
    1005            0 :                 "max_vectored_read_bytes" => {
    1006            0 :                     let bytes = parse_toml_u64("max_vectored_read_bytes", item)? as usize;
    1007            0 :                     builder.get_max_vectored_read_bytes(
    1008            0 :                         MaxVectoredReadBytes(
    1009            0 :                             NonZeroUsize::new(bytes).expect("Max byte size of vectored read must be greater than 0")))
    1010              :                 }
    1011            0 :                 "validate_vectored_get" => {
    1012            0 :                     builder.get_validate_vectored_get(parse_toml_bool("validate_vectored_get", item)?)
    1013              :                 }
    1014            0 :                 "ephemeral_bytes_per_memory_kb" => {
    1015            0 :                     builder.get_ephemeral_bytes_per_memory_kb(parse_toml_u64("ephemeral_bytes_per_memory_kb", item)? as usize)
    1016              :                 }
    1017            0 :                 _ => bail!("unrecognized pageserver option '{key}'"),
    1018              :             }
    1019              :         }
    1020              : 
    1021           18 :         let mut conf = builder.build().context("invalid config")?;
    1022              : 
    1023           18 :         if conf.http_auth_type == AuthType::NeonJWT || conf.pg_auth_type == AuthType::NeonJWT {
    1024            0 :             let auth_validation_public_key_path = conf
    1025            0 :                 .auth_validation_public_key_path
    1026            0 :                 .get_or_insert_with(|| workdir.join("auth_public_key.pem"));
    1027            0 :             ensure!(
    1028            0 :                 auth_validation_public_key_path.exists(),
    1029            0 :                 format!(
    1030            0 :                     "Can't find auth_validation_public_key at '{auth_validation_public_key_path}'",
    1031            0 :                 )
    1032              :             );
    1033           18 :         }
    1034              : 
    1035           18 :         conf.default_tenant_conf = t_conf.merge(TenantConf::default());
    1036           18 : 
    1037           18 :         Ok(conf)
    1038           18 :     }
    1039              : 
    1040              :     #[cfg(test)]
    1041          171 :     pub fn test_repo_dir(test_name: &str) -> Utf8PathBuf {
    1042          171 :         let test_output_dir = std::env::var("TEST_OUTPUT").unwrap_or("../tmp_check".into());
    1043          171 :         Utf8PathBuf::from(format!("{test_output_dir}/test_{test_name}"))
    1044          171 :     }
    1045              : 
    1046          167 :     pub fn dummy_conf(repo_dir: Utf8PathBuf) -> Self {
    1047          167 :         let pg_distrib_dir = Utf8PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../pg_install");
    1048          167 : 
    1049          167 :         PageServerConf {
    1050          167 :             id: NodeId(0),
    1051          167 :             wait_lsn_timeout: Duration::from_secs(60),
    1052          167 :             wal_redo_timeout: Duration::from_secs(60),
    1053          167 :             page_cache_size: defaults::DEFAULT_PAGE_CACHE_SIZE,
    1054          167 :             max_file_descriptors: defaults::DEFAULT_MAX_FILE_DESCRIPTORS,
    1055          167 :             listen_pg_addr: defaults::DEFAULT_PG_LISTEN_ADDR.to_string(),
    1056          167 :             listen_http_addr: defaults::DEFAULT_HTTP_LISTEN_ADDR.to_string(),
    1057          167 :             availability_zone: None,
    1058          167 :             superuser: "cloud_admin".to_string(),
    1059          167 :             workdir: repo_dir,
    1060          167 :             pg_distrib_dir,
    1061          167 :             http_auth_type: AuthType::Trust,
    1062          167 :             pg_auth_type: AuthType::Trust,
    1063          167 :             auth_validation_public_key_path: None,
    1064          167 :             remote_storage_config: None,
    1065          167 :             default_tenant_conf: TenantConf::default(),
    1066          167 :             broker_endpoint: storage_broker::DEFAULT_ENDPOINT.parse().unwrap(),
    1067          167 :             broker_keepalive_interval: Duration::from_secs(5000),
    1068          167 :             log_format: LogFormat::from_str(defaults::DEFAULT_LOG_FORMAT).unwrap(),
    1069          167 :             concurrent_tenant_warmup: ConfigurableSemaphore::new(
    1070          167 :                 NonZeroUsize::new(DEFAULT_CONCURRENT_TENANT_WARMUP)
    1071          167 :                     .expect("Invalid default constant"),
    1072          167 :             ),
    1073          167 :             concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::default(),
    1074          167 :             eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore::default(
    1075          167 :             ),
    1076          167 :             metric_collection_interval: Duration::from_secs(60),
    1077          167 :             cached_metric_collection_interval: Duration::from_secs(60 * 60),
    1078          167 :             metric_collection_endpoint: defaults::DEFAULT_METRIC_COLLECTION_ENDPOINT,
    1079          167 :             metric_collection_bucket: None,
    1080          167 :             synthetic_size_calculation_interval: Duration::from_secs(60),
    1081          167 :             disk_usage_based_eviction: None,
    1082          167 :             test_remote_failures: 0,
    1083          167 :             ondemand_download_behavior_treat_error_as_warn: false,
    1084          167 :             background_task_maximum_delay: Duration::ZERO,
    1085          167 :             control_plane_api: None,
    1086          167 :             control_plane_api_token: None,
    1087          167 :             control_plane_emergency_mode: false,
    1088          167 :             heatmap_upload_concurrency: defaults::DEFAULT_HEATMAP_UPLOAD_CONCURRENCY,
    1089          167 :             secondary_download_concurrency: defaults::DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY,
    1090          167 :             ingest_batch_size: defaults::DEFAULT_INGEST_BATCH_SIZE,
    1091          167 :             virtual_file_io_engine: DEFAULT_VIRTUAL_FILE_IO_ENGINE.parse().unwrap(),
    1092          167 :             get_vectored_impl: defaults::DEFAULT_GET_VECTORED_IMPL.parse().unwrap(),
    1093          167 :             get_impl: defaults::DEFAULT_GET_IMPL.parse().unwrap(),
    1094          167 :             max_vectored_read_bytes: MaxVectoredReadBytes(
    1095          167 :                 NonZeroUsize::new(defaults::DEFAULT_MAX_VECTORED_READ_BYTES)
    1096          167 :                     .expect("Invalid default constant"),
    1097          167 :             ),
    1098          167 :             validate_vectored_get: defaults::DEFAULT_VALIDATE_VECTORED_GET,
    1099          167 :             ephemeral_bytes_per_memory_kb: defaults::DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB,
    1100          167 :         }
    1101          167 :     }
    1102              : }
    1103              : 
    1104              : // Helper functions to parse a toml Item
    1105              : 
    1106           96 : fn parse_toml_string(name: &str, item: &Item) -> Result<String> {
    1107           96 :     let s = item
    1108           96 :         .as_str()
    1109           96 :         .with_context(|| format!("configure option {name} is not a string"))?;
    1110           96 :     Ok(s.to_string())
    1111           96 : }
    1112              : 
    1113           42 : fn parse_toml_u64(name: &str, item: &Item) -> Result<u64> {
    1114              :     // A toml integer is signed, so it cannot represent the full range of an u64. That's OK
    1115              :     // for our use, though.
    1116           42 :     let i: i64 = item
    1117           42 :         .as_integer()
    1118           42 :         .with_context(|| format!("configure option {name} is not an integer"))?;
    1119           42 :     if i < 0 {
    1120            0 :         bail!("configure option {name} cannot be negative");
    1121           42 :     }
    1122           42 :     Ok(i as u64)
    1123           42 : }
    1124              : 
    1125            0 : fn parse_toml_bool(name: &str, item: &Item) -> Result<bool> {
    1126            0 :     item.as_bool()
    1127            0 :         .with_context(|| format!("configure option {name} is not a bool"))
    1128            0 : }
    1129              : 
    1130           76 : fn parse_toml_duration(name: &str, item: &Item) -> Result<Duration> {
    1131           76 :     let s = item
    1132           76 :         .as_str()
    1133           76 :         .with_context(|| format!("configure option {name} is not a string"))?;
    1134              : 
    1135           76 :     Ok(humantime::parse_duration(s)?)
    1136           76 : }
    1137              : 
    1138            0 : fn parse_toml_from_str<T>(name: &str, item: &Item) -> anyhow::Result<T>
    1139            0 : where
    1140            0 :     T: FromStr,
    1141            0 :     <T as FromStr>::Err: std::fmt::Display,
    1142            0 : {
    1143            0 :     let v = item
    1144            0 :         .as_str()
    1145            0 :         .with_context(|| format!("configure option {name} is not a string"))?;
    1146            0 :     T::from_str(v).map_err(|e| {
    1147            0 :         anyhow!(
    1148            0 :             "Failed to parse string as {parse_type} for configure option {name}: {e}",
    1149            0 :             parse_type = stringify!(T)
    1150            0 :         )
    1151            0 :     })
    1152            0 : }
    1153              : 
    1154            2 : fn deserialize_from_item<T>(name: &str, item: &Item) -> anyhow::Result<T>
    1155            2 : where
    1156            2 :     T: serde::de::DeserializeOwned,
    1157            2 : {
    1158              :     // ValueDeserializer::new is not public, so use the ValueDeserializer's documented way
    1159            2 :     let deserializer = match item.clone().into_value() {
    1160            2 :         Ok(value) => value.into_deserializer(),
    1161            0 :         Err(item) => anyhow::bail!("toml_edit::Item '{item}' is not a toml_edit::Value"),
    1162              :     };
    1163            2 :     T::deserialize(deserializer).with_context(|| format!("deserializing item for node {name}"))
    1164            2 : }
    1165              : 
    1166              : /// Configurable semaphore permits setting.
    1167              : ///
    1168              : /// Does not allow semaphore permits to be zero, because at runtime initially zero permits and empty
    1169              : /// semaphore cannot be distinguished, leading any feature using these to await forever (or until
    1170              : /// new permits are added).
    1171              : #[derive(Debug, Clone)]
    1172              : pub struct ConfigurableSemaphore {
    1173              :     initial_permits: NonZeroUsize,
    1174              :     inner: std::sync::Arc<tokio::sync::Semaphore>,
    1175              : }
    1176              : 
    1177              : impl ConfigurableSemaphore {
    1178              :     pub const DEFAULT_INITIAL: NonZeroUsize = match NonZeroUsize::new(1) {
    1179              :         Some(x) => x,
    1180              :         None => panic!("const unwrap is not yet stable"),
    1181              :     };
    1182              : 
    1183              :     /// Initializse using a non-zero amount of permits.
    1184              :     ///
    1185              :     /// Require a non-zero initial permits, because using permits == 0 is a crude way to disable a
    1186              :     /// feature such as [`Tenant::gather_size_inputs`]. Otherwise any semaphore using future will
    1187              :     /// behave like [`futures::future::pending`], just waiting until new permits are added.
    1188              :     ///
    1189              :     /// [`Tenant::gather_size_inputs`]: crate::tenant::Tenant::gather_size_inputs
    1190          567 :     pub fn new(initial_permits: NonZeroUsize) -> Self {
    1191          567 :         ConfigurableSemaphore {
    1192          567 :             initial_permits,
    1193          567 :             inner: std::sync::Arc::new(tokio::sync::Semaphore::new(initial_permits.get())),
    1194          567 :         }
    1195          567 :     }
    1196              : 
    1197              :     /// Returns the configured amount of permits.
    1198            0 :     pub fn initial_permits(&self) -> NonZeroUsize {
    1199            0 :         self.initial_permits
    1200            0 :     }
    1201              : }
    1202              : 
    1203              : impl Default for ConfigurableSemaphore {
    1204          342 :     fn default() -> Self {
    1205          342 :         Self::new(Self::DEFAULT_INITIAL)
    1206          342 :     }
    1207              : }
    1208              : 
    1209              : impl PartialEq for ConfigurableSemaphore {
    1210           12 :     fn eq(&self, other: &Self) -> bool {
    1211           12 :         // the number of permits can be increased at runtime, so we cannot really fulfill the
    1212           12 :         // PartialEq value equality otherwise
    1213           12 :         self.initial_permits == other.initial_permits
    1214           12 :     }
    1215              : }
    1216              : 
    1217              : impl Eq for ConfigurableSemaphore {}
    1218              : 
    1219              : impl ConfigurableSemaphore {
    1220            0 :     pub fn inner(&self) -> &std::sync::Arc<tokio::sync::Semaphore> {
    1221            0 :         &self.inner
    1222            0 :     }
    1223              : }
    1224              : 
    1225              : #[cfg(test)]
    1226              : mod tests {
    1227              :     use std::{fs, num::NonZeroU32};
    1228              : 
    1229              :     use camino_tempfile::{tempdir, Utf8TempDir};
    1230              :     use pageserver_api::models::EvictionPolicy;
    1231              :     use remote_storage::{RemoteStorageKind, S3Config};
    1232              :     use utils::serde_percent::Percent;
    1233              : 
    1234              :     use super::*;
    1235              :     use crate::DEFAULT_PG_VERSION;
    1236              : 
    1237              :     const ALL_BASE_VALUES_TOML: &str = r#"
    1238              : # Initial configuration file created by 'pageserver --init'
    1239              : 
    1240              : listen_pg_addr = '127.0.0.1:64000'
    1241              : listen_http_addr = '127.0.0.1:9898'
    1242              : 
    1243              : wait_lsn_timeout = '111 s'
    1244              : wal_redo_timeout = '111 s'
    1245              : 
    1246              : page_cache_size = 444
    1247              : max_file_descriptors = 333
    1248              : 
    1249              : # initial superuser role name to use when creating a new tenant
    1250              : initial_superuser_name = 'zzzz'
    1251              : id = 10
    1252              : 
    1253              : metric_collection_interval = '222 s'
    1254              : cached_metric_collection_interval = '22200 s'
    1255              : metric_collection_endpoint = 'http://localhost:80/metrics'
    1256              : synthetic_size_calculation_interval = '333 s'
    1257              : 
    1258              : log_format = 'json'
    1259              : background_task_maximum_delay = '334 s'
    1260              : 
    1261              : "#;
    1262              : 
    1263              :     #[test]
    1264            2 :     fn parse_defaults() -> anyhow::Result<()> {
    1265            2 :         let tempdir = tempdir()?;
    1266            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1267            2 :         let broker_endpoint = storage_broker::DEFAULT_ENDPOINT;
    1268            2 :         // we have to create dummy values to overcome the validation errors
    1269            2 :         let config_string = format!(
    1270            2 :             "pg_distrib_dir='{pg_distrib_dir}'\nid=10\nbroker_endpoint = '{broker_endpoint}'",
    1271            2 :         );
    1272            2 :         let toml = config_string.parse()?;
    1273              : 
    1274            2 :         let parsed_config = PageServerConf::parse_and_validate(&toml, &workdir)
    1275            2 :             .unwrap_or_else(|e| panic!("Failed to parse config '{config_string}', reason: {e:?}"));
    1276            2 : 
    1277            2 :         assert_eq!(
    1278            2 :             parsed_config,
    1279            2 :             PageServerConf {
    1280            2 :                 id: NodeId(10),
    1281            2 :                 listen_pg_addr: defaults::DEFAULT_PG_LISTEN_ADDR.to_string(),
    1282            2 :                 listen_http_addr: defaults::DEFAULT_HTTP_LISTEN_ADDR.to_string(),
    1283            2 :                 availability_zone: None,
    1284            2 :                 wait_lsn_timeout: humantime::parse_duration(defaults::DEFAULT_WAIT_LSN_TIMEOUT)?,
    1285            2 :                 wal_redo_timeout: humantime::parse_duration(defaults::DEFAULT_WAL_REDO_TIMEOUT)?,
    1286            2 :                 superuser: defaults::DEFAULT_SUPERUSER.to_string(),
    1287            2 :                 page_cache_size: defaults::DEFAULT_PAGE_CACHE_SIZE,
    1288            2 :                 max_file_descriptors: defaults::DEFAULT_MAX_FILE_DESCRIPTORS,
    1289            2 :                 workdir,
    1290            2 :                 pg_distrib_dir,
    1291            2 :                 http_auth_type: AuthType::Trust,
    1292            2 :                 pg_auth_type: AuthType::Trust,
    1293            2 :                 auth_validation_public_key_path: None,
    1294            2 :                 remote_storage_config: None,
    1295            2 :                 default_tenant_conf: TenantConf::default(),
    1296            2 :                 broker_endpoint: storage_broker::DEFAULT_ENDPOINT.parse().unwrap(),
    1297            2 :                 broker_keepalive_interval: humantime::parse_duration(
    1298            2 :                     storage_broker::DEFAULT_KEEPALIVE_INTERVAL
    1299            2 :                 )?,
    1300            2 :                 log_format: LogFormat::from_str(defaults::DEFAULT_LOG_FORMAT).unwrap(),
    1301            2 :                 concurrent_tenant_warmup: ConfigurableSemaphore::new(
    1302            2 :                     NonZeroUsize::new(DEFAULT_CONCURRENT_TENANT_WARMUP).unwrap()
    1303            2 :                 ),
    1304            2 :                 concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::default(),
    1305            2 :                 eviction_task_immitated_concurrent_logical_size_queries:
    1306            2 :                     ConfigurableSemaphore::default(),
    1307            2 :                 metric_collection_interval: humantime::parse_duration(
    1308            2 :                     defaults::DEFAULT_METRIC_COLLECTION_INTERVAL
    1309            2 :                 )?,
    1310            2 :                 cached_metric_collection_interval: humantime::parse_duration(
    1311            2 :                     defaults::DEFAULT_CACHED_METRIC_COLLECTION_INTERVAL
    1312            2 :                 )?,
    1313            2 :                 metric_collection_endpoint: defaults::DEFAULT_METRIC_COLLECTION_ENDPOINT,
    1314            2 :                 metric_collection_bucket: None,
    1315            2 :                 synthetic_size_calculation_interval: humantime::parse_duration(
    1316            2 :                     defaults::DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL
    1317            2 :                 )?,
    1318            2 :                 disk_usage_based_eviction: None,
    1319            2 :                 test_remote_failures: 0,
    1320            2 :                 ondemand_download_behavior_treat_error_as_warn: false,
    1321            2 :                 background_task_maximum_delay: humantime::parse_duration(
    1322            2 :                     defaults::DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY
    1323            2 :                 )?,
    1324            2 :                 control_plane_api: None,
    1325            2 :                 control_plane_api_token: None,
    1326            2 :                 control_plane_emergency_mode: false,
    1327            2 :                 heatmap_upload_concurrency: defaults::DEFAULT_HEATMAP_UPLOAD_CONCURRENCY,
    1328            2 :                 secondary_download_concurrency: defaults::DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY,
    1329            2 :                 ingest_batch_size: defaults::DEFAULT_INGEST_BATCH_SIZE,
    1330            2 :                 virtual_file_io_engine: DEFAULT_VIRTUAL_FILE_IO_ENGINE.parse().unwrap(),
    1331            2 :                 get_vectored_impl: defaults::DEFAULT_GET_VECTORED_IMPL.parse().unwrap(),
    1332            2 :                 get_impl: defaults::DEFAULT_GET_IMPL.parse().unwrap(),
    1333            2 :                 max_vectored_read_bytes: MaxVectoredReadBytes(
    1334            2 :                     NonZeroUsize::new(defaults::DEFAULT_MAX_VECTORED_READ_BYTES)
    1335            2 :                         .expect("Invalid default constant")
    1336            2 :                 ),
    1337              :                 validate_vectored_get: defaults::DEFAULT_VALIDATE_VECTORED_GET,
    1338              :                 ephemeral_bytes_per_memory_kb: defaults::DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB,
    1339              :             },
    1340            0 :             "Correct defaults should be used when no config values are provided"
    1341              :         );
    1342              : 
    1343            2 :         Ok(())
    1344            2 :     }
    1345              : 
    1346              :     #[test]
    1347            2 :     fn parse_basic_config() -> anyhow::Result<()> {
    1348            2 :         let tempdir = tempdir()?;
    1349            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1350            2 :         let broker_endpoint = storage_broker::DEFAULT_ENDPOINT;
    1351            2 : 
    1352            2 :         let config_string = format!(
    1353            2 :             "{ALL_BASE_VALUES_TOML}pg_distrib_dir='{pg_distrib_dir}'\nbroker_endpoint = '{broker_endpoint}'",
    1354            2 :         );
    1355            2 :         let toml = config_string.parse()?;
    1356              : 
    1357            2 :         let parsed_config = PageServerConf::parse_and_validate(&toml, &workdir)
    1358            2 :             .unwrap_or_else(|e| panic!("Failed to parse config '{config_string}', reason: {e:?}"));
    1359            2 : 
    1360            2 :         assert_eq!(
    1361            2 :             parsed_config,
    1362            2 :             PageServerConf {
    1363            2 :                 id: NodeId(10),
    1364            2 :                 listen_pg_addr: "127.0.0.1:64000".to_string(),
    1365            2 :                 listen_http_addr: "127.0.0.1:9898".to_string(),
    1366            2 :                 availability_zone: None,
    1367            2 :                 wait_lsn_timeout: Duration::from_secs(111),
    1368            2 :                 wal_redo_timeout: Duration::from_secs(111),
    1369            2 :                 superuser: "zzzz".to_string(),
    1370            2 :                 page_cache_size: 444,
    1371            2 :                 max_file_descriptors: 333,
    1372            2 :                 workdir,
    1373            2 :                 pg_distrib_dir,
    1374            2 :                 http_auth_type: AuthType::Trust,
    1375            2 :                 pg_auth_type: AuthType::Trust,
    1376            2 :                 auth_validation_public_key_path: None,
    1377            2 :                 remote_storage_config: None,
    1378            2 :                 default_tenant_conf: TenantConf::default(),
    1379            2 :                 broker_endpoint: storage_broker::DEFAULT_ENDPOINT.parse().unwrap(),
    1380            2 :                 broker_keepalive_interval: Duration::from_secs(5),
    1381            2 :                 log_format: LogFormat::Json,
    1382            2 :                 concurrent_tenant_warmup: ConfigurableSemaphore::new(
    1383            2 :                     NonZeroUsize::new(DEFAULT_CONCURRENT_TENANT_WARMUP).unwrap()
    1384            2 :                 ),
    1385            2 :                 concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::default(),
    1386            2 :                 eviction_task_immitated_concurrent_logical_size_queries:
    1387            2 :                     ConfigurableSemaphore::default(),
    1388            2 :                 metric_collection_interval: Duration::from_secs(222),
    1389            2 :                 cached_metric_collection_interval: Duration::from_secs(22200),
    1390            2 :                 metric_collection_endpoint: Some(Url::parse("http://localhost:80/metrics")?),
    1391            2 :                 metric_collection_bucket: None,
    1392            2 :                 synthetic_size_calculation_interval: Duration::from_secs(333),
    1393            2 :                 disk_usage_based_eviction: None,
    1394            2 :                 test_remote_failures: 0,
    1395            2 :                 ondemand_download_behavior_treat_error_as_warn: false,
    1396            2 :                 background_task_maximum_delay: Duration::from_secs(334),
    1397            2 :                 control_plane_api: None,
    1398            2 :                 control_plane_api_token: None,
    1399            2 :                 control_plane_emergency_mode: false,
    1400            2 :                 heatmap_upload_concurrency: defaults::DEFAULT_HEATMAP_UPLOAD_CONCURRENCY,
    1401            2 :                 secondary_download_concurrency: defaults::DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY,
    1402            2 :                 ingest_batch_size: 100,
    1403            2 :                 virtual_file_io_engine: DEFAULT_VIRTUAL_FILE_IO_ENGINE.parse().unwrap(),
    1404            2 :                 get_vectored_impl: defaults::DEFAULT_GET_VECTORED_IMPL.parse().unwrap(),
    1405            2 :                 get_impl: defaults::DEFAULT_GET_IMPL.parse().unwrap(),
    1406            2 :                 max_vectored_read_bytes: MaxVectoredReadBytes(
    1407            2 :                     NonZeroUsize::new(defaults::DEFAULT_MAX_VECTORED_READ_BYTES)
    1408            2 :                         .expect("Invalid default constant")
    1409            2 :                 ),
    1410              :                 validate_vectored_get: defaults::DEFAULT_VALIDATE_VECTORED_GET,
    1411              :                 ephemeral_bytes_per_memory_kb: defaults::DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB,
    1412              :             },
    1413            0 :             "Should be able to parse all basic config values correctly"
    1414              :         );
    1415              : 
    1416            2 :         Ok(())
    1417            2 :     }
    1418              : 
    1419              :     #[test]
    1420            2 :     fn parse_remote_fs_storage_config() -> anyhow::Result<()> {
    1421            2 :         let tempdir = tempdir()?;
    1422            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1423            2 :         let broker_endpoint = "http://127.0.0.1:7777";
    1424            2 : 
    1425            2 :         let local_storage_path = tempdir.path().join("local_remote_storage");
    1426            2 : 
    1427            2 :         let identical_toml_declarations = &[
    1428            2 :             format!(
    1429            2 :                 r#"[remote_storage]
    1430            2 : local_path = '{local_storage_path}'"#,
    1431            2 :             ),
    1432            2 :             format!("remote_storage={{local_path='{local_storage_path}'}}"),
    1433            2 :         ];
    1434              : 
    1435            6 :         for remote_storage_config_str in identical_toml_declarations {
    1436            4 :             let config_string = format!(
    1437            4 :                 r#"{ALL_BASE_VALUES_TOML}
    1438            4 : pg_distrib_dir='{pg_distrib_dir}'
    1439            4 : broker_endpoint = '{broker_endpoint}'
    1440            4 : 
    1441            4 : {remote_storage_config_str}"#,
    1442            4 :             );
    1443              : 
    1444            4 :             let toml = config_string.parse()?;
    1445              : 
    1446            4 :             let parsed_remote_storage_config = PageServerConf::parse_and_validate(&toml, &workdir)
    1447            4 :                 .unwrap_or_else(|e| {
    1448            0 :                     panic!("Failed to parse config '{config_string}', reason: {e:?}")
    1449            4 :                 })
    1450            4 :                 .remote_storage_config
    1451            4 :                 .expect("Should have remote storage config for the local FS");
    1452            4 : 
    1453            4 :             assert_eq!(
    1454            4 :                 parsed_remote_storage_config,
    1455            4 :                 RemoteStorageConfig {
    1456            4 :                     storage: RemoteStorageKind::LocalFs { local_path: local_storage_path.clone() },
    1457            4 :                     timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    1458            4 :                 },
    1459            0 :                 "Remote storage config should correctly parse the local FS config and fill other storage defaults"
    1460              :             );
    1461              :         }
    1462            2 :         Ok(())
    1463            2 :     }
    1464              : 
    1465              :     #[test]
    1466            2 :     fn parse_remote_s3_storage_config() -> anyhow::Result<()> {
    1467            2 :         let tempdir = tempdir()?;
    1468            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1469              : 
    1470            2 :         let bucket_name = "some-sample-bucket".to_string();
    1471            2 :         let bucket_region = "eu-north-1".to_string();
    1472            2 :         let prefix_in_bucket = "test_prefix".to_string();
    1473            2 :         let endpoint = "http://localhost:5000".to_string();
    1474            2 :         let max_concurrent_syncs = NonZeroUsize::new(111).unwrap();
    1475            2 :         let max_sync_errors = NonZeroU32::new(222).unwrap();
    1476            2 :         let s3_concurrency_limit = NonZeroUsize::new(333).unwrap();
    1477            2 :         let broker_endpoint = "http://127.0.0.1:7777";
    1478            2 : 
    1479            2 :         let identical_toml_declarations = &[
    1480            2 :             format!(
    1481            2 :                 r#"[remote_storage]
    1482            2 : max_concurrent_syncs = {max_concurrent_syncs}
    1483            2 : max_sync_errors = {max_sync_errors}
    1484            2 : bucket_name = '{bucket_name}'
    1485            2 : bucket_region = '{bucket_region}'
    1486            2 : prefix_in_bucket = '{prefix_in_bucket}'
    1487            2 : endpoint = '{endpoint}'
    1488            2 : concurrency_limit = {s3_concurrency_limit}"#
    1489            2 :             ),
    1490            2 :             format!(
    1491            2 :                 "remote_storage={{max_concurrent_syncs={max_concurrent_syncs}, max_sync_errors={max_sync_errors}, bucket_name='{bucket_name}',\
    1492            2 :                 bucket_region='{bucket_region}', prefix_in_bucket='{prefix_in_bucket}', endpoint='{endpoint}', concurrency_limit={s3_concurrency_limit}}}",
    1493            2 :             ),
    1494            2 :         ];
    1495              : 
    1496            6 :         for remote_storage_config_str in identical_toml_declarations {
    1497            4 :             let config_string = format!(
    1498            4 :                 r#"{ALL_BASE_VALUES_TOML}
    1499            4 : pg_distrib_dir='{pg_distrib_dir}'
    1500            4 : broker_endpoint = '{broker_endpoint}'
    1501            4 : 
    1502            4 : {remote_storage_config_str}"#,
    1503            4 :             );
    1504              : 
    1505            4 :             let toml = config_string.parse()?;
    1506              : 
    1507            4 :             let parsed_remote_storage_config = PageServerConf::parse_and_validate(&toml, &workdir)
    1508            4 :                 .unwrap_or_else(|e| {
    1509            0 :                     panic!("Failed to parse config '{config_string}', reason: {e:?}")
    1510            4 :                 })
    1511            4 :                 .remote_storage_config
    1512            4 :                 .expect("Should have remote storage config for S3");
    1513            4 : 
    1514            4 :             assert_eq!(
    1515            4 :                 parsed_remote_storage_config,
    1516            4 :                 RemoteStorageConfig {
    1517            4 :                     storage: RemoteStorageKind::AwsS3(S3Config {
    1518            4 :                         bucket_name: bucket_name.clone(),
    1519            4 :                         bucket_region: bucket_region.clone(),
    1520            4 :                         prefix_in_bucket: Some(prefix_in_bucket.clone()),
    1521            4 :                         endpoint: Some(endpoint.clone()),
    1522            4 :                         concurrency_limit: s3_concurrency_limit,
    1523            4 :                         max_keys_per_list_response: None,
    1524            4 :                         upload_storage_class: None,
    1525            4 :                     }),
    1526            4 :                     timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    1527            4 :                 },
    1528            0 :                 "Remote storage config should correctly parse the S3 config"
    1529              :             );
    1530              :         }
    1531            2 :         Ok(())
    1532            2 :     }
    1533              : 
    1534              :     #[test]
    1535            2 :     fn parse_tenant_config() -> anyhow::Result<()> {
    1536            2 :         let tempdir = tempdir()?;
    1537            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1538              : 
    1539            2 :         let broker_endpoint = "http://127.0.0.1:7777";
    1540            2 :         let trace_read_requests = true;
    1541            2 : 
    1542            2 :         let config_string = format!(
    1543            2 :             r#"{ALL_BASE_VALUES_TOML}
    1544            2 : pg_distrib_dir='{pg_distrib_dir}'
    1545            2 : broker_endpoint = '{broker_endpoint}'
    1546            2 : 
    1547            2 : [tenant_config]
    1548            2 : trace_read_requests = {trace_read_requests}"#,
    1549            2 :         );
    1550              : 
    1551            2 :         let toml = config_string.parse()?;
    1552              : 
    1553            2 :         let conf = PageServerConf::parse_and_validate(&toml, &workdir)?;
    1554            2 :         assert_eq!(
    1555              :             conf.default_tenant_conf.trace_read_requests, trace_read_requests,
    1556            0 :             "Tenant config from pageserver config file should be parsed and udpated values used as defaults for all tenants",
    1557              :         );
    1558              : 
    1559            2 :         Ok(())
    1560            2 :     }
    1561              : 
    1562              :     #[test]
    1563            2 :     fn parse_incorrect_tenant_config() -> anyhow::Result<()> {
    1564            2 :         let config_string = r#"
    1565            2 :             [tenant_config]
    1566            2 :             checkpoint_distance = -1 # supposed to be an u64
    1567            2 :         "#
    1568            2 :         .to_string();
    1569              : 
    1570            2 :         let toml: Document = config_string.parse()?;
    1571            2 :         let item = toml.get("tenant_config").unwrap();
    1572            2 :         let error = TenantConfOpt::try_from(item.to_owned()).unwrap_err();
    1573            2 : 
    1574            2 :         let expected_error_str = "checkpoint_distance: invalid value: integer `-1`, expected u64";
    1575            2 :         assert_eq!(error.to_string(), expected_error_str);
    1576              : 
    1577            2 :         Ok(())
    1578            2 :     }
    1579              : 
    1580              :     #[test]
    1581            2 :     fn parse_override_tenant_config() -> anyhow::Result<()> {
    1582            2 :         let config_string = r#"tenant_config={ min_resident_size_override =  400 }"#.to_string();
    1583              : 
    1584            2 :         let toml: Document = config_string.parse()?;
    1585            2 :         let item = toml.get("tenant_config").unwrap();
    1586            2 :         let conf = TenantConfOpt::try_from(item.to_owned()).unwrap();
    1587            2 : 
    1588            2 :         assert_eq!(conf.min_resident_size_override, Some(400));
    1589              : 
    1590            2 :         Ok(())
    1591            2 :     }
    1592              : 
    1593              :     #[test]
    1594            2 :     fn eviction_pageserver_config_parse() -> anyhow::Result<()> {
    1595            2 :         let tempdir = tempdir()?;
    1596            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir)?;
    1597              : 
    1598            2 :         let pageserver_conf_toml = format!(
    1599            2 :             r#"pg_distrib_dir = "{pg_distrib_dir}"
    1600            2 : metric_collection_endpoint = "http://sample.url"
    1601            2 : metric_collection_interval = "10min"
    1602            2 : id = 222
    1603            2 : 
    1604            2 : [disk_usage_based_eviction]
    1605            2 : max_usage_pct = 80
    1606            2 : min_avail_bytes = 0
    1607            2 : period = "10s"
    1608            2 : 
    1609            2 : [tenant_config]
    1610            2 : evictions_low_residence_duration_metric_threshold = "20m"
    1611            2 : 
    1612            2 : [tenant_config.eviction_policy]
    1613            2 : kind = "LayerAccessThreshold"
    1614            2 : period = "20m"
    1615            2 : threshold = "20m"
    1616            2 : "#,
    1617            2 :         );
    1618            2 :         let toml: Document = pageserver_conf_toml.parse()?;
    1619            2 :         let conf = PageServerConf::parse_and_validate(&toml, &workdir)?;
    1620              : 
    1621            2 :         assert_eq!(conf.pg_distrib_dir, pg_distrib_dir);
    1622            2 :         assert_eq!(
    1623            2 :             conf.metric_collection_endpoint,
    1624            2 :             Some("http://sample.url".parse().unwrap())
    1625            2 :         );
    1626            2 :         assert_eq!(
    1627            2 :             conf.metric_collection_interval,
    1628            2 :             Duration::from_secs(10 * 60)
    1629            2 :         );
    1630            2 :         assert_eq!(
    1631            2 :             conf.default_tenant_conf
    1632            2 :                 .evictions_low_residence_duration_metric_threshold,
    1633            2 :             Duration::from_secs(20 * 60)
    1634            2 :         );
    1635            2 :         assert_eq!(conf.id, NodeId(222));
    1636            2 :         assert_eq!(
    1637            2 :             conf.disk_usage_based_eviction,
    1638            2 :             Some(DiskUsageEvictionTaskConfig {
    1639            2 :                 max_usage_pct: Percent::new(80).unwrap(),
    1640            2 :                 min_avail_bytes: 0,
    1641            2 :                 period: Duration::from_secs(10),
    1642            2 :                 #[cfg(feature = "testing")]
    1643            2 :                 mock_statvfs: None,
    1644            2 :                 eviction_order: crate::disk_usage_eviction_task::EvictionOrder::AbsoluteAccessed,
    1645            2 :             })
    1646            2 :         );
    1647              : 
    1648            2 :         match &conf.default_tenant_conf.eviction_policy {
    1649            2 :             EvictionPolicy::LayerAccessThreshold(eviction_threshold) => {
    1650            2 :                 assert_eq!(eviction_threshold.period, Duration::from_secs(20 * 60));
    1651            2 :                 assert_eq!(eviction_threshold.threshold, Duration::from_secs(20 * 60));
    1652              :             }
    1653            0 :             other => unreachable!("Unexpected eviction policy tenant settings: {other:?}"),
    1654              :         }
    1655              : 
    1656            2 :         Ok(())
    1657            2 :     }
    1658              : 
    1659              :     #[test]
    1660            2 :     fn parse_imitation_only_pageserver_config() {
    1661            2 :         let tempdir = tempdir().unwrap();
    1662            2 :         let (workdir, pg_distrib_dir) = prepare_fs(&tempdir).unwrap();
    1663            2 : 
    1664            2 :         let pageserver_conf_toml = format!(
    1665            2 :             r#"pg_distrib_dir = "{pg_distrib_dir}"
    1666            2 : metric_collection_endpoint = "http://sample.url"
    1667            2 : metric_collection_interval = "10min"
    1668            2 : id = 222
    1669            2 : 
    1670            2 : [tenant_config]
    1671            2 : evictions_low_residence_duration_metric_threshold = "20m"
    1672            2 : 
    1673            2 : [tenant_config.eviction_policy]
    1674            2 : kind = "OnlyImitiate"
    1675            2 : period = "20m"
    1676            2 : threshold = "20m"
    1677            2 : "#,
    1678            2 :         );
    1679            2 :         let toml: Document = pageserver_conf_toml.parse().unwrap();
    1680            2 :         let conf = PageServerConf::parse_and_validate(&toml, &workdir).unwrap();
    1681            2 : 
    1682            2 :         match &conf.default_tenant_conf.eviction_policy {
    1683            2 :             EvictionPolicy::OnlyImitiate(t) => {
    1684            2 :                 assert_eq!(t.period, Duration::from_secs(20 * 60));
    1685            2 :                 assert_eq!(t.threshold, Duration::from_secs(20 * 60));
    1686              :             }
    1687            0 :             other => unreachable!("Unexpected eviction policy tenant settings: {other:?}"),
    1688              :         }
    1689            2 :     }
    1690              : 
    1691           14 :     fn prepare_fs(tempdir: &Utf8TempDir) -> anyhow::Result<(Utf8PathBuf, Utf8PathBuf)> {
    1692           14 :         let tempdir_path = tempdir.path();
    1693           14 : 
    1694           14 :         let workdir = tempdir_path.join("workdir");
    1695           14 :         fs::create_dir_all(&workdir)?;
    1696              : 
    1697           14 :         let pg_distrib_dir = tempdir_path.join("pg_distrib");
    1698           14 :         let pg_distrib_dir_versioned = pg_distrib_dir.join(format!("v{DEFAULT_PG_VERSION}"));
    1699           14 :         fs::create_dir_all(&pg_distrib_dir_versioned)?;
    1700           14 :         let postgres_bin_dir = pg_distrib_dir_versioned.join("bin");
    1701           14 :         fs::create_dir_all(&postgres_bin_dir)?;
    1702           14 :         fs::write(postgres_bin_dir.join("postgres"), "I'm postgres, trust me")?;
    1703              : 
    1704           14 :         Ok((workdir, pg_distrib_dir))
    1705           14 :     }
    1706              : }
        

Generated by: LCOV version 2.1-beta