fix(commands): goroutine leaks in ping.go
License: MIT Signed-off-by: Overbool <overbool.xu@gmail.com>
Overbool committed
Sep 9, 2018 at 19:08 UTC
a26228a73fa1bb961e2d0c1a71d314f61240e34e
1 file changed
+31
-9
core/commands/ping.go
+31
-9
@@ -10,10 +10,10 @@ import (
10
"time"
11
12
cmds "github.com/ipfs/go-ipfs/commands"
13
- core "github.com/ipfs/go-ipfs/core"
13
+ "github.com/ipfs/go-ipfs/core"
14
15
u "gx/ipfs/QmPdKqUcHGFdeSpvjVoaTRPPstGif9GBZb5Q56RVw9o69A/go-ipfs-util"
16
- peer "gx/ipfs/QmQsErDt8Qgw1XrsXf2BpEzDgGWtB1YLsTAARBup5b6B9W/go-libp2p-peer"
16
+ "gx/ipfs/QmQsErDt8Qgw1XrsXf2BpEzDgGWtB1YLsTAARBup5b6B9W/go-libp2p-peer"
17
"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
18
ma "gx/ipfs/QmYmsdtJ3HsodkePE3eU3TsCaP2YvPZJ4LoXnNkDE5Tpt7/go-multiaddr"
19
pstore "gx/ipfs/Qmda4cPRvSRyox3SqgJN6DfSZGU5TtHufPTp9uXjFj71X6/go-libp2p-peerstore"
@@ -120,33 +120,49 @@ func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int)
120
121
if len(n.Peerstore.Addrs(pid)) == 0 {
122
// Make sure we can find the node in question
123
- outChan <- &PingResult{
123
+ select {
124
+ case outChan <- &PingResult{
125
Text: fmt.Sprintf("Looking up peer %s", pid.Pretty()),
126
Success: true,
127
+ }:
128
+ case <-ctx.Done():
129
+ return
130
}
131
132
ctx, cancel := context.WithTimeout(ctx, kPingTimeout)
133
defer cancel()
134
p, err := n.Routing.FindPeer(ctx, pid)
135
if err != nil {
132
- outChan <- &PingResult{Text: fmt.Sprintf("Peer lookup error: %s", err)}
136
+ select {
137
+ case outChan <- &PingResult{Text: fmt.Sprintf("Peer lookup error: %s", err)}:
138
+ case <-ctx.Done():
139
+ return
140
+ }
141
+
142
return
143
}
144
n.Peerstore.AddAddrs(p.ID, p.Addrs, pstore.TempAddrTTL)
145
}
146
138
- outChan <- &PingResult{
147
+ select {
148
+ case outChan <- &PingResult{
149
Text: fmt.Sprintf("PING %s.", pid.Pretty()),
150
Success: true,
151
+ }:
152
+ case <-ctx.Done():
153
+ return
154
}
155
156
ctx, cancel := context.WithTimeout(ctx, kPingTimeout*time.Duration(numPings))
157
defer cancel()
158
pings, err := n.Ping.Ping(ctx, pid)
159
if err != nil {
147
- outChan <- &PingResult{
160
+ select {
161
+ case outChan <- &PingResult{
162
Success: false,
163
Text: fmt.Sprintf("Ping error: %s", err),
164
+ }:
165
+ case <-ctx.Done():
166
}
167
return
168
}
@@ -163,19 +179,25 @@ func pingPeer(ctx context.Context, n *core.IpfsNode, pid peer.ID, numPings int)
179
done = true
180
break
181
}
166
-
167
- outChan <- &PingResult{
182
+ select {
183
+ case outChan <- &PingResult{
184
Success: true,
185
Time: t,
186
+ }:
187
+ case <-ctx.Done():
188
+ return
189
}
190
total += t
191
time.Sleep(time.Second)
192
}
193
}
194
averagems := total.Seconds() * 1000 / float64(numPings)
176
- outChan <- &PingResult{
195
+ select {
196
+ case outChan <- &PingResult{
197
Success: true,
198
Text: fmt.Sprintf("Average latency: %.2fms", averagems),
199
+ }:
200
+ case <-ctx.Done():
201
}
202
}()
203
return outChan