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

misc/metrics: Add protocols label to address-specific metrics #2982

Merged
merged 27 commits into from
Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
d7c0f89
Getting started
John-LittleBearLabs Oct 4, 2022
3345407
Merge remote-tracking branch 'jt/master' into addrstak_metric
John-LittleBearLabs Oct 4, 2022
32d5eb0
Merge remote-tracking branch 'origin/master' into addrstak_metric
John-LittleBearLabs Oct 7, 2022
d815970
Post merge fixup and re-check.
John-LittleBearLabs Oct 7, 2022
14e906a
Pulling protocol_stack functionality into this repo, by request.
John-LittleBearLabs Oct 11, 2022
808c439
A couple of suggestions from PR
John-LittleBearLabs Oct 13, 2022
4842a64
Merge remote-tracking branch 'origin/master' into addrstak_metric
John-LittleBearLabs Oct 13, 2022
9c6b300
Label wrapper
John-LittleBearLabs Oct 14, 2022
f165e01
MultiaddrExt
John-LittleBearLabs Oct 14, 2022
b2c74ed
not From
John-LittleBearLabs Oct 14, 2022
50c8bb5
cargo fmt
John-LittleBearLabs Oct 14, 2022
d74e7e5
clippy
John-LittleBearLabs Oct 14, 2022
e5974ca
changelog
John-LittleBearLabs Oct 14, 2022
1d13413
Merge remote-tracking branch 'origin/master' into addrstak_metric
John-LittleBearLabs Oct 17, 2022
3900f69
Version bump.
John-LittleBearLabs Oct 17, 2022
9a227ca
PR comment
John-LittleBearLabs Oct 19, 2022
b618cf8
Merge remote-tracking branch 'origin/master' into addrstak_metric
John-LittleBearLabs Nov 2, 2022
16c802b
A couple PR comments.
John-LittleBearLabs Nov 2, 2022
6a5a593
Use protocol stack for a few more metrics.
John-LittleBearLabs Nov 3, 2022
6983a59
metric label naming consistency
John-LittleBearLabs Nov 4, 2022
c8bcc82
remove impl From
John-LittleBearLabs Nov 4, 2022
ece8c9b
PR comments & clippy
John-LittleBearLabs Nov 8, 2022
db1bcdc
Merge from master, update protocol_stack to use upstream. Should have…
John-LittleBearLabs Nov 14, 2022
0f6bdd1
Fix a clippy and a no-default-feature use stmt
John-LittleBearLabs Nov 14, 2022
f787368
Move `Labels` to usage site
thomaseizinger Nov 15, 2022
0d3ec5b
Merge branch 'master' into addrstak_metric
mergify[bot] Nov 15, 2022
7176f14
Merge branch 'master' into addrstak_metric
thomaseizinger Nov 15, 2022
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
26 changes: 22 additions & 4 deletions misc/metrics/examples/metrics/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use futures::stream::StreamExt;
use libp2p::core::Multiaddr;
use libp2p::metrics::{Metrics, Recorder};
use libp2p::swarm::SwarmEvent;
use libp2p::{identity, ping, NetworkBehaviour, PeerId, Swarm};
use libp2p::{identify, identity, ping, NetworkBehaviour, PeerId, Swarm};
use libp2p_swarm::keep_alive;
use log::info;
use prometheus_client::registry::Registry;
Expand All @@ -71,8 +71,8 @@ fn main() -> Result<(), Box<dyn Error>> {
info!("Local peer id: {:?}", local_peer_id);

let mut swarm = Swarm::new(
block_on(libp2p::development_transport(local_key))?,
Behaviour::default(),
block_on(libp2p::development_transport(local_key.clone()))?,
Behaviour::new(local_key),
local_peer_id,
);

Expand All @@ -95,6 +95,10 @@ fn main() -> Result<(), Box<dyn Error>> {
info!("{:?}", ping_event);
metrics.record(&ping_event);
}
SwarmEvent::Behaviour(BehaviourEvent::Identify(identify_event)) => {
info!("{:?}", identify_event);
metrics.record(&identify_event);
}
swarm_event => {
info!("{:?}", swarm_event);
metrics.record(&swarm_event);
Expand All @@ -109,8 +113,22 @@ fn main() -> Result<(), Box<dyn Error>> {
///
/// For illustrative purposes, this includes the [`keep_alive::Behaviour`]) behaviour so the ping actually happen
/// and can be observed via the metrics.
#[derive(NetworkBehaviour, Default)]
#[derive(NetworkBehaviour)]
struct Behaviour {
identify: identify::Behaviour,
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour,
}

impl Behaviour {
fn new(local_key: libp2p::identity::Keypair) -> Self {
John-LittleBearLabs marked this conversation as resolved.
Show resolved Hide resolved
Self {
ping: ping::Behaviour::default(),
identify: identify::Behaviour::new(identify::Config::new(
"/ipfs/0.1.0".into(),
local_key.public(),
)),
keep_alive: keep_alive::Behaviour::default(),
}
}
}
16 changes: 16 additions & 0 deletions misc/metrics/src/identify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::protocol_stack;
use libp2p_core::PeerId;
use prometheus_client::encoding::text::{EncodeMetric, Encoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::histogram::{exponential_buckets, Histogram};
use prometheus_client::metrics::MetricType;
use prometheus_client::registry::Registry;
Expand All @@ -36,6 +38,7 @@ pub struct Metrics {
received_info_listen_addrs: Histogram,
received_info_protocols: Histogram,
sent: Counter,
listen_addresses: Family<protocol_stack::Label, Counter>,
}

impl Metrics {
Expand Down Expand Up @@ -100,6 +103,13 @@ impl Metrics {
Box::new(sent.clone()),
);

let listen_addresses = Family::default();
sub_registry.register(
"listen_addresses",
"Number of listen addresses for remote peer per protocol stack",
Box::new(listen_addresses.clone()),
);

Self {
protocols,
error,
Expand All @@ -108,6 +118,7 @@ impl Metrics {
received_info_listen_addrs,
received_info_protocols,
sent,
listen_addresses,
}
}
}
Expand Down Expand Up @@ -167,6 +178,11 @@ impl super::Recorder<libp2p_identify::Event> for Metrics {
.observe(info.protocols.len() as f64);
self.received_info_listen_addrs
.observe(info.listen_addrs.len() as f64);
for listen_addr in &info.listen_addrs {
self.listen_addresses
.get_or_create(&protocol_stack::Label::for_multi_address(&listen_addr))
.inc();
}
}
libp2p_identify::Event::Sent { .. } => {
self.sent.inc();
Expand Down
1 change: 1 addition & 0 deletions misc/metrics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ mod identify;
mod kad;
#[cfg(feature = "ping")]
mod ping;
mod protocol_stack;
#[cfg(feature = "relay")]
mod relay;
mod swarm;
Expand Down
86 changes: 86 additions & 0 deletions misc/metrics/src/protocol_stack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use libp2p_core::multiaddr::{Multiaddr, Protocol};
use prometheus_client::encoding::text::Encode;

#[derive(Encode, Hash, Clone, Eq, PartialEq)]
pub struct Label {
John-LittleBearLabs marked this conversation as resolved.
Show resolved Hide resolved
address_stack: String,
}
impl Label {
Copy link
Member

Choose a reason for hiding this comment

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

Why not implement From for Label?

impl From<&Multiaddr> for Label {

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we had this at some point and I recommended to move away from it. Unless we are actually using From as an abstraction somewhere, using a generic function has downsides in terms of clarity. It also encourages the use of .into at callsites which makes it hard to see, what this is actually being converted into.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah yes, that sounds familiar. I probably resolved & hid the comment when I committed the recommended change, but it's probably still above somewhere.

Personally I think I prefer the From approach in this case - since the struct has such an incredibly narrow usage I don't think there's too much confusion about what into is doing. But of course I'll go with whatever the consensus is.

Copy link
Contributor

@thomaseizinger thomaseizinger Nov 4, 2022

Choose a reason for hiding this comment

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

From would be nice if we could change the signature of get_or_create to accept an impl Into<S> so you don't have to call .into.

Unfortunately we can't do that without requiring ownership on _every_callsite which would require allocations even though we only need ownership inside the get_or_create function for the first call. Meaning a lot of these allocations would be wasted.

I'd be in favor of not obfuscating what we are converting here:

  1. Using .into makes it hard to find all usages of Labels. Currently, I have to delete the From impl and see where the compiler fails.
  2. I find this:
                    self.listen_addresses
                        .get_or_create(&protocol_stack::Labels::new(&listen_addr))
                        .inc();

much clearer to read than this:

                    self.listen_addresses
                        .get_or_create(&listen_addr.into())
                        .inc();

The former I can glance over whereas with the latter, my brain stops and is like: "Hang on, into() what?". And I have to recall the function signature of get_or_create, check the type of listen_addr and search for From implementations to understand what is happening here.

  1. If we ever need more data for the labels, From would need to be using a tuple at which point we need a constructor anyway.
  2. Out of principle, I think we should not be depending on abstractions (From), if we don't use them. Traits are only useful in generic code, so unless we can make a function that uses T: Into where we can pass a &Multiaddr, I think this doesn't qualify.

pub fn for_multi_address(ma: &Multiaddr) -> Self {
John-LittleBearLabs marked this conversation as resolved.
Show resolved Hide resolved
Self {
address_stack: ma.protocol_stack(),
}
}
}

//TODO: remove this trait and tag() and replace with calls to the upstream method
// once that lands : https://github.com/multiformats/rust-multiaddr/pull/60
// In the meantime there is no _ case in the match so one can easily detect mismatch in supported
// protocols when dependency version changes.
trait MultiaddrExt {
fn protocol_stack(&self) -> String;
}
Copy link
Member

Choose a reason for hiding this comment

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

I still need to cut a new release of multiaddr. Sorry for the delay.

impl MultiaddrExt for Multiaddr {
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
fn protocol_stack(&self) -> String {
// Has potential to allocate multiple times, but this line expresses the intent here.
// std::iter::once("/").chain(ma.iter().map(tag).intersperse("/")).collect()
let len = self.iter().fold(0, |acc, proto| acc + tag(proto).len() + 1);
let mut result = String::with_capacity(len);
for proto_tag in self.iter().map(tag) {
result.push('/');
result.push_str(proto_tag);
}
result
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
}
}

pub fn tag(proto: Protocol) -> &'static str {
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
use Protocol::*;
match proto {
Dccp(_) => "dccp",
Dns(_) => "dns",
Dns4(_) => "dns4",
Dns6(_) => "dns6",
Dnsaddr(_) => "dnsaddr",
Http => "http",
Https => "https",
Ip4(_) => "ip4",
Ip6(_) => "ip6",
P2pWebRtcDirect => "p2p-webrtc-direct",
P2pWebRtcStar => "p2p-webrtc-star",
P2pWebSocketStar => "p2p-websocket-star",
Memory(_) => "memory",
Onion(_, _) => "onion",
Onion3(_) => "onion3",
P2p(_) => "p2p",
P2pCircuit => "p2p-circuit",
Quic => "quic",
Sctp(_) => "sctp",
Tcp(_) => "tcp",
Tls => "tls",
Udp(_) => "udp",
Udt => "udt",
Unix(_) => "unix",
Utp => "utp",
Ws(ref s) if s == "/" => "ws",
Ws(_) => "x-parity-ws",
Wss(ref s) if s == "/" => "wss",
Wss(_) => "x-parity-wss",
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn ip6_tcp_wss_p2p() {
let ma = Multiaddr::try_from("/ip6/2001:8a0:7ac5:4201:3ac9:86ff:fe31:7095/tcp/8000/wss/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC").expect("testbad");
let actual = Label::for_multi_address(&ma);
assert_eq!(actual.address_stack, "/ip6/tcp/wss/p2p");
let mut buf = Vec::new();
actual.encode(&mut buf).expect("encode failed");
let actual = String::from_utf8(buf).expect("invalid utf-8?");
assert_eq!(actual, r#"address_stack="/ip6/tcp/wss/p2p""#);
}
}
13 changes: 8 additions & 5 deletions misc/metrics/src/swarm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

use crate::protocol_stack;
use prometheus_client::encoding::text::Encode;
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;

pub struct Metrics {
connections_incoming: Counter,
connections_incoming: Family<protocol_stack::Label, Counter>,
connections_incoming_error: Family<IncomingConnectionErrorLabels, Counter>,

connections_established: Family<ConnectionEstablishedLabels, Counter>,
Expand All @@ -45,10 +46,10 @@ impl Metrics {
pub fn new(registry: &mut Registry) -> Self {
let sub_registry = registry.sub_registry_with_prefix("swarm");

let connections_incoming = Counter::default();
let connections_incoming = Family::default();
sub_registry.register(
"connections_incoming",
"Number of incoming connections",
"Number of incoming connections per address stack",
Box::new(connections_incoming.clone()),
);

Expand Down Expand Up @@ -156,8 +157,10 @@ impl<TBvEv, THandleErr> super::Recorder<libp2p_swarm::SwarmEvent<TBvEv, THandleE
})
.inc();
}
libp2p_swarm::SwarmEvent::IncomingConnection { .. } => {
self.connections_incoming.inc();
libp2p_swarm::SwarmEvent::IncomingConnection { send_back_addr, .. } => {
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
self.connections_incoming
.get_or_create(&protocol_stack::Label::for_multi_address(&send_back_addr))
.inc();
}
libp2p_swarm::SwarmEvent::IncomingConnectionError { error, .. } => {
self.connections_incoming_error
Expand Down