Line data Source code
1 : use camino::Utf8PathBuf;
2 :
3 : #[cfg(test)]
4 : mod tests;
5 :
6 : use const_format::formatcp;
7 : pub const DEFAULT_PG_LISTEN_PORT: u16 = 64000;
8 : pub const DEFAULT_PG_LISTEN_ADDR: &str = formatcp!("127.0.0.1:{DEFAULT_PG_LISTEN_PORT}");
9 : pub const DEFAULT_HTTP_LISTEN_PORT: u16 = 9898;
10 : pub const DEFAULT_HTTP_LISTEN_ADDR: &str = formatcp!("127.0.0.1:{DEFAULT_HTTP_LISTEN_PORT}");
11 :
12 : use std::collections::HashMap;
13 : use std::num::{NonZeroU64, NonZeroUsize};
14 : use std::str::FromStr;
15 : use std::time::Duration;
16 :
17 : use postgres_backend::AuthType;
18 : use remote_storage::RemoteStorageConfig;
19 : use serde_with::serde_as;
20 : use utils::logging::LogFormat;
21 : use utils::postgres_client::PostgresClientProtocol;
22 :
23 : use crate::models::{ImageCompressionAlgorithm, LsnLease};
24 :
25 : // Certain metadata (e.g. externally-addressable name, AZ) is delivered
26 : // as a separate structure. This information is not neeed by the pageserver
27 : // itself, it is only used for registering the pageserver with the control
28 : // plane and/or storage controller.
29 : //
30 9 : #[derive(PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
31 : pub struct NodeMetadata {
32 : #[serde(rename = "host")]
33 : pub postgres_host: String,
34 : #[serde(rename = "port")]
35 : pub postgres_port: u16,
36 : pub http_host: String,
37 : pub http_port: u16,
38 : pub https_port: Option<u16>,
39 :
40 : // Deployment tools may write fields to the metadata file beyond what we
41 : // use in this type: this type intentionally only names fields that require.
42 : #[serde(flatten)]
43 : pub other: HashMap<String, serde_json::Value>,
44 : }
45 :
46 : /// `pageserver.toml`
47 : ///
48 : /// We use serde derive with `#[serde(default)]` to generate a deserializer
49 : /// that fills in the default values for each config field.
50 : ///
51 : /// If there cannot be a static default value because we need to make runtime
52 : /// checks to determine the default, make it an `Option` (which defaults to None).
53 : /// The runtime check should be done in the consuming crate, i.e., `pageserver`.
54 : ///
55 : /// Unknown fields are silently ignored during deserialization.
56 : /// The alternative, which we used in the past, was to set `deny_unknown_fields`,
57 : /// which fails deserialization, and hence pageserver startup, if there is an unknown field.
58 : /// The reason we don't do that anymore is that it complicates
59 : /// usage of config fields for feature flagging, which we commonly do for
60 : /// region-by-region rollouts.
61 : /// The complications mainly arise because the `pageserver.toml` contents on a
62 : /// prod server have a separate lifecycle from the pageserver binary.
63 : /// For instance, `pageserver.toml` contents today are defined in the internal
64 : /// infra repo, and thus introducing a new config field to pageserver and
65 : /// rolling it out to prod servers are separate commits in separate repos
66 : /// that can't be made or rolled back atomically.
67 : /// Rollbacks in particular pose a risk with deny_unknown_fields because
68 : /// the old pageserver binary may reject a new config field, resulting in
69 : /// an outage unless the person doing the pageserver rollback remembers
70 : /// to also revert the commit that added the config field in to the
71 : /// `pageserver.toml` templates in the internal infra repo.
72 : /// (A pre-deploy config check would eliminate this risk during rollbacks,
73 : /// cf [here](https://github.com/neondatabase/cloud/issues/24349).)
74 : /// In addition to this compatibility problem during emergency rollbacks,
75 : /// deny_unknown_fields adds further complications when decomissioning a feature
76 : /// flag: with deny_unknown_fields, we can't remove a flag from the [`ConfigToml`]
77 : /// until all prod servers' `pageserver.toml` files have been updated to a version
78 : /// that doesn't specify the flag. Otherwise new software would fail to start up.
79 : /// This adds the requirement for an intermediate step where the new config field
80 : /// is accepted but ignored, prolonging the decomissioning process by an entire
81 : /// release cycle.
82 : /// By contrast with unknown fields silently ignored, decomissioning a feature
83 : /// flag is a one-step process: we can skip the intermediate step and straight
84 : /// remove the field from the [`ConfigToml`]. We leave the field in the
85 : /// `pageserver.toml` files on prod servers until we reach certainty that we
86 : /// will not roll back to old software whose behavior was dependent on config.
87 : /// Then we can remove the field from the templates in the internal infra repo.
88 : /// This process is [documented internally](
89 : /// https://docs.neon.build/storage/pageserver_configuration.html).
90 : ///
91 : /// Note that above relaxed compatbility for the config format does NOT APPLY
92 : /// TO THE STORAGE FORMAT. As general guidance, when introducing storage format
93 : /// changes, ensure that the potential rollback target version will be compatible
94 : /// with the new format. This must hold regardless of what flags are set in in the `pageserver.toml`:
95 : /// any format version that exists in an environment must be compatible with the software that runs there.
96 : /// Use a pageserver.toml flag only to gate whether software _writes_ the new format.
97 : /// For more compatibility considerations, refer to [internal docs](
98 : /// https://docs.neon.build/storage/compat.html?highlight=compat#format-versions--compatibility)
99 : #[serde_as]
100 3 : #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
101 : #[serde(default)]
102 : pub struct ConfigToml {
103 : // types mapped 1:1 into the runtime PageServerConfig type
104 : pub listen_pg_addr: String,
105 : pub listen_http_addr: String,
106 : pub listen_https_addr: Option<String>,
107 : pub ssl_key_file: Utf8PathBuf,
108 : pub ssl_cert_file: Utf8PathBuf,
109 : #[serde(with = "humantime_serde")]
110 : pub ssl_cert_reload_period: Duration,
111 : pub ssl_ca_file: Option<Utf8PathBuf>,
112 : pub availability_zone: Option<String>,
113 : #[serde(with = "humantime_serde")]
114 : pub wait_lsn_timeout: Duration,
115 : #[serde(with = "humantime_serde")]
116 : pub wal_redo_timeout: Duration,
117 : pub superuser: String,
118 : pub locale: String,
119 : pub page_cache_size: usize,
120 : pub max_file_descriptors: usize,
121 : pub pg_distrib_dir: Option<Utf8PathBuf>,
122 : #[serde_as(as = "serde_with::DisplayFromStr")]
123 : pub http_auth_type: AuthType,
124 : #[serde_as(as = "serde_with::DisplayFromStr")]
125 : pub pg_auth_type: AuthType,
126 : pub auth_validation_public_key_path: Option<Utf8PathBuf>,
127 : pub remote_storage: Option<RemoteStorageConfig>,
128 : pub tenant_config: TenantConfigToml,
129 : #[serde_as(as = "serde_with::DisplayFromStr")]
130 : pub broker_endpoint: storage_broker::Uri,
131 : #[serde(with = "humantime_serde")]
132 : pub broker_keepalive_interval: Duration,
133 : #[serde_as(as = "serde_with::DisplayFromStr")]
134 : pub log_format: LogFormat,
135 : pub concurrent_tenant_warmup: NonZeroUsize,
136 : pub concurrent_tenant_size_logical_size_queries: NonZeroUsize,
137 : #[serde(with = "humantime_serde")]
138 : pub metric_collection_interval: Duration,
139 : pub metric_collection_endpoint: Option<reqwest::Url>,
140 : pub metric_collection_bucket: Option<RemoteStorageConfig>,
141 : #[serde(with = "humantime_serde")]
142 : pub synthetic_size_calculation_interval: Duration,
143 : pub disk_usage_based_eviction: Option<DiskUsageEvictionTaskConfig>,
144 : pub test_remote_failures: u64,
145 : pub ondemand_download_behavior_treat_error_as_warn: bool,
146 : #[serde(with = "humantime_serde")]
147 : pub background_task_maximum_delay: Duration,
148 : pub control_plane_api: Option<reqwest::Url>,
149 : pub control_plane_api_token: Option<String>,
150 : pub control_plane_emergency_mode: bool,
151 : /// Unstable feature: subject to change or removal without notice.
152 : /// See <https://github.com/neondatabase/neon/pull/9218>.
153 : pub import_pgdata_upcall_api: Option<reqwest::Url>,
154 : /// Unstable feature: subject to change or removal without notice.
155 : /// See <https://github.com/neondatabase/neon/pull/9218>.
156 : pub import_pgdata_upcall_api_token: Option<String>,
157 : /// Unstable feature: subject to change or removal without notice.
158 : /// See <https://github.com/neondatabase/neon/pull/9218>.
159 : pub import_pgdata_aws_endpoint_url: Option<reqwest::Url>,
160 : pub heatmap_upload_concurrency: usize,
161 : pub secondary_download_concurrency: usize,
162 : pub virtual_file_io_engine: Option<crate::models::virtual_file::IoEngineKind>,
163 : pub ingest_batch_size: u64,
164 : pub max_vectored_read_bytes: MaxVectoredReadBytes,
165 : pub image_compression: ImageCompressionAlgorithm,
166 : pub timeline_offloading: bool,
167 : pub ephemeral_bytes_per_memory_kb: usize,
168 : pub l0_flush: Option<crate::models::L0FlushConfig>,
169 : pub virtual_file_io_mode: Option<crate::models::virtual_file::IoMode>,
170 : #[serde(skip_serializing_if = "Option::is_none")]
171 : pub no_sync: Option<bool>,
172 : pub wal_receiver_protocol: PostgresClientProtocol,
173 : pub page_service_pipelining: PageServicePipeliningConfig,
174 : pub get_vectored_concurrent_io: GetVectoredConcurrentIo,
175 : pub enable_read_path_debugging: Option<bool>,
176 : #[serde(skip_serializing_if = "Option::is_none")]
177 : pub validate_wal_contiguity: Option<bool>,
178 : #[serde(skip_serializing_if = "Option::is_none")]
179 : pub load_previous_heatmap: Option<bool>,
180 : #[serde(skip_serializing_if = "Option::is_none")]
181 : pub generate_unarchival_heatmap: Option<bool>,
182 : pub tracing: Option<Tracing>,
183 : pub enable_tls_page_service_api: bool,
184 : pub dev_mode: bool,
185 : pub timeline_import_config: TimelineImportConfig,
186 : #[serde(skip_serializing_if = "Option::is_none")]
187 : pub basebackup_cache_config: Option<BasebackupCacheConfig>,
188 : }
189 :
190 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
191 : pub struct DiskUsageEvictionTaskConfig {
192 : pub max_usage_pct: utils::serde_percent::Percent,
193 : pub min_avail_bytes: u64,
194 : #[serde(with = "humantime_serde")]
195 : pub period: Duration,
196 : #[cfg(feature = "testing")]
197 : pub mock_statvfs: Option<statvfs::mock::Behavior>,
198 : /// Select sorting for evicted layers
199 : #[serde(default)]
200 : pub eviction_order: EvictionOrder,
201 : }
202 :
203 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
204 : #[serde(tag = "mode", rename_all = "kebab-case")]
205 : pub enum PageServicePipeliningConfig {
206 : Serial,
207 : Pipelined(PageServicePipeliningConfigPipelined),
208 : }
209 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
210 : pub struct PageServicePipeliningConfigPipelined {
211 : /// Causes runtime errors if larger than max get_vectored batch size.
212 : pub max_batch_size: NonZeroUsize,
213 : pub execution: PageServiceProtocolPipelinedExecutionStrategy,
214 : // The default below is such that new versions of the software can start
215 : // with the old configuration.
216 : #[serde(default)]
217 : pub batching: PageServiceProtocolPipelinedBatchingStrategy,
218 : }
219 :
220 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
221 : #[serde(rename_all = "kebab-case")]
222 : pub enum PageServiceProtocolPipelinedExecutionStrategy {
223 : ConcurrentFutures,
224 : Tasks,
225 : }
226 :
227 0 : #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
228 : #[serde(rename_all = "kebab-case")]
229 : pub enum PageServiceProtocolPipelinedBatchingStrategy {
230 : /// All get page requests in a batch will be at the same LSN
231 : #[default]
232 : UniformLsn,
233 : /// Get page requests in a batch may be at different LSN
234 : ///
235 : /// One key cannot be present more than once at different LSNs in
236 : /// the same batch.
237 : ScatteredLsn,
238 : }
239 :
240 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
241 : #[serde(tag = "mode", rename_all = "kebab-case")]
242 : pub enum GetVectoredConcurrentIo {
243 : /// The read path is fully sequential: layers are visited
244 : /// one after the other and IOs are issued and waited upon
245 : /// from the same task that traverses the layers.
246 : Sequential,
247 : /// The read path still traverses layers sequentially, and
248 : /// index blocks will be read into the PS PageCache from
249 : /// that task, with waiting.
250 : /// But data IOs are dispatched and waited upon from a sidecar
251 : /// task so that the traversing task can continue to traverse
252 : /// layers while the IOs are in flight.
253 : /// If the PS PageCache miss rate is low, this improves
254 : /// throughput dramatically.
255 : SidecarTask,
256 : }
257 :
258 2 : #[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
259 : pub struct Ratio {
260 : pub numerator: usize,
261 : pub denominator: usize,
262 : }
263 :
264 3 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
265 : pub struct OtelExporterConfig {
266 : pub endpoint: String,
267 : pub protocol: OtelExporterProtocol,
268 : #[serde(with = "humantime_serde")]
269 : pub timeout: Duration,
270 : }
271 :
272 1 : #[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
273 : #[serde(rename_all = "kebab-case")]
274 : pub enum OtelExporterProtocol {
275 : Grpc,
276 : HttpBinary,
277 : HttpJson,
278 : }
279 :
280 2 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
281 : pub struct Tracing {
282 : pub sampling_ratio: Ratio,
283 : pub export_config: OtelExporterConfig,
284 : }
285 :
286 : impl From<&OtelExporterConfig> for tracing_utils::ExportConfig {
287 0 : fn from(val: &OtelExporterConfig) -> Self {
288 0 : tracing_utils::ExportConfig {
289 0 : endpoint: Some(val.endpoint.clone()),
290 0 : protocol: val.protocol.into(),
291 0 : timeout: val.timeout,
292 0 : }
293 0 : }
294 : }
295 :
296 : impl From<OtelExporterProtocol> for tracing_utils::Protocol {
297 0 : fn from(val: OtelExporterProtocol) -> Self {
298 0 : match val {
299 0 : OtelExporterProtocol::Grpc => tracing_utils::Protocol::Grpc,
300 0 : OtelExporterProtocol::HttpJson => tracing_utils::Protocol::HttpJson,
301 0 : OtelExporterProtocol::HttpBinary => tracing_utils::Protocol::HttpBinary,
302 : }
303 0 : }
304 : }
305 :
306 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
307 : pub struct TimelineImportConfig {
308 : pub import_job_concurrency: NonZeroUsize,
309 : pub import_job_soft_size_limit: NonZeroUsize,
310 : pub import_job_checkpoint_threshold: NonZeroUsize,
311 : }
312 :
313 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
314 : #[serde(default)]
315 : pub struct BasebackupCacheConfig {
316 : #[serde(with = "humantime_serde")]
317 : pub cleanup_period: Duration,
318 : // FIXME: Support max_size_bytes.
319 : // pub max_size_bytes: usize,
320 : pub max_size_entries: i64,
321 : }
322 :
323 : impl Default for BasebackupCacheConfig {
324 0 : fn default() -> Self {
325 0 : Self {
326 0 : cleanup_period: Duration::from_secs(60),
327 0 : // max_size_bytes: 1024 * 1024 * 1024, // 1 GiB
328 0 : max_size_entries: 1000,
329 0 : }
330 0 : }
331 : }
332 :
333 : pub mod statvfs {
334 : pub mod mock {
335 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
336 : #[serde(tag = "type")]
337 : pub enum Behavior {
338 : Success {
339 : blocksize: u64,
340 : total_blocks: u64,
341 : name_filter: Option<utils::serde_regex::Regex>,
342 : },
343 : #[cfg(feature = "testing")]
344 : Failure { mocked_error: MockedError },
345 : }
346 :
347 : #[cfg(feature = "testing")]
348 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
349 : #[allow(clippy::upper_case_acronyms)]
350 : pub enum MockedError {
351 : EIO,
352 : }
353 :
354 : #[cfg(feature = "testing")]
355 : impl From<MockedError> for nix::Error {
356 0 : fn from(e: MockedError) -> Self {
357 0 : match e {
358 0 : MockedError::EIO => nix::Error::EIO,
359 0 : }
360 0 : }
361 : }
362 : }
363 : }
364 :
365 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
366 : #[serde(tag = "type", content = "args")]
367 : pub enum EvictionOrder {
368 : RelativeAccessed {
369 : highest_layer_count_loses_first: bool,
370 : },
371 : }
372 :
373 : impl Default for EvictionOrder {
374 1 : fn default() -> Self {
375 1 : Self::RelativeAccessed {
376 1 : highest_layer_count_loses_first: true,
377 1 : }
378 1 : }
379 : }
380 :
381 0 : #[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
382 : #[serde(transparent)]
383 : pub struct MaxVectoredReadBytes(pub NonZeroUsize);
384 :
385 : /// Tenant-level configuration values, used for various purposes.
386 0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
387 : #[serde(default)]
388 : pub struct TenantConfigToml {
389 : // Flush out an inmemory layer, if it's holding WAL older than this
390 : // This puts a backstop on how much WAL needs to be re-digested if the
391 : // page server crashes.
392 : // This parameter actually determines L0 layer file size.
393 : pub checkpoint_distance: u64,
394 : // Inmemory layer is also flushed at least once in checkpoint_timeout to
395 : // eventually upload WAL after activity is stopped.
396 : #[serde(with = "humantime_serde")]
397 : pub checkpoint_timeout: Duration,
398 : // Target file size, when creating image and delta layers.
399 : // This parameter determines L1 layer file size.
400 : pub compaction_target_size: u64,
401 : // How often to check if there's compaction work to be done.
402 : // Duration::ZERO means automatic compaction is disabled.
403 : #[serde(with = "humantime_serde")]
404 : pub compaction_period: Duration,
405 : /// Level0 delta layer threshold for compaction.
406 : pub compaction_threshold: usize,
407 : /// Controls the amount of L0 included in a single compaction iteration.
408 : /// The unit is `checkpoint_distance`, i.e., a size.
409 : /// We add L0s to the set of layers to compact until their cumulative
410 : /// size exceeds `compaction_upper_limit * checkpoint_distance`.
411 : pub compaction_upper_limit: usize,
412 : pub compaction_algorithm: crate::models::CompactionAlgorithmSettings,
413 : /// If true, enable shard ancestor compaction (enabled by default).
414 : pub compaction_shard_ancestor: bool,
415 : /// If true, compact down L0 across all tenant timelines before doing regular compaction. L0
416 : /// compaction must be responsive to avoid read amp during heavy ingestion. Defaults to true.
417 : pub compaction_l0_first: bool,
418 : /// If true, use a separate semaphore (i.e. concurrency limit) for the L0 compaction pass. Only
419 : /// has an effect if `compaction_l0_first` is true. Defaults to true.
420 : pub compaction_l0_semaphore: bool,
421 : /// Level0 delta layer threshold at which to delay layer flushes such that they take 2x as long,
422 : /// and block on layer flushes during ephemeral layer rolls, for compaction backpressure. This
423 : /// helps compaction keep up with WAL ingestion, and avoids read amplification blowing up.
424 : /// Should be >compaction_threshold. 0 to disable. Defaults to 3x compaction_threshold.
425 : pub l0_flush_delay_threshold: Option<usize>,
426 : /// Level0 delta layer threshold at which to stall layer flushes. Must be >compaction_threshold
427 : /// to avoid deadlock. 0 to disable. Disabled by default.
428 : pub l0_flush_stall_threshold: Option<usize>,
429 : // Determines how much history is retained, to allow
430 : // branching and read replicas at an older point in time.
431 : // The unit is #of bytes of WAL.
432 : // Page versions older than this are garbage collected away.
433 : pub gc_horizon: u64,
434 : // Interval at which garbage collection is triggered.
435 : // Duration::ZERO means automatic GC is disabled
436 : #[serde(with = "humantime_serde")]
437 : pub gc_period: Duration,
438 : // Delta layer churn threshold to create L1 image layers.
439 : pub image_creation_threshold: usize,
440 : // Determines how much history is retained, to allow
441 : // branching and read replicas at an older point in time.
442 : // The unit is time.
443 : // Page versions older than this are garbage collected away.
444 : #[serde(with = "humantime_serde")]
445 : pub pitr_interval: Duration,
446 : /// Maximum amount of time to wait while opening a connection to receive wal, before erroring.
447 : #[serde(with = "humantime_serde")]
448 : pub walreceiver_connect_timeout: Duration,
449 : /// Considers safekeepers stalled after no WAL updates were received longer than this threshold.
450 : /// A stalled safekeeper will be changed to a newer one when it appears.
451 : #[serde(with = "humantime_serde")]
452 : pub lagging_wal_timeout: Duration,
453 : /// Considers safekeepers lagging when their WAL is behind another safekeeper for more than this threshold.
454 : /// A lagging safekeeper will be changed after `lagging_wal_timeout` time elapses since the last WAL update,
455 : /// to avoid eager reconnects.
456 : pub max_lsn_wal_lag: NonZeroU64,
457 : pub eviction_policy: crate::models::EvictionPolicy,
458 : pub min_resident_size_override: Option<u64>,
459 : // See the corresponding metric's help string.
460 : #[serde(with = "humantime_serde")]
461 : pub evictions_low_residence_duration_metric_threshold: Duration,
462 :
463 : /// If non-zero, the period between uploads of a heatmap from attached tenants. This
464 : /// may be disabled if a Tenant will not have secondary locations: only secondary
465 : /// locations will use the heatmap uploaded by attached locations.
466 : #[serde(with = "humantime_serde")]
467 : pub heatmap_period: Duration,
468 :
469 : /// If true then SLRU segments are dowloaded on demand, if false SLRU segments are included in basebackup
470 : pub lazy_slru_download: bool,
471 :
472 : pub timeline_get_throttle: crate::models::ThrottleConfig,
473 :
474 : // How much WAL must be ingested before checking again whether a new image layer is required.
475 : // Expresed in multiples of checkpoint distance.
476 : pub image_layer_creation_check_threshold: u8,
477 :
478 : // How many multiples of L0 `compaction_threshold` will preempt image layer creation and do L0 compaction.
479 : // Set to 0 to disable preemption.
480 : pub image_creation_preempt_threshold: usize,
481 :
482 : /// The length for an explicit LSN lease request.
483 : /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
484 : #[serde(with = "humantime_serde")]
485 : pub lsn_lease_length: Duration,
486 :
487 : /// The length for an implicit LSN lease granted as part of `get_lsn_by_timestamp` request.
488 : /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
489 : #[serde(with = "humantime_serde")]
490 : pub lsn_lease_length_for_ts: Duration,
491 :
492 : /// Enable auto-offloading of timelines.
493 : /// (either this flag or the pageserver-global one need to be set)
494 : pub timeline_offloading: bool,
495 :
496 : pub wal_receiver_protocol_override: Option<PostgresClientProtocol>,
497 :
498 : /// Enable rel_size_v2 for this tenant. Once enabled, the tenant will persist this information into
499 : /// `index_part.json`, and it cannot be reversed.
500 : pub rel_size_v2_enabled: bool,
501 :
502 : // gc-compaction related configs
503 : /// Enable automatic gc-compaction trigger on this tenant.
504 : pub gc_compaction_enabled: bool,
505 : /// Enable verification of gc-compaction results.
506 : pub gc_compaction_verification: bool,
507 : /// The initial threshold for gc-compaction in KB. Once the total size of layers below the gc-horizon is above this threshold,
508 : /// gc-compaction will be triggered.
509 : pub gc_compaction_initial_threshold_kb: u64,
510 : /// The ratio that triggers the auto gc-compaction. If (the total size of layers between L2 LSN and gc-horizon) / (size below the L2 LSN)
511 : /// is above this ratio, gc-compaction will be triggered.
512 : pub gc_compaction_ratio_percent: u64,
513 : /// Tenant level performance sampling ratio override. Controls the ratio of get page requests
514 : /// that will get perf sampling for the tenant.
515 : pub sampling_ratio: Option<Ratio>,
516 :
517 : /// Capacity of relsize snapshot cache (used by replicas).
518 : pub relsize_snapshot_cache_capacity: usize,
519 :
520 : /// Enable preparing basebackup on XLOG_CHECKPOINT_SHUTDOWN and using it in basebackup requests.
521 : // FIXME: Remove skip_serializing_if when the feature is stable.
522 : #[serde(skip_serializing_if = "std::ops::Not::not")]
523 : pub basebackup_cache_enabled: bool,
524 : }
525 :
526 : pub mod defaults {
527 : pub use storage_broker::DEFAULT_ENDPOINT as BROKER_DEFAULT_ENDPOINT;
528 :
529 : use crate::models::ImageCompressionAlgorithm;
530 :
531 : pub const DEFAULT_WAIT_LSN_TIMEOUT: &str = "300 s";
532 : pub const DEFAULT_WAL_REDO_TIMEOUT: &str = "60 s";
533 :
534 : pub const DEFAULT_SUPERUSER: &str = "cloud_admin";
535 : pub const DEFAULT_LOCALE: &str = if cfg!(target_os = "macos") {
536 : "C"
537 : } else {
538 : "C.UTF-8"
539 : };
540 :
541 : pub const DEFAULT_PAGE_CACHE_SIZE: usize = 8192;
542 : pub const DEFAULT_MAX_FILE_DESCRIPTORS: usize = 100;
543 :
544 : pub const DEFAULT_LOG_FORMAT: &str = "plain";
545 :
546 : pub const DEFAULT_CONCURRENT_TENANT_WARMUP: usize = 8;
547 :
548 : pub const DEFAULT_CONCURRENT_TENANT_SIZE_LOGICAL_SIZE_QUERIES: usize = 1;
549 :
550 : pub const DEFAULT_METRIC_COLLECTION_INTERVAL: &str = "10 min";
551 : pub const DEFAULT_METRIC_COLLECTION_ENDPOINT: Option<reqwest::Url> = None;
552 : pub const DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL: &str = "10 min";
553 : pub const DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY: &str = "10s";
554 :
555 : pub const DEFAULT_HEATMAP_UPLOAD_CONCURRENCY: usize = 8;
556 : pub const DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY: usize = 1;
557 :
558 : pub const DEFAULT_INGEST_BATCH_SIZE: u64 = 100;
559 :
560 : /// Soft limit for the maximum size of a vectored read.
561 : ///
562 : /// This is determined by the largest NeonWalRecord that can exist (minus dbdir and reldir keys
563 : /// which are bounded by the blob io limits only). As of this writing, that is a `NeonWalRecord::ClogSetCommitted` record,
564 : /// with 32k xids. That's the max number of XIDS on a single CLOG page. The size of such a record
565 : /// is `sizeof(Transactionid) * 32768 + (some fixed overhead from 'timestamp`, the Vec length and whatever extra serde serialization adds)`.
566 : /// That is, slightly above 128 kB.
567 : pub const DEFAULT_MAX_VECTORED_READ_BYTES: usize = 130 * 1024; // 130 KiB
568 :
569 : pub const DEFAULT_IMAGE_COMPRESSION: ImageCompressionAlgorithm =
570 : ImageCompressionAlgorithm::Zstd { level: Some(1) };
571 :
572 : pub const DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB: usize = 0;
573 :
574 : pub const DEFAULT_IO_BUFFER_ALIGNMENT: usize = 512;
575 :
576 : pub const DEFAULT_WAL_RECEIVER_PROTOCOL: utils::postgres_client::PostgresClientProtocol =
577 : utils::postgres_client::PostgresClientProtocol::Vanilla;
578 :
579 : pub const DEFAULT_SSL_KEY_FILE: &str = "server.key";
580 : pub const DEFAULT_SSL_CERT_FILE: &str = "server.crt";
581 : }
582 :
583 : impl Default for ConfigToml {
584 127 : fn default() -> Self {
585 : use defaults::*;
586 :
587 : Self {
588 127 : listen_pg_addr: (DEFAULT_PG_LISTEN_ADDR.to_string()),
589 127 : listen_http_addr: (DEFAULT_HTTP_LISTEN_ADDR.to_string()),
590 127 : listen_https_addr: (None),
591 127 : ssl_key_file: Utf8PathBuf::from(DEFAULT_SSL_KEY_FILE),
592 127 : ssl_cert_file: Utf8PathBuf::from(DEFAULT_SSL_CERT_FILE),
593 127 : ssl_cert_reload_period: Duration::from_secs(60),
594 127 : ssl_ca_file: None,
595 127 : availability_zone: (None),
596 127 : wait_lsn_timeout: (humantime::parse_duration(DEFAULT_WAIT_LSN_TIMEOUT)
597 127 : .expect("cannot parse default wait lsn timeout")),
598 127 : wal_redo_timeout: (humantime::parse_duration(DEFAULT_WAL_REDO_TIMEOUT)
599 127 : .expect("cannot parse default wal redo timeout")),
600 127 : superuser: (DEFAULT_SUPERUSER.to_string()),
601 127 : locale: DEFAULT_LOCALE.to_string(),
602 127 : page_cache_size: (DEFAULT_PAGE_CACHE_SIZE),
603 127 : max_file_descriptors: (DEFAULT_MAX_FILE_DESCRIPTORS),
604 127 : pg_distrib_dir: None, // Utf8PathBuf::from("./pg_install"), // TODO: formely, this was std::env::current_dir()
605 127 : http_auth_type: (AuthType::Trust),
606 127 : pg_auth_type: (AuthType::Trust),
607 127 : auth_validation_public_key_path: (None),
608 127 : remote_storage: None,
609 127 : broker_endpoint: (storage_broker::DEFAULT_ENDPOINT
610 127 : .parse()
611 127 : .expect("failed to parse default broker endpoint")),
612 127 : broker_keepalive_interval: (humantime::parse_duration(
613 127 : storage_broker::DEFAULT_KEEPALIVE_INTERVAL,
614 127 : )
615 127 : .expect("cannot parse default keepalive interval")),
616 127 : log_format: (LogFormat::from_str(DEFAULT_LOG_FORMAT).unwrap()),
617 127 :
618 127 : concurrent_tenant_warmup: (NonZeroUsize::new(DEFAULT_CONCURRENT_TENANT_WARMUP)
619 127 : .expect("Invalid default constant")),
620 127 : concurrent_tenant_size_logical_size_queries: NonZeroUsize::new(
621 127 : DEFAULT_CONCURRENT_TENANT_SIZE_LOGICAL_SIZE_QUERIES,
622 127 : )
623 127 : .unwrap(),
624 127 : metric_collection_interval: (humantime::parse_duration(
625 127 : DEFAULT_METRIC_COLLECTION_INTERVAL,
626 127 : )
627 127 : .expect("cannot parse default metric collection interval")),
628 127 : synthetic_size_calculation_interval: (humantime::parse_duration(
629 127 : DEFAULT_SYNTHETIC_SIZE_CALCULATION_INTERVAL,
630 127 : )
631 127 : .expect("cannot parse default synthetic size calculation interval")),
632 127 : metric_collection_endpoint: (DEFAULT_METRIC_COLLECTION_ENDPOINT),
633 127 :
634 127 : metric_collection_bucket: (None),
635 127 :
636 127 : disk_usage_based_eviction: (None),
637 127 :
638 127 : test_remote_failures: (0),
639 127 :
640 127 : ondemand_download_behavior_treat_error_as_warn: (false),
641 127 :
642 127 : background_task_maximum_delay: (humantime::parse_duration(
643 127 : DEFAULT_BACKGROUND_TASK_MAXIMUM_DELAY,
644 127 : )
645 127 : .unwrap()),
646 127 :
647 127 : control_plane_api: (None),
648 127 : control_plane_api_token: (None),
649 127 : control_plane_emergency_mode: (false),
650 127 :
651 127 : import_pgdata_upcall_api: (None),
652 127 : import_pgdata_upcall_api_token: (None),
653 127 : import_pgdata_aws_endpoint_url: (None),
654 127 :
655 127 : heatmap_upload_concurrency: (DEFAULT_HEATMAP_UPLOAD_CONCURRENCY),
656 127 : secondary_download_concurrency: (DEFAULT_SECONDARY_DOWNLOAD_CONCURRENCY),
657 127 :
658 127 : ingest_batch_size: (DEFAULT_INGEST_BATCH_SIZE),
659 127 :
660 127 : virtual_file_io_engine: None,
661 127 :
662 127 : max_vectored_read_bytes: (MaxVectoredReadBytes(
663 127 : NonZeroUsize::new(DEFAULT_MAX_VECTORED_READ_BYTES).unwrap(),
664 127 : )),
665 127 : image_compression: (DEFAULT_IMAGE_COMPRESSION),
666 127 : timeline_offloading: true,
667 127 : ephemeral_bytes_per_memory_kb: (DEFAULT_EPHEMERAL_BYTES_PER_MEMORY_KB),
668 127 : l0_flush: None,
669 127 : virtual_file_io_mode: None,
670 127 : tenant_config: TenantConfigToml::default(),
671 127 : no_sync: None,
672 127 : wal_receiver_protocol: DEFAULT_WAL_RECEIVER_PROTOCOL,
673 127 : page_service_pipelining: PageServicePipeliningConfig::Pipelined(
674 127 : PageServicePipeliningConfigPipelined {
675 127 : max_batch_size: NonZeroUsize::new(32).unwrap(),
676 127 : execution: PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures,
677 127 : batching: PageServiceProtocolPipelinedBatchingStrategy::ScatteredLsn,
678 127 : },
679 127 : ),
680 127 : get_vectored_concurrent_io: GetVectoredConcurrentIo::SidecarTask,
681 127 : enable_read_path_debugging: if cfg!(feature = "testing") {
682 127 : Some(true)
683 : } else {
684 0 : None
685 : },
686 127 : validate_wal_contiguity: None,
687 127 : load_previous_heatmap: None,
688 127 : generate_unarchival_heatmap: None,
689 127 : tracing: None,
690 127 : enable_tls_page_service_api: false,
691 127 : dev_mode: false,
692 127 : timeline_import_config: TimelineImportConfig {
693 127 : import_job_concurrency: NonZeroUsize::new(128).unwrap(),
694 127 : import_job_soft_size_limit: NonZeroUsize::new(1024 * 1024 * 1024).unwrap(),
695 127 : import_job_checkpoint_threshold: NonZeroUsize::new(128).unwrap(),
696 127 : },
697 127 : basebackup_cache_config: None,
698 127 : }
699 127 : }
700 : }
701 :
702 : pub mod tenant_conf_defaults {
703 :
704 : // FIXME: This current value is very low. I would imagine something like 1 GB or 10 GB
705 : // would be more appropriate. But a low value forces the code to be exercised more,
706 : // which is good for now to trigger bugs.
707 : // This parameter actually determines L0 layer file size.
708 : pub const DEFAULT_CHECKPOINT_DISTANCE: u64 = 256 * 1024 * 1024;
709 : pub const DEFAULT_CHECKPOINT_TIMEOUT: &str = "10 m";
710 :
711 : // FIXME the below configs are only used by legacy algorithm. The new algorithm
712 : // has different parameters.
713 :
714 : // Target file size, when creating image and delta layers.
715 : // This parameter determines L1 layer file size.
716 : pub const DEFAULT_COMPACTION_TARGET_SIZE: u64 = 128 * 1024 * 1024;
717 :
718 : pub const DEFAULT_COMPACTION_PERIOD: &str = "20 s";
719 : pub const DEFAULT_COMPACTION_THRESHOLD: usize = 10;
720 : pub const DEFAULT_COMPACTION_SHARD_ANCESTOR: bool = true;
721 :
722 : // This value needs to be tuned to avoid OOM. We have 3/4*CPUs threads for L0 compaction, that's
723 : // 3/4*8=6 on most of our pageservers. Compacting 10 layers requires a maximum of
724 : // DEFAULT_CHECKPOINT_DISTANCE*10 memory, that's 2560MB. So with this config, we can get a maximum peak
725 : // compaction usage of 15360MB.
726 : pub const DEFAULT_COMPACTION_UPPER_LIMIT: usize = 10;
727 : // Enable L0 compaction pass and semaphore by default. L0 compaction must be responsive to avoid
728 : // read amp.
729 : pub const DEFAULT_COMPACTION_L0_FIRST: bool = true;
730 : pub const DEFAULT_COMPACTION_L0_SEMAPHORE: bool = true;
731 :
732 : pub const DEFAULT_COMPACTION_ALGORITHM: crate::models::CompactionAlgorithm =
733 : crate::models::CompactionAlgorithm::Legacy;
734 :
735 : pub const DEFAULT_GC_HORIZON: u64 = 64 * 1024 * 1024;
736 :
737 : // Large DEFAULT_GC_PERIOD is fine as long as PITR_INTERVAL is larger.
738 : // If there's a need to decrease this value, first make sure that GC
739 : // doesn't hold a layer map write lock for non-trivial operations.
740 : // Relevant: https://github.com/neondatabase/neon/issues/3394
741 : pub const DEFAULT_GC_PERIOD: &str = "1 hr";
742 : pub const DEFAULT_IMAGE_CREATION_THRESHOLD: usize = 3;
743 : // Currently, any value other than 0 will trigger image layer creation preemption immediately with L0 backpressure
744 : // without looking at the exact number of L0 layers.
745 : // It was expected to have the following behavior:
746 : // > If there are more than threshold * compaction_threshold (that is 3 * 10 in the default config) L0 layers, image
747 : // > layer creation will end immediately. Set to 0 to disable.
748 : pub const DEFAULT_IMAGE_CREATION_PREEMPT_THRESHOLD: usize = 3;
749 : pub const DEFAULT_PITR_INTERVAL: &str = "7 days";
750 : pub const DEFAULT_WALRECEIVER_CONNECT_TIMEOUT: &str = "10 seconds";
751 : pub const DEFAULT_WALRECEIVER_LAGGING_WAL_TIMEOUT: &str = "10 seconds";
752 : // The default limit on WAL lag should be set to avoid causing disconnects under high throughput
753 : // scenarios: since the broker stats are updated ~1/s, a value of 1GiB should be sufficient for
754 : // throughputs up to 1GiB/s per timeline.
755 : pub const DEFAULT_MAX_WALRECEIVER_LSN_WAL_LAG: u64 = 1024 * 1024 * 1024;
756 : pub const DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD: &str = "24 hour";
757 : // By default ingest enough WAL for two new L0 layers before checking if new image
758 : // image layers should be created.
759 : pub const DEFAULT_IMAGE_LAYER_CREATION_CHECK_THRESHOLD: u8 = 2;
760 : pub const DEFAULT_GC_COMPACTION_ENABLED: bool = false;
761 : pub const DEFAULT_GC_COMPACTION_VERIFICATION: bool = true;
762 : pub const DEFAULT_GC_COMPACTION_INITIAL_THRESHOLD_KB: u64 = 5 * 1024 * 1024; // 5GB
763 : pub const DEFAULT_GC_COMPACTION_RATIO_PERCENT: u64 = 100;
764 : pub const DEFAULT_RELSIZE_SNAPSHOT_CACHE_CAPACITY: usize = 1000;
765 : }
766 :
767 : impl Default for TenantConfigToml {
768 127 : fn default() -> Self {
769 : use tenant_conf_defaults::*;
770 127 : Self {
771 127 : checkpoint_distance: DEFAULT_CHECKPOINT_DISTANCE,
772 127 : checkpoint_timeout: humantime::parse_duration(DEFAULT_CHECKPOINT_TIMEOUT)
773 127 : .expect("cannot parse default checkpoint timeout"),
774 127 : compaction_target_size: DEFAULT_COMPACTION_TARGET_SIZE,
775 127 : compaction_period: humantime::parse_duration(DEFAULT_COMPACTION_PERIOD)
776 127 : .expect("cannot parse default compaction period"),
777 127 : compaction_threshold: DEFAULT_COMPACTION_THRESHOLD,
778 127 : compaction_upper_limit: DEFAULT_COMPACTION_UPPER_LIMIT,
779 127 : compaction_algorithm: crate::models::CompactionAlgorithmSettings {
780 127 : kind: DEFAULT_COMPACTION_ALGORITHM,
781 127 : },
782 127 : compaction_shard_ancestor: DEFAULT_COMPACTION_SHARD_ANCESTOR,
783 127 : compaction_l0_first: DEFAULT_COMPACTION_L0_FIRST,
784 127 : compaction_l0_semaphore: DEFAULT_COMPACTION_L0_SEMAPHORE,
785 127 : l0_flush_delay_threshold: None,
786 127 : l0_flush_stall_threshold: None,
787 127 : gc_horizon: DEFAULT_GC_HORIZON,
788 127 : gc_period: humantime::parse_duration(DEFAULT_GC_PERIOD)
789 127 : .expect("cannot parse default gc period"),
790 127 : image_creation_threshold: DEFAULT_IMAGE_CREATION_THRESHOLD,
791 127 : pitr_interval: humantime::parse_duration(DEFAULT_PITR_INTERVAL)
792 127 : .expect("cannot parse default PITR interval"),
793 127 : walreceiver_connect_timeout: humantime::parse_duration(
794 127 : DEFAULT_WALRECEIVER_CONNECT_TIMEOUT,
795 127 : )
796 127 : .expect("cannot parse default walreceiver connect timeout"),
797 127 : lagging_wal_timeout: humantime::parse_duration(DEFAULT_WALRECEIVER_LAGGING_WAL_TIMEOUT)
798 127 : .expect("cannot parse default walreceiver lagging wal timeout"),
799 127 : max_lsn_wal_lag: NonZeroU64::new(DEFAULT_MAX_WALRECEIVER_LSN_WAL_LAG)
800 127 : .expect("cannot parse default max walreceiver Lsn wal lag"),
801 127 : eviction_policy: crate::models::EvictionPolicy::NoEviction,
802 127 : min_resident_size_override: None,
803 127 : evictions_low_residence_duration_metric_threshold: humantime::parse_duration(
804 127 : DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD,
805 127 : )
806 127 : .expect("cannot parse default evictions_low_residence_duration_metric_threshold"),
807 127 : heatmap_period: Duration::ZERO,
808 127 : lazy_slru_download: false,
809 127 : timeline_get_throttle: crate::models::ThrottleConfig::disabled(),
810 127 : image_layer_creation_check_threshold: DEFAULT_IMAGE_LAYER_CREATION_CHECK_THRESHOLD,
811 127 : image_creation_preempt_threshold: DEFAULT_IMAGE_CREATION_PREEMPT_THRESHOLD,
812 127 : lsn_lease_length: LsnLease::DEFAULT_LENGTH,
813 127 : lsn_lease_length_for_ts: LsnLease::DEFAULT_LENGTH_FOR_TS,
814 127 : timeline_offloading: true,
815 127 : wal_receiver_protocol_override: None,
816 127 : rel_size_v2_enabled: false,
817 127 : gc_compaction_enabled: DEFAULT_GC_COMPACTION_ENABLED,
818 127 : gc_compaction_verification: DEFAULT_GC_COMPACTION_VERIFICATION,
819 127 : gc_compaction_initial_threshold_kb: DEFAULT_GC_COMPACTION_INITIAL_THRESHOLD_KB,
820 127 : gc_compaction_ratio_percent: DEFAULT_GC_COMPACTION_RATIO_PERCENT,
821 127 : sampling_ratio: None,
822 127 : relsize_snapshot_cache_capacity: DEFAULT_RELSIZE_SNAPSHOT_CACHE_CAPACITY,
823 127 : basebackup_cache_enabled: false,
824 127 : }
825 127 : }
826 : }
|