Skip to main content

typed_store/
metrics.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    cell::RefCell,
7    sync::{
8        Arc,
9        atomic::{AtomicU64, Ordering},
10    },
11    time::Duration,
12};
13
14use once_cell::sync::OnceCell;
15use prometheus_filtered::{
16    HistogramVec, IntCounterVec, IntGaugeVec, MetricLevel, Registry,
17    register_histogram_vec_with_registry, register_int_counter_vec_with_registry,
18    register_int_gauge_vec_with_registry,
19};
20use rocksdb::{PerfContext, PerfMetric, PerfStatsLevel, perf::set_perf_stats};
21use tap::TapFallible;
22use tracing::warn;
23
24thread_local! {
25    static PER_THREAD_ROCKS_PERF_CONTEXT: std::cell::RefCell<rocksdb::PerfContext>  = RefCell::new(PerfContext::default());
26}
27
28const LATENCY_SEC_BUCKETS: &[f64] = &[
29    0.00001, 0.00005, // 10 mcs, 50 mcs
30    0.0001, 0.0002, 0.0003, 0.0004, 0.0005, // 100..500 mcs
31    0.001, 0.002, 0.003, 0.004, 0.005, // 1..5ms
32    0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1., 2.5, 5., 10.,
33];
34
35#[derive(Debug, Clone)]
36// A struct for sampling based on number of operations or duration.
37// Sampling happens if the duration expires and after number of operations
38pub struct SamplingInterval {
39    // Sample once every time duration
40    pub once_every_duration: Duration,
41    // Sample once every number of operations
42    pub after_num_ops: u64,
43    // Counter for keeping track of previous sample
44    pub counter: Arc<AtomicU64>,
45}
46
47impl Default for SamplingInterval {
48    fn default() -> Self {
49        // Enabled with 60 second interval
50        SamplingInterval::new(Duration::from_secs(60), 0)
51    }
52}
53
54impl SamplingInterval {
55    pub fn new(once_every_duration: Duration, after_num_ops: u64) -> Self {
56        let counter = Arc::new(AtomicU64::new(1));
57        if !once_every_duration.is_zero() {
58            let counter = Arc::downgrade(&counter);
59            tokio::task::spawn(async move {
60                while let Some(counter) = counter.upgrade() {
61                    if counter.load(Ordering::SeqCst) > after_num_ops {
62                        counter.store(0, Ordering::SeqCst);
63                    }
64                    drop(counter);
65                    tokio::time::sleep(once_every_duration).await;
66                }
67            });
68        }
69        SamplingInterval {
70            once_every_duration,
71            after_num_ops,
72            counter,
73        }
74    }
75    pub fn new_from_self(&self) -> SamplingInterval {
76        SamplingInterval::new(self.once_every_duration, self.after_num_ops)
77    }
78    pub fn sample(&self) -> bool {
79        if self.once_every_duration.is_zero() {
80            self.counter
81                .fetch_add(1, Ordering::Relaxed)
82                .is_multiple_of(self.after_num_ops + 1)
83        } else {
84            self.counter.fetch_add(1, Ordering::Relaxed) == 0
85        }
86    }
87}
88
89#[derive(Debug)]
90pub struct ColumnFamilyMetrics {
91    pub rocksdb_total_sst_files_size: IntGaugeVec,
92    pub rocksdb_total_blob_files_size: IntGaugeVec,
93    pub rocksdb_total_num_files: IntGaugeVec,
94    pub rocksdb_num_level0_files: IntGaugeVec,
95    pub rocksdb_current_size_active_mem_tables: IntGaugeVec,
96    pub rocksdb_size_all_mem_tables: IntGaugeVec,
97    pub rocksdb_num_snapshots: IntGaugeVec,
98    pub rocksdb_oldest_snapshot_time: IntGaugeVec,
99    pub rocksdb_actual_delayed_write_rate: IntGaugeVec,
100    pub rocksdb_is_write_stopped: IntGaugeVec,
101    pub rocksdb_block_cache_capacity: IntGaugeVec,
102    pub rocksdb_block_cache_usage: IntGaugeVec,
103    pub rocksdb_block_cache_pinned_usage: IntGaugeVec,
104    pub rocksdb_estimate_table_readers_mem: IntGaugeVec,
105    pub rocksdb_num_immutable_mem_tables: IntGaugeVec,
106    pub rocksdb_mem_table_flush_pending: IntGaugeVec,
107    pub rocksdb_compaction_pending: IntGaugeVec,
108    pub rocksdb_estimate_pending_compaction_bytes: IntGaugeVec,
109    pub rocksdb_num_running_compactions: IntGaugeVec,
110    pub rocksdb_num_running_flushes: IntGaugeVec,
111    pub rocksdb_estimate_oldest_key_time: IntGaugeVec,
112    pub rocksdb_background_errors: IntGaugeVec,
113    pub rocksdb_estimated_num_keys: IntGaugeVec,
114    pub rocksdb_base_level: IntGaugeVec,
115}
116
117impl ColumnFamilyMetrics {
118    pub(crate) fn new(registry: &Registry) -> Self {
119        ColumnFamilyMetrics {
120            rocksdb_total_sst_files_size: register_int_gauge_vec_with_registry!(
121                "rocksdb_total_sst_files_size",
122                "The storage size occupied by the sst files in the column family",
123                &["cf_name"],
124                registry;
125                MetricLevel::Trace,
126            )
127            .unwrap(),
128            rocksdb_total_blob_files_size: register_int_gauge_vec_with_registry!(
129                "rocksdb_total_blob_files_size",
130                "The storage size occupied by the blob files in the column family",
131                &["cf_name"],
132                registry;
133                MetricLevel::Trace,
134            )
135            .unwrap(),
136            rocksdb_total_num_files: register_int_gauge_vec_with_registry!(
137                "rocksdb_total_num_files",
138                "Total number of files used in the column family",
139                &["cf_name"],
140                registry;
141                MetricLevel::Trace,
142            )
143            .unwrap(),
144            rocksdb_num_level0_files: register_int_gauge_vec_with_registry!(
145                "rocksdb_num_level0_files",
146                "Number of level 0 files in the column family",
147                &["cf_name"],
148                registry;
149                MetricLevel::Trace,
150            )
151            .unwrap(),
152            rocksdb_current_size_active_mem_tables: register_int_gauge_vec_with_registry!(
153                "rocksdb_current_size_active_mem_tables",
154                "The current approximate size of active memtable (bytes).",
155                &["cf_name"],
156                registry;
157                MetricLevel::Trace,
158            )
159            .unwrap(),
160            rocksdb_size_all_mem_tables: register_int_gauge_vec_with_registry!(
161                "rocksdb_size_all_mem_tables",
162                "The memory size occupied by the column family's in-memory buffer",
163                &["cf_name"],
164                registry;
165                MetricLevel::Trace,
166            )
167            .unwrap(),
168            rocksdb_num_snapshots: register_int_gauge_vec_with_registry!(
169                "rocksdb_num_snapshots",
170                "Number of snapshots held for the column family",
171                &["cf_name"],
172                registry;
173                MetricLevel::Trace,
174            )
175            .unwrap(),
176            rocksdb_oldest_snapshot_time: register_int_gauge_vec_with_registry!(
177                "rocksdb_oldest_snapshot_time",
178                "Unit timestamp of the oldest unreleased snapshot",
179                &["cf_name"],
180                registry;
181                MetricLevel::Trace,
182            )
183            .unwrap(),
184            rocksdb_actual_delayed_write_rate: register_int_gauge_vec_with_registry!(
185                "rocksdb_actual_delayed_write_rate",
186                "The current actual delayed write rate. 0 means no delay",
187                &["cf_name"],
188                registry;
189                MetricLevel::Trace,
190            )
191            .unwrap(),
192            rocksdb_is_write_stopped: register_int_gauge_vec_with_registry!(
193                "rocksdb_is_write_stopped",
194                "A flag indicating whether writes are stopped on this column family. 1 indicates writes have been stopped.",
195                &["cf_name"],
196                registry;
197                MetricLevel::Trace,
198            )
199            .unwrap(),
200            rocksdb_block_cache_capacity: register_int_gauge_vec_with_registry!(
201                "rocksdb_block_cache_capacity",
202                "The block cache capacity of the column family.",
203                &["cf_name"],
204                registry;
205                MetricLevel::Trace,
206            )
207            .unwrap(),
208            rocksdb_block_cache_usage: register_int_gauge_vec_with_registry!(
209                "rocksdb_block_cache_usage",
210                "The memory size used by the column family in the block cache.",
211                &["cf_name"],
212                registry;
213                MetricLevel::Trace,
214            )
215            .unwrap(),
216            rocksdb_block_cache_pinned_usage: register_int_gauge_vec_with_registry!(
217                "rocksdb_block_cache_pinned_usage",
218                "The memory size used by the column family in the block cache where entries are pinned",
219                &["cf_name"],
220                registry;
221                MetricLevel::Trace,
222            )
223            .unwrap(),
224            rocksdb_estimate_table_readers_mem: register_int_gauge_vec_with_registry!(
225                "rocksdb_estimate_table_readers_mem",
226                "The estimated memory size used for reading SST tables in this column
227                family such as filters and index blocks. Note that this number does not
228                include the memory used in block cache.",
229                &["cf_name"],
230                registry;
231                MetricLevel::Trace,
232            )
233            .unwrap(),
234            rocksdb_num_immutable_mem_tables: register_int_gauge_vec_with_registry!(
235                "rocksdb_num_immutable_mem_tables",
236                "The number of immutable memtables that have not yet been flushed.",
237                &["cf_name"],
238                registry;
239                MetricLevel::Trace,
240            )
241            .unwrap(),
242            rocksdb_mem_table_flush_pending: register_int_gauge_vec_with_registry!(
243                "rocksdb_mem_table_flush_pending",
244                "A 1 or 0 flag indicating whether a memtable flush is pending.
245                If this number is 1, it means a memtable is waiting for being flushed,
246                but there might be too many L0 files that prevents it from being flushed.",
247                &["cf_name"],
248                registry;
249                MetricLevel::Trace,
250            )
251            .unwrap(),
252            rocksdb_compaction_pending: register_int_gauge_vec_with_registry!(
253                "rocksdb_compaction_pending",
254                "A 1 or 0 flag indicating whether a compaction job is pending.
255                If this number is 1, it means some part of the column family requires
256                compaction in order to maintain shape of LSM tree, but the compaction
257                is pending because the desired compaction job is either waiting for
258                other dependent compactions to be finished or waiting for an available
259                compaction thread.",
260                &["cf_name"],
261                registry;
262                MetricLevel::Trace,
263            )
264            .unwrap(),
265            rocksdb_estimate_pending_compaction_bytes: register_int_gauge_vec_with_registry!(
266                "rocksdb_estimate_pending_compaction_bytes",
267                "Estimated total number of bytes compaction needs to rewrite to get all levels down
268                to under target size. Not valid for other compactions than level-based.",
269                &["cf_name"],
270                registry;
271                MetricLevel::Trace,
272            )
273            .unwrap(),
274            rocksdb_num_running_compactions: register_int_gauge_vec_with_registry!(
275                "rocksdb_num_running_compactions",
276                "The number of compactions that are currently running for the column family.",
277                &["cf_name"],
278                registry;
279                MetricLevel::Trace,
280            )
281            .unwrap(),
282            rocksdb_num_running_flushes: register_int_gauge_vec_with_registry!(
283                "rocksdb_num_running_flushes",
284                "The number of flushes that are currently running for the column family.",
285                &["cf_name"],
286                registry;
287                MetricLevel::Trace,
288            )
289            .unwrap(),
290            rocksdb_estimate_oldest_key_time: register_int_gauge_vec_with_registry!(
291                "rocksdb_estimate_oldest_key_time",
292                "Estimation of the oldest key timestamp in the DB. Only available
293                for FIFO compaction with compaction_options_fifo.allow_compaction = false.",
294                &["cf_name"],
295                registry;
296                MetricLevel::Trace,
297            )
298            .unwrap(),
299            rocksdb_estimated_num_keys: register_int_gauge_vec_with_registry!(
300                "rocksdb_estimated_num_keys",
301                "The estimated number of keys in the table",
302                &["cf_name"],
303                registry;
304                MetricLevel::Trace,
305            )
306            .unwrap(),
307            rocksdb_background_errors: register_int_gauge_vec_with_registry!(
308                "rocksdb_background_errors",
309                "The accumulated number of RocksDB background errors.",
310                &["cf_name"],
311                registry;
312                MetricLevel::Trace,
313            )
314            .unwrap(),
315            rocksdb_base_level: register_int_gauge_vec_with_registry!(
316                "rocksdb_base_level",
317                "The number of level to which L0 data will be compacted.",
318                &["cf_name"],
319                registry;
320                MetricLevel::Trace,
321            )
322            .unwrap(),
323        }
324    }
325}
326
327#[derive(Debug)]
328pub struct OperationMetrics {
329    pub rocksdb_iter_latency_seconds: HistogramVec,
330    pub rocksdb_iter_bytes: HistogramVec,
331    pub rocksdb_iter_keys: HistogramVec,
332    pub rocksdb_get_latency_seconds: HistogramVec,
333    pub rocksdb_get_bytes: HistogramVec,
334    pub rocksdb_multiget_latency_seconds: HistogramVec,
335    pub rocksdb_multiget_bytes: HistogramVec,
336    pub rocksdb_put_latency_seconds: HistogramVec,
337    pub rocksdb_put_bytes: HistogramVec,
338    pub rocksdb_batch_put_bytes: HistogramVec,
339    pub rocksdb_delete_latency_seconds: HistogramVec,
340    pub rocksdb_deletes: IntCounterVec,
341    pub rocksdb_batch_commit_latency_seconds: HistogramVec,
342    pub rocksdb_batch_commit_bytes: HistogramVec,
343    pub rocksdb_num_active_db_handles: IntGaugeVec,
344    pub rocksdb_close_duration_ms: IntGaugeVec,
345    pub rocksdb_very_slow_batch_writes_count: IntCounterVec,
346    pub rocksdb_very_slow_batch_writes_duration_ms: IntCounterVec,
347    pub rocksdb_very_slow_puts_count: IntCounterVec,
348    pub rocksdb_very_slow_puts_duration_ms: IntCounterVec,
349}
350
351impl OperationMetrics {
352    pub(crate) fn new(registry: &Registry) -> Self {
353        OperationMetrics {
354            rocksdb_iter_latency_seconds: register_histogram_vec_with_registry!(
355                "rocksdb_iter_latency_seconds",
356                "Rocksdb iter latency in seconds",
357                &["cf_name"],
358                LATENCY_SEC_BUCKETS.to_vec(),
359                registry;
360                MetricLevel::Trace,
361            )
362            .unwrap(),
363            rocksdb_iter_bytes: register_histogram_vec_with_registry!(
364                "rocksdb_iter_bytes",
365                "Rocksdb iter size in bytes",
366                &["cf_name"],
367                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
368                    .unwrap()
369                    .to_vec(),
370                registry;
371                MetricLevel::Trace,
372            )
373            .unwrap(),
374            rocksdb_iter_keys: register_histogram_vec_with_registry!(
375                "rocksdb_iter_keys",
376                "Rocksdb iter num keys",
377                &["cf_name"],
378                registry;
379                MetricLevel::Trace,
380            )
381            .unwrap(),
382            rocksdb_get_latency_seconds: register_histogram_vec_with_registry!(
383                "rocksdb_get_latency_seconds",
384                "Rocksdb get latency in seconds",
385                &["cf_name"],
386                LATENCY_SEC_BUCKETS.to_vec(),
387                registry;
388                MetricLevel::Trace,
389            )
390            .unwrap(),
391            rocksdb_get_bytes: register_histogram_vec_with_registry!(
392                "rocksdb_get_bytes",
393                "Rocksdb get call returned data size in bytes",
394                &["cf_name"],
395                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
396                    .unwrap()
397                    .to_vec(),
398                registry;
399                MetricLevel::Trace,
400            )
401            .unwrap(),
402            rocksdb_multiget_latency_seconds: register_histogram_vec_with_registry!(
403                "rocksdb_multiget_latency_seconds",
404                "Rocksdb multiget latency in seconds",
405                &["cf_name"],
406                LATENCY_SEC_BUCKETS.to_vec(),
407                registry;
408                MetricLevel::Trace,
409            )
410            .unwrap(),
411            rocksdb_multiget_bytes: register_histogram_vec_with_registry!(
412                "rocksdb_multiget_bytes",
413                "Rocksdb multiget call returned data size in bytes",
414                &["cf_name"],
415                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
416                    .unwrap()
417                    .to_vec(),
418                registry;
419                MetricLevel::Trace,
420            )
421            .unwrap(),
422            rocksdb_put_latency_seconds: register_histogram_vec_with_registry!(
423                "rocksdb_put_latency_seconds",
424                "Rocksdb put latency in seconds",
425                &["cf_name"],
426                LATENCY_SEC_BUCKETS.to_vec(),
427                registry;
428                MetricLevel::Trace,
429            )
430            .unwrap(),
431            rocksdb_put_bytes: register_histogram_vec_with_registry!(
432                "rocksdb_put_bytes",
433                "Rocksdb put call puts data size in bytes",
434                &["cf_name"],
435                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
436                    .unwrap()
437                    .to_vec(),
438                registry;
439                MetricLevel::Trace,
440            )
441            .unwrap(),
442            rocksdb_batch_put_bytes: register_histogram_vec_with_registry!(
443                "rocksdb_batch_put_bytes",
444                "Rocksdb batch put call puts data size in bytes",
445                &["cf_name"],
446                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
447                    .unwrap()
448                    .to_vec(),
449                registry;
450                MetricLevel::Trace,
451            )
452            .unwrap(),
453            rocksdb_delete_latency_seconds: register_histogram_vec_with_registry!(
454                "rocksdb_delete_latency_seconds",
455                "Rocksdb delete latency in seconds",
456                &["cf_name"],
457                LATENCY_SEC_BUCKETS.to_vec(),
458                registry;
459                MetricLevel::Trace,
460            )
461            .unwrap(),
462            rocksdb_deletes: register_int_counter_vec_with_registry!(
463                "rocksdb_deletes",
464                "Rocksdb delete calls",
465                &["cf_name"],
466                registry;
467                MetricLevel::Trace,
468            )
469            .unwrap(),
470            rocksdb_batch_commit_latency_seconds: register_histogram_vec_with_registry!(
471                "rocksdb_write_batch_commit_latency_seconds",
472                "Rocksdb schema batch commit latency in seconds",
473                &["db_name"],
474                LATENCY_SEC_BUCKETS.to_vec(),
475                registry;
476                MetricLevel::Trace,
477            )
478            .unwrap(),
479            rocksdb_batch_commit_bytes: register_histogram_vec_with_registry!(
480                "rocksdb_batch_commit_bytes",
481                "Rocksdb schema batch commit size in bytes",
482                &["db_name"],
483                prometheus_filtered::exponential_buckets(1.0, 4.0, 15)
484                    .unwrap()
485                    .to_vec(),
486                registry;
487                MetricLevel::Trace,
488            )
489            .unwrap(),
490            rocksdb_num_active_db_handles: register_int_gauge_vec_with_registry!(
491                "rocksdb_num_active_db_handles",
492                "Number of active db handles",
493                &["db_name"],
494                registry;
495                MetricLevel::Trace,
496            )
497            .unwrap(),
498            rocksdb_close_duration_ms: register_int_gauge_vec_with_registry!(
499                "rocksdb_close_duration_ms",
500                "Time taken by the last close of the database, in milliseconds",
501                &["db_name"],
502                registry;
503                MetricLevel::Warn,
504            )
505            .unwrap(),
506            rocksdb_very_slow_batch_writes_count: register_int_counter_vec_with_registry!(
507                "rocksdb_num_very_slow_batch_writes",
508                "Number of batch writes that took more than 1 second and were slower than 32 MiB/s",
509                &["db_name"],
510                registry;
511                MetricLevel::Trace,
512            )
513            .unwrap(),
514            rocksdb_very_slow_batch_writes_duration_ms: register_int_counter_vec_with_registry!(
515                "rocksdb_very_slow_batch_writes_duration",
516                "Total time in milliseconds spent on batch writes that took more than 1 second and were slower than 32 MiB/s",
517                &["db_name"],
518                registry;
519                MetricLevel::Trace,
520            )
521            .unwrap(),
522            rocksdb_very_slow_puts_count: register_int_counter_vec_with_registry!(
523                "rocksdb_num_very_slow_puts",
524                "Number of puts that took more than 1 second",
525                &["cf_name"],
526                registry;
527                MetricLevel::Trace,
528            )
529            .unwrap(),
530            rocksdb_very_slow_puts_duration_ms: register_int_counter_vec_with_registry!(
531                "rocksdb_very_slow_puts_duration",
532                "Total time in milliseconds spent on puts that took more than 1 second",
533                &["cf_name"],
534                registry;
535                MetricLevel::Trace,
536            )
537            .unwrap(),
538        }
539    }
540}
541
542pub struct RocksDBPerfContext;
543
544impl Default for RocksDBPerfContext {
545    fn default() -> Self {
546        set_perf_stats(PerfStatsLevel::EnableTime);
547        PER_THREAD_ROCKS_PERF_CONTEXT.with(|perf_context| {
548            perf_context.borrow_mut().reset();
549        });
550        RocksDBPerfContext {}
551    }
552}
553
554impl Drop for RocksDBPerfContext {
555    fn drop(&mut self) {
556        set_perf_stats(PerfStatsLevel::Disable);
557    }
558}
559
560#[derive(Debug)]
561pub struct ReadPerfContextMetrics {
562    pub user_key_comparison_count: IntCounterVec,
563    pub block_cache_hit_count: IntCounterVec,
564    pub block_read_count: IntCounterVec,
565    pub block_read_byte: IntCounterVec,
566    pub block_read_nanos: IntCounterVec,
567    pub block_checksum_nanos: IntCounterVec,
568    pub block_decompress_nanos: IntCounterVec,
569    pub get_read_bytes: IntCounterVec,
570    pub multiget_read_bytes: IntCounterVec,
571    pub get_snapshot_nanos: IntCounterVec,
572    pub get_from_memtable_nanos: IntCounterVec,
573    pub get_from_memtable_count: IntCounterVec,
574    pub get_post_process_nanos: IntCounterVec,
575    pub get_from_output_files_nanos: IntCounterVec,
576    pub db_mutex_lock_nanos: IntCounterVec,
577    pub db_condition_wait_nanos: IntCounterVec,
578    pub merge_operator_nanos: IntCounterVec,
579    pub read_index_block_nanos: IntCounterVec,
580    pub read_filter_block_nanos: IntCounterVec,
581    pub new_table_block_iter_nanos: IntCounterVec,
582    pub block_seek_nanos: IntCounterVec,
583    pub find_table_nanos: IntCounterVec,
584    pub bloom_memtable_hit_count: IntCounterVec,
585    pub bloom_memtable_miss_count: IntCounterVec,
586    pub bloom_sst_hit_count: IntCounterVec,
587    pub bloom_sst_miss_count: IntCounterVec,
588    pub key_lock_wait_time: IntCounterVec,
589    pub key_lock_wait_count: IntCounterVec,
590    pub internal_delete_skipped_count: IntCounterVec,
591    pub internal_skipped_count: IntCounterVec,
592}
593
594impl ReadPerfContextMetrics {
595    pub(crate) fn new(registry: &Registry) -> Self {
596        ReadPerfContextMetrics {
597            user_key_comparison_count: register_int_counter_vec_with_registry!(
598                "user_key_comparison_count",
599                "Helps us figure out whether too many comparisons in binary search can be a problem,
600                especially when a more expensive comparator is used. Moreover, since number of comparisons
601                is usually uniform based on the memtable size, the SST file size for Level 0 and size of other
602                levels, an significant increase of the counter can indicate unexpected LSM-tree shape.
603                You may want to check whether flush/compaction can keep up with the write speed",
604                &["cf_name"],
605                registry;
606                MetricLevel::Trace,
607            )
608            .unwrap(),
609            block_cache_hit_count: register_int_counter_vec_with_registry!(
610                "block_cache_hit_count",
611                "Tells us how many times we read data blocks from block cache, and block_read_count tells us how many
612                times we have to read blocks from the file system (either block cache is disabled or it is a cache miss).
613                We can evaluate the block cache efficiency by looking at the two counters over time.",
614                &["cf_name"],
615                registry;
616                MetricLevel::Trace,
617            )
618            .unwrap(),
619            block_read_count: register_int_counter_vec_with_registry!(
620                "block_read_count",
621                "Tells us how many times we have to read blocks from the file system (either block cache is disabled or it is a cache miss)",
622                &["cf_name"],
623                registry;
624                MetricLevel::Trace,
625            )
626            .unwrap(),
627            block_read_byte: register_int_counter_vec_with_registry!(
628                "block_read_byte",
629                "Tells us how many total bytes we read from the file system. It can tell us whether a slow query can be caused by reading
630                large blocks from the file system. Index and bloom filter blocks are usually large blocks. A large block can also be the result
631                of a very large key or value",
632                &["cf_name"],
633                registry;
634                MetricLevel::Trace,
635            )
636            .unwrap(),
637            block_read_nanos: register_int_counter_vec_with_registry!(
638                "block_read_nanos",
639                "Total nanos spent on block reads",
640                &["cf_name"],
641                registry;
642                MetricLevel::Trace,
643            )
644            .unwrap(),
645            block_checksum_nanos: register_int_counter_vec_with_registry!(
646                "block_checksum_nanos",
647                "Total nanos spent on verifying block checksum",
648                &["cf_name"],
649                registry;
650                MetricLevel::Trace,
651            )
652            .unwrap(),
653            block_decompress_nanos: register_int_counter_vec_with_registry!(
654                "block_decompress_nanos",
655                "Total nanos spent on decompressing a block",
656                &["cf_name"],
657                registry;
658                MetricLevel::Trace,
659            )
660            .unwrap(),
661            get_read_bytes: register_int_counter_vec_with_registry!(
662                "get_read_bytes",
663                "Total bytes for values returned by Get",
664                &["cf_name"],
665                registry;
666                MetricLevel::Trace,
667            )
668            .unwrap(),
669            multiget_read_bytes: register_int_counter_vec_with_registry!(
670                "multiget_read_bytes",
671                "Total bytes for values returned by MultiGet.",
672                &["cf_name"],
673                registry;
674                MetricLevel::Trace,
675            )
676            .unwrap(),
677            get_snapshot_nanos: register_int_counter_vec_with_registry!(
678                "get_snapshot_nanos",
679                "Time spent in getting snapshot.",
680                &["cf_name"],
681                registry;
682                MetricLevel::Trace,
683            )
684            .unwrap(),
685            get_from_memtable_nanos: register_int_counter_vec_with_registry!(
686                "get_from_memtable_nanos",
687                "Time spent on reading data from memtable.",
688                &["cf_name"],
689                registry;
690                MetricLevel::Trace,
691            )
692            .unwrap(),
693            get_from_memtable_count: register_int_counter_vec_with_registry!(
694                "get_from_memtable_count",
695                "Number of memtables queried",
696                &["cf_name"],
697                registry;
698                MetricLevel::Trace,
699            )
700            .unwrap(),
701            get_post_process_nanos: register_int_counter_vec_with_registry!(
702                "get_post_process_nanos",
703                "Total nanos spent after Get() finds a key",
704                &["cf_name"],
705                registry;
706                MetricLevel::Trace,
707            )
708            .unwrap(),
709            get_from_output_files_nanos: register_int_counter_vec_with_registry!(
710                "get_from_output_files_nanos",
711                "Total nanos reading from output files",
712                &["cf_name"],
713                registry;
714                MetricLevel::Trace,
715            )
716            .unwrap(),
717            db_mutex_lock_nanos: register_int_counter_vec_with_registry!(
718                "db_mutex_lock_nanos",
719                "Time spent on acquiring db mutex",
720                &["cf_name"],
721                registry;
722                MetricLevel::Trace,
723            )
724            .unwrap(),
725            db_condition_wait_nanos: register_int_counter_vec_with_registry!(
726                "db_condition_wait_nanos",
727                "Time spent waiting with a condition variable created with DB Mutex.",
728                &["cf_name"],
729                registry;
730                MetricLevel::Trace,
731            )
732            .unwrap(),
733            merge_operator_nanos: register_int_counter_vec_with_registry!(
734                "merge_operator_nanos",
735                "Time spent on merge operator.",
736                &["cf_name"],
737                registry;
738                MetricLevel::Trace,
739            )
740            .unwrap(),
741            read_index_block_nanos: register_int_counter_vec_with_registry!(
742                "read_index_block_nanos",
743                "Time spent on reading index block from block cache or SST file",
744                &["cf_name"],
745                registry;
746                MetricLevel::Trace,
747            )
748            .unwrap(),
749            read_filter_block_nanos: register_int_counter_vec_with_registry!(
750                "read_filter_block_nanos",
751                "Time spent on reading filter block from block cache or SST file",
752                &["cf_name"],
753                registry;
754                MetricLevel::Trace,
755            )
756            .unwrap(),
757            new_table_block_iter_nanos: register_int_counter_vec_with_registry!(
758                "new_table_block_iter_nanos",
759                "Time spent on creating data block iterator",
760                &["cf_name"],
761                registry;
762                MetricLevel::Trace,
763            )
764            .unwrap(),
765            block_seek_nanos: register_int_counter_vec_with_registry!(
766                "block_seek_nanos",
767                "Time spent on seeking a key in data/index blocks",
768                &["cf_name"],
769                registry;
770                MetricLevel::Trace,
771            )
772            .unwrap(),
773            find_table_nanos: register_int_counter_vec_with_registry!(
774                "find_table_nanos",
775                "Time spent on finding or creating a table reader",
776                &["cf_name"],
777                registry;
778                MetricLevel::Trace,
779            )
780            .unwrap(),
781            bloom_memtable_hit_count: register_int_counter_vec_with_registry!(
782                "bloom_memtable_hit_count",
783                "Total number of mem table bloom hits",
784                &["cf_name"],
785                registry;
786                MetricLevel::Trace,
787            )
788            .unwrap(),
789            bloom_memtable_miss_count: register_int_counter_vec_with_registry!(
790                "bloom_memtable_miss_count",
791                "Total number of mem table bloom misses",
792                &["cf_name"],
793                registry;
794                MetricLevel::Trace,
795            )
796            .unwrap(),
797            bloom_sst_hit_count: register_int_counter_vec_with_registry!(
798                "bloom_sst_hit_count",
799                "Total number of SST table bloom hits",
800                &["cf_name"],
801                registry;
802                MetricLevel::Trace,
803            )
804            .unwrap(),
805            bloom_sst_miss_count: register_int_counter_vec_with_registry!(
806                "bloom_sst_miss_count",
807                "Total number of SST table bloom misses",
808                &["cf_name"],
809                registry;
810                MetricLevel::Trace,
811            )
812            .unwrap(),
813            key_lock_wait_time: register_int_counter_vec_with_registry!(
814                "key_lock_wait_time",
815                "Time spent waiting on key locks in transaction lock manager",
816                &["cf_name"],
817                registry;
818                MetricLevel::Trace,
819            )
820            .unwrap(),
821            key_lock_wait_count: register_int_counter_vec_with_registry!(
822                "key_lock_wait_count",
823                "Number of times acquiring a lock was blocked by another transaction",
824                &["cf_name"],
825                registry;
826                MetricLevel::Trace,
827            )
828            .unwrap(),
829            internal_delete_skipped_count: register_int_counter_vec_with_registry!(
830                "internal_delete_skipped_count",
831                "Total number of deleted keys skipped during iteration",
832                &["cf_name"],
833                registry;
834                MetricLevel::Trace,
835            )
836                .unwrap(),
837            internal_skipped_count: register_int_counter_vec_with_registry!(
838                "internal_skipped_count",
839                "Totall number of internal keys skipped during iteration",
840                &["cf_name"],
841                registry;
842                MetricLevel::Trace,
843            )
844                .unwrap(),
845        }
846    }
847
848    pub fn report_metrics(&self, cf_name: &str) {
849        PER_THREAD_ROCKS_PERF_CONTEXT.with(|perf_context_cell| {
850            set_perf_stats(PerfStatsLevel::Disable);
851            let perf_context = perf_context_cell.borrow();
852            self.user_key_comparison_count
853                .with_label_values(&[cf_name])
854                .inc_by(perf_context.metric(PerfMetric::UserKeyComparisonCount));
855            self.block_cache_hit_count
856                .with_label_values(&[cf_name])
857                .inc_by(perf_context.metric(PerfMetric::BlockCacheHitCount));
858            self.block_read_count
859                .with_label_values(&[cf_name])
860                .inc_by(perf_context.metric(PerfMetric::BlockReadCount));
861            self.block_read_byte
862                .with_label_values(&[cf_name])
863                .inc_by(perf_context.metric(PerfMetric::BlockReadByte));
864            self.block_read_nanos
865                .with_label_values(&[cf_name])
866                .inc_by(perf_context.metric(PerfMetric::BlockReadTime));
867            self.block_read_count
868                .with_label_values(&[cf_name])
869                .inc_by(perf_context.metric(PerfMetric::BlockReadCount));
870            self.block_checksum_nanos
871                .with_label_values(&[cf_name])
872                .inc_by(perf_context.metric(PerfMetric::BlockChecksumTime));
873            self.block_decompress_nanos
874                .with_label_values(&[cf_name])
875                .inc_by(perf_context.metric(PerfMetric::BlockDecompressTime));
876            self.get_read_bytes
877                .with_label_values(&[cf_name])
878                .inc_by(perf_context.metric(PerfMetric::GetReadBytes));
879            self.multiget_read_bytes
880                .with_label_values(&[cf_name])
881                .inc_by(perf_context.metric(PerfMetric::MultigetReadBytes));
882            self.get_snapshot_nanos
883                .with_label_values(&[cf_name])
884                .inc_by(perf_context.metric(PerfMetric::GetSnapshotTime));
885            self.get_from_memtable_nanos
886                .with_label_values(&[cf_name])
887                .inc_by(perf_context.metric(PerfMetric::GetFromMemtableTime));
888            self.get_from_memtable_count
889                .with_label_values(&[cf_name])
890                .inc_by(perf_context.metric(PerfMetric::GetFromMemtableCount));
891            self.get_post_process_nanos
892                .with_label_values(&[cf_name])
893                .inc_by(perf_context.metric(PerfMetric::GetPostProcessTime));
894            self.get_from_output_files_nanos
895                .with_label_values(&[cf_name])
896                .inc_by(perf_context.metric(PerfMetric::GetFromOutputFilesTime));
897            self.db_mutex_lock_nanos
898                .with_label_values(&[cf_name])
899                .inc_by(perf_context.metric(PerfMetric::DbMutexLockNanos));
900            self.db_condition_wait_nanos
901                .with_label_values(&[cf_name])
902                .inc_by(perf_context.metric(PerfMetric::DbConditionWaitNanos));
903            self.merge_operator_nanos
904                .with_label_values(&[cf_name])
905                .inc_by(perf_context.metric(PerfMetric::MergeOperatorTimeNanos));
906            self.read_index_block_nanos
907                .with_label_values(&[cf_name])
908                .inc_by(perf_context.metric(PerfMetric::ReadIndexBlockNanos));
909            self.read_filter_block_nanos
910                .with_label_values(&[cf_name])
911                .inc_by(perf_context.metric(PerfMetric::ReadFilterBlockNanos));
912            self.new_table_block_iter_nanos
913                .with_label_values(&[cf_name])
914                .inc_by(perf_context.metric(PerfMetric::NewTableBlockIterNanos));
915            self.block_seek_nanos
916                .with_label_values(&[cf_name])
917                .inc_by(perf_context.metric(PerfMetric::BlockSeekNanos));
918            self.find_table_nanos
919                .with_label_values(&[cf_name])
920                .inc_by(perf_context.metric(PerfMetric::FindTableNanos));
921            self.bloom_memtable_hit_count
922                .with_label_values(&[cf_name])
923                .inc_by(perf_context.metric(PerfMetric::BloomMemtableHitCount));
924            self.bloom_memtable_miss_count
925                .with_label_values(&[cf_name])
926                .inc_by(perf_context.metric(PerfMetric::BloomMemtableMissCount));
927            self.bloom_sst_hit_count
928                .with_label_values(&[cf_name])
929                .inc_by(perf_context.metric(PerfMetric::BloomSstHitCount));
930            self.bloom_sst_miss_count
931                .with_label_values(&[cf_name])
932                .inc_by(perf_context.metric(PerfMetric::BloomSstMissCount));
933            self.key_lock_wait_time
934                .with_label_values(&[cf_name])
935                .inc_by(perf_context.metric(PerfMetric::KeyLockWaitTime));
936            self.key_lock_wait_count
937                .with_label_values(&[cf_name])
938                .inc_by(perf_context.metric(PerfMetric::KeyLockWaitCount));
939            self.internal_delete_skipped_count
940                .with_label_values(&[cf_name])
941                .inc_by(perf_context.metric(PerfMetric::InternalDeleteSkippedCount));
942            self.internal_skipped_count
943                .with_label_values(&[cf_name])
944                .inc_by(perf_context.metric(PerfMetric::InternalKeySkippedCount));
945        });
946    }
947}
948
949#[derive(Debug)]
950pub struct WritePerfContextMetrics {
951    pub write_wal_nanos: IntCounterVec,
952    pub write_memtable_nanos: IntCounterVec,
953    pub write_delay_nanos: IntCounterVec,
954    pub write_pre_and_post_process_nanos: IntCounterVec,
955    pub write_db_mutex_lock_nanos: IntCounterVec,
956    pub write_db_condition_wait_nanos: IntCounterVec,
957    pub write_key_lock_wait_nanos: IntCounterVec,
958    pub write_key_lock_wait_count: IntCounterVec,
959}
960
961impl WritePerfContextMetrics {
962    pub(crate) fn new(registry: &Registry) -> Self {
963        WritePerfContextMetrics {
964            write_wal_nanos: register_int_counter_vec_with_registry!(
965                "write_wal_nanos",
966                "Total nanos spent on writing to WAL",
967                &["cf_name"],
968                registry;
969                MetricLevel::Trace,
970            )
971            .unwrap(),
972            write_memtable_nanos: register_int_counter_vec_with_registry!(
973                "write_memtable_nanos",
974                "Total nanos spent on writing to memtable",
975                &["cf_name"],
976                registry;
977                MetricLevel::Trace,
978            )
979            .unwrap(),
980            write_delay_nanos: register_int_counter_vec_with_registry!(
981                "write_delay_nanos",
982                "Total nanos spent on delaying or throttling write",
983                &["cf_name"],
984                registry;
985                MetricLevel::Trace,
986            )
987            .unwrap(),
988            write_pre_and_post_process_nanos: register_int_counter_vec_with_registry!(
989                "write_pre_and_post_process_nanos",
990                "Total nanos spent on writing a record, excluding the above four things",
991                &["cf_name"],
992                registry;
993                MetricLevel::Trace,
994            )
995            .unwrap(),
996            write_db_mutex_lock_nanos: register_int_counter_vec_with_registry!(
997                "write_db_mutex_lock_nanos",
998                "Time spent on acquiring db mutex",
999                &["cf_name"],
1000                registry;
1001                MetricLevel::Trace,
1002            )
1003            .unwrap(),
1004            write_db_condition_wait_nanos: register_int_counter_vec_with_registry!(
1005                "write_db_condition_wait_nanos",
1006                "Time spent waiting with a condition variable created with DB Mutex.",
1007                &["cf_name"],
1008                registry;
1009                MetricLevel::Trace,
1010            )
1011            .unwrap(),
1012            write_key_lock_wait_nanos: register_int_counter_vec_with_registry!(
1013                "write_key_lock_wait_time",
1014                "Time spent waiting on key locks in transaction lock manager",
1015                &["cf_name"],
1016                registry;
1017                MetricLevel::Trace,
1018            )
1019            .unwrap(),
1020            write_key_lock_wait_count: register_int_counter_vec_with_registry!(
1021                "write_key_lock_wait_count",
1022                "Number of times acquiring a lock was blocked by another transaction",
1023                &["cf_name"],
1024                registry;
1025                MetricLevel::Trace,
1026            )
1027            .unwrap(),
1028        }
1029    }
1030    pub fn report_metrics(&self, db_name: &str) {
1031        PER_THREAD_ROCKS_PERF_CONTEXT.with(|perf_context_cell| {
1032            set_perf_stats(PerfStatsLevel::Disable);
1033            let perf_context = perf_context_cell.borrow();
1034            self.write_wal_nanos
1035                .with_label_values(&[db_name])
1036                .inc_by(perf_context.metric(PerfMetric::WriteWalTime));
1037            self.write_memtable_nanos
1038                .with_label_values(&[db_name])
1039                .inc_by(perf_context.metric(PerfMetric::WriteMemtableTime));
1040            self.write_delay_nanos
1041                .with_label_values(&[db_name])
1042                .inc_by(perf_context.metric(PerfMetric::WriteDelayTime));
1043            self.write_pre_and_post_process_nanos
1044                .with_label_values(&[db_name])
1045                .inc_by(perf_context.metric(PerfMetric::WritePreAndPostProcessTime));
1046            self.write_db_mutex_lock_nanos
1047                .with_label_values(&[db_name])
1048                .inc_by(perf_context.metric(PerfMetric::DbMutexLockNanos));
1049            self.write_db_condition_wait_nanos
1050                .with_label_values(&[db_name])
1051                .inc_by(perf_context.metric(PerfMetric::DbConditionWaitNanos));
1052            self.write_key_lock_wait_nanos
1053                .with_label_values(&[db_name])
1054                .inc_by(perf_context.metric(PerfMetric::KeyLockWaitTime));
1055            self.write_key_lock_wait_count
1056                .with_label_values(&[db_name])
1057                .inc_by(perf_context.metric(PerfMetric::KeyLockWaitCount));
1058        });
1059    }
1060}
1061
1062#[derive(Debug)]
1063pub struct DBMetrics {
1064    pub op_metrics: OperationMetrics,
1065    pub cf_metrics: ColumnFamilyMetrics,
1066    pub read_perf_ctx_metrics: ReadPerfContextMetrics,
1067    pub write_perf_ctx_metrics: WritePerfContextMetrics,
1068}
1069
1070static ONCE: OnceCell<Arc<DBMetrics>> = OnceCell::new();
1071
1072impl DBMetrics {
1073    fn new(registry: &Registry) -> Self {
1074        DBMetrics {
1075            op_metrics: OperationMetrics::new(registry),
1076            cf_metrics: ColumnFamilyMetrics::new(registry),
1077            read_perf_ctx_metrics: ReadPerfContextMetrics::new(registry),
1078            write_perf_ctx_metrics: WritePerfContextMetrics::new(registry),
1079        }
1080    }
1081    pub fn init(registry: &Registry) -> &'static Arc<DBMetrics> {
1082        // Initialize this before creating any instance of DBMap
1083        // TODO: Remove static initialization because this basically means we can
1084        // only ever initialize db metrics once with a registry whereas
1085        // in the code we might want to initialize it with different
1086        // registries. The problem is underlying metrics cannot be re-initialized
1087        // or prometheus complains. We essentially need to pass in DBMetrics
1088        // everywhere we create DBMap as the right fix
1089        let _ = ONCE
1090            .set(Arc::new(DBMetrics::new(registry)))
1091            // this happens many times during tests
1092            .tap_err(|_| warn!("DBMetrics registry overwritten"));
1093        ONCE.get().unwrap()
1094    }
1095    pub fn increment_num_active_dbs(&self, db_name: &str) {
1096        self.op_metrics
1097            .rocksdb_num_active_db_handles
1098            .with_label_values(&[db_name])
1099            .inc();
1100    }
1101    pub fn decrement_num_active_dbs(&self, db_name: &str) {
1102        self.op_metrics
1103            .rocksdb_num_active_db_handles
1104            .with_label_values(&[db_name])
1105            .dec();
1106    }
1107    /// Removes `cf_name`'s series from every per-column-family metric, for a
1108    /// column family that has been dropped: a store that drops one per epoch
1109    /// would otherwise keep publishing the series of every epoch it held.
1110    pub fn remove_column_family(&self, cf_name: &str) {
1111        macro_rules! remove {
1112            ($($metric:expr),* $(,)?) => {
1113                $(
1114                    // Absent if the column family was never used.
1115                    let _ = $metric.remove_label_values(&[cf_name]);
1116                )*
1117            };
1118        }
1119        remove!(
1120            self.cf_metrics.rocksdb_total_sst_files_size,
1121            self.cf_metrics.rocksdb_total_blob_files_size,
1122            self.cf_metrics.rocksdb_total_num_files,
1123            self.cf_metrics.rocksdb_num_level0_files,
1124            self.cf_metrics.rocksdb_current_size_active_mem_tables,
1125            self.cf_metrics.rocksdb_size_all_mem_tables,
1126            self.cf_metrics.rocksdb_num_snapshots,
1127            self.cf_metrics.rocksdb_oldest_snapshot_time,
1128            self.cf_metrics.rocksdb_actual_delayed_write_rate,
1129            self.cf_metrics.rocksdb_is_write_stopped,
1130            self.cf_metrics.rocksdb_block_cache_capacity,
1131            self.cf_metrics.rocksdb_block_cache_usage,
1132            self.cf_metrics.rocksdb_block_cache_pinned_usage,
1133            self.cf_metrics.rocksdb_estimate_table_readers_mem,
1134            self.cf_metrics.rocksdb_num_immutable_mem_tables,
1135            self.cf_metrics.rocksdb_mem_table_flush_pending,
1136            self.cf_metrics.rocksdb_compaction_pending,
1137            self.cf_metrics.rocksdb_estimate_pending_compaction_bytes,
1138            self.cf_metrics.rocksdb_num_running_compactions,
1139            self.cf_metrics.rocksdb_num_running_flushes,
1140            self.cf_metrics.rocksdb_estimate_oldest_key_time,
1141            self.cf_metrics.rocksdb_background_errors,
1142            self.cf_metrics.rocksdb_estimated_num_keys,
1143            self.cf_metrics.rocksdb_base_level,
1144            self.op_metrics.rocksdb_iter_latency_seconds,
1145            self.op_metrics.rocksdb_iter_bytes,
1146            self.op_metrics.rocksdb_iter_keys,
1147            self.op_metrics.rocksdb_get_latency_seconds,
1148            self.op_metrics.rocksdb_get_bytes,
1149            self.op_metrics.rocksdb_multiget_latency_seconds,
1150            self.op_metrics.rocksdb_multiget_bytes,
1151            self.op_metrics.rocksdb_put_latency_seconds,
1152            self.op_metrics.rocksdb_put_bytes,
1153            self.op_metrics.rocksdb_batch_put_bytes,
1154            self.op_metrics.rocksdb_delete_latency_seconds,
1155            self.op_metrics.rocksdb_deletes,
1156            self.op_metrics.rocksdb_very_slow_puts_count,
1157            self.op_metrics.rocksdb_very_slow_puts_duration_ms,
1158            self.read_perf_ctx_metrics.user_key_comparison_count,
1159            self.read_perf_ctx_metrics.block_cache_hit_count,
1160            self.read_perf_ctx_metrics.block_read_count,
1161            self.read_perf_ctx_metrics.block_read_byte,
1162            self.read_perf_ctx_metrics.block_read_nanos,
1163            self.read_perf_ctx_metrics.block_checksum_nanos,
1164            self.read_perf_ctx_metrics.block_decompress_nanos,
1165            self.read_perf_ctx_metrics.get_read_bytes,
1166            self.read_perf_ctx_metrics.multiget_read_bytes,
1167            self.read_perf_ctx_metrics.get_snapshot_nanos,
1168            self.read_perf_ctx_metrics.get_from_memtable_nanos,
1169            self.read_perf_ctx_metrics.get_from_memtable_count,
1170            self.read_perf_ctx_metrics.get_post_process_nanos,
1171            self.read_perf_ctx_metrics.get_from_output_files_nanos,
1172            self.read_perf_ctx_metrics.db_mutex_lock_nanos,
1173            self.read_perf_ctx_metrics.db_condition_wait_nanos,
1174            self.read_perf_ctx_metrics.merge_operator_nanos,
1175            self.read_perf_ctx_metrics.read_index_block_nanos,
1176            self.read_perf_ctx_metrics.read_filter_block_nanos,
1177            self.read_perf_ctx_metrics.new_table_block_iter_nanos,
1178            self.read_perf_ctx_metrics.block_seek_nanos,
1179            self.read_perf_ctx_metrics.find_table_nanos,
1180            self.read_perf_ctx_metrics.bloom_memtable_hit_count,
1181            self.read_perf_ctx_metrics.bloom_memtable_miss_count,
1182            self.read_perf_ctx_metrics.bloom_sst_hit_count,
1183            self.read_perf_ctx_metrics.bloom_sst_miss_count,
1184            self.read_perf_ctx_metrics.key_lock_wait_time,
1185            self.read_perf_ctx_metrics.key_lock_wait_count,
1186            self.read_perf_ctx_metrics.internal_delete_skipped_count,
1187            self.read_perf_ctx_metrics.internal_skipped_count,
1188            self.write_perf_ctx_metrics.write_wal_nanos,
1189            self.write_perf_ctx_metrics.write_memtable_nanos,
1190            self.write_perf_ctx_metrics.write_delay_nanos,
1191            self.write_perf_ctx_metrics.write_pre_and_post_process_nanos,
1192            self.write_perf_ctx_metrics.write_db_mutex_lock_nanos,
1193            self.write_perf_ctx_metrics.write_db_condition_wait_nanos,
1194            self.write_perf_ctx_metrics.write_key_lock_wait_nanos,
1195            self.write_perf_ctx_metrics.write_key_lock_wait_count,
1196        );
1197    }
1198
1199    pub fn get() -> &'static Arc<DBMetrics> {
1200        // Lazily initialize against the global default registry when no explicit
1201        // `init` has run. `get_or_init` ensures the rocksdb metrics are
1202        // registered at most once even when first reached concurrently.
1203        ONCE.get_or_init(|| Arc::new(DBMetrics::new(prometheus_filtered::default_registry())))
1204    }
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209    use std::time::Duration;
1210
1211    use crate::metrics::SamplingInterval;
1212
1213    // `RuntimeMetrics` is not provided by the deterministic simulator's tokio
1214    // fork. Under the simulator `#[tokio::test]` is turned into an ignored test
1215    // anyway, so this turns off nothing that would otherwise run.
1216    #[cfg(not(msim))]
1217    fn alive_tasks() -> usize {
1218        tokio::runtime::Handle::current()
1219            .metrics()
1220            .num_alive_tasks()
1221    }
1222
1223    /// A timed interval keeps a task resetting its counter, and that task stops
1224    /// once the last clone of the interval is dropped.
1225    #[cfg(not(msim))]
1226    #[tokio::test]
1227    async fn a_dropped_interval_stops_its_task() {
1228        let tasks_before = alive_tasks();
1229        let interval = SamplingInterval::new(Duration::from_millis(10), 0);
1230        let clone = interval.clone();
1231        assert_eq!(alive_tasks(), tasks_before + 1);
1232
1233        drop(interval);
1234        drop(clone);
1235        for _ in 0..100 {
1236            if alive_tasks() == tasks_before {
1237                return;
1238            }
1239            tokio::time::sleep(Duration::from_millis(10)).await;
1240        }
1241        assert_eq!(
1242            alive_tasks(),
1243            tasks_before,
1244            "the task outlived the interval"
1245        );
1246    }
1247}