zebrad 7.2.0

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! An HTTP endpoint for metrics collection.

#![allow(non_local_definitions)]

use std::net::SocketAddr;

use abscissa_core::{Component, FrameworkError, FrameworkErrorKind};
use metrics::Recorder;
use serde::{Deserialize, Serialize};

pub mod catalog;
mod process_memory;

#[cfg(all(test, feature = "sentry"))]
pub(crate) use process_memory::record;
pub use process_memory::record_process_memory;

pub(crate) mod node_context;
#[cfg(feature = "sentry")]
pub(crate) mod sentry_policy;

// `metrics-process` describes fewer metrics on Windows, so the catalog only matches elsewhere.
#[cfg(all(test, not(target_os = "windows")))]
mod tests;

/// How often the process metrics are sampled.
#[cfg(not(windows))]
const PROCESS_METRICS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15);

/// Bucket upper bounds for work that usually takes well under a millisecond.
const SUB_MILLISECOND_BUCKETS: &[f64] = &[
    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,
    0.5, 1.0,
];

/// Bucket upper bounds for block verification, block template, and announcement latency.
const BLOCK_LATENCY_BUCKETS: &[f64] = &[
    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,
];

/// Bucket upper bounds for downloads from peers.
const DOWNLOAD_BUCKETS: &[f64] = &[
    0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0,
];

/// The histograms that Prometheus exports as histograms with these bucket upper bounds, in
/// seconds. Every other histogram is exported as a summary with quantiles.
///
/// Adding a histogram here removes its `quantile` series, which breaks queries that use them.
pub const HISTOGRAM_BUCKETS: &[(&str, &[f64])] = &[
    (
        "zebra.consensus.block.phase.duration_seconds",
        BLOCK_LATENCY_BUCKETS,
    ),
    (
        "state.block_writer.phase.duration_seconds",
        SUB_MILLISECOND_BUCKETS,
    ),
    (
        "zebra.net.block.decode.wait_seconds",
        SUB_MILLISECOND_BUCKETS,
    ),
    (
        "zebra.net.block.decode.duration_seconds",
        SUB_MILLISECOND_BUCKETS,
    ),
    ("gossip.block.download.duration_seconds", DOWNLOAD_BUCKETS),
    (
        "gossip.block.verify_commit.duration_seconds",
        BLOCK_LATENCY_BUCKETS,
    ),
    (
        "rpc.getblocktemplate.build.duration_seconds",
        BLOCK_LATENCY_BUCKETS,
    ),
    (
        "rpc.getblocktemplate.first_template.duration_seconds",
        BLOCK_LATENCY_BUCKETS,
    ),
    (
        "sync.mined.block.announcement.duration_seconds",
        BLOCK_LATENCY_BUCKETS,
    ),
    (
        "mempool.tip_cleanup.duration_seconds",
        SUB_MILLISECOND_BUCKETS,
    ),
    ("mempool.expiry.duration_seconds", SUB_MILLISECOND_BUCKETS),
    (
        "rpc.request.duration_seconds",
        &[
            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,
        ],
    ),
    (
        "zcash.net.peer.handshake.duration_seconds",
        &[
            0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0, 30.0,
        ],
    ),
];

/// Abscissa component which runs a metrics endpoint.
#[derive(Debug, Component)]
pub struct MetricsEndpoint {}

impl MetricsEndpoint {
    /// Create the component.
    pub fn new(config: &Config) -> Result<Self, FrameworkError> {
        #[cfg(feature = "sentry")]
        let sentry = crate::sentry::metrics_recorder();
        #[cfg(not(feature = "sentry"))]
        let sentry = None::<metrics::NoopRecorder>;

        let recorder_installed = if let Some(addr) = config.endpoint_addr {
            Self::open_endpoint(addr, sentry)?
        } else if let Some(sentry) = sentry {
            install(sentry)?;
            true
        } else {
            false
        };

        if recorder_installed {
            spawn_process_metrics();
        }

        Ok(Self {})
    }

    /// Opens the Prometheus endpoint, also recording metrics with `other` if it is provided.
    ///
    /// Returns whether a global recorder was installed.
    #[cfg(feature = "prometheus")]
    fn open_endpoint<R>(addr: SocketAddr, other: Option<R>) -> Result<bool, FrameworkError>
    where
        R: Recorder + Send + Sync + 'static,
    {
        info!("Trying to open metrics endpoint at {}...", addr);

        let builder = prometheus_builder()
            .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?
            .with_http_listener(addr);

        match install_with_prometheus(builder, other) {
            Ok(()) => info!("Opened metrics endpoint at {}", addr),
            Err(e) => panic!(
                "Opening metrics endpoint listener {addr:?} failed: {e:?}. \
                 Hint: Check if another zebrad or zcashd process is running. \
                 Try changing the metrics endpoint_addr in the Zebra config.",
            ),
        }

        Ok(true)
    }

