Skip to content

Commit 8e1c532

Browse files
authored
fix(p2p): infinity loop if no peer in queue (gnolang#3593)
1 parent fd24486 commit 8e1c532

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

tm2/pkg/p2p/switch.go

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,9 @@ type MultiplexSwitch struct {
7272
privatePeers sync.Map // ID -> nothing; lookup table of peers who are not shared
7373
transport Transport
7474

75-
dialQueue *dial.Queue
76-
events *events.Events
75+
dialQueue *dial.Queue
76+
dialNotify chan struct{}
77+
events *events.Events
7778
}
7879

7980
// NewMultiplexSwitch creates a new MultiplexSwitch with the given config.
@@ -88,6 +89,7 @@ func NewMultiplexSwitch(
8889
peers: newSet(),
8990
transport: transport,
9091
dialQueue: dial.NewQueue(),
92+
dialNotify: make(chan struct{}, 1),
9193
events: events.New(),
9294
maxInboundPeers: defaultCfg.MaxNumInboundPeers,
9395
maxOutboundPeers: defaultCfg.MaxNumOutboundPeers,
@@ -262,13 +264,15 @@ func (sw *MultiplexSwitch) runDialLoop(ctx context.Context) {
262264
select {
263265
case <-ctx.Done():
264266
sw.Logger.Debug("dial context canceled")
265-
266267
return
268+
267269
default:
268270
// Grab a dial item
269271
item := sw.dialQueue.Peek()
270272
if item == nil {
271-
// Nothing to dial
273+
// Nothing to dial, wait until something is
274+
// added to the queue
275+
sw.waitForPeersToDial(ctx)
272276
continue
273277
}
274278

@@ -565,6 +569,7 @@ func (sw *MultiplexSwitch) DialPeers(peerAddrs ...*types.NetAddress) {
565569
}
566570

567571
sw.dialQueue.Push(item)
572+
sw.notifyAddPeerToDial()
568573
}
569574
}
570575

@@ -588,6 +593,7 @@ func (sw *MultiplexSwitch) dialItems(dialItems ...dial.Item) {
588593
}
589594

590595
sw.dialQueue.Push(dialItem)
596+
sw.notifyAddPeerToDial()
591597
}
592598
}
593599

@@ -698,6 +704,20 @@ func (sw *MultiplexSwitch) addPeer(p PeerConn) error {
698704
return nil
699705
}
700706

707+
func (sw *MultiplexSwitch) notifyAddPeerToDial() {
708+
select {
709+
case sw.dialNotify <- struct{}{}:
710+
default:
711+
}
712+
}
713+
714+
func (sw *MultiplexSwitch) waitForPeersToDial(ctx context.Context) {
715+
select {
716+
case <-ctx.Done():
717+
case <-sw.dialNotify:
718+
}
719+
}
720+
701721
// logTelemetry logs the switch telemetry data
702722
// to global metrics funnels
703723
func (sw *MultiplexSwitch) logTelemetry() {

0 commit comments

Comments
 (0)