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

Generated by: LCOV version 2.1-beta