    /// Warns that the endpoint can't be opened, and records metrics with `other` if it is
    /// provided.
    ///
    /// Returns whether a global recorder was installed.
    #[cfg(not(feature = "prometheus"))]
    fn open_endpoint<R>(addr: SocketAddr, other: Option<R>) -> Result<bool, FrameworkError>
    where
        R: Recorder + Send + Sync + 'static,
    {
        warn!(
            ?addr,
            "unable to activate configured metrics endpoint: \
             enable the 'prometheus' feature when compiling zebrad",
        );

        other.map_or(Ok(false), |other| install(other).map(|()| true))
    }
}

/// Describes every metric Zebra records to the current recorder.
///
/// Call this right after installing the global recorder: descriptions sent while no recorder is
/// installed are lost.
pub fn describe_all() {
    zebra_consensus::metrics::describe();
    zebra_network::metrics::describe();
    zebra_state::metrics::describe();
    zebra_rpc::metrics::describe();
    catalog::describe();
    #[cfg(not(windows))]
    describe_process_metrics();
}

/// Describes the process metrics recorded by [`spawn_process_metrics`].
#[cfg(not(windows))]
fn describe_process_metrics() {
    use metrics::{describe_counter, describe_gauge, Unit};

    describe_counter!(
        "process_cpu_seconds_total",
        Unit::Seconds,
        "Total user and system CPU time spent in seconds."
    );
    for (name, unit, description) in [
        (
            "process_open_fds",
            Unit::Count,
            "Number of open file descriptors.",
        ),
        (
            "process_max_fds",
            Unit::Count,
            "Maximum number of open file descriptors.",
        ),
        (
            "process_virtual_memory_bytes",
            Unit::Bytes,
            "Virtual memory size in bytes.",
        ),
        (
            "process_virtual_memory_max_bytes",
            Unit::Bytes,
            "Maximum amount of virtual memory available in bytes.",
        ),
        (
            "process_resident_memory_bytes",
            Unit::Bytes,
            "Resident memory size in bytes.",
        ),
        (
            "process_start_time_seconds",
            Unit::Seconds,
            "Start time of the process since unix epoch in seconds.",
        ),
        (
            "process_threads",
            Unit::Count,
            "Number of OS threads in the process.",
        ),
    ] {
        describe_gauge!(name, unit, description);
    }
}

/// Describes every metric, registers the failure counters at zero, and records the build info
/// once, through the recorder that was just installed, whichever backends it sends to.
fn describe_and_record_build_info() {
    describe_all();
    zebra_consensus::metrics::register_failure_counters();

    // A single series with value 1 exposes the version:
    // https://www.robustperception.io/exposing-the-software-version-to-prometheus
    metrics::counter!(
        concat!(env!("CARGO_PKG_NAME"), ".build.info"),
        "version" => env!("CARGO_PKG_VERSION"),
        "commit" => crate::application::ZebradApp::git_commit().unwrap_or("unknown"),
    )
    .increment(1);
}

/// Records the process metrics through the global recorder, which must already be installed.
///
/// Samples once immediately, then every [`PROCESS_METRICS_INTERVAL`] on a dedicated thread, so
/// the readings neither depend on a backend nor run on a Tokio worker.
#[cfg(not(windows))]
fn spawn_process_metrics() {
    record_process_metrics();

    let sampler = std::thread::Builder::new()
        .name("process-metrics".to_owned())
        .spawn(|| loop {
            std::thread::sleep(PROCESS_METRICS_INTERVAL);
            record_process_metrics();
        });
    if let Err(error) = sampler {
        warn!(?error, "unable to start periodic process metrics");
    }
}

/// Process metrics aren't recorded on Windows, see the `metrics-process` dependency.
#[cfg(windows)]
fn spawn_process_metrics() {}

