LCOV - code coverage report
Current view: top level - pageserver/src - metrics.rs (source / functions) Coverage Total Hit
Test: 2b0730d767f560e20b6748f57465922aa8bb805e.info Lines: 73.2 % 2268 1661
Test Date: 2024-09-25 14:04:07 Functions: 65.4 % 260 170

            Line data    Source code
       1              : use enum_map::EnumMap;
       2              : use metrics::{
       3              :     register_counter_vec, register_gauge_vec, register_histogram, register_histogram_vec,
       4              :     register_int_counter, register_int_counter_pair_vec, register_int_counter_vec,
       5              :     register_int_gauge, register_int_gauge_vec, register_uint_gauge, register_uint_gauge_vec,
       6              :     Counter, CounterVec, GaugeVec, Histogram, HistogramVec, IntCounter, IntCounterPair,
       7              :     IntCounterPairVec, IntCounterVec, IntGauge, IntGaugeVec, UIntGauge, UIntGaugeVec,
       8              : };
       9              : use once_cell::sync::Lazy;
      10              : use pageserver_api::shard::TenantShardId;
      11              : use strum::{EnumCount, VariantNames};
      12              : use strum_macros::{IntoStaticStr, VariantNames};
      13              : use tracing::warn;
      14              : use utils::id::TimelineId;
      15              : 
      16              : /// Prometheus histogram buckets (in seconds) for operations in the critical
      17              : /// path. In other words, operations that directly affect that latency of user
      18              : /// queries.
      19              : ///
      20              : /// The buckets capture the majority of latencies in the microsecond and
      21              : /// millisecond range but also extend far enough up to distinguish "bad" from
      22              : /// "really bad".
      23              : const CRITICAL_OP_BUCKETS: &[f64] = &[
      24              :     0.000_001, 0.000_010, 0.000_100, // 1 us, 10 us, 100 us
      25              :     0.001_000, 0.010_000, 0.100_000, // 1 ms, 10 ms, 100 ms
      26              :     1.0, 10.0, 100.0, // 1 s, 10 s, 100 s
      27              : ];
      28              : 
      29              : // Metrics collected on operations on the storage repository.
      30         9936 : #[derive(Debug, VariantNames, IntoStaticStr)]
      31              : #[strum(serialize_all = "kebab_case")]
      32              : pub(crate) enum StorageTimeOperation {
      33              :     #[strum(serialize = "layer flush")]
      34              :     LayerFlush,
      35              : 
      36              :     #[strum(serialize = "compact")]
      37              :     Compact,
      38              : 
      39              :     #[strum(serialize = "create images")]
      40              :     CreateImages,
      41              : 
      42              :     #[strum(serialize = "logical size")]
      43              :     LogicalSize,
      44              : 
      45              :     #[strum(serialize = "imitate logical size")]
      46              :     ImitateLogicalSize,
      47              : 
      48              :     #[strum(serialize = "load layer map")]
      49              :     LoadLayerMap,
      50              : 
      51              :     #[strum(serialize = "gc")]
      52              :     Gc,
      53              : 
      54              :     #[strum(serialize = "find gc cutoffs")]
      55              :     FindGcCutoffs,
      56              : }
      57              : 
      58          510 : pub(crate) static STORAGE_TIME_SUM_PER_TIMELINE: Lazy<CounterVec> = Lazy::new(|| {
      59          510 :     register_counter_vec!(
      60          510 :         "pageserver_storage_operations_seconds_sum",
      61          510 :         "Total time spent on storage operations with operation, tenant and timeline dimensions",
      62          510 :         &["operation", "tenant_id", "shard_id", "timeline_id"],
      63          510 :     )
      64          510 :     .expect("failed to define a metric")
      65          510 : });
      66              : 
      67          510 : pub(crate) static STORAGE_TIME_COUNT_PER_TIMELINE: Lazy<IntCounterVec> = Lazy::new(|| {
      68          510 :     register_int_counter_vec!(
      69          510 :         "pageserver_storage_operations_seconds_count",
      70          510 :         "Count of storage operations with operation, tenant and timeline dimensions",
      71          510 :         &["operation", "tenant_id", "shard_id", "timeline_id"],
      72          510 :     )
      73          510 :     .expect("failed to define a metric")
      74          510 : });
      75              : 
      76              : // Buckets for background operations like compaction, GC, size calculation
      77              : const STORAGE_OP_BUCKETS: &[f64] = &[0.010, 0.100, 1.0, 10.0, 100.0, 1000.0];
      78              : 
      79          510 : pub(crate) static STORAGE_TIME_GLOBAL: Lazy<HistogramVec> = Lazy::new(|| {
      80          510 :     register_histogram_vec!(
      81          510 :         "pageserver_storage_operations_seconds_global",
      82          510 :         "Time spent on storage operations",
      83          510 :         &["operation"],
      84          510 :         STORAGE_OP_BUCKETS.into(),
      85          510 :     )
      86          510 :     .expect("failed to define a metric")
      87          510 : });
      88              : 
      89            0 : pub(crate) static READ_NUM_LAYERS_VISITED: Lazy<Histogram> = Lazy::new(|| {
      90            0 :     register_histogram!(
      91            0 :         "pageserver_layers_visited_per_read_global",
      92            0 :         "Number of layers visited to reconstruct one key",
      93            0 :         vec![1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0],
      94            0 :     )
      95            0 :     .expect("failed to define a metric")
      96            0 : });
      97              : 
      98          498 : pub(crate) static VEC_READ_NUM_LAYERS_VISITED: Lazy<Histogram> = Lazy::new(|| {
      99          498 :     register_histogram!(
     100          498 :         "pageserver_layers_visited_per_vectored_read_global",
     101          498 :         "Average number of layers visited to reconstruct one key",
     102          498 :         vec![1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0],
     103          498 :     )
     104          498 :     .expect("failed to define a metric")
     105          498 : });
     106              : 
     107              : // Metrics collected on operations on the storage repository.
     108              : #[derive(
     109         2016 :     Clone, Copy, enum_map::Enum, strum_macros::EnumString, strum_macros::Display, IntoStaticStr,
     110              : )]
     111              : pub(crate) enum GetKind {
     112              :     Singular,
     113              :     Vectored,
     114              : }
     115              : 
     116              : pub(crate) struct ReconstructTimeMetrics {
     117              :     singular: Histogram,
     118              :     vectored: Histogram,
     119              : }
     120              : 
     121          504 : pub(crate) static RECONSTRUCT_TIME: Lazy<ReconstructTimeMetrics> = Lazy::new(|| {
     122          504 :     let inner = register_histogram_vec!(
     123          504 :         "pageserver_getpage_reconstruct_seconds",
     124          504 :         "Time spent in reconstruct_value (reconstruct a page from deltas)",
     125          504 :         &["get_kind"],
     126          504 :         CRITICAL_OP_BUCKETS.into(),
     127          504 :     )
     128          504 :     .expect("failed to define a metric");
     129          504 : 
     130          504 :     ReconstructTimeMetrics {
     131          504 :         singular: inner.with_label_values(&[GetKind::Singular.into()]),
     132          504 :         vectored: inner.with_label_values(&[GetKind::Vectored.into()]),
     133          504 :     }
     134          504 : });
     135              : 
     136              : impl ReconstructTimeMetrics {
     137      1880463 :     pub(crate) fn for_get_kind(&self, get_kind: GetKind) -> &Histogram {
     138      1880463 :         match get_kind {
     139      1879131 :             GetKind::Singular => &self.singular,
     140         1332 :             GetKind::Vectored => &self.vectored,
     141              :         }
     142      1880463 :     }
     143              : }
     144              : 
     145              : pub(crate) struct ReconstructDataTimeMetrics {
     146              :     singular: Histogram,
     147              :     vectored: Histogram,
     148              : }
     149              : 
     150              : impl ReconstructDataTimeMetrics {
     151      1880511 :     pub(crate) fn for_get_kind(&self, get_kind: GetKind) -> &Histogram {
     152      1880511 :         match get_kind {
     153      1879179 :             GetKind::Singular => &self.singular,
     154         1332 :             GetKind::Vectored => &self.vectored,
     155              :         }
     156      1880511 :     }
     157              : }
     158              : 
     159          504 : pub(crate) static GET_RECONSTRUCT_DATA_TIME: Lazy<ReconstructDataTimeMetrics> = Lazy::new(|| {
     160          504 :     let inner = register_histogram_vec!(
     161          504 :         "pageserver_getpage_get_reconstruct_data_seconds",
     162          504 :         "Time spent in get_reconstruct_value_data",
     163          504 :         &["get_kind"],
     164          504 :         CRITICAL_OP_BUCKETS.into(),
     165          504 :     )
     166          504 :     .expect("failed to define a metric");
     167          504 : 
     168          504 :     ReconstructDataTimeMetrics {
     169          504 :         singular: inner.with_label_values(&[GetKind::Singular.into()]),
     170          504 :         vectored: inner.with_label_values(&[GetKind::Vectored.into()]),
     171          504 :     }
     172          504 : });
     173              : 
     174              : pub(crate) struct GetVectoredLatency {
     175              :     map: EnumMap<TaskKind, Option<Histogram>>,
     176              : }
     177              : 
     178              : #[allow(dead_code)]
     179              : pub(crate) struct ScanLatency {
     180              :     map: EnumMap<TaskKind, Option<Histogram>>,
     181              : }
     182              : 
     183              : impl GetVectoredLatency {
     184              :     // Only these task types perform vectored gets. Filter all other tasks out to reduce total
     185              :     // cardinality of the metric.
     186              :     const TRACKED_TASK_KINDS: [TaskKind; 2] = [TaskKind::Compaction, TaskKind::PageRequestHandler];
     187              : 
     188         3396 :     pub(crate) fn for_task_kind(&self, task_kind: TaskKind) -> Option<&Histogram> {
     189         3396 :         self.map[task_kind].as_ref()
     190         3396 :     }
     191              : }
     192              : 
     193              : impl ScanLatency {
     194              :     // Only these task types perform vectored gets. Filter all other tasks out to reduce total
     195              :     // cardinality of the metric.
     196              :     const TRACKED_TASK_KINDS: [TaskKind; 1] = [TaskKind::PageRequestHandler];
     197              : 
     198           72 :     pub(crate) fn for_task_kind(&self, task_kind: TaskKind) -> Option<&Histogram> {
     199           72 :         self.map[task_kind].as_ref()
     200           72 :     }
     201              : }
     202              : 
     203              : pub(crate) struct ScanLatencyOngoingRecording<'a> {
     204              :     parent: &'a Histogram,
     205              :     start: std::time::Instant,
     206              : }
     207              : 
     208              : impl<'a> ScanLatencyOngoingRecording<'a> {
     209            0 :     pub(crate) fn start_recording(parent: &'a Histogram) -> ScanLatencyOngoingRecording<'a> {
     210            0 :         let start = Instant::now();
     211            0 :         ScanLatencyOngoingRecording { parent, start }
     212            0 :     }
     213              : 
     214            0 :     pub(crate) fn observe(self, throttled: Option<Duration>) {
     215            0 :         let elapsed = self.start.elapsed();
     216            0 :         let ex_throttled = if let Some(throttled) = throttled {
     217            0 :             elapsed.checked_sub(throttled)
     218              :         } else {
     219            0 :             Some(elapsed)
     220              :         };
     221            0 :         if let Some(ex_throttled) = ex_throttled {
     222            0 :             self.parent.observe(ex_throttled.as_secs_f64());
     223            0 :         } else {
     224            0 :             use utils::rate_limit::RateLimit;
     225            0 :             static LOGGED: Lazy<Mutex<RateLimit>> =
     226            0 :                 Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(10))));
     227            0 :             let mut rate_limit = LOGGED.lock().unwrap();
     228            0 :             rate_limit.call(|| {
     229            0 :                 warn!("error deducting time spent throttled; this message is logged at a global rate limit");
     230            0 :             });
     231            0 :         }
     232            0 :     }
     233              : }
     234              : 
     235          486 : pub(crate) static GET_VECTORED_LATENCY: Lazy<GetVectoredLatency> = Lazy::new(|| {
     236          486 :     let inner = register_histogram_vec!(
     237          486 :         "pageserver_get_vectored_seconds",
     238          486 :         "Time spent in get_vectored, excluding time spent in timeline_get_throttle.",
     239          486 :         &["task_kind"],
     240          486 :         CRITICAL_OP_BUCKETS.into(),
     241          486 :     )
     242          486 :     .expect("failed to define a metric");
     243          486 : 
     244          486 :     GetVectoredLatency {
     245        14580 :         map: EnumMap::from_array(std::array::from_fn(|task_kind_idx| {
     246        14580 :             let task_kind = <TaskKind as enum_map::Enum>::from_usize(task_kind_idx);
     247        14580 : 
     248        14580 :             if GetVectoredLatency::TRACKED_TASK_KINDS.contains(&task_kind) {
     249          972 :                 let task_kind = task_kind.into();
     250          972 :                 Some(inner.with_label_values(&[task_kind]))
     251              :             } else {
     252        13608 :                 None
     253              :             }
     254        14580 :         })),
     255          486 :     }
     256          486 : });
     257              : 
     258           24 : pub(crate) static SCAN_LATENCY: Lazy<ScanLatency> = Lazy::new(|| {
     259           24 :     let inner = register_histogram_vec!(
     260           24 :         "pageserver_scan_seconds",
     261           24 :         "Time spent in scan, excluding time spent in timeline_get_throttle.",
     262           24 :         &["task_kind"],
     263           24 :         CRITICAL_OP_BUCKETS.into(),
     264           24 :     )
     265           24 :     .expect("failed to define a metric");
     266           24 : 
     267           24 :     ScanLatency {
     268          720 :         map: EnumMap::from_array(std::array::from_fn(|task_kind_idx| {
     269          720 :             let task_kind = <TaskKind as enum_map::Enum>::from_usize(task_kind_idx);
     270          720 : 
     271          720 :             if ScanLatency::TRACKED_TASK_KINDS.contains(&task_kind) {
     272           24 :                 let task_kind = task_kind.into();
     273           24 :                 Some(inner.with_label_values(&[task_kind]))
     274              :             } else {
     275          696 :                 None
     276              :             }
     277          720 :         })),
     278           24 :     }
     279           24 : });
     280              : 
     281              : pub(crate) struct PageCacheMetricsForTaskKind {
     282              :     pub read_accesses_immutable: IntCounter,
     283              :     pub read_hits_immutable: IntCounter,
     284              : }
     285              : 
     286              : pub(crate) struct PageCacheMetrics {
     287              :     map: EnumMap<TaskKind, EnumMap<PageContentKind, PageCacheMetricsForTaskKind>>,
     288              : }
     289              : 
     290          258 : static PAGE_CACHE_READ_HITS: Lazy<IntCounterVec> = Lazy::new(|| {
     291          258 :     register_int_counter_vec!(
     292          258 :         "pageserver_page_cache_read_hits_total",
     293          258 :         "Number of read accesses to the page cache that hit",
     294          258 :         &["task_kind", "key_kind", "content_kind", "hit_kind"]
     295          258 :     )
     296          258 :     .expect("failed to define a metric")
     297          258 : });
     298              : 
     299          258 : static PAGE_CACHE_READ_ACCESSES: Lazy<IntCounterVec> = Lazy::new(|| {
     300          258 :     register_int_counter_vec!(
     301          258 :         "pageserver_page_cache_read_accesses_total",
     302          258 :         "Number of read accesses to the page cache",
     303          258 :         &["task_kind", "key_kind", "content_kind"]
     304          258 :     )
     305          258 :     .expect("failed to define a metric")
     306          258 : });
     307              : 
     308          258 : pub(crate) static PAGE_CACHE: Lazy<PageCacheMetrics> = Lazy::new(|| PageCacheMetrics {
     309         7740 :     map: EnumMap::from_array(std::array::from_fn(|task_kind| {
     310         7740 :         let task_kind = <TaskKind as enum_map::Enum>::from_usize(task_kind);
     311         7740 :         let task_kind: &'static str = task_kind.into();
     312        61920 :         EnumMap::from_array(std::array::from_fn(|content_kind| {
     313        61920 :             let content_kind = <PageContentKind as enum_map::Enum>::from_usize(content_kind);
     314        61920 :             let content_kind: &'static str = content_kind.into();
     315        61920 :             PageCacheMetricsForTaskKind {
     316        61920 :                 read_accesses_immutable: {
     317        61920 :                     PAGE_CACHE_READ_ACCESSES
     318        61920 :                         .get_metric_with_label_values(&[task_kind, "immutable", content_kind])
     319        61920 :                         .unwrap()
     320        61920 :                 },
     321        61920 : 
     322        61920 :                 read_hits_immutable: {
     323        61920 :                     PAGE_CACHE_READ_HITS
     324        61920 :                         .get_metric_with_label_values(&[task_kind, "immutable", content_kind, "-"])
     325        61920 :                         .unwrap()
     326        61920 :                 },
     327        61920 :             }
     328        61920 :         }))
     329         7740 :     })),
     330          258 : });
     331              : 
     332              : impl PageCacheMetrics {
     333      3310222 :     pub(crate) fn for_ctx(&self, ctx: &RequestContext) -> &PageCacheMetricsForTaskKind {
     334      3310222 :         &self.map[ctx.task_kind()][ctx.page_content_kind()]
     335      3310222 :     }
     336              : }
     337              : 
     338              : pub(crate) struct PageCacheSizeMetrics {
     339              :     pub max_bytes: UIntGauge,
     340              : 
     341              :     pub current_bytes_immutable: UIntGauge,
     342              : }
     343              : 
     344          258 : static PAGE_CACHE_SIZE_CURRENT_BYTES: Lazy<UIntGaugeVec> = Lazy::new(|| {
     345          258 :     register_uint_gauge_vec!(
     346          258 :         "pageserver_page_cache_size_current_bytes",
     347          258 :         "Current size of the page cache in bytes, by key kind",
     348          258 :         &["key_kind"]
     349          258 :     )
     350          258 :     .expect("failed to define a metric")
     351          258 : });
     352              : 
     353              : pub(crate) static PAGE_CACHE_SIZE: Lazy<PageCacheSizeMetrics> =
     354          258 :     Lazy::new(|| PageCacheSizeMetrics {
     355          258 :         max_bytes: {
     356          258 :             register_uint_gauge!(
     357          258 :                 "pageserver_page_cache_size_max_bytes",
     358          258 :                 "Maximum size of the page cache in bytes"
     359          258 :             )
     360          258 :             .expect("failed to define a metric")
     361          258 :         },
     362          258 :         current_bytes_immutable: {
     363          258 :             PAGE_CACHE_SIZE_CURRENT_BYTES
     364          258 :                 .get_metric_with_label_values(&["immutable"])
     365          258 :                 .unwrap()
     366          258 :         },
     367          258 :     });
     368              : 
     369              : pub(crate) mod page_cache_eviction_metrics {
     370              :     use std::num::NonZeroUsize;
     371              : 
     372              :     use metrics::{register_int_counter_vec, IntCounter, IntCounterVec};
     373              :     use once_cell::sync::Lazy;
     374              : 
     375              :     #[derive(Clone, Copy)]
     376              :     pub(crate) enum Outcome {
     377              :         FoundSlotUnused { iters: NonZeroUsize },
     378              :         FoundSlotEvicted { iters: NonZeroUsize },
     379              :         ItersExceeded { iters: NonZeroUsize },
     380              :     }
     381              : 
     382          258 :     static ITERS_TOTAL_VEC: Lazy<IntCounterVec> = Lazy::new(|| {
     383          258 :         register_int_counter_vec!(
     384          258 :             "pageserver_page_cache_find_victim_iters_total",
     385          258 :             "Counter for the number of iterations in the find_victim loop",
     386          258 :             &["outcome"],
     387          258 :         )
     388          258 :         .expect("failed to define a metric")
     389          258 :     });
     390              : 
     391          258 :     static CALLS_VEC: Lazy<IntCounterVec> = Lazy::new(|| {
     392          258 :         register_int_counter_vec!(
     393          258 :             "pageserver_page_cache_find_victim_calls",
     394          258 :             "Incremented at the end of each find_victim() call.\
     395          258 :              Filter by outcome to get e.g., eviction rate.",
     396          258 :             &["outcome"]
     397          258 :         )
     398          258 :         .unwrap()
     399          258 :     });
     400              : 
     401        96463 :     pub(crate) fn observe(outcome: Outcome) {
     402              :         macro_rules! dry {
     403              :             ($label:literal, $iters:expr) => {{
     404              :                 static LABEL: &'static str = $label;
     405              :                 static ITERS_TOTAL: Lazy<IntCounter> =
     406          318 :                     Lazy::new(|| ITERS_TOTAL_VEC.with_label_values(&[LABEL]));
     407              :                 static CALLS: Lazy<IntCounter> =
     408          318 :                     Lazy::new(|| CALLS_VEC.with_label_values(&[LABEL]));
     409              :                 ITERS_TOTAL.inc_by(($iters.get()) as u64);
     410              :                 CALLS.inc();
     411              :             }};
     412              :         }
     413        96463 :         match outcome {
     414         4440 :             Outcome::FoundSlotUnused { iters } => dry!("found_empty", iters),
     415        92023 :             Outcome::FoundSlotEvicted { iters } => {
     416        92023 :                 dry!("found_evicted", iters)
     417              :             }
     418            0 :             Outcome::ItersExceeded { iters } => {
     419            0 :                 dry!("err_iters_exceeded", iters);
     420            0 :                 super::page_cache_errors_inc(super::PageCacheErrorKind::EvictIterLimit);
     421            0 :             }
     422              :         }
     423        96463 :     }
     424              : }
     425              : 
     426            0 : static PAGE_CACHE_ERRORS: Lazy<IntCounterVec> = Lazy::new(|| {
     427            0 :     register_int_counter_vec!(
     428            0 :         "page_cache_errors_total",
     429            0 :         "Number of timeouts while acquiring a pinned slot in the page cache",
     430            0 :         &["error_kind"]
     431            0 :     )
     432            0 :     .expect("failed to define a metric")
     433            0 : });
     434              : 
     435            0 : #[derive(IntoStaticStr)]
     436              : #[strum(serialize_all = "kebab_case")]
     437              : pub(crate) enum PageCacheErrorKind {
     438              :     AcquirePinnedSlotTimeout,
     439              :     EvictIterLimit,
     440              : }
     441              : 
     442            0 : pub(crate) fn page_cache_errors_inc(error_kind: PageCacheErrorKind) {
     443            0 :     PAGE_CACHE_ERRORS
     444            0 :         .get_metric_with_label_values(&[error_kind.into()])
     445            0 :         .unwrap()
     446            0 :         .inc();
     447            0 : }
     448              : 
     449           54 : pub(crate) static WAIT_LSN_TIME: Lazy<Histogram> = Lazy::new(|| {
     450           54 :     register_histogram!(
     451           54 :         "pageserver_wait_lsn_seconds",
     452           54 :         "Time spent waiting for WAL to arrive",
     453           54 :         CRITICAL_OP_BUCKETS.into(),
     454           54 :     )
     455           54 :     .expect("failed to define a metric")
     456           54 : });
     457              : 
     458          510 : static LAST_RECORD_LSN: Lazy<IntGaugeVec> = Lazy::new(|| {
     459          510 :     register_int_gauge_vec!(
     460          510 :         "pageserver_last_record_lsn",
     461          510 :         "Last record LSN grouped by timeline",
     462          510 :         &["tenant_id", "shard_id", "timeline_id"]
     463          510 :     )
     464          510 :     .expect("failed to define a metric")
     465          510 : });
     466              : 
     467          510 : static PITR_HISTORY_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     468          510 :     register_uint_gauge_vec!(
     469          510 :         "pageserver_pitr_history_size",
     470          510 :         "Data written since PITR cutoff on this timeline",
     471          510 :         &["tenant_id", "shard_id", "timeline_id"]
     472          510 :     )
     473          510 :     .expect("failed to define a metric")
     474          510 : });
     475              : 
     476         5064 : #[derive(strum_macros::EnumString, strum_macros::Display, strum_macros::IntoStaticStr)]
     477              : #[strum(serialize_all = "kebab_case")]
     478              : pub(crate) enum MetricLayerKind {
     479              :     Delta,
     480              :     Image,
     481              : }
     482              : 
     483          510 : static TIMELINE_LAYER_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     484          510 :     register_uint_gauge_vec!(
     485          510 :         "pageserver_layer_bytes",
     486          510 :         "Sum of layer physical sizes in bytes",
     487          510 :         &["tenant_id", "shard_id", "timeline_id", "kind"]
     488          510 :     )
     489          510 :     .expect("failed to define a metric")
     490          510 : });
     491              : 
     492          510 : static TIMELINE_LAYER_COUNT: Lazy<UIntGaugeVec> = Lazy::new(|| {
     493          510 :     register_uint_gauge_vec!(
     494          510 :         "pageserver_layer_count",
     495          510 :         "Number of layers that exist",
     496          510 :         &["tenant_id", "shard_id", "timeline_id", "kind"]
     497          510 :     )
     498          510 :     .expect("failed to define a metric")
     499          510 : });
     500              : 
     501          510 : static TIMELINE_ARCHIVE_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     502          510 :     register_uint_gauge_vec!(
     503          510 :         "pageserver_archive_size",
     504          510 :         "Timeline's logical size if it is considered eligible for archival (outside PITR window), else zero",
     505          510 :         &["tenant_id", "shard_id", "timeline_id"]
     506          510 :     )
     507          510 :     .expect("failed to define a metric")
     508          510 : });
     509              : 
     510          510 : static STANDBY_HORIZON: Lazy<IntGaugeVec> = Lazy::new(|| {
     511          510 :     register_int_gauge_vec!(
     512          510 :         "pageserver_standby_horizon",
     513          510 :         "Standby apply LSN for which GC is hold off, by timeline.",
     514          510 :         &["tenant_id", "shard_id", "timeline_id"]
     515          510 :     )
     516          510 :     .expect("failed to define a metric")
     517          510 : });
     518              : 
     519          510 : static RESIDENT_PHYSICAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     520          510 :     register_uint_gauge_vec!(
     521          510 :         "pageserver_resident_physical_size",
     522          510 :         "The size of the layer files present in the pageserver's filesystem, for attached locations.",
     523          510 :         &["tenant_id", "shard_id", "timeline_id"]
     524          510 :     )
     525          510 :     .expect("failed to define a metric")
     526          510 : });
     527              : 
     528          510 : static VISIBLE_PHYSICAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     529          510 :     register_uint_gauge_vec!(
     530          510 :         "pageserver_visible_physical_size",
     531          510 :         "The size of the layer files present in the pageserver's filesystem.",
     532          510 :         &["tenant_id", "shard_id", "timeline_id"]
     533          510 :     )
     534          510 :     .expect("failed to define a metric")
     535          510 : });
     536              : 
     537          498 : pub(crate) static RESIDENT_PHYSICAL_SIZE_GLOBAL: Lazy<UIntGauge> = Lazy::new(|| {
     538          498 :     register_uint_gauge!(
     539          498 :         "pageserver_resident_physical_size_global",
     540          498 :         "Like `pageserver_resident_physical_size`, but without tenant/timeline dimensions."
     541          498 :     )
     542          498 :     .expect("failed to define a metric")
     543          498 : });
     544              : 
     545          510 : static REMOTE_PHYSICAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     546          510 :     register_uint_gauge_vec!(
     547          510 :         "pageserver_remote_physical_size",
     548          510 :         "The size of the layer files present in the remote storage that are listed in the remote index_part.json.",
     549          510 :         // Corollary: If any files are missing from the index part, they won't be included here.
     550          510 :         &["tenant_id", "shard_id", "timeline_id"]
     551          510 :     )
     552          510 :     .expect("failed to define a metric")
     553          510 : });
     554              : 
     555          510 : static REMOTE_PHYSICAL_SIZE_GLOBAL: Lazy<UIntGauge> = Lazy::new(|| {
     556          510 :     register_uint_gauge!(
     557          510 :         "pageserver_remote_physical_size_global",
     558          510 :         "Like `pageserver_remote_physical_size`, but without tenant/timeline dimensions."
     559          510 :     )
     560          510 :     .expect("failed to define a metric")
     561          510 : });
     562              : 
     563           12 : pub(crate) static REMOTE_ONDEMAND_DOWNLOADED_LAYERS: Lazy<IntCounter> = Lazy::new(|| {
     564           12 :     register_int_counter!(
     565           12 :         "pageserver_remote_ondemand_downloaded_layers_total",
     566           12 :         "Total on-demand downloaded layers"
     567           12 :     )
     568           12 :     .unwrap()
     569           12 : });
     570              : 
     571           12 : pub(crate) static REMOTE_ONDEMAND_DOWNLOADED_BYTES: Lazy<IntCounter> = Lazy::new(|| {
     572           12 :     register_int_counter!(
     573           12 :         "pageserver_remote_ondemand_downloaded_bytes_total",
     574           12 :         "Total bytes of layers on-demand downloaded",
     575           12 :     )
     576           12 :     .unwrap()
     577           12 : });
     578              : 
     579          510 : static CURRENT_LOGICAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
     580          510 :     register_uint_gauge_vec!(
     581          510 :         "pageserver_current_logical_size",
     582          510 :         "Current logical size grouped by timeline",
     583          510 :         &["tenant_id", "shard_id", "timeline_id"]
     584          510 :     )
     585          510 :     .expect("failed to define current logical size metric")
     586          510 : });
     587              : 
     588          510 : static AUX_FILE_SIZE: Lazy<IntGaugeVec> = Lazy::new(|| {
     589          510 :     register_int_gauge_vec!(
     590          510 :         "pageserver_aux_file_estimated_size",
     591          510 :         "The size of all aux files for a timeline in aux file v2 store.",
     592          510 :         &["tenant_id", "shard_id", "timeline_id"]
     593          510 :     )
     594          510 :     .expect("failed to define a metric")
     595          510 : });
     596              : 
     597          510 : static VALID_LSN_LEASE_COUNT: Lazy<UIntGaugeVec> = Lazy::new(|| {
     598          510 :     register_uint_gauge_vec!(
     599          510 :         "pageserver_valid_lsn_lease_count",
     600          510 :         "The number of valid leases after refreshing gc info.",
     601          510 :         &["tenant_id", "shard_id", "timeline_id"],
     602          510 :     )
     603          510 :     .expect("failed to define a metric")
     604          510 : });
     605              : 
     606            0 : pub(crate) static CIRCUIT_BREAKERS_BROKEN: Lazy<IntCounter> = Lazy::new(|| {
     607            0 :     register_int_counter!(
     608            0 :         "pageserver_circuit_breaker_broken",
     609            0 :         "How many times a circuit breaker has broken"
     610            0 :     )
     611            0 :     .expect("failed to define a metric")
     612            0 : });
     613              : 
     614            0 : pub(crate) static CIRCUIT_BREAKERS_UNBROKEN: Lazy<IntCounter> = Lazy::new(|| {
     615            0 :     register_int_counter!(
     616            0 :         "pageserver_circuit_breaker_unbroken",
     617            0 :         "How many times a circuit breaker has been un-broken (recovered)"
     618            0 :     )
     619            0 :     .expect("failed to define a metric")
     620            0 : });
     621              : 
     622          486 : pub(crate) static COMPRESSION_IMAGE_INPUT_BYTES: Lazy<IntCounter> = Lazy::new(|| {
     623          486 :     register_int_counter!(
     624          486 :         "pageserver_compression_image_in_bytes_total",
     625          486 :         "Size of data written into image layers before compression"
     626          486 :     )
     627          486 :     .expect("failed to define a metric")
     628          486 : });
     629              : 
     630          486 : pub(crate) static COMPRESSION_IMAGE_INPUT_BYTES_CONSIDERED: Lazy<IntCounter> = Lazy::new(|| {
     631          486 :     register_int_counter!(
     632          486 :         "pageserver_compression_image_in_bytes_considered",
     633          486 :         "Size of potentially compressible data written into image layers before compression"
     634          486 :     )
     635          486 :     .expect("failed to define a metric")
     636          486 : });
     637              : 
     638          486 : pub(crate) static COMPRESSION_IMAGE_INPUT_BYTES_CHOSEN: Lazy<IntCounter> = Lazy::new(|| {
     639          486 :     register_int_counter!(
     640          486 :         "pageserver_compression_image_in_bytes_chosen",
     641          486 :         "Size of data whose compressed form was written into image layers"
     642          486 :     )
     643          486 :     .expect("failed to define a metric")
     644          486 : });
     645              : 
     646          486 : pub(crate) static COMPRESSION_IMAGE_OUTPUT_BYTES: Lazy<IntCounter> = Lazy::new(|| {
     647          486 :     register_int_counter!(
     648          486 :         "pageserver_compression_image_out_bytes_total",
     649          486 :         "Size of compressed image layer written"
     650          486 :     )
     651          486 :     .expect("failed to define a metric")
     652          486 : });
     653              : 
     654              : pub(crate) mod initial_logical_size {
     655              :     use metrics::{register_int_counter, register_int_counter_vec, IntCounter, IntCounterVec};
     656              :     use once_cell::sync::Lazy;
     657              : 
     658              :     pub(crate) struct StartCalculation(IntCounterVec);
     659          510 :     pub(crate) static START_CALCULATION: Lazy<StartCalculation> = Lazy::new(|| {
     660          510 :         StartCalculation(
     661          510 :             register_int_counter_vec!(
     662          510 :                 "pageserver_initial_logical_size_start_calculation",
     663          510 :                 "Incremented each time we start an initial logical size calculation attempt. \
     664          510 :                  The `circumstances` label provides some additional details.",
     665          510 :                 &["attempt", "circumstances"]
     666          510 :             )
     667          510 :             .unwrap(),
     668          510 :         )
     669          510 :     });
     670              : 
     671              :     struct DropCalculation {
     672              :         first: IntCounter,
     673              :         retry: IntCounter,
     674              :     }
     675              : 
     676          510 :     static DROP_CALCULATION: Lazy<DropCalculation> = Lazy::new(|| {
     677          510 :         let vec = register_int_counter_vec!(
     678          510 :             "pageserver_initial_logical_size_drop_calculation",
     679          510 :             "Incremented each time we abort a started size calculation attmpt.",
     680          510 :             &["attempt"]
     681          510 :         )
     682          510 :         .unwrap();
     683          510 :         DropCalculation {
     684          510 :             first: vec.with_label_values(&["first"]),
     685          510 :             retry: vec.with_label_values(&["retry"]),
     686          510 :         }
     687          510 :     });
     688              : 
     689              :     pub(crate) struct Calculated {
     690              :         pub(crate) births: IntCounter,
     691              :         pub(crate) deaths: IntCounter,
     692              :     }
     693              : 
     694          510 :     pub(crate) static CALCULATED: Lazy<Calculated> = Lazy::new(|| Calculated {
     695          510 :         births: register_int_counter!(
     696          510 :             "pageserver_initial_logical_size_finish_calculation",
     697          510 :             "Incremented every time we finish calculation of initial logical size.\
     698          510 :              If everything is working well, this should happen at most once per Timeline object."
     699          510 :         )
     700          510 :         .unwrap(),
     701          510 :         deaths: register_int_counter!(
     702          510 :             "pageserver_initial_logical_size_drop_finished_calculation",
     703          510 :             "Incremented when we drop a finished initial logical size calculation result.\
     704          510 :              Mainly useful to turn pageserver_initial_logical_size_finish_calculation into a gauge."
     705          510 :         )
     706          510 :         .unwrap(),
     707          510 :     });
     708              : 
     709              :     pub(crate) struct OngoingCalculationGuard {
     710              :         inc_drop_calculation: Option<IntCounter>,
     711              :     }
     712              : 
     713          546 :     #[derive(strum_macros::IntoStaticStr)]
     714              :     pub(crate) enum StartCircumstances {
     715              :         EmptyInitial,
     716              :         SkippedConcurrencyLimiter,
     717              :         AfterBackgroundTasksRateLimit,
     718              :     }
     719              : 
     720              :     impl StartCalculation {
     721          546 :         pub(crate) fn first(&self, circumstances: StartCircumstances) -> OngoingCalculationGuard {
     722          546 :             let circumstances_label: &'static str = circumstances.into();
     723          546 :             self.0
     724          546 :                 .with_label_values(&["first", circumstances_label])
     725          546 :                 .inc();
     726          546 :             OngoingCalculationGuard {
     727          546 :                 inc_drop_calculation: Some(DROP_CALCULATION.first.clone()),
     728          546 :             }
     729          546 :         }
     730            0 :         pub(crate) fn retry(&self, circumstances: StartCircumstances) -> OngoingCalculationGuard {
     731            0 :             let circumstances_label: &'static str = circumstances.into();
     732            0 :             self.0
     733            0 :                 .with_label_values(&["retry", circumstances_label])
     734            0 :                 .inc();
     735            0 :             OngoingCalculationGuard {
     736            0 :                 inc_drop_calculation: Some(DROP_CALCULATION.retry.clone()),
     737            0 :             }
     738            0 :         }
     739              :     }
     740              : 
     741              :     impl Drop for OngoingCalculationGuard {
     742          546 :         fn drop(&mut self) {
     743          546 :             if let Some(counter) = self.inc_drop_calculation.take() {
     744            0 :                 counter.inc();
     745          546 :             }
     746          546 :         }
     747              :     }
     748              : 
     749              :     impl OngoingCalculationGuard {
     750          546 :         pub(crate) fn calculation_result_saved(mut self) -> FinishedCalculationGuard {
     751          546 :             drop(self.inc_drop_calculation.take());
     752          546 :             CALCULATED.births.inc();
     753          546 :             FinishedCalculationGuard {
     754          546 :                 inc_on_drop: CALCULATED.deaths.clone(),
     755          546 :             }
     756          546 :         }
     757              :     }
     758              : 
     759              :     pub(crate) struct FinishedCalculationGuard {
     760              :         inc_on_drop: IntCounter,
     761              :     }
     762              : 
     763              :     impl Drop for FinishedCalculationGuard {
     764           18 :         fn drop(&mut self) {
     765           18 :             self.inc_on_drop.inc();
     766           18 :         }
     767              :     }
     768              : 
     769              :     // context: https://github.com/neondatabase/neon/issues/5963
     770              :     pub(crate) static TIMELINES_WHERE_WALRECEIVER_GOT_APPROXIMATE_SIZE: Lazy<IntCounter> =
     771            0 :         Lazy::new(|| {
     772            0 :             register_int_counter!(
     773            0 :                 "pageserver_initial_logical_size_timelines_where_walreceiver_got_approximate_size",
     774            0 :                 "Counter for the following event: walreceiver calls\
     775            0 :                  Timeline::get_current_logical_size() and it returns `Approximate` for the first time."
     776            0 :             )
     777            0 :             .unwrap()
     778            0 :         });
     779              : }
     780              : 
     781            0 : static DIRECTORY_ENTRIES_COUNT: Lazy<UIntGaugeVec> = Lazy::new(|| {
     782            0 :     register_uint_gauge_vec!(
     783            0 :         "pageserver_directory_entries_count",
     784            0 :         "Sum of the entries in pageserver-stored directory listings",
     785            0 :         &["tenant_id", "shard_id", "timeline_id"]
     786            0 :     )
     787            0 :     .expect("failed to define a metric")
     788            0 : });
     789              : 
     790          516 : pub(crate) static TENANT_STATE_METRIC: Lazy<UIntGaugeVec> = Lazy::new(|| {
     791          516 :     register_uint_gauge_vec!(
     792          516 :         "pageserver_tenant_states_count",
     793          516 :         "Count of tenants per state",
     794          516 :         &["state"]
     795          516 :     )
     796          516 :     .expect("Failed to register pageserver_tenant_states_count metric")
     797          516 : });
     798              : 
     799              : /// A set of broken tenants.
     800              : ///
     801              : /// These are expected to be so rare that a set is fine. Set as in a new timeseries per each broken
     802              : /// tenant.
     803           36 : pub(crate) static BROKEN_TENANTS_SET: Lazy<UIntGaugeVec> = Lazy::new(|| {
     804           36 :     register_uint_gauge_vec!(
     805           36 :         "pageserver_broken_tenants_count",
     806           36 :         "Set of broken tenants",
     807           36 :         &["tenant_id", "shard_id"]
     808           36 :     )
     809           36 :     .expect("Failed to register pageserver_tenant_states_count metric")
     810           36 : });
     811              : 
     812           18 : pub(crate) static TENANT_SYNTHETIC_SIZE_METRIC: Lazy<UIntGaugeVec> = Lazy::new(|| {
     813           18 :     register_uint_gauge_vec!(
     814           18 :         "pageserver_tenant_synthetic_cached_size_bytes",
     815           18 :         "Synthetic size of each tenant in bytes",
     816           18 :         &["tenant_id"]
     817           18 :     )
     818           18 :     .expect("Failed to register pageserver_tenant_synthetic_cached_size_bytes metric")
     819           18 : });
     820              : 
     821            0 : pub(crate) static EVICTION_ITERATION_DURATION: Lazy<HistogramVec> = Lazy::new(|| {
     822            0 :     register_histogram_vec!(
     823            0 :         "pageserver_eviction_iteration_duration_seconds_global",
     824            0 :         "Time spent on a single eviction iteration",
     825            0 :         &["period_secs", "threshold_secs"],
     826            0 :         STORAGE_OP_BUCKETS.into(),
     827            0 :     )
     828            0 :     .expect("failed to define a metric")
     829            0 : });
     830              : 
     831          510 : static EVICTIONS: Lazy<IntCounterVec> = Lazy::new(|| {
     832          510 :     register_int_counter_vec!(
     833          510 :         "pageserver_evictions",
     834          510 :         "Number of layers evicted from the pageserver",
     835          510 :         &["tenant_id", "shard_id", "timeline_id"]
     836          510 :     )
     837          510 :     .expect("failed to define a metric")
     838          510 : });
     839              : 
     840          510 : static EVICTIONS_WITH_LOW_RESIDENCE_DURATION: Lazy<IntCounterVec> = Lazy::new(|| {
     841          510 :     register_int_counter_vec!(
     842          510 :         "pageserver_evictions_with_low_residence_duration",
     843          510 :         "If a layer is evicted that was resident for less than `low_threshold`, it is counted to this counter. \
     844          510 :          Residence duration is determined using the `residence_duration_data_source`.",
     845          510 :         &["tenant_id", "shard_id", "timeline_id", "residence_duration_data_source", "low_threshold_secs"]
     846          510 :     )
     847          510 :     .expect("failed to define a metric")
     848          510 : });
     849              : 
     850            0 : pub(crate) static UNEXPECTED_ONDEMAND_DOWNLOADS: Lazy<IntCounter> = Lazy::new(|| {
     851            0 :     register_int_counter!(
     852            0 :         "pageserver_unexpected_ondemand_downloads_count",
     853            0 :         "Number of unexpected on-demand downloads. \
     854            0 :          We log more context for each increment, so, forgo any labels in this metric.",
     855            0 :     )
     856            0 :     .expect("failed to define a metric")
     857            0 : });
     858              : 
     859              : /// How long did we take to start up?  Broken down by labels to describe
     860              : /// different phases of startup.
     861            0 : pub static STARTUP_DURATION: Lazy<GaugeVec> = Lazy::new(|| {
     862            0 :     register_gauge_vec!(
     863            0 :         "pageserver_startup_duration_seconds",
     864            0 :         "Time taken by phases of pageserver startup, in seconds",
     865            0 :         &["phase"]
     866            0 :     )
     867            0 :     .expect("Failed to register pageserver_startup_duration_seconds metric")
     868            0 : });
     869              : 
     870            0 : pub static STARTUP_IS_LOADING: Lazy<UIntGauge> = Lazy::new(|| {
     871            0 :     register_uint_gauge!(
     872            0 :         "pageserver_startup_is_loading",
     873            0 :         "1 while in initial startup load of tenants, 0 at other times"
     874            0 :     )
     875            0 :     .expect("Failed to register pageserver_startup_is_loading")
     876            0 : });
     877              : 
     878          498 : pub(crate) static TIMELINE_EPHEMERAL_BYTES: Lazy<UIntGauge> = Lazy::new(|| {
     879          498 :     register_uint_gauge!(
     880          498 :         "pageserver_timeline_ephemeral_bytes",
     881          498 :         "Total number of bytes in ephemeral layers, summed for all timelines.  Approximate, lazily updated."
     882          498 :     )
     883          498 :     .expect("Failed to register metric")
     884          498 : });
     885              : 
     886              : /// Metrics related to the lifecycle of a [`crate::tenant::Tenant`] object: things
     887              : /// like how long it took to load.
     888              : ///
     889              : /// Note that these are process-global metrics, _not_ per-tenant metrics.  Per-tenant
     890              : /// metrics are rather expensive, and usually fine grained stuff makes more sense
     891              : /// at a timeline level than tenant level.
     892              : pub(crate) struct TenantMetrics {
     893              :     /// How long did tenants take to go from construction to active state?
     894              :     pub(crate) activation: Histogram,
     895              :     pub(crate) preload: Histogram,
     896              :     pub(crate) attach: Histogram,
     897              : 
     898              :     /// How many tenants are included in the initial startup of the pagesrever?
     899              :     pub(crate) startup_scheduled: IntCounter,
     900              :     pub(crate) startup_complete: IntCounter,
     901              : }
     902              : 
     903            0 : pub(crate) static TENANT: Lazy<TenantMetrics> = Lazy::new(|| {
     904            0 :     TenantMetrics {
     905            0 :     activation: register_histogram!(
     906            0 :         "pageserver_tenant_activation_seconds",
     907            0 :         "Time taken by tenants to activate, in seconds",
     908            0 :         CRITICAL_OP_BUCKETS.into()
     909            0 :     )
     910            0 :     .expect("Failed to register metric"),
     911            0 :     preload: register_histogram!(
     912            0 :         "pageserver_tenant_preload_seconds",
     913            0 :         "Time taken by tenants to load remote metadata on startup/attach, in seconds",
     914            0 :         CRITICAL_OP_BUCKETS.into()
     915            0 :     )
     916            0 :     .expect("Failed to register metric"),
     917            0 :     attach: register_histogram!(
     918            0 :         "pageserver_tenant_attach_seconds",
     919            0 :         "Time taken by tenants to intialize, after remote metadata is already loaded",
     920            0 :         CRITICAL_OP_BUCKETS.into()
     921            0 :     )
     922            0 :     .expect("Failed to register metric"),
     923            0 :     startup_scheduled: register_int_counter!(
     924            0 :         "pageserver_tenant_startup_scheduled",
     925            0 :         "Number of tenants included in pageserver startup (doesn't count tenants attached later)"
     926            0 :     ).expect("Failed to register metric"),
     927            0 :     startup_complete: register_int_counter!(
     928            0 :         "pageserver_tenant_startup_complete",
     929            0 :         "Number of tenants that have completed warm-up, or activated on-demand during initial startup: \
     930            0 :          should eventually reach `pageserver_tenant_startup_scheduled_total`.  Does not include broken \
     931            0 :          tenants: such cases will lead to this metric never reaching the scheduled count."
     932            0 :     ).expect("Failed to register metric"),
     933            0 : }
     934            0 : });
     935              : 
     936              : /// Each `Timeline`'s  [`EVICTIONS_WITH_LOW_RESIDENCE_DURATION`] metric.
     937              : #[derive(Debug)]
     938              : pub(crate) struct EvictionsWithLowResidenceDuration {
     939              :     data_source: &'static str,
     940              :     threshold: Duration,
     941              :     counter: Option<IntCounter>,
     942              : }
     943              : 
     944              : pub(crate) struct EvictionsWithLowResidenceDurationBuilder {
     945              :     data_source: &'static str,
     946              :     threshold: Duration,
     947              : }
     948              : 
     949              : impl EvictionsWithLowResidenceDurationBuilder {
     950         1242 :     pub fn new(data_source: &'static str, threshold: Duration) -> Self {
     951         1242 :         Self {
     952         1242 :             data_source,
     953         1242 :             threshold,
     954         1242 :         }
     955         1242 :     }
     956              : 
     957         1242 :     fn build(
     958         1242 :         &self,
     959         1242 :         tenant_id: &str,
     960         1242 :         shard_id: &str,
     961         1242 :         timeline_id: &str,
     962         1242 :     ) -> EvictionsWithLowResidenceDuration {
     963         1242 :         let counter = EVICTIONS_WITH_LOW_RESIDENCE_DURATION
     964         1242 :             .get_metric_with_label_values(&[
     965         1242 :                 tenant_id,
     966         1242 :                 shard_id,
     967         1242 :                 timeline_id,
     968         1242 :                 self.data_source,
     969         1242 :                 &EvictionsWithLowResidenceDuration::threshold_label_value(self.threshold),
     970         1242 :             ])
     971         1242 :             .unwrap();
     972         1242 :         EvictionsWithLowResidenceDuration {
     973         1242 :             data_source: self.data_source,
     974         1242 :             threshold: self.threshold,
     975         1242 :             counter: Some(counter),
     976         1242 :         }
     977         1242 :     }
     978              : }
     979              : 
     980              : impl EvictionsWithLowResidenceDuration {
     981         1266 :     fn threshold_label_value(threshold: Duration) -> String {
     982         1266 :         format!("{}", threshold.as_secs())
     983         1266 :     }
     984              : 
     985           12 :     pub fn observe(&self, observed_value: Duration) {
     986           12 :         if observed_value < self.threshold {
     987           12 :             self.counter
     988           12 :                 .as_ref()
     989           12 :                 .expect("nobody calls this function after `remove_from_vec`")
     990           12 :                 .inc();
     991           12 :         }
     992           12 :     }
     993              : 
     994           24 :     pub fn change_threshold(
     995           24 :         &mut self,
     996           24 :         tenant_id: &str,
     997           24 :         shard_id: &str,
     998           24 :         timeline_id: &str,
     999           24 :         new_threshold: Duration,
    1000           24 :     ) {
    1001           24 :         if new_threshold == self.threshold {
    1002           24 :             return;
    1003            0 :         }
    1004            0 :         let mut with_new = EvictionsWithLowResidenceDurationBuilder::new(
    1005            0 :             self.data_source,
    1006            0 :             new_threshold,
    1007            0 :         )
    1008            0 :         .build(tenant_id, shard_id, timeline_id);
    1009            0 :         std::mem::swap(self, &mut with_new);
    1010            0 :         with_new.remove(tenant_id, shard_id, timeline_id);
    1011           24 :     }
    1012              : 
    1013              :     // This could be a `Drop` impl, but, we need the `tenant_id` and `timeline_id`.
    1014           24 :     fn remove(&mut self, tenant_id: &str, shard_id: &str, timeline_id: &str) {
    1015           24 :         let Some(_counter) = self.counter.take() else {
    1016            0 :             return;
    1017              :         };
    1018              : 
    1019           24 :         let threshold = Self::threshold_label_value(self.threshold);
    1020           24 : 
    1021           24 :         let removed = EVICTIONS_WITH_LOW_RESIDENCE_DURATION.remove_label_values(&[
    1022           24 :             tenant_id,
    1023           24 :             shard_id,
    1024           24 :             timeline_id,
    1025           24 :             self.data_source,
    1026           24 :             &threshold,
    1027           24 :         ]);
    1028           24 : 
    1029           24 :         match removed {
    1030            0 :             Err(e) => {
    1031            0 :                 // this has been hit in staging as
    1032            0 :                 // <https://neondatabase.sentry.io/issues/4142396994/>, but we don't know how.
    1033            0 :                 // because we can be in the drop path already, don't risk:
    1034            0 :                 // - "double-panic => illegal instruction" or
    1035            0 :                 // - future "drop panick => abort"
    1036            0 :                 //
    1037            0 :                 // so just nag: (the error has the labels)
    1038            0 :                 tracing::warn!("failed to remove EvictionsWithLowResidenceDuration, it was already removed? {e:#?}");
    1039              :             }
    1040              :             Ok(()) => {
    1041              :                 // to help identify cases where we double-remove the same values, let's log all
    1042              :                 // deletions?
    1043           24 :                 tracing::info!("removed EvictionsWithLowResidenceDuration with {tenant_id}, {timeline_id}, {}, {threshold}", self.data_source);
    1044              :             }
    1045              :         }
    1046           24 :     }
    1047              : }
    1048              : 
    1049              : // Metrics collected on disk IO operations
    1050              : //
    1051              : // Roughly logarithmic scale.
    1052              : const STORAGE_IO_TIME_BUCKETS: &[f64] = &[
    1053              :     0.000030, // 30 usec
    1054              :     0.001000, // 1000 usec
    1055              :     0.030,    // 30 ms
    1056              :     1.000,    // 1000 ms
    1057              :     30.000,   // 30000 ms
    1058              : ];
    1059              : 
    1060              : /// VirtualFile fs operation variants.
    1061              : ///
    1062              : /// Operations:
    1063              : /// - open ([`std::fs::OpenOptions::open`])
    1064              : /// - close (dropping [`crate::virtual_file::VirtualFile`])
    1065              : /// - close-by-replace (close by replacement algorithm)
    1066              : /// - read (`read_at`)
    1067              : /// - write (`write_at`)
    1068              : /// - seek (modify internal position or file length query)
    1069              : /// - fsync ([`std::fs::File::sync_all`])
    1070              : /// - metadata ([`std::fs::File::metadata`])
    1071              : #[derive(
    1072         5400 :     Debug, Clone, Copy, strum_macros::EnumCount, strum_macros::EnumIter, strum_macros::FromRepr,
    1073              : )]
    1074              : pub(crate) enum StorageIoOperation {
    1075              :     Open,
    1076              :     OpenAfterReplace,
    1077              :     Close,
    1078              :     CloseByReplace,
    1079              :     Read,
    1080              :     Write,
    1081              :     Seek,
    1082              :     Fsync,
    1083              :     Metadata,
    1084              : }
    1085              : 
    1086              : impl StorageIoOperation {
    1087         5400 :     pub fn as_str(&self) -> &'static str {
    1088         5400 :         match self {
    1089          600 :             StorageIoOperation::Open => "open",
    1090          600 :             StorageIoOperation::OpenAfterReplace => "open-after-replace",
    1091          600 :             StorageIoOperation::Close => "close",
    1092          600 :             StorageIoOperation::CloseByReplace => "close-by-replace",
    1093          600 :             StorageIoOperation::Read => "read",
    1094          600 :             StorageIoOperation::Write => "write",
    1095          600 :             StorageIoOperation::Seek => "seek",
    1096          600 :             StorageIoOperation::Fsync => "fsync",
    1097          600 :             StorageIoOperation::Metadata => "metadata",
    1098              :         }
    1099         5400 :     }
    1100              : }
    1101              : 
    1102              : /// Tracks time taken by fs operations near VirtualFile.
    1103              : #[derive(Debug)]
    1104              : pub(crate) struct StorageIoTime {
    1105              :     metrics: [Histogram; StorageIoOperation::COUNT],
    1106              : }
    1107              : 
    1108              : impl StorageIoTime {
    1109          600 :     fn new() -> Self {
    1110          600 :         let storage_io_histogram_vec = register_histogram_vec!(
    1111          600 :             "pageserver_io_operations_seconds",
    1112          600 :             "Time spent in IO operations",
    1113          600 :             &["operation"],
    1114          600 :             STORAGE_IO_TIME_BUCKETS.into()
    1115          600 :         )
    1116          600 :         .expect("failed to define a metric");
    1117         5400 :         let metrics = std::array::from_fn(|i| {
    1118         5400 :             let op = StorageIoOperation::from_repr(i).unwrap();
    1119         5400 :             storage_io_histogram_vec
    1120         5400 :                 .get_metric_with_label_values(&[op.as_str()])
    1121         5400 :                 .unwrap()
    1122         5400 :         });
    1123          600 :         Self { metrics }
    1124          600 :     }
    1125              : 
    1126      6886070 :     pub(crate) fn get(&self, op: StorageIoOperation) -> &Histogram {
    1127      6886070 :         &self.metrics[op as usize]
    1128      6886070 :     }
    1129              : }
    1130              : 
    1131              : pub(crate) static STORAGE_IO_TIME_METRIC: Lazy<StorageIoTime> = Lazy::new(StorageIoTime::new);
    1132              : 
    1133              : const STORAGE_IO_SIZE_OPERATIONS: &[&str] = &["read", "write"];
    1134              : 
    1135              : // Needed for the https://neonprod.grafana.net/d/5uK9tHL4k/picking-tenant-for-relocation?orgId=1
    1136          588 : pub(crate) static STORAGE_IO_SIZE: Lazy<IntGaugeVec> = Lazy::new(|| {
    1137          588 :     register_int_gauge_vec!(
    1138          588 :         "pageserver_io_operations_bytes_total",
    1139          588 :         "Total amount of bytes read/written in IO operations",
    1140          588 :         &["operation", "tenant_id", "shard_id", "timeline_id"]
    1141          588 :     )
    1142          588 :     .expect("failed to define a metric")
    1143          588 : });
    1144              : 
    1145              : #[cfg(not(test))]
    1146              : pub(crate) mod virtual_file_descriptor_cache {
    1147              :     use super::*;
    1148              : 
    1149            0 :     pub(crate) static SIZE_MAX: Lazy<UIntGauge> = Lazy::new(|| {
    1150            0 :         register_uint_gauge!(
    1151            0 :             "pageserver_virtual_file_descriptor_cache_size_max",
    1152            0 :             "Maximum number of open file descriptors in the cache."
    1153            0 :         )
    1154            0 :         .unwrap()
    1155            0 :     });
    1156              : 
    1157              :     // SIZE_CURRENT: derive it like so:
    1158              :     // ```
    1159              :     // sum (pageserver_io_operations_seconds_count{operation=~"^(open|open-after-replace)$")
    1160              :     // -ignoring(operation)
    1161              :     // sum(pageserver_io_operations_seconds_count{operation=~"^(close|close-by-replace)$"}
    1162              :     // ```
    1163              : }
    1164              : 
    1165              : #[cfg(not(test))]
    1166              : pub(crate) mod virtual_file_io_engine {
    1167              :     use super::*;
    1168              : 
    1169            0 :     pub(crate) static KIND: Lazy<UIntGaugeVec> = Lazy::new(|| {
    1170            0 :         register_uint_gauge_vec!(
    1171            0 :             "pageserver_virtual_file_io_engine_kind",
    1172            0 :             "The configured io engine for VirtualFile",
    1173            0 :             &["kind"],
    1174            0 :         )
    1175            0 :         .unwrap()
    1176            0 :     });
    1177              : }
    1178              : 
    1179              : struct GlobalAndPerTimelineHistogramTimer<'a, 'c> {
    1180              :     global_metric: &'a Histogram,
    1181              : 
    1182              :     // Optional because not all op types are tracked per-timeline
    1183              :     timeline_metric: Option<&'a Histogram>,
    1184              : 
    1185              :     ctx: &'c RequestContext,
    1186              :     start: std::time::Instant,
    1187              :     op: SmgrQueryType,
    1188              : }
    1189              : 
    1190              : impl<'a, 'c> Drop for GlobalAndPerTimelineHistogramTimer<'a, 'c> {
    1191           30 :     fn drop(&mut self) {
    1192           30 :         let elapsed = self.start.elapsed();
    1193           30 :         let ex_throttled = self
    1194           30 :             .ctx
    1195           30 :             .micros_spent_throttled
    1196           30 :             .close_and_checked_sub_from(elapsed);
    1197           30 :         let ex_throttled = match ex_throttled {
    1198           30 :             Ok(res) => res,
    1199            0 :             Err(error) => {
    1200              :                 use utils::rate_limit::RateLimit;
    1201              :                 static LOGGED: Lazy<Mutex<enum_map::EnumMap<SmgrQueryType, RateLimit>>> =
    1202            0 :                     Lazy::new(|| {
    1203            0 :                         Mutex::new(enum_map::EnumMap::from_array(std::array::from_fn(|_| {
    1204            0 :                             RateLimit::new(Duration::from_secs(10))
    1205            0 :                         })))
    1206            0 :                     });
    1207            0 :                 let mut guard = LOGGED.lock().unwrap();
    1208            0 :                 let rate_limit = &mut guard[self.op];
    1209            0 :                 rate_limit.call(|| {
    1210            0 :                     warn!(op=?self.op, error, "error deducting time spent throttled; this message is logged at a global rate limit");
    1211            0 :                 });
    1212            0 :                 elapsed
    1213              :             }
    1214              :         };
    1215           30 :         self.global_metric.observe(ex_throttled.as_secs_f64());
    1216           30 :         if let Some(timeline_metric) = self.timeline_metric {
    1217            6 :             timeline_metric.observe(ex_throttled.as_secs_f64());
    1218           24 :         }
    1219           30 :     }
    1220              : }
    1221              : 
    1222              : #[derive(
    1223              :     Debug,
    1224              :     Clone,
    1225              :     Copy,
    1226         7686 :     IntoStaticStr,
    1227              :     strum_macros::EnumCount,
    1228           72 :     strum_macros::EnumIter,
    1229         6360 :     strum_macros::FromRepr,
    1230              :     enum_map::Enum,
    1231              : )]
    1232              : #[strum(serialize_all = "snake_case")]
    1233              : pub enum SmgrQueryType {
    1234              :     GetRelExists,
    1235              :     GetRelSize,
    1236              :     GetPageAtLsn,
    1237              :     GetDbSize,
    1238              :     GetSlruSegment,
    1239              : }
    1240              : 
    1241              : #[derive(Debug)]
    1242              : pub(crate) struct SmgrQueryTimePerTimeline {
    1243              :     global_metrics: [Histogram; SmgrQueryType::COUNT],
    1244              :     per_timeline_getpage: Histogram,
    1245              : }
    1246              : 
    1247          516 : static SMGR_QUERY_TIME_PER_TENANT_TIMELINE: Lazy<HistogramVec> = Lazy::new(|| {
    1248          516 :     register_histogram_vec!(
    1249          516 :         "pageserver_smgr_query_seconds",
    1250          516 :         "Time spent on smgr query handling, aggegated by query type and tenant/timeline.",
    1251          516 :         &["smgr_query_type", "tenant_id", "shard_id", "timeline_id"],
    1252          516 :         CRITICAL_OP_BUCKETS.into(),
    1253          516 :     )
    1254          516 :     .expect("failed to define a metric")
    1255          516 : });
    1256              : 
    1257          516 : static SMGR_QUERY_TIME_GLOBAL_BUCKETS: Lazy<Vec<f64>> = Lazy::new(|| {
    1258          516 :     [
    1259          516 :         1,
    1260          516 :         10,
    1261          516 :         20,
    1262          516 :         40,
    1263          516 :         60,
    1264          516 :         80,
    1265          516 :         100,
    1266          516 :         200,
    1267          516 :         300,
    1268          516 :         400,
    1269          516 :         500,
    1270          516 :         600,
    1271          516 :         700,
    1272          516 :         800,
    1273          516 :         900,
    1274          516 :         1_000, // 1ms
    1275          516 :         2_000,
    1276          516 :         4_000,
    1277          516 :         6_000,
    1278          516 :         8_000,
    1279          516 :         10_000, // 10ms
    1280          516 :         20_000,
    1281          516 :         40_000,
    1282          516 :         60_000,
    1283          516 :         80_000,
    1284          516 :         100_000,
    1285          516 :         200_000,
    1286          516 :         400_000,
    1287          516 :         600_000,
    1288          516 :         800_000,
    1289          516 :         1_000_000, // 1s
    1290          516 :         2_000_000,
    1291          516 :         4_000_000,
    1292          516 :         6_000_000,
    1293          516 :         8_000_000,
    1294          516 :         10_000_000, // 10s
    1295          516 :         20_000_000,
    1296          516 :         50_000_000,
    1297          516 :         100_000_000,
    1298          516 :         200_000_000,
    1299          516 :         1_000_000_000, // 1000s
    1300          516 :     ]
    1301          516 :     .into_iter()
    1302          516 :     .map(Duration::from_micros)
    1303        21156 :     .map(|d| d.as_secs_f64())
    1304          516 :     .collect()
    1305          516 : });
    1306              : 
    1307          516 : static SMGR_QUERY_TIME_GLOBAL: Lazy<HistogramVec> = Lazy::new(|| {
    1308          516 :     register_histogram_vec!(
    1309          516 :         "pageserver_smgr_query_seconds_global",
    1310          516 :         "Time spent on smgr query handling, aggregated by query type.",
    1311          516 :         &["smgr_query_type"],
    1312          516 :         SMGR_QUERY_TIME_GLOBAL_BUCKETS.clone(),
    1313          516 :     )
    1314          516 :     .expect("failed to define a metric")
    1315          516 : });
    1316              : 
    1317              : impl SmgrQueryTimePerTimeline {
    1318         1272 :     pub(crate) fn new(tenant_shard_id: &TenantShardId, timeline_id: &TimelineId) -> Self {
    1319         1272 :         let tenant_id = tenant_shard_id.tenant_id.to_string();
    1320         1272 :         let shard_slug = format!("{}", tenant_shard_id.shard_slug());
    1321         1272 :         let timeline_id = timeline_id.to_string();
    1322         6360 :         let global_metrics = std::array::from_fn(|i| {
    1323         6360 :             let op = SmgrQueryType::from_repr(i).unwrap();
    1324         6360 :             SMGR_QUERY_TIME_GLOBAL
    1325         6360 :                 .get_metric_with_label_values(&[op.into()])
    1326         6360 :                 .unwrap()
    1327         6360 :         });
    1328         1272 : 
    1329         1272 :         let per_timeline_getpage = SMGR_QUERY_TIME_PER_TENANT_TIMELINE
    1330         1272 :             .get_metric_with_label_values(&[
    1331         1272 :                 SmgrQueryType::GetPageAtLsn.into(),
    1332         1272 :                 &tenant_id,
    1333         1272 :                 &shard_slug,
    1334         1272 :                 &timeline_id,
    1335         1272 :             ])
    1336         1272 :             .unwrap();
    1337         1272 :         Self {
    1338         1272 :             global_metrics,
    1339         1272 :             per_timeline_getpage,
    1340         1272 :         }
    1341         1272 :     }
    1342           30 :     pub(crate) fn start_timer<'c: 'a, 'a>(
    1343           30 :         &'a self,
    1344           30 :         op: SmgrQueryType,
    1345           30 :         ctx: &'c RequestContext,
    1346           30 :     ) -> Option<impl Drop + '_> {
    1347           30 :         let global_metric = &self.global_metrics[op as usize];
    1348           30 :         let start = Instant::now();
    1349           30 :         match ctx.micros_spent_throttled.open() {
    1350           30 :             Ok(()) => (),
    1351            0 :             Err(error) => {
    1352            0 :                 use utils::rate_limit::RateLimit;
    1353            0 :                 static LOGGED: Lazy<Mutex<enum_map::EnumMap<SmgrQueryType, RateLimit>>> =
    1354            0 :                     Lazy::new(|| {
    1355            0 :                         Mutex::new(enum_map::EnumMap::from_array(std::array::from_fn(|_| {
    1356            0 :                             RateLimit::new(Duration::from_secs(10))
    1357            0 :                         })))
    1358            0 :                     });
    1359            0 :                 let mut guard = LOGGED.lock().unwrap();
    1360            0 :                 let rate_limit = &mut guard[op];
    1361            0 :                 rate_limit.call(|| {
    1362            0 :                     warn!(?op, error, "error opening micros_spent_throttled; this message is logged at a global rate limit");
    1363            0 :                 });
    1364            0 :             }
    1365              :         }
    1366              : 
    1367           30 :         let timeline_metric = if matches!(op, SmgrQueryType::GetPageAtLsn) {
    1368            6 :             Some(&self.per_timeline_getpage)
    1369              :         } else {
    1370           24 :             None
    1371              :         };
    1372              : 
    1373           30 :         Some(GlobalAndPerTimelineHistogramTimer {
    1374           30 :             global_metric,
    1375           30 :             timeline_metric,
    1376           30 :             ctx,
    1377           30 :             start,
    1378           30 :             op,
    1379           30 :         })
    1380           30 :     }
    1381              : }
    1382              : 
    1383              : #[cfg(test)]
    1384              : mod smgr_query_time_tests {
    1385              :     use pageserver_api::shard::TenantShardId;
    1386              :     use strum::IntoEnumIterator;
    1387              :     use utils::id::{TenantId, TimelineId};
    1388              : 
    1389              :     use crate::{
    1390              :         context::{DownloadBehavior, RequestContext},
    1391              :         task_mgr::TaskKind,
    1392              :     };
    1393              : 
    1394              :     // Regression test, we used hard-coded string constants before using an enum.
    1395              :     #[test]
    1396            6 :     fn op_label_name() {
    1397              :         use super::SmgrQueryType::*;
    1398            6 :         let expect: [(super::SmgrQueryType, &'static str); 5] = [
    1399            6 :             (GetRelExists, "get_rel_exists"),
    1400            6 :             (GetRelSize, "get_rel_size"),
    1401            6 :             (GetPageAtLsn, "get_page_at_lsn"),
    1402            6 :             (GetDbSize, "get_db_size"),
    1403            6 :             (GetSlruSegment, "get_slru_segment"),
    1404            6 :         ];
    1405           36 :         for (op, expect) in expect {
    1406           30 :             let actual: &'static str = op.into();
    1407           30 :             assert_eq!(actual, expect);
    1408              :         }
    1409            6 :     }
    1410              : 
    1411              :     #[test]
    1412            6 :     fn basic() {
    1413            6 :         let ops: Vec<_> = super::SmgrQueryType::iter().collect();
    1414              : 
    1415           36 :         for op in &ops {
    1416           30 :             let tenant_id = TenantId::generate();
    1417           30 :             let timeline_id = TimelineId::generate();
    1418           30 :             let metrics = super::SmgrQueryTimePerTimeline::new(
    1419           30 :                 &TenantShardId::unsharded(tenant_id),
    1420           30 :                 &timeline_id,
    1421           30 :             );
    1422           30 : 
    1423           60 :             let get_counts = || {
    1424           60 :                 let global: u64 = ops
    1425           60 :                     .iter()
    1426          300 :                     .map(|op| metrics.global_metrics[*op as usize].get_sample_count())
    1427           60 :                     .sum();
    1428           60 :                 (global, metrics.per_timeline_getpage.get_sample_count())
    1429           60 :             };
    1430              : 
    1431           30 :             let (pre_global, pre_per_tenant_timeline) = get_counts();
    1432           30 :             assert_eq!(pre_per_tenant_timeline, 0);
    1433              : 
    1434           30 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Download);
    1435           30 :             let timer = metrics.start_timer(*op, &ctx);
    1436           30 :             drop(timer);
    1437           30 : 
    1438           30 :             let (post_global, post_per_tenant_timeline) = get_counts();
    1439           30 :             if matches!(op, super::SmgrQueryType::GetPageAtLsn) {
    1440              :                 // getpage ops are tracked per-timeline, others aren't
    1441            6 :                 assert_eq!(post_per_tenant_timeline, 1);
    1442              :             } else {
    1443           24 :                 assert_eq!(post_per_tenant_timeline, 0);
    1444              :             }
    1445           30 :             assert!(post_global > pre_global);
    1446              :         }
    1447            6 :     }
    1448              : }
    1449              : 
    1450              : // keep in sync with control plane Go code so that we can validate
    1451              : // compute's basebackup_ms metric with our perspective in the context of SLI/SLO.
    1452            0 : static COMPUTE_STARTUP_BUCKETS: Lazy<[f64; 28]> = Lazy::new(|| {
    1453            0 :     // Go code uses milliseconds. Variable is called `computeStartupBuckets`
    1454            0 :     [
    1455            0 :         5, 10, 20, 30, 50, 70, 100, 120, 150, 200, 250, 300, 350, 400, 450, 500, 600, 800, 1000,
    1456            0 :         1500, 2000, 2500, 3000, 5000, 10000, 20000, 40000, 60000,
    1457            0 :     ]
    1458            0 :     .map(|ms| (ms as f64) / 1000.0)
    1459            0 : });
    1460              : 
    1461              : pub(crate) struct BasebackupQueryTime {
    1462              :     ok: Histogram,
    1463              :     error: Histogram,
    1464              : }
    1465              : 
    1466            0 : pub(crate) static BASEBACKUP_QUERY_TIME: Lazy<BasebackupQueryTime> = Lazy::new(|| {
    1467            0 :     let vec = register_histogram_vec!(
    1468            0 :         "pageserver_basebackup_query_seconds",
    1469            0 :         "Histogram of basebackup queries durations, by result type",
    1470            0 :         &["result"],
    1471            0 :         COMPUTE_STARTUP_BUCKETS.to_vec(),
    1472            0 :     )
    1473            0 :     .expect("failed to define a metric");
    1474            0 :     BasebackupQueryTime {
    1475            0 :         ok: vec.get_metric_with_label_values(&["ok"]).unwrap(),
    1476            0 :         error: vec.get_metric_with_label_values(&["error"]).unwrap(),
    1477            0 :     }
    1478            0 : });
    1479              : 
    1480              : pub(crate) struct BasebackupQueryTimeOngoingRecording<'a, 'c> {
    1481              :     parent: &'a BasebackupQueryTime,
    1482              :     ctx: &'c RequestContext,
    1483              :     start: std::time::Instant,
    1484              : }
    1485              : 
    1486              : impl BasebackupQueryTime {
    1487            0 :     pub(crate) fn start_recording<'c: 'a, 'a>(
    1488            0 :         &'a self,
    1489            0 :         ctx: &'c RequestContext,
    1490            0 :     ) -> BasebackupQueryTimeOngoingRecording<'_, '_> {
    1491            0 :         let start = Instant::now();
    1492            0 :         match ctx.micros_spent_throttled.open() {
    1493            0 :             Ok(()) => (),
    1494            0 :             Err(error) => {
    1495            0 :                 use utils::rate_limit::RateLimit;
    1496            0 :                 static LOGGED: Lazy<Mutex<RateLimit>> =
    1497            0 :                     Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(10))));
    1498            0 :                 let mut rate_limit = LOGGED.lock().unwrap();
    1499            0 :                 rate_limit.call(|| {
    1500            0 :                     warn!(error, "error opening micros_spent_throttled; this message is logged at a global rate limit");
    1501            0 :                 });
    1502            0 :             }
    1503              :         }
    1504            0 :         BasebackupQueryTimeOngoingRecording {
    1505            0 :             parent: self,
    1506            0 :             ctx,
    1507            0 :             start,
    1508            0 :         }
    1509            0 :     }
    1510              : }
    1511              : 
    1512              : impl<'a, 'c> BasebackupQueryTimeOngoingRecording<'a, 'c> {
    1513            0 :     pub(crate) fn observe<T, E>(self, res: &Result<T, E>) {
    1514            0 :         let elapsed = self.start.elapsed();
    1515            0 :         let ex_throttled = self
    1516            0 :             .ctx
    1517            0 :             .micros_spent_throttled
    1518            0 :             .close_and_checked_sub_from(elapsed);
    1519            0 :         let ex_throttled = match ex_throttled {
    1520            0 :             Ok(ex_throttled) => ex_throttled,
    1521            0 :             Err(error) => {
    1522              :                 use utils::rate_limit::RateLimit;
    1523              :                 static LOGGED: Lazy<Mutex<RateLimit>> =
    1524            0 :                     Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(10))));
    1525            0 :                 let mut rate_limit = LOGGED.lock().unwrap();
    1526            0 :                 rate_limit.call(|| {
    1527            0 :                     warn!(error, "error deducting time spent throttled; this message is logged at a global rate limit");
    1528            0 :                 });
    1529            0 :                 elapsed
    1530              :             }
    1531              :         };
    1532            0 :         let metric = if res.is_ok() {
    1533            0 :             &self.parent.ok
    1534              :         } else {
    1535            0 :             &self.parent.error
    1536              :         };
    1537            0 :         metric.observe(ex_throttled.as_secs_f64());
    1538            0 :     }
    1539              : }
    1540              : 
    1541            0 : pub(crate) static LIVE_CONNECTIONS: Lazy<IntCounterPairVec> = Lazy::new(|| {
    1542            0 :     register_int_counter_pair_vec!(
    1543            0 :         "pageserver_live_connections_started",
    1544            0 :         "Number of network connections that we started handling",
    1545            0 :         "pageserver_live_connections_finished",
    1546            0 :         "Number of network connections that we finished handling",
    1547            0 :         &["pageserver_connection_kind"]
    1548            0 :     )
    1549            0 :     .expect("failed to define a metric")
    1550            0 : });
    1551              : 
    1552            0 : #[derive(Clone, Copy, enum_map::Enum, IntoStaticStr)]
    1553              : pub(crate) enum ComputeCommandKind {
    1554              :     PageStreamV2,
    1555              :     Basebackup,
    1556              :     Fullbackup,
    1557              :     LeaseLsn,
    1558              : }
    1559              : 
    1560              : pub(crate) struct ComputeCommandCounters {
    1561              :     map: EnumMap<ComputeCommandKind, IntCounter>,
    1562              : }
    1563              : 
    1564            0 : pub(crate) static COMPUTE_COMMANDS_COUNTERS: Lazy<ComputeCommandCounters> = Lazy::new(|| {
    1565            0 :     let inner = register_int_counter_vec!(
    1566            0 :         "pageserver_compute_commands",
    1567            0 :         "Number of compute -> pageserver commands processed",
    1568            0 :         &["command"]
    1569            0 :     )
    1570            0 :     .expect("failed to define a metric");
    1571            0 : 
    1572            0 :     ComputeCommandCounters {
    1573            0 :         map: EnumMap::from_array(std::array::from_fn(|i| {
    1574            0 :             let command = <ComputeCommandKind as enum_map::Enum>::from_usize(i);
    1575            0 :             let command_str: &'static str = command.into();
    1576            0 :             inner.with_label_values(&[command_str])
    1577            0 :         })),
    1578            0 :     }
    1579            0 : });
    1580              : 
    1581              : impl ComputeCommandCounters {
    1582            0 :     pub(crate) fn for_command(&self, command: ComputeCommandKind) -> &IntCounter {
    1583            0 :         &self.map[command]
    1584            0 :     }
    1585              : }
    1586              : 
    1587              : // remote storage metrics
    1588              : 
    1589          504 : static REMOTE_TIMELINE_CLIENT_CALLS: Lazy<IntCounterPairVec> = Lazy::new(|| {
    1590          504 :     register_int_counter_pair_vec!(
    1591          504 :         "pageserver_remote_timeline_client_calls_started",
    1592          504 :         "Number of started calls to remote timeline client.",
    1593          504 :         "pageserver_remote_timeline_client_calls_finished",
    1594          504 :         "Number of finshed calls to remote timeline client.",
    1595          504 :         &[
    1596          504 :             "tenant_id",
    1597          504 :             "shard_id",
    1598          504 :             "timeline_id",
    1599          504 :             "file_kind",
    1600          504 :             "op_kind"
    1601          504 :         ],
    1602          504 :     )
    1603          504 :     .unwrap()
    1604          504 : });
    1605              : 
    1606              : static REMOTE_TIMELINE_CLIENT_BYTES_STARTED_COUNTER: Lazy<IntCounterVec> =
    1607          492 :     Lazy::new(|| {
    1608          492 :         register_int_counter_vec!(
    1609          492 :         "pageserver_remote_timeline_client_bytes_started",
    1610          492 :         "Incremented by the number of bytes associated with a remote timeline client operation. \
    1611          492 :          The increment happens when the operation is scheduled.",
    1612          492 :         &["tenant_id", "shard_id", "timeline_id", "file_kind", "op_kind"],
    1613          492 :     )
    1614          492 :         .expect("failed to define a metric")
    1615          492 :     });
    1616              : 
    1617          492 : static REMOTE_TIMELINE_CLIENT_BYTES_FINISHED_COUNTER: Lazy<IntCounterVec> = Lazy::new(|| {
    1618          492 :     register_int_counter_vec!(
    1619          492 :         "pageserver_remote_timeline_client_bytes_finished",
    1620          492 :         "Incremented by the number of bytes associated with a remote timeline client operation. \
    1621          492 :          The increment happens when the operation finishes (regardless of success/failure/shutdown).",
    1622          492 :         &["tenant_id", "shard_id", "timeline_id", "file_kind", "op_kind"],
    1623          492 :     )
    1624          492 :     .expect("failed to define a metric")
    1625          492 : });
    1626              : 
    1627              : pub(crate) struct TenantManagerMetrics {
    1628              :     tenant_slots_attached: UIntGauge,
    1629              :     tenant_slots_secondary: UIntGauge,
    1630              :     tenant_slots_inprogress: UIntGauge,
    1631              :     pub(crate) tenant_slot_writes: IntCounter,
    1632              :     pub(crate) unexpected_errors: IntCounter,
    1633              : }
    1634              : 
    1635              : impl TenantManagerMetrics {
    1636              :     /// Helpers for tracking slots.  Note that these do not track the lifetime of TenantSlot objects
    1637              :     /// exactly: they track the lifetime of the slots _in the tenant map_.
    1638            6 :     pub(crate) fn slot_inserted(&self, slot: &TenantSlot) {
    1639            6 :         match slot {
    1640            0 :             TenantSlot::Attached(_) => {
    1641            0 :                 self.tenant_slots_attached.inc();
    1642            0 :             }
    1643            0 :             TenantSlot::Secondary(_) => {
    1644            0 :                 self.tenant_slots_secondary.inc();
    1645            0 :             }
    1646            6 :             TenantSlot::InProgress(_) => {
    1647            6 :                 self.tenant_slots_inprogress.inc();
    1648            6 :             }
    1649              :         }
    1650            6 :     }
    1651              : 
    1652            6 :     pub(crate) fn slot_removed(&self, slot: &TenantSlot) {
    1653            6 :         match slot {
    1654            6 :             TenantSlot::Attached(_) => {
    1655            6 :                 self.tenant_slots_attached.dec();
    1656            6 :             }
    1657            0 :             TenantSlot::Secondary(_) => {
    1658            0 :                 self.tenant_slots_secondary.dec();
    1659            0 :             }
    1660            0 :             TenantSlot::InProgress(_) => {
    1661            0 :                 self.tenant_slots_inprogress.dec();
    1662            0 :             }
    1663              :         }
    1664            6 :     }
    1665              : 
    1666              :     #[cfg(all(debug_assertions, not(test)))]
    1667            0 :     pub(crate) fn slots_total(&self) -> u64 {
    1668            0 :         self.tenant_slots_attached.get()
    1669            0 :             + self.tenant_slots_secondary.get()
    1670            0 :             + self.tenant_slots_inprogress.get()
    1671            0 :     }
    1672              : }
    1673              : 
    1674            6 : pub(crate) static TENANT_MANAGER: Lazy<TenantManagerMetrics> = Lazy::new(|| {
    1675            6 :     let tenant_slots = register_uint_gauge_vec!(
    1676            6 :         "pageserver_tenant_manager_slots",
    1677            6 :         "How many slots currently exist, including all attached, secondary and in-progress operations",
    1678            6 :         &["mode"]
    1679            6 :     )
    1680            6 :     .expect("failed to define a metric");
    1681            6 :     TenantManagerMetrics {
    1682            6 :         tenant_slots_attached: tenant_slots
    1683            6 :             .get_metric_with_label_values(&["attached"])
    1684            6 :             .unwrap(),
    1685            6 :         tenant_slots_secondary: tenant_slots
    1686            6 :             .get_metric_with_label_values(&["secondary"])
    1687            6 :             .unwrap(),
    1688            6 :         tenant_slots_inprogress: tenant_slots
    1689            6 :             .get_metric_with_label_values(&["inprogress"])
    1690            6 :             .unwrap(),
    1691            6 :         tenant_slot_writes: register_int_counter!(
    1692            6 :             "pageserver_tenant_manager_slot_writes",
    1693            6 :             "Writes to a tenant slot, including all of create/attach/detach/delete"
    1694            6 :         )
    1695            6 :         .expect("failed to define a metric"),
    1696            6 :         unexpected_errors: register_int_counter!(
    1697            6 :             "pageserver_tenant_manager_unexpected_errors_total",
    1698            6 :             "Number of unexpected conditions encountered: nonzero value indicates a non-fatal bug."
    1699            6 :         )
    1700            6 :         .expect("failed to define a metric"),
    1701            6 :     }
    1702            6 : });
    1703              : 
    1704              : pub(crate) struct DeletionQueueMetrics {
    1705              :     pub(crate) keys_submitted: IntCounter,
    1706              :     pub(crate) keys_dropped: IntCounter,
    1707              :     pub(crate) keys_executed: IntCounter,
    1708              :     pub(crate) keys_validated: IntCounter,
    1709              :     pub(crate) dropped_lsn_updates: IntCounter,
    1710              :     pub(crate) unexpected_errors: IntCounter,
    1711              :     pub(crate) remote_errors: IntCounterVec,
    1712              : }
    1713           83 : pub(crate) static DELETION_QUEUE: Lazy<DeletionQueueMetrics> = Lazy::new(|| {
    1714           83 :     DeletionQueueMetrics{
    1715           83 : 
    1716           83 :     keys_submitted: register_int_counter!(
    1717           83 :         "pageserver_deletion_queue_submitted_total",
    1718           83 :         "Number of objects submitted for deletion"
    1719           83 :     )
    1720           83 :     .expect("failed to define a metric"),
    1721           83 : 
    1722           83 :     keys_dropped: register_int_counter!(
    1723           83 :         "pageserver_deletion_queue_dropped_total",
    1724           83 :         "Number of object deletions dropped due to stale generation."
    1725           83 :     )
    1726           83 :     .expect("failed to define a metric"),
    1727           83 : 
    1728           83 :     keys_executed: register_int_counter!(
    1729           83 :         "pageserver_deletion_queue_executed_total",
    1730           83 :         "Number of objects deleted. Only includes objects that we actually deleted, sum with pageserver_deletion_queue_dropped_total for the total number of keys processed to completion"
    1731           83 :     )
    1732           83 :     .expect("failed to define a metric"),
    1733           83 : 
    1734           83 :     keys_validated: register_int_counter!(
    1735           83 :         "pageserver_deletion_queue_validated_total",
    1736           83 :         "Number of keys validated for deletion.  Sum with pageserver_deletion_queue_dropped_total for the total number of keys that have passed through the validation stage."
    1737           83 :     )
    1738           83 :     .expect("failed to define a metric"),
    1739           83 : 
    1740           83 :     dropped_lsn_updates: register_int_counter!(
    1741           83 :         "pageserver_deletion_queue_dropped_lsn_updates_total",
    1742           83 :         "Updates to remote_consistent_lsn dropped due to stale generation number."
    1743           83 :     )
    1744           83 :     .expect("failed to define a metric"),
    1745           83 :     unexpected_errors: register_int_counter!(
    1746           83 :         "pageserver_deletion_queue_unexpected_errors_total",
    1747           83 :         "Number of unexpected condiions that may stall the queue: any value above zero is unexpected."
    1748           83 :     )
    1749           83 :     .expect("failed to define a metric"),
    1750           83 :     remote_errors: register_int_counter_vec!(
    1751           83 :         "pageserver_deletion_queue_remote_errors_total",
    1752           83 :         "Retryable remote I/O errors while executing deletions, for example 503 responses to DeleteObjects",
    1753           83 :         &["op_kind"],
    1754           83 :     )
    1755           83 :     .expect("failed to define a metric")
    1756           83 : }
    1757           83 : });
    1758              : 
    1759              : pub(crate) struct SecondaryModeMetrics {
    1760              :     pub(crate) upload_heatmap: IntCounter,
    1761              :     pub(crate) upload_heatmap_errors: IntCounter,
    1762              :     pub(crate) upload_heatmap_duration: Histogram,
    1763              :     pub(crate) download_heatmap: IntCounter,
    1764              :     pub(crate) download_layer: IntCounter,
    1765              : }
    1766            0 : pub(crate) static SECONDARY_MODE: Lazy<SecondaryModeMetrics> = Lazy::new(|| {
    1767            0 :     SecondaryModeMetrics {
    1768            0 :     upload_heatmap: register_int_counter!(
    1769            0 :         "pageserver_secondary_upload_heatmap",
    1770            0 :         "Number of heatmaps written to remote storage by attached tenants"
    1771            0 :     )
    1772            0 :     .expect("failed to define a metric"),
    1773            0 :     upload_heatmap_errors: register_int_counter!(
    1774            0 :         "pageserver_secondary_upload_heatmap_errors",
    1775            0 :         "Failures writing heatmap to remote storage"
    1776            0 :     )
    1777            0 :     .expect("failed to define a metric"),
    1778            0 :     upload_heatmap_duration: register_histogram!(
    1779            0 :         "pageserver_secondary_upload_heatmap_duration",
    1780            0 :         "Time to build and upload a heatmap, including any waiting inside the remote storage client"
    1781            0 :     )
    1782            0 :     .expect("failed to define a metric"),
    1783            0 :     download_heatmap: register_int_counter!(
    1784            0 :         "pageserver_secondary_download_heatmap",
    1785            0 :         "Number of downloads of heatmaps by secondary mode locations, including when it hasn't changed"
    1786            0 :     )
    1787            0 :     .expect("failed to define a metric"),
    1788            0 :     download_layer: register_int_counter!(
    1789            0 :         "pageserver_secondary_download_layer",
    1790            0 :         "Number of downloads of layers by secondary mode locations"
    1791            0 :     )
    1792            0 :     .expect("failed to define a metric"),
    1793            0 : }
    1794            0 : });
    1795              : 
    1796            0 : pub(crate) static SECONDARY_RESIDENT_PHYSICAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
    1797            0 :     register_uint_gauge_vec!(
    1798            0 :         "pageserver_secondary_resident_physical_size",
    1799            0 :         "The size of the layer files present in the pageserver's filesystem, for secondary locations.",
    1800            0 :         &["tenant_id", "shard_id"]
    1801            0 :     )
    1802            0 :     .expect("failed to define a metric")
    1803            0 : });
    1804              : 
    1805            0 : pub(crate) static NODE_UTILIZATION_SCORE: Lazy<UIntGauge> = Lazy::new(|| {
    1806            0 :     register_uint_gauge!(
    1807            0 :         "pageserver_utilization_score",
    1808            0 :         "The utilization score we report to the storage controller for scheduling, where 0 is empty, 1000000 is full, and anything above is considered overloaded",
    1809            0 :     )
    1810            0 :     .expect("failed to define a metric")
    1811            0 : });
    1812              : 
    1813            0 : pub(crate) static SECONDARY_HEATMAP_TOTAL_SIZE: Lazy<UIntGaugeVec> = Lazy::new(|| {
    1814            0 :     register_uint_gauge_vec!(
    1815            0 :         "pageserver_secondary_heatmap_total_size",
    1816            0 :         "The total size in bytes of all layers in the most recently downloaded heatmap.",
    1817            0 :         &["tenant_id", "shard_id"]
    1818            0 :     )
    1819            0 :     .expect("failed to define a metric")
    1820            0 : });
    1821              : 
    1822              : #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    1823              : pub enum RemoteOpKind {
    1824              :     Upload,
    1825              :     Download,
    1826              :     Delete,
    1827              : }
    1828              : impl RemoteOpKind {
    1829        40296 :     pub fn as_str(&self) -> &'static str {
    1830        40296 :         match self {
    1831        38035 :             Self::Upload => "upload",
    1832          156 :             Self::Download => "download",
    1833         2105 :             Self::Delete => "delete",
    1834              :         }
    1835        40296 :     }
    1836              : }
    1837              : 
    1838              : #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
    1839              : pub enum RemoteOpFileKind {
    1840              :     Layer,
    1841              :     Index,
    1842              : }
    1843              : impl RemoteOpFileKind {
    1844        40296 :     pub fn as_str(&self) -> &'static str {
    1845        40296 :         match self {
    1846        27374 :             Self::Layer => "layer",
    1847        12922 :             Self::Index => "index",
    1848              :         }
    1849        40296 :     }
    1850              : }
    1851              : 
    1852          495 : pub(crate) static REMOTE_OPERATION_TIME: Lazy<HistogramVec> = Lazy::new(|| {
    1853          495 :     register_histogram_vec!(
    1854          495 :         "pageserver_remote_operation_seconds",
    1855          495 :         "Time spent on remote storage operations. \
    1856          495 :         Grouped by tenant, timeline, operation_kind and status. \
    1857          495 :         Does not account for time spent waiting in remote timeline client's queues.",
    1858          495 :         &["file_kind", "op_kind", "status"]
    1859          495 :     )
    1860          495 :     .expect("failed to define a metric")
    1861          495 : });
    1862              : 
    1863            0 : pub(crate) static TENANT_TASK_EVENTS: Lazy<IntCounterVec> = Lazy::new(|| {
    1864            0 :     register_int_counter_vec!(
    1865            0 :         "pageserver_tenant_task_events",
    1866            0 :         "Number of task start/stop/fail events.",
    1867            0 :         &["event"],
    1868            0 :     )
    1869            0 :     .expect("Failed to register tenant_task_events metric")
    1870            0 : });
    1871              : 
    1872              : pub struct BackgroundLoopSemaphoreMetrics {
    1873              :     counters: EnumMap<BackgroundLoopKind, IntCounterPair>,
    1874              :     durations: EnumMap<BackgroundLoopKind, Counter>,
    1875              : }
    1876              : 
    1877              : pub(crate) static BACKGROUND_LOOP_SEMAPHORE: Lazy<BackgroundLoopSemaphoreMetrics> = Lazy::new(
    1878           60 :     || {
    1879           60 :         let counters = register_int_counter_pair_vec!(
    1880           60 :             "pageserver_background_loop_semaphore_wait_start_count",
    1881           60 :             "Counter for background loop concurrency-limiting semaphore acquire calls started",
    1882           60 :             "pageserver_background_loop_semaphore_wait_finish_count",
    1883           60 :             "Counter for background loop concurrency-limiting semaphore acquire calls finished",
    1884           60 :             &["task"],
    1885           60 :         )
    1886           60 :         .unwrap();
    1887           60 : 
    1888           60 :         let durations = register_counter_vec!(
    1889           60 :             "pageserver_background_loop_semaphore_wait_duration_seconds",
    1890           60 :             "Sum of wall clock time spent waiting on the background loop concurrency-limiting semaphore acquire calls",
    1891           60 :             &["task"],
    1892           60 :         )
    1893           60 :         .unwrap();
    1894           60 : 
    1895           60 :         BackgroundLoopSemaphoreMetrics {
    1896          540 :             counters: enum_map::EnumMap::from_array(std::array::from_fn(|i| {
    1897          540 :                 let kind = <BackgroundLoopKind as enum_map::Enum>::from_usize(i);
    1898          540 :                 counters.with_label_values(&[kind.into()])
    1899          540 :             })),
    1900          540 :             durations: enum_map::EnumMap::from_array(std::array::from_fn(|i| {
    1901          540 :                 let kind = <BackgroundLoopKind as enum_map::Enum>::from_usize(i);
    1902          540 :                 durations.with_label_values(&[kind.into()])
    1903          540 :             })),
    1904           60 :         }
    1905           60 :     },
    1906              : );
    1907              : 
    1908              : impl BackgroundLoopSemaphoreMetrics {
    1909         1092 :     pub(crate) fn measure_acquisition(&self, task: BackgroundLoopKind) -> impl Drop + '_ {
    1910              :         struct Record<'a> {
    1911              :             metrics: &'a BackgroundLoopSemaphoreMetrics,
    1912              :             task: BackgroundLoopKind,
    1913              :             _counter_guard: metrics::IntCounterPairGuard,
    1914              :             start: Instant,
    1915              :         }
    1916              :         impl Drop for Record<'_> {
    1917         1092 :             fn drop(&mut self) {
    1918         1092 :                 let elapsed = self.start.elapsed().as_secs_f64();
    1919         1092 :                 self.metrics.durations[self.task].inc_by(elapsed);
    1920         1092 :             }
    1921              :         }
    1922         1092 :         Record {
    1923         1092 :             metrics: self,
    1924         1092 :             task,
    1925         1092 :             _counter_guard: self.counters[task].guard(),
    1926         1092 :             start: Instant::now(),
    1927         1092 :         }
    1928         1092 :     }
    1929              : }
    1930              : 
    1931            0 : pub(crate) static BACKGROUND_LOOP_PERIOD_OVERRUN_COUNT: Lazy<IntCounterVec> = Lazy::new(|| {
    1932            0 :     register_int_counter_vec!(
    1933            0 :         "pageserver_background_loop_period_overrun_count",
    1934            0 :         "Incremented whenever warn_when_period_overrun() logs a warning.",
    1935            0 :         &["task", "period"],
    1936            0 :     )
    1937            0 :     .expect("failed to define a metric")
    1938            0 : });
    1939              : 
    1940              : // walreceiver metrics
    1941              : 
    1942            0 : pub(crate) static WALRECEIVER_STARTED_CONNECTIONS: Lazy<IntCounter> = Lazy::new(|| {
    1943            0 :     register_int_counter!(
    1944            0 :         "pageserver_walreceiver_started_connections_total",
    1945            0 :         "Number of started walreceiver connections"
    1946            0 :     )
    1947            0 :     .expect("failed to define a metric")
    1948            0 : });
    1949              : 
    1950            0 : pub(crate) static WALRECEIVER_ACTIVE_MANAGERS: Lazy<IntGauge> = Lazy::new(|| {
    1951            0 :     register_int_gauge!(
    1952            0 :         "pageserver_walreceiver_active_managers",
    1953            0 :         "Number of active walreceiver managers"
    1954            0 :     )
    1955            0 :     .expect("failed to define a metric")
    1956            0 : });
    1957              : 
    1958            0 : pub(crate) static WALRECEIVER_SWITCHES: Lazy<IntCounterVec> = Lazy::new(|| {
    1959            0 :     register_int_counter_vec!(
    1960            0 :         "pageserver_walreceiver_switches_total",
    1961            0 :         "Number of walreceiver manager change_connection calls",
    1962            0 :         &["reason"]
    1963            0 :     )
    1964            0 :     .expect("failed to define a metric")
    1965            0 : });
    1966              : 
    1967            0 : pub(crate) static WALRECEIVER_BROKER_UPDATES: Lazy<IntCounter> = Lazy::new(|| {
    1968            0 :     register_int_counter!(
    1969            0 :         "pageserver_walreceiver_broker_updates_total",
    1970            0 :         "Number of received broker updates in walreceiver"
    1971            0 :     )
    1972            0 :     .expect("failed to define a metric")
    1973            0 : });
    1974              : 
    1975            6 : pub(crate) static WALRECEIVER_CANDIDATES_EVENTS: Lazy<IntCounterVec> = Lazy::new(|| {
    1976            6 :     register_int_counter_vec!(
    1977            6 :         "pageserver_walreceiver_candidates_events_total",
    1978            6 :         "Number of walreceiver candidate events",
    1979            6 :         &["event"]
    1980            6 :     )
    1981            6 :     .expect("failed to define a metric")
    1982            6 : });
    1983              : 
    1984              : pub(crate) static WALRECEIVER_CANDIDATES_ADDED: Lazy<IntCounter> =
    1985            0 :     Lazy::new(|| WALRECEIVER_CANDIDATES_EVENTS.with_label_values(&["add"]));
    1986              : 
    1987              : pub(crate) static WALRECEIVER_CANDIDATES_REMOVED: Lazy<IntCounter> =
    1988            6 :     Lazy::new(|| WALRECEIVER_CANDIDATES_EVENTS.with_label_values(&["remove"]));
    1989              : 
    1990              : // Metrics collected on WAL redo operations
    1991              : //
    1992              : // We collect the time spent in actual WAL redo ('redo'), and time waiting
    1993              : // for access to the postgres process ('wait') since there is only one for
    1994              : // each tenant.
    1995              : 
    1996              : /// Time buckets are small because we want to be able to measure the
    1997              : /// smallest redo processing times. These buckets allow us to measure down
    1998              : /// to 5us, which equates to 200'000 pages/sec, which equates to 1.6GB/sec.
    1999              : /// This is much better than the previous 5ms aka 200 pages/sec aka 1.6MB/sec.
    2000              : ///
    2001              : /// Values up to 1s are recorded because metrics show that we have redo
    2002              : /// durations and lock times larger than 0.250s.
    2003              : macro_rules! redo_histogram_time_buckets {
    2004              :     () => {
    2005              :         vec![
    2006              :             0.000_005, 0.000_010, 0.000_025, 0.000_050, 0.000_100, 0.000_250, 0.000_500, 0.001_000,
    2007              :             0.002_500, 0.005_000, 0.010_000, 0.025_000, 0.050_000, 0.100_000, 0.250_000, 0.500_000,
    2008              :             1.000_000,
    2009              :         ]
    2010              :     };
    2011              : }
    2012              : 
    2013              : /// While we're at it, also measure the amount of records replayed in each
    2014              : /// operation. We have a global 'total replayed' counter, but that's not
    2015              : /// as useful as 'what is the skew for how many records we replay in one
    2016              : /// operation'.
    2017              : macro_rules! redo_histogram_count_buckets {
    2018              :     () => {
    2019              :         vec![0.0, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0]
    2020              :     };
    2021              : }
    2022              : 
    2023              : macro_rules! redo_bytes_histogram_count_buckets {
    2024              :     () => {
    2025              :         // powers of (2^.5), from 2^4.5 to 2^15 (22 buckets)
    2026              :         // rounded up to the next multiple of 8 to capture any MAXALIGNed record of that size, too.
    2027              :         vec![
    2028              :             24.0, 32.0, 48.0, 64.0, 96.0, 128.0, 184.0, 256.0, 368.0, 512.0, 728.0, 1024.0, 1456.0,
    2029              :             2048.0, 2904.0, 4096.0, 5800.0, 8192.0, 11592.0, 16384.0, 23176.0, 32768.0,
    2030              :         ]
    2031              :     };
    2032              : }
    2033              : 
    2034              : pub(crate) struct WalIngestMetrics {
    2035              :     pub(crate) bytes_received: IntCounter,
    2036              :     pub(crate) records_received: IntCounter,
    2037              :     pub(crate) records_committed: IntCounter,
    2038              :     pub(crate) records_filtered: IntCounter,
    2039              : }
    2040              : 
    2041            6 : pub(crate) static WAL_INGEST: Lazy<WalIngestMetrics> = Lazy::new(|| WalIngestMetrics {
    2042            6 :     bytes_received: register_int_counter!(
    2043            6 :         "pageserver_wal_ingest_bytes_received",
    2044            6 :         "Bytes of WAL ingested from safekeepers",
    2045            6 :     )
    2046            6 :     .unwrap(),
    2047            6 :     records_received: register_int_counter!(
    2048            6 :         "pageserver_wal_ingest_records_received",
    2049            6 :         "Number of WAL records received from safekeepers"
    2050            6 :     )
    2051            6 :     .expect("failed to define a metric"),
    2052            6 :     records_committed: register_int_counter!(
    2053            6 :         "pageserver_wal_ingest_records_committed",
    2054            6 :         "Number of WAL records which resulted in writes to pageserver storage"
    2055            6 :     )
    2056            6 :     .expect("failed to define a metric"),
    2057            6 :     records_filtered: register_int_counter!(
    2058            6 :         "pageserver_wal_ingest_records_filtered",
    2059            6 :         "Number of WAL records filtered out due to sharding"
    2060            6 :     )
    2061            6 :     .expect("failed to define a metric"),
    2062            6 : });
    2063              : 
    2064           18 : pub(crate) static WAL_REDO_TIME: Lazy<Histogram> = Lazy::new(|| {
    2065           18 :     register_histogram!(
    2066           18 :         "pageserver_wal_redo_seconds",
    2067           18 :         "Time spent on WAL redo",
    2068           18 :         redo_histogram_time_buckets!()
    2069           18 :     )
    2070           18 :     .expect("failed to define a metric")
    2071           18 : });
    2072              : 
    2073           18 : pub(crate) static WAL_REDO_RECORDS_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
    2074           18 :     register_histogram!(
    2075           18 :         "pageserver_wal_redo_records_histogram",
    2076           18 :         "Histogram of number of records replayed per redo in the Postgres WAL redo process",
    2077           18 :         redo_histogram_count_buckets!(),
    2078           18 :     )
    2079           18 :     .expect("failed to define a metric")
    2080           18 : });
    2081              : 
    2082           18 : pub(crate) static WAL_REDO_BYTES_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
    2083           18 :     register_histogram!(
    2084           18 :         "pageserver_wal_redo_bytes_histogram",
    2085           18 :         "Histogram of number of records replayed per redo sent to Postgres",
    2086           18 :         redo_bytes_histogram_count_buckets!(),
    2087           18 :     )
    2088           18 :     .expect("failed to define a metric")
    2089           18 : });
    2090              : 
    2091              : // FIXME: isn't this already included by WAL_REDO_RECORDS_HISTOGRAM which has _count?
    2092           18 : pub(crate) static WAL_REDO_RECORD_COUNTER: Lazy<IntCounter> = Lazy::new(|| {
    2093           18 :     register_int_counter!(
    2094           18 :         "pageserver_replayed_wal_records_total",
    2095           18 :         "Number of WAL records replayed in WAL redo process"
    2096           18 :     )
    2097           18 :     .unwrap()
    2098           18 : });
    2099              : 
    2100              : #[rustfmt::skip]
    2101           18 : pub(crate) static WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
    2102           18 :     register_histogram!(
    2103           18 :         "pageserver_wal_redo_process_launch_duration",
    2104           18 :         "Histogram of the duration of successful WalRedoProcess::launch calls",
    2105           18 :         vec![
    2106           18 :             0.0002, 0.0004, 0.0006, 0.0008, 0.0010,
    2107           18 :             0.0020, 0.0040, 0.0060, 0.0080, 0.0100,
    2108           18 :             0.0200, 0.0400, 0.0600, 0.0800, 0.1000,
    2109           18 :             0.2000, 0.4000, 0.6000, 0.8000, 1.0000,
    2110           18 :             1.5000, 2.0000, 2.5000, 3.0000, 4.0000, 10.0000
    2111           18 :         ],
    2112           18 :     )
    2113           18 :     .expect("failed to define a metric")
    2114           18 : });
    2115              : 
    2116              : pub(crate) struct WalRedoProcessCounters {
    2117              :     pub(crate) started: IntCounter,
    2118              :     pub(crate) killed_by_cause: enum_map::EnumMap<WalRedoKillCause, IntCounter>,
    2119              :     pub(crate) active_stderr_logger_tasks_started: IntCounter,
    2120              :     pub(crate) active_stderr_logger_tasks_finished: IntCounter,
    2121              : }
    2122              : 
    2123           54 : #[derive(Debug, enum_map::Enum, strum_macros::IntoStaticStr)]
    2124              : pub(crate) enum WalRedoKillCause {
    2125              :     WalRedoProcessDrop,
    2126              :     NoLeakChildDrop,
    2127              :     Startup,
    2128              : }
    2129              : 
    2130              : impl Default for WalRedoProcessCounters {
    2131           18 :     fn default() -> Self {
    2132           18 :         let started = register_int_counter!(
    2133           18 :             "pageserver_wal_redo_process_started_total",
    2134           18 :             "Number of WAL redo processes started",
    2135           18 :         )
    2136           18 :         .unwrap();
    2137           18 : 
    2138           18 :         let killed = register_int_counter_vec!(
    2139           18 :             "pageserver_wal_redo_process_stopped_total",
    2140           18 :             "Number of WAL redo processes stopped",
    2141           18 :             &["cause"],
    2142           18 :         )
    2143           18 :         .unwrap();
    2144           18 : 
    2145           18 :         let active_stderr_logger_tasks_started = register_int_counter!(
    2146           18 :             "pageserver_walredo_stderr_logger_tasks_started_total",
    2147           18 :             "Number of active walredo stderr logger tasks that have started",
    2148           18 :         )
    2149           18 :         .unwrap();
    2150           18 : 
    2151           18 :         let active_stderr_logger_tasks_finished = register_int_counter!(
    2152           18 :             "pageserver_walredo_stderr_logger_tasks_finished_total",
    2153           18 :             "Number of active walredo stderr logger tasks that have finished",
    2154           18 :         )
    2155           18 :         .unwrap();
    2156           18 : 
    2157           18 :         Self {
    2158           18 :             started,
    2159           54 :             killed_by_cause: EnumMap::from_array(std::array::from_fn(|i| {
    2160           54 :                 let cause = <WalRedoKillCause as enum_map::Enum>::from_usize(i);
    2161           54 :                 let cause_str: &'static str = cause.into();
    2162           54 :                 killed.with_label_values(&[cause_str])
    2163           54 :             })),
    2164           18 :             active_stderr_logger_tasks_started,
    2165           18 :             active_stderr_logger_tasks_finished,
    2166           18 :         }
    2167           18 :     }
    2168              : }
    2169              : 
    2170              : pub(crate) static WAL_REDO_PROCESS_COUNTERS: Lazy<WalRedoProcessCounters> =
    2171              :     Lazy::new(WalRedoProcessCounters::default);
    2172              : 
    2173              : /// Similar to `prometheus::HistogramTimer` but does not record on drop.
    2174              : pub(crate) struct StorageTimeMetricsTimer {
    2175              :     metrics: StorageTimeMetrics,
    2176              :     start: Instant,
    2177              : }
    2178              : 
    2179              : impl StorageTimeMetricsTimer {
    2180        14584 :     fn new(metrics: StorageTimeMetrics) -> Self {
    2181        14584 :         Self {
    2182        14584 :             metrics,
    2183        14584 :             start: Instant::now(),
    2184        14584 :         }
    2185        14584 :     }
    2186              : 
    2187              :     /// Record the time from creation to now.
    2188        11193 :     pub fn stop_and_record(self) {
    2189        11193 :         let duration = self.start.elapsed().as_secs_f64();
    2190        11193 :         self.metrics.timeline_sum.inc_by(duration);
    2191        11193 :         self.metrics.timeline_count.inc();
    2192        11193 :         self.metrics.global_histogram.observe(duration);
    2193        11193 :     }
    2194              : 
    2195              :     /// Turns this timer into a timer, which will always record -- usually this means recording
    2196              :     /// regardless an early `?` path was taken in a function.
    2197         2262 :     pub(crate) fn record_on_drop(self) -> AlwaysRecordingStorageTimeMetricsTimer {
    2198         2262 :         AlwaysRecordingStorageTimeMetricsTimer(Some(self))
    2199         2262 :     }
    2200              : }
    2201              : 
    2202              : pub(crate) struct AlwaysRecordingStorageTimeMetricsTimer(Option<StorageTimeMetricsTimer>);
    2203              : 
    2204              : impl Drop for AlwaysRecordingStorageTimeMetricsTimer {
    2205         2262 :     fn drop(&mut self) {
    2206         2262 :         if let Some(inner) = self.0.take() {
    2207         2262 :             inner.stop_and_record();
    2208         2262 :         }
    2209         2262 :     }
    2210              : }
    2211              : 
    2212              : /// Timing facilities for an globally histogrammed metric, which is supported by per tenant and
    2213              : /// timeline total sum and count.
    2214              : #[derive(Clone, Debug)]
    2215              : pub(crate) struct StorageTimeMetrics {
    2216              :     /// Sum of f64 seconds, per operation, tenant_id and timeline_id
    2217              :     timeline_sum: Counter,
    2218              :     /// Number of oeprations, per operation, tenant_id and timeline_id
    2219              :     timeline_count: IntCounter,
    2220              :     /// Global histogram having only the "operation" label.
    2221              :     global_histogram: Histogram,
    2222              : }
    2223              : 
    2224              : impl StorageTimeMetrics {
    2225         9936 :     pub fn new(
    2226         9936 :         operation: StorageTimeOperation,
    2227         9936 :         tenant_id: &str,
    2228         9936 :         shard_id: &str,
    2229         9936 :         timeline_id: &str,
    2230         9936 :     ) -> Self {
    2231         9936 :         let operation: &'static str = operation.into();
    2232         9936 : 
    2233         9936 :         let timeline_sum = STORAGE_TIME_SUM_PER_TIMELINE
    2234         9936 :             .get_metric_with_label_values(&[operation, tenant_id, shard_id, timeline_id])
    2235         9936 :             .unwrap();
    2236         9936 :         let timeline_count = STORAGE_TIME_COUNT_PER_TIMELINE
    2237         9936 :             .get_metric_with_label_values(&[operation, tenant_id, shard_id, timeline_id])
    2238         9936 :             .unwrap();
    2239         9936 :         let global_histogram = STORAGE_TIME_GLOBAL
    2240         9936 :             .get_metric_with_label_values(&[operation])
    2241         9936 :             .unwrap();
    2242         9936 : 
    2243         9936 :         StorageTimeMetrics {
    2244         9936 :             timeline_sum,
    2245         9936 :             timeline_count,
    2246         9936 :             global_histogram,
    2247         9936 :         }
    2248         9936 :     }
    2249              : 
    2250              :     /// Starts timing a new operation.
    2251              :     ///
    2252              :     /// Note: unlike `prometheus::HistogramTimer` the returned timer does not record on drop.
    2253        14584 :     pub fn start_timer(&self) -> StorageTimeMetricsTimer {
    2254        14584 :         StorageTimeMetricsTimer::new(self.clone())
    2255        14584 :     }
    2256              : }
    2257              : 
    2258              : #[derive(Debug)]
    2259              : pub(crate) struct TimelineMetrics {
    2260              :     tenant_id: String,
    2261              :     shard_id: String,
    2262              :     timeline_id: String,
    2263              :     pub flush_time_histo: StorageTimeMetrics,
    2264              :     pub compact_time_histo: StorageTimeMetrics,
    2265              :     pub create_images_time_histo: StorageTimeMetrics,
    2266              :     pub logical_size_histo: StorageTimeMetrics,
    2267              :     pub imitate_logical_size_histo: StorageTimeMetrics,
    2268              :     pub load_layer_map_histo: StorageTimeMetrics,
    2269              :     pub garbage_collect_histo: StorageTimeMetrics,
    2270              :     pub find_gc_cutoffs_histo: StorageTimeMetrics,
    2271              :     pub last_record_gauge: IntGauge,
    2272              :     pub pitr_history_size: UIntGauge,
    2273              :     pub archival_size: UIntGauge,
    2274              :     pub(crate) layer_size_image: UIntGauge,
    2275              :     pub(crate) layer_count_image: UIntGauge,
    2276              :     pub(crate) layer_size_delta: UIntGauge,
    2277              :     pub(crate) layer_count_delta: UIntGauge,
    2278              :     pub standby_horizon_gauge: IntGauge,
    2279              :     pub resident_physical_size_gauge: UIntGauge,
    2280              :     pub visible_physical_size_gauge: UIntGauge,
    2281              :     /// copy of LayeredTimeline.current_logical_size
    2282              :     pub current_logical_size_gauge: UIntGauge,
    2283              :     pub aux_file_size_gauge: IntGauge,
    2284              :     pub directory_entries_count_gauge: Lazy<UIntGauge, Box<dyn Send + Fn() -> UIntGauge>>,
    2285              :     pub evictions: IntCounter,
    2286              :     pub evictions_with_low_residence_duration: std::sync::RwLock<EvictionsWithLowResidenceDuration>,
    2287              :     /// Number of valid LSN leases.
    2288              :     pub valid_lsn_lease_count_gauge: UIntGauge,
    2289              :     shutdown: std::sync::atomic::AtomicBool,
    2290              : }
    2291              : 
    2292              : impl TimelineMetrics {
    2293         1242 :     pub fn new(
    2294         1242 :         tenant_shard_id: &TenantShardId,
    2295         1242 :         timeline_id_raw: &TimelineId,
    2296         1242 :         evictions_with_low_residence_duration_builder: EvictionsWithLowResidenceDurationBuilder,
    2297         1242 :     ) -> Self {
    2298         1242 :         let tenant_id = tenant_shard_id.tenant_id.to_string();
    2299         1242 :         let shard_id = format!("{}", tenant_shard_id.shard_slug());
    2300         1242 :         let timeline_id = timeline_id_raw.to_string();
    2301         1242 :         let flush_time_histo = StorageTimeMetrics::new(
    2302         1242 :             StorageTimeOperation::LayerFlush,
    2303         1242 :             &tenant_id,
    2304         1242 :             &shard_id,
    2305         1242 :             &timeline_id,
    2306         1242 :         );
    2307         1242 :         let compact_time_histo = StorageTimeMetrics::new(
    2308         1242 :             StorageTimeOperation::Compact,
    2309         1242 :             &tenant_id,
    2310         1242 :             &shard_id,
    2311         1242 :             &timeline_id,
    2312         1242 :         );
    2313         1242 :         let create_images_time_histo = StorageTimeMetrics::new(
    2314         1242 :             StorageTimeOperation::CreateImages,
    2315         1242 :             &tenant_id,
    2316         1242 :             &shard_id,
    2317         1242 :             &timeline_id,
    2318         1242 :         );
    2319         1242 :         let logical_size_histo = StorageTimeMetrics::new(
    2320         1242 :             StorageTimeOperation::LogicalSize,
    2321         1242 :             &tenant_id,
    2322         1242 :             &shard_id,
    2323         1242 :             &timeline_id,
    2324         1242 :         );
    2325         1242 :         let imitate_logical_size_histo = StorageTimeMetrics::new(
    2326         1242 :             StorageTimeOperation::ImitateLogicalSize,
    2327         1242 :             &tenant_id,
    2328         1242 :             &shard_id,
    2329         1242 :             &timeline_id,
    2330         1242 :         );
    2331         1242 :         let load_layer_map_histo = StorageTimeMetrics::new(
    2332         1242 :             StorageTimeOperation::LoadLayerMap,
    2333         1242 :             &tenant_id,
    2334         1242 :             &shard_id,
    2335         1242 :             &timeline_id,
    2336         1242 :         );
    2337         1242 :         let garbage_collect_histo = StorageTimeMetrics::new(
    2338         1242 :             StorageTimeOperation::Gc,
    2339         1242 :             &tenant_id,
    2340         1242 :             &shard_id,
    2341         1242 :             &timeline_id,
    2342         1242 :         );
    2343         1242 :         let find_gc_cutoffs_histo = StorageTimeMetrics::new(
    2344         1242 :             StorageTimeOperation::FindGcCutoffs,
    2345         1242 :             &tenant_id,
    2346         1242 :             &shard_id,
    2347         1242 :             &timeline_id,
    2348         1242 :         );
    2349         1242 :         let last_record_gauge = LAST_RECORD_LSN
    2350         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2351         1242 :             .unwrap();
    2352         1242 : 
    2353         1242 :         let pitr_history_size = PITR_HISTORY_SIZE
    2354         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2355         1242 :             .unwrap();
    2356         1242 : 
    2357         1242 :         let archival_size = TIMELINE_ARCHIVE_SIZE
    2358         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2359         1242 :             .unwrap();
    2360         1242 : 
    2361         1242 :         let layer_size_image = TIMELINE_LAYER_SIZE
    2362         1242 :             .get_metric_with_label_values(&[
    2363         1242 :                 &tenant_id,
    2364         1242 :                 &shard_id,
    2365         1242 :                 &timeline_id,
    2366         1242 :                 MetricLayerKind::Image.into(),
    2367         1242 :             ])
    2368         1242 :             .unwrap();
    2369         1242 : 
    2370         1242 :         let layer_count_image = TIMELINE_LAYER_COUNT
    2371         1242 :             .get_metric_with_label_values(&[
    2372         1242 :                 &tenant_id,
    2373         1242 :                 &shard_id,
    2374         1242 :                 &timeline_id,
    2375         1242 :                 MetricLayerKind::Image.into(),
    2376         1242 :             ])
    2377         1242 :             .unwrap();
    2378         1242 : 
    2379         1242 :         let layer_size_delta = TIMELINE_LAYER_SIZE
    2380         1242 :             .get_metric_with_label_values(&[
    2381         1242 :                 &tenant_id,
    2382         1242 :                 &shard_id,
    2383         1242 :                 &timeline_id,
    2384         1242 :                 MetricLayerKind::Delta.into(),
    2385         1242 :             ])
    2386         1242 :             .unwrap();
    2387         1242 : 
    2388         1242 :         let layer_count_delta = TIMELINE_LAYER_COUNT
    2389         1242 :             .get_metric_with_label_values(&[
    2390         1242 :                 &tenant_id,
    2391         1242 :                 &shard_id,
    2392         1242 :                 &timeline_id,
    2393         1242 :                 MetricLayerKind::Delta.into(),
    2394         1242 :             ])
    2395         1242 :             .unwrap();
    2396         1242 : 
    2397         1242 :         let standby_horizon_gauge = STANDBY_HORIZON
    2398         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2399         1242 :             .unwrap();
    2400         1242 :         let resident_physical_size_gauge = RESIDENT_PHYSICAL_SIZE
    2401         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2402         1242 :             .unwrap();
    2403         1242 :         let visible_physical_size_gauge = VISIBLE_PHYSICAL_SIZE
    2404         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2405         1242 :             .unwrap();
    2406         1242 :         // TODO: we shouldn't expose this metric
    2407         1242 :         let current_logical_size_gauge = CURRENT_LOGICAL_SIZE
    2408         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2409         1242 :             .unwrap();
    2410         1242 :         let aux_file_size_gauge = AUX_FILE_SIZE
    2411         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2412         1242 :             .unwrap();
    2413         1242 :         // TODO use impl Trait syntax here once we have ability to use it: https://github.com/rust-lang/rust/issues/63065
    2414         1242 :         let directory_entries_count_gauge_closure = {
    2415         1242 :             let tenant_shard_id = *tenant_shard_id;
    2416         1242 :             let timeline_id_raw = *timeline_id_raw;
    2417            0 :             move || {
    2418            0 :                 let tenant_id = tenant_shard_id.tenant_id.to_string();
    2419            0 :                 let shard_id = format!("{}", tenant_shard_id.shard_slug());
    2420            0 :                 let timeline_id = timeline_id_raw.to_string();
    2421            0 :                 let gauge: UIntGauge = DIRECTORY_ENTRIES_COUNT
    2422            0 :                     .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2423            0 :                     .unwrap();
    2424            0 :                 gauge
    2425            0 :             }
    2426              :         };
    2427         1242 :         let directory_entries_count_gauge: Lazy<UIntGauge, Box<dyn Send + Fn() -> UIntGauge>> =
    2428         1242 :             Lazy::new(Box::new(directory_entries_count_gauge_closure));
    2429         1242 :         let evictions = EVICTIONS
    2430         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2431         1242 :             .unwrap();
    2432         1242 :         let evictions_with_low_residence_duration = evictions_with_low_residence_duration_builder
    2433         1242 :             .build(&tenant_id, &shard_id, &timeline_id);
    2434         1242 : 
    2435         1242 :         let valid_lsn_lease_count_gauge = VALID_LSN_LEASE_COUNT
    2436         1242 :             .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
    2437         1242 :             .unwrap();
    2438         1242 : 
    2439         1242 :         TimelineMetrics {
    2440         1242 :             tenant_id,
    2441         1242 :             shard_id,
    2442         1242 :             timeline_id,
    2443         1242 :             flush_time_histo,
    2444         1242 :             compact_time_histo,
    2445         1242 :             create_images_time_histo,
    2446         1242 :             logical_size_histo,
    2447         1242 :             imitate_logical_size_histo,
    2448         1242 :             garbage_collect_histo,
    2449         1242 :             find_gc_cutoffs_histo,
    2450         1242 :             load_layer_map_histo,
    2451         1242 :             last_record_gauge,
    2452         1242 :             pitr_history_size,
    2453         1242 :             archival_size,
    2454         1242 :             layer_size_image,
    2455         1242 :             layer_count_image,
    2456         1242 :             layer_size_delta,
    2457         1242 :             layer_count_delta,
    2458         1242 :             standby_horizon_gauge,
    2459         1242 :             resident_physical_size_gauge,
    2460         1242 :             visible_physical_size_gauge,
    2461         1242 :             current_logical_size_gauge,
    2462         1242 :             aux_file_size_gauge,
    2463         1242 :             directory_entries_count_gauge,
    2464         1242 :             evictions,
    2465         1242 :             evictions_with_low_residence_duration: std::sync::RwLock::new(
    2466         1242 :                 evictions_with_low_residence_duration,
    2467         1242 :             ),
    2468         1242 :             valid_lsn_lease_count_gauge,
    2469         1242 :             shutdown: std::sync::atomic::AtomicBool::default(),
    2470         1242 :         }
    2471         1242 :     }
    2472              : 
    2473         4530 :     pub(crate) fn record_new_file_metrics(&self, sz: u64) {
    2474         4530 :         self.resident_physical_size_add(sz);
    2475         4530 :     }
    2476              : 
    2477         1430 :     pub(crate) fn resident_physical_size_sub(&self, sz: u64) {
    2478         1430 :         self.resident_physical_size_gauge.sub(sz);
    2479         1430 :         crate::metrics::RESIDENT_PHYSICAL_SIZE_GLOBAL.sub(sz);
    2480         1430 :     }
    2481              : 
    2482         4620 :     pub(crate) fn resident_physical_size_add(&self, sz: u64) {
    2483         4620 :         self.resident_physical_size_gauge.add(sz);
    2484         4620 :         crate::metrics::RESIDENT_PHYSICAL_SIZE_GLOBAL.add(sz);
    2485         4620 :     }
    2486              : 
    2487           24 :     pub(crate) fn resident_physical_size_get(&self) -> u64 {
    2488           24 :         self.resident_physical_size_gauge.get()
    2489           24 :     }
    2490              : 
    2491           24 :     pub(crate) fn shutdown(&self) {
    2492           24 :         let was_shutdown = self
    2493           24 :             .shutdown
    2494           24 :             .swap(true, std::sync::atomic::Ordering::Relaxed);
    2495           24 : 
    2496           24 :         if was_shutdown {
    2497              :             // this happens on tenant deletion because tenant first shuts down timelines, then
    2498              :             // invokes timeline deletion which first shuts down the timeline again.
    2499              :             // TODO: this can be removed once https://github.com/neondatabase/neon/issues/5080
    2500            0 :             return;
    2501           24 :         }
    2502           24 : 
    2503           24 :         let tenant_id = &self.tenant_id;
    2504           24 :         let timeline_id = &self.timeline_id;
    2505           24 :         let shard_id = &self.shard_id;
    2506           24 :         let _ = LAST_RECORD_LSN.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2507           24 :         let _ = STANDBY_HORIZON.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2508           24 :         {
    2509           24 :             RESIDENT_PHYSICAL_SIZE_GLOBAL.sub(self.resident_physical_size_get());
    2510           24 :             let _ = RESIDENT_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2511           24 :         }
    2512           24 :         let _ = VISIBLE_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2513           24 :         let _ = CURRENT_LOGICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2514           24 :         if let Some(metric) = Lazy::get(&DIRECTORY_ENTRIES_COUNT) {
    2515            0 :             let _ = metric.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2516           24 :         }
    2517              : 
    2518           24 :         let _ = TIMELINE_ARCHIVE_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2519           24 :         let _ = PITR_HISTORY_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2520           24 : 
    2521           24 :         let _ = TIMELINE_LAYER_SIZE.remove_label_values(&[
    2522           24 :             tenant_id,
    2523           24 :             shard_id,
    2524           24 :             timeline_id,
    2525           24 :             MetricLayerKind::Image.into(),
    2526           24 :         ]);
    2527           24 :         let _ = TIMELINE_LAYER_COUNT.remove_label_values(&[
    2528           24 :             tenant_id,
    2529           24 :             shard_id,
    2530           24 :             timeline_id,
    2531           24 :             MetricLayerKind::Image.into(),
    2532           24 :         ]);
    2533           24 :         let _ = TIMELINE_LAYER_SIZE.remove_label_values(&[
    2534           24 :             tenant_id,
    2535           24 :             shard_id,
    2536           24 :             timeline_id,
    2537           24 :             MetricLayerKind::Delta.into(),
    2538           24 :         ]);
    2539           24 :         let _ = TIMELINE_LAYER_COUNT.remove_label_values(&[
    2540           24 :             tenant_id,
    2541           24 :             shard_id,
    2542           24 :             timeline_id,
    2543           24 :             MetricLayerKind::Delta.into(),
    2544           24 :         ]);
    2545           24 : 
    2546           24 :         let _ = EVICTIONS.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2547           24 :         let _ = AUX_FILE_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2548           24 :         let _ = VALID_LSN_LEASE_COUNT.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2549           24 : 
    2550           24 :         self.evictions_with_low_residence_duration
    2551           24 :             .write()
    2552           24 :             .unwrap()
    2553           24 :             .remove(tenant_id, shard_id, timeline_id);
    2554              : 
    2555              :         // The following metrics are born outside of the TimelineMetrics lifecycle but still
    2556              :         // removed at the end of it. The idea is to have the metrics outlive the
    2557              :         // entity during which they're observed, e.g., the smgr metrics shall
    2558              :         // outlive an individual smgr connection, but not the timeline.
    2559              : 
    2560          216 :         for op in StorageTimeOperation::VARIANTS {
    2561          192 :             let _ = STORAGE_TIME_SUM_PER_TIMELINE.remove_label_values(&[
    2562          192 :                 op,
    2563          192 :                 tenant_id,
    2564          192 :                 shard_id,
    2565          192 :                 timeline_id,
    2566          192 :             ]);
    2567          192 :             let _ = STORAGE_TIME_COUNT_PER_TIMELINE.remove_label_values(&[
    2568          192 :                 op,
    2569          192 :                 tenant_id,
    2570          192 :                 shard_id,
    2571          192 :                 timeline_id,
    2572          192 :             ]);
    2573          192 :         }
    2574              : 
    2575           72 :         for op in STORAGE_IO_SIZE_OPERATIONS {
    2576           48 :             let _ = STORAGE_IO_SIZE.remove_label_values(&[op, tenant_id, shard_id, timeline_id]);
    2577           48 :         }
    2578              : 
    2579           24 :         let _ = SMGR_QUERY_TIME_PER_TENANT_TIMELINE.remove_label_values(&[
    2580           24 :             SmgrQueryType::GetPageAtLsn.into(),
    2581           24 :             tenant_id,
    2582           24 :             shard_id,
    2583           24 :             timeline_id,
    2584           24 :         ]);
    2585           24 :     }
    2586              : }
    2587              : 
    2588           18 : pub(crate) fn remove_tenant_metrics(tenant_shard_id: &TenantShardId) {
    2589           18 :     // Only shard zero deals in synthetic sizes
    2590           18 :     if tenant_shard_id.is_shard_zero() {
    2591           18 :         let tid = tenant_shard_id.tenant_id.to_string();
    2592           18 :         let _ = TENANT_SYNTHETIC_SIZE_METRIC.remove_label_values(&[&tid]);
    2593           18 :     }
    2594              : 
    2595              :     // we leave the BROKEN_TENANTS_SET entry if any
    2596           18 : }
    2597              : 
    2598              : use futures::Future;
    2599              : use pin_project_lite::pin_project;
    2600              : use std::collections::HashMap;
    2601              : use std::num::NonZeroUsize;
    2602              : use std::pin::Pin;
    2603              : use std::sync::atomic::AtomicU64;
    2604              : use std::sync::{Arc, Mutex};
    2605              : use std::task::{Context, Poll};
    2606              : use std::time::{Duration, Instant};
    2607              : 
    2608              : use crate::context::{PageContentKind, RequestContext};
    2609              : use crate::task_mgr::TaskKind;
    2610              : use crate::tenant::mgr::TenantSlot;
    2611              : use crate::tenant::tasks::BackgroundLoopKind;
    2612              : 
    2613              : /// Maintain a per timeline gauge in addition to the global gauge.
    2614              : pub(crate) struct PerTimelineRemotePhysicalSizeGauge {
    2615              :     last_set: AtomicU64,
    2616              :     gauge: UIntGauge,
    2617              : }
    2618              : 
    2619              : impl PerTimelineRemotePhysicalSizeGauge {
    2620         1272 :     fn new(per_timeline_gauge: UIntGauge) -> Self {
    2621         1272 :         Self {
    2622         1272 :             last_set: AtomicU64::new(0),
    2623         1272 :             gauge: per_timeline_gauge,
    2624         1272 :         }
    2625         1272 :     }
    2626         5459 :     pub(crate) fn set(&self, sz: u64) {
    2627         5459 :         self.gauge.set(sz);
    2628         5459 :         let prev = self.last_set.swap(sz, std::sync::atomic::Ordering::Relaxed);
    2629         5459 :         if sz < prev {
    2630           78 :             REMOTE_PHYSICAL_SIZE_GLOBAL.sub(prev - sz);
    2631         5381 :         } else {
    2632         5381 :             REMOTE_PHYSICAL_SIZE_GLOBAL.add(sz - prev);
    2633         5381 :         };
    2634         5459 :     }
    2635            6 :     pub(crate) fn get(&self) -> u64 {
    2636            6 :         self.gauge.get()
    2637            6 :     }
    2638              : }
    2639              : 
    2640              : impl Drop for PerTimelineRemotePhysicalSizeGauge {
    2641           54 :     fn drop(&mut self) {
    2642           54 :         REMOTE_PHYSICAL_SIZE_GLOBAL.sub(self.last_set.load(std::sync::atomic::Ordering::Relaxed));
    2643           54 :     }
    2644              : }
    2645              : 
    2646              : pub(crate) struct RemoteTimelineClientMetrics {
    2647              :     tenant_id: String,
    2648              :     shard_id: String,
    2649              :     timeline_id: String,
    2650              :     pub(crate) remote_physical_size_gauge: PerTimelineRemotePhysicalSizeGauge,
    2651              :     calls: Mutex<HashMap<(&'static str, &'static str), IntCounterPair>>,
    2652              :     bytes_started_counter: Mutex<HashMap<(&'static str, &'static str), IntCounter>>,
    2653              :     bytes_finished_counter: Mutex<HashMap<(&'static str, &'static str), IntCounter>>,
    2654              : }
    2655              : 
    2656              : impl RemoteTimelineClientMetrics {
    2657         1272 :     pub fn new(tenant_shard_id: &TenantShardId, timeline_id: &TimelineId) -> Self {
    2658         1272 :         let tenant_id_str = tenant_shard_id.tenant_id.to_string();
    2659         1272 :         let shard_id_str = format!("{}", tenant_shard_id.shard_slug());
    2660         1272 :         let timeline_id_str = timeline_id.to_string();
    2661         1272 : 
    2662         1272 :         let remote_physical_size_gauge = PerTimelineRemotePhysicalSizeGauge::new(
    2663         1272 :             REMOTE_PHYSICAL_SIZE
    2664         1272 :                 .get_metric_with_label_values(&[&tenant_id_str, &shard_id_str, &timeline_id_str])
    2665         1272 :                 .unwrap(),
    2666         1272 :         );
    2667         1272 : 
    2668         1272 :         RemoteTimelineClientMetrics {
    2669         1272 :             tenant_id: tenant_id_str,
    2670         1272 :             shard_id: shard_id_str,
    2671         1272 :             timeline_id: timeline_id_str,
    2672         1272 :             calls: Mutex::new(HashMap::default()),
    2673         1272 :             bytes_started_counter: Mutex::new(HashMap::default()),
    2674         1272 :             bytes_finished_counter: Mutex::new(HashMap::default()),
    2675         1272 :             remote_physical_size_gauge,
    2676         1272 :         }
    2677         1272 :     }
    2678              : 
    2679         8140 :     pub fn remote_operation_time(
    2680         8140 :         &self,
    2681         8140 :         file_kind: &RemoteOpFileKind,
    2682         8140 :         op_kind: &RemoteOpKind,
    2683         8140 :         status: &'static str,
    2684         8140 :     ) -> Histogram {
    2685         8140 :         let key = (file_kind.as_str(), op_kind.as_str(), status);
    2686         8140 :         REMOTE_OPERATION_TIME
    2687         8140 :             .get_metric_with_label_values(&[key.0, key.1, key.2])
    2688         8140 :             .unwrap()
    2689         8140 :     }
    2690              : 
    2691        19167 :     fn calls_counter_pair(
    2692        19167 :         &self,
    2693        19167 :         file_kind: &RemoteOpFileKind,
    2694        19167 :         op_kind: &RemoteOpKind,
    2695        19167 :     ) -> IntCounterPair {
    2696        19167 :         let mut guard = self.calls.lock().unwrap();
    2697        19167 :         let key = (file_kind.as_str(), op_kind.as_str());
    2698        19167 :         let metric = guard.entry(key).or_insert_with(move || {
    2699         2242 :             REMOTE_TIMELINE_CLIENT_CALLS
    2700         2242 :                 .get_metric_with_label_values(&[
    2701         2242 :                     &self.tenant_id,
    2702         2242 :                     &self.shard_id,
    2703         2242 :                     &self.timeline_id,
    2704         2242 :                     key.0,
    2705         2242 :                     key.1,
    2706         2242 :                 ])
    2707         2242 :                 .unwrap()
    2708        19167 :         });
    2709        19167 :         metric.clone()
    2710        19167 :     }
    2711              : 
    2712         4554 :     fn bytes_started_counter(
    2713         4554 :         &self,
    2714         4554 :         file_kind: &RemoteOpFileKind,
    2715         4554 :         op_kind: &RemoteOpKind,
    2716         4554 :     ) -> IntCounter {
    2717         4554 :         let mut guard = self.bytes_started_counter.lock().unwrap();
    2718         4554 :         let key = (file_kind.as_str(), op_kind.as_str());
    2719         4554 :         let metric = guard.entry(key).or_insert_with(move || {
    2720          864 :             REMOTE_TIMELINE_CLIENT_BYTES_STARTED_COUNTER
    2721          864 :                 .get_metric_with_label_values(&[
    2722          864 :                     &self.tenant_id,
    2723          864 :                     &self.shard_id,
    2724          864 :                     &self.timeline_id,
    2725          864 :                     key.0,
    2726          864 :                     key.1,
    2727          864 :                 ])
    2728          864 :                 .unwrap()
    2729         4554 :         });
    2730         4554 :         metric.clone()
    2731         4554 :     }
    2732              : 
    2733         8399 :     fn bytes_finished_counter(
    2734         8399 :         &self,
    2735         8399 :         file_kind: &RemoteOpFileKind,
    2736         8399 :         op_kind: &RemoteOpKind,
    2737         8399 :     ) -> IntCounter {
    2738         8399 :         let mut guard = self.bytes_finished_counter.lock().unwrap();
    2739         8399 :         let key = (file_kind.as_str(), op_kind.as_str());
    2740         8399 :         let metric = guard.entry(key).or_insert_with(move || {
    2741          864 :             REMOTE_TIMELINE_CLIENT_BYTES_FINISHED_COUNTER
    2742          864 :                 .get_metric_with_label_values(&[
    2743          864 :                     &self.tenant_id,
    2744          864 :                     &self.shard_id,
    2745          864 :                     &self.timeline_id,
    2746          864 :                     key.0,
    2747          864 :                     key.1,
    2748          864 :                 ])
    2749          864 :                 .unwrap()
    2750         8399 :         });
    2751         8399 :         metric.clone()
    2752         8399 :     }
    2753              : }
    2754              : 
    2755              : #[cfg(test)]
    2756              : impl RemoteTimelineClientMetrics {
    2757           18 :     pub fn get_bytes_started_counter_value(
    2758           18 :         &self,
    2759           18 :         file_kind: &RemoteOpFileKind,
    2760           18 :         op_kind: &RemoteOpKind,
    2761           18 :     ) -> Option<u64> {
    2762           18 :         let guard = self.bytes_started_counter.lock().unwrap();
    2763           18 :         let key = (file_kind.as_str(), op_kind.as_str());
    2764           18 :         guard.get(&key).map(|counter| counter.get())
    2765           18 :     }
    2766              : 
    2767           18 :     pub fn get_bytes_finished_counter_value(
    2768           18 :         &self,
    2769           18 :         file_kind: &RemoteOpFileKind,
    2770           18 :         op_kind: &RemoteOpKind,
    2771           18 :     ) -> Option<u64> {
    2772           18 :         let guard = self.bytes_finished_counter.lock().unwrap();
    2773           18 :         let key = (file_kind.as_str(), op_kind.as_str());
    2774           18 :         guard.get(&key).map(|counter| counter.get())
    2775           18 :     }
    2776              : }
    2777              : 
    2778              : /// See [`RemoteTimelineClientMetrics::call_begin`].
    2779              : #[must_use]
    2780              : pub(crate) struct RemoteTimelineClientCallMetricGuard {
    2781              :     /// Decremented on drop.
    2782              :     calls_counter_pair: Option<IntCounterPair>,
    2783              :     /// If Some(), this references the bytes_finished metric, and we increment it by the given `u64` on drop.
    2784              :     bytes_finished: Option<(IntCounter, u64)>,
    2785              : }
    2786              : 
    2787              : impl RemoteTimelineClientCallMetricGuard {
    2788              :     /// Consume this guard object without performing the metric updates it would do on `drop()`.
    2789              :     /// The caller vouches to do the metric updates manually.
    2790        10310 :     pub fn will_decrement_manually(mut self) {
    2791        10310 :         let RemoteTimelineClientCallMetricGuard {
    2792        10310 :             calls_counter_pair,
    2793        10310 :             bytes_finished,
    2794        10310 :         } = &mut self;
    2795        10310 :         calls_counter_pair.take();
    2796        10310 :         bytes_finished.take();
    2797        10310 :     }
    2798              : }
    2799              : 
    2800              : impl Drop for RemoteTimelineClientCallMetricGuard {
    2801        10388 :     fn drop(&mut self) {
    2802        10388 :         let RemoteTimelineClientCallMetricGuard {
    2803        10388 :             calls_counter_pair,
    2804        10388 :             bytes_finished,
    2805        10388 :         } = self;
    2806        10388 :         if let Some(guard) = calls_counter_pair.take() {
    2807           78 :             guard.dec();
    2808        10310 :         }
    2809        10388 :         if let Some((bytes_finished_metric, value)) = bytes_finished {
    2810            0 :             bytes_finished_metric.inc_by(*value);
    2811        10388 :         }
    2812        10388 :     }
    2813              : }
    2814              : 
    2815              : /// The enum variants communicate to the [`RemoteTimelineClientMetrics`] whether to
    2816              : /// track the byte size of this call in applicable metric(s).
    2817              : pub(crate) enum RemoteTimelineClientMetricsCallTrackSize {
    2818              :     /// Do not account for this call's byte size in any metrics.
    2819              :     /// The `reason` field is there to make the call sites self-documenting
    2820              :     /// about why they don't need the metric.
    2821              :     DontTrackSize { reason: &'static str },
    2822              :     /// Track the byte size of the call in applicable metric(s).
    2823              :     Bytes(u64),
    2824              : }
    2825              : 
    2826              : impl RemoteTimelineClientMetrics {
    2827              :     /// Update the metrics that change when a call to the remote timeline client instance starts.
    2828              :     ///
    2829              :     /// Drop the returned guard object once the operation is finished to updates corresponding metrics that track completions.
    2830              :     /// Or, use [`RemoteTimelineClientCallMetricGuard::will_decrement_manually`] and [`call_end`](Self::call_end) if that
    2831              :     /// is more suitable.
    2832              :     /// Never do both.
    2833        10388 :     pub(crate) fn call_begin(
    2834        10388 :         &self,
    2835        10388 :         file_kind: &RemoteOpFileKind,
    2836        10388 :         op_kind: &RemoteOpKind,
    2837        10388 :         size: RemoteTimelineClientMetricsCallTrackSize,
    2838        10388 :     ) -> RemoteTimelineClientCallMetricGuard {
    2839        10388 :         let calls_counter_pair = self.calls_counter_pair(file_kind, op_kind);
    2840        10388 :         calls_counter_pair.inc();
    2841              : 
    2842        10388 :         let bytes_finished = match size {
    2843         5834 :             RemoteTimelineClientMetricsCallTrackSize::DontTrackSize { reason: _reason } => {
    2844         5834 :                 // nothing to do
    2845         5834 :                 None
    2846              :             }
    2847         4554 :             RemoteTimelineClientMetricsCallTrackSize::Bytes(size) => {
    2848         4554 :                 self.bytes_started_counter(file_kind, op_kind).inc_by(size);
    2849         4554 :                 let finished_counter = self.bytes_finished_counter(file_kind, op_kind);
    2850         4554 :                 Some((finished_counter, size))
    2851              :             }
    2852              :         };
    2853        10388 :         RemoteTimelineClientCallMetricGuard {
    2854        10388 :             calls_counter_pair: Some(calls_counter_pair),
    2855        10388 :             bytes_finished,
    2856        10388 :         }
    2857        10388 :     }
    2858              : 
    2859              :     /// Manually udpate the metrics that track completions, instead of using the guard object.
    2860              :     /// Using the guard object is generally preferable.
    2861              :     /// See [`call_begin`](Self::call_begin) for more context.
    2862         8779 :     pub(crate) fn call_end(
    2863         8779 :         &self,
    2864         8779 :         file_kind: &RemoteOpFileKind,
    2865         8779 :         op_kind: &RemoteOpKind,
    2866         8779 :         size: RemoteTimelineClientMetricsCallTrackSize,
    2867         8779 :     ) {
    2868         8779 :         let calls_counter_pair = self.calls_counter_pair(file_kind, op_kind);
    2869         8779 :         calls_counter_pair.dec();
    2870         8779 :         match size {
    2871         4934 :             RemoteTimelineClientMetricsCallTrackSize::DontTrackSize { reason: _reason } => {}
    2872         3845 :             RemoteTimelineClientMetricsCallTrackSize::Bytes(size) => {
    2873         3845 :                 self.bytes_finished_counter(file_kind, op_kind).inc_by(size);
    2874         3845 :             }
    2875              :         }
    2876         8779 :     }
    2877              : }
    2878              : 
    2879              : impl Drop for RemoteTimelineClientMetrics {
    2880           54 :     fn drop(&mut self) {
    2881           54 :         let RemoteTimelineClientMetrics {
    2882           54 :             tenant_id,
    2883           54 :             shard_id,
    2884           54 :             timeline_id,
    2885           54 :             remote_physical_size_gauge,
    2886           54 :             calls,
    2887           54 :             bytes_started_counter,
    2888           54 :             bytes_finished_counter,
    2889           54 :         } = self;
    2890           72 :         for ((a, b), _) in calls.get_mut().unwrap().drain() {
    2891           72 :             let mut res = [Ok(()), Ok(())];
    2892           72 :             REMOTE_TIMELINE_CLIENT_CALLS
    2893           72 :                 .remove_label_values(&mut res, &[tenant_id, shard_id, timeline_id, a, b]);
    2894           72 :             // don't care about results
    2895           72 :         }
    2896           54 :         for ((a, b), _) in bytes_started_counter.get_mut().unwrap().drain() {
    2897           18 :             let _ = REMOTE_TIMELINE_CLIENT_BYTES_STARTED_COUNTER.remove_label_values(&[
    2898           18 :                 tenant_id,
    2899           18 :                 shard_id,
    2900           18 :                 timeline_id,
    2901           18 :                 a,
    2902           18 :                 b,
    2903           18 :             ]);
    2904           18 :         }
    2905           54 :         for ((a, b), _) in bytes_finished_counter.get_mut().unwrap().drain() {
    2906           18 :             let _ = REMOTE_TIMELINE_CLIENT_BYTES_FINISHED_COUNTER.remove_label_values(&[
    2907           18 :                 tenant_id,
    2908           18 :                 shard_id,
    2909           18 :                 timeline_id,
    2910           18 :                 a,
    2911           18 :                 b,
    2912           18 :             ]);
    2913           18 :         }
    2914           54 :         {
    2915           54 :             let _ = remote_physical_size_gauge; // use to avoid 'unused' warning in desctructuring above
    2916           54 :             let _ = REMOTE_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
    2917           54 :         }
    2918           54 :     }
    2919              : }
    2920              : 
    2921              : /// Wrapper future that measures the time spent by a remote storage operation,
    2922              : /// and records the time and success/failure as a prometheus metric.
    2923              : pub(crate) trait MeasureRemoteOp: Sized {
    2924         8422 :     fn measure_remote_op(
    2925         8422 :         self,
    2926         8422 :         file_kind: RemoteOpFileKind,
    2927         8422 :         op: RemoteOpKind,
    2928         8422 :         metrics: Arc<RemoteTimelineClientMetrics>,
    2929         8422 :     ) -> MeasuredRemoteOp<Self> {
    2930         8422 :         let start = Instant::now();
    2931         8422 :         MeasuredRemoteOp {
    2932         8422 :             inner: self,
    2933         8422 :             file_kind,
    2934         8422 :             op,
    2935         8422 :             start,
    2936         8422 :             metrics,
    2937         8422 :         }
    2938         8422 :     }
    2939              : }
    2940              : 
    2941              : impl<T: Sized> MeasureRemoteOp for T {}
    2942              : 
    2943              : pin_project! {
    2944              :     pub(crate) struct MeasuredRemoteOp<F>
    2945              :     {
    2946              :         #[pin]
    2947              :         inner: F,
    2948              :         file_kind: RemoteOpFileKind,
    2949              :         op: RemoteOpKind,
    2950              :         start: Instant,
    2951              :         metrics: Arc<RemoteTimelineClientMetrics>,
    2952              :     }
    2953              : }
    2954              : 
    2955              : impl<F: Future<Output = Result<O, E>>, O, E> Future for MeasuredRemoteOp<F> {
    2956              :     type Output = Result<O, E>;
    2957              : 
    2958       130656 :     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    2959       130656 :         let this = self.project();
    2960       130656 :         let poll_result = this.inner.poll(cx);
    2961       130656 :         if let Poll::Ready(ref res) = poll_result {
    2962         8140 :             let duration = this.start.elapsed();
    2963         8140 :             let status = if res.is_ok() { &"success" } else { &"failure" };
    2964         8140 :             this.metrics
    2965         8140 :                 .remote_operation_time(this.file_kind, this.op, status)
    2966         8140 :                 .observe(duration.as_secs_f64());
    2967       122516 :         }
    2968       130656 :         poll_result
    2969       130656 :     }
    2970              : }
    2971              : 
    2972              : pub mod tokio_epoll_uring {
    2973              :     use metrics::{register_int_counter, UIntGauge};
    2974              :     use once_cell::sync::Lazy;
    2975              : 
    2976              :     pub struct Collector {
    2977              :         descs: Vec<metrics::core::Desc>,
    2978              :         systems_created: UIntGauge,
    2979              :         systems_destroyed: UIntGauge,
    2980              :     }
    2981              : 
    2982              :     impl metrics::core::Collector for Collector {
    2983            0 :         fn desc(&self) -> Vec<&metrics::core::Desc> {
    2984            0 :             self.descs.iter().collect()
    2985            0 :         }
    2986              : 
    2987            0 :         fn collect(&self) -> Vec<metrics::proto::MetricFamily> {
    2988            0 :             let mut mfs = Vec::with_capacity(Self::NMETRICS);
    2989            0 :             let tokio_epoll_uring::metrics::Metrics {
    2990            0 :                 systems_created,
    2991            0 :                 systems_destroyed,
    2992            0 :             } = tokio_epoll_uring::metrics::global();
    2993            0 :             self.systems_created.set(systems_created);
    2994            0 :             mfs.extend(self.systems_created.collect());
    2995            0 :             self.systems_destroyed.set(systems_destroyed);
    2996            0 :             mfs.extend(self.systems_destroyed.collect());
    2997            0 :             mfs
    2998            0 :         }
    2999              :     }
    3000              : 
    3001              :     impl Collector {
    3002              :         const NMETRICS: usize = 2;
    3003              : 
    3004              :         #[allow(clippy::new_without_default)]
    3005            0 :         pub fn new() -> Self {
    3006            0 :             let mut descs = Vec::new();
    3007            0 : 
    3008            0 :             let systems_created = UIntGauge::new(
    3009            0 :                 "pageserver_tokio_epoll_uring_systems_created",
    3010            0 :                 "counter of tokio-epoll-uring systems that were created",
    3011            0 :             )
    3012            0 :             .unwrap();
    3013            0 :             descs.extend(
    3014            0 :                 metrics::core::Collector::desc(&systems_created)
    3015            0 :                     .into_iter()
    3016            0 :                     .cloned(),
    3017            0 :             );
    3018            0 : 
    3019            0 :             let systems_destroyed = UIntGauge::new(
    3020            0 :                 "pageserver_tokio_epoll_uring_systems_destroyed",
    3021            0 :                 "counter of tokio-epoll-uring systems that were destroyed",
    3022            0 :             )
    3023            0 :             .unwrap();
    3024            0 :             descs.extend(
    3025            0 :                 metrics::core::Collector::desc(&systems_destroyed)
    3026            0 :                     .into_iter()
    3027            0 :                     .cloned(),
    3028            0 :             );
    3029            0 : 
    3030            0 :             Self {
    3031            0 :                 descs,
    3032            0 :                 systems_created,
    3033            0 :                 systems_destroyed,
    3034            0 :             }
    3035            0 :         }
    3036              :     }
    3037              : 
    3038          303 :     pub(crate) static THREAD_LOCAL_LAUNCH_SUCCESSES: Lazy<metrics::IntCounter> = Lazy::new(|| {
    3039          303 :         register_int_counter!(
    3040          303 :             "pageserver_tokio_epoll_uring_pageserver_thread_local_launch_success_count",
    3041          303 :             "Number of times where thread_local_system creation spanned multiple executor threads",
    3042          303 :         )
    3043          303 :         .unwrap()
    3044          303 :     });
    3045              : 
    3046            0 :     pub(crate) static THREAD_LOCAL_LAUNCH_FAILURES: Lazy<metrics::IntCounter> = Lazy::new(|| {
    3047            0 :         register_int_counter!(
    3048            0 :             "pageserver_tokio_epoll_uring_pageserver_thread_local_launch_failures_count",
    3049            0 :             "Number of times thread_local_system creation failed and was retried after back-off.",
    3050            0 :         )
    3051            0 :         .unwrap()
    3052            0 :     });
    3053              : }
    3054              : 
    3055              : pub(crate) mod tenant_throttling {
    3056              :     use metrics::{register_int_counter_vec, IntCounter};
    3057              :     use once_cell::sync::Lazy;
    3058              : 
    3059              :     use crate::tenant::{self, throttle::Metric};
    3060              : 
    3061              :     pub(crate) struct TimelineGet {
    3062              :         wait_time: IntCounter,
    3063              :         count: IntCounter,
    3064              :     }
    3065              : 
    3066          516 :     pub(crate) static TIMELINE_GET: Lazy<TimelineGet> = Lazy::new(|| {
    3067          516 :         static WAIT_USECS: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
    3068          516 :             register_int_counter_vec!(
    3069          516 :             "pageserver_tenant_throttling_wait_usecs_sum_global",
    3070          516 :             "Sum of microseconds that tenants spent waiting for a tenant throttle of a given kind.",
    3071          516 :             &["kind"]
    3072          516 :         )
    3073          516 :             .unwrap()
    3074          516 :         });
    3075              : 
    3076          516 :         static WAIT_COUNT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
    3077          516 :             register_int_counter_vec!(
    3078          516 :                 "pageserver_tenant_throttling_count_global",
    3079          516 :                 "Count of tenant throttlings, by kind of throttle.",
    3080          516 :                 &["kind"]
    3081          516 :             )
    3082          516 :             .unwrap()
    3083          516 :         });
    3084              : 
    3085          516 :         let kind = "timeline_get";
    3086          516 :         TimelineGet {
    3087          516 :             wait_time: WAIT_USECS.with_label_values(&[kind]),
    3088          516 :             count: WAIT_COUNT.with_label_values(&[kind]),
    3089          516 :         }
    3090          516 :     });
    3091              : 
    3092              :     impl Metric for &'static TimelineGet {
    3093              :         #[inline(always)]
    3094            0 :         fn observe_throttling(
    3095            0 :             &self,
    3096            0 :             tenant::throttle::Observation { wait_time }: &tenant::throttle::Observation,
    3097            0 :         ) {
    3098            0 :             let val = u64::try_from(wait_time.as_micros()).unwrap();
    3099            0 :             self.wait_time.inc_by(val);
    3100            0 :             self.count.inc();
    3101            0 :         }
    3102              :     }
    3103              : }
    3104              : 
    3105              : pub(crate) mod disk_usage_based_eviction {
    3106              :     use super::*;
    3107              : 
    3108              :     pub(crate) struct Metrics {
    3109              :         pub(crate) tenant_collection_time: Histogram,
    3110              :         pub(crate) tenant_layer_count: Histogram,
    3111              :         pub(crate) layers_collected: IntCounter,
    3112              :         pub(crate) layers_selected: IntCounter,
    3113              :         pub(crate) layers_evicted: IntCounter,
    3114              :     }
    3115              : 
    3116              :     impl Default for Metrics {
    3117            0 :         fn default() -> Self {
    3118            0 :             let tenant_collection_time = register_histogram!(
    3119            0 :                 "pageserver_disk_usage_based_eviction_tenant_collection_seconds",
    3120            0 :                 "Time spent collecting layers from a tenant -- not normalized by collected layer amount",
    3121            0 :                 vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0]
    3122            0 :             )
    3123            0 :             .unwrap();
    3124            0 : 
    3125            0 :             let tenant_layer_count = register_histogram!(
    3126            0 :                 "pageserver_disk_usage_based_eviction_tenant_collected_layers",
    3127            0 :                 "Amount of layers gathered from a tenant",
    3128            0 :                 vec![5.0, 50.0, 500.0, 5000.0, 50000.0]
    3129            0 :             )
    3130            0 :             .unwrap();
    3131            0 : 
    3132            0 :             let layers_collected = register_int_counter!(
    3133            0 :                 "pageserver_disk_usage_based_eviction_collected_layers_total",
    3134            0 :                 "Amount of layers collected"
    3135            0 :             )
    3136            0 :             .unwrap();
    3137            0 : 
    3138            0 :             let layers_selected = register_int_counter!(
    3139            0 :                 "pageserver_disk_usage_based_eviction_select_layers_total",
    3140            0 :                 "Amount of layers selected"
    3141            0 :             )
    3142            0 :             .unwrap();
    3143            0 : 
    3144            0 :             let layers_evicted = register_int_counter!(
    3145            0 :                 "pageserver_disk_usage_based_eviction_evicted_layers_total",
    3146            0 :                 "Amount of layers successfully evicted"
    3147            0 :             )
    3148            0 :             .unwrap();
    3149            0 : 
    3150            0 :             Self {
    3151            0 :                 tenant_collection_time,
    3152            0 :                 tenant_layer_count,
    3153            0 :                 layers_collected,
    3154            0 :                 layers_selected,
    3155            0 :                 layers_evicted,
    3156            0 :             }
    3157            0 :         }
    3158              :     }
    3159              : 
    3160              :     pub(crate) static METRICS: Lazy<Metrics> = Lazy::new(Metrics::default);
    3161              : }
    3162              : 
    3163          498 : static TOKIO_EXECUTOR_THREAD_COUNT: Lazy<UIntGaugeVec> = Lazy::new(|| {
    3164          498 :     register_uint_gauge_vec!(
    3165          498 :         "pageserver_tokio_executor_thread_configured_count",
    3166          498 :         "Total number of configued tokio executor threads in the process.
    3167          498 :          The `setup` label denotes whether we're running with multiple runtimes or a single runtime.",
    3168          498 :         &["setup"],
    3169          498 :     )
    3170          498 :     .unwrap()
    3171          498 : });
    3172              : 
    3173          498 : pub(crate) fn set_tokio_runtime_setup(setup: &str, num_threads: NonZeroUsize) {
    3174              :     static SERIALIZE: std::sync::Mutex<()> = std::sync::Mutex::new(());
    3175          498 :     let _guard = SERIALIZE.lock().unwrap();
    3176          498 :     TOKIO_EXECUTOR_THREAD_COUNT.reset();
    3177          498 :     TOKIO_EXECUTOR_THREAD_COUNT
    3178          498 :         .get_metric_with_label_values(&[setup])
    3179          498 :         .unwrap()
    3180          498 :         .set(u64::try_from(num_threads.get()).unwrap());
    3181          498 : }
    3182              : 
    3183            0 : pub fn preinitialize_metrics() {
    3184            0 :     // Python tests need these and on some we do alerting.
    3185            0 :     //
    3186            0 :     // FIXME(4813): make it so that we have no top level metrics as this fn will easily fall out of
    3187            0 :     // order:
    3188            0 :     // - global metrics reside in a Lazy<PageserverMetrics>
    3189            0 :     //   - access via crate::metrics::PS_METRICS.some_metric.inc()
    3190            0 :     // - could move the statics into TimelineMetrics::new()?
    3191            0 : 
    3192            0 :     // counters
    3193            0 :     [
    3194            0 :         &UNEXPECTED_ONDEMAND_DOWNLOADS,
    3195            0 :         &WALRECEIVER_STARTED_CONNECTIONS,
    3196            0 :         &WALRECEIVER_BROKER_UPDATES,
    3197            0 :         &WALRECEIVER_CANDIDATES_ADDED,
    3198            0 :         &WALRECEIVER_CANDIDATES_REMOVED,
    3199            0 :         &tokio_epoll_uring::THREAD_LOCAL_LAUNCH_FAILURES,
    3200            0 :         &tokio_epoll_uring::THREAD_LOCAL_LAUNCH_SUCCESSES,
    3201            0 :         &REMOTE_ONDEMAND_DOWNLOADED_LAYERS,
    3202            0 :         &REMOTE_ONDEMAND_DOWNLOADED_BYTES,
    3203            0 :         &CIRCUIT_BREAKERS_BROKEN,
    3204            0 :         &CIRCUIT_BREAKERS_UNBROKEN,
    3205            0 :     ]
    3206            0 :     .into_iter()
    3207            0 :     .for_each(|c| {
    3208            0 :         Lazy::force(c);
    3209            0 :     });
    3210            0 : 
    3211            0 :     // Deletion queue stats
    3212            0 :     Lazy::force(&DELETION_QUEUE);
    3213            0 : 
    3214            0 :     // Tenant stats
    3215            0 :     Lazy::force(&TENANT);
    3216            0 : 
    3217            0 :     // Tenant manager stats
    3218            0 :     Lazy::force(&TENANT_MANAGER);
    3219            0 : 
    3220            0 :     Lazy::force(&crate::tenant::storage_layer::layer::LAYER_IMPL_METRICS);
    3221            0 :     Lazy::force(&disk_usage_based_eviction::METRICS);
    3222              : 
    3223            0 :     for state_name in pageserver_api::models::TenantState::VARIANTS {
    3224            0 :         // initialize the metric for all gauges, otherwise the time series might seemingly show
    3225            0 :         // values from last restart.
    3226            0 :         TENANT_STATE_METRIC.with_label_values(&[state_name]).set(0);
    3227            0 :     }
    3228              : 
    3229              :     // countervecs
    3230            0 :     [&BACKGROUND_LOOP_PERIOD_OVERRUN_COUNT]
    3231            0 :         .into_iter()
    3232            0 :         .for_each(|c| {
    3233            0 :             Lazy::force(c);
    3234            0 :         });
    3235            0 : 
    3236            0 :     // gauges
    3237            0 :     WALRECEIVER_ACTIVE_MANAGERS.get();
    3238            0 : 
    3239            0 :     // histograms
    3240            0 :     [
    3241            0 :         &READ_NUM_LAYERS_VISITED,
    3242            0 :         &VEC_READ_NUM_LAYERS_VISITED,
    3243            0 :         &WAIT_LSN_TIME,
    3244            0 :         &WAL_REDO_TIME,
    3245            0 :         &WAL_REDO_RECORDS_HISTOGRAM,
    3246            0 :         &WAL_REDO_BYTES_HISTOGRAM,
    3247            0 :         &WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM,
    3248            0 :     ]
    3249            0 :     .into_iter()
    3250            0 :     .for_each(|h| {
    3251            0 :         Lazy::force(h);
    3252            0 :     });
    3253            0 : 
    3254            0 :     // Custom
    3255            0 :     Lazy::force(&RECONSTRUCT_TIME);
    3256            0 :     Lazy::force(&tenant_throttling::TIMELINE_GET);
    3257            0 :     Lazy::force(&BASEBACKUP_QUERY_TIME);
    3258            0 :     Lazy::force(&COMPUTE_COMMANDS_COUNTERS);
    3259            0 : }
        

Generated by: LCOV version 2.1-beta