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

WIP: Add the metrics recording feature for libp2p #431

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 4 additions & 0 deletions nomos-libp2p/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ hex = "0.4.3"
log = "0.4.19"
thiserror = "1.0.40"
tracing = "0.1"
prometheus-client = { version = "0.21.0", optional = true }

[dev-dependencies]
env_logger = "0.10.0"
serde_json = "1.0.99"
tokio = { version = "1", features = ["time"] }

[features]
metrics = ["libp2p/metrics", "prometheus-client"]
25 changes: 24 additions & 1 deletion nomos-libp2p/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use blake2::digest::{consts::U32, Digest};
use blake2::Blake2b;
use libp2p::gossipsub::{Message, MessageId, TopicHash};

#[cfg(feature = "metrics")]
use libp2p::metrics::Metrics;
pub use libp2p::{
core::upgrade,
dns,
Expand All @@ -23,12 +25,16 @@ pub use libp2p::{
};
use libp2p::{swarm::ConnectionId, tcp::tokio::Tcp};
pub use multiaddr::{multiaddr, Multiaddr, Protocol};
#[cfg(feature = "metrics")]
use prometheus_client::registry::Registry;
use serde::{Deserialize, Serialize};

/// Wraps [`libp2p::Swarm`], and config it for use within Nomos.
pub struct Swarm {
// A core libp2p swarm
swarm: libp2p::Swarm<Behaviour>,
#[cfg(feature = "metrics")]
metrics: Metrics,
}

#[derive(NetworkBehaviour)]
Expand Down Expand Up @@ -108,7 +114,19 @@ impl Swarm {

swarm.listen_on(multiaddr!(Ip4(config.host), Tcp(config.port)))?;

Ok(Swarm { swarm })
#[cfg(feature = "metrics")]
let metrics = {
let mut metric_registry = Registry::default();
Copy link
Member

Choose a reason for hiding this comment

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

Is it true, that if we'll want to have one prometheus service inside the node (spawned as described in TODO comment) then metrics_registry will need to be passed as reference instead of created here?

Copy link
Contributor Author

@youngjoon-lee youngjoon-lee Sep 21, 2023

Choose a reason for hiding this comment

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

Ah right. I’ll reopen this after checking how this can be used with the existing the metrics service. I think we cannot merge this without figuring out how to use this.

Copy link
Contributor Author

@youngjoon-lee youngjoon-lee Sep 25, 2023

Choose a reason for hiding this comment

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

Hm. I think that the way how libp2p gathers/exposes metrics is not flexible. Even if we add a prometheus backend in our metrics service, we need to pass the reference of prometheus_client::registry::Registry to the libp2p network service, so that it can be used as described in this PR. I don't think that's a good design. Also, it seems that the only way we can query metrics from the Registry is dumping all metrics using the text encoder or others. I think that this way doesn't fit with the design of our metrics service which has update() and load() functions.

I'd like to suggest to postpone this discussion since this topic isn't in priority. Sorry for opening this PR without enough research. Later when we really begin using our metrics service, we can think about how we can adopt prometheus-client (or if it's necessary).

Metrics::new(&mut metric_registry)
//TODO: use `metric_registry` to expose metrics to external
// https://github.com/libp2p/rust-libp2p/blob/c1551d71b6a7ad673706d7106c797fe464cb2820/examples/metrics/src/main.rs#L67-L67
};

Ok(Swarm {
swarm,
#[cfg(feature = "metrics")]
metrics,
})
}

/// Initiates a connection attempt to a peer
Expand Down Expand Up @@ -157,6 +175,11 @@ impl Swarm {
&self.swarm
}

#[cfg(feature = "metrics")]
pub fn metrics(&self) -> &Metrics {
&self.metrics
}

pub fn is_subscribed(&mut self, topic: &str) -> bool {
let topic_hash = Self::topic_hash(topic);

Expand Down
1 change: 1 addition & 0 deletions nomos-services/network/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ tokio = { version = "1", features = ["full"] }
default = []
waku = ["waku-bindings"]
libp2p = ["nomos-libp2p", "rand", "humantime-serde"]
metrics = ["nomos-libp2p/metrics"]
mock = ["rand", "chrono"]
43 changes: 37 additions & 6 deletions nomos-services/network/src/backends/libp2p/swarm.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::{collections::HashMap, ops::Range, time::Duration};

use mixnet_client::MixnetClient;
#[cfg(feature = "metrics")]
use nomos_libp2p::libp2p::metrics::Recorder;
use nomos_libp2p::{
gossipsub::{self, Message},
libp2p::swarm::ConnectionId,
Expand Down Expand Up @@ -90,14 +92,41 @@ impl SwarmHandler {

fn handle_event(&mut self, event: SwarmEvent<BehaviourEvent, THandlerErr<Behaviour>>) {
match event {
SwarmEvent::Behaviour(BehaviourEvent::Gossipsub(gossipsub::Event::Message {
propagation_source: peer_id,
message_id: id,
SwarmEvent::Behaviour(BehaviourEvent::Gossipsub(event)) => {
self.handle_gossipsub_event(event);
}
swarm_event => {
self.handle_swarm_event(swarm_event);
}
}
}

fn handle_gossipsub_event(&mut self, event: gossipsub::Event) {
#[cfg(feature = "metrics")]
self.swarm.metrics().record(&event);

match event {
gossipsub::Event::Message {
propagation_source,
message_id,
message,
})) => {
tracing::debug!("Got message with id: {id} from peer: {peer_id}");
} => {
tracing::debug!(
"Got message with id: {message_id} propagated from {propagation_source}"
);
log_error!(self.events_tx.send(Event::Message(message)));
}
event => {
tracing::debug!("gossipsub event: {event:?}");
}
}
}

fn handle_swarm_event(&mut self, event: SwarmEvent<BehaviourEvent, THandlerErr<Behaviour>>) {
#[cfg(feature = "metrics")]
self.swarm.metrics().record(&event);

match event {
SwarmEvent::ConnectionEstablished {
peer_id,
connection_id,
Expand Down Expand Up @@ -130,7 +159,9 @@ impl SwarmHandler {
);
self.retry_connect(connection_id);
}
_ => {}
event => {
tracing::debug!("swarm event: {event:?}");
}
}
}

Expand Down
Loading