-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtraefik.go
257 lines (218 loc) · 5.82 KB
/
traefik.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
package traefik
import (
"context"
"net"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/plugin/pkg/fall"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
var log = clog.NewWithPlugin("traefik")
//goland:noinspection GoNameStartsWithPackageName
type TraefikConfigEntry struct {
cname *string
a *[]net.IP
ttl uint32
}
//goland:noinspection GoNameStartsWithPackageName
type TraefikConfigEntryMap map[string]*TraefikConfigEntry
//goland:noinspection GoNameStartsWithPackageName
type TraefikConfig struct {
baseUrl *url.URL
cname *string
a *[]net.IP
ttl uint32
refreshInterval uint32
insecureSkipVerify bool
hostMatcher *regexp.Regexp
apiHostname string
apiHostnameIsIp bool
apiIp *net.IP
resolveApiHost bool
}
type Traefik struct {
Next plugin.Handler
Config *TraefikConfig
TraefikClient *TraefikClient
mappings TraefikConfigEntryMap
ready bool
mutex sync.RWMutex
Fall fall.F
}
func (t *Traefik) Name() string { return "traefik" }
func (t *Traefik) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
if state.QClass() != dns.ClassINET || state.QType() != dns.TypeA {
return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
requestCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
qname := state.QName()
answers := []dns.RR{}
for _, q := range state.Req.Question {
find := strings.ToLower(q.Name[:len(q.Name)-1])
result := t.getEntry(find)
if result != nil {
if t.Config.cname != nil {
answers = cname(qname, t.Config.ttl, t.Config.cname)
} else if t.Config.a != nil {
answers = a(qname, t.Config.ttl, *t.Config.a)
}
}
}
m := new(dns.Msg)
if len(answers) == 0 {
if t.Fall.Through(qname) && t.Next != nil {
log.Debug("Falling through. 0 answers")
return plugin.NextOrFailure(t.Name(), t.Next, ctx, w, r)
}
log.Debug("Returning NXDOMAIN")
m.Rcode = dns.RcodeNameError
}
m.SetReply(r)
m.Authoritative = true
m.Answer = answers
//goland:noinspection ALL
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
func (t *Traefik) start() error {
log.Info("Starting!")
err := t.refresh(true)
if err != nil {
log.Warningf("Failed to load Traefik HTTP routers, will retry: %s", err)
}
uptimeTicker := time.NewTicker(time.Duration(t.Config.refreshInterval) * time.Second)
for {
select {
case <-uptimeTicker.C:
log.Debug("Refreshing sites")
err := t.refresh(false)
if err != nil {
log.Warningf("Error loading Traefik HTTP routers: %v", err)
}
}
}
}
func (t *Traefik) getEntry(host string) *TraefikConfigEntry {
t.mutex.RLock()
defer t.mutex.RUnlock()
if t.Config.resolveApiHost && !t.Config.apiHostnameIsIp && t.Config.apiHostname == host {
return &TraefikConfigEntry{
a: t.Config.a,
ttl: t.Config.ttl,
}
}
value, foundIt := t.mappings[host]
if !foundIt {
return nil
}
return value
}
func (t *Traefik) refresh(first bool) error {
if first {
log.Infof("Checking for Traefik HTTP routers...")
}
routers, err := t.TraefikClient.GetHttpRouters()
if err != nil {
log.Errorf("Error retrieving Traefik HTTP routers: %s", err)
return err
}
t.mutex.Lock()
defer t.mutex.Unlock()
adds, deletes := 0, 0
fromTraefik := map[string]struct{}{}
for _, s := range *routers {
//goland:noinspection ALL
strs := t.Config.hostMatcher.FindAllStringSubmatch(s.Rule, -1)
for _, s := range strs {
if len(s) == 3 {
host := strings.ToLower(s[2])
fromTraefik[host] = struct{}{}
if t.Config.cname != nil {
_, exists := t.mappings[host]
if !exists {
log.Infof("+ CNAME %s -> %s", host, *t.Config.cname)
t.mappings[host] = &TraefikConfigEntry{
cname: t.Config.cname,
ttl: t.Config.ttl,
}
adds += 1
}
} else if t.Config.a != nil {
_, exists := t.mappings[host]
if !exists {
log.Infof("+ %s -> %s", host, ConvertIPsToString(*t.Config.a))
t.mappings[host] = &TraefikConfigEntry{
a: t.Config.a,
ttl: t.Config.ttl,
}
adds += 1
}
}
}
}
}
toDelete := map[string]struct{}{}
for cachedHost := range t.mappings {
_, stillExists := fromTraefik[cachedHost]
if !stillExists {
if t.Config.cname != nil {
log.Infof("- CNAME %s -> %s", cachedHost, *t.Config.cname)
} else if t.Config.a != nil {
log.Infof("- A %s -> %s", cachedHost, ConvertIPsToString(*t.Config.a))
}
toDelete[cachedHost] = struct{}{}
deletes += 1
}
}
for del := range toDelete {
delete(t.mappings, del)
}
if adds > 0 && deletes > 0 {
log.Infof("Added %d, deleted %d entries", adds, deletes)
} else if adds > 0 {
log.Infof("Added %d entries", adds)
} else if deletes > 0 {
log.Infof("Deleted %d entries", deletes)
} else {
if first {
log.Warning("Failed to load Traefik HTTP routes... Will try again")
} else {
log.Debug("No changes detected")
}
}
t.ready = true
return nil
}
func a(zone string, ttl uint32, ips []net.IP) []dns.RR {
answers := make([]dns.RR, len(ips))
for i, ip := range ips {
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: ttl}
r.A = ip
answers[i] = r
}
return answers
}
func cname(zone string, ttl uint32, target *string) []dns.RR {
answers := make([]dns.RR, 1)
r := new(dns.CNAME)
r.Hdr = dns.RR_Header{Name: zone, Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: ttl}
r.Target = *target
answers[0] = r
return answers
}
func ConvertIPsToString(ips []net.IP) string {
var ipStrings []string
for _, ip := range ips {
ipStrings = append(ipStrings, ip.String())
}
return strings.Join(ipStrings, ",")
}