LCOV - code coverage report
Current view: top level - pageserver/src - config.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 77.6 % 1005 780
Test Date: 2024-05-10 13:18:37 Functions: 54.1 % 133 72

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

Generated by: LCOV version 2.1-beta