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