ping.go 4.31 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: `
Jeromy's avatar
Jeromy committed
34 35 36
		ipfs ping is a tool to find a node (in the routing system),
		send pings, wait for pongs, and print out round-trip latency information.
		`,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
37 38
	},
	Arguments: []cmds.Argument{
39 40 41
		cmds.StringArg("peer ID", true, true, "ID of peer to be pinged"),
	},
	Options: []cmds.Option{
Jeromy's avatar
Jeromy committed
42
		cmds.IntOption("count", "n", "number of ping messages to send"),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
	},
	Marshalers: cmds.MarshalerMap{
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
			outChan, ok := res.Output().(chan interface{})
			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)
58 59 60
				if len(obj.Text) > 0 {
					buf = bytes.NewBufferString(obj.Text + "\n")
				} else if obj.Success {
Jeromy's avatar
Jeromy committed
61
					fmt.Fprintf(buf, "Pong received: time=%.2f ms\n", obj.Time.Seconds()*1000)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
				} 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) {
		n, err := req.Context().GetNode()
		if err != nil {
			return nil, err
		}

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

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

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

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

Jeromy's avatar
Jeromy committed
104
		outChan := make(chan interface{})
105

Jeromy's avatar
Jeromy committed
106
		go pingPeer(n, peerID, numPings, outChan)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
107 108 109 110 111

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

func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) {
	defer close(outChan)

Jeromy's avatar
Jeromy committed
116 117 118 119 120
	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
121

Jeromy's avatar
Jeromy committed
122 123 124 125 126 127 128 129
		// TODO: get master context passed in
		ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout)
		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
130 131
	}

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

	var total time.Duration
	for i := 0; i < numPings; i++ {
Jeromy's avatar
Jeromy committed
136 137
		ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout)
		took, err := n.Routing.Ping(ctx, pid)
Jeromy's avatar
Jeromy committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
		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
155 156 157 158 159 160 161 162 163 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

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
}