kaspad/infrastructure/network/connmanager/outgoing_connections.go
stasatdaglabs a795a9e619
Add a size limit to the address manager (#1652)
* Remove a random address from the address manager if it's full.

* Implement TestOverfillAddressManager.

* Add connectionFailedCount to addresses.

* Mark connection failures.

* Mark connection successes.

* Implement removing by most connection failures.

* Expand TestOverfillAddressManager.

* Add comments.

* Use a better method for finding the address with the greatest connectionFailedCount.

* Fix a comment.

* Compare addresses by IP in TestOverfillAddressManager.

* Add a comment for updateNotBanned.

Co-authored-by: Ori Newman <orinewman1@gmail.com>
2021-04-05 17:56:13 +03:00

53 lines
1.7 KiB
Go

package connmanager
import "github.com/kaspanet/kaspad/app/appmessage"
// checkOutgoingConnections goes over all activeOutgoing and makes sure they are still active.
// Then it opens connections so that we have targetOutgoing active connections
func (c *ConnectionManager) checkOutgoingConnections(connSet connectionSet) {
for address := range c.activeOutgoing {
connection, ok := connSet.get(address)
if ok { // connection is still connected
connSet.remove(connection)
continue
}
// if connection is dead - remove from list of active ones
delete(c.activeOutgoing, address)
}
connections := c.netAdapter.P2PConnections()
connectedAddresses := make([]*appmessage.NetAddress, len(connections))
for i, connection := range connections {
connectedAddresses[i] = connection.NetAddress()
}
liveConnections := len(c.activeOutgoing)
if c.targetOutgoing == liveConnections {
return
}
log.Debugf("Have got %d outgoing connections out of target %d, adding %d more",
liveConnections, c.targetOutgoing, c.targetOutgoing-liveConnections)
connectionsNeededCount := c.targetOutgoing - len(c.activeOutgoing)
netAddresses := c.addressManager.RandomAddresses(connectionsNeededCount, connectedAddresses)
for _, netAddress := range netAddresses {
addressString := netAddress.TCPAddress().String()
log.Debugf("Connecting to %s because we have %d outgoing connections and the target is "+
"%d", addressString, len(c.activeOutgoing), c.targetOutgoing)
err := c.initiateConnection(addressString)
if err != nil {
log.Infof("Couldn't connect to %s: %s", addressString, err)
c.addressManager.MarkConnectionFailure(netAddress)
continue
}
c.addressManager.MarkConnectionSuccess(netAddress)
c.activeOutgoing[addressString] = struct{}{}
}
}