LCOV - code coverage report
Current view: top level - pageserver/src/tenant - config.rs (source / functions) Coverage Total Hit
Test: 5187d4b6d9cfe1c429baf0147b0578521d04e1ed.info Lines: 63.9 % 294 188
Test Date: 2024-06-26 21:48:01 Functions: 12.6 % 175 22

            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          169 :     pub(crate) fn attached_single(
     188          169 :         tenant_conf: TenantConfOpt,
     189          169 :         generation: Generation,
     190          169 :         shard_params: &models::ShardParameters,
     191          169 :     ) -> Self {
     192          169 :         Self {
     193          169 :             mode: LocationMode::Attached(AttachedLocationConfig {
     194          169 :                 generation,
     195          169 :                 attach_mode: AttachmentMode::Single,
     196          169 :             }),
     197          169 :             shard: ShardIdentity::from_params(ShardNumber(0), shard_params),
     198          169 :             tenant_conf,
     199          169 :         }
     200          169 :     }
     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 trace_read_requests: bool,
     339              :     pub eviction_policy: EvictionPolicy,
     340              :     pub min_resident_size_override: Option<u64>,
     341              :     // See the corresponding metric's help string.
     342              :     #[serde(with = "humantime_serde")]
     343              :     pub evictions_low_residence_duration_metric_threshold: Duration,
     344              : 
     345              :     /// If non-zero, the period between uploads of a heatmap from attached tenants.  This
     346              :     /// may be disabled if a Tenant will not have secondary locations: only secondary
     347              :     /// locations will use the heatmap uploaded by attached locations.
     348              :     #[serde(with = "humantime_serde")]
     349              :     pub heatmap_period: Duration,
     350              : 
     351              :     /// If true then SLRU segments are dowloaded on demand, if false SLRU segments are included in basebackup
     352              :     pub lazy_slru_download: bool,
     353              : 
     354              :     pub timeline_get_throttle: pageserver_api::models::ThrottleConfig,
     355              : 
     356              :     // How much WAL must be ingested before checking again whether a new image layer is required.
     357              :     // Expresed in multiples of checkpoint distance.
     358              :     pub image_layer_creation_check_threshold: u8,
     359              : 
     360              :     /// Switch to a new aux file policy. Switching this flag requires the user has not written any aux file into
     361              :     /// the storage before, and this flag cannot be switched back. Otherwise there will be data corruptions.
     362              :     /// There is a `last_aux_file_policy` flag which gets persisted in `index_part.json` once the first aux
     363              :     /// file is written.
     364              :     pub switch_aux_file_policy: AuxFilePolicy,
     365              : 
     366              :     /// The length for an explicit LSN lease request.
     367              :     /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
     368              :     #[serde(with = "humantime_serde")]
     369              :     pub lsn_lease_length: Duration,
     370              : 
     371              :     /// The length for an implicit LSN lease granted as part of `get_lsn_by_timestamp` request.
     372              :     /// Layers needed to reconstruct pages at LSN will not be GC-ed during this interval.
     373              :     #[serde(with = "humantime_serde")]
     374              :     pub lsn_lease_length_for_ts: Duration,
     375              : }
     376              : 
     377              : /// Same as TenantConf, but this struct preserves the information about
     378              : /// which parameters are set and which are not.
     379          152 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
     380              : pub struct TenantConfOpt {
     381              :     #[serde(skip_serializing_if = "Option::is_none")]
     382              :     #[serde(default)]
     383              :     pub checkpoint_distance: Option<u64>,
     384              : 
     385              :     #[serde(skip_serializing_if = "Option::is_none")]
     386              :     #[serde(with = "humantime_serde")]
     387              :     #[serde(default)]
     388              :     pub checkpoint_timeout: Option<Duration>,
     389              : 
     390              :     #[serde(skip_serializing_if = "Option::is_none")]
     391              :     #[serde(default)]
     392              :     pub compaction_target_size: Option<u64>,
     393              : 
     394              :     #[serde(skip_serializing_if = "Option::is_none")]
     395              :     #[serde(with = "humantime_serde")]
     396              :     #[serde(default)]
     397              :     pub compaction_period: Option<Duration>,
     398              : 
     399              :     #[serde(skip_serializing_if = "Option::is_none")]
     400              :     #[serde(default)]
     401              :     pub compaction_threshold: Option<usize>,
     402              : 
     403              :     #[serde(skip_serializing_if = "Option::is_none")]
     404              :     #[serde(default)]
     405              :     pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
     406              : 
     407              :     #[serde(skip_serializing_if = "Option::is_none")]
     408              :     #[serde(default)]
     409              :     pub gc_horizon: Option<u64>,
     410              : 
     411              :     #[serde(skip_serializing_if = "Option::is_none")]
     412              :     #[serde(with = "humantime_serde")]
     413              :     #[serde(default)]
     414              :     pub gc_period: Option<Duration>,
     415              : 
     416              :     #[serde(skip_serializing_if = "Option::is_none")]
     417              :     #[serde(default)]
     418              :     pub image_creation_threshold: Option<usize>,
     419              : 
     420              :     #[serde(skip_serializing_if = "Option::is_none")]
     421              :     #[serde(with = "humantime_serde")]
     422              :     #[serde(default)]
     423              :     pub pitr_interval: Option<Duration>,
     424              : 
     425              :     #[serde(skip_serializing_if = "Option::is_none")]
     426              :     #[serde(with = "humantime_serde")]
     427              :     #[serde(default)]
     428              :     pub walreceiver_connect_timeout: Option<Duration>,
     429              : 
     430              :     #[serde(skip_serializing_if = "Option::is_none")]
     431              :     #[serde(with = "humantime_serde")]
     432              :     #[serde(default)]
     433              :     pub lagging_wal_timeout: Option<Duration>,
     434              : 
     435              :     #[serde(skip_serializing_if = "Option::is_none")]
     436              :     #[serde(default)]
     437              :     pub max_lsn_wal_lag: Option<NonZeroU64>,
     438              : 
     439              :     #[serde(skip_serializing_if = "Option::is_none")]
     440              :     #[serde(default)]
     441              :     pub trace_read_requests: Option<bool>,
     442              : 
     443              :     #[serde(skip_serializing_if = "Option::is_none")]
     444              :     #[serde(default)]
     445              :     pub eviction_policy: Option<EvictionPolicy>,
     446              : 
     447              :     #[serde(skip_serializing_if = "Option::is_none")]
     448              :     #[serde(default)]
     449              :     pub min_resident_size_override: Option<u64>,
     450              : 
     451              :     #[serde(skip_serializing_if = "Option::is_none")]
     452              :     #[serde(with = "humantime_serde")]
     453              :     #[serde(default)]
     454              :     pub evictions_low_residence_duration_metric_threshold: Option<Duration>,
     455              : 
     456              :     #[serde(skip_serializing_if = "Option::is_none")]
     457              :     #[serde(with = "humantime_serde")]
     458              :     #[serde(default)]
     459              :     pub heatmap_period: Option<Duration>,
     460              : 
     461              :     #[serde(skip_serializing_if = "Option::is_none")]
     462              :     #[serde(default)]
     463              :     pub lazy_slru_download: Option<bool>,
     464              : 
     465              :     #[serde(skip_serializing_if = "Option::is_none")]
     466              :     pub timeline_get_throttle: Option<pageserver_api::models::ThrottleConfig>,
     467              : 
     468              :     #[serde(skip_serializing_if = "Option::is_none")]
     469              :     pub image_layer_creation_check_threshold: Option<u8>,
     470              : 
     471              :     #[serde(skip_serializing_if = "Option::is_none")]
     472              :     #[serde(default)]
     473              :     pub switch_aux_file_policy: Option<AuxFilePolicy>,
     474              : 
     475              :     #[serde(skip_serializing_if = "Option::is_none")]
     476              :     #[serde(with = "humantime_serde")]
     477              :     #[serde(default)]
     478              :     pub lsn_lease_length: Option<Duration>,
     479              : 
     480              :     #[serde(skip_serializing_if = "Option::is_none")]
     481              :     #[serde(with = "humantime_serde")]
     482              :     #[serde(default)]
     483              :     pub lsn_lease_length_for_ts: Option<Duration>,
     484              : }
     485              : 
     486              : impl TenantConfOpt {
     487           18 :     pub fn merge(&self, global_conf: TenantConf) -> TenantConf {
     488           18 :         TenantConf {
     489           18 :             checkpoint_distance: self
     490           18 :                 .checkpoint_distance
     491           18 :                 .unwrap_or(global_conf.checkpoint_distance),
     492           18 :             checkpoint_timeout: self
     493           18 :                 .checkpoint_timeout
     494           18 :                 .unwrap_or(global_conf.checkpoint_timeout),
     495           18 :             compaction_target_size: self
     496           18 :                 .compaction_target_size
     497           18 :                 .unwrap_or(global_conf.compaction_target_size),
     498           18 :             compaction_period: self
     499           18 :                 .compaction_period
     500           18 :                 .unwrap_or(global_conf.compaction_period),
     501           18 :             compaction_threshold: self
     502           18 :                 .compaction_threshold
     503           18 :                 .unwrap_or(global_conf.compaction_threshold),
     504           18 :             compaction_algorithm: self
     505           18 :                 .compaction_algorithm
     506           18 :                 .as_ref()
     507           18 :                 .unwrap_or(&global_conf.compaction_algorithm)
     508           18 :                 .clone(),
     509           18 :             gc_horizon: self.gc_horizon.unwrap_or(global_conf.gc_horizon),
     510           18 :             gc_period: self.gc_period.unwrap_or(global_conf.gc_period),
     511           18 :             image_creation_threshold: self
     512           18 :                 .image_creation_threshold
     513           18 :                 .unwrap_or(global_conf.image_creation_threshold),
     514           18 :             pitr_interval: self.pitr_interval.unwrap_or(global_conf.pitr_interval),
     515           18 :             walreceiver_connect_timeout: self
     516           18 :                 .walreceiver_connect_timeout
     517           18 :                 .unwrap_or(global_conf.walreceiver_connect_timeout),
     518           18 :             lagging_wal_timeout: self
     519           18 :                 .lagging_wal_timeout
     520           18 :                 .unwrap_or(global_conf.lagging_wal_timeout),
     521           18 :             max_lsn_wal_lag: self.max_lsn_wal_lag.unwrap_or(global_conf.max_lsn_wal_lag),
     522           18 :             trace_read_requests: self
     523           18 :                 .trace_read_requests
     524           18 :                 .unwrap_or(global_conf.trace_read_requests),
     525           18 :             eviction_policy: self.eviction_policy.unwrap_or(global_conf.eviction_policy),
     526           18 :             min_resident_size_override: self
     527           18 :                 .min_resident_size_override
     528           18 :                 .or(global_conf.min_resident_size_override),
     529           18 :             evictions_low_residence_duration_metric_threshold: self
     530           18 :                 .evictions_low_residence_duration_metric_threshold
     531           18 :                 .unwrap_or(global_conf.evictions_low_residence_duration_metric_threshold),
     532           18 :             heatmap_period: self.heatmap_period.unwrap_or(global_conf.heatmap_period),
     533           18 :             lazy_slru_download: self
     534           18 :                 .lazy_slru_download
     535           18 :                 .unwrap_or(global_conf.lazy_slru_download),
     536           18 :             timeline_get_throttle: self
     537           18 :                 .timeline_get_throttle
     538           18 :                 .clone()
     539           18 :                 .unwrap_or(global_conf.timeline_get_throttle),
     540           18 :             image_layer_creation_check_threshold: self
     541           18 :                 .image_layer_creation_check_threshold
     542           18 :                 .unwrap_or(global_conf.image_layer_creation_check_threshold),
     543           18 :             switch_aux_file_policy: self
     544           18 :                 .switch_aux_file_policy
     545           18 :                 .unwrap_or(global_conf.switch_aux_file_policy),
     546           18 :             lsn_lease_length: self
     547           18 :                 .lsn_lease_length
     548           18 :                 .unwrap_or(global_conf.lsn_lease_length),
     549           18 :             lsn_lease_length_for_ts: self
     550           18 :                 .lsn_lease_length_for_ts
     551           18 :                 .unwrap_or(global_conf.lsn_lease_length_for_ts),
     552           18 :         }
     553           18 :     }
     554              : }
     555              : 
     556              : impl Default for TenantConf {
     557          362 :     fn default() -> Self {
     558          362 :         use defaults::*;
     559          362 :         Self {
     560          362 :             checkpoint_distance: DEFAULT_CHECKPOINT_DISTANCE,
     561          362 :             checkpoint_timeout: humantime::parse_duration(DEFAULT_CHECKPOINT_TIMEOUT)
     562          362 :                 .expect("cannot parse default checkpoint timeout"),
     563          362 :             compaction_target_size: DEFAULT_COMPACTION_TARGET_SIZE,
     564          362 :             compaction_period: humantime::parse_duration(DEFAULT_COMPACTION_PERIOD)
     565          362 :                 .expect("cannot parse default compaction period"),
     566          362 :             compaction_threshold: DEFAULT_COMPACTION_THRESHOLD,
     567          362 :             compaction_algorithm: CompactionAlgorithmSettings {
     568          362 :                 kind: DEFAULT_COMPACTION_ALGORITHM,
     569          362 :             },
     570          362 :             gc_horizon: DEFAULT_GC_HORIZON,
     571          362 :             gc_period: humantime::parse_duration(DEFAULT_GC_PERIOD)
     572          362 :                 .expect("cannot parse default gc period"),
     573          362 :             image_creation_threshold: DEFAULT_IMAGE_CREATION_THRESHOLD,
     574          362 :             pitr_interval: humantime::parse_duration(DEFAULT_PITR_INTERVAL)
     575          362 :                 .expect("cannot parse default PITR interval"),
     576          362 :             walreceiver_connect_timeout: humantime::parse_duration(
     577          362 :                 DEFAULT_WALRECEIVER_CONNECT_TIMEOUT,
     578          362 :             )
     579          362 :             .expect("cannot parse default walreceiver connect timeout"),
     580          362 :             lagging_wal_timeout: humantime::parse_duration(DEFAULT_WALRECEIVER_LAGGING_WAL_TIMEOUT)
     581          362 :                 .expect("cannot parse default walreceiver lagging wal timeout"),
     582          362 :             max_lsn_wal_lag: NonZeroU64::new(DEFAULT_MAX_WALRECEIVER_LSN_WAL_LAG)
     583          362 :                 .expect("cannot parse default max walreceiver Lsn wal lag"),
     584          362 :             trace_read_requests: false,
     585          362 :             eviction_policy: EvictionPolicy::NoEviction,
     586          362 :             min_resident_size_override: None,
     587          362 :             evictions_low_residence_duration_metric_threshold: humantime::parse_duration(
     588          362 :                 DEFAULT_EVICTIONS_LOW_RESIDENCE_DURATION_METRIC_THRESHOLD,
     589          362 :             )
     590          362 :             .expect("cannot parse default evictions_low_residence_duration_metric_threshold"),
     591          362 :             heatmap_period: Duration::ZERO,
     592          362 :             lazy_slru_download: false,
     593          362 :             timeline_get_throttle: crate::tenant::throttle::Config::disabled(),
     594          362 :             image_layer_creation_check_threshold: DEFAULT_IMAGE_LAYER_CREATION_CHECK_THRESHOLD,
     595          362 :             switch_aux_file_policy: AuxFilePolicy::default_tenant_config(),
     596          362 :             lsn_lease_length: LsnLease::DEFAULT_LENGTH,
     597          362 :             lsn_lease_length_for_ts: LsnLease::DEFAULT_LENGTH_FOR_TS,
     598          362 :         }
     599          362 :     }
     600              : }
     601              : 
     602              : impl TryFrom<&'_ models::TenantConfig> for TenantConfOpt {
     603              :     type Error = anyhow::Error;
     604              : 
     605            4 :     fn try_from(request_data: &'_ models::TenantConfig) -> Result<Self, Self::Error> {
     606              :         // Convert the request_data to a JSON Value
     607            4 :         let json_value: Value = serde_json::to_value(request_data)?;
     608              : 
     609              :         // Create a Deserializer from the JSON Value
     610            4 :         let deserializer = json_value.into_deserializer();
     611              : 
     612              :         // Use serde_path_to_error to deserialize the JSON Value into TenantConfOpt
     613            4 :         let tenant_conf: TenantConfOpt = serde_path_to_error::deserialize(deserializer)?;
     614              : 
     615            2 :         Ok(tenant_conf)
     616            4 :     }
     617              : }
     618              : 
     619              : impl TryFrom<toml_edit::Item> for TenantConfOpt {
     620              :     type Error = anyhow::Error;
     621              : 
     622           10 :     fn try_from(item: toml_edit::Item) -> Result<Self, Self::Error> {
     623           10 :         match item {
     624            2 :             toml_edit::Item::Value(value) => {
     625            2 :                 let d = value.into_deserializer();
     626            2 :                 return serde_path_to_error::deserialize(d)
     627            2 :                     .map_err(|e| anyhow::anyhow!("{}: {}", e.path(), e.inner().message()));
     628              :             }
     629            8 :             toml_edit::Item::Table(table) => {
     630            8 :                 let deserializer = toml_edit::de::Deserializer::new(table.into());
     631            8 :                 return serde_path_to_error::deserialize(deserializer)
     632            8 :                     .map_err(|e| anyhow::anyhow!("{}: {}", e.path(), e.inner().message()));
     633              :             }
     634              :             _ => {
     635            0 :                 bail!("expected non-inline table but found {item}")
     636              :             }
     637              :         }
     638           10 :     }
     639              : }
     640              : 
     641              : /// This is a conversion from our internal tenant config object to the one used
     642              : /// in external APIs.
     643              : impl From<TenantConfOpt> for models::TenantConfig {
     644            0 :     fn from(value: TenantConfOpt) -> Self {
     645            0 :         fn humantime(d: Duration) -> String {
     646            0 :             format!("{}s", d.as_secs())
     647            0 :         }
     648            0 :         Self {
     649            0 :             checkpoint_distance: value.checkpoint_distance,
     650            0 :             checkpoint_timeout: value.checkpoint_timeout.map(humantime),
     651            0 :             compaction_algorithm: value.compaction_algorithm,
     652            0 :             compaction_target_size: value.compaction_target_size,
     653            0 :             compaction_period: value.compaction_period.map(humantime),
     654            0 :             compaction_threshold: value.compaction_threshold,
     655            0 :             gc_horizon: value.gc_horizon,
     656            0 :             gc_period: value.gc_period.map(humantime),
     657            0 :             image_creation_threshold: value.image_creation_threshold,
     658            0 :             pitr_interval: value.pitr_interval.map(humantime),
     659            0 :             walreceiver_connect_timeout: value.walreceiver_connect_timeout.map(humantime),
     660            0 :             lagging_wal_timeout: value.lagging_wal_timeout.map(humantime),
     661            0 :             max_lsn_wal_lag: value.max_lsn_wal_lag,
     662            0 :             trace_read_requests: value.trace_read_requests,
     663            0 :             eviction_policy: value.eviction_policy,
     664            0 :             min_resident_size_override: value.min_resident_size_override,
     665            0 :             evictions_low_residence_duration_metric_threshold: value
     666            0 :                 .evictions_low_residence_duration_metric_threshold
     667            0 :                 .map(humantime),
     668            0 :             heatmap_period: value.heatmap_period.map(humantime),
     669            0 :             lazy_slru_download: value.lazy_slru_download,
     670            0 :             timeline_get_throttle: value.timeline_get_throttle.map(ThrottleConfig::from),
     671            0 :             image_layer_creation_check_threshold: value.image_layer_creation_check_threshold,
     672            0 :             switch_aux_file_policy: value.switch_aux_file_policy,
     673            0 :             lsn_lease_length: value.lsn_lease_length.map(humantime),
     674            0 :             lsn_lease_length_for_ts: value.lsn_lease_length_for_ts.map(humantime),
     675            0 :         }
     676            0 :     }
     677              : }
     678              : 
     679              : #[cfg(test)]
     680              : mod tests {
     681              :     use super::*;
     682              :     use models::TenantConfig;
     683              : 
     684              :     #[test]
     685            2 :     fn de_serializing_pageserver_config_omits_empty_values() {
     686            2 :         let small_conf = TenantConfOpt {
     687            2 :             gc_horizon: Some(42),
     688            2 :             ..TenantConfOpt::default()
     689            2 :         };
     690            2 : 
     691            2 :         let toml_form = toml_edit::ser::to_string(&small_conf).unwrap();
     692            2 :         assert_eq!(toml_form, "gc_horizon = 42\n");
     693            2 :         assert_eq!(small_conf, toml_edit::de::from_str(&toml_form).unwrap());
     694              : 
     695            2 :         let json_form = serde_json::to_string(&small_conf).unwrap();
     696            2 :         assert_eq!(json_form, "{\"gc_horizon\":42}");
     697            2 :         assert_eq!(small_conf, serde_json::from_str(&json_form).unwrap());
     698            2 :     }
     699              : 
     700              :     #[test]
     701            2 :     fn test_try_from_models_tenant_config_err() {
     702            2 :         let tenant_config = models::TenantConfig {
     703            2 :             lagging_wal_timeout: Some("5a".to_string()),
     704            2 :             ..TenantConfig::default()
     705            2 :         };
     706            2 : 
     707            2 :         let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config);
     708            2 : 
     709            2 :         assert!(
     710            2 :             tenant_conf_opt.is_err(),
     711            0 :             "Suceeded to convert TenantConfig to TenantConfOpt"
     712              :         );
     713              : 
     714            2 :         let expected_error_str =
     715            2 :             "lagging_wal_timeout: invalid value: string \"5a\", expected a duration";
     716            2 :         assert_eq!(tenant_conf_opt.unwrap_err().to_string(), expected_error_str);
     717            2 :     }
     718              : 
     719              :     #[test]
     720            2 :     fn test_try_from_models_tenant_config_success() {
     721            2 :         let tenant_config = models::TenantConfig {
     722            2 :             lagging_wal_timeout: Some("5s".to_string()),
     723            2 :             ..TenantConfig::default()
     724            2 :         };
     725            2 : 
     726            2 :         let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config).unwrap();
     727            2 : 
     728            2 :         assert_eq!(
     729            2 :             tenant_conf_opt.lagging_wal_timeout,
     730            2 :             Some(Duration::from_secs(5))
     731            2 :         );
     732            2 :     }
     733              : }
        

Generated by: LCOV version 2.1-beta