ping.go 4.4 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
				} 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
75
		ctx := req.Context().Context
Brian Tiger Chow's avatar
Brian Tiger Chow committed
76 77 78 79 80
		n, err := req.Context().GetNode()
		if err != nil {
			return nil, err
		}

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

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

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

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

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
		ctx, _ := context.WithTimeout(ctx, kPingTimeout)
Jeromy's avatar
Jeromy committed
124 125 126 127 128 129
		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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	var done bool
Jeromy's avatar
Jeromy committed
135
	var total time.Duration
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137 138 139 140 141 142 143 144
	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
145
		took, err := n.Routing.Ping(ctx, pid)
Jeromy's avatar
Jeromy committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
		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
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 192 193 194 195 196 197 198 199

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
}