aboutsummaryrefslogtreecommitdiff
path: root/plugin/file/reload.go
blob: e73c5b87df9f4dc0793a95bf3e17c19f0f9ca363 (plain) (blame)
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
package file

import (
	"os"
	"time"
)

// TickTime is clock resolution. By default ticks every second. Handler checks if reloadInterval has been reached on every tick.
var TickTime = 1 * time.Second

// Reload reloads a zone when it is changed on disk. If z.NoReload is true, no reloading will be done.
func (z *Zone) Reload() error {
	if z.ReloadInterval == 0 {
		return nil
	}
	tick := time.NewTicker(TickTime)

	go func() {

		for {
			select {

			case <-tick.C:
				if z.LastReloaded.Add(z.ReloadInterval).After(time.Now()) {
					//reload interval not reached yet
					continue
				}
				//saving timestamp of last attempted reload
				z.LastReloaded = time.Now()

				zFile := z.File()
				reader, err := os.Open(zFile)
				if err != nil {
					log.Errorf("Failed to open zone %q in %q: %v", z.origin, zFile, err)
					continue
				}

				serial := z.SOASerialIfDefined()
				zone, err := Parse(reader, z.origin, zFile, serial)
				if err != nil {
					if _, ok := err.(*serialErr); !ok {
						log.Errorf("Parsing zone %q: %v", z.origin, err)
					}
					continue
				}

				// copy elements we need
				z.reloadMu.Lock()
				z.Apex = zone.Apex
				z.Tree = zone.Tree
				z.reloadMu.Unlock()

				log.Infof("Successfully reloaded zone %q in %q with serial %d", z.origin, zFile, z.Apex.SOA.Serial)
				z.Notify()

			case <-z.reloadShutdown:
				tick.Stop()
				return
			}
		}
	}()
	return nil
}

// SOASerialIfDefined returns the SOA's serial if the zone has a SOA record in the Apex, or
// -1 otherwise.
func (z *Zone) SOASerialIfDefined() int64 {
	z.reloadMu.Lock()
	defer z.reloadMu.Unlock()
	if z.Apex.SOA != nil {
		return int64(z.Apex.SOA.Serial)
	}
	return -1
}