#![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;
#[cfg(all(test, not(target_os = "windows")))]
mod tests;
#[cfg(not(windows))]
const PROCESS_METRICS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(15);
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,
];
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,
];
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,
];
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,
],
),
];
#[derive(Debug, Component)]
pub struct MetricsEndpoint {}
impl MetricsEndpoint {
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 {})
}
#[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)
}
#[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))
}
}
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();
}
#[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);
}
}
fn describe_and_record_build_info() {
describe_all();
zebra_consensus::metrics::register_failure_counters();
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);
}
#[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");
}
}
#[cfg(windows)]
fn spawn_process_metrics() {}
#[cfg(not(windows))]
fn record_process_metrics() {
let sample = metrics_process::collector::collect();
if let Some(seconds) = sample.cpu_seconds_total {
metrics::counter!("process_cpu_seconds_total").absolute(seconds as u64);
}
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 {
metrics::gauge!(name).set(value as f64);
}
}
}
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(())
}
#[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,
)
},
)
}
#[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),
}
}
#[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(())
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
pub endpoint_addr: Option<SocketAddr>,
}
#[allow(unknown_lints)]
#[allow(clippy::derivable_impls)]
impl Default for Config {
fn default() -> Self {
Self {
endpoint_addr: None,
}
}
}