Skip to content

Commit

Permalink
plugin/host: parse file without holding lock (#2270)
Browse files Browse the repository at this point in the history
* plugin/host: parse file without holding lock

Parse first and then swap the maps *while* holding the lock.

Signed-off-by: Miek Gieben <miek@miek.nl>

* add back in the parse function, but now purely for testing

Signed-off-by: Miek Gieben <miek@miek.nl>
  • Loading branch information
miekg authored and yongtang committed Nov 3, 2018
1 parent 921b02e commit c2331d7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
3 changes: 3 additions & 0 deletions plugin/hosts/hosts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package hosts

import (
"context"
"io"
"strings"
"testing"

Expand All @@ -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))
Expand Down
14 changes: 6 additions & 8 deletions plugin/hosts/hostsfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,17 @@ func (h *Hostsfile) readHosts() {
return
}

newMap := h.parse(file, h.inline)
log.Debugf("Parsed hosts file into %d entries", newMap.Len())

h.Lock()
defer h.Unlock()
h.parseReader(file)

h.hmap = newMap
// Update the data cache.
h.mtime = stat.ModTime()
h.size = stat.Size()

h.Unlock()
}

func (h *Hostsfile) initInline(inline []string) {
Expand All @@ -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()
Expand Down

0 comments on commit c2331d7

Please sign in to comment.