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