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