LCOV - code coverage report
Current view: top level - libs/metrics/src - lib.rs (source / functions) Coverage Total Hit
Test: 32f4a56327bc9da697706839ed4836b2a00a408f.info Lines: 80.2 % 96 77
Test Date: 2024-02-07 07:37:29 Functions: 57.1 % 28 16

            Line data    Source code
       1              : //! We re-export those from prometheus crate to
       2              : //! make sure that we use the same dep version everywhere.
       3              : //! Otherwise, we might not see all metrics registered via
       4              : //! a default registry.
       5              : #![deny(clippy::undocumented_unsafe_blocks)]
       6              : 
       7              : use once_cell::sync::Lazy;
       8              : use prometheus::core::{
       9              :     Atomic, AtomicU64, Collector, GenericCounter, GenericCounterVec, GenericGauge, GenericGaugeVec,
      10              : };
      11              : pub use prometheus::opts;
      12              : pub use prometheus::register;
      13              : pub use prometheus::Error;
      14              : pub use prometheus::{core, default_registry, proto};
      15              : pub use prometheus::{exponential_buckets, linear_buckets};
      16              : pub use prometheus::{register_counter_vec, Counter, CounterVec};
      17              : pub use prometheus::{register_gauge, Gauge};
      18              : pub use prometheus::{register_gauge_vec, GaugeVec};
      19              : pub use prometheus::{register_histogram, Histogram};
      20              : pub use prometheus::{register_histogram_vec, HistogramVec};
      21              : pub use prometheus::{register_int_counter, IntCounter};
      22              : pub use prometheus::{register_int_counter_vec, IntCounterVec};
      23              : pub use prometheus::{register_int_gauge, IntGauge};
      24              : pub use prometheus::{register_int_gauge_vec, IntGaugeVec};
      25              : pub use prometheus::{Encoder, TextEncoder};
      26              : use prometheus::{Registry, Result};
      27              : 
      28              : pub mod launch_timestamp;
      29              : mod wrappers;
      30              : pub use wrappers::{CountedReader, CountedWriter};
      31              : mod hll;
      32              : pub mod metric_vec_duration;
      33              : pub use hll::{HyperLogLog, HyperLogLogVec};
      34              : 
      35              : pub type UIntGauge = GenericGauge<AtomicU64>;
      36              : pub type UIntGaugeVec = GenericGaugeVec<AtomicU64>;
      37              : 
      38              : #[macro_export]
      39              : macro_rules! register_uint_gauge_vec {
      40              :     ($NAME:expr, $HELP:expr, $LABELS_NAMES:expr $(,)?) => {{
      41              :         let gauge_vec = UIntGaugeVec::new($crate::opts!($NAME, $HELP), $LABELS_NAMES).unwrap();
      42              :         $crate::register(Box::new(gauge_vec.clone())).map(|_| gauge_vec)
      43              :     }};
      44              : }
      45              : 
      46              : #[macro_export]
      47              : macro_rules! register_uint_gauge {
      48              :     ($NAME:expr, $HELP:expr $(,)?) => {{
      49              :         let gauge = $crate::UIntGauge::new($NAME, $HELP).unwrap();
      50              :         $crate::register(Box::new(gauge.clone())).map(|_| gauge)
      51              :     }};
      52              : }
      53              : 
      54              : /// Special internal registry, to collect metrics independently from the default registry.
      55              : /// Was introduced to fix deadlock with lazy registration of metrics in the default registry.
      56              : static INTERNAL_REGISTRY: Lazy<Registry> = Lazy::new(Registry::new);
      57              : 
      58              : /// Register a collector in the internal registry. MUST be called before the first call to `gather()`.
      59              : /// Otherwise, we can have a deadlock in the `gather()` call, trying to register a new collector
      60              : /// while holding the lock.
      61          510 : pub fn register_internal(c: Box<dyn Collector>) -> Result<()> {
      62          510 :     INTERNAL_REGISTRY.register(c)
      63          510 : }
      64              : 
      65              : /// Gathers all Prometheus metrics and records the I/O stats just before that.
      66              : ///
      67              : /// Metrics gathering is a relatively simple and standalone operation, so
      68              : /// it might be fine to do it this way to keep things simple.
      69         1255 : pub fn gather() -> Vec<prometheus::proto::MetricFamily> {
      70         1255 :     update_rusage_metrics();
      71         1255 :     let mut mfs = prometheus::gather();
      72         1255 :     let mut internal_mfs = INTERNAL_REGISTRY.gather();
      73         1255 :     mfs.append(&mut internal_mfs);
      74         1255 :     mfs
      75         1255 : }
      76              : 
      77          407 : static DISK_IO_BYTES: Lazy<IntGaugeVec> = Lazy::new(|| {
      78          407 :     register_int_gauge_vec!(
      79          407 :         "libmetrics_disk_io_bytes_total",
      80          407 :         "Bytes written and read from disk, grouped by the operation (read|write)",
      81          407 :         &["io_operation"]
      82          407 :     )
      83          407 :     .expect("Failed to register disk i/o bytes int gauge vec")
      84          407 : });
      85              : 
      86          407 : static MAXRSS_KB: Lazy<IntGauge> = Lazy::new(|| {
      87          407 :     register_int_gauge!(
      88          407 :         "libmetrics_maxrss_kb",
      89          407 :         "Memory usage (Maximum Resident Set Size)"
      90          407 :     )
      91          407 :     .expect("Failed to register maxrss_kb int gauge")
      92          407 : });
      93              : 
      94              : pub const DISK_WRITE_SECONDS_BUCKETS: &[f64] = &[
      95              :     0.000_050, 0.000_100, 0.000_500, 0.001, 0.003, 0.005, 0.01, 0.05, 0.1, 0.3, 0.5,
      96              : ];
      97              : 
      98         1140 : pub fn set_build_info_metric(revision: &str, build_tag: &str) {
      99         1140 :     let metric = register_int_gauge_vec!(
     100         1140 :         "libmetrics_build_info",
     101         1140 :         "Build/version information",
     102         1140 :         &["revision", "build_tag"]
     103         1140 :     )
     104         1140 :     .expect("Failed to register build info metric");
     105         1140 :     metric.with_label_values(&[revision, build_tag]).set(1);
     106         1140 : }
     107              : 
     108              : // Records I/O stats in a "cross-platform" way.
     109              : // Compiles both on macOS and Linux, but current macOS implementation always returns 0 as values for I/O stats.
     110              : // An alternative is to read procfs (`/proc/[pid]/io`) which does not work under macOS at all, hence abandoned.
     111              : //
     112              : // Uses https://www.freebsd.org/cgi/man.cgi?query=getrusage to retrieve the number of block operations
     113              : // performed by the process.
     114              : // We know the size of the block, so we can determine the I/O bytes out of it.
     115              : // The value might be not 100% exact, but should be fine for Prometheus metrics in this case.
     116              : #[allow(clippy::unnecessary_cast)]
     117         1255 : fn update_rusage_metrics() {
     118         1255 :     let rusage_stats = get_rusage_stats();
     119         1255 : 
     120         1255 :     const BYTES_IN_BLOCK: i64 = 512;
     121         1255 :     DISK_IO_BYTES
     122         1255 :         .with_label_values(&["read"])
     123         1255 :         .set(rusage_stats.ru_inblock * BYTES_IN_BLOCK);
     124         1255 :     DISK_IO_BYTES
     125         1255 :         .with_label_values(&["write"])
     126         1255 :         .set(rusage_stats.ru_oublock * BYTES_IN_BLOCK);
     127         1255 :     MAXRSS_KB.set(rusage_stats.ru_maxrss);
     128         1255 : }
     129              : 
     130         1255 : fn get_rusage_stats() -> libc::rusage {
     131         1255 :     let mut rusage = std::mem::MaybeUninit::uninit();
     132         1255 : 
     133         1255 :     // SAFETY: kernel will initialize the struct for us
     134         1255 :     unsafe {
     135         1255 :         let ret = libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr());
     136         1255 :         assert!(ret == 0, "getrusage failed: bad args");
     137         1255 :         rusage.assume_init()
     138         1255 :     }
     139         1255 : }
     140              : 
     141              : /// Create an [`IntCounterPairVec`] and registers to default registry.
     142              : #[macro_export(local_inner_macros)]
     143              : macro_rules! register_int_counter_pair_vec {
     144              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr, $LABELS_NAMES:expr $(,)?) => {{
     145              :         match (
     146              :             $crate::register_int_counter_vec!($NAME1, $HELP1, $LABELS_NAMES),
     147              :             $crate::register_int_counter_vec!($NAME2, $HELP2, $LABELS_NAMES),
     148              :         ) {
     149              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPairVec::new(inc, dec)),
     150              :             (Err(e), _) | (_, Err(e)) => Err(e),
     151              :         }
     152              :     }};
     153              : }
     154              : /// Create an [`IntCounterPair`] and registers to default registry.
     155              : #[macro_export(local_inner_macros)]
     156              : macro_rules! register_int_counter_pair {
     157              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr $(,)?) => {{
     158              :         match (
     159              :             $crate::register_int_counter!($NAME1, $HELP1),
     160              :             $crate::register_int_counter!($NAME2, $HELP2),
     161              :         ) {
     162              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPair::new(inc, dec)),
     163              :             (Err(e), _) | (_, Err(e)) => Err(e),
     164              :         }
     165              :     }};
     166              : }
     167              : 
     168              : /// A Pair of [`GenericCounterVec`]s. Like an [`GenericGaugeVec`] but will always observe changes
     169              : pub struct GenericCounterPairVec<P: Atomic> {
     170              :     inc: GenericCounterVec<P>,
     171              :     dec: GenericCounterVec<P>,
     172              : }
     173              : 
     174              : /// A Pair of [`GenericCounter`]s. Like an [`GenericGauge`] but will always observe changes
     175              : pub struct GenericCounterPair<P: Atomic> {
     176              :     inc: GenericCounter<P>,
     177              :     dec: GenericCounter<P>,
     178              : }
     179              : 
     180              : impl<P: Atomic> GenericCounterPairVec<P> {
     181         1001 :     pub fn new(inc: GenericCounterVec<P>, dec: GenericCounterVec<P>) -> Self {
     182         1001 :         Self { inc, dec }
     183         1001 :     }
     184              : 
     185              :     /// `get_metric_with_label_values` returns the [`GenericCounterPair<P>`] for the given slice
     186              :     /// of label values (same order as the VariableLabels in Desc). If that combination of
     187              :     /// label values is accessed for the first time, a new [`GenericCounterPair<P>`] is created.
     188              :     ///
     189              :     /// An error is returned if the number of label values is not the same as the
     190              :     /// number of VariableLabels in Desc.
     191         6454 :     pub fn get_metric_with_label_values(&self, vals: &[&str]) -> Result<GenericCounterPair<P>> {
     192         6454 :         Ok(GenericCounterPair {
     193         6454 :             inc: self.inc.get_metric_with_label_values(vals)?,
     194         6454 :             dec: self.dec.get_metric_with_label_values(vals)?,
     195              :         })
     196         6454 :     }
     197              : 
     198              :     /// `with_label_values` works as `get_metric_with_label_values`, but panics if an error
     199              :     /// occurs.
     200         6454 :     pub fn with_label_values(&self, vals: &[&str]) -> GenericCounterPair<P> {
     201         6454 :         self.get_metric_with_label_values(vals).unwrap()
     202         6454 :     }
     203              : }
     204              : 
     205              : impl<P: Atomic> GenericCounterPair<P> {
     206            7 :     pub fn new(inc: GenericCounter<P>, dec: GenericCounter<P>) -> Self {
     207            7 :         Self { inc, dec }
     208            7 :     }
     209              : 
     210              :     /// Increment the gauge by 1, returning a guard that decrements by 1 on drop.
     211         6461 :     pub fn guard(&self) -> GenericCounterPairGuard<P> {
     212         6461 :         self.inc.inc();
     213         6461 :         GenericCounterPairGuard(self.dec.clone())
     214         6461 :     }
     215              : 
     216              :     /// Increment the gauge by n, returning a guard that decrements by n on drop.
     217            0 :     pub fn guard_by(&self, n: P::T) -> GenericCounterPairGuardBy<P> {
     218            0 :         self.inc.inc_by(n);
     219            0 :         GenericCounterPairGuardBy(self.dec.clone(), n)
     220            0 :     }
     221              : 
     222              :     /// Increase the gauge by 1.
     223              :     #[inline]
     224            0 :     pub fn inc(&self) {
     225            0 :         self.inc.inc();
     226            0 :     }
     227              : 
     228              :     /// Decrease the gauge by 1.
     229              :     #[inline]
     230            0 :     pub fn dec(&self) {
     231            0 :         self.dec.inc();
     232            0 :     }
     233              : 
     234              :     /// Add the given value to the gauge. (The value can be
     235              :     /// negative, resulting in a decrement of the gauge.)
     236              :     #[inline]
     237            0 :     pub fn inc_by(&self, v: P::T) {
     238            0 :         self.inc.inc_by(v);
     239            0 :     }
     240              : 
     241              :     /// Subtract the given value from the gauge. (The value can be
     242              :     /// negative, resulting in an increment of the gauge.)
     243              :     #[inline]
     244            0 :     pub fn dec_by(&self, v: P::T) {
     245            0 :         self.dec.inc_by(v);
     246            0 :     }
     247              : }
     248              : 
     249              : /// Guard returned by [`GenericCounterPair::guard`]
     250              : pub struct GenericCounterPairGuard<P: Atomic>(GenericCounter<P>);
     251              : 
     252              : impl<P: Atomic> Drop for GenericCounterPairGuard<P> {
     253         6031 :     fn drop(&mut self) {
     254         6031 :         self.0.inc();
     255         6031 :     }
     256              : }
     257              : /// Guard returned by [`GenericCounterPair::guard_by`]
     258              : pub struct GenericCounterPairGuardBy<P: Atomic>(GenericCounter<P>, P::T);
     259              : 
     260              : impl<P: Atomic> Drop for GenericCounterPairGuardBy<P> {
     261            0 :     fn drop(&mut self) {
     262            0 :         self.0.inc_by(self.1);
     263            0 :     }
     264              : }
     265              : 
     266              : /// A Pair of [`IntCounterVec`]s. Like an [`IntGaugeVec`] but will always observe changes
     267              : pub type IntCounterPairVec = GenericCounterPairVec<AtomicU64>;
     268              : 
     269              : /// A Pair of [`IntCounter`]s. Like an [`IntGauge`] but will always observe changes
     270              : pub type IntCounterPair = GenericCounterPair<AtomicU64>;
     271              : 
     272              : /// A guard for [`IntCounterPair`] that will decrement the gauge on drop
     273              : pub type IntCounterPairGuard = GenericCounterPairGuard<AtomicU64>;
        

Generated by: LCOV version 2.1-beta