Line data Source code
1 : //! Functions for handling per-tenant configuration options
2 : //!
3 : //! If tenant is created with --config option,
4 : //! the tenant-specific config will be stored in tenant's directory.
5 : //! Otherwise, global pageserver's config is used.
6 : //!
7 : //! If the tenant config file is corrupted, the tenant will be disabled.
8 : //! We cannot use global or default config instead, because wrong settings
9 : //! may lead to a data loss.
10 : //!
11 : use anyhow::bail;
12 : use pageserver_api::models::AuxFilePolicy;
13 : use pageserver_api::models::CompactionAlgorithm;
14 : use pageserver_api::models::CompactionAlgorithmSettings;
15 : use pageserver_api::models::EvictionPolicy;
16 : use pageserver_api::models::LsnLease;
17 : use pageserver_api::models::{self, ThrottleConfig};
18 : use pageserver_api::shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize};
19 : use serde::de::IntoDeserializer;
20 : use serde::{Deserialize, Serialize};
21 : use serde_json::Value;
22 : use std::num::NonZeroU64;
23 : use std::time::Duration;
24 : use utils::generation::Generation;
25 :
26 : pub mod defaults {
27 :
28 : // FIXME: This current value is very low. I would imagine something like 1 GB or 10 GB
29 : // would be more appropriate. But a low value forces the code to be exercised more,
30 : // which is good for now to trigger bugs.
31 : // This parameter actually determines L0 layer file size.
32 : pub const DEFAULT_CHECKPOINT_DISTANCE: u64 = 256 * 1024 * 1024;
33 : pub const DEFAULT_CHECKPOINT_TIMEOUT: &str = "10 m";
34 :
35 : // FIXME the below configs are only used by legacy algorithm. The new algorithm
36 : // has different parameters.
37 :
38 : // Target file size, when creating image and delta layers.
39 : // This parameter determines L1 layer file size.
40 : pub const DEFAULT_COMPACTION_TARGET_SIZE: u64 = 128 * 1024 * 1024;
41 :
42 : pub const DEFAULT_COMPACTION_PERIOD: &str = "20 s";
43 : pub const DEFAULT_COMPACTION_THRESHOLD: usize = 10;
44 : pub const DEFAULT_COMPACTION_ALGORITHM: super::CompactionAlgorithm =
45 : super::CompactionAlgorithm::Legacy;
46 :
47 : pub const DEFAULT_GC_HORIZON: u64 = 64 * 1024 * 1024;
48 :
49 : // Large DEFAULT_GC_PERIOD is fine as long as PITR_INTERVAL is larger.
50 : // If there's a need to decrease this value, first make sure that GC
51 : // doesn't hold a layer map write lock for non-trivial operations.
52 : // Relevant: https://github.com/neondatabase/neon/issues/3394
53 : pub const DEFAULT_GC_PERIOD: &str = "1 hr";
54 : pub const DEFAULT_IMAGE_CREATION_THRESHOLD: usize = 3;
55 : pub const DEFAULT_PITR_INTERVAL: &str = "7 days";
56 : pub const DEFAULT_WALRECEIVER_CONNECT_TIMEOUT: &str = "10 seconds";
57 : pub const DEFAULT_WALRECEIVER_LAGGING_WAL_TIMEOUT: &str = "10 seconds";
58 : // The default limit on WAL lag should be set to avoid causing disconnects under high throughput
59 : // scenarios: since the broker stats are updated ~1/s, a value of 1GiB should be sufficient for
60 : // throughputs up to 1GiB/s per timeline.
61 : pub const DEFAULT_MAX_WALRECEIVER_LSN_WAL_LAG: u64 = 1024 * 1024 * 1024;
62 : pub const DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD: &str = "24 hour";
63 : // By default ingest enough WAL for two new L0 layers before checking if new image
64 : // image layers should be created.
65 : pub const DEFAULT_IMAGE_LAYER_CREATION_CHECK_THRESHOLD: u8 = 2;
66 :
67 : pub const DEFAULT_INGEST_BATCH_SIZE: u64 = 100;
68 : }
69 :
70 0 : #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
71 : pub(crate) enum AttachmentMode {
72 : /// Our generation is current as far as we know, and as far as we know we are the only attached
73 : /// pageserver. This is the "normal" attachment mode.
74 : Single,
75 : /// Our generation number is current as far as we know, but we are advised that another
76 : /// pageserver is still attached, and therefore to avoid executing deletions. This is
77 : /// the attachment mode of a pagesever that is the destination of a migration.
78 : Multi,
79 : /// Our generation number is superseded, or about to be superseded. We are advised
80 : /// to avoid remote storage writes if possible, and to avoid sending billing data. This
81 : /// is the attachment mode of a pageserver that is the origin of a migration.
82 : Stale,
83 : }
84 :
85 0 : #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
86 : pub(crate) struct AttachedLocationConfig {
87 : pub(crate) generation: Generation,
88 : pub(crate) attach_mode: AttachmentMode,
89 : // TODO: add a flag to override AttachmentMode's policies under
90 : // disk pressure (i.e. unblock uploads under disk pressure in Stale
91 : // state, unblock deletions after timeout in Multi state)
92 : }
93 :
94 0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
95 : pub(crate) struct SecondaryLocationConfig {
96 : /// If true, keep the local cache warm by polling remote storage
97 : pub(crate) warm: bool,
98 : }
99 :
100 0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
101 : pub(crate) enum LocationMode {
102 : Attached(AttachedLocationConfig),
103 : Secondary(SecondaryLocationConfig),
104 : }
105 :
106 : /// Per-tenant, per-pageserver configuration. All pageservers use the same TenantConf,
107 : /// but have distinct LocationConf.
108 0 : #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
109 : pub(crate) struct LocationConf {
110 : /// The location-specific part of the configuration, describes the operating
111 : /// mode of this pageserver for this tenant.
112 : pub(crate) mode: LocationMode,
113 :
114 : /// The detailed shard identity. This structure is already scoped within
115 : /// a TenantShardId, but we need the full ShardIdentity to enable calculating
116 : /// key->shard mappings.
117 : #[serde(default = "ShardIdentity::unsharded")]
118 : #[serde(skip_serializing_if = "ShardIdentity::is_unsharded")]
119 : pub(crate) shard: ShardIdentity,
120 :
121 : /// The pan-cluster tenant configuration, the same on all locations
122 : pub(crate) tenant_conf: TenantConfOpt,
123 : }
124 :
125 : impl std::fmt::Debug for LocationConf {
126 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 0 : match &self.mode {
128 0 : LocationMode::Attached(conf) => {
129 0 : write!(
130 0 : f,
131 0 : "Attached {:?}, gen={:?}",
132 0 : conf.attach_mode, conf.generation
133 0 : )
134 : }
135 0 : LocationMode::Secondary(conf) => {
136 0 : write!(f, "Secondary, warm={}", conf.warm)
137 : }
138 : }
139 0 : }
140 : }
141 :
142 : impl AttachedLocationConfig {
143 : /// Consult attachment mode to determine whether we are currently permitted
144 : /// to delete layers. This is only advisory, not required for data safety.
145 : /// See [`AttachmentMode`] for more context.
146 754 : pub(crate) fn may_delete_layers_hint(&self) -> bool {
147 754 : // TODO: add an override for disk pressure in AttachedLocationConfig,
148 754 : // and respect it here.
149 754 : match &self.attach_mode {
150 754 : AttachmentMode::Single => true,
151 : AttachmentMode::Multi | AttachmentMode::Stale => {
152 : // In Multi mode we avoid doing deletions because some other
153 : // attached pageserver might get 404 while trying to read
154 : // a layer we delete which is still referenced in their metadata.
155 : //
156 : // In Stale mode, we avoid doing deletions because we expect
157 : // that they would ultimately fail validation in the deletion
158 : // queue due to our stale generation.
159 0 : false
160 : }
161 : }
162 754 : }
163 :
164 : /// Whether we are currently hinted that it is worthwhile to upload layers.
165 : /// This is only advisory, not required for data safety.
166 : /// See [`AttachmentMode`] for more context.
167 0 : pub(crate) fn may_upload_layers_hint(&self) -> bool {
168 0 : // TODO: add an override for disk pressure in AttachedLocationConfig,
169 0 : // and respect it here.
170 0 : match &self.attach_mode {
171 0 : AttachmentMode::Single | AttachmentMode::Multi => true,
172 : AttachmentMode::Stale => {
173 : // In Stale mode, we avoid doing uploads because we expect that
174 : // our replacement pageserver will already have started its own
175 : // IndexPart that will never reference layers we upload: it is
176 : // wasteful.
177 0 : false
178 : }
179 : }
180 0 : }
181 : }
182 :
183 : impl LocationConf {
184 : /// For use when loading from a legacy configuration: presence of a tenant
185 : /// implies it is in AttachmentMode::Single, which used to be the only
186 : /// possible state. This function should eventually be removed.
187 182 : pub(crate) fn attached_single(
188 182 : tenant_conf: TenantConfOpt,
189 182 : generation: Generation,
190 182 : shard_params: &models::ShardParameters,
191 182 : ) -> Self {
192 182 : Self {
193 182 : mode: LocationMode::Attached(AttachedLocationConfig {
194 182 : generation,
195 182 : attach_mode: AttachmentMode::Single,
196 182 : }),
197 182 : shard: ShardIdentity::from_params(ShardNumber(0), shard_params),
198 182 : tenant_conf,
199 182 : }
200 182 : }
201 :
202 : /// For use when attaching/re-attaching: update the generation stored in this
203 : /// structure. If we were in a secondary state, promote to attached (posession
204 : /// of a fresh generation implies this).
205 0 : pub(crate) fn attach_in_generation(&mut self, mode: AttachmentMode, generation: Generation) {
206 0 : match &mut self.mode {
207 0 : LocationMode::Attached(attach_conf) => {
208 0 : attach_conf.generation = generation;
209 0 : attach_conf.attach_mode = mode;
210 0 : }
211 : LocationMode::Secondary(_) => {
212 : // We are promoted to attached by the control plane's re-attach response
213 0 : self.mode = LocationMode::Attached(AttachedLocationConfig {
214 0 : generation,
215 0 : attach_mode: mode,
216 0 : })
217 : }
218 : }
219 0 : }
220 :
221 0 : pub(crate) fn try_from(conf: &'_ models::LocationConfig) -> anyhow::Result<Self> {
222 0 : let tenant_conf = TenantConfOpt::try_from(&conf.tenant_conf)?;
223 :
224 0 : fn get_generation(conf: &'_ models::LocationConfig) -> Result<Generation, anyhow::Error> {
225 0 : conf.generation
226 0 : .map(Generation::new)
227 0 : .ok_or_else(|| anyhow::anyhow!("Generation must be set when attaching"))
228 0 : }
229 :
230 0 : let mode = match &conf.mode {
231 : models::LocationConfigMode::AttachedMulti => {
232 : LocationMode::Attached(AttachedLocationConfig {
233 0 : generation: get_generation(conf)?,
234 0 : attach_mode: AttachmentMode::Multi,
235 : })
236 : }
237 : models::LocationConfigMode::AttachedSingle => {
238 : LocationMode::Attached(AttachedLocationConfig {
239 0 : generation: get_generation(conf)?,
240 0 : attach_mode: AttachmentMode::Single,
241 : })
242 : }
243 : models::LocationConfigMode::AttachedStale => {
244 : LocationMode::Attached(AttachedLocationConfig {
245 0 : generation: get_generation(conf)?,
246 0 : attach_mode: AttachmentMode::Stale,
247 : })
248 : }
249 : models::LocationConfigMode::Secondary => {
250 0 : anyhow::ensure!(conf.generation.is_none());
251 :
252 0 : let warm = conf
253 0 : .secondary_conf
254 0 : .as_ref()
255 0 : .map(|c| c.warm)
256 0 : .unwrap_or(false);
257 0 : LocationMode::Secondary(SecondaryLocationConfig { warm })
258 : }
259 : models::LocationConfigMode::Detached => {
260 : // Should not have been called: API code should translate this mode
261 : // into a detach rather than trying to decode it as a LocationConf
262 0 : return Err(anyhow::anyhow!("Cannot decode a Detached configuration"));
263 : }
264 : };
265 :
266 0 : let shard = if conf.shard_count == 0 {
267 0 : ShardIdentity::unsharded()
268 : } else {
269 0 : ShardIdentity::new(
270 0 : ShardNumber(conf.shard_number),
271 0 : ShardCount::new(conf.shard_count),
272 0 : ShardStripeSize(conf.shard_stripe_size),
273 0 : )?
274 : };
275 :
276 0 : Ok(Self {
277 0 : shard,
278 0 : mode,
279 0 : tenant_conf,
280 0 : })
281 0 : }
282 : }
283 :
284 : /// A tenant's calcuated configuration, which is the result of merging a
285 : /// tenant's TenantConfOpt with the global TenantConf from PageServerConf.
286 : ///
287 : /// For storing and transmitting individual tenant's configuration, see
288 : /// TenantConfOpt.
289 0 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290 : pub struct TenantConf {
291 : // Flush out an inmemory layer, if it's holding WAL older than this
292 : // This puts a backstop on how much WAL needs to be re-digested if the
293 : // page server crashes.
294 : // This parameter actually determines L0 layer file size.
295 : pub checkpoint_distance: u64,
296 : // Inmemory layer is also flushed at least once in checkpoint_timeout to
297 : // eventually upload WAL after activity is stopped.
298 : #[serde(with = "humantime_serde")]
299 : pub checkpoint_timeout: Duration,
300 : // Target file size, when creating image and delta layers.
301 : // This parameter determines L1 layer file size.
302 : pub compaction_target_size: u64,
303 : // How often to check if there's compaction work to be done.
304 : // Duration::ZERO means automatic compaction is disabled.
305 : #[serde(with = "humantime_serde")]
306 : pub compaction_period: Duration,
307 : // Level0 delta layer threshold for compaction.
308 : pub compaction_threshold: usize,
309 : pub compaction_algorithm: CompactionAlgorithmSettings,
310 : // Determines how much history is retained, to allow
311 : // branching and read replicas at an older point in time.
312 : // The unit is #of bytes of WAL.
313 : // Page versions older than this are garbage collected away.
314 : pub gc_horizon: u64,
315 : // Interval at which garbage collection is triggered.
316 : // Duration::ZERO means automatic GC is disabled
317 : #[serde(with = "humantime_serde")]
318 : pub gc_period: Duration,
319 : // Delta layer churn threshold to create L1 image layers.
320 : pub image_creation_threshold: usize,
321 : // Determines how much history is retained, to allow
322 : // branching and read replicas at an older point in time.
323 : // The unit is time.
324 : // Page versions older than this are garbage collected away.
325 : #[serde(with = "humantime_serde")]
326 : pub pitr_interval: Duration,
327 : /// Maximum amount of time to wait while opening a connection to receive wal, before erroring.
328 : #[serde(with = "humantime_serde")]
329 : pub walreceiver_connect_timeout: Duration,
330 : /// Considers safekeepers stalled after no WAL updates were received longer than this threshold.
331 : /// A stalled safekeeper will be changed to a newer one when it appears.
332 : #[serde(with = "humantime_serde")]
333 : pub lagging_wal_timeout: Duration,
334 : /// Considers safekeepers lagging when their WAL is behind another safekeeper for more than this threshold.
335 : /// A lagging safekeeper will be changed after `lagging_wal_timeout` time elapses since the last WAL update,
336 : /// to avoid eager reconnects.
337 : pub max_lsn_wal_lag: NonZeroU64,
338 : pub eviction_policy: EvictionPolicy,
339 : pub min_resident_size_override: Option<u64>,
340 : // See the corresponding metric's help string.
341 : #[serde(with = "humantime_serde")]
342 : pub evictions_low_residence_duration_metric_threshold: Duration,
343 :
344 : /// If non-zero, the period between uploads of a heatmap from attached tenants. This
345 : /// may be disabled if a Tenant will not have secondary locations: only secondary
346 : /// locations will use the heatmap uploaded by attached locations.
347 : #[serde(with = "humantime_serde")]
348 : pub heatmap_period: Duration,
349 :
350 : /// If true then SLRU segments are dowloaded on demand, if false SLRU segments are included in basebackup
351 : pub lazy_slru_download: bool,
352 :
353 : pub timeline_get_throttle: pageserver_api::models::ThrottleConfig,
354 :
355 : // How much WAL must be ingested before checking again whether a new image layer is required.
356 : // Expresed in multiples of checkpoint distance.
357 : pub image_layer_creation_check_threshold: u8,
358 :
359 : /// Switch to a new aux file policy. Switching this flag requires the user has not written any aux file into
360 : /// the storage before, and this flag cannot be switched back. Otherwise there will be data corruptions.
361 : /// There is a `last_aux_file_policy` flag which gets persisted in `index_part.json` once the first aux
362 : /// file is written.
363 : pub switch_aux_file_policy: AuxFilePolicy,
364 :
365 : /// The length for an explicit LSN lease request.
366 : /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
367 : #[serde(with = "humantime_serde")]
368 : pub lsn_lease_length: Duration,
369 :
370 : /// The length for an implicit LSN lease granted as part of `get_lsn_by_timestamp` request.
371 : /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
372 : #[serde(with = "humantime_serde")]
373 : pub lsn_lease_length_for_ts: Duration,
374 : }
375 :
376 : /// Same as TenantConf, but this struct preserves the information about
377 : /// which parameters are set and which are not.
378 146 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
379 : pub struct TenantConfOpt {
380 : #[serde(skip_serializing_if = "Option::is_none")]
381 : #[serde(default)]
382 : pub checkpoint_distance: Option<u64>,
383 :
384 : #[serde(skip_serializing_if = "Option::is_none")]
385 : #[serde(with = "humantime_serde")]
386 : #[serde(default)]
387 : pub checkpoint_timeout: Option<Duration>,
388 :
389 : #[serde(skip_serializing_if = "Option::is_none")]
390 : #[serde(default)]
391 : pub compaction_target_size: Option<u64>,
392 :
393 : #[serde(skip_serializing_if = "Option::is_none")]
394 : #[serde(with = "humantime_serde")]
395 : #[serde(default)]
396 : pub compaction_period: Option<Duration>,
397 :
398 : #[serde(skip_serializing_if = "Option::is_none")]
399 : #[serde(default)]
400 : pub compaction_threshold: Option<usize>,
401 :
402 : #[serde(skip_serializing_if = "Option::is_none")]
403 : #[serde(default)]
404 : pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
405 :
406 : #[serde(skip_serializing_if = "Option::is_none")]
407 : #[serde(default)]
408 : pub gc_horizon: Option<u64>,
409 :
410 : #[serde(skip_serializing_if = "Option::is_none")]
411 : #[serde(with = "humantime_serde")]
412 : #[serde(default)]
413 : pub gc_period: Option<Duration>,
414 :
415 : #[serde(skip_serializing_if = "Option::is_none")]
416 : #[serde(default)]
417 : pub image_creation_threshold: Option<usize>,
418 :
419 : #[serde(skip_serializing_if = "Option::is_none")]
420 : #[serde(with = "humantime_serde")]
421 : #[serde(default)]
422 : pub pitr_interval: Option<Duration>,
423 :
424 : #[serde(skip_serializing_if = "Option::is_none")]
425 : #[serde(with = "humantime_serde")]
426 : #[serde(default)]
427 : pub walreceiver_connect_timeout: Option<Duration>,
428 :
429 : #[serde(skip_serializing_if = "Option::is_none")]
430 : #[serde(with = "humantime_serde")]
431 : #[serde(default)]
432 : pub lagging_wal_timeout: Option<Duration>,
433 :
434 : #[serde(skip_serializing_if = "Option::is_none")]
435 : #[serde(default)]
436 : pub max_lsn_wal_lag: Option<NonZeroU64>,
437 :
438 : #[serde(skip_serializing_if = "Option::is_none")]
439 : #[serde(default)]
440 : pub eviction_policy: Option<EvictionPolicy>,
441 :
442 : #[serde(skip_serializing_if = "Option::is_none")]
443 : #[serde(default)]
444 : pub min_resident_size_override: Option<u64>,
445 :
446 : #[serde(skip_serializing_if = "Option::is_none")]
447 : #[serde(with = "humantime_serde")]
448 : #[serde(default)]
449 : pub evictions_low_residence_duration_metric_threshold: Option<Duration>,
450 :
451 : #[serde(skip_serializing_if = "Option::is_none")]
452 : #[serde(with = "humantime_serde")]
453 : #[serde(default)]
454 : pub heatmap_period: Option<Duration>,
455 :
456 : #[serde(skip_serializing_if = "Option::is_none")]
457 : #[serde(default)]
458 : pub lazy_slru_download: Option<bool>,
459 :
460 : #[serde(skip_serializing_if = "Option::is_none")]
461 : pub timeline_get_throttle: Option<pageserver_api::models::ThrottleConfig>,
462 :
463 : #[serde(skip_serializing_if = "Option::is_none")]
464 : pub image_layer_creation_check_threshold: Option<u8>,
465 :
466 : #[serde(skip_serializing_if = "Option::is_none")]
467 : #[serde(default)]
468 : pub switch_aux_file_policy: Option<AuxFilePolicy>,
469 :
470 : #[serde(skip_serializing_if = "Option::is_none")]
471 : #[serde(with = "humantime_serde")]
472 : #[serde(default)]
473 : pub lsn_lease_length: Option<Duration>,
474 :
475 : #[serde(skip_serializing_if = "Option::is_none")]
476 : #[serde(with = "humantime_serde")]
477 : #[serde(default)]
478 : pub lsn_lease_length_for_ts: Option<Duration>,
479 : }
480 :
481 : impl TenantConfOpt {
482 16 : pub fn merge(&self, global_conf: TenantConf) -> TenantConf {
483 16 : TenantConf {
484 16 : checkpoint_distance: self
485 16 : .checkpoint_distance
486 16 : .unwrap_or(global_conf.checkpoint_distance),
487 16 : checkpoint_timeout: self
488 16 : .checkpoint_timeout
489 16 : .unwrap_or(global_conf.checkpoint_timeout),
490 16 : compaction_target_size: self
491 16 : .compaction_target_size
492 16 : .unwrap_or(global_conf.compaction_target_size),
493 16 : compaction_period: self
494 16 : .compaction_period
495 16 : .unwrap_or(global_conf.compaction_period),
496 16 : compaction_threshold: self
497 16 : .compaction_threshold
498 16 : .unwrap_or(global_conf.compaction_threshold),
499 16 : compaction_algorithm: self
500 16 : .compaction_algorithm
501 16 : .as_ref()
502 16 : .unwrap_or(&global_conf.compaction_algorithm)
503 16 : .clone(),
504 16 : gc_horizon: self.gc_horizon.unwrap_or(global_conf.gc_horizon),
505 16 : gc_period: self.gc_period.unwrap_or(global_conf.gc_period),
506 16 : image_creation_threshold: self
507 16 : .image_creation_threshold
508 16 : .unwrap_or(global_conf.image_creation_threshold),
509 16 : pitr_interval: self.pitr_interval.unwrap_or(global_conf.pitr_interval),
510 16 : walreceiver_connect_timeout: self
511 16 : .walreceiver_connect_timeout
512 16 : .unwrap_or(global_conf.walreceiver_connect_timeout),
513 16 : lagging_wal_timeout: self
514 16 : .lagging_wal_timeout
515 16 : .unwrap_or(global_conf.lagging_wal_timeout),
516 16 : max_lsn_wal_lag: self.max_lsn_wal_lag.unwrap_or(global_conf.max_lsn_wal_lag),
517 16 : eviction_policy: self.eviction_policy.unwrap_or(global_conf.eviction_policy),
518 16 : min_resident_size_override: self
519 16 : .min_resident_size_override
520 16 : .or(global_conf.min_resident_size_override),
521 16 : evictions_low_residence_duration_metric_threshold: self
522 16 : .evictions_low_residence_duration_metric_threshold
523 16 : .unwrap_or(global_conf.evictions_low_residence_duration_metric_threshold),
524 16 : heatmap_period: self.heatmap_period.unwrap_or(global_conf.heatmap_period),
525 16 : lazy_slru_download: self
526 16 : .lazy_slru_download
527 16 : .unwrap_or(global_conf.lazy_slru_download),
528 16 : timeline_get_throttle: self
529 16 : .timeline_get_throttle
530 16 : .clone()
531 16 : .unwrap_or(global_conf.timeline_get_throttle),
532 16 : image_layer_creation_check_threshold: self
533 16 : .image_layer_creation_check_threshold
534 16 : .unwrap_or(global_conf.image_layer_creation_check_threshold),
535 16 : switch_aux_file_policy: self
536 16 : .switch_aux_file_policy
537 16 : .unwrap_or(global_conf.switch_aux_file_policy),
538 16 : lsn_lease_length: self
539 16 : .lsn_lease_length
540 16 : .unwrap_or(global_conf.lsn_lease_length),
541 16 : lsn_lease_length_for_ts: self
542 16 : .lsn_lease_length_for_ts
543 16 : .unwrap_or(global_conf.lsn_lease_length_for_ts),
544 16 : }
545 16 : }
546 : }
547 :
548 : impl Default for TenantConf {
549 384 : fn default() -> Self {
550 384 : use defaults::*;
551 384 : Self {
552 384 : checkpoint_distance: DEFAULT_CHECKPOINT_DISTANCE,
553 384 : checkpoint_timeout: humantime::parse_duration(DEFAULT_CHECKPOINT_TIMEOUT)
554 384 : .expect("cannot parse default checkpoint timeout"),
555 384 : compaction_target_size: DEFAULT_COMPACTION_TARGET_SIZE,
556 384 : compaction_period: humantime::parse_duration(DEFAULT_COMPACTION_PERIOD)
557 384 : .expect("cannot parse default compaction period"),
558 384 : compaction_threshold: DEFAULT_COMPACTION_THRESHOLD,
559 384 : compaction_algorithm: CompactionAlgorithmSettings {
560 384 : kind: DEFAULT_COMPACTION_ALGORITHM,
561 384 : },
562 384 : gc_horizon: DEFAULT_GC_HORIZON,
563 384 : gc_period: humantime::parse_duration(DEFAULT_GC_PERIOD)
564 384 : .expect("cannot parse default gc period"),
565 384 : image_creation_threshold: DEFAULT_IMAGE_CREATION_THRESHOLD,
566 384 : pitr_interval: humantime::parse_duration(DEFAULT_PITR_INTERVAL)
567 384 : .expect("cannot parse default PITR interval"),
568 384 : walreceiver_connect_timeout: humantime::parse_duration(
569 384 : DEFAULT_WALRECEIVER_CONNECT_TIMEOUT,
570 384 : )
571 384 : .expect("cannot parse default walreceiver connect timeout"),
572 384 : lagging_wal_timeout: humantime::parse_duration(DEFAULT_WALRECEIVER_LAGGING_WAL_TIMEOUT)
573 384 : .expect("cannot parse default walreceiver lagging wal timeout"),
574 384 : max_lsn_wal_lag: NonZeroU64::new(DEFAULT_MAX_WALRECEIVER_LSN_WAL_LAG)
575 384 : .expect("cannot parse default max walreceiver Lsn wal lag"),
576 384 : eviction_policy: EvictionPolicy::NoEviction,
577 384 : min_resident_size_override: None,
578 384 : evictions_low_residence_duration_metric_threshold: humantime::parse_duration(
579 384 : DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD,
580 384 : )
581 384 : .expect("cannot parse default evictions_low_residence_duration_metric_threshold"),
582 384 : heatmap_period: Duration::ZERO,
583 384 : lazy_slru_download: false,
584 384 : timeline_get_throttle: crate::tenant::throttle::Config::disabled(),
585 384 : image_layer_creation_check_threshold: DEFAULT_IMAGE_LAYER_CREATION_CHECK_THRESHOLD,
586 384 : switch_aux_file_policy: AuxFilePolicy::default_tenant_config(),
587 384 : lsn_lease_length: LsnLease::DEFAULT_LENGTH,
588 384 : lsn_lease_length_for_ts: LsnLease::DEFAULT_LENGTH_FOR_TS,
589 384 : }
590 384 : }
591 : }
592 :
593 : impl TryFrom<&'_ models::TenantConfig> for TenantConfOpt {
594 : type Error = anyhow::Error;
595 :
596 4 : fn try_from(request_data: &'_ models::TenantConfig) -> Result<Self, Self::Error> {
597 : // Convert the request_data to a JSON Value
598 4 : let json_value: Value = serde_json::to_value(request_data)?;
599 :
600 : // Create a Deserializer from the JSON Value
601 4 : let deserializer = json_value.into_deserializer();
602 :
603 : // Use serde_path_to_error to deserialize the JSON Value into TenantConfOpt
604 4 : let tenant_conf: TenantConfOpt = serde_path_to_error::deserialize(deserializer)?;
605 :
606 2 : Ok(tenant_conf)
607 4 : }
608 : }
609 :
610 : impl TryFrom<toml_edit::Item> for TenantConfOpt {
611 : type Error = anyhow::Error;
612 :
613 8 : fn try_from(item: toml_edit::Item) -> Result<Self, Self::Error> {
614 8 : match item {
615 2 : toml_edit::Item::Value(value) => {
616 2 : let d = value.into_deserializer();
617 2 : return serde_path_to_error::deserialize(d)
618 2 : .map_err(|e| anyhow::anyhow!("{}: {}", e.path(), e.inner().message()));
619 : }
620 6 : toml_edit::Item::Table(table) => {
621 6 : let deserializer = toml_edit::de::Deserializer::new(table.into());
622 6 : return serde_path_to_error::deserialize(deserializer)
623 6 : .map_err(|e| anyhow::anyhow!("{}: {}", e.path(), e.inner().message()));
624 : }
625 : _ => {
626 0 : bail!("expected non-inline table but found {item}")
627 : }
628 : }
629 8 : }
630 : }
631 :
632 : /// This is a conversion from our internal tenant config object to the one used
633 : /// in external APIs.
634 : impl From<TenantConfOpt> for models::TenantConfig {
635 0 : fn from(value: TenantConfOpt) -> Self {
636 0 : fn humantime(d: Duration) -> String {
637 0 : format!("{}s", d.as_secs())
638 0 : }
639 0 : Self {
640 0 : checkpoint_distance: value.checkpoint_distance,
641 0 : checkpoint_timeout: value.checkpoint_timeout.map(humantime),
642 0 : compaction_algorithm: value.compaction_algorithm,
643 0 : compaction_target_size: value.compaction_target_size,
644 0 : compaction_period: value.compaction_period.map(humantime),
645 0 : compaction_threshold: value.compaction_threshold,
646 0 : gc_horizon: value.gc_horizon,
647 0 : gc_period: value.gc_period.map(humantime),
648 0 : image_creation_threshold: value.image_creation_threshold,
649 0 : pitr_interval: value.pitr_interval.map(humantime),
650 0 : walreceiver_connect_timeout: value.walreceiver_connect_timeout.map(humantime),
651 0 : lagging_wal_timeout: value.lagging_wal_timeout.map(humantime),
652 0 : max_lsn_wal_lag: value.max_lsn_wal_lag,
653 0 : eviction_policy: value.eviction_policy,
654 0 : min_resident_size_override: value.min_resident_size_override,
655 0 : evictions_low_residence_duration_metric_threshold: value
656 0 : .evictions_low_residence_duration_metric_threshold
657 0 : .map(humantime),
658 0 : heatmap_period: value.heatmap_period.map(humantime),
659 0 : lazy_slru_download: value.lazy_slru_download,
660 0 : timeline_get_throttle: value.timeline_get_throttle.map(ThrottleConfig::from),
661 0 : image_layer_creation_check_threshold: value.image_layer_creation_check_threshold,
662 0 : switch_aux_file_policy: value.switch_aux_file_policy,
663 0 : lsn_lease_length: value.lsn_lease_length.map(humantime),
664 0 : lsn_lease_length_for_ts: value.lsn_lease_length_for_ts.map(humantime),
665 0 : }
666 0 : }
667 : }
668 :
669 : #[cfg(test)]
670 : mod tests {
671 : use super::*;
672 : use models::TenantConfig;
673 :
674 : #[test]
675 2 : fn de_serializing_pageserver_config_omits_empty_values() {
676 2 : let small_conf = TenantConfOpt {
677 2 : gc_horizon: Some(42),
678 2 : ..TenantConfOpt::default()
679 2 : };
680 2 :
681 2 : let toml_form = toml_edit::ser::to_string(&small_conf).unwrap();
682 2 : assert_eq!(toml_form, "gc_horizon = 42\n");
683 2 : assert_eq!(small_conf, toml_edit::de::from_str(&toml_form).unwrap());
684 :
685 2 : let json_form = serde_json::to_string(&small_conf).unwrap();
686 2 : assert_eq!(json_form, "{\"gc_horizon\":42}");
687 2 : assert_eq!(small_conf, serde_json::from_str(&json_form).unwrap());
688 2 : }
689 :
690 : #[test]
691 2 : fn test_try_from_models_tenant_config_err() {
692 2 : let tenant_config = models::TenantConfig {
693 2 : lagging_wal_timeout: Some("5a".to_string()),
694 2 : ..TenantConfig::default()
695 2 : };
696 2 :
697 2 : let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config);
698 2 :
699 2 : assert!(
700 2 : tenant_conf_opt.is_err(),
701 0 : "Suceeded to convert TenantConfig to TenantConfOpt"
702 : );
703 :
704 2 : let expected_error_str =
705 2 : "lagging_wal_timeout: invalid value: string \"5a\", expected a duration";
706 2 : assert_eq!(tenant_conf_opt.unwrap_err().to_string(), expected_error_str);
707 2 : }
708 :
709 : #[test]
710 2 : fn test_try_from_models_tenant_config_success() {
711 2 : let tenant_config = models::TenantConfig {
712 2 : lagging_wal_timeout: Some("5s".to_string()),
713 2 : ..TenantConfig::default()
714 2 : };
715 2 :
716 2 : let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config).unwrap();
717 2 :
718 2 : assert_eq!(
719 2 : tenant_conf_opt.lagging_wal_timeout,
720 2 : Some(Duration::from_secs(5))
721 2 : );
722 2 : }
723 : }
|