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