forked from rancher/external-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
292 lines (266 loc) · 7.48 KB
/
main.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
package main
import (
"flag"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/rancher/external-dns/metadata"
"github.com/rancher/external-dns/providers"
"os"
"strings"
"sync"
"time"
)
const (
//FIXME - change metadata url to rancher-metadata
metadataUrl = "http://localhost:90"
poll = 1000
)
type Op struct {
Name string
}
var (
Add = Op{Name: "Add"}
Remove = Op{Name: "Remove"}
Update = Op{Name: "Update"}
)
var (
providerName = flag.String("provider", "", "External provider name")
debug = flag.Bool("debug", false, "Debug")
logFile = flag.String("log", "", "Log file")
stack metadata.Stack
provider providers.Provider
m metadata.MetadataHandler
)
func setEnv() {
flag.Parse()
provider = providers.GetProvider(*providerName)
if *debug {
log.SetLevel(log.DebugLevel)
}
if *logFile != "" {
if output, err := os.OpenFile(*logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil {
log.Fatalf("Failed to log to file %s: %v", *logFile, err)
} else {
log.SetOutput(output)
formatter := &log.TextFormatter{
FullTimestamp: true,
}
log.SetFormatter(formatter)
}
}
m = metadata.NewHandler(metadataUrl)
selfStack, err := m.GetSelfStack()
if err != nil {
log.Errorf("Error reading stack info: %v", err)
}
stack = selfStack
}
func main() {
log.Infof("Starting Rancher External DNS service")
setEnv()
log.Infof("Powered by %s", provider.GetName())
version := "init"
for {
newVersion, err := m.GetVersion()
if err != nil {
log.Errorf("Error reading version: %v", err)
} else if version == newVersion {
log.Debug("No changes in version: %s", newVersion)
} else {
log.Debug("Version has been changed. Old version: %s. New version: %s.", version, newVersion)
err := updateDnsRecords(m)
if err != nil {
log.Errorf("Failed to update DNS records: %v", err)
}
version = newVersion
}
time.Sleep(time.Duration(poll) * time.Millisecond)
}
}
func updateDnsRecords(m metadata.MetadataHandler) error {
metadataRecs, err := getMetadataDnsRecords(m)
if err != nil {
log.Errorf("Error reading external dns entries: %v", err)
}
log.Debugf("DNS records from metadata: %v", metadataRecs)
providerRecs, err := getProviderDnsRecords()
if err != nil {
log.Errorf("Provider error reading dns entries: %v", err)
}
log.Debugf("DNS records from provider: %v", providerRecs)
err = addMissingRecords(metadataRecs, providerRecs)
if err != nil {
log.Errorf("Failed to add missing records: %v", err)
}
err = removeExtraRecords(metadataRecs, providerRecs)
if err != nil {
log.Errorf("Failed to remove extra records: %v", err)
}
err = updateExistingRecords(metadataRecs, providerRecs)
if err != nil {
log.Errorf("Failed to update existing records records: %v", err)
}
return nil
}
func addMissingRecords(metadataRecs map[string]providers.DnsRecord, providerRecs map[string]providers.DnsRecord) error {
var toAdd []providers.DnsRecord
for key, _ := range metadataRecs {
if _, ok := providerRecs[key]; !ok {
toAdd = append(toAdd, metadataRecs[key])
}
}
if len(toAdd) == 0 {
log.Debug("No DNS records to add")
return nil
} else {
log.Infof("DNS records to add: %v", toAdd)
}
return updateRecords(toAdd, &Add)
}
func updateRecords(toChange []providers.DnsRecord, op *Op) error {
values := make(chan providers.DnsRecord)
var wg sync.WaitGroup
wg.Add(len(toChange))
for _, value := range toChange {
go func(value providers.DnsRecord) {
defer wg.Done()
values <- value
}(value)
}
go func() error {
for value := range values {
switch *op {
case Add:
log.Infof("Adding dns record: %v", value)
err := provider.AddRecord(value)
if err != nil {
return fmt.Errorf("Failed to add DNS record %v: %v", value, err)
}
case Remove:
log.Infof("Removing dns record: %v", value)
err := provider.RemoveRecord(value)
if err != nil {
return fmt.Errorf("Failed to remove DNS record %v: %v", value, err)
}
case Update:
log.Infof("Updating dns record: %v", value)
err := provider.UpdateRecord(value)
if err != nil {
return fmt.Errorf("Failed to update DNS record %v: %v", value, err)
}
}
}
return nil
}()
wg.Wait()
return nil
}
func updateExistingRecords(metadataRecs map[string]providers.DnsRecord, providerRecs map[string]providers.DnsRecord) error {
var toUpdate []providers.DnsRecord
for key, _ := range metadataRecs {
if _, ok := providerRecs[key]; ok {
metadataR := make(map[string]struct{}, len(metadataRecs[key].Records))
for _, s := range metadataRecs[key].Records {
metadataR[s] = struct{}{}
}
providerR := make(map[string]struct{}, len(providerRecs[key].Records))
for _, s := range providerRecs[key].Records {
providerR[s] = struct{}{}
}
var update bool
if len(metadataR) != len(providerR) {
update = true
} else {
for key, _ := range metadataR {
if _, ok := providerR[key]; !ok {
update = true
}
}
for key, _ := range providerR {
if _, ok := metadataR[key]; !ok {
update = true
}
}
}
if update {
toUpdate = append(toUpdate, metadataRecs[key])
}
}
}
if len(toUpdate) == 0 {
log.Debug("No DNS records to update")
return nil
} else {
log.Infof("DNS records to update: %v", toUpdate)
}
return updateRecords(toUpdate, &Update)
}
func removeExtraRecords(metadataRecs map[string]providers.DnsRecord, providerRecs map[string]providers.DnsRecord) error {
var toRemove []providers.DnsRecord
for key, _ := range providerRecs {
if _, ok := metadataRecs[key]; !ok {
toRemove = append(toRemove, providerRecs[key])
}
}
if len(toRemove) == 0 {
log.Debug("No DNS records to remove")
return nil
} else {
log.Infof("DNS records to remove: %v", toRemove)
}
return updateRecords(toRemove, &Remove)
}
func getProviderDnsRecords() (map[string]providers.DnsRecord, error) {
allRecords, err := provider.GetRecords()
if err != nil {
return nil, err
}
ourRecords := make(map[string]providers.DnsRecord, len(allRecords))
joins := []string{stack.EnvironmentName, providers.RootDomainName}
suffix := strings.ToLower(strings.Join(joins, "."))
for _, value := range allRecords {
if strings.HasSuffix(value.DomainName, suffix) {
ourRecords[value.DomainName] = value
}
}
return ourRecords, nil
}
func getMetadataDnsRecords(m metadata.MetadataHandler) (map[string]providers.DnsRecord, error) {
containers, err := m.GetContainers()
if err != nil {
return nil, err
}
dnsEntries := make(map[string]providers.DnsRecord)
for _, container := range containers {
if container.StackName == stack.Name {
hostUUID := container.HostUUID
if len(hostUUID) == 0 {
log.Debugf("Container's %v host_uuid is empty", container.Name)
continue
}
host, err := m.GetHost(hostUUID)
if err != nil {
log.Infof("%v", err)
continue
}
ip := host.AgentIP
domainNameEntries := []string{container.ServiceName, container.StackName, stack.EnvironmentName, providers.RootDomainName}
domainName := strings.ToLower(strings.Join(domainNameEntries, "."))
var dnsEntry providers.DnsRecord
var records []string
if _, ok := dnsEntries[domainName]; ok {
records = []string{ip}
} else {
records = dnsEntries[domainName].Records
records = append(records, ip)
}
dnsEntry = providers.DnsRecord{domainName, records, "A", 300}
dnsEntries[domainName] = dnsEntry
}
}
records := make(map[string]providers.DnsRecord, len(dnsEntries))
for _, value := range dnsEntries {
records[value.DomainName] = value
}
return records, nil
}