Skip to main content

reth_node_metrics/
recorder.rs

1//! Prometheus recorder
2
3use eyre::WrapErr;
4use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
5use metrics_util::layers::{PrefixLayer, Stack};
6use parking_lot::Mutex;
7use std::{collections::HashMap, sync::OnceLock};
8use tokio::{runtime, task::JoinHandle};
9use tracing::Instrument;
10
11/// Installs the Prometheus recorder as the global recorder.
12///
13/// Note: This must be installed before any metrics are `described`.
14///
15/// Caution: This only configures the global recorder and does not spawn the exporter.
16/// Callers must run [`PrometheusRecorder::spawn_upkeep`] manually.
17///
18/// Use [`init_prometheus_recorder`] to install a custom recorder.
19pub fn install_prometheus_recorder() -> &'static PrometheusRecorder {
20    PROMETHEUS_RECORDER_HANDLE.get_or_init(|| {
21        PrometheusRecorder::install().expect("Failed to install Prometheus recorder")
22    })
23}
24
25/// Installs the provided recorder as the global recorder.
26///
27/// To customize the builder, first construct a recorder with
28/// [`PrometheusRecorder::install_with_builder`], then pass it here.
29///
30/// # Panics
31///
32/// Panics if a recorder has already been installed.
33pub fn init_prometheus_recorder(recorder: PrometheusRecorder) -> &'static PrometheusRecorder {
34    PROMETHEUS_RECORDER_HANDLE.set(recorder).expect("Prometheus recorder already installed");
35    PROMETHEUS_RECORDER_HANDLE.get().expect("Prometheus recorder is set")
36}
37
38/// The default Prometheus recorder handle. We use a global static to ensure that it is only
39/// installed once.
40static PROMETHEUS_RECORDER_HANDLE: OnceLock<PrometheusRecorder> = OnceLock::new();
41
42/// Installs the Prometheus recorder with a custom builder.
43///
44/// Returns an error if a recorder has already been installed.
45pub fn try_install_prometheus_recorder_with_builder(
46    builder: PrometheusBuilder,
47) -> eyre::Result<&'static PrometheusRecorder> {
48    let recorder = PrometheusRecorder::install_with_builder(builder)?;
49    PROMETHEUS_RECORDER_HANDLE
50        .set(recorder)
51        .map_err(|_| eyre::eyre!("Prometheus recorder already installed"))?;
52    Ok(PROMETHEUS_RECORDER_HANDLE.get().expect("recorder is set"))
53}
54
55/// A handle to the Prometheus recorder.
56///
57/// This is intended to be used as the global recorder.
58/// Callers must call [`PrometheusRecorder::spawn_upkeep`] on a runtime that drives upkeep.
59#[derive(Debug)]
60pub struct PrometheusRecorder {
61    handle: PrometheusHandle,
62    upkeep: Mutex<HashMap<runtime::Id, JoinHandle<()>>>,
63}
64
65impl PrometheusRecorder {
66    fn new(handle: PrometheusHandle) -> Self {
67        Self { handle, upkeep: Default::default() }
68    }
69
70    /// Returns a reference to the [`PrometheusHandle`].
71    pub const fn handle(&self) -> &PrometheusHandle {
72        &self.handle
73    }
74
75    /// Spawns one upkeep task per Tokio runtime. Repeated calls on the same runtime reuse it.
76    ///
77    /// ## Panics
78    ///
79    /// This method must be called from within an existing Tokio runtime or it will panic.
80    ///
81    /// See also [`PrometheusHandle::run_upkeep`]
82    pub fn spawn_upkeep(&self) {
83        let runtime = runtime::Handle::current();
84        let mut upkeep = self.upkeep.lock();
85        upkeep.retain(|_, task| !task.is_finished());
86        upkeep.entry(runtime.id()).or_insert_with(|| {
87            let handle = self.handle.clone();
88            runtime.spawn(
89                async move {
90                    loop {
91                        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
92                        handle.run_upkeep();
93                    }
94                }
95                .in_current_span(),
96            )
97        });
98    }
99
100    /// Installs Prometheus as the metrics recorder.
101    ///
102    /// Caution: This only configures the global recorder and does not spawn the exporter.
103    /// Callers must run [`Self::spawn_upkeep`] manually.
104    pub fn install() -> eyre::Result<Self> {
105        Self::install_with_builder(PrometheusBuilder::new())
106    }
107
108    /// Installs Prometheus as the metrics recorder with a custom builder.
109    ///
110    /// Caution: This only configures the global recorder and does not spawn the exporter.
111    /// Callers must run [`Self::spawn_upkeep`] manually.
112    pub fn install_with_builder(builder: PrometheusBuilder) -> eyre::Result<Self> {
113        let recorder = builder.build_recorder();
114        let handle = recorder.handle();
115
116        // Build metrics stack
117        Stack::new(recorder)
118            .push(PrefixLayer::new("reth"))
119            .install()
120            .wrap_err("Couldn't set metrics recorder.")?;
121
122        Ok(Self::new(handle))
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    // Dependencies using different version of the `metrics` crate (to be exact, 0.21 vs 0.22)
131    // may not be able to communicate with each other through the global recorder.
132    //
133    // This test ensures that `metrics-process` dependency plays well with the current
134    // `metrics-exporter-prometheus` dependency version.
135    #[test]
136    fn process_metrics() {
137        let recorder = install_prometheus_recorder();
138
139        let process = metrics_process::Collector::default();
140        process.describe();
141        process.collect();
142
143        let metrics = recorder.handle().render();
144        assert!(metrics.contains("process_cpu_seconds_total"), "{metrics:?}");
145    }
146
147    #[test]
148    fn upkeep_follows_the_runtime_lifetime() {
149        let recorder = PrometheusRecorder::new(PrometheusBuilder::new().build_recorder().handle());
150        let first = runtime::Builder::new_current_thread().enable_time().build().unwrap();
151        let second = runtime::Builder::new_current_thread().enable_time().build().unwrap();
152
153        first.block_on(async { recorder.spawn_upkeep() });
154        second.block_on(async { recorder.spawn_upkeep() });
155        first.block_on(async { recorder.spawn_upkeep() });
156        assert_eq!(first.metrics().num_alive_tasks(), 1);
157        assert_eq!(second.metrics().num_alive_tasks(), 1);
158
159        drop(first);
160        second.block_on(async { recorder.spawn_upkeep() });
161        assert_eq!(second.metrics().num_alive_tasks(), 1);
162        assert_eq!(recorder.upkeep.lock().len(), 1);
163    }
164}