Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: prometheus metrics for RPC methods #4607

Merged
merged 7 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
- [#3959](https://github.com/ChainSafe/forest/issues/3959) Added support for the
Ethereum RPC name aliases.

- [#4607](https://github.com/ChainSafe/forest/pull/4607) Expose usage and timing
metrics for RPC methods.

### Changed

### Removed
Expand Down
34 changes: 33 additions & 1 deletion src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ use once_cell::sync::Lazy;
use parking_lot::{RwLock, RwLockWriteGuard};
use prometheus_client::{
encoding::EncodeLabelSet,
metrics::{counter::Counter, family::Family, histogram::Histogram},
metrics::{
counter::Counter,
family::Family,
histogram::{exponential_buckets, Histogram},
},
};
use std::sync::Arc;
use std::{path::PathBuf, time::Instant};
Expand Down Expand Up @@ -38,6 +42,29 @@ pub static LRU_CACHE_MISS: Lazy<Family<KindLabel, Counter>> = Lazy::new(|| {
metric
});

pub static RPC_METHOD_FAILURE: Lazy<Family<RpcMethodLabel, Counter>> = Lazy::new(|| {
let metric = Family::default();
DEFAULT_REGISTRY.write().register(
"rpc_method_failure",
"Number of failed RPC calls",
metric.clone(),
);
metric
});

pub static RPC_METHOD_TIME: Lazy<Family<RpcMethodLabel, Histogram>> = Lazy::new(|| {
let metric = Family::<RpcMethodLabel, Histogram>::new_with_constructor(|| {
// Histogram with 10 buckets starting from 0.01s going to 5.12s, each bucket twice as big as the last.
Histogram::new(exponential_buckets(0.01, 2.0, 10))
});
crate::metrics::default_registry().register(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I'm curious. Is there a particular reason we do not use DEFAULT_REGISTRY.write() here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the default_registry() hides the detail that the registry is under an RwLock.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But, I see that all other metrics use DEFAULT_REGISTRY.write() in this file.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They likely shouldn't. :)

"rpc_processing_time",
"Duration of RPC method call",
metric.clone(),
);
metric
});

pub async fn init_prometheus<DB>(
prometheus_listener: TcpListener,
db_directory: PathBuf,
Expand Down Expand Up @@ -101,6 +128,11 @@ where
)
}

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct RpcMethodLabel {
pub method: String,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct KindLabel {
kind: &'static str,
Expand Down
57 changes: 57 additions & 0 deletions src/rpc/metrics_layer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::metrics;
use futures::future::BoxFuture;
use futures::FutureExt;
use jsonrpsee::server::middleware::rpc::RpcServiceT;
use jsonrpsee::MethodResponse;
use tower::Layer;

// State-less jsonrpcsee layer for measuring RPC metrics
#[derive(Clone)]
pub struct MetricsLayer {}

impl<S> Layer<S> for MetricsLayer {
type Service = RecordMetrics<S>;

fn layer(&self, service: S) -> Self::Service {
RecordMetrics { service }
}
}

#[derive(Clone)]
pub struct RecordMetrics<S> {
service: S,
}

impl<'a, S> RpcServiceT<'a> for RecordMetrics<S>
where
S: RpcServiceT<'a> + Send + Sync + Clone + 'static,
{
type Future = BoxFuture<'a, MethodResponse>;

fn call(&self, req: jsonrpsee::types::Request<'a>) -> Self::Future {
let service = self.service.clone();
let method = metrics::RpcMethodLabel {
method: req.method_name().to_owned(),
};

async move {
// Cannot use HistogramTimerExt::start_timer here since it would lock the metric.
let start_time = std::time::Instant::now();
let req = service.call(req).await;

metrics::RPC_METHOD_TIME
.get_or_create(&method)
.observe(start_time.elapsed().as_secs_f64());

if req.is_error() {
metrics::RPC_METHOD_FAILURE.get_or_create(&method).inc();
}

req
}
.boxed()
}
}
12 changes: 8 additions & 4 deletions src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
mod auth_layer;
mod channel;
mod client;
mod metrics_layer;
mod request;

pub use client::Client;
Expand Down Expand Up @@ -298,6 +299,7 @@ use crate::key_management::KeyStore;
use crate::rpc::auth_layer::AuthLayer;
use crate::rpc::channel::RpcModule as FilRpcModule;
pub use crate::rpc::channel::CANCEL_METHOD_NAME;
use crate::rpc::metrics_layer::MetricsLayer;

use crate::blocks::Tipset;
use fvm_ipld_blockstore::Blockstore;
Expand Down Expand Up @@ -436,10 +438,12 @@ where
// NOTE, the rpc middleware must be initialized here to be able to created once per connection
// with data from the connection such as the headers in this example
let headers = req.headers().clone();
let rpc_middleware = RpcServiceBuilder::new().layer(AuthLayer {
headers,
keystore: keystore.clone(),
});
let rpc_middleware = RpcServiceBuilder::new()
.layer(AuthLayer {
headers,
keystore: keystore.clone(),
})
.layer(MetricsLayer {});
let mut jsonrpsee_svc = svc_builder
.set_rpc_middleware(rpc_middleware)
.build(methods, stop_handle);
Expand Down
Loading