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