prevent wantmanager from leaking goroutines (and memory)
License: MIT Signed-off-by: Jeromy <jeromyj@gmail.com>
Jeromy committed
Jun 11, 2015 at 09:22 UTC
c5b40b3b0269c171170c00d44189661c5b8310b0
1 file changed
+37
-24
exchange/bitswap/wantmanager.go
+37
-24
@@ -137,36 +137,49 @@ func (mq *msgQueue) runQueue(ctx context.Context) {
137
for {
138
select {
139
case <-mq.work: // there is work to be done
140
-
141
- err := mq.network.ConnectTo(ctx, mq.p)
142
- if err != nil {
143
- log.Noticef("cant connect to peer %s: %s", mq.p, err)
144
- // TODO: cant connect, what now?
145
- continue
146
- }
147
-
148
- // grab outgoing message
149
- mq.outlk.Lock()
150
- wlm := mq.out
151
- if wlm == nil || wlm.Empty() {
152
- mq.outlk.Unlock()
153
- continue
154
- }
155
- mq.out = nil
156
- mq.outlk.Unlock()
157
-
158
- // send wantlist updates
159
- err = mq.network.SendMessage(ctx, mq.p, wlm)
160
- if err != nil {
161
- log.Noticef("bitswap send error: %s", err)
162
- // TODO: what do we do if this fails?
163
- }
140
+ mq.doWork(ctx)
141
case <-mq.done:
142
return
143
}
144
}
145
}
146
147
+func (mq *msgQueue) doWork(ctx context.Context) {
148
+ // allow a minute for connections
149
+ // this includes looking them up in the dht
150
+ // dialing them, and handshaking
151
+ conctx, cancel := context.WithTimeout(ctx, time.Minute)
152
+ defer cancel()
153
+
154
+ err := mq.network.ConnectTo(conctx, mq.p)
155
+ if err != nil {
156
+ log.Noticef("cant connect to peer %s: %s", mq.p, err)
157
+ // TODO: cant connect, what now?
158
+ return
159
+ }
160
+
161
+ // grab outgoing message
162
+ mq.outlk.Lock()
163
+ wlm := mq.out
164
+ mq.out = nil
165
+ mq.outlk.Unlock()
166
+
167
+ if wlm == nil || wlm.Empty() {
168
+ return
169
+ }
170
+
171
+ sendctx, cancel := context.WithTimeout(ctx, time.Second*30)
172
+ defer cancel()
173
+
174
+ // send wantlist updates
175
+ err = mq.network.SendMessage(sendctx, mq.p, wlm)
176
+ if err != nil {
177
+ log.Noticef("bitswap send error: %s", err)
178
+ // TODO: what do we do if this fails?
179
+ return
180
+ }
181
+}
182
+
183
func (pm *WantManager) Connected(p peer.ID) {
184
pm.connect <- p
185
}