From f7941e9841a960dcc08a352d8565ffd3edd74740 Mon Sep 17 00:00:00 2001 From: Juan Batiz-Benet Date: Sat, 10 Jan 2015 21:08:34 -0800 Subject: [PATCH] ping: use context --- core/commands/ping.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/core/commands/ping.go b/core/commands/ping.go index 523d4357d..096852cb8 100644 --- a/core/commands/ping.go +++ b/core/commands/ping.go @@ -72,6 +72,7 @@ Send pings to a peer using the routing system to discover its address }, }, Run: func(req cmds.Request) (interface{}, error) { + ctx := req.Context().Context n, err := req.Context().GetNode() if err != nil { return nil, err @@ -103,14 +104,14 @@ Send pings to a peer using the routing system to discover its address outChan := make(chan interface{}) - go pingPeer(n, peerID, numPings, outChan) + go pingPeer(ctx, n, peerID, numPings, outChan) return outChan, nil }, Type: PingResult{}, } -func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) { +func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) { defer close(outChan) if len(n.Peerstore.Addresses(pid)) == 0 { @@ -119,8 +120,7 @@ func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interfac Text: fmt.Sprintf("Looking up peer %s", pid.Pretty()), } - // TODO: get master context passed in - ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout) + ctx, _ := context.WithTimeout(ctx, kPingTimeout) p, err := n.Routing.FindPeer(ctx, pid) if err != nil { outChan <- &PingResult{Text: fmt.Sprintf("Peer lookup error: %s", err)} @@ -131,9 +131,17 @@ func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interfac outChan <- &PingResult{Text: fmt.Sprintf("PING %s.", pid.Pretty())} + var done bool var total time.Duration - for i := 0; i < numPings; i++ { - ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout) + for i := 0; i < numPings && !done; i++ { + select { + case <-ctx.Done(): + done = true + continue + default: + } + + ctx, _ := context.WithTimeout(ctx, kPingTimeout) took, err := n.Routing.Ping(ctx, pid) if err != nil { log.Errorf("Ping error: %s", err)