From c2331d7dda8280053f96ce6ff1b50aace306992a Mon Sep 17 00:00:00 2001 From: Miek Gieben Date: Sat, 3 Nov 2018 20:00:07 +0000 Subject: [PATCH] plugin/host: parse file without holding lock (#2270) * plugin/host: parse file without holding lock Parse first and then swap the maps *while* holding the lock. Signed-off-by: Miek Gieben * add back in the parse function, but now purely for testing Signed-off-by: Miek Gieben --- plugin/hosts/hosts_test.go | 3 +++ plugin/hosts/hostsfile.go | 16 +++++++--------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/plugin/hosts/hosts_test.go b/plugin/hosts/hosts_test.go index db3876132..1b74ef9ee 100644 --- a/plugin/hosts/hosts_test.go +++ b/plugin/hosts/hosts_test.go @@ -2,6 +2,7 @@ package hosts import ( "context" + "io" "strings" "testing" @@ -11,6 +12,8 @@ import ( "github.com/miekg/dns" ) +func (h *Hostsfile) parseReader(r io.Reader) { h.hmap = h.parse(r, h.inline) } + func TestLookupA(t *testing.T) { h := Hosts{Next: test.ErrorHandler(), Hostsfile: &Hostsfile{Origins: []string{"."}}} h.parseReader(strings.NewReader(hostsExample)) diff --git a/plugin/hosts/hostsfile.go b/plugin/hosts/hostsfile.go index af5e054fd..8b2ffa0a6 100644 --- a/plugin/hosts/hostsfile.go +++ b/plugin/hosts/hostsfile.go @@ -106,13 +106,17 @@ func (h *Hostsfile) readHosts() { return } - h.Lock() - defer h.Unlock() - h.parseReader(file) + newMap := h.parse(file, h.inline) + log.Debugf("Parsed hosts file into %d entries", newMap.Len()) + h.Lock() + + h.hmap = newMap // Update the data cache. h.mtime = stat.ModTime() h.size = stat.Size() + + h.Unlock() } func (h *Hostsfile) initInline(inline []string) { @@ -125,12 +129,6 @@ func (h *Hostsfile) initInline(inline []string) { *h.hmap = *h.inline } -func (h *Hostsfile) parseReader(r io.Reader) { - h.hmap = h.parse(r, h.inline) - - log.Debugf("Parsed hosts file into %d entries", h.hmap.Len()) -} - // Parse reads the hostsfile and populates the byName and byAddr maps. func (h *Hostsfile) parse(r io.Reader, override *hostsMap) *hostsMap { hmap := newHostsMap()