Simplify enum -> str with strum (#2164)

## Issue Addressed

NA

## Proposed Changes

As per #2100, uses derives from the sturm library to implement AsRef<str> and AsStaticRef to easily get str values from enums without creating new Strings. Furthermore unifies all attestation error counter into one IntCounterVec vector.

These works are originally by @blacktemplar, I've just created this PR so I can resolve some merge conflicts.

## Additional Info

NA


Co-authored-by: blacktemplar <blacktemplar@a1.net>
This commit is contained in:
Paul Hauner 2021-01-19 06:33:58 +00:00
parent 8892114f52
commit 805e152f66
14 changed files with 82 additions and 255 deletions

24
Cargo.lock generated
View File

@ -597,6 +597,7 @@ dependencies = [
"smallvec", "smallvec",
"state_processing", "state_processing",
"store", "store",
"strum",
"task_executor", "task_executor",
"tempfile", "tempfile",
"tokio 0.3.6", "tokio 0.3.6",
@ -2010,6 +2011,7 @@ dependencies = [
"slog-term", "slog-term",
"smallvec", "smallvec",
"snap", "snap",
"strum",
"task_executor", "task_executor",
"tempfile", "tempfile",
"tiny-keccak 2.0.2", "tiny-keccak 2.0.2",
@ -4211,6 +4213,7 @@ dependencies = [
"smallvec", "smallvec",
"state_processing", "state_processing",
"store", "store",
"strum",
"task_executor", "task_executor",
"tempfile", "tempfile",
"tokio 0.3.6", "tokio 0.3.6",
@ -6266,6 +6269,27 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "strum"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7318c509b5ba57f18533982607f24070a55d353e90d4cae30c467cdb2ad5ac5c"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee8bc6b87a5112aeeab1f4a9f7ab634fe6cbefc4850006df31267f4cfb9e3149"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "1.0.0" version = "1.0.0"

View File

@ -61,3 +61,4 @@ regex = "1.3.9"
exit-future = "0.2.0" exit-future = "0.2.0"
slasher = { path = "../../slasher" } slasher = { path = "../../slasher" }
eth2 = { path = "../../common/eth2" } eth2 = { path = "../../common/eth2" }
strum = { version = "0.20", features = ["derive"] }

View File

@ -48,6 +48,7 @@ use state_processing::{
}, },
}; };
use std::borrow::Cow; use std::borrow::Cow;
use strum::AsRefStr;
use tree_hash::TreeHash; use tree_hash::TreeHash;
use types::{ use types::{
Attestation, BeaconCommittee, CommitteeIndex, Epoch, EthSpec, Hash256, IndexedAttestation, Attestation, BeaconCommittee, CommitteeIndex, Epoch, EthSpec, Hash256, IndexedAttestation,
@ -61,7 +62,7 @@ use types::{
/// other than `BeaconChainError`). /// other than `BeaconChainError`).
/// - The application encountered an internal error whilst attempting to determine validity /// - The application encountered an internal error whilst attempting to determine validity
/// (the `BeaconChainError` variant) /// (the `BeaconChainError` variant)
#[derive(Debug)] #[derive(Debug, AsRefStr)]
pub enum Error { pub enum Error {
/// The attestation is from a slot that is later than the current slot (with respect to the /// The attestation is from a slot that is later than the current slot (with respect to the
/// gossip clock disparity). /// gossip clock disparity).

View File

@ -38,6 +38,7 @@ task_executor = { path = "../../common/task_executor" }
rand = "0.7.3" rand = "0.7.3"
directory = { path = "../../common/directory" } directory = { path = "../../common/directory" }
regex = "1.3.9" regex = "1.3.9"
strum = { version = "0.20", features = ["derive"] }
[dependencies.libp2p] [dependencies.libp2p]
#version = "0.23.0" #version = "0.23.0"

View File

@ -437,7 +437,7 @@ impl<TSpec: EthSpec> Behaviour<TSpec> {
.peers .peers
.read() .read()
.peer_info(propagation_source) .peer_info(propagation_source)
.map(|info| info.client.kind.as_static_ref()) .map(|info| info.client.kind.as_ref())
{ {
metrics::inc_counter_vec( metrics::inc_counter_vec(
&metrics::GOSSIP_UNACCEPTED_MESSAGES_PER_CLIENT, &metrics::GOSSIP_UNACCEPTED_MESSAGES_PER_CLIENT,

View File

@ -4,6 +4,7 @@
use libp2p::identify::IdentifyInfo; use libp2p::identify::IdentifyInfo;
use serde::Serialize; use serde::Serialize;
use strum::{AsRefStr, AsStaticStr};
/// Various client and protocol information related to a node. /// Various client and protocol information related to a node.
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug, Serialize)]
@ -20,7 +21,7 @@ pub struct Client {
pub agent_string: Option<String>, pub agent_string: Option<String>,
} }
#[derive(Clone, Debug, Serialize, PartialEq)] #[derive(Clone, Debug, Serialize, PartialEq, AsRefStr, AsStaticStr)]
pub enum ClientKind { pub enum ClientKind {
/// A lighthouse node (the best kind). /// A lighthouse node (the best kind).
Lighthouse, Lighthouse,
@ -98,26 +99,6 @@ impl std::fmt::Display for Client {
} }
} }
impl ClientKind {
pub fn as_static_ref(&self) -> &'static str {
use ClientKind::*;
match self {
Lighthouse => "Lighthouse",
Nimbus => "Nimbus",
Teku => "Teku",
Prysm => "Prysm",
Lodestar => "Lodestar",
Unknown => "Unknown",
}
}
}
impl AsRef<str> for ClientKind {
fn as_ref(&self) -> &str {
self.as_static_ref()
}
}
impl std::fmt::Display for ClientKind { impl std::fmt::Display for ClientKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_ref()) f.write_str(self.as_ref())

View File

@ -158,8 +158,8 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
metrics::inc_counter_vec( metrics::inc_counter_vec(
&metrics::PEER_ACTION_EVENTS_PER_CLIENT, &metrics::PEER_ACTION_EVENTS_PER_CLIENT,
&[ &[
info.client.kind.as_static_ref(), info.client.kind.as_ref(),
PeerAction::Fatal.as_static_str(), PeerAction::Fatal.as_ref(),
source.into(), source.into(),
], ],
); );
@ -193,11 +193,7 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
info.apply_peer_action_to_score(action); info.apply_peer_action_to_score(action);
metrics::inc_counter_vec( metrics::inc_counter_vec(
&metrics::PEER_ACTION_EVENTS_PER_CLIENT, &metrics::PEER_ACTION_EVENTS_PER_CLIENT,
&[ &[info.client.kind.as_ref(), action.as_ref(), source.into()],
info.client.kind.as_static_ref(),
action.as_static_str(),
source.into(),
],
); );
Self::handle_score_transitions( Self::handle_score_transitions(
@ -407,9 +403,9 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
metrics::inc_counter_vec( metrics::inc_counter_vec(
&metrics::TOTAL_RPC_ERRORS_PER_CLIENT, &metrics::TOTAL_RPC_ERRORS_PER_CLIENT,
&[ &[
client.kind.as_static_ref(), client.kind.as_ref(),
err.as_static_str(), err.as_static_str(),
direction.as_static_str(), direction.as_ref(),
], ],
); );

View File

@ -11,6 +11,7 @@ use serde::{
use std::collections::HashSet; use std::collections::HashSet;
use std::net::{IpAddr, SocketAddr}; use std::net::{IpAddr, SocketAddr};
use std::time::Instant; use std::time::Instant;
use strum::AsRefStr;
use types::{EthSpec, SubnetId}; use types::{EthSpec, SubnetId};
use PeerConnectionStatus::*; use PeerConnectionStatus::*;
@ -320,21 +321,13 @@ impl Default for PeerStatus {
} }
/// Connection Direction of connection. /// Connection Direction of connection.
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum ConnectionDirection { pub enum ConnectionDirection {
Incoming, Incoming,
Outgoing, Outgoing,
} }
impl ConnectionDirection {
pub fn as_static_str(&self) -> &'static str {
match self {
ConnectionDirection::Incoming => "incoming",
ConnectionDirection::Outgoing => "outgoing",
}
}
}
/// Connection Status of the peer. /// Connection Status of the peer.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum PeerConnectionStatus { pub enum PeerConnectionStatus {

View File

@ -8,6 +8,7 @@
use crate::behaviour::GOSSIPSUB_GREYLIST_THRESHOLD; use crate::behaviour::GOSSIPSUB_GREYLIST_THRESHOLD;
use serde::Serialize; use serde::Serialize;
use std::time::Instant; use std::time::Instant;
use strum::AsRefStr;
use tokio::time::Duration; use tokio::time::Duration;
lazy_static! { lazy_static! {
@ -42,7 +43,8 @@ const GOSSIPSUB_POSITIVE_SCORE_WEIGHT: f64 = GOSSIPSUB_NEGATIVE_SCORE_WEIGHT;
/// Each variant has an associated score change. /// Each variant has an associated score change.
// To easily assess the behaviour of scores changes the number of variants should stay low, and // To easily assess the behaviour of scores changes the number of variants should stay low, and
// somewhat generic. // somewhat generic.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum PeerAction { pub enum PeerAction {
/// We should not communicate more with this peer. /// We should not communicate more with this peer.
/// This action will cause the peer to get banned. /// This action will cause the peer to get banned.
@ -94,17 +96,6 @@ impl std::fmt::Display for PeerAction {
} }
} }
impl PeerAction {
pub fn as_static_str(&self) -> &'static str {
match self {
PeerAction::HighToleranceError => "high_tolerance",
PeerAction::MidToleranceError => "mid_tolerance",
PeerAction::LowToleranceError => "low_tolerance",
PeerAction::Fatal => "fatal",
}
}
}
/// The expected state of the peer given the peer's score. /// The expected state of the peer given the peer's score.
#[derive(Debug, PartialEq, Clone, Copy)] #[derive(Debug, PartialEq, Clone, Copy)]
pub(crate) enum ScoreState { pub(crate) enum ScoreState {

View File

@ -9,6 +9,7 @@ use ssz_types::{
VariableList, VariableList,
}; };
use std::ops::Deref; use std::ops::Deref;
use strum::AsStaticStr;
use types::{Epoch, EthSpec, Hash256, SignedBeaconBlock, Slot}; use types::{Epoch, EthSpec, Hash256, SignedBeaconBlock, Slot};
/// Maximum number of blocks in a single request. /// Maximum number of blocks in a single request.
@ -257,7 +258,8 @@ pub enum RPCCodedResponse<T: EthSpec> {
} }
/// The code assigned to an erroneous `RPCResponse`. /// The code assigned to an erroneous `RPCResponse`.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq, AsStaticStr)]
#[strum(serialize_all = "snake_case")]
pub enum RPCResponseErrorCode { pub enum RPCResponseErrorCode {
RateLimited, RateLimited,
InvalidRequest, InvalidRequest,

View File

@ -17,6 +17,7 @@ use ssz_types::VariableList;
use std::io; use std::io;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::time::Duration; use std::time::Duration;
use strum::{AsStaticRef, AsStaticStr};
use tokio_io_timeout::TimeoutStream; use tokio_io_timeout::TimeoutStream;
use tokio_util::{ use tokio_util::{
codec::Framed, codec::Framed,
@ -470,10 +471,12 @@ where
} }
/// Error in RPC Encoding/Decoding. /// Error in RPC Encoding/Decoding.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, AsStaticStr)]
#[strum(serialize_all = "snake_case")]
pub enum RPCError { pub enum RPCError {
/// Error when decoding the raw buffer from ssz. /// Error when decoding the raw buffer from ssz.
// NOTE: in the future a ssz::DecodeError should map to an InvalidData error // NOTE: in the future a ssz::DecodeError should map to an InvalidData error
#[strum(serialize = "decode_error")]
SSZDecodeError(ssz::DecodeError), SSZDecodeError(ssz::DecodeError),
/// IO Error. /// IO Error.
IoError(String), IoError(String),
@ -571,22 +574,8 @@ impl RPCError {
/// Used for metrics. /// Used for metrics.
pub fn as_static_str(&self) -> &'static str { pub fn as_static_str(&self) -> &'static str {
match self { match self {
RPCError::SSZDecodeError { .. } => "decode_error", RPCError::ErrorResponse(ref code, ..) => code.as_static(),
RPCError::IoError { .. } => "io_error", e => e.as_static(),
RPCError::ErrorResponse(ref code, ..) => match code {
RPCResponseErrorCode::RateLimited => "rate_limited",
RPCResponseErrorCode::InvalidRequest => "invalid_request",
RPCResponseErrorCode::ServerError => "server_error",
RPCResponseErrorCode::ResourceUnavailable => "resource_unavailable",
RPCResponseErrorCode::Unknown => "unknown_response_code",
},
RPCError::StreamTimeout => "stream_timeout",
RPCError::UnsupportedProtocol => "unsupported_protocol",
RPCError::IncompleteStream => "incomplete_stream",
RPCError::InvalidData => "invalid_data",
RPCError::InternalError { .. } => "internal_error",
RPCError::NegotiationTimeout => "negotiation_timeout",
RPCError::HandlerRejected => "handler_rejected",
} }
} }
} }

View File

@ -1,5 +1,6 @@
use libp2p::gossipsub::{IdentTopic as Topic, TopicHash}; use libp2p::gossipsub::{IdentTopic as Topic, TopicHash};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use strum::AsRefStr;
use types::SubnetId; use types::SubnetId;
/// The gossipsub topic names. /// The gossipsub topic names.
@ -36,13 +37,15 @@ pub struct GossipTopic {
/// Enum that brings these topics into the rust type system. /// Enum that brings these topics into the rust type system.
// NOTE: There is intentionally no unknown type here. We only allow known gossipsub topics. // NOTE: There is intentionally no unknown type here. We only allow known gossipsub topics.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, AsRefStr)]
#[strum(serialize_all = "snake_case")]
pub enum GossipKind { pub enum GossipKind {
/// Topic for publishing beacon blocks. /// Topic for publishing beacon blocks.
BeaconBlock, BeaconBlock,
/// Topic for publishing aggregate attestations and proofs. /// Topic for publishing aggregate attestations and proofs.
BeaconAggregateAndProof, BeaconAggregateAndProof,
/// Topic for publishing raw attestations on a particular subnet. /// Topic for publishing raw attestations on a particular subnet.
#[strum(serialize = "beacon_attestation")]
Attestation(SubnetId), Attestation(SubnetId),
/// Topic for publishing voluntary exits. /// Topic for publishing voluntary exits.
VoluntaryExit, VoluntaryExit,
@ -52,20 +55,6 @@ pub enum GossipKind {
AttesterSlashing, AttesterSlashing,
} }
impl AsRef<str> for GossipKind {
fn as_ref(&self) -> &str {
use GossipKind::*;
match self {
BeaconBlock => "beacon_block",
BeaconAggregateAndProof => "beacon_aggregate_and_proof",
Attestation(_) => "beacon_attestation",
VoluntaryExit => "voluntary_exit",
ProposerSlashing => "proposer_slashing",
AttesterSlashing => "attester_slashing",
}
}
}
impl std::fmt::Display for GossipKind { impl std::fmt::Display for GossipKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
@ -310,4 +299,20 @@ mod tests {
Some(SubnetId::new(42)) Some(SubnetId::new(42))
); );
} }
#[test]
fn test_as_str_ref() {
assert_eq!("beacon_block", BeaconBlock.as_ref());
assert_eq!(
"beacon_aggregate_and_proof",
BeaconAggregateAndProof.as_ref()
);
assert_eq!(
"beacon_attestation",
Attestation(SubnetId::new(42)).as_ref()
);
assert_eq!("voluntary_exit", VoluntaryExit.as_ref());
assert_eq!("proposer_slashing", ProposerSlashing.as_ref());
assert_eq!("attester_slashing", AttesterSlashing.as_ref());
}
} }

View File

@ -44,3 +44,4 @@ itertools = "0.9.0"
num_cpus = "1.13.0" num_cpus = "1.13.0"
lru_cache = { path = "../../common/lru_cache" } lru_cache = { path = "../../common/lru_cache" }
if-addrs = "0.6.4" if-addrs = "0.6.4"
strum = { version = "0.20"}

View File

@ -6,6 +6,7 @@ use eth2_libp2p::{
use fnv::FnvHashMap; use fnv::FnvHashMap;
pub use lighthouse_metrics::*; pub use lighthouse_metrics::*;
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
use strum::AsStaticRef;
use types::{subnet_id::subnet_id_to_string, EthSpec}; use types::{subnet_id::subnet_id_to_string, EthSpec};
lazy_static! { lazy_static! {
@ -308,113 +309,14 @@ lazy_static! {
} }
lazy_static! { lazy_static! {
/* pub static ref GOSSIP_ATTESTATION_ERRORS_PER_TYPE: Result<IntCounterVec> =
* Attestation Errors try_create_int_counter_vec(
*/ "gossipsub_attestation_errors_per_type",
pub static ref GOSSIP_ATTESTATION_ERROR_FUTURE_EPOCH: Result<IntCounter> = try_create_int_counter( "Gossipsub attestation errors per error type",
"gossipsub_attestation_error_future_epoch", &["type"]
"Count of a specific error type (see metric name)" );
);
pub static ref GOSSIP_ATTESTATION_ERROR_PAST_EPOCH: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_past_epoch",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_FUTURE_SLOT: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_future_slot",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_PAST_SLOT: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_past_slot",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_SELECTION_PROOF: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_invalid_selection_proof",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_SIGNATURE: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_invalid_signature",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_EMPTY_AGGREGATION_BITFIELD: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_empty_aggregation_bitfield",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_AGGREGATOR_PUBKEY_UNKNOWN: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_aggregator_pubkey_unknown",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_AGGREGATOR_NOT_IN_COMMITTEE: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_aggregator_not_in_committee",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_ATTESTATION_ALREADY_KNOWN: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_attestation_already_known",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_AGGREGATOR_ALREADY_KNOWN: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_aggregator_already_known",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_PRIOR_ATTESTATION_KNOWN: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_prior_attestation_known",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_VALIDATOR_INDEX_TOO_HIGH: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_validator_index_too_high",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_UNKNOWN_HEAD_BLOCK: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_unknown_head_block",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_UNKNOWN_TARGET_ROOT: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_unknown_target_root",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_BAD_TARGET_EPOCH: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_bad_target_epoch",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_NO_COMMITTEE_FOR_SLOT_AND_INDEX: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_no_committee_for_slot_and_index",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_NOT_EXACTLY_ONE_AGGREGATION_BIT_SET: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_not_exactly_one_aggregation_bit_set",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_ATTESTS_TO_FUTURE_BLOCK: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_attests_to_future_block",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_SUBNET_ID: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_invalid_subnet_id",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_STATE_PROCESSING: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_invalid_state_processing",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_TOO_MANY_SKIPPED_SLOTS: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_invalid_too_many_skipped_slots",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_TARGET_ROOT: Result<IntCounter> = try_create_int_counter(
"gossip_attestation_error_invalid_target_root",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_INVALID_TARGET_EPOCH: Result<IntCounter> = try_create_int_counter(
"gossip_attestation_error_invalid_target_epoch",
"Count of a specific error type (see metric name)"
);
pub static ref GOSSIP_ATTESTATION_ERROR_BEACON_CHAIN_ERROR: Result<IntCounter> = try_create_int_counter(
"gossipsub_attestation_error_beacon_chain_error",
"Count of a specific error type (see metric name)"
);
pub static ref INBOUND_LIBP2P_BYTES: Result<IntGauge> = pub static ref INBOUND_LIBP2P_BYTES: Result<IntGauge> =
try_create_int_gauge("libp2p_inbound_bytes", "The inbound bandwidth over libp2p"); try_create_int_gauge("libp2p_inbound_bytes", "The inbound bandwidth over libp2p");
pub static ref OUTBOUND_LIBP2P_BYTES: Result<IntGauge> = try_create_int_gauge( pub static ref OUTBOUND_LIBP2P_BYTES: Result<IntGauge> = try_create_int_gauge(
"libp2p_outbound_bytes", "libp2p_outbound_bytes",
"The outbound bandwidth over libp2p" "The outbound bandwidth over libp2p"
@ -452,67 +354,7 @@ lazy_static! {
} }
pub fn register_attestation_error(error: &AttnError) { pub fn register_attestation_error(error: &AttnError) {
match error { inc_counter_vec(&GOSSIP_ATTESTATION_ERRORS_PER_TYPE, &[error.as_ref()]);
AttnError::FutureEpoch { .. } => inc_counter(&GOSSIP_ATTESTATION_ERROR_FUTURE_EPOCH),
AttnError::PastEpoch { .. } => inc_counter(&GOSSIP_ATTESTATION_ERROR_PAST_EPOCH),
AttnError::FutureSlot { .. } => inc_counter(&GOSSIP_ATTESTATION_ERROR_FUTURE_SLOT),
AttnError::PastSlot { .. } => inc_counter(&GOSSIP_ATTESTATION_ERROR_PAST_SLOT),
AttnError::InvalidSelectionProof { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_SELECTION_PROOF)
}
AttnError::InvalidSignature => inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_SIGNATURE),
AttnError::EmptyAggregationBitfield => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_EMPTY_AGGREGATION_BITFIELD)
}
AttnError::AggregatorPubkeyUnknown(_) => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_AGGREGATOR_PUBKEY_UNKNOWN)
}
AttnError::AggregatorNotInCommittee { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_AGGREGATOR_NOT_IN_COMMITTEE)
}
AttnError::AttestationAlreadyKnown { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_ATTESTATION_ALREADY_KNOWN)
}
AttnError::AggregatorAlreadyKnown(_) => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_AGGREGATOR_ALREADY_KNOWN)
}
AttnError::PriorAttestationKnown { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_PRIOR_ATTESTATION_KNOWN)
}
AttnError::ValidatorIndexTooHigh(_) => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_VALIDATOR_INDEX_TOO_HIGH)
}
AttnError::UnknownHeadBlock { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_UNKNOWN_HEAD_BLOCK)
}
AttnError::UnknownTargetRoot(_) => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_UNKNOWN_TARGET_ROOT)
}
AttnError::BadTargetEpoch => inc_counter(&GOSSIP_ATTESTATION_ERROR_BAD_TARGET_EPOCH),
AttnError::NoCommitteeForSlotAndIndex { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_NO_COMMITTEE_FOR_SLOT_AND_INDEX)
}
AttnError::NotExactlyOneAggregationBitSet(_) => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_NOT_EXACTLY_ONE_AGGREGATION_BIT_SET)
}
AttnError::AttestsToFutureBlock { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_ATTESTS_TO_FUTURE_BLOCK)
}
AttnError::InvalidSubnetId { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_SUBNET_ID)
}
AttnError::Invalid(_) => inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_STATE_PROCESSING),
AttnError::InvalidTargetRoot { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_TARGET_ROOT)
}
AttnError::InvalidTargetEpoch { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_TARGET_EPOCH)
}
AttnError::TooManySkippedSlots { .. } => {
inc_counter(&GOSSIP_ATTESTATION_ERROR_INVALID_TOO_MANY_SKIPPED_SLOTS)
}
AttnError::BeaconChainError(_) => inc_counter(&GOSSIP_ATTESTATION_ERROR_BEACON_CHAIN_ERROR),
}
} }
/// Inspects the `messages` that were being sent to the network and updates Prometheus metrics. /// Inspects the `messages` that were being sent to the network and updates Prometheus metrics.
@ -732,7 +574,7 @@ pub fn update_gossip_metrics<T: EthSpec>(
for (peer_id, _) in gossipsub.all_peers() { for (peer_id, _) in gossipsub.all_peers() {
let client = peers let client = peers
.peer_info(peer_id) .peer_info(peer_id)
.map(|peer_info| peer_info.client.kind.as_static_ref()) .map(|peer_info| peer_info.client.kind.as_static())
.unwrap_or_else(|| "Unknown"); .unwrap_or_else(|| "Unknown");
peer_to_client.insert(peer_id, client); peer_to_client.insert(peer_id, client);