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