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: forest-cli net info #3292

Merged
merged 8 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
loading forest.car.zst files.
- [#3284](https://github.com/ChainSafe/forest/pull/3284): Add `--diff` flag to
`archive export`.
- [#3292](https://github.com/ChainSafe/forest/pull/3292): Add `net info`
subcommand to `forest-cli`.

### Changed

Expand Down
1 change: 1 addition & 0 deletions scripts/gen_coverage_report.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ cov forest-cli snapshot export
cov forest-cli attach --exec 'showPeers()'
cov forest-cli net listen
cov forest-cli net peers
cov forest-cli net info

# Load the admin token
TOKEN=$(cat "$TOKEN_PATH")
Expand Down
3 changes: 3 additions & 0 deletions scripts/tests/calibnet_other_check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ $FOREST_CLI_PATH chain set-head --epoch -10 --force
echo "Test subcommand: info show"
$FOREST_CLI_PATH info show

echo "Test subcommand: net info"
$FOREST_CLI_PATH net info

$FOREST_CLI_PATH sync wait # allow the node to re-sync
19 changes: 17 additions & 2 deletions src/cli/subcommands/net_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::rpc_client::net_ops::*;
use ahash::HashSet;
use cid::multibase;
use clap::Subcommand;
use itertools::Itertools;

use super::{handle_rpc_err, print_stdout, Config};
use crate::cli::subcommands::cli_error_and_die;
Expand All @@ -15,6 +16,8 @@ use crate::cli::subcommands::cli_error_and_die;
pub enum NetCommands {
/// Lists `libp2p` swarm listener addresses
Listen,
/// Lists `libp2p` swarm network info
Info,
/// Lists `libp2p` swarm peers
Peers,
/// Connects to a peer by its peer ID and multi-addresses
Expand Down Expand Up @@ -44,6 +47,19 @@ impl NetCommands {
print_stdout(addresses.join("\n"));
Ok(())
}
Self::Info => {
let info = net_info((), &config.client.rpc_token)
.await
.map_err(handle_rpc_err)?;
println!("forest libp2p swarm info:");
Copy link
Member

Choose a reason for hiding this comment

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

Perhaps we could implement Display for the NetInfoResult?

Copy link
Contributor Author

@hanabi1224 hanabi1224 Jul 31, 2023

Choose a reason for hiding this comment

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

I thought about it but not sure if it's good practice to implement a multi-line Display message, formatting a multi-line message with print macro could end up with messy result

Copy link
Member

Choose a reason for hiding this comment

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

I'm good with either approach.

println!("num peers: {}", info.num_peers);
println!("num connections: {}", info.num_connections);
println!("num pending: {}", info.num_pending);
println!("num pending incoming: {}", info.num_pending_incoming);
println!("num pending outgoing: {}", info.num_pending_outgoing);
println!("num established: {}", info.num_established);
Ok(())
}
Self::Peers => {
let addrs = net_peers((), &config.client.rpc_token)
.await
Expand All @@ -60,8 +76,7 @@ impl NetCommands {
_ => true,
})
.map(|addr| addr.to_string())
.collect::<HashSet<_>>()
.into_iter()
.unique()
.collect();
if addresses.is_empty() {
return None;
Expand Down
8 changes: 7 additions & 1 deletion src/libp2p/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ use std::{
time::{Duration, SystemTime, UNIX_EPOCH},
};

use crate::blocks::GossipBlock;
use crate::chain::ChainStore;
use crate::libp2p_bitswap::{
request_manager::BitswapRequestManager, BitswapStoreRead, BitswapStoreReadWrite,
};
use crate::message::SignedMessage;
use crate::{blocks::GossipBlock, rpc_api::net_api::NetInfoResult};
use ahash::{HashMap, HashSet};
use anyhow::Context;
use cid::Cid;
Expand Down Expand Up @@ -170,6 +170,7 @@ pub enum NetworkMessage {
pub enum NetRPCMethods {
AddrsListen(OneShotSender<(PeerId, HashSet<Multiaddr>)>),
Peers(OneShotSender<HashMap<PeerId, HashSet<Multiaddr>>>),
Info(OneShotSender<NetInfoResult>),
Connect(OneShotSender<bool>, PeerId, HashSet<Multiaddr>),
Disconnect(OneShotSender<()>, PeerId),
}
Expand Down Expand Up @@ -437,6 +438,11 @@ async fn handle_network_message(
warn!("Failed to get Libp2p peers");
}
}
NetRPCMethods::Info(response_channel) => {
if response_channel.send(swarm.network_info().into()).is_err() {
warn!("Failed to get Libp2p peers");
}
}
NetRPCMethods::Connect(response_channel, peer_id, addresses) => {
let mut success = false;

Expand Down
1 change: 1 addition & 0 deletions src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ where
// Net API
.with_method(NET_ADDRS_LISTEN, net_api::net_addrs_listen::<DB>)
.with_method(NET_PEERS, net_api::net_peers::<DB>)
.with_method(NET_INFO, net_api::net_info::<DB>)
.with_method(NET_CONNECT, net_api::net_connect::<DB>)
.with_method(NET_DISCONNECT, net_api::net_disconnect::<DB>)
// DB API
Expand Down
12 changes: 12 additions & 0 deletions src/rpc/net_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,18 @@ pub(in crate::rpc) async fn net_peers<DB: Blockstore + Clone + Send + Sync + 'st
Ok(connections)
}

pub(in crate::rpc) async fn net_info<DB: Blockstore>(
data: Data<RPCState<DB>>,
) -> Result<NetInfoResult, JsonRpcError> {
let (tx, rx) = oneshot::channel();
let req = NetworkMessage::JSONRPCRequest {
method: NetRPCMethods::Info(tx),
};

data.network_send.send_async(req).await?;
Ok(rx.await?)
}

pub(in crate::rpc) async fn net_connect<DB: Blockstore + Clone + Send + Sync + 'static>(
data: Data<RPCState<DB>>,
Params(params): Params<NetConnectParams>,
Expand Down
30 changes: 30 additions & 0 deletions src/rpc_api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ pub static ACCESS_MAP: Lazy<HashMap<&str, Access>> = Lazy::new(|| {
// Net API
access.insert(net_api::NET_ADDRS_LISTEN, Access::Read);
access.insert(net_api::NET_PEERS, Access::Read);
access.insert(net_api::NET_INFO, Access::Read);
access.insert(net_api::NET_CONNECT, Access::Write);
access.insert(net_api::NET_DISCONNECT, Access::Write);

Expand Down Expand Up @@ -417,6 +418,8 @@ pub mod common_api {

/// Net API
pub mod net_api {
use serde::{Deserialize, Serialize};

use crate::rpc_api::data_types::AddrInfo;

pub const NET_ADDRS_LISTEN: &str = "Filecoin.NetAddrsListen";
Expand All @@ -427,6 +430,33 @@ pub mod net_api {
pub type NetPeersParams = ();
pub type NetPeersResult = Vec<AddrInfo>;

pub const NET_INFO: &str = "Filecoin.NetInfo";
pub type NetInfoParams = ();

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct NetInfoResult {
pub num_peers: usize,
pub num_connections: u32,
pub num_pending: u32,
pub num_pending_incoming: u32,
pub num_pending_outgoing: u32,
pub num_established: u32,
}

impl From<libp2p::swarm::NetworkInfo> for NetInfoResult {
fn from(i: libp2p::swarm::NetworkInfo) -> Self {
let counters = i.connection_counters();
Self {
num_peers: i.num_peers(),
num_connections: counters.num_connections(),
num_pending: counters.num_pending(),
num_pending_incoming: counters.num_pending_incoming(),
num_pending_outgoing: counters.num_pending_outgoing(),
num_established: counters.num_established(),
}
}
}

pub const NET_CONNECT: &str = "Filecoin.NetConnect";
pub type NetConnectParams = (AddrInfo,);
pub type NetConnectResult = ();
Expand Down
7 changes: 7 additions & 0 deletions src/rpc_client/net_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ pub async fn net_peers(
call(NET_PEERS, params, auth_token).await
}

pub async fn net_info(
params: NetInfoParams,
auth_token: &Option<String>,
) -> Result<NetInfoResult, Error> {
call(NET_INFO, params, auth_token).await
}

pub async fn net_connect(
params: NetConnectParams,
auth_token: &Option<String>,
Expand Down