From 4d3f1b83a62c8c7bd4b828336efb4ca7ae536c9e Mon Sep 17 00:00:00 2001 From: Eugene Bujak Date: Sat, 29 Dec 2018 19:13:00 +0300 Subject: [PATCH] Fix race conditions found by -race --- dhcpd/dhcpd.go | 9 ++++++++- dnsforward/stats.go | 8 ++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/dhcpd/dhcpd.go b/dhcpd/dhcpd.go index 2b1198e4..deeaac02 100644 --- a/dhcpd/dhcpd.go +++ b/dhcpd/dhcpd.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "net" + "sync" "time" "github.com/hmage/golibs/log" @@ -47,6 +48,7 @@ type Server struct { IPpool map[[4]byte]net.HardwareAddr ServerConfig + sync.RWMutex } // Start will listen on port 67 and serve DHCP requests. @@ -179,7 +181,9 @@ func (s *Server) reserveLease(p dhcp4.Packet) (*Lease, error) { log.Tracef("Assigning to %s IP address %s", hwaddr, ip.String()) hostname := p.ParseOptions()[dhcp4.OptionHostName] lease := &Lease{HWAddr: hwaddr, IP: ip, Hostname: string(hostname)} + s.Lock() s.leases = append(s.leases, lease) + s.Unlock() return lease, nil } @@ -387,5 +391,8 @@ func (s *Server) ServeDHCP(p dhcp4.Packet, msgType dhcp4.MessageType, options dh } func (s *Server) Leases() []*Lease { - return s.leases + s.RLock() + result := s.leases + s.RUnlock() + return result } diff --git a/dnsforward/stats.go b/dnsforward/stats.go index 5791e1dc..9d11504b 100644 --- a/dnsforward/stats.go +++ b/dnsforward/stats.go @@ -142,6 +142,8 @@ func statsRotator() { type counter struct { name string // used as key in periodic stats value int64 + + sync.Mutex } func newDNSCounter(name string) *counter { @@ -156,7 +158,9 @@ func (c *counter) IncWithTime(when time.Time) { statistics.PerMinute.Inc(c.name, when) statistics.PerHour.Inc(c.name, when) statistics.PerDay.Inc(c.name, when) + c.Lock() c.value++ + c.Unlock() } func (c *counter) Inc() { @@ -167,6 +171,8 @@ type histogram struct { name string // used as key in periodic stats count int64 total float64 + + sync.Mutex } func newDNSHistogram(name string) *histogram { @@ -180,8 +186,10 @@ func (h *histogram) ObserveWithTime(value float64, when time.Time) { statistics.PerMinute.Observe(h.name, when, value) statistics.PerHour.Observe(h.name, when, value) statistics.PerDay.Observe(h.name, when, value) + h.Lock() h.count++ h.total += value + h.Unlock() } func (h *histogram) Observe(value float64) {