/// Records one sample of the process metrics.
#[cfg(not(windows))]
fn record_process_metrics() {
    let sample = metrics_process::collector::collect();

    if let Some(seconds) = sample.cpu_seconds_total {
        // `metrics` counters only hold whole numbers, so this drops the fraction of a second.
        metrics::counter!("process_cpu_seconds_total").absolute(seconds as u64);
    }

    // `metrics-process` reports an unlimited maximum as 0, which isn't a usable maximum.
    let limited = |max: Option<u64>| max.filter(|&max| max != 0);

    for (name, value) in [
        ("process_open_fds", sample.open_fds),
        ("process_max_fds", limited(sample.max_fds)),
        ("process_virtual_memory_bytes", sample.virtual_memory_bytes),
        (
            "process_virtual_memory_max_bytes",
            limited(sample.virtual_memory_max_bytes),
        ),
        (
            "process_resident_memory_bytes",
            sample.resident_memory_bytes,
        ),
        ("process_start_time_seconds", sample.start_time_seconds),
        ("process_threads", sample.threads),
    ] {
        if let Some(value) = value {
            // Process sizes, counts, and times stay far below 2^53, so `f64` holds them exactly.
            metrics::gauge!(name).set(value as f64);
        }
    }
}

/// Installs `recorder` as the global metrics recorder, then describes every metric and records
/// the build info through it.
fn install<R>(recorder: R) -> Result<(), FrameworkError>
where
    R: Recorder + Send + Sync + 'static,
{
    metrics::set_global_recorder(recorder)
        .map_err(|e| FrameworkErrorKind::ComponentError.context(e))?;
    describe_and_record_build_info();

    Ok(())
}

/// Returns the Prometheus exporter's configuration, before its endpoint is added.
#[cfg(feature = "prometheus")]
fn prometheus_builder(
) -> Result<metrics_exporter_prometheus::PrometheusBuilder, metrics_exporter_prometheus::BuildError>
{
    HISTOGRAM_BUCKETS.iter().try_fold(
        metrics_exporter_prometheus::PrometheusBuilder::new(),
        |builder, (name, buckets)| {
            builder.set_buckets_for_metric(
                metrics_exporter_prometheus::Matcher::Full((*name).to_owned()),
                buckets,
            )
        },
    )
}

/// Returns the recorder that receives every metric: `prometheus`, and `other` beside it if it is
/// provided.
#[cfg(feature = "prometheus")]
fn with_prometheus<R>(
    prometheus: metrics_exporter_prometheus::PrometheusRecorder,
    other: Option<R>,
) -> Box<dyn Recorder + Sync>
where
    R: Recorder + Send + Sync + 'static,
{
    use metrics_util::layers::FanoutBuilder;

    match other {
        Some(other) => Box::new(
            FanoutBuilder::default()
                .add_recorder(prometheus)
                .add_recorder(other)
                .build(),
        ),
        None => Box::new(prometheus),
    }
}

/// Installs the Prometheus recorder from `builder`, with `other` beside it if it is provided, as
/// the global recorder, then describes every metric and records the build info through it.
///
/// The build info is recorded before this returns, so it is already exported when the caller
/// logs that the endpoint is open.
///
/// Like [`PrometheusBuilder::install`] outside a Tokio runtime, which is how Zebra calls it, this
/// serves the endpoint from its own thread.
///
/// [`PrometheusBuilder::install`]: metrics_exporter_prometheus::PrometheusBuilder::install
#[cfg(feature = "prometheus")]
fn install_with_prometheus<R>(
    builder: metrics_exporter_prometheus::PrometheusBuilder,
    other: Option<R>,
) -> Result<(), crate::BoxError>
where
    R: Recorder + Send + Sync + 'static,
{
    use metrics_exporter_prometheus::BuildError;

    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| BuildError::FailedToCreateRuntime(e.to_string()))?;

    let (prometheus, exporter) = {
        let _guard = runtime.enter();
        builder.build()?
    };

    std::thread::Builder::new()
        .name("metrics-exporter-prometheus-http".to_owned())
        .spawn(move || runtime.block_on(exporter))
        .map_err(|e| BuildError::FailedToCreateRuntime(e.to_string()))?;

    metrics::set_global_recorder(with_prometheus(prometheus, other)).map_err(|e| e.to_string())?;
    describe_and_record_build_info();

    Ok(())
}

/// Metrics configuration section.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
    /// The address used for the Prometheus metrics endpoint.
    ///
    /// Install Zebra using `cargo install --features=prometheus` to enable this config.
    ///
    /// The endpoint is disabled if this is set to `None`.
    pub endpoint_addr: Option<SocketAddr>,
}

// we like our default configs to be explicit
#[allow(unknown_lints)]
#[allow(clippy::derivable_impls)]
impl Default for Config {
    fn default() -> Self {
        Self {
            endpoint_addr: None,
        }
    }
}