ping: use context
Juan Batiz-Benet committed
Jan 10, 2015 at 21:08 UTC
f7941e9841a960dcc08a352d8565ffd3edd74740
1 file changed
+14
-6
core/commands/ping.go
+14
-6
@@ -72,6 +72,7 @@ Send pings to a peer using the routing system to discover its address
72
},
73
},
74
Run: func(req cmds.Request) (interface{}, error) {
75
+ ctx := req.Context().Context
76
n, err := req.Context().GetNode()
77
if err != nil {
78
return nil, err
@@ -103,14 +104,14 @@ Send pings to a peer using the routing system to discover its address
104
105
outChan := make(chan interface{})
106
106
- go pingPeer(n, peerID, numPings, outChan)
107
+ go pingPeer(ctx, n, peerID, numPings, outChan)
108
109
return outChan, nil
110
},
111
Type: PingResult{},
112
}
113
113
-func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) {
114
+func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interface{}) {
115
defer close(outChan)
116
117
if len(n.Peerstore.Addresses(pid)) == 0 {
@@ -119,8 +120,7 @@ func pingPeer(n *core.IpfsNode, pid peer.ID, numPings int, outChan chan interfac
120
Text: fmt.Sprintf("Looking up peer %s", pid.Pretty()),
121
}
122
122
- // TODO: get master context passed in
123
- ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout)
123
+ ctx, _ := context.WithTimeout(ctx, kPingTimeout)
124
p, err := n.Routing.FindPeer(ctx, pid)
125
if err != nil {
126
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
131
132
outChan <- &PingResult{Text: fmt.Sprintf("PING %s.", pid.Pretty())}
133
134
+ var done bool
135
var total time.Duration
135
- for i := 0; i < numPings; i++ {
136
- ctx, _ := context.WithTimeout(context.TODO(), kPingTimeout)
136
+ for i := 0; i < numPings && !done; i++ {
137
+ select {
138
+ case <-ctx.Done():
139
+ done = true
140
+ continue
141
+ default:
142
+ }
143
+
144
+ ctx, _ := context.WithTimeout(ctx, kPingTimeout)
145
took, err := n.Routing.Ping(ctx, pid)
146
if err != nil {
147
log.Errorf("Ping error: %s", err)