-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdnsmon.go
123 lines (107 loc) · 2.51 KB
/
dnsmon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Package dnsmon contains the DNS monitor.
package dnsmon
import (
"fmt"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
)
// DNSMon is a DNS monitor.
type DNSMon struct {
config *Config
watcher *fsnotify.Watcher
updates chan struct{}
done chan struct{}
closed chan struct{}
}
// isResolvConfEvent checks if event is a resolv.conf file event.
func (d *DNSMon) isResolvConfEvent(event fsnotify.Event) bool {
switch event.Name {
case d.config.ETCResolvConf:
return true
case d.config.StubResolvConf:
return true
case d.config.SystemdResolvConf:
return true
}
return false
}
// sendUpdate sends an update over the updates channel.
func (d *DNSMon) sendUpdate() {
// send an update or abort if we are shutting down
select {
case d.updates <- struct{}{}:
case <-d.done:
}
}
// start starts the DNSMon.
func (d *DNSMon) start() {
defer close(d.closed)
defer close(d.updates)
defer func() {
if err := d.watcher.Close(); err != nil {
log.WithError(err).Error("DNSMon file watcher close error")
}
}()
// send initial update
d.sendUpdate()
// watch the files
for {
select {
case event, ok := <-d.watcher.Events:
if !ok {
log.Error("DNSMon got unexpected close of events channel")
return
}
if d.isResolvConfEvent(event) {
log.WithFields(log.Fields{
"name": event.Name,
"op": event.Op,
}).Debug("DNSMon handling resolv.conf event")
d.sendUpdate()
}
case err, ok := <-d.watcher.Errors:
if !ok {
log.Error("DNSMon got unexpected close of errors channel")
return
}
log.WithError(err).Error("DNSMon watcher error event")
case <-d.done:
return
}
}
}
// Start starts the DNSMon.
func (d *DNSMon) Start() error {
// create watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("could not create file watcher: %w", err)
}
// add resolv.conf folders to watcher
for _, dir := range d.config.resolvConfDirs() {
if err := watcher.Add(dir); err != nil {
log.WithError(err).WithField("dir", dir).Debug("DNSMon add resolv.conf dir error")
}
}
d.watcher = watcher
go d.start()
return nil
}
// Stop stops the DNSMon.
func (d *DNSMon) Stop() {
close(d.done)
<-d.closed
}
// Updates returns the channel for dns config updates.
func (d *DNSMon) Updates() chan struct{} {
return d.updates
}
// NewDNSMon returns a new DNSMon.
func NewDNSMon(config *Config) *DNSMon {
return &DNSMon{
config: config,
updates: make(chan struct{}),
done: make(chan struct{}),
closed: make(chan struct{}),
}
}