From 075a54192c79dffffd7d8f5e46f10b495631f9e3 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 17 Nov 2022 18:03:04 +0300 Subject: [PATCH] network: don't try too many connections Consider mainnet, it has an AttemptConnPeers of 20, so may already have 3 peers and request 20 more, then have 4th connected and attemtp 20 more again, this leads to a huge number of connections easily. --- pkg/network/discovery.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/network/discovery.go b/pkg/network/discovery.go index 9a6b96b23..f33e98980 100644 --- a/pkg/network/discovery.go +++ b/pkg/network/discovery.go @@ -49,6 +49,7 @@ type DefaultDiscovery struct { goodAddrs map[string]capability.Capabilities unconnectedAddrs map[string]int attempted map[string]bool + outstanding int32 optimalFanOut int32 networkSize int32 requestCh chan int @@ -119,6 +120,8 @@ func (d *DefaultDiscovery) pushToPoolOrDrop(addr string) { // RequestRemote tries to establish a connection with n nodes. func (d *DefaultDiscovery) RequestRemote(requested int) { + outstanding := int(atomic.LoadInt32(&d.outstanding)) + requested -= outstanding for ; requested > 0; requested-- { var nextAddr string d.lock.Lock() @@ -146,6 +149,7 @@ func (d *DefaultDiscovery) RequestRemote(requested int) { } d.attempted[nextAddr] = true d.lock.Unlock() + atomic.AddInt32(&d.outstanding, 1) go d.tryAddress(nextAddr) } } @@ -291,6 +295,7 @@ func (d *DefaultDiscovery) updateNetSize() { func (d *DefaultDiscovery) tryAddress(addr string) { p, err := d.transport.Dial(addr, d.dialTimeout) + atomic.AddInt32(&d.outstanding, -1) d.lock.Lock() delete(d.attempted, addr) if err == nil {