|
| 1 | +package peer |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "strconv" |
| 7 | + |
| 8 | + libp2pNetwork "github.com/libp2p/go-libp2p/core/network" |
| 9 | + "github.com/spf13/cobra" |
| 10 | + |
| 11 | + "github.com/pokt-network/pocket/app/client/cli/helpers" |
| 12 | + "github.com/pokt-network/pocket/p2p/utils" |
| 13 | + "github.com/pokt-network/pocket/shared/modules" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + printConnectionsHeader = []string{"Peer ID", "Multiaddr", "Opened", "Direction", "NumStreams"} |
| 18 | + |
| 19 | + connectionsCmd = &cobra.Command{ |
| 20 | + Use: "connections", |
| 21 | + Short: "Print open peer connections", |
| 22 | + RunE: connectionsRunE, |
| 23 | + } |
| 24 | +) |
| 25 | + |
| 26 | +func init() { |
| 27 | + PeerCmd.AddCommand(connectionsCmd) |
| 28 | +} |
| 29 | + |
| 30 | +func connectionsRunE(cmd *cobra.Command, _ []string) error { |
| 31 | + bus, ok := helpers.GetValueFromCLIContext[modules.Bus](cmd, helpers.BusCLICtxKey) |
| 32 | + if !ok { |
| 33 | + log.Fatal("unable to get bus from context") |
| 34 | + } |
| 35 | + |
| 36 | + p2pModule := bus.GetP2PModule() |
| 37 | + if p2pModule == nil { |
| 38 | + return fmt.Errorf("no p2p module found on the bus") |
| 39 | + } |
| 40 | + |
| 41 | + conns := p2pModule.GetConnections() |
| 42 | + if err := printConnections(conns); err != nil { |
| 43 | + return fmt.Errorf("printing connections: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + return nil |
| 47 | +} |
| 48 | + |
| 49 | +func peerConnsRowConsumerFactory(conns []libp2pNetwork.Conn) utils.RowConsumer { |
| 50 | + return func(provideRow utils.RowProvider) error { |
| 51 | + for _, conn := range conns { |
| 52 | + err := provideRow( |
| 53 | + conn.RemotePeer().String(), |
| 54 | + conn.RemoteMultiaddr().String(), |
| 55 | + conn.Stat().Opened.String(), |
| 56 | + conn.Stat().Direction.String(), |
| 57 | + strconv.Itoa(conn.Stat().NumStreams), |
| 58 | + ) |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + } |
| 63 | + return nil |
| 64 | + } |
| 65 | +} |
| 66 | +func printConnections(conns []libp2pNetwork.Conn) error { |
| 67 | + return utils.PrintTable(printConnectionsHeader, peerConnsRowConsumerFactory(conns)) |
| 68 | +} |
0 commit comments