ping.go 4.45 KB
Newer Older
Brian Tiger Chow's avatar
Brian Tiger Chow committed
1 2 3 4 5 6
package commands

import (
	"bytes"
	"fmt"
	"io"
Jeromy's avatar
Jeromy committed
7
	"strings"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
8 9 10
	"time"

	cmds "github.com/jbenet/go-ipfs/commands"
Jeromy's avatar
Jeromy committed
11
	core "github.com/jbenet/go-ipfs/core"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
12 13 14 15
	peer "github.com/jbenet/go-ipfs/p2p/peer"
	u "github.com/jbenet/go-ipfs/util"

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
Jeromy's avatar
Jeromy committed
16
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
17 18
)

Jeromy's avatar
Jeromy committed
19 20
const kPingTimeout = 10 * time.Second

Brian Tiger Chow's avatar
Brian Tiger Chow committed
21 22 23
type PingResult struct {
	Success bool
	Time    time.Duration
24
	Text    string
Brian Tiger Chow's avatar
Brian Tiger Chow committed
25 26 27 28 29 30
}

var PingCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "send echo request packets to IPFS hosts",
		Synopsis: `
Jeromy's avatar
Jeromy committed
31 32
Send pings to a peer using the routing system to discover its address
		`,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
33
		ShortDescription: `
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34 35 36
ipfs ping is a tool to test sending data to other nodes. It finds nodes
via the routing system, send pings, wait for pongs, and print out round-
trip latency information.
Jeromy's avatar
Jeromy committed
37
		`,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
38 39
	},
	Arguments: []cmds.Argument{
40
		cmds.StringArg("peer ID", true, true, "ID of peer to be pinged").EnableStdin(),
41 42
	},
	Options: []cmds.Option{
Jeromy's avatar
Jeromy committed
43
		cmds.IntOption("count", "n", "number of ping messages to send"),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
44 45 46
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
47
			outChan, ok := res.Output().(<-chan interface{})
Brian Tiger Chow's avatar
Brian Tiger Chow committed
48 49 50 51 52 53 54 55 56 57 58
			if !ok {
				return nil, u.ErrCast()
			}

			marshal := func(v interface{}) (io.Reader, error) {
				obj, ok := v.(*PingResult)
				if !ok {
					return nil, u.ErrCast()
				}

				buf := new(bytes.Buffer)
59 60 61
				if len(obj.Text) > 0 {
					buf = bytes.NewBufferString(obj.Text + "\n")
				} else if obj.Success {
Jeromy's avatar
Jeromy committed
62
					fmt.Fprintf(buf, "Pong received: time=%.2f ms\n", obj.Time.Seconds()*1000)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
63 64 65 66 67 68 69 70 71 72 73 74 75
				} else {
					fmt.Fprintf(buf, "Pong failed\n")
				}
				return buf, nil
			}

			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
			}, nil
		},
	},
	Run: func(req cmds.Request) (interface{}, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
		ctx := req.Context().Context
Brian Tiger Chow's avatar
Brian Tiger Chow committed
77 78 79 80 81
		n, err := req.Context().GetNode()
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
82
		// Must be online!
Brian Tiger Chow's avatar
Brian Tiger Chow committed
83 84 85 86
		if !n.OnlineMode() {
			return nil, errNotOnline
		}

Jeromy's avatar
Jeromy committed
87
		addr, peerID, err := ParsePeerParam(req.Arguments()[0])
Jeromy's avatar
Jeromy committed
88 89
		if err != nil {
			return nil, err
Jeromy's avatar
Jeromy committed
90 91
		}

Jeromy's avatar
Jeromy committed
92
		if addr != nil {
Jeromy's avatar
Jeromy committed
93 94 95
			n.Peerstore.AddAddress(peerID, addr)
		}

Jeromy's avatar
Jeromy committed
96 97 98
		// Set up number of pings
		numPings := 10
		val, found, err := req.Option("count").Int()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
99 100 101
		if err != nil {
			return nil, err
		}
Jeromy's avatar
Jeromy committed
102 103 104 105
		if found {
			numPings = val
		}

Jeromy's avatar
Jeromy committed
106
		outChan := make(chan interface{})
107

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108
		go pingPeer(ctx, n, peerID, numPings, outChan)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
109 110 111 112 113

		return outChan, nil
	},
	Type: PingResult{},
}
Jeromy's avatar
Jeromy committed
114

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115
func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) {
Jeromy's avatar
Jeromy committed
116 117
	defer close(outChan)

Jeromy's avatar
Jeromy committed
118 119 120 121 122
	if len(n.Peerstore.Addresses(pid)) == 0 {
		// Make sure we can find the node in question
		outChan <- &PingResult{
			Text: fmt.Sprintf("Looking up peer %s", pid.Pretty()),
		}
Jeromy's avatar
Jeromy committed
123

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124
		ctx, _ := context.WithTimeout(ctx, kPingTimeout)
Jeromy's avatar
Jeromy committed
125 126 127 128 129 130
		p, err := n.Routing.FindPeer(ctx, pid)
		if err != nil {
			outChan <- &PingResult{Text: fmt.Sprintf("Peer lookup error: %s", err)}
			return
		}
		n.Peerstore.AddPeerInfo(p)
Jeromy's avatar
Jeromy committed
131 132
	}

Jeromy's avatar
Jeromy committed
133
	outChan <- &PingResult{Text: fmt.Sprintf("PING %s.", pid.Pretty())}
Jeromy's avatar
Jeromy committed
134

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135
	var done bool
Jeromy's avatar
Jeromy committed
136
	var total time.Duration
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140 141 142 143 144 145
	for i := 0; i < numPings && !done; i++ {
		select {
		case <-ctx.Done():
			done = true
			continue
		default:
		}

		ctx, _ := context.WithTimeout(ctx, kPingTimeout)
Jeromy's avatar
Jeromy committed
146
		took, err := n.Routing.Ping(ctx, pid)
Jeromy's avatar
Jeromy committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
		if err != nil {
			log.Errorf("Ping error: %s", err)
			outChan <- &PingResult{Text: fmt.Sprintf("Ping error: %s", err)}
			break
		}
		outChan <- &PingResult{
			Success: true,
			Time:    took,
		}
		total += took
		time.Sleep(time.Second)
	}
	averagems := total.Seconds() * 1000 / float64(numPings)
	outChan <- &PingResult{
		Text: fmt.Sprintf("Average latency: %.2fms", averagems),
	}
}
Jeromy's avatar
Jeromy committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

func ParsePeerParam(text string) (ma.Multiaddr, peer.ID, error) {
	// to be replaced with just multiaddr parsing, once ptp is a multiaddr protocol
	idx := strings.LastIndex(text, "/")
	if idx == -1 {
		pid, err := peer.IDB58Decode(text)
		if err != nil {
			return nil, "", err
		}

		return nil, pid, nil
	}

	addrS := text[:idx]
	peeridS := text[idx+1:]

	var maddr ma.Multiaddr
	var pid peer.ID

	// make sure addrS parses as a multiaddr.
	if len(addrS) > 0 {
		var err error
		maddr, err = ma.NewMultiaddr(addrS)
		if err != nil {
			return nil, "", err
		}
	}

	// make sure idS parses as a peer.ID
	var err error
	pid, err = peer.IDB58Decode(peeridS)
	if err != nil {
		return nil, "", err
	}

	return maddr, pid, nil
}