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: cli/net: implement 'net ping' command #8357

Merged
merged 4 commits into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all 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 api/api_net.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"context"
"time"

metrics "github.com/libp2p/go-libp2p-core/metrics"
"github.com/libp2p/go-libp2p-core/network"
Expand All @@ -25,6 +26,7 @@ type Net interface {

NetConnectedness(context.Context, peer.ID) (network.Connectedness, error) //perm:read
NetPeers(context.Context) ([]peer.AddrInfo, error) //perm:read
NetPing(context.Context, peer.ID) (time.Duration, error) //perm:read
NetConnect(context.Context, peer.AddrInfo) error //perm:write
NetAddrsListen(context.Context) (peer.AddrInfo, error) //perm:read
NetDisconnect(context.Context, peer.ID) error //perm:write
Expand Down
16 changes: 16 additions & 0 deletions api/mocks/mock_full.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions api/proxy_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions api/v0api/gomock_reflect_3555711957/prog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package main
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm confused about the purpose of this tool. Is this file supposed to be checked in? I'm not seeing a big change to the mocking framework in this PR that would indicate we need this binary. If we do want this behavior wouldn't it make sense to put this in the cmd directory as its own binary or a tool in lotus-shed? If it needs to stay here why the 355.. magic number?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh, this is just a temp file created by gomock when generating mocks, probably got here through git add -a ..; Shouldn't be here


import (
"encoding/gob"
"flag"
"fmt"
"os"
"path"
"reflect"

"github.com/golang/mock/mockgen/model"

pkg_ "github.com/filecoin-project/lotus/api/v0api"
)

var output = flag.String("output", "", "The output file name, or empty to use stdout.")
Copy link
Contributor

Choose a reason for hiding this comment

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

When I run this on standard out I get a bunch of errors from binary output as you'd expect from gob output. stdout doesn't seem like a useful default


func main() {
flag.Parse()

its := []struct {
sym string
typ reflect.Type
}{

{"FullNode", reflect.TypeOf((*pkg_.FullNode)(nil)).Elem()},
}
pkg := &model.Package{
// NOTE: This behaves contrary to documented behaviour if the
// package name is not the final component of the import path.
// The reflect package doesn't expose the package name, though.
Name: path.Base("github.com/filecoin-project/lotus/api/v0api"),
}

for _, it := range its {
intf, err := model.InterfaceFromInterfaceType(it.typ)
if err != nil {
fmt.Fprintf(os.Stderr, "Reflection: %v\n", err)
os.Exit(1)
}
intf.Name = it.sym
pkg.Interfaces = append(pkg.Interfaces, intf)
}

outfile := os.Stdout
if len(*output) != 0 {
var err error
outfile, err = os.Create(*output)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open output file %q", *output)
}
defer func() {
if err := outfile.Close(); err != nil {
fmt.Fprintf(os.Stderr, "failed to close output file %q", *output)
os.Exit(1)
}
}()
}

if err := gob.NewEncoder(outfile).Encode(pkg); err != nil {
fmt.Fprintf(os.Stderr, "gob encode: %v\n", err)
os.Exit(1)
}
}
16 changes: 16 additions & 0 deletions api/v0api/v0mocks/mock_full.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified build/openrpc/full.json.gz
Binary file not shown.
Binary file modified build/openrpc/miner.json.gz
Binary file not shown.
Binary file modified build/openrpc/worker.json.gz
Binary file not shown.
164 changes: 126 additions & 38 deletions cli/net.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package cli

import (
"context"
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"text/tabwriter"
"time"

"github.com/dustin/go-humanize"
"github.com/urfave/cli/v2"
Expand All @@ -28,6 +30,7 @@ var NetCmd = &cli.Command{
Usage: "Manage P2P Network",
Subcommands: []*cli.Command{
NetPeers,
NetPing,
NetConnect,
NetListen,
NetId,
Expand Down Expand Up @@ -117,6 +120,82 @@ var NetPeers = &cli.Command{
},
}

var NetPing = &cli.Command{
Name: "ping",
Usage: "Ping peers",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "count",
Value: 10,
Aliases: []string{"c"},
Usage: "specify the number of times it should ping",
},
&cli.DurationFlag{
Name: "interval",
Value: time.Second,
Aliases: []string{"i"},
Usage: "minimum time between pings",
},
},
Action: func(cctx *cli.Context) error {
if cctx.Args().Len() != 1 {
return xerrors.Errorf("please provide a peerID")
}

api, closer, err := GetAPI(cctx)
if err != nil {
return err
}
defer closer()

ctx := ReqContext(cctx)

pis, err := addrInfoFromArg(ctx, cctx)
if err != nil {
return err
}

count := cctx.Int("count")
interval := cctx.Duration("interval")

for _, pi := range pis {
err := api.NetConnect(ctx, pi)
if err != nil {
return xerrors.Errorf("connect: %w", err)
}

fmt.Printf("PING %s\n", pi.ID)
var avg time.Duration
var successful int

for i := 0; i < count && ctx.Err() == nil; i++ {
start := time.Now()

rtt, err := api.NetPing(ctx, pi.ID)
if err != nil {
if ctx.Err() != nil {
break
}
log.Errorf("Ping failed: error=%v", err)
continue
}
fmt.Printf("Pong received: time=%v\n", rtt)
avg = avg + rtt
successful++

wctx, cancel := context.WithTimeout(ctx, time.Until(start.Add(interval)))
<-wctx.Done()
cancel()
}

if successful > 0 {
fmt.Printf("Average latency: %v\n", avg/time.Duration(successful))
}
}
return nil
},
}

var NetScores = &cli.Command{
Name: "scores",
Usage: "Print peers' pubsub scores",
Expand Down Expand Up @@ -192,45 +271,9 @@ var NetConnect = &cli.Command{
defer closer()
ctx := ReqContext(cctx)

pis, err := addrutil.ParseAddresses(ctx, cctx.Args().Slice())
pis, err := addrInfoFromArg(ctx, cctx)
if err != nil {
a, perr := address.NewFromString(cctx.Args().First())
if perr != nil {
return err
}

na, fc, err := GetFullNodeAPI(cctx)
if err != nil {
return err
}
defer fc()

mi, err := na.StateMinerInfo(ctx, a, types.EmptyTSK)
if err != nil {
return xerrors.Errorf("getting miner info: %w", err)
}

if mi.PeerId == nil {
return xerrors.Errorf("no PeerID for miner")
}
multiaddrs := make([]multiaddr.Multiaddr, 0, len(mi.Multiaddrs))
for i, a := range mi.Multiaddrs {
maddr, err := multiaddr.NewMultiaddrBytes(a)
if err != nil {
log.Warnf("parsing multiaddr %d (%x): %s", i, a, err)
continue
}
multiaddrs = append(multiaddrs, maddr)
}

pi := peer.AddrInfo{
ID: *mi.PeerId,
Addrs: multiaddrs,
}

fmt.Printf("%s -> %s\n", a, pi)

pis = append(pis, pi)
return err
}

for _, pi := range pis {
Expand All @@ -247,6 +290,51 @@ var NetConnect = &cli.Command{
},
}

func addrInfoFromArg(ctx context.Context, cctx *cli.Context) ([]peer.AddrInfo, error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I know this is just copied over from existing code but this method is surprising. It looks like it will either handle a slice of libp2p peer addr infos or it will take a single miner addr. Either the name should carry over some of the complexity ("addrInfoFromAddrInfosOrMinerAddr") or you should add a comment describing what's going on.

pis, err := addrutil.ParseAddresses(ctx, cctx.Args().Slice())
if err != nil {
a, perr := address.NewFromString(cctx.Args().First())
if perr != nil {
return nil, err
}

na, fc, err := GetFullNodeAPI(cctx)
if err != nil {
return nil, err
}
defer fc()

mi, err := na.StateMinerInfo(ctx, a, types.EmptyTSK)
if err != nil {
return nil, xerrors.Errorf("getting miner info: %w", err)
}

if mi.PeerId == nil {
return nil, xerrors.Errorf("no PeerID for miner")
}
multiaddrs := make([]multiaddr.Multiaddr, 0, len(mi.Multiaddrs))
for i, a := range mi.Multiaddrs {
maddr, err := multiaddr.NewMultiaddrBytes(a)
if err != nil {
log.Warnf("parsing multiaddr %d (%x): %s", i, a, err)
continue
}
multiaddrs = append(multiaddrs, maddr)
}

pi := peer.AddrInfo{
ID: *mi.PeerId,
Addrs: multiaddrs,
}

fmt.Printf("%s -> %s\n", a, pi)

pis = append(pis, pi)
}

return pis, err
}

var NetId = &cli.Command{
Name: "id",
Usage: "Get node identity",
Expand Down
Loading