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 626490 : pub(crate) fn for_get_kind(&self, get_kind: GetKind) -> &Histogram {
140 626490 : match get_kind {
141 626066 : GetKind::Singular => &self.singular,
142 424 : GetKind::Vectored => &self.vectored,
143 : }
144 626490 : }
145 : }
146 :
147 : pub(crate) struct ReconstructDataTimeMetrics {
148 : singular: Histogram,
149 : vectored: Histogram,
150 : }
151 :
152 : impl ReconstructDataTimeMetrics {
153 626506 : pub(crate) fn for_get_kind(&self, get_kind: GetKind) -> &Histogram {
154 626506 : match get_kind {
155 626082 : GetKind::Singular => &self.singular,
156 424 : GetKind::Vectored => &self.vectored,
157 : }
158 626506 : }
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 1101436 : pub(crate) fn for_ctx(&self, ctx: &RequestContext) -> &PageCacheMetricsForTaskKind {
336 1101436 : &self.map[ctx.task_kind()][ctx.page_content_kind()]
337 1101436 : }
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 32007 : 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 32007 : match outcome {
416 1476 : Outcome::FoundSlotUnused { iters } => dry!("found_empty", iters),
417 30531 : Outcome::FoundSlotEvicted { iters } => {
418 30531 : 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 32007 : }
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 2277116 : pub(crate) fn get(&self, op: StorageIoOperation) -> &Histogram {
1129 2277116 : &self.metrics[op as usize]
1130 2277116 : }
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 30 : pub(crate) static DELETION_QUEUE: Lazy<DeletionQueueMetrics> = Lazy::new(|| {
1770 30 : DeletionQueueMetrics{
1771 30 :
1772 30 : keys_submitted: register_int_counter!(
1773 30 : "pageserver_deletion_queue_submitted_total",
1774 30 : "Number of objects submitted for deletion"
1775 30 : )
1776 30 : .expect("failed to define a metric"),
1777 30 :
1778 30 : keys_dropped: register_int_counter!(
1779 30 : "pageserver_deletion_queue_dropped_total",
1780 30 : "Number of object deletions dropped due to stale generation."
1781 30 : )
1782 30 : .expect("failed to define a metric"),
1783 30 :
1784 30 : keys_executed: register_int_counter!(
1785 30 : "pageserver_deletion_queue_executed_total",
1786 30 : "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 30 : )
1788 30 : .expect("failed to define a metric"),
1789 30 :
1790 30 : keys_validated: register_int_counter!(
1791 30 : "pageserver_deletion_queue_validated_total",
1792 30 : "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 30 : )
1794 30 : .expect("failed to define a metric"),
1795 30 :
1796 30 : dropped_lsn_updates: register_int_counter!(
1797 30 : "pageserver_deletion_queue_dropped_lsn_updates_total",
1798 30 : "Updates to remote_consistent_lsn dropped due to stale generation number."
1799 30 : )
1800 30 : .expect("failed to define a metric"),
1801 30 : unexpected_errors: register_int_counter!(
1802 30 : "pageserver_deletion_queue_unexpected_errors_total",
1803 30 : "Number of unexpected condiions that may stall the queue: any value above zero is unexpected."
1804 30 : )
1805 30 : .expect("failed to define a metric"),
1806 30 : remote_errors: register_int_counter_vec!(
1807 30 : "pageserver_deletion_queue_remote_errors_total",
1808 30 : "Retryable remote I/O errors while executing deletions, for example 503 responses to DeleteObjects",
1809 30 : &["op_kind"],
1810 30 : )
1811 30 : .expect("failed to define a metric")
1812 30 : }
1813 30 : });
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 13638 : pub fn as_str(&self) -> &'static str {
1886 13638 : match self {
1887 12827 : Self::Upload => "upload",
1888 52 : Self::Download => "download",
1889 759 : Self::Delete => "delete",
1890 : }
1891 13638 : }
1892 : }
1893 :
1894 : #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
1895 : pub enum RemoteOpFileKind {
1896 : Layer,
1897 : Index,
1898 : }
1899 : impl RemoteOpFileKind {
1900 13638 : pub fn as_str(&self) -> &'static str {
1901 13638 : match self {
1902 9378 : Self::Layer => "layer",
1903 4260 : Self::Index => "index",
1904 : }
1905 13638 : }
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 : }
2096 :
2097 2 : pub(crate) static WAL_INGEST: Lazy<WalIngestMetrics> = Lazy::new(|| WalIngestMetrics {
2098 2 : bytes_received: register_int_counter!(
2099 2 : "pageserver_wal_ingest_bytes_received",
2100 2 : "Bytes of WAL ingested from safekeepers",
2101 2 : )
2102 2 : .unwrap(),
2103 2 : records_received: register_int_counter!(
2104 2 : "pageserver_wal_ingest_records_received",
2105 2 : "Number of WAL records received from safekeepers"
2106 2 : )
2107 2 : .expect("failed to define a metric"),
2108 2 : records_committed: register_int_counter!(
2109 2 : "pageserver_wal_ingest_records_committed",
2110 2 : "Number of WAL records which resulted in writes to pageserver storage"
2111 2 : )
2112 2 : .expect("failed to define a metric"),
2113 2 : records_filtered: register_int_counter!(
2114 2 : "pageserver_wal_ingest_records_filtered",
2115 2 : "Number of WAL records filtered out due to sharding"
2116 2 : )
2117 2 : .expect("failed to define a metric"),
2118 2 : });
2119 :
2120 6 : pub(crate) static WAL_REDO_TIME: Lazy<Histogram> = Lazy::new(|| {
2121 6 : register_histogram!(
2122 6 : "pageserver_wal_redo_seconds",
2123 6 : "Time spent on WAL redo",
2124 6 : redo_histogram_time_buckets!()
2125 6 : )
2126 6 : .expect("failed to define a metric")
2127 6 : });
2128 :
2129 6 : pub(crate) static WAL_REDO_RECORDS_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
2130 6 : register_histogram!(
2131 6 : "pageserver_wal_redo_records_histogram",
2132 6 : "Histogram of number of records replayed per redo in the Postgres WAL redo process",
2133 6 : redo_histogram_count_buckets!(),
2134 6 : )
2135 6 : .expect("failed to define a metric")
2136 6 : });
2137 :
2138 6 : pub(crate) static WAL_REDO_BYTES_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
2139 6 : register_histogram!(
2140 6 : "pageserver_wal_redo_bytes_histogram",
2141 6 : "Histogram of number of records replayed per redo sent to Postgres",
2142 6 : redo_bytes_histogram_count_buckets!(),
2143 6 : )
2144 6 : .expect("failed to define a metric")
2145 6 : });
2146 :
2147 : // FIXME: isn't this already included by WAL_REDO_RECORDS_HISTOGRAM which has _count?
2148 6 : pub(crate) static WAL_REDO_RECORD_COUNTER: Lazy<IntCounter> = Lazy::new(|| {
2149 6 : register_int_counter!(
2150 6 : "pageserver_replayed_wal_records_total",
2151 6 : "Number of WAL records replayed in WAL redo process"
2152 6 : )
2153 6 : .unwrap()
2154 6 : });
2155 :
2156 : #[rustfmt::skip]
2157 8 : pub(crate) static WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM: Lazy<Histogram> = Lazy::new(|| {
2158 8 : register_histogram!(
2159 8 : "pageserver_wal_redo_process_launch_duration",
2160 8 : "Histogram of the duration of successful WalRedoProcess::launch calls",
2161 8 : vec![
2162 8 : 0.0002, 0.0004, 0.0006, 0.0008, 0.0010,
2163 8 : 0.0020, 0.0040, 0.0060, 0.0080, 0.0100,
2164 8 : 0.0200, 0.0400, 0.0600, 0.0800, 0.1000,
2165 8 : 0.2000, 0.4000, 0.6000, 0.8000, 1.0000,
2166 8 : 1.5000, 2.0000, 2.5000, 3.0000, 4.0000, 10.0000
2167 8 : ],
2168 8 : )
2169 8 : .expect("failed to define a metric")
2170 8 : });
2171 :
2172 : pub(crate) struct WalRedoProcessCounters {
2173 : pub(crate) started: IntCounter,
2174 : pub(crate) killed_by_cause: enum_map::EnumMap<WalRedoKillCause, IntCounter>,
2175 : pub(crate) active_stderr_logger_tasks_started: IntCounter,
2176 : pub(crate) active_stderr_logger_tasks_finished: IntCounter,
2177 : }
2178 :
2179 24 : #[derive(Debug, enum_map::Enum, strum_macros::IntoStaticStr)]
2180 : pub(crate) enum WalRedoKillCause {
2181 : WalRedoProcessDrop,
2182 : NoLeakChildDrop,
2183 : Startup,
2184 : }
2185 :
2186 : impl Default for WalRedoProcessCounters {
2187 8 : fn default() -> Self {
2188 8 : let started = register_int_counter!(
2189 8 : "pageserver_wal_redo_process_started_total",
2190 8 : "Number of WAL redo processes started",
2191 8 : )
2192 8 : .unwrap();
2193 8 :
2194 8 : let killed = register_int_counter_vec!(
2195 8 : "pageserver_wal_redo_process_stopped_total",
2196 8 : "Number of WAL redo processes stopped",
2197 8 : &["cause"],
2198 8 : )
2199 8 : .unwrap();
2200 8 :
2201 8 : let active_stderr_logger_tasks_started = register_int_counter!(
2202 8 : "pageserver_walredo_stderr_logger_tasks_started_total",
2203 8 : "Number of active walredo stderr logger tasks that have started",
2204 8 : )
2205 8 : .unwrap();
2206 8 :
2207 8 : let active_stderr_logger_tasks_finished = register_int_counter!(
2208 8 : "pageserver_walredo_stderr_logger_tasks_finished_total",
2209 8 : "Number of active walredo stderr logger tasks that have finished",
2210 8 : )
2211 8 : .unwrap();
2212 8 :
2213 8 : Self {
2214 8 : started,
2215 24 : killed_by_cause: EnumMap::from_array(std::array::from_fn(|i| {
2216 24 : let cause = <WalRedoKillCause as enum_map::Enum>::from_usize(i);
2217 24 : let cause_str: &'static str = cause.into();
2218 24 : killed.with_label_values(&[cause_str])
2219 24 : })),
2220 8 : active_stderr_logger_tasks_started,
2221 8 : active_stderr_logger_tasks_finished,
2222 8 : }
2223 8 : }
2224 : }
2225 :
2226 : pub(crate) static WAL_REDO_PROCESS_COUNTERS: Lazy<WalRedoProcessCounters> =
2227 : Lazy::new(WalRedoProcessCounters::default);
2228 :
2229 : /// Similar to `prometheus::HistogramTimer` but does not record on drop.
2230 : pub(crate) struct StorageTimeMetricsTimer {
2231 : metrics: StorageTimeMetrics,
2232 : start: Instant,
2233 : }
2234 :
2235 : impl StorageTimeMetricsTimer {
2236 3348 : fn new(metrics: StorageTimeMetrics) -> Self {
2237 3348 : Self {
2238 3348 : metrics,
2239 3348 : start: Instant::now(),
2240 3348 : }
2241 3348 : }
2242 :
2243 : /// Record the time from creation to now.
2244 2220 : pub fn stop_and_record(self) {
2245 2220 : let duration = self.start.elapsed().as_secs_f64();
2246 2220 : self.metrics.timeline_sum.inc_by(duration);
2247 2220 : self.metrics.timeline_count.inc();
2248 2220 : self.metrics.global_histogram.observe(duration);
2249 2220 : }
2250 :
2251 : /// Turns this timer into a timer, which will always record -- usually this means recording
2252 : /// regardless an early `?` path was taken in a function.
2253 4 : pub(crate) fn record_on_drop(self) -> AlwaysRecordingStorageTimeMetricsTimer {
2254 4 : AlwaysRecordingStorageTimeMetricsTimer(Some(self))
2255 4 : }
2256 : }
2257 :
2258 : pub(crate) struct AlwaysRecordingStorageTimeMetricsTimer(Option<StorageTimeMetricsTimer>);
2259 :
2260 : impl Drop for AlwaysRecordingStorageTimeMetricsTimer {
2261 4 : fn drop(&mut self) {
2262 4 : if let Some(inner) = self.0.take() {
2263 4 : inner.stop_and_record();
2264 4 : }
2265 4 : }
2266 : }
2267 :
2268 : /// Timing facilities for an globally histogrammed metric, which is supported by per tenant and
2269 : /// timeline total sum and count.
2270 : #[derive(Clone, Debug)]
2271 : pub(crate) struct StorageTimeMetrics {
2272 : /// Sum of f64 seconds, per operation, tenant_id and timeline_id
2273 : timeline_sum: Counter,
2274 : /// Number of oeprations, per operation, tenant_id and timeline_id
2275 : timeline_count: IntCounter,
2276 : /// Global histogram having only the "operation" label.
2277 : global_histogram: Histogram,
2278 : }
2279 :
2280 : impl StorageTimeMetrics {
2281 3280 : pub fn new(
2282 3280 : operation: StorageTimeOperation,
2283 3280 : tenant_id: &str,
2284 3280 : shard_id: &str,
2285 3280 : timeline_id: &str,
2286 3280 : ) -> Self {
2287 3280 : let operation: &'static str = operation.into();
2288 3280 :
2289 3280 : let timeline_sum = STORAGE_TIME_SUM_PER_TIMELINE
2290 3280 : .get_metric_with_label_values(&[operation, tenant_id, shard_id, timeline_id])
2291 3280 : .unwrap();
2292 3280 : let timeline_count = STORAGE_TIME_COUNT_PER_TIMELINE
2293 3280 : .get_metric_with_label_values(&[operation, tenant_id, shard_id, timeline_id])
2294 3280 : .unwrap();
2295 3280 : let global_histogram = STORAGE_TIME_GLOBAL
2296 3280 : .get_metric_with_label_values(&[operation])
2297 3280 : .unwrap();
2298 3280 :
2299 3280 : StorageTimeMetrics {
2300 3280 : timeline_sum,
2301 3280 : timeline_count,
2302 3280 : global_histogram,
2303 3280 : }
2304 3280 : }
2305 :
2306 : /// Starts timing a new operation.
2307 : ///
2308 : /// Note: unlike `prometheus::HistogramTimer` the returned timer does not record on drop.
2309 3348 : pub fn start_timer(&self) -> StorageTimeMetricsTimer {
2310 3348 : StorageTimeMetricsTimer::new(self.clone())
2311 3348 : }
2312 : }
2313 :
2314 : #[derive(Debug)]
2315 : pub(crate) struct TimelineMetrics {
2316 : tenant_id: String,
2317 : shard_id: String,
2318 : timeline_id: String,
2319 : pub flush_time_histo: StorageTimeMetrics,
2320 : pub compact_time_histo: StorageTimeMetrics,
2321 : pub create_images_time_histo: StorageTimeMetrics,
2322 : pub logical_size_histo: StorageTimeMetrics,
2323 : pub imitate_logical_size_histo: StorageTimeMetrics,
2324 : pub load_layer_map_histo: StorageTimeMetrics,
2325 : pub garbage_collect_histo: StorageTimeMetrics,
2326 : pub find_gc_cutoffs_histo: StorageTimeMetrics,
2327 : pub last_record_gauge: IntGauge,
2328 : pub pitr_history_size: UIntGauge,
2329 : pub archival_size: UIntGauge,
2330 : pub(crate) layer_size_image: UIntGauge,
2331 : pub(crate) layer_count_image: UIntGauge,
2332 : pub(crate) layer_size_delta: UIntGauge,
2333 : pub(crate) layer_count_delta: UIntGauge,
2334 : pub standby_horizon_gauge: IntGauge,
2335 : pub resident_physical_size_gauge: UIntGauge,
2336 : pub visible_physical_size_gauge: UIntGauge,
2337 : /// copy of LayeredTimeline.current_logical_size
2338 : pub current_logical_size_gauge: UIntGauge,
2339 : pub aux_file_size_gauge: IntGauge,
2340 : pub directory_entries_count_gauge: Lazy<UIntGauge, Box<dyn Send + Fn() -> UIntGauge>>,
2341 : pub evictions: IntCounter,
2342 : pub evictions_with_low_residence_duration: std::sync::RwLock<EvictionsWithLowResidenceDuration>,
2343 : /// Number of valid LSN leases.
2344 : pub valid_lsn_lease_count_gauge: UIntGauge,
2345 : shutdown: std::sync::atomic::AtomicBool,
2346 : }
2347 :
2348 : impl TimelineMetrics {
2349 410 : pub fn new(
2350 410 : tenant_shard_id: &TenantShardId,
2351 410 : timeline_id_raw: &TimelineId,
2352 410 : evictions_with_low_residence_duration_builder: EvictionsWithLowResidenceDurationBuilder,
2353 410 : ) -> Self {
2354 410 : let tenant_id = tenant_shard_id.tenant_id.to_string();
2355 410 : let shard_id = format!("{}", tenant_shard_id.shard_slug());
2356 410 : let timeline_id = timeline_id_raw.to_string();
2357 410 : let flush_time_histo = StorageTimeMetrics::new(
2358 410 : StorageTimeOperation::LayerFlush,
2359 410 : &tenant_id,
2360 410 : &shard_id,
2361 410 : &timeline_id,
2362 410 : );
2363 410 : let compact_time_histo = StorageTimeMetrics::new(
2364 410 : StorageTimeOperation::Compact,
2365 410 : &tenant_id,
2366 410 : &shard_id,
2367 410 : &timeline_id,
2368 410 : );
2369 410 : let create_images_time_histo = StorageTimeMetrics::new(
2370 410 : StorageTimeOperation::CreateImages,
2371 410 : &tenant_id,
2372 410 : &shard_id,
2373 410 : &timeline_id,
2374 410 : );
2375 410 : let logical_size_histo = StorageTimeMetrics::new(
2376 410 : StorageTimeOperation::LogicalSize,
2377 410 : &tenant_id,
2378 410 : &shard_id,
2379 410 : &timeline_id,
2380 410 : );
2381 410 : let imitate_logical_size_histo = StorageTimeMetrics::new(
2382 410 : StorageTimeOperation::ImitateLogicalSize,
2383 410 : &tenant_id,
2384 410 : &shard_id,
2385 410 : &timeline_id,
2386 410 : );
2387 410 : let load_layer_map_histo = StorageTimeMetrics::new(
2388 410 : StorageTimeOperation::LoadLayerMap,
2389 410 : &tenant_id,
2390 410 : &shard_id,
2391 410 : &timeline_id,
2392 410 : );
2393 410 : let garbage_collect_histo = StorageTimeMetrics::new(
2394 410 : StorageTimeOperation::Gc,
2395 410 : &tenant_id,
2396 410 : &shard_id,
2397 410 : &timeline_id,
2398 410 : );
2399 410 : let find_gc_cutoffs_histo = StorageTimeMetrics::new(
2400 410 : StorageTimeOperation::FindGcCutoffs,
2401 410 : &tenant_id,
2402 410 : &shard_id,
2403 410 : &timeline_id,
2404 410 : );
2405 410 : let last_record_gauge = LAST_RECORD_LSN
2406 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2407 410 : .unwrap();
2408 410 :
2409 410 : let pitr_history_size = PITR_HISTORY_SIZE
2410 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2411 410 : .unwrap();
2412 410 :
2413 410 : let archival_size = TIMELINE_ARCHIVE_SIZE
2414 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2415 410 : .unwrap();
2416 410 :
2417 410 : let layer_size_image = TIMELINE_LAYER_SIZE
2418 410 : .get_metric_with_label_values(&[
2419 410 : &tenant_id,
2420 410 : &shard_id,
2421 410 : &timeline_id,
2422 410 : MetricLayerKind::Image.into(),
2423 410 : ])
2424 410 : .unwrap();
2425 410 :
2426 410 : let layer_count_image = TIMELINE_LAYER_COUNT
2427 410 : .get_metric_with_label_values(&[
2428 410 : &tenant_id,
2429 410 : &shard_id,
2430 410 : &timeline_id,
2431 410 : MetricLayerKind::Image.into(),
2432 410 : ])
2433 410 : .unwrap();
2434 410 :
2435 410 : let layer_size_delta = TIMELINE_LAYER_SIZE
2436 410 : .get_metric_with_label_values(&[
2437 410 : &tenant_id,
2438 410 : &shard_id,
2439 410 : &timeline_id,
2440 410 : MetricLayerKind::Delta.into(),
2441 410 : ])
2442 410 : .unwrap();
2443 410 :
2444 410 : let layer_count_delta = TIMELINE_LAYER_COUNT
2445 410 : .get_metric_with_label_values(&[
2446 410 : &tenant_id,
2447 410 : &shard_id,
2448 410 : &timeline_id,
2449 410 : MetricLayerKind::Delta.into(),
2450 410 : ])
2451 410 : .unwrap();
2452 410 :
2453 410 : let standby_horizon_gauge = STANDBY_HORIZON
2454 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2455 410 : .unwrap();
2456 410 : let resident_physical_size_gauge = RESIDENT_PHYSICAL_SIZE
2457 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2458 410 : .unwrap();
2459 410 : let visible_physical_size_gauge = VISIBLE_PHYSICAL_SIZE
2460 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2461 410 : .unwrap();
2462 410 : // TODO: we shouldn't expose this metric
2463 410 : let current_logical_size_gauge = CURRENT_LOGICAL_SIZE
2464 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2465 410 : .unwrap();
2466 410 : let aux_file_size_gauge = AUX_FILE_SIZE
2467 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2468 410 : .unwrap();
2469 410 : // TODO use impl Trait syntax here once we have ability to use it: https://github.com/rust-lang/rust/issues/63065
2470 410 : let directory_entries_count_gauge_closure = {
2471 410 : let tenant_shard_id = *tenant_shard_id;
2472 410 : let timeline_id_raw = *timeline_id_raw;
2473 0 : move || {
2474 0 : let tenant_id = tenant_shard_id.tenant_id.to_string();
2475 0 : let shard_id = format!("{}", tenant_shard_id.shard_slug());
2476 0 : let timeline_id = timeline_id_raw.to_string();
2477 0 : let gauge: UIntGauge = DIRECTORY_ENTRIES_COUNT
2478 0 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2479 0 : .unwrap();
2480 0 : gauge
2481 0 : }
2482 : };
2483 410 : let directory_entries_count_gauge: Lazy<UIntGauge, Box<dyn Send + Fn() -> UIntGauge>> =
2484 410 : Lazy::new(Box::new(directory_entries_count_gauge_closure));
2485 410 : let evictions = EVICTIONS
2486 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2487 410 : .unwrap();
2488 410 : let evictions_with_low_residence_duration = evictions_with_low_residence_duration_builder
2489 410 : .build(&tenant_id, &shard_id, &timeline_id);
2490 410 :
2491 410 : let valid_lsn_lease_count_gauge = VALID_LSN_LEASE_COUNT
2492 410 : .get_metric_with_label_values(&[&tenant_id, &shard_id, &timeline_id])
2493 410 : .unwrap();
2494 410 :
2495 410 : TimelineMetrics {
2496 410 : tenant_id,
2497 410 : shard_id,
2498 410 : timeline_id,
2499 410 : flush_time_histo,
2500 410 : compact_time_histo,
2501 410 : create_images_time_histo,
2502 410 : logical_size_histo,
2503 410 : imitate_logical_size_histo,
2504 410 : garbage_collect_histo,
2505 410 : find_gc_cutoffs_histo,
2506 410 : load_layer_map_histo,
2507 410 : last_record_gauge,
2508 410 : pitr_history_size,
2509 410 : archival_size,
2510 410 : layer_size_image,
2511 410 : layer_count_image,
2512 410 : layer_size_delta,
2513 410 : layer_count_delta,
2514 410 : standby_horizon_gauge,
2515 410 : resident_physical_size_gauge,
2516 410 : visible_physical_size_gauge,
2517 410 : current_logical_size_gauge,
2518 410 : aux_file_size_gauge,
2519 410 : directory_entries_count_gauge,
2520 410 : evictions,
2521 410 : evictions_with_low_residence_duration: std::sync::RwLock::new(
2522 410 : evictions_with_low_residence_duration,
2523 410 : ),
2524 410 : valid_lsn_lease_count_gauge,
2525 410 : shutdown: std::sync::atomic::AtomicBool::default(),
2526 410 : }
2527 410 : }
2528 :
2529 1506 : pub(crate) fn record_new_file_metrics(&self, sz: u64) {
2530 1506 : self.resident_physical_size_add(sz);
2531 1506 : }
2532 :
2533 473 : pub(crate) fn resident_physical_size_sub(&self, sz: u64) {
2534 473 : self.resident_physical_size_gauge.sub(sz);
2535 473 : crate::metrics::RESIDENT_PHYSICAL_SIZE_GLOBAL.sub(sz);
2536 473 : }
2537 :
2538 1536 : pub(crate) fn resident_physical_size_add(&self, sz: u64) {
2539 1536 : self.resident_physical_size_gauge.add(sz);
2540 1536 : crate::metrics::RESIDENT_PHYSICAL_SIZE_GLOBAL.add(sz);
2541 1536 : }
2542 :
2543 8 : pub(crate) fn resident_physical_size_get(&self) -> u64 {
2544 8 : self.resident_physical_size_gauge.get()
2545 8 : }
2546 :
2547 8 : pub(crate) fn shutdown(&self) {
2548 8 : let was_shutdown = self
2549 8 : .shutdown
2550 8 : .swap(true, std::sync::atomic::Ordering::Relaxed);
2551 8 :
2552 8 : if was_shutdown {
2553 : // this happens on tenant deletion because tenant first shuts down timelines, then
2554 : // invokes timeline deletion which first shuts down the timeline again.
2555 : // TODO: this can be removed once https://github.com/neondatabase/neon/issues/5080
2556 0 : return;
2557 8 : }
2558 8 :
2559 8 : let tenant_id = &self.tenant_id;
2560 8 : let timeline_id = &self.timeline_id;
2561 8 : let shard_id = &self.shard_id;
2562 8 : let _ = LAST_RECORD_LSN.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2563 8 : let _ = STANDBY_HORIZON.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2564 8 : {
2565 8 : RESIDENT_PHYSICAL_SIZE_GLOBAL.sub(self.resident_physical_size_get());
2566 8 : let _ = RESIDENT_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2567 8 : }
2568 8 : let _ = VISIBLE_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2569 8 : let _ = CURRENT_LOGICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2570 8 : if let Some(metric) = Lazy::get(&DIRECTORY_ENTRIES_COUNT) {
2571 0 : let _ = metric.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2572 8 : }
2573 :
2574 8 : let _ = TIMELINE_ARCHIVE_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2575 8 : let _ = PITR_HISTORY_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2576 8 :
2577 8 : let _ = TIMELINE_LAYER_SIZE.remove_label_values(&[
2578 8 : tenant_id,
2579 8 : shard_id,
2580 8 : timeline_id,
2581 8 : MetricLayerKind::Image.into(),
2582 8 : ]);
2583 8 : let _ = TIMELINE_LAYER_COUNT.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_SIZE.remove_label_values(&[
2590 8 : tenant_id,
2591 8 : shard_id,
2592 8 : timeline_id,
2593 8 : MetricLayerKind::Delta.into(),
2594 8 : ]);
2595 8 : let _ = TIMELINE_LAYER_COUNT.remove_label_values(&[
2596 8 : tenant_id,
2597 8 : shard_id,
2598 8 : timeline_id,
2599 8 : MetricLayerKind::Delta.into(),
2600 8 : ]);
2601 8 :
2602 8 : let _ = EVICTIONS.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2603 8 : let _ = AUX_FILE_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2604 8 : let _ = VALID_LSN_LEASE_COUNT.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2605 8 :
2606 8 : self.evictions_with_low_residence_duration
2607 8 : .write()
2608 8 : .unwrap()
2609 8 : .remove(tenant_id, shard_id, timeline_id);
2610 :
2611 : // The following metrics are born outside of the TimelineMetrics lifecycle but still
2612 : // removed at the end of it. The idea is to have the metrics outlive the
2613 : // entity during which they're observed, e.g., the smgr metrics shall
2614 : // outlive an individual smgr connection, but not the timeline.
2615 :
2616 72 : for op in StorageTimeOperation::VARIANTS {
2617 64 : let _ = STORAGE_TIME_SUM_PER_TIMELINE.remove_label_values(&[
2618 64 : op,
2619 64 : tenant_id,
2620 64 : shard_id,
2621 64 : timeline_id,
2622 64 : ]);
2623 64 : let _ = STORAGE_TIME_COUNT_PER_TIMELINE.remove_label_values(&[
2624 64 : op,
2625 64 : tenant_id,
2626 64 : shard_id,
2627 64 : timeline_id,
2628 64 : ]);
2629 64 : }
2630 :
2631 24 : for op in STORAGE_IO_SIZE_OPERATIONS {
2632 16 : let _ = STORAGE_IO_SIZE.remove_label_values(&[op, tenant_id, shard_id, timeline_id]);
2633 16 : }
2634 :
2635 8 : let _ = SMGR_QUERY_STARTED_PER_TENANT_TIMELINE.remove_label_values(&[
2636 8 : SmgrQueryType::GetPageAtLsn.into(),
2637 8 : tenant_id,
2638 8 : shard_id,
2639 8 : timeline_id,
2640 8 : ]);
2641 8 : let _ = SMGR_QUERY_TIME_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 : }
2648 : }
2649 :
2650 6 : pub(crate) fn remove_tenant_metrics(tenant_shard_id: &TenantShardId) {
2651 6 : // Only shard zero deals in synthetic sizes
2652 6 : if tenant_shard_id.is_shard_zero() {
2653 6 : let tid = tenant_shard_id.tenant_id.to_string();
2654 6 : let _ = TENANT_SYNTHETIC_SIZE_METRIC.remove_label_values(&[&tid]);
2655 6 : }
2656 :
2657 6 : tenant_throttling::remove_tenant_metrics(tenant_shard_id);
2658 6 :
2659 6 : // we leave the BROKEN_TENANTS_SET entry if any
2660 6 : }
2661 :
2662 : use futures::Future;
2663 : use pin_project_lite::pin_project;
2664 : use std::collections::HashMap;
2665 : use std::num::NonZeroUsize;
2666 : use std::pin::Pin;
2667 : use std::sync::atomic::AtomicU64;
2668 : use std::sync::{Arc, Mutex};
2669 : use std::task::{Context, Poll};
2670 : use std::time::{Duration, Instant};
2671 :
2672 : use crate::context::{PageContentKind, RequestContext};
2673 : use crate::task_mgr::TaskKind;
2674 : use crate::tenant::mgr::TenantSlot;
2675 : use crate::tenant::tasks::BackgroundLoopKind;
2676 :
2677 : /// Maintain a per timeline gauge in addition to the global gauge.
2678 : pub(crate) struct PerTimelineRemotePhysicalSizeGauge {
2679 : last_set: AtomicU64,
2680 : gauge: UIntGauge,
2681 : }
2682 :
2683 : impl PerTimelineRemotePhysicalSizeGauge {
2684 420 : fn new(per_timeline_gauge: UIntGauge) -> Self {
2685 420 : Self {
2686 420 : last_set: AtomicU64::new(0),
2687 420 : gauge: per_timeline_gauge,
2688 420 : }
2689 420 : }
2690 1806 : pub(crate) fn set(&self, sz: u64) {
2691 1806 : self.gauge.set(sz);
2692 1806 : let prev = self.last_set.swap(sz, std::sync::atomic::Ordering::Relaxed);
2693 1806 : if sz < prev {
2694 22 : REMOTE_PHYSICAL_SIZE_GLOBAL.sub(prev - sz);
2695 1784 : } else {
2696 1784 : REMOTE_PHYSICAL_SIZE_GLOBAL.add(sz - prev);
2697 1784 : };
2698 1806 : }
2699 2 : pub(crate) fn get(&self) -> u64 {
2700 2 : self.gauge.get()
2701 2 : }
2702 : }
2703 :
2704 : impl Drop for PerTimelineRemotePhysicalSizeGauge {
2705 18 : fn drop(&mut self) {
2706 18 : REMOTE_PHYSICAL_SIZE_GLOBAL.sub(self.last_set.load(std::sync::atomic::Ordering::Relaxed));
2707 18 : }
2708 : }
2709 :
2710 : pub(crate) struct RemoteTimelineClientMetrics {
2711 : tenant_id: String,
2712 : shard_id: String,
2713 : timeline_id: String,
2714 : pub(crate) remote_physical_size_gauge: PerTimelineRemotePhysicalSizeGauge,
2715 : calls: Mutex<HashMap<(&'static str, &'static str), IntCounterPair>>,
2716 : bytes_started_counter: Mutex<HashMap<(&'static str, &'static str), IntCounter>>,
2717 : bytes_finished_counter: Mutex<HashMap<(&'static str, &'static str), IntCounter>>,
2718 : }
2719 :
2720 : impl RemoteTimelineClientMetrics {
2721 420 : pub fn new(tenant_shard_id: &TenantShardId, timeline_id: &TimelineId) -> Self {
2722 420 : let tenant_id_str = tenant_shard_id.tenant_id.to_string();
2723 420 : let shard_id_str = format!("{}", tenant_shard_id.shard_slug());
2724 420 : let timeline_id_str = timeline_id.to_string();
2725 420 :
2726 420 : let remote_physical_size_gauge = PerTimelineRemotePhysicalSizeGauge::new(
2727 420 : REMOTE_PHYSICAL_SIZE
2728 420 : .get_metric_with_label_values(&[&tenant_id_str, &shard_id_str, &timeline_id_str])
2729 420 : .unwrap(),
2730 420 : );
2731 420 :
2732 420 : RemoteTimelineClientMetrics {
2733 420 : tenant_id: tenant_id_str,
2734 420 : shard_id: shard_id_str,
2735 420 : timeline_id: timeline_id_str,
2736 420 : calls: Mutex::new(HashMap::default()),
2737 420 : bytes_started_counter: Mutex::new(HashMap::default()),
2738 420 : bytes_finished_counter: Mutex::new(HashMap::default()),
2739 420 : remote_physical_size_gauge,
2740 420 : }
2741 420 : }
2742 :
2743 2773 : pub fn remote_operation_time(
2744 2773 : &self,
2745 2773 : file_kind: &RemoteOpFileKind,
2746 2773 : op_kind: &RemoteOpKind,
2747 2773 : status: &'static str,
2748 2773 : ) -> Histogram {
2749 2773 : let key = (file_kind.as_str(), op_kind.as_str(), status);
2750 2773 : REMOTE_OPERATION_TIME
2751 2773 : .get_metric_with_label_values(&[key.0, key.1, key.2])
2752 2773 : .unwrap()
2753 2773 : }
2754 :
2755 6474 : fn calls_counter_pair(
2756 6474 : &self,
2757 6474 : file_kind: &RemoteOpFileKind,
2758 6474 : op_kind: &RemoteOpKind,
2759 6474 : ) -> IntCounterPair {
2760 6474 : let mut guard = self.calls.lock().unwrap();
2761 6474 : let key = (file_kind.as_str(), op_kind.as_str());
2762 6474 : let metric = guard.entry(key).or_insert_with(move || {
2763 735 : REMOTE_TIMELINE_CLIENT_CALLS
2764 735 : .get_metric_with_label_values(&[
2765 735 : &self.tenant_id,
2766 735 : &self.shard_id,
2767 735 : &self.timeline_id,
2768 735 : key.0,
2769 735 : key.1,
2770 735 : ])
2771 735 : .unwrap()
2772 6474 : });
2773 6474 : metric.clone()
2774 6474 : }
2775 :
2776 1514 : fn bytes_started_counter(
2777 1514 : &self,
2778 1514 : file_kind: &RemoteOpFileKind,
2779 1514 : op_kind: &RemoteOpKind,
2780 1514 : ) -> IntCounter {
2781 1514 : let mut guard = self.bytes_started_counter.lock().unwrap();
2782 1514 : let key = (file_kind.as_str(), op_kind.as_str());
2783 1514 : let metric = guard.entry(key).or_insert_with(move || {
2784 284 : REMOTE_TIMELINE_CLIENT_BYTES_STARTED_COUNTER
2785 284 : .get_metric_with_label_values(&[
2786 284 : &self.tenant_id,
2787 284 : &self.shard_id,
2788 284 : &self.timeline_id,
2789 284 : key.0,
2790 284 : key.1,
2791 284 : ])
2792 284 : .unwrap()
2793 1514 : });
2794 1514 : metric.clone()
2795 1514 : }
2796 :
2797 2865 : fn bytes_finished_counter(
2798 2865 : &self,
2799 2865 : file_kind: &RemoteOpFileKind,
2800 2865 : op_kind: &RemoteOpKind,
2801 2865 : ) -> IntCounter {
2802 2865 : let mut guard = self.bytes_finished_counter.lock().unwrap();
2803 2865 : let key = (file_kind.as_str(), op_kind.as_str());
2804 2865 : let metric = guard.entry(key).or_insert_with(move || {
2805 284 : REMOTE_TIMELINE_CLIENT_BYTES_FINISHED_COUNTER
2806 284 : .get_metric_with_label_values(&[
2807 284 : &self.tenant_id,
2808 284 : &self.shard_id,
2809 284 : &self.timeline_id,
2810 284 : key.0,
2811 284 : key.1,
2812 284 : ])
2813 284 : .unwrap()
2814 2865 : });
2815 2865 : metric.clone()
2816 2865 : }
2817 : }
2818 :
2819 : #[cfg(test)]
2820 : impl RemoteTimelineClientMetrics {
2821 6 : pub fn get_bytes_started_counter_value(
2822 6 : &self,
2823 6 : file_kind: &RemoteOpFileKind,
2824 6 : op_kind: &RemoteOpKind,
2825 6 : ) -> Option<u64> {
2826 6 : let guard = self.bytes_started_counter.lock().unwrap();
2827 6 : let key = (file_kind.as_str(), op_kind.as_str());
2828 6 : guard.get(&key).map(|counter| counter.get())
2829 6 : }
2830 :
2831 6 : pub fn get_bytes_finished_counter_value(
2832 6 : &self,
2833 6 : file_kind: &RemoteOpFileKind,
2834 6 : op_kind: &RemoteOpKind,
2835 6 : ) -> Option<u64> {
2836 6 : let guard = self.bytes_finished_counter.lock().unwrap();
2837 6 : let key = (file_kind.as_str(), op_kind.as_str());
2838 6 : guard.get(&key).map(|counter| counter.get())
2839 6 : }
2840 : }
2841 :
2842 : /// See [`RemoteTimelineClientMetrics::call_begin`].
2843 : #[must_use]
2844 : pub(crate) struct RemoteTimelineClientCallMetricGuard {
2845 : /// Decremented on drop.
2846 : calls_counter_pair: Option<IntCounterPair>,
2847 : /// If Some(), this references the bytes_finished metric, and we increment it by the given `u64` on drop.
2848 : bytes_finished: Option<(IntCounter, u64)>,
2849 : }
2850 :
2851 : impl RemoteTimelineClientCallMetricGuard {
2852 : /// Consume this guard object without performing the metric updates it would do on `drop()`.
2853 : /// The caller vouches to do the metric updates manually.
2854 3401 : pub fn will_decrement_manually(mut self) {
2855 3401 : let RemoteTimelineClientCallMetricGuard {
2856 3401 : calls_counter_pair,
2857 3401 : bytes_finished,
2858 3401 : } = &mut self;
2859 3401 : calls_counter_pair.take();
2860 3401 : bytes_finished.take();
2861 3401 : }
2862 : }
2863 :
2864 : impl Drop for RemoteTimelineClientCallMetricGuard {
2865 3427 : fn drop(&mut self) {
2866 3427 : let RemoteTimelineClientCallMetricGuard {
2867 3427 : calls_counter_pair,
2868 3427 : bytes_finished,
2869 3427 : } = self;
2870 3427 : if let Some(guard) = calls_counter_pair.take() {
2871 26 : guard.dec();
2872 3401 : }
2873 3427 : if let Some((bytes_finished_metric, value)) = bytes_finished {
2874 0 : bytes_finished_metric.inc_by(*value);
2875 3427 : }
2876 3427 : }
2877 : }
2878 :
2879 : /// The enum variants communicate to the [`RemoteTimelineClientMetrics`] whether to
2880 : /// track the byte size of this call in applicable metric(s).
2881 : pub(crate) enum RemoteTimelineClientMetricsCallTrackSize {
2882 : /// Do not account for this call's byte size in any metrics.
2883 : /// The `reason` field is there to make the call sites self-documenting
2884 : /// about why they don't need the metric.
2885 : DontTrackSize { reason: &'static str },
2886 : /// Track the byte size of the call in applicable metric(s).
2887 : Bytes(u64),
2888 : }
2889 :
2890 : impl RemoteTimelineClientMetrics {
2891 : /// Update the metrics that change when a call to the remote timeline client instance starts.
2892 : ///
2893 : /// Drop the returned guard object once the operation is finished to updates corresponding metrics that track completions.
2894 : /// Or, use [`RemoteTimelineClientCallMetricGuard::will_decrement_manually`] and [`call_end`](Self::call_end) if that
2895 : /// is more suitable.
2896 : /// Never do both.
2897 3427 : pub(crate) fn call_begin(
2898 3427 : &self,
2899 3427 : file_kind: &RemoteOpFileKind,
2900 3427 : op_kind: &RemoteOpKind,
2901 3427 : size: RemoteTimelineClientMetricsCallTrackSize,
2902 3427 : ) -> RemoteTimelineClientCallMetricGuard {
2903 3427 : let calls_counter_pair = self.calls_counter_pair(file_kind, op_kind);
2904 3427 : calls_counter_pair.inc();
2905 :
2906 3427 : let bytes_finished = match size {
2907 1913 : RemoteTimelineClientMetricsCallTrackSize::DontTrackSize { reason: _reason } => {
2908 1913 : // nothing to do
2909 1913 : None
2910 : }
2911 1514 : RemoteTimelineClientMetricsCallTrackSize::Bytes(size) => {
2912 1514 : self.bytes_started_counter(file_kind, op_kind).inc_by(size);
2913 1514 : let finished_counter = self.bytes_finished_counter(file_kind, op_kind);
2914 1514 : Some((finished_counter, size))
2915 : }
2916 : };
2917 3427 : RemoteTimelineClientCallMetricGuard {
2918 3427 : calls_counter_pair: Some(calls_counter_pair),
2919 3427 : bytes_finished,
2920 3427 : }
2921 3427 : }
2922 :
2923 : /// Manually udpate the metrics that track completions, instead of using the guard object.
2924 : /// Using the guard object is generally preferable.
2925 : /// See [`call_begin`](Self::call_begin) for more context.
2926 3047 : pub(crate) fn call_end(
2927 3047 : &self,
2928 3047 : file_kind: &RemoteOpFileKind,
2929 3047 : op_kind: &RemoteOpKind,
2930 3047 : size: RemoteTimelineClientMetricsCallTrackSize,
2931 3047 : ) {
2932 3047 : let calls_counter_pair = self.calls_counter_pair(file_kind, op_kind);
2933 3047 : calls_counter_pair.dec();
2934 3047 : match size {
2935 1696 : RemoteTimelineClientMetricsCallTrackSize::DontTrackSize { reason: _reason } => {}
2936 1351 : RemoteTimelineClientMetricsCallTrackSize::Bytes(size) => {
2937 1351 : self.bytes_finished_counter(file_kind, op_kind).inc_by(size);
2938 1351 : }
2939 : }
2940 3047 : }
2941 : }
2942 :
2943 : impl Drop for RemoteTimelineClientMetrics {
2944 18 : fn drop(&mut self) {
2945 18 : let RemoteTimelineClientMetrics {
2946 18 : tenant_id,
2947 18 : shard_id,
2948 18 : timeline_id,
2949 18 : remote_physical_size_gauge,
2950 18 : calls,
2951 18 : bytes_started_counter,
2952 18 : bytes_finished_counter,
2953 18 : } = self;
2954 22 : for ((a, b), _) in calls.get_mut().unwrap().drain() {
2955 22 : let mut res = [Ok(()), Ok(())];
2956 22 : REMOTE_TIMELINE_CLIENT_CALLS
2957 22 : .remove_label_values(&mut res, &[tenant_id, shard_id, timeline_id, a, b]);
2958 22 : // don't care about results
2959 22 : }
2960 18 : for ((a, b), _) in bytes_started_counter.get_mut().unwrap().drain() {
2961 6 : let _ = REMOTE_TIMELINE_CLIENT_BYTES_STARTED_COUNTER.remove_label_values(&[
2962 6 : tenant_id,
2963 6 : shard_id,
2964 6 : timeline_id,
2965 6 : a,
2966 6 : b,
2967 6 : ]);
2968 6 : }
2969 18 : for ((a, b), _) in bytes_finished_counter.get_mut().unwrap().drain() {
2970 6 : let _ = REMOTE_TIMELINE_CLIENT_BYTES_FINISHED_COUNTER.remove_label_values(&[
2971 6 : tenant_id,
2972 6 : shard_id,
2973 6 : timeline_id,
2974 6 : a,
2975 6 : b,
2976 6 : ]);
2977 6 : }
2978 18 : {
2979 18 : let _ = remote_physical_size_gauge; // use to avoid 'unused' warning in desctructuring above
2980 18 : let _ = REMOTE_PHYSICAL_SIZE.remove_label_values(&[tenant_id, shard_id, timeline_id]);
2981 18 : }
2982 18 : }
2983 : }
2984 :
2985 : /// Wrapper future that measures the time spent by a remote storage operation,
2986 : /// and records the time and success/failure as a prometheus metric.
2987 : pub(crate) trait MeasureRemoteOp: Sized {
2988 2845 : fn measure_remote_op(
2989 2845 : self,
2990 2845 : file_kind: RemoteOpFileKind,
2991 2845 : op: RemoteOpKind,
2992 2845 : metrics: Arc<RemoteTimelineClientMetrics>,
2993 2845 : ) -> MeasuredRemoteOp<Self> {
2994 2845 : let start = Instant::now();
2995 2845 : MeasuredRemoteOp {
2996 2845 : inner: self,
2997 2845 : file_kind,
2998 2845 : op,
2999 2845 : start,
3000 2845 : metrics,
3001 2845 : }
3002 2845 : }
3003 : }
3004 :
3005 : impl<T: Sized> MeasureRemoteOp for T {}
3006 :
3007 : pin_project! {
3008 : pub(crate) struct MeasuredRemoteOp<F>
3009 : {
3010 : #[pin]
3011 : inner: F,
3012 : file_kind: RemoteOpFileKind,
3013 : op: RemoteOpKind,
3014 : start: Instant,
3015 : metrics: Arc<RemoteTimelineClientMetrics>,
3016 : }
3017 : }
3018 :
3019 : impl<F: Future<Output = Result<O, E>>, O, E> Future for MeasuredRemoteOp<F> {
3020 : type Output = Result<O, E>;
3021 :
3022 44469 : fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
3023 44469 : let this = self.project();
3024 44469 : let poll_result = this.inner.poll(cx);
3025 44469 : if let Poll::Ready(ref res) = poll_result {
3026 2773 : let duration = this.start.elapsed();
3027 2773 : let status = if res.is_ok() { &"success" } else { &"failure" };
3028 2773 : this.metrics
3029 2773 : .remote_operation_time(this.file_kind, this.op, status)
3030 2773 : .observe(duration.as_secs_f64());
3031 41696 : }
3032 44469 : poll_result
3033 44469 : }
3034 : }
3035 :
3036 : pub mod tokio_epoll_uring {
3037 : use metrics::{register_int_counter, UIntGauge};
3038 : use once_cell::sync::Lazy;
3039 :
3040 : pub struct Collector {
3041 : descs: Vec<metrics::core::Desc>,
3042 : systems_created: UIntGauge,
3043 : systems_destroyed: UIntGauge,
3044 : }
3045 :
3046 : impl metrics::core::Collector for Collector {
3047 0 : fn desc(&self) -> Vec<&metrics::core::Desc> {
3048 0 : self.descs.iter().collect()
3049 0 : }
3050 :
3051 0 : fn collect(&self) -> Vec<metrics::proto::MetricFamily> {
3052 0 : let mut mfs = Vec::with_capacity(Self::NMETRICS);
3053 0 : let tokio_epoll_uring::metrics::Metrics {
3054 0 : systems_created,
3055 0 : systems_destroyed,
3056 0 : } = tokio_epoll_uring::metrics::global();
3057 0 : self.systems_created.set(systems_created);
3058 0 : mfs.extend(self.systems_created.collect());
3059 0 : self.systems_destroyed.set(systems_destroyed);
3060 0 : mfs.extend(self.systems_destroyed.collect());
3061 0 : mfs
3062 0 : }
3063 : }
3064 :
3065 : impl Collector {
3066 : const NMETRICS: usize = 2;
3067 :
3068 : #[allow(clippy::new_without_default)]
3069 0 : pub fn new() -> Self {
3070 0 : let mut descs = Vec::new();
3071 0 :
3072 0 : let systems_created = UIntGauge::new(
3073 0 : "pageserver_tokio_epoll_uring_systems_created",
3074 0 : "counter of tokio-epoll-uring systems that were created",
3075 0 : )
3076 0 : .unwrap();
3077 0 : descs.extend(
3078 0 : metrics::core::Collector::desc(&systems_created)
3079 0 : .into_iter()
3080 0 : .cloned(),
3081 0 : );
3082 0 :
3083 0 : let systems_destroyed = UIntGauge::new(
3084 0 : "pageserver_tokio_epoll_uring_systems_destroyed",
3085 0 : "counter of tokio-epoll-uring systems that were destroyed",
3086 0 : )
3087 0 : .unwrap();
3088 0 : descs.extend(
3089 0 : metrics::core::Collector::desc(&systems_destroyed)
3090 0 : .into_iter()
3091 0 : .cloned(),
3092 0 : );
3093 0 :
3094 0 : Self {
3095 0 : descs,
3096 0 : systems_created,
3097 0 : systems_destroyed,
3098 0 : }
3099 0 : }
3100 : }
3101 :
3102 99 : pub(crate) static THREAD_LOCAL_LAUNCH_SUCCESSES: Lazy<metrics::IntCounter> = Lazy::new(|| {
3103 99 : register_int_counter!(
3104 99 : "pageserver_tokio_epoll_uring_pageserver_thread_local_launch_success_count",
3105 99 : "Number of times where thread_local_system creation spanned multiple executor threads",
3106 99 : )
3107 99 : .unwrap()
3108 99 : });
3109 :
3110 0 : pub(crate) static THREAD_LOCAL_LAUNCH_FAILURES: Lazy<metrics::IntCounter> = Lazy::new(|| {
3111 0 : register_int_counter!(
3112 0 : "pageserver_tokio_epoll_uring_pageserver_thread_local_launch_failures_count",
3113 0 : "Number of times thread_local_system creation failed and was retried after back-off.",
3114 0 : )
3115 0 : .unwrap()
3116 0 : });
3117 : }
3118 :
3119 : pub(crate) mod tenant_throttling {
3120 : use metrics::{register_int_counter_vec, IntCounter};
3121 : use once_cell::sync::Lazy;
3122 : use utils::shard::TenantShardId;
3123 :
3124 : use crate::tenant::{self, throttle::Metric};
3125 :
3126 : struct GlobalAndPerTenantIntCounter {
3127 : global: IntCounter,
3128 : per_tenant: IntCounter,
3129 : }
3130 :
3131 : impl GlobalAndPerTenantIntCounter {
3132 : #[inline(always)]
3133 0 : pub(crate) fn inc(&self) {
3134 0 : self.inc_by(1)
3135 0 : }
3136 : #[inline(always)]
3137 0 : pub(crate) fn inc_by(&self, n: u64) {
3138 0 : self.global.inc_by(n);
3139 0 : self.per_tenant.inc_by(n);
3140 0 : }
3141 : }
3142 :
3143 : pub(crate) struct TimelineGet {
3144 : count_accounted_start: GlobalAndPerTenantIntCounter,
3145 : count_accounted_finish: GlobalAndPerTenantIntCounter,
3146 : wait_time: GlobalAndPerTenantIntCounter,
3147 : count_throttled: GlobalAndPerTenantIntCounter,
3148 : }
3149 :
3150 168 : static COUNT_ACCOUNTED_START: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3151 168 : register_int_counter_vec!(
3152 168 : "pageserver_tenant_throttling_count_accounted_start_global",
3153 168 : "Count of tenant throttling starts, by kind of throttle.",
3154 168 : &["kind"]
3155 168 : )
3156 168 : .unwrap()
3157 168 : });
3158 168 : static COUNT_ACCOUNTED_START_PER_TENANT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3159 168 : register_int_counter_vec!(
3160 168 : "pageserver_tenant_throttling_count_accounted_start",
3161 168 : "Count of tenant throttling starts, by kind of throttle.",
3162 168 : &["kind", "tenant_id", "shard_id"]
3163 168 : )
3164 168 : .unwrap()
3165 168 : });
3166 168 : static COUNT_ACCOUNTED_FINISH: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3167 168 : register_int_counter_vec!(
3168 168 : "pageserver_tenant_throttling_count_accounted_finish_global",
3169 168 : "Count of tenant throttling finishes, by kind of throttle.",
3170 168 : &["kind"]
3171 168 : )
3172 168 : .unwrap()
3173 168 : });
3174 168 : static COUNT_ACCOUNTED_FINISH_PER_TENANT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3175 168 : register_int_counter_vec!(
3176 168 : "pageserver_tenant_throttling_count_accounted_finish",
3177 168 : "Count of tenant throttling finishes, by kind of throttle.",
3178 168 : &["kind", "tenant_id", "shard_id"]
3179 168 : )
3180 168 : .unwrap()
3181 168 : });
3182 168 : static WAIT_USECS: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3183 168 : register_int_counter_vec!(
3184 168 : "pageserver_tenant_throttling_wait_usecs_sum_global",
3185 168 : "Sum of microseconds that spent waiting throttle by kind of throttle.",
3186 168 : &["kind"]
3187 168 : )
3188 168 : .unwrap()
3189 168 : });
3190 168 : static WAIT_USECS_PER_TENANT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3191 168 : register_int_counter_vec!(
3192 168 : "pageserver_tenant_throttling_wait_usecs_sum",
3193 168 : "Sum of microseconds that spent waiting throttle by kind of throttle.",
3194 168 : &["kind", "tenant_id", "shard_id"]
3195 168 : )
3196 168 : .unwrap()
3197 168 : });
3198 :
3199 168 : static WAIT_COUNT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3200 168 : register_int_counter_vec!(
3201 168 : "pageserver_tenant_throttling_count_global",
3202 168 : "Count of tenant throttlings, by kind of throttle.",
3203 168 : &["kind"]
3204 168 : )
3205 168 : .unwrap()
3206 168 : });
3207 168 : static WAIT_COUNT_PER_TENANT: Lazy<metrics::IntCounterVec> = Lazy::new(|| {
3208 168 : register_int_counter_vec!(
3209 168 : "pageserver_tenant_throttling_count",
3210 168 : "Count of tenant throttlings, by kind of throttle.",
3211 168 : &["kind", "tenant_id", "shard_id"]
3212 168 : )
3213 168 : .unwrap()
3214 168 : });
3215 :
3216 : const KIND: &str = "timeline_get";
3217 :
3218 : impl TimelineGet {
3219 186 : pub(crate) fn new(tenant_shard_id: &TenantShardId) -> Self {
3220 186 : let per_tenant_label_values = &[
3221 186 : KIND,
3222 186 : &tenant_shard_id.tenant_id.to_string(),
3223 186 : &tenant_shard_id.shard_slug().to_string(),
3224 186 : ];
3225 186 : TimelineGet {
3226 186 : count_accounted_start: {
3227 186 : GlobalAndPerTenantIntCounter {
3228 186 : global: COUNT_ACCOUNTED_START.with_label_values(&[KIND]),
3229 186 : per_tenant: COUNT_ACCOUNTED_START_PER_TENANT
3230 186 : .with_label_values(per_tenant_label_values),
3231 186 : }
3232 186 : },
3233 186 : count_accounted_finish: {
3234 186 : GlobalAndPerTenantIntCounter {
3235 186 : global: COUNT_ACCOUNTED_FINISH.with_label_values(&[KIND]),
3236 186 : per_tenant: COUNT_ACCOUNTED_FINISH_PER_TENANT
3237 186 : .with_label_values(per_tenant_label_values),
3238 186 : }
3239 186 : },
3240 186 : wait_time: {
3241 186 : GlobalAndPerTenantIntCounter {
3242 186 : global: WAIT_USECS.with_label_values(&[KIND]),
3243 186 : per_tenant: WAIT_USECS_PER_TENANT
3244 186 : .with_label_values(per_tenant_label_values),
3245 186 : }
3246 186 : },
3247 186 : count_throttled: {
3248 186 : GlobalAndPerTenantIntCounter {
3249 186 : global: WAIT_COUNT.with_label_values(&[KIND]),
3250 186 : per_tenant: WAIT_COUNT_PER_TENANT
3251 186 : .with_label_values(per_tenant_label_values),
3252 186 : }
3253 186 : },
3254 186 : }
3255 186 : }
3256 : }
3257 :
3258 0 : pub(crate) fn preinitialize_global_metrics() {
3259 0 : Lazy::force(&COUNT_ACCOUNTED_START);
3260 0 : Lazy::force(&COUNT_ACCOUNTED_FINISH);
3261 0 : Lazy::force(&WAIT_USECS);
3262 0 : Lazy::force(&WAIT_COUNT);
3263 0 : }
3264 :
3265 6 : pub(crate) fn remove_tenant_metrics(tenant_shard_id: &TenantShardId) {
3266 24 : for m in &[
3267 6 : &COUNT_ACCOUNTED_START_PER_TENANT,
3268 6 : &COUNT_ACCOUNTED_FINISH_PER_TENANT,
3269 6 : &WAIT_USECS_PER_TENANT,
3270 6 : &WAIT_COUNT_PER_TENANT,
3271 24 : ] {
3272 24 : let _ = m.remove_label_values(&[
3273 24 : KIND,
3274 24 : &tenant_shard_id.tenant_id.to_string(),
3275 24 : &tenant_shard_id.shard_slug().to_string(),
3276 24 : ]);
3277 24 : }
3278 6 : }
3279 :
3280 : impl Metric for TimelineGet {
3281 : #[inline(always)]
3282 0 : fn accounting_start(&self) {
3283 0 : self.count_accounted_start.inc();
3284 0 : }
3285 : #[inline(always)]
3286 0 : fn accounting_finish(&self) {
3287 0 : self.count_accounted_finish.inc();
3288 0 : }
3289 : #[inline(always)]
3290 0 : fn observe_throttling(
3291 0 : &self,
3292 0 : tenant::throttle::Observation { wait_time }: &tenant::throttle::Observation,
3293 0 : ) {
3294 0 : let val = u64::try_from(wait_time.as_micros()).unwrap();
3295 0 : self.wait_time.inc_by(val);
3296 0 : self.count_throttled.inc();
3297 0 : }
3298 : }
3299 : }
3300 :
3301 : pub(crate) mod disk_usage_based_eviction {
3302 : use super::*;
3303 :
3304 : pub(crate) struct Metrics {
3305 : pub(crate) tenant_collection_time: Histogram,
3306 : pub(crate) tenant_layer_count: Histogram,
3307 : pub(crate) layers_collected: IntCounter,
3308 : pub(crate) layers_selected: IntCounter,
3309 : pub(crate) layers_evicted: IntCounter,
3310 : }
3311 :
3312 : impl Default for Metrics {
3313 0 : fn default() -> Self {
3314 0 : let tenant_collection_time = register_histogram!(
3315 0 : "pageserver_disk_usage_based_eviction_tenant_collection_seconds",
3316 0 : "Time spent collecting layers from a tenant -- not normalized by collected layer amount",
3317 0 : vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0]
3318 0 : )
3319 0 : .unwrap();
3320 0 :
3321 0 : let tenant_layer_count = register_histogram!(
3322 0 : "pageserver_disk_usage_based_eviction_tenant_collected_layers",
3323 0 : "Amount of layers gathered from a tenant",
3324 0 : vec![5.0, 50.0, 500.0, 5000.0, 50000.0]
3325 0 : )
3326 0 : .unwrap();
3327 0 :
3328 0 : let layers_collected = register_int_counter!(
3329 0 : "pageserver_disk_usage_based_eviction_collected_layers_total",
3330 0 : "Amount of layers collected"
3331 0 : )
3332 0 : .unwrap();
3333 0 :
3334 0 : let layers_selected = register_int_counter!(
3335 0 : "pageserver_disk_usage_based_eviction_select_layers_total",
3336 0 : "Amount of layers selected"
3337 0 : )
3338 0 : .unwrap();
3339 0 :
3340 0 : let layers_evicted = register_int_counter!(
3341 0 : "pageserver_disk_usage_based_eviction_evicted_layers_total",
3342 0 : "Amount of layers successfully evicted"
3343 0 : )
3344 0 : .unwrap();
3345 0 :
3346 0 : Self {
3347 0 : tenant_collection_time,
3348 0 : tenant_layer_count,
3349 0 : layers_collected,
3350 0 : layers_selected,
3351 0 : layers_evicted,
3352 0 : }
3353 0 : }
3354 : }
3355 :
3356 : pub(crate) static METRICS: Lazy<Metrics> = Lazy::new(Metrics::default);
3357 : }
3358 :
3359 162 : static TOKIO_EXECUTOR_THREAD_COUNT: Lazy<UIntGaugeVec> = Lazy::new(|| {
3360 162 : register_uint_gauge_vec!(
3361 162 : "pageserver_tokio_executor_thread_configured_count",
3362 162 : "Total number of configued tokio executor threads in the process.
3363 162 : The `setup` label denotes whether we're running with multiple runtimes or a single runtime.",
3364 162 : &["setup"],
3365 162 : )
3366 162 : .unwrap()
3367 162 : });
3368 :
3369 162 : pub(crate) fn set_tokio_runtime_setup(setup: &str, num_threads: NonZeroUsize) {
3370 : static SERIALIZE: std::sync::Mutex<()> = std::sync::Mutex::new(());
3371 162 : let _guard = SERIALIZE.lock().unwrap();
3372 162 : TOKIO_EXECUTOR_THREAD_COUNT.reset();
3373 162 : TOKIO_EXECUTOR_THREAD_COUNT
3374 162 : .get_metric_with_label_values(&[setup])
3375 162 : .unwrap()
3376 162 : .set(u64::try_from(num_threads.get()).unwrap());
3377 162 : }
3378 :
3379 0 : pub fn preinitialize_metrics() {
3380 0 : // Python tests need these and on some we do alerting.
3381 0 : //
3382 0 : // FIXME(4813): make it so that we have no top level metrics as this fn will easily fall out of
3383 0 : // order:
3384 0 : // - global metrics reside in a Lazy<PageserverMetrics>
3385 0 : // - access via crate::metrics::PS_METRICS.some_metric.inc()
3386 0 : // - could move the statics into TimelineMetrics::new()?
3387 0 :
3388 0 : // counters
3389 0 : [
3390 0 : &UNEXPECTED_ONDEMAND_DOWNLOADS,
3391 0 : &WALRECEIVER_STARTED_CONNECTIONS,
3392 0 : &WALRECEIVER_BROKER_UPDATES,
3393 0 : &WALRECEIVER_CANDIDATES_ADDED,
3394 0 : &WALRECEIVER_CANDIDATES_REMOVED,
3395 0 : &tokio_epoll_uring::THREAD_LOCAL_LAUNCH_FAILURES,
3396 0 : &tokio_epoll_uring::THREAD_LOCAL_LAUNCH_SUCCESSES,
3397 0 : &REMOTE_ONDEMAND_DOWNLOADED_LAYERS,
3398 0 : &REMOTE_ONDEMAND_DOWNLOADED_BYTES,
3399 0 : &CIRCUIT_BREAKERS_BROKEN,
3400 0 : &CIRCUIT_BREAKERS_UNBROKEN,
3401 0 : ]
3402 0 : .into_iter()
3403 0 : .for_each(|c| {
3404 0 : Lazy::force(c);
3405 0 : });
3406 0 :
3407 0 : // Deletion queue stats
3408 0 : Lazy::force(&DELETION_QUEUE);
3409 0 :
3410 0 : // Tenant stats
3411 0 : Lazy::force(&TENANT);
3412 0 :
3413 0 : // Tenant manager stats
3414 0 : Lazy::force(&TENANT_MANAGER);
3415 0 :
3416 0 : Lazy::force(&crate::tenant::storage_layer::layer::LAYER_IMPL_METRICS);
3417 0 : Lazy::force(&disk_usage_based_eviction::METRICS);
3418 :
3419 0 : for state_name in pageserver_api::models::TenantState::VARIANTS {
3420 0 : // initialize the metric for all gauges, otherwise the time series might seemingly show
3421 0 : // values from last restart.
3422 0 : TENANT_STATE_METRIC.with_label_values(&[state_name]).set(0);
3423 0 : }
3424 :
3425 : // countervecs
3426 0 : [
3427 0 : &BACKGROUND_LOOP_PERIOD_OVERRUN_COUNT,
3428 0 : &SMGR_QUERY_STARTED_GLOBAL,
3429 0 : ]
3430 0 : .into_iter()
3431 0 : .for_each(|c| {
3432 0 : Lazy::force(c);
3433 0 : });
3434 0 :
3435 0 : // gauges
3436 0 : WALRECEIVER_ACTIVE_MANAGERS.get();
3437 0 :
3438 0 : // histograms
3439 0 : [
3440 0 : &READ_NUM_LAYERS_VISITED,
3441 0 : &VEC_READ_NUM_LAYERS_VISITED,
3442 0 : &WAIT_LSN_TIME,
3443 0 : &WAL_REDO_TIME,
3444 0 : &WAL_REDO_RECORDS_HISTOGRAM,
3445 0 : &WAL_REDO_BYTES_HISTOGRAM,
3446 0 : &WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM,
3447 0 : ]
3448 0 : .into_iter()
3449 0 : .for_each(|h| {
3450 0 : Lazy::force(h);
3451 0 : });
3452 0 :
3453 0 : // Custom
3454 0 : Lazy::force(&RECONSTRUCT_TIME);
3455 0 : Lazy::force(&BASEBACKUP_QUERY_TIME);
3456 0 : Lazy::force(&COMPUTE_COMMANDS_COUNTERS);
3457 0 :
3458 0 : tenant_throttling::preinitialize_global_metrics();
3459 0 : }
|