-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
467 lines (409 loc) · 10.6 KB
/
config.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright (c) 2018-2019, AT&T Intellectual Property. All rights reserved.
// SPDX-License-Identifier: GPL-2.0-only
package forwarding
import (
"fmt"
"io"
"os"
"reflect"
"strings"
"sync/atomic"
"text/template"
"github.com/danos/vyatta-service-dns/internal/fswatcher"
"github.com/danos/vyatta-service-dns/internal/log"
"github.com/danos/vyatta-service-dns/internal/process"
)
const cfgFile = `### Autogenerated by vci-service-dns
### Note: Manual changes to this file will be lost during
### the next commit.
log-facility={{.ForwardingStateFile}}
no-poll
edns-packet-max=4096
{{range .Conf.ListenInterfaces -}}
interface={{.}}
{{end -}}
cache-size={{.Conf.CacheSize}}
{{range .Conf.Nameservers -}}
server={{.}} # statically configured
{{end -}}
{{range .Conf.DomainOverrides -}}
server=/{{.Domain}}/{{.Server}} # domain-override
{{end -}}
{{if .UseForwardingConf -}}
resolv-file={{.ForwardingConf}}
{{end -}}
no-hosts
addn-hosts={{.HostsFile}}
conf-dir={{.ConfDir}},{{.ConfDirExt}}
`
const envFile = `### Autogenerated by vyatta-service-dns
DNSMASQ_PID_FILE={{.PidFile}}
DNSMASQ_CONF={{.ConfFile}}
`
var cfgFileTemplate *template.Template
var envFileTemplate *template.Template
func init() {
t := template.New("ForwardingConf")
t.Funcs(template.FuncMap{})
cfgFileTemplate = template.Must(t.Parse(cfgFile))
t = template.New("ForwardingEnv")
t.Funcs(template.FuncMap{})
envFileTemplate = template.Must(t.Parse(envFile))
}
type ConfigData struct {
DHCPInterfaces []string `rfc7951:"dhcp,omitempty"`
CacheSize uint32 `rfc7951:"cache-size"`
ListenInterfaces []string `rfc7951:"listen-on,omitempty"`
Nameservers []string `rfc7951:"name-server,omitempty"`
System bool `rfc7951:"system,emptyleaf"`
DomainOverrides []struct {
Domain string `rfc7951:"tagnode"`
Server string `rfc7951:"server"`
} `rfc7951:"domain,omitempty"`
}
func (c *ConfigData) nsDerivedFromConf() bool {
return len(c.DHCPInterfaces) > 0 || len(c.Nameservers) > 0 || c.System
}
type ConfigOption func(*Config)
func ConfigFile(file string) ConfigOption {
return func(c *Config) {
c.conffile = file
}
}
func ConfigDir(dir string, extensions ...string) ConfigOption {
return func(c *Config) {
c.confdir = dir
c.confdirext = extensions
}
}
func PIDFile(file string) ConfigOption {
return func(c *Config) {
c.pidfile = file
}
}
func ENVFile(file string) ConfigOption {
return func(c *Config) {
c.envfile = file
}
}
func Unit(unit string) ConfigOption {
return func(c *Config) {
c.unit = unit
}
}
func StateFile(file string) ConfigOption {
return func(c *Config) {
c.statefile = file
}
}
func DHCPConfigFileFmt(pattern string) ConfigOption {
return func(c *Config) {
c.dhcpconffilepattern = pattern
}
}
func DHCPWatchFmt(pattern string) ConfigOption {
return func(c *Config) {
c.dhcpwatchpattern = pattern
}
}
func SystemConfigFile(file string) ConfigOption {
return func(c *Config) {
c.systemconffile = file
}
}
func ResolvFile(file string) ConfigOption {
return func(c *Config) {
c.resolvfile = file
}
}
func HostsFile(file string) ConfigOption {
return func(c *Config) {
c.hostsfile = file
}
}
func InstanceName(name string) ConfigOption {
return func(c *Config) {
c.instance = name
}
}
func VRFHelpers(sub process.VRFSubscriber, chk process.VRFChecker) ConfigOption {
return func(c *Config) {
c.vrfSub = sub
c.vrfChk = chk
origPcons := c.pCons
c.pCons = func(name string) process.Process {
if c.vrfSub != nil {
return process.NewVrfDependantProcess(
c.instance,
c.vrfSub,
c.vrfChk,
origPcons(name))
}
return origPcons(name)
}
}
}
type Config struct {
currentConfig atomic.Value
dhcpConfig *dhcpConfig
systemConfig *systemConfig
resolvWatcher *reloadWatcher
hostsWatcher *reloadWatcher
forwardingProcess process.Process
// options
instance string
instanceDir string
conffile string
confdir string
confdirext []string
pidfile string
envfile string
unit string
statefile string
dhcpwatchpattern string
dhcpconffilepattern string
systemconffile string
resolvfile string
hostsfile string
pCons func(string) process.Process
vrfSub process.VRFSubscriber
vrfChk process.VRFChecker
}
func NewInstanceConfig(name string, opts ...ConfigOption) *Config {
// Setup a default instance Config object
instanceDirFmt := "/run/dns/vrf/%s"
instanceDir := fmt.Sprintf(instanceDirFmt, name)
iopts := []ConfigOption{
InstanceName(name),
Unit(fmt.Sprintf("dnsmasq@%s.service", name)),
ENVFile(fmt.Sprintf("%s/dnsmasq.env", instanceDir)),
ConfigFile(fmt.Sprintf("%s/dnsmasq.conf", instanceDir)),
ConfigDir(fmt.Sprintf("%s/dnsmasq.d", instanceDir), "*.conf"),
DHCPConfigFileFmt(fmt.Sprintf("%s/dnsmasq.d/dhcpinterface-%%s.conf", instanceDir)),
SystemConfigFile(fmt.Sprintf("%s/dnsmasq.d/system.conf", instanceDir)),
PIDFile(fmt.Sprintf("%s/dnsmasq.pid", instanceDir)),
StateFile(fmt.Sprintf("%s/dnsmasq.log", instanceDir)),
ResolvFile(fmt.Sprintf("%s/resolv.conf", instanceDir)),
HostsFile(fmt.Sprintf("%s/hosts", instanceDir)),
}
//Allow user options to override default instance options by appending them to the list
iopts = append(iopts, opts...)
conf := NewConfig(iopts...)
conf.instanceDir = instanceDir
return conf
}
func NewConfig(opts ...ConfigOption) *Config {
// Default config options
const (
conffile = "/etc/dnsmasq.conf"
confdir = "/etc/dnsmasq.d"
confdirext = "*.conf"
unit = "dnsmasq.service"
statefile = "/var/log/dnsmasq.log"
pidfile = "/var/run/dnsmasq/dnsmasq.pid"
resolvfile = "/etc/resolv.conf"
hostsfile = "/etc/hosts"
systemNameserverConf = "/etc/dnsmasq.d/system.conf"
dhcpWatchPattern = "/var/lib/dhcp/dhclient_%s_lease"
dhcpConffileTemplate = "/etc/dnsmasq.d/dhcpinterface-%s.conf"
)
conf := &Config{
instance: "default",
conffile: conffile,
confdir: confdir,
confdirext: []string{confdirext},
statefile: statefile,
pidfile: pidfile,
unit: unit,
dhcpwatchpattern: dhcpWatchPattern,
dhcpconffilepattern: dhcpConffileTemplate,
systemconffile: systemNameserverConf,
resolvfile: resolvfile,
hostsfile: hostsfile,
pCons: process.NewSystemdProcess,
}
// run options to change the defaults
for _, opt := range opts {
opt(conf)
}
conf.forwardingProcess = conf.pCons(conf.unit)
conf.dhcpConfig = &dhcpConfig{
proc: conf.forwardingProcess,
watchFmt: conf.dhcpwatchpattern,
confFileFmt: conf.dhcpconffilepattern,
}
conf.systemConfig = &systemConfig{
proc: conf.forwardingProcess,
watchFile: conf.resolvfile,
confFile: conf.systemconffile,
}
conf.currentConfig.Store(&ConfigData{})
return conf
}
func (c *Config) Get() *ConfigData {
return c.currentConfig.Load().(*ConfigData)
}
func (c *Config) Set(conf *ConfigData) error {
const logPrefix = "forwarding-config-set:"
old := c.Get()
if reflect.DeepEqual(old, conf) {
return nil
}
if conf != nil {
err := c.updateConfiguration(conf)
if err != nil {
return err
}
} else {
c.deleteConfiguration()
}
c.currentConfig.Store(conf)
return nil
}
func (c *Config) updateConfiguration(conf *ConfigData) error {
err := c.ensureEnvironment()
if err != nil {
return err
}
f, err := os.OpenFile(c.conffile,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
err = c.writeForwardingConfig(f, conf)
if err != nil {
return err
}
if c.envfile != "" {
envf, err := os.OpenFile(c.envfile,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer envf.Close()
err = writeEnvironmentFile(envf, c.pidfile, c.conffile)
if err != nil {
return err
}
}
if conf.nsDerivedFromConf() {
c.resolvWatcher.stop()
c.resolvWatcher = nil
} else if c.resolvWatcher == nil {
c.resolvWatcher = startReloadWatcher(
c.resolvfile, c.forwardingProcess)
}
if c.hostsWatcher == nil {
c.hostsWatcher = startReloadWatcher(
c.hostsfile, c.forwardingProcess)
}
c.dhcpConfig.Set(conf.DHCPInterfaces)
c.systemConfig.Set(conf.System)
err = c.forwardingProcess.Restart()
if err != nil {
return err
}
return nil
}
func (c *Config) ensureEnvironment() error {
dirs := []string{c.instanceDir, c.confdir}
for _, dir := range dirs {
if dir == "" {
continue
}
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
}
return nil
}
func (c *Config) deleteConfiguration() {
const logPrefix = "forwarding-config-set delete:"
c.resolvWatcher.stop()
c.hostsWatcher.stop()
c.dhcpConfig.Set(nil)
c.systemConfig.Set(false)
err := c.forwardingProcess.Stop()
if err != nil {
log.Dlog.Println(logPrefix, err)
}
files := []string{c.conffile, c.envfile, c.statefile}
for _, file := range files {
err = os.Remove(file)
if err != nil {
log.Dlog.Println(logPrefix, err)
}
}
if c.instanceDir != "" {
os.Remove(c.instanceDir)
}
if c.confdir != "" {
err := os.RemoveAll(c.confdir)
if err != nil {
log.Dlog.Println(logPrefix, err)
}
}
}
func (c *Config) writeForwardingConfig(w io.Writer, conf *ConfigData) error {
templateInput := struct {
ConfDir string
ConfDirExt string
ForwardingConf string
ForwardingStateFile string
Conf *ConfigData
UseForwardingConf bool
HostsFile string
}{
ConfDir: c.confdir,
ConfDirExt: strings.Join(c.confdirext, ","),
ForwardingConf: c.conffile,
ForwardingStateFile: c.statefile,
Conf: conf,
UseForwardingConf: conf.nsDerivedFromConf(),
HostsFile: c.hostsfile,
}
return cfgFileTemplate.Execute(w, &templateInput)
}
func writeEnvironmentFile(w io.Writer, pidfile, conffile string) error {
tmplInput := struct {
PidFile, ConfFile string
}{
PidFile: pidfile,
ConfFile: conffile,
}
return envFileTemplate.Execute(w, &tmplInput)
}
type reloadWatcher struct {
proc process.Process
file string
watcher *fswatcher.Watcher
}
func startReloadWatcher(
file string,
proc process.Process,
) *reloadWatcher {
out := &reloadWatcher{
proc: proc,
file: file,
}
out.watcher = fswatcher.Start(
fswatcher.LogPrefix("resolv watcher:"),
fswatcher.Logger(log.Dlog),
fswatcher.Handler(file, out),
)
return out
}
func (w *reloadWatcher) CloseWrite(name string) error {
if name != w.file {
return nil
}
return w.proc.Reload()
}
func (w *reloadWatcher) stop() {
if w == nil {
return
}
w.watcher.Stop()
}