forked from kubernetes-sigs/external-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinode.go
545 lines (446 loc) · 14.1 KB
/
linode.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package provider
import (
"context"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"github.com/linode/linodego"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"sigs.k8s.io/external-dns/endpoint"
"sigs.k8s.io/external-dns/plan"
)
// LinodeDomainClient interface to ease testing
type LinodeDomainClient interface {
ListDomainRecords(ctx context.Context, domainID int, opts *linodego.ListOptions) ([]*linodego.DomainRecord, error)
ListDomains(ctx context.Context, opts *linodego.ListOptions) ([]*linodego.Domain, error)
CreateDomainRecord(ctx context.Context, domainID int, domainrecord linodego.DomainRecordCreateOptions) (*linodego.DomainRecord, error)
DeleteDomainRecord(ctx context.Context, domainID int, id int) error
UpdateDomainRecord(ctx context.Context, domainID int, id int, domainrecord linodego.DomainRecordUpdateOptions) (*linodego.DomainRecord, error)
}
// LinodeProvider is an implementation of Provider for Digital Ocean's DNS.
type LinodeProvider struct {
Client LinodeDomainClient
domainFilter endpoint.DomainFilter
DryRun bool
}
// LinodeChanges All API calls calculated from the plan
type LinodeChanges struct {
Creates []*LinodeChangeCreate
Deletes []*LinodeChangeDelete
Updates []*LinodeChangeUpdate
}
// LinodeChangeCreate Linode Domain Record Creates
type LinodeChangeCreate struct {
Domain *linodego.Domain
Options linodego.DomainRecordCreateOptions
}
// LinodeChangeUpdate Linode Domain Record Updates
type LinodeChangeUpdate struct {
Domain *linodego.Domain
DomainRecord *linodego.DomainRecord
Options linodego.DomainRecordUpdateOptions
}
// LinodeChangeDelete Linode Domain Record Deletes
type LinodeChangeDelete struct {
Domain *linodego.Domain
DomainRecord *linodego.DomainRecord
}
// NewLinodeProvider initializes a new Linode DNS based Provider.
func NewLinodeProvider(domainFilter endpoint.DomainFilter, dryRun bool, appVersion string) (*LinodeProvider, error) {
token, ok := os.LookupEnv("LINODE_TOKEN")
if !ok {
return nil, fmt.Errorf("no token found")
}
tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
oauth2Client := &http.Client{
Transport: &oauth2.Transport{
Source: tokenSource,
},
}
linodeClient := linodego.NewClient(oauth2Client)
linodeClient.SetUserAgent(fmt.Sprintf("ExternalDNS/%s linodego/%s", appVersion, linodego.Version))
provider := &LinodeProvider{
Client: &linodeClient,
domainFilter: domainFilter,
DryRun: dryRun,
}
return provider, nil
}
// Zones returns the list of hosted zones.
func (p *LinodeProvider) Zones(ctx context.Context) ([]*linodego.Domain, error) {
zones, err := p.fetchZones(ctx)
if err != nil {
return nil, err
}
return zones, nil
}
// Records returns the list of records in a given zone.
func (p *LinodeProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) {
zones, err := p.Zones(ctx)
if err != nil {
return nil, err
}
var endpoints []*endpoint.Endpoint
for _, zone := range zones {
records, err := p.fetchRecords(ctx, zone.ID)
if err != nil {
return nil, err
}
for _, r := range records {
if supportedRecordType(string(r.Type)) {
name := fmt.Sprintf("%s.%s", r.Name, zone.Domain)
// root name is identified by the empty string and should be
// translated to zone name for the endpoint entry.
if r.Name == "" {
name = zone.Domain
}
endpoints = append(endpoints, endpoint.NewEndpointWithTTL(name, string(r.Type), endpoint.TTL(r.TTLSec), r.Target))
}
}
}
return endpoints, nil
}
func (p *LinodeProvider) fetchRecords(ctx context.Context, domainID int) ([]*linodego.DomainRecord, error) {
records, err := p.Client.ListDomainRecords(ctx, domainID, nil)
if err != nil {
return nil, err
}
return records, nil
}
func (p *LinodeProvider) fetchZones(ctx context.Context) ([]*linodego.Domain, error) {
var zones []*linodego.Domain
allZones, err := p.Client.ListDomains(ctx, linodego.NewListOptions(0, ""))
if err != nil {
return nil, err
}
for _, zone := range allZones {
if !p.domainFilter.Match(zone.Domain) {
continue
}
zones = append(zones, zone)
}
return zones, nil
}
// submitChanges takes a zone and a collection of Changes and sends them as a single transaction.
func (p *LinodeProvider) submitChanges(ctx context.Context, changes LinodeChanges) error {
for _, change := range changes.Creates {
logFields := log.Fields{
"record": change.Options.Name,
"type": change.Options.Type,
"action": "Create",
"zoneName": change.Domain.Domain,
"zoneID": change.Domain.ID,
}
log.WithFields(logFields).Info("Creating record.")
if p.DryRun {
log.WithFields(logFields).Info("Would create record.")
} else if _, err := p.Client.CreateDomainRecord(ctx, change.Domain.ID, change.Options); err != nil {
log.WithFields(logFields).Errorf(
"Failed to Create record: %v",
err,
)
}
}
for _, change := range changes.Deletes {
logFields := log.Fields{
"record": change.DomainRecord.Name,
"type": change.DomainRecord.Type,
"action": "Delete",
"zoneName": change.Domain.Domain,
"zoneID": change.Domain.ID,
}
log.WithFields(logFields).Info("Deleting record.")
if p.DryRun {
log.WithFields(logFields).Info("Would delete record.")
} else if err := p.Client.DeleteDomainRecord(ctx, change.Domain.ID, change.DomainRecord.ID); err != nil {
log.WithFields(logFields).Errorf(
"Failed to Delete record: %v",
err,
)
}
}
for _, change := range changes.Updates {
logFields := log.Fields{
"record": change.Options.Name,
"type": change.Options.Type,
"action": "Update",
"zoneName": change.Domain.Domain,
"zoneID": change.Domain.ID,
}
log.WithFields(logFields).Info("Updating record.")
if p.DryRun {
log.WithFields(logFields).Info("Would update record.")
} else if _, err := p.Client.UpdateDomainRecord(ctx, change.Domain.ID, change.DomainRecord.ID, change.Options); err != nil {
log.WithFields(logFields).Errorf(
"Failed to Update record: %v",
err,
)
}
}
return nil
}
func getWeight() *int {
weight := 1
return &weight
}
func getPort() *int {
port := 0
return &port
}
func getPriority() *int {
priority := 0
return &priority
}
// ApplyChanges applies a given set of changes in a given zone.
func (p *LinodeProvider) ApplyChanges(ctx context.Context, changes *plan.Changes) error {
recordsByZoneID := make(map[string][]*linodego.DomainRecord)
zones, err := p.fetchZones(ctx)
if err != nil {
return err
}
zonesByID := make(map[string]*linodego.Domain)
zoneNameIDMapper := zoneIDName{}
for _, z := range zones {
zoneNameIDMapper.Add(strconv.Itoa(z.ID), z.Domain)
zonesByID[strconv.Itoa(z.ID)] = z
}
// Fetch records for each zone
for _, zone := range zones {
records, err := p.fetchRecords(ctx, zone.ID)
if err != nil {
return err
}
recordsByZoneID[strconv.Itoa(zone.ID)] = append(recordsByZoneID[strconv.Itoa(zone.ID)], records...)
}
createsByZone := endpointsByZone(zoneNameIDMapper, changes.Create)
updatesByZone := endpointsByZone(zoneNameIDMapper, changes.UpdateNew)
deletesByZone := endpointsByZone(zoneNameIDMapper, changes.Delete)
var linodeCreates []*LinodeChangeCreate
var linodeUpdates []*LinodeChangeUpdate
var linodeDeletes []*LinodeChangeDelete
// Generate Creates
for zoneID, creates := range createsByZone {
zone := zonesByID[zoneID]
if len(creates) == 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"zoneName": zone.Domain,
}).Debug("Skipping Zone, no creates found.")
continue
}
records := recordsByZoneID[zoneID]
for _, ep := range creates {
matchedRecords := getRecordID(records, zone, ep)
if len(matchedRecords) != 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"zoneName": zone.Domain,
"dnsName": ep.DNSName,
"recordType": ep.RecordType,
}).Warn("Records found which should not exist")
}
recordType, err := convertRecordType(ep.RecordType)
if err != nil {
return err
}
for _, target := range ep.Targets {
linodeCreates = append(linodeCreates, &LinodeChangeCreate{
Domain: zone,
Options: linodego.DomainRecordCreateOptions{
Target: target,
Name: getStrippedRecordName(zone, ep),
Type: recordType,
Weight: getWeight(),
Port: getPort(),
Priority: getPriority(),
TTLSec: int(ep.RecordTTL),
},
})
}
}
}
// Generate Updates
for zoneID, updates := range updatesByZone {
zone := zonesByID[zoneID]
if len(updates) == 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"zoneName": zone.Domain,
}).Debug("Skipping Zone, no updates found.")
continue
}
records := recordsByZoneID[zoneID]
for _, ep := range updates {
matchedRecords := getRecordID(records, zone, ep)
if len(matchedRecords) == 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"dnsName": ep.DNSName,
"zoneName": zone.Domain,
"recordType": ep.RecordType,
}).Warn("Update Records not found.")
}
recordType, err := convertRecordType(ep.RecordType)
if err != nil {
return err
}
matchedRecordsByTarget := make(map[string]*linodego.DomainRecord)
for _, record := range matchedRecords {
matchedRecordsByTarget[record.Target] = record
}
for _, target := range ep.Targets {
if record, ok := matchedRecordsByTarget[target]; ok {
log.WithFields(log.Fields{
"zoneID": zoneID,
"dnsName": ep.DNSName,
"zoneName": zone.Domain,
"recordType": ep.RecordType,
"target": target,
}).Warn("Updating Existing Target")
linodeUpdates = append(linodeUpdates, &LinodeChangeUpdate{
Domain: zone,
DomainRecord: record,
Options: linodego.DomainRecordUpdateOptions{
Target: target,
Name: getStrippedRecordName(zone, ep),
Type: recordType,
Weight: getWeight(),
Port: getPort(),
Priority: getPriority(),
TTLSec: int(ep.RecordTTL),
},
})
delete(matchedRecordsByTarget, target)
} else {
// Record did not previously exist, create new 'target'
log.WithFields(log.Fields{
"zoneID": zoneID,
"dnsName": ep.DNSName,
"zoneName": zone.Domain,
"recordType": ep.RecordType,
"target": target,
}).Warn("Creating New Target")
linodeCreates = append(linodeCreates, &LinodeChangeCreate{
Domain: zone,
Options: linodego.DomainRecordCreateOptions{
Target: target,
Name: getStrippedRecordName(zone, ep),
Type: recordType,
Weight: getWeight(),
Port: getPort(),
Priority: getPriority(),
TTLSec: int(ep.RecordTTL),
},
})
}
}
// Any remaining records have been removed, delete them
for _, record := range matchedRecordsByTarget {
log.WithFields(log.Fields{
"zoneID": zoneID,
"dnsName": ep.DNSName,
"zoneName": zone.Domain,
"recordType": ep.RecordType,
"target": record.Target,
}).Warn("Deleting Target")
linodeDeletes = append(linodeDeletes, &LinodeChangeDelete{
Domain: zone,
DomainRecord: record,
})
}
}
}
// Generate Deletes
for zoneID, deletes := range deletesByZone {
zone := zonesByID[zoneID]
if len(deletes) == 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"zoneName": zone.Domain,
}).Debug("Skipping Zone, no deletes found.")
continue
}
records := recordsByZoneID[zoneID]
for _, ep := range deletes {
matchedRecords := getRecordID(records, zone, ep)
if len(matchedRecords) == 0 {
log.WithFields(log.Fields{
"zoneID": zoneID,
"dnsName": ep.DNSName,
"zoneName": zone.Domain,
"recordType": ep.RecordType,
}).Warn("Records to Delete not found.")
}
for _, record := range matchedRecords {
linodeDeletes = append(linodeDeletes, &LinodeChangeDelete{
Domain: zone,
DomainRecord: record,
})
}
}
}
return p.submitChanges(ctx, LinodeChanges{
Creates: linodeCreates,
Deletes: linodeDeletes,
Updates: linodeUpdates,
})
}
func endpointsByZone(zoneNameIDMapper zoneIDName, endpoints []*endpoint.Endpoint) map[string][]*endpoint.Endpoint {
endpointsByZone := make(map[string][]*endpoint.Endpoint)
for _, ep := range endpoints {
zoneID, _ := zoneNameIDMapper.FindZone(ep.DNSName)
if zoneID == "" {
log.Debugf("Skipping record %s because no hosted zone matching record DNS Name was detected", ep.DNSName)
continue
}
endpointsByZone[zoneID] = append(endpointsByZone[zoneID], ep)
}
return endpointsByZone
}
func convertRecordType(recordType string) (linodego.DomainRecordType, error) {
switch recordType {
case "A":
return linodego.RecordTypeA, nil
case "AAAA":
return linodego.RecordTypeAAAA, nil
case "CNAME":
return linodego.RecordTypeCNAME, nil
case "TXT":
return linodego.RecordTypeTXT, nil
case "SRV":
return linodego.RecordTypeSRV, nil
default:
return "", fmt.Errorf("invalid Record Type: %s", recordType)
}
}
func getStrippedRecordName(zone *linodego.Domain, ep *endpoint.Endpoint) string {
// Handle root
if ep.DNSName == zone.Domain {
return ""
}
return strings.TrimSuffix(ep.DNSName, "."+zone.Domain)
}
func getRecordID(records []*linodego.DomainRecord, zone *linodego.Domain, ep *endpoint.Endpoint) []*linodego.DomainRecord {
var matchedRecords []*linodego.DomainRecord
for _, record := range records {
if record.Name == getStrippedRecordName(zone, ep) && string(record.Type) == ep.RecordType {
matchedRecords = append(matchedRecords, record)
}
}
return matchedRecords
}