Skip to main content

zebrad/components/
metrics.rs

1//! An HTTP endpoint for metrics collection.
2
3#![allow(non_local_definitions)]
4
5use std::net::SocketAddr;
6
7use abscissa_core::{Component, FrameworkError, FrameworkErrorKind};
8use metrics::Recorder;
9use serde::{Deserialize, Serialize};
10
11pub mod catalog;
12mod process_memory;
13
14#[cfg(all(test, feature = "sentry"))]
15pub(crate) use process_memory::record;
16pub use process_memory::record_process_memory;
17
18pub(crate) mod node_context;
19#[cfg(feature = "sentry")]
20pub(crate) mod sentry_policy;
21
22// `metrics-process` describes fewer metrics on Windows, so the catalog only matches elsewhere.
23#[cfg(all(test, not(target_os = "windows")))]
24mod tests;
25
26/// How often the process metrics are sampled.
27#[cfg(not(windows))]
28const PROCESS_METRICS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15);
29
30/// Bucket upper bounds for work that usually takes well under a millisecond.
31const SUB_MILLISECOND_BUCKETS: &[f64] = &[
32    0.00001, 0.00005, 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25,
33    0.5, 1.0,
34];
35
36/// Bucket upper bounds for block verification, block template, and announcement latency.
37const BLOCK_LATENCY_BUCKETS: &[f64] = &[
38    0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0,
39];
40
41/// Bucket upper bounds for downloads from peers.
42const DOWNLOAD_BUCKETS: &[f64] = &[
43    0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0,
44];
45
46/// The histograms that Prometheus exports as histograms with these bucket upper bounds, in
47/// seconds. Every other histogram is exported as a summary with quantiles.
48///
49/// Adding a histogram here removes its `quantile` series, which breaks queries that use them.
50pub const HISTOGRAM_BUCKETS: &[(&str, &[f64])] = &[
51    (
52        "zebra.consensus.block.phase.duration_seconds",
53        BLOCK_LATENCY_BUCKETS,
54    ),
55    (
56        "state.block_writer.phase.duration_seconds",
57        SUB_MILLISECOND_BUCKETS,
58    ),
59    (
60        "zebra.net.block.decode.wait_seconds",
61        SUB_MILLISECOND_BUCKETS,
62    ),
63    (
64        "zebra.net.block.decode.duration_seconds",
65        SUB_MILLISECOND_BUCKETS,
66    ),
67    ("gossip.block.download.duration_seconds", DOWNLOAD_BUCKETS),
68    (
69        "gossip.block.verify_commit.duration_seconds",
70        BLOCK_LATENCY_BUCKETS,
71    ),
72    (
73        "rpc.getblocktemplate.build.duration_seconds",
74        BLOCK_LATENCY_BUCKETS,
75    ),
76    (
77        "rpc.getblocktemplate.first_template.duration_seconds",
78        BLOCK_LATENCY_BUCKETS,
79    ),
80    (
81        "sync.mined.block.announcement.duration_seconds",
82        BLOCK_LATENCY_BUCKETS,
83    ),
84    (
85        "mempool.tip_cleanup.duration_seconds",
86        SUB_MILLISECOND_BUCKETS,
87    ),
88    ("mempool.expiry.duration_seconds", SUB_MILLISECOND_BUCKETS),
89    (
90        "rpc.request.duration_seconds",
91        &[
92            0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0,
93        ],
94    ),
95    (
96        "zcash.net.peer.handshake.duration_seconds",
97        &[
98            0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0, 30.0,
99        ],
100    ),
101];
102
103/// Abscissa component which runs a metrics endpoint.
104#[derive(Debug, Component)]
105pub struct MetricsEndpoint {}
106
107impl MetricsEndpoint {
108    /// Create the component.
109    pub fn new(config: &Config) -> Result<Self, FrameworkError> {
110        #[cfg(feature = "sentry")]
111        let sentry = crate::sentry::metrics_recorder();
112        #[cfg(not(feature = "sentry"))]
113        let sentry = None::<metrics::NoopRecorder>;
114
115        let recorder_installed = if let Some(addr) = config.endpoint_addr {
116            Self::open_endpoint(addr, sentry)?
117        } else if let Some(sentry) = sentry {
118            install(sentry)?;
119            true
120        } else {
121            false
122        };
123
124        if recorder_installed {
125            spawn_process_metrics();
126        }
127
128        Ok(Self {})
129    }
130
131    /// Opens the Prometheus endpoint, also recording metrics with `other` if it is provided.
132    ///
133    /// Returns whether a global recorder was installed.
134    #[cfg(feature = "prometheus")]
135    fn open_endpoint<R>(addr: SocketAddr, other: Option<R>) -> Result<bool, FrameworkError>
136    where
137        R: Recorder + Send + Sync + 'static,
138    {
139        info!("Trying to open metrics endpoint at {}...", addr);
140
141        let builder = prometheus_builder()
142            .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?
143            .with_http_listener(addr);
144
145        match install_with_prometheus(builder, other) {
146            Ok(()) => info!("Opened metrics endpoint at {}", addr),
147            Err(e) => panic!(
148                "Opening metrics endpoint listener {addr:?} failed: {e:?}. \
149                 Hint: Check if another zebrad or zcashd process is running. \
150                 Try changing the metrics endpoint_addr in the Zebra config.",
151            ),
152        }
153
154        Ok(true)
155    }
156
157    /// Warns that the endpoint can't be opened, and records metrics with `other` if it is
158    /// provided.
159    ///
160    /// Returns whether a global recorder was installed.
161    #[cfg(not(feature = "prometheus"))]
162    fn open_endpoint<R>(addr: SocketAddr, other: Option<R>) -> Result<bool, FrameworkError>
163    where
164        R: Recorder + Send + Sync + 'static,
165    {
166        warn!(
167            ?addr,
168            "unable to activate configured metrics endpoint: \
169             enable the 'prometheus' feature when compiling zebrad",
170        );
171
172        other.map_or(Ok(false), |other| install(other).map(|()| true))
173    }
174}
175
176/// Describes every metric Zebra records to the current recorder.
177///
178/// Call this right after installing the global recorder: descriptions sent while no recorder is
179/// installed are lost.
180pub fn describe_all() {
181    zebra_consensus::metrics::describe();
182    zebra_network::metrics::describe();
183    zebra_state::metrics::describe();
184    zebra_rpc::metrics::describe();
185    catalog::describe();
186    #[cfg(not(windows))]
187    describe_process_metrics();
188}
189
190/// Describes the process metrics recorded by [`spawn_process_metrics`].
191#[cfg(not(windows))]
192fn describe_process_metrics() {
193    use metrics::{describe_counter, describe_gauge, Unit};
194
195    describe_counter!(
196        "process_cpu_seconds_total",
197        Unit::Seconds,
198        "Total user and system CPU time spent in seconds."
199    );
200    for (name, unit, description) in [
201        (
202            "process_open_fds",
203            Unit::Count,
204            "Number of open file descriptors.",
205        ),
206        (
207            "process_max_fds",
208            Unit::Count,
209            "Maximum number of open file descriptors.",
210        ),
211        (
212            "process_virtual_memory_bytes",
213            Unit::Bytes,
214            "Virtual memory size in bytes.",
215        ),
216        (
217            "process_virtual_memory_max_bytes",
218            Unit::Bytes,
219            "Maximum amount of virtual memory available in bytes.",
220        ),
221        (
222            "process_resident_memory_bytes",
223            Unit::Bytes,
224            "Resident memory size in bytes.",
225        ),
226        (
227            "process_start_time_seconds",
228            Unit::Seconds,
229            "Start time of the process since unix epoch in seconds.",
230        ),
231        (
232            "process_threads",
233            Unit::Count,
234            "Number of OS threads in the process.",
235        ),
236    ] {
237        describe_gauge!(name, unit, description);
238    }
239}
240
241/// Describes every metric, registers the failure counters at zero, and records the build info
242/// once, through the recorder that was just installed, whichever backends it sends to.
243fn describe_and_record_build_info() {
244    describe_all();
245    zebra_consensus::metrics::register_failure_counters();
246
247    // A single series with value 1 exposes the version:
248    // https://www.robustperception.io/exposing-the-software-version-to-prometheus
249    metrics::counter!(
250        concat!(env!("CARGO_PKG_NAME"), ".build.info"),
251        "version" => env!("CARGO_PKG_VERSION"),
252        "commit" => crate::application::ZebradApp::git_commit().unwrap_or("unknown"),
253    )
254    .increment(1);
255}
256
257/// Records the process metrics through the global recorder, which must already be installed.
258///
259/// Samples once immediately, then every [`PROCESS_METRICS_INTERVAL`] on a dedicated thread, so
260/// the readings neither depend on a backend nor run on a Tokio worker.
261#[cfg(not(windows))]
262fn spawn_process_metrics() {
263    record_process_metrics();
264
265    let sampler = std::thread::Builder::new()
266        .name("process-metrics".to_owned())
267        .spawn(|| loop {
268            std::thread::sleep(PROCESS_METRICS_INTERVAL);
269            record_process_metrics();
270        });
271    if let Err(error) = sampler {
272        warn!(?error, "unable to start periodic process metrics");
273    }
274}
275
276/// Process metrics aren't recorded on Windows, see the `metrics-process` dependency.
277#[cfg(windows)]
278fn spawn_process_metrics() {}
279
280/// Records one sample of the process metrics.
281#[cfg(not(windows))]
282fn record_process_metrics() {
283    let sample = metrics_process::collector::collect();
284
285    if let Some(seconds) = sample.cpu_seconds_total {
286        // `metrics` counters only hold whole numbers, so this drops the fraction of a second.
287        metrics::counter!("process_cpu_seconds_total").absolute(seconds as u64);
288    }
289
290    // `metrics-process` reports an unlimited maximum as 0, which isn't a usable maximum.
291    let limited = |max: Option<u64>| max.filter(|&max| max != 0);
292
293    for (name, value) in [
294        ("process_open_fds", sample.open_fds),
295        ("process_max_fds", limited(sample.max_fds)),
296        ("process_virtual_memory_bytes", sample.virtual_memory_bytes),
297        (
298            "process_virtual_memory_max_bytes",
299            limited(sample.virtual_memory_max_bytes),
300        ),
301        (
302            "process_resident_memory_bytes",
303            sample.resident_memory_bytes,
304        ),
305        ("process_start_time_seconds", sample.start_time_seconds),
306        ("process_threads", sample.threads),
307    ] {
308        if let Some(value) = value {
309            // Process sizes, counts, and times stay far below 2^53, so `f64` holds them exactly.
310            metrics::gauge!(name).set(value as f64);
311        }
312    }
313}
314
315/// Installs `recorder` as the global metrics recorder, then describes every metric and records
316/// the build info through it.
317fn install<R>(recorder: R) -> Result<(), FrameworkError>
318where
319    R: Recorder + Send + Sync + 'static,
320{
321    metrics::set_global_recorder(recorder)
322        .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?;
323    describe_and_record_build_info();
324
325    Ok(())
326}
327
328/// Returns the Prometheus exporter's configuration, before its endpoint is added.
329#[cfg(feature = "prometheus")]
330fn prometheus_builder(
331) -> Result<metrics_exporter_prometheus::PrometheusBuilder, metrics_exporter_prometheus::BuildError>
332{
333    HISTOGRAM_BUCKETS.iter().try_fold(
334        metrics_exporter_prometheus::PrometheusBuilder::new(),
335        |builder, (name, buckets)| {
336            builder.set_buckets_for_metric(
337                metrics_exporter_prometheus::Matcher::Full((*name).to_owned()),
338                buckets,
339            )
340        },
341    )
342}
343
344/// Returns the recorder that receives every metric: `prometheus`, and `other` beside it if it is
345/// provided.
346#[cfg(feature = "prometheus")]
347fn with_prometheus<R>(
348    prometheus: metrics_exporter_prometheus::PrometheusRecorder,
349    other: Option<R>,
350) -> Box<dyn Recorder + Sync>
351where
352    R: Recorder + Send + Sync + 'static,
353{
354    use metrics_util::layers::FanoutBuilder;
355
356    match other {
357        Some(other) => Box::new(
358            FanoutBuilder::default()
359                .add_recorder(prometheus)
360                .add_recorder(other)
361                .build(),
362        ),
363        None => Box::new(prometheus),
364    }
365}
366
367/// Installs the Prometheus recorder from `builder`, with `other` beside it if it is provided, as
368/// the global recorder, then describes every metric and records the build info through it.
369///
370/// The build info is recorded before this returns, so it is already exported when the caller
371/// logs that the endpoint is open.
372///
373/// Like [`PrometheusBuilder::install`] outside a Tokio runtime, which is how Zebra calls it, this
374/// serves the endpoint from its own thread.
375///
376/// [`PrometheusBuilder::install`]: metrics_exporter_prometheus::PrometheusBuilder::install
377#[cfg(feature = "prometheus")]
378fn install_with_prometheus<R>(
379    builder: metrics_exporter_prometheus::PrometheusBuilder,
380    other: Option<R>,
381) -> Result<(), crate::BoxError>
382where
383    R: Recorder + Send + Sync + 'static,
384{
385    use metrics_exporter_prometheus::BuildError;
386
387    let runtime = tokio::runtime::Builder::new_current_thread()
388        .enable_all()
389        .build()
390        .map_err(|e| BuildError::FailedToCreateRuntime(e.to_string()))?;
391
392    let (prometheus, exporter) = {
393        let _guard = runtime.enter();
394        builder.build()?
395    };
396
397    std::thread::Builder::new()
398        .name("metrics-exporter-prometheus-http".to_owned())
399        .spawn(move || runtime.block_on(exporter))
400        .map_err(|e| BuildError::FailedToCreateRuntime(e.to_string()))?;
401
402    metrics::set_global_recorder(with_prometheus(prometheus, other)).map_err(|e| e.to_string())?;
403    describe_and_record_build_info();
404
405    Ok(())
406}
407
408/// Metrics configuration section.
409#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
410#[serde(deny_unknown_fields, default)]
411pub struct Config {
412    /// The address used for the Prometheus metrics endpoint.
413    ///
414    /// Install Zebra using `cargo install --features=prometheus` to enable this config.
415    ///
416    /// The endpoint is disabled if this is set to `None`.
417    pub endpoint_addr: Option<SocketAddr>,
418}
419
420// we like our default configs to be explicit
421#[allow(unknown_lints)]
422#[allow(clippy::derivable_impls)]
423impl Default for Config {
424    fn default() -> Self {
425        Self {
426            endpoint_addr: None,
427        }
428    }
429}