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