refactor getPeers for locked scope

This commit is contained in:
vyzo 2018-05-09 11:47:16 +03:00
parent f36100a1f9
commit 7f690dcc68
1 changed files with 30 additions and 20 deletions

View File

@ -85,30 +85,13 @@ func (as *AmbientAutoNAT) background() {
}
func (as *AmbientAutoNAT) autodetect() {
if len(as.peers) == 0 {
peers := as.getPeers()
if len(peers) == 0 {
log.Debugf("skipping NAT auto detection; no autonat peers")
return
}
as.mx.Lock()
peers := make([]peer.ID, 0, len(as.peers))
for p := range as.peers {
if len(as.host.Network().ConnsToPeer(p)) > 0 {
peers = append(peers, p)
}
}
if len(peers) == 0 {
// we don't have any open connections, try any autonat peer that we know about
for p := range as.peers {
peers = append(peers, p)
}
}
as.mx.Unlock()
shufflePeers(peers)
for _, p := range peers {
cli := NewAutoNATClient(as.host, p)
ctx, cancel := context.WithTimeout(as.ctx, AutoNATRequestTimeout)
@ -141,6 +124,33 @@ func (as *AmbientAutoNAT) autodetect() {
as.mx.Unlock()
}
func (as *AmbientAutoNAT) getPeers() []peer.ID {
as.mx.Lock()
defer as.mx.Unlock()
if len(as.peers) == 0 {
return nil
}
peers := make([]peer.ID, 0, len(as.peers))
for p := range as.peers {
if len(as.host.Network().ConnsToPeer(p)) > 0 {
peers = append(peers, p)
}
}
if len(peers) == 0 {
// we don't have any open connections, try any autonat peer that we know about
for p := range as.peers {
peers = append(peers, p)
}
}
shufflePeers(peers)
return peers
}
func shufflePeers(peers []peer.ID) {
for i := range peers {
j := rand.Intn(i + 1)