network: fix data race in server peers map access

This commit is contained in:
Roman Khimov 2019-11-06 12:38:47 +03:00
parent 19918f471d
commit d5a7ad2c47

View file

@ -163,15 +163,19 @@ func (s *Server) run() {
"addr": p.RemoteAddr(), "addr": p.RemoteAddr(),
}).Error(err) }).Error(err)
} }
s.lock.Lock()
s.peers[p] = true s.peers[p] = true
s.lock.Unlock()
log.WithFields(log.Fields{ log.WithFields(log.Fields{
"addr": p.RemoteAddr(), "addr": p.RemoteAddr(),
}).Info("new peer connected") }).Info("new peer connected")
updatePeersConnectedMetric(s.PeerCount()) updatePeersConnectedMetric(s.PeerCount())
case drop := <-s.unregister: case drop := <-s.unregister:
s.lock.Lock()
if s.peers[drop.peer] { if s.peers[drop.peer] {
delete(s.peers, drop.peer) delete(s.peers, drop.peer)
s.lock.Unlock()
log.WithFields(log.Fields{ log.WithFields(log.Fields{
"addr": drop.peer.RemoteAddr(), "addr": drop.peer.RemoteAddr(),
"reason": drop.reason, "reason": drop.reason,
@ -181,9 +185,12 @@ func (s *Server) run() {
s.discovery.UnregisterConnectedAddr(addr) s.discovery.UnregisterConnectedAddr(addr)
s.discovery.BackFill(addr) s.discovery.BackFill(addr)
updatePeersConnectedMetric(s.PeerCount()) updatePeersConnectedMetric(s.PeerCount())
} } else {
// else the peer is already gone, which can happen // else the peer is already gone, which can happen
// because we have two goroutines sending signals here // because we have two goroutines sending signals here
s.lock.Unlock()
}
} }
} }
} }