aboutsummaryrefslogtreecommitdiff
path: root/plugin/secondary/setup.go
blob: 97d8cd9f5dc1804be183f928bb0354c3470e29ea (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
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
package secondary

import (
	"time"

	"github.com/coredns/caddy"
	"github.com/coredns/coredns/core/dnsserver"
	"github.com/coredns/coredns/plugin"
	"github.com/coredns/coredns/plugin/file"
	clog "github.com/coredns/coredns/plugin/pkg/log"
	"github.com/coredns/coredns/plugin/pkg/parse"
	"github.com/coredns/coredns/plugin/pkg/upstream"
)

var log = clog.NewWithPlugin("secondary")

func init() { plugin.Register("secondary", setup) }

func setup(c *caddy.Controller) error {
	zones, err := secondaryParse(c)
	if err != nil {
		return plugin.Error("secondary", err)
	}

	// Add startup functions to retrieve the zone and keep it up to date.
	for i := range zones.Names {
		n := zones.Names[i]
		z := zones.Z[n]
		if len(z.TransferFrom) > 0 {
			c.OnStartup(func() error {
				z.StartupOnce.Do(func() {
					go func() {
						dur := time.Millisecond * 250
						step := time.Duration(2)
						max := time.Second * 10
						for {
							err := z.TransferIn()
							if err == nil {
								break
							}
							log.Warningf("All '%s' masters failed to transfer, retrying in %s: %s", n, dur.String(), err)
							time.Sleep(dur)
							dur = step * dur
							if dur > max {
								dur = max
							}
						}
						z.Update()
					}()
				})
				return nil
			})
		}
	}

	dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
		return Secondary{file.File{Next: next, Zones: zones}}
	})

	return nil
}

func secondaryParse(c *caddy.Controller) (file.Zones, error) {
	z := make(map[string]*file.Zone)
	names := []string{}
	for c.Next() {

		if c.Val() == "secondary" {
			// secondary [origin]
			origins := plugin.OriginsFromArgsOrServerBlock(c.RemainingArgs(), c.ServerBlockKeys)
			for i := range origins {
				z[origins[i]] = file.NewZone(origins[i], "stdin")
				names = append(names, origins[i])
			}

			for c.NextBlock() {

				f := []string{}

				switch c.Val() {
				case "transfer":
					var err error
					f, err = parse.TransferIn(c)
					if err != nil {
						return file.Zones{}, err
					}
				default:
					return file.Zones{}, c.Errf("unknown property '%s'", c.Val())
				}

				for _, origin := range origins {
					if f != nil {
						z[origin].TransferFrom = append(z[origin].TransferFrom, f...)
					}
					z[origin].Upstream = upstream.New()
				}
			}
		}
	}
	return file.Zones{Z: z, Names: names}, nil
}