Skip to content

Commit

Permalink
monitor libp2p connection info (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
getong authored Jan 27, 2025
1 parent f405202 commit 3d88776
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
16 changes: 16 additions & 0 deletions src/mod_libp2p/behavior.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashSet;

use libp2p::{
identify::{Behaviour as IdentifyBehavior, Event as IdentifyEvent},
kad::{
Expand All @@ -6,6 +8,7 @@ use libp2p::{
},
ping::{self, Behaviour as PingBehaviour, Event as PingEvent},
swarm::NetworkBehaviour,
PeerId,
};

#[derive(NetworkBehaviour)]
Expand All @@ -28,6 +31,19 @@ impl AgentBehavior {
ping,
}
}

pub fn kad_known_peers(&mut self) -> HashSet<PeerId> {
let mut peers = HashSet::new();
for b in self.kad.kbuckets() {
for e in b.iter() {
if !peers.contains(e.node.key.preimage()) {
peers.insert(*e.node.key.preimage());
}
}
}

peers
}
}

#[derive(Debug)]
Expand Down
18 changes: 16 additions & 2 deletions src/mod_libp2p/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ use libp2p::{
};
use once_cell::sync::Lazy;
use serde_json::{json, Value};
use std::{error::Error, time::Duration};
use std::{collections::HashSet, error::Error, time::Duration};
use tokio::sync::Mutex;
use tracing::error;
use tracing::{error, info};

pub const TEST_BOOSTNODE_PEER_ID_LIST: [&str; 3] = [
"16Uiu2HAm5SPUotukayoKUZG5jQQ9zAGgjAXXz4Tg62kzZMbikLdQ",
Expand Down Expand Up @@ -76,9 +76,23 @@ impl EventLoop {
}

pub(crate) async fn run(&mut self) {
let mut interval1 = tokio::time::interval(tokio::time::Duration::from_secs(60));
let mut interval2 = tokio::time::interval(tokio::time::Duration::from_secs(60));
loop {
tokio::select! {
event = self.swarm.select_next_some() => self.handle_event(event).await,
_ = interval1.tick() => {
let peer_list = self.swarm.behaviour_mut().kad_known_peers();
info!("\n------ 60 secs, local_peer_id is {:?}, kad peer list is {:?}\n\n", self.swarm.local_peer_id(), peer_list);
}

_ = interval2.tick() => {
let mut peer_list = HashSet::new();
for peer in self.swarm.connected_peers() {
peer_list.insert(peer);
}
info!("\n------ 60 secs, local_peer_id is {:?}, swarm peer list is {:?}\n\n", self.swarm.local_peer_id(), peer_list);
}
}
}
}
Expand Down

0 comments on commit 3d88776

Please sign in to comment.