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