-
Notifications
You must be signed in to change notification settings - Fork 271
/
commands.go
745 lines (674 loc) · 18.9 KB
/
commands.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
package cli53
import (
"context"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/miekg/dns"
)
const ChangeBatchSize = 100
func createZone(ctx context.Context, name, comment, vpcId, vpcRegion, delegationSetId string) {
callerReference := uniqueReference()
req := route53.CreateHostedZoneInput{
CallerReference: &callerReference,
Name: &name,
HostedZoneConfig: &route53.HostedZoneConfig{
Comment: &comment,
},
}
if vpcId != "" && vpcRegion != "" {
req.VPC = &route53.VPC{
VPCId: aws.String(vpcId),
VPCRegion: aws.String(vpcRegion),
}
}
if delegationSetId != "" {
delegationSetId = strings.Replace(delegationSetId, "/delegationset/", "", 1)
req.DelegationSetId = aws.String(delegationSetId)
}
resp, err := r53.CreateHostedZoneWithContext(ctx, &req)
fatalIfErr(err)
fmt.Printf("Created zone: '%s' ID: '%s'\n", *resp.HostedZone.Name, *resp.HostedZone.Id)
}
func createReusableDelegationSet(ctx context.Context, zoneId string) {
callerReference := uniqueReference()
req := route53.CreateReusableDelegationSetInput{
CallerReference: &callerReference,
}
if zoneId != "" {
req.HostedZoneId = &zoneId
}
resp, err := r53.CreateReusableDelegationSetWithContext(ctx, &req)
fatalIfErr(err)
ds := resp.DelegationSet
fmt.Printf("Created reusable delegation set ID: '%s'\n", *ds.Id)
for _, ns := range ds.NameServers {
fmt.Printf("Nameserver: %s\n", *ns)
}
}
func listReusableDelegationSets(ctx context.Context) {
req := route53.ListReusableDelegationSetsInput{}
resp, err := r53.ListReusableDelegationSetsWithContext(ctx, &req)
fatalIfErr(err)
fmt.Printf("Reusable delegation sets:\n")
if len(resp.DelegationSets) == 0 {
fmt.Println("none")
return
}
for _, ds := range resp.DelegationSets {
var nameservers []string
for _, ns := range ds.NameServers {
nameservers = append(nameservers, *ns)
}
fmt.Printf("- ID: %s Nameservers: %s\n", *ds.Id, strings.Join(nameservers, ", "))
}
}
func deleteReusableDelegationSet(ctx context.Context, id string) {
if !strings.HasPrefix(id, "/delegationset/") {
id = "/delegationset/" + id
}
req := route53.DeleteReusableDelegationSetInput{
Id: &id,
}
_, err := r53.DeleteReusableDelegationSetWithContext(ctx, &req)
fatalIfErr(err)
fmt.Printf("Deleted reusable delegation set\n")
}
func deleteRecordSets(ctx context.Context, zone *route53.HostedZone, rrsets []*route53.ResourceRecordSet, wait bool) (int, error) {
// delete all non-default SOA/NS records
changes := []*route53.Change{}
for _, rrset := range rrsets {
if !isAuthRecord(zone, rrset) {
change := &route53.Change{
Action: aws.String("DELETE"),
ResourceRecordSet: rrset,
}
changes = append(changes, change)
}
}
if len(changes) > 0 {
req := route53.ChangeResourceRecordSetsInput{
HostedZoneId: zone.Id,
ChangeBatch: &route53.ChangeBatch{
Changes: changes,
},
}
resp, err := r53.ChangeResourceRecordSetsWithContext(ctx, &req)
if err != nil {
return 0, err
}
if wait {
waitForChange(ctx, resp.ChangeInfo)
}
}
return len(changes), nil
}
func purgeZoneRecords(ctx context.Context, zone *route53.HostedZone, wait bool) {
total := 0
err := batchListAllRecordSets(ctx, r53, *zone.Id, func(rrsets []*route53.ResourceRecordSet) {
n, err := deleteRecordSets(ctx, zone, rrsets, wait)
fatalIfErr(err)
total += n
})
fatalIfErr(err)
fmt.Printf("%d record sets deleted\n", total)
}
func deleteZone(ctx context.Context, name string, purge bool) {
zone := lookupZone(ctx, name)
if purge {
purgeZoneRecords(ctx, zone, false)
}
req := route53.DeleteHostedZoneInput{Id: zone.Id}
_, err := r53.DeleteHostedZoneWithContext(ctx, &req)
fatalIfErr(err)
fmt.Printf("Deleted zone: '%s' ID: '%s'\n", *zone.Name, *zone.Id)
}
func listZones(ctx context.Context, formatter Formatter) {
zones := make(chan *route53.HostedZone)
go func() {
req := route53.ListHostedZonesInput{}
for {
// paginated
resp, err := r53.ListHostedZonesWithContext(ctx, &req)
fatalIfErr(err)
for _, zone := range resp.HostedZones {
zones <- zone
}
if *resp.IsTruncated {
req.Marker = resp.NextMarker
} else {
break
}
}
close(zones)
}()
formatter.formatZoneList(zones, os.Stdout)
}
func isAuthRecord(zone *route53.HostedZone, rrset *route53.ResourceRecordSet) bool {
return (*rrset.Type == "SOA" || *rrset.Type == "NS") && *rrset.Name == *zone.Name
}
func expandSelfAliases(records []dns.RR, zone *route53.HostedZone) {
for _, record := range records {
expandSelfAlias(record, zone)
}
}
func expandSelfAlias(record dns.RR, zone *route53.HostedZone) {
if awsrr, ok := record.(*AWSRR); ok {
record = awsrr.RR
}
if alias, ok := record.(*dns.PrivateRR); ok {
rdata := alias.Data.(*ALIASRdata)
if rdata.ZoneId == "$self" {
rdata.ZoneId = strings.Replace(*zone.Id, "/hostedzone/", "", 1)
rdata.Target = qualifyName(rdata.Target, *zone.Name)
}
}
}
type Key struct {
Name string
Rrtype uint16
Identifier string
}
type changeSorter struct {
changes []*route53.Change
}
func (r changeSorter) Len() int {
return len(r.changes)
}
func (r changeSorter) Swap(i, j int) {
r.changes[i], r.changes[j] = r.changes[j], r.changes[i]
}
func (r changeSorter) Less(i, j int) bool {
// sort non-aliases first
if r.changes[i].ResourceRecordSet.AliasTarget == nil {
return true
}
if r.changes[j].ResourceRecordSet.AliasTarget == nil {
return false
}
return *r.changes[i].ResourceRecordSet.Name < *r.changes[j].ResourceRecordSet.Name
}
func groupRecords(records []dns.RR) map[Key][]dns.RR {
// group records by name+type and optionally identifier
grouped := map[Key][]dns.RR{}
for _, record := range records {
var identifier string
if aws, ok := record.(*AWSRR); ok {
identifier = aws.Identifier
}
if alias, ok := record.(*dns.PrivateRR); ok {
// issue #195: alias records need to be keyed by the type of the alias too
rdata := alias.Data.(*ALIASRdata)
identifier += "@" + rdata.Type
}
key := Key{record.Header().Name, record.Header().Rrtype, identifier}
grouped[key] = append(grouped[key], record)
}
return grouped
}
type importArgs struct {
name string
file string
wait bool
editauth bool
replace bool
upsert bool
dryrun bool
}
func rrsetKey(rrset *route53.ResourceRecordSet) string {
key := fmt.Sprintf("%s %s", *rrset.Type, *rrset.Name)
if rrset.TTL != nil {
key += fmt.Sprintf(" %d", *rrset.TTL)
}
var rrs []string
for _, rr := range rrset.ResourceRecords {
rrs = append(rrs, rr.String())
}
if rrset.AliasTarget != nil {
rrs = append(rrs, rrset.AliasTarget.String())
}
sort.Strings(rrs)
for _, rr := range rrs {
key += " " + rr
}
return key
}
func validateBindFile(args importArgs) {
var reader io.Reader
if args.file == "-" {
reader = os.Stdin
} else {
f, err := os.Open(args.file)
fatalIfErr(err)
defer f.Close()
reader = f
}
parseBindFile(reader, args.file, "validate.test")
}
func importBind(ctx context.Context, args importArgs) {
zone := lookupZone(ctx, args.name)
var reader io.Reader
if args.file == "-" {
reader = os.Stdin
} else {
f, err := os.Open(args.file)
fatalIfErr(err)
defer f.Close()
reader = f
}
records := parseBindFile(reader, args.file, *zone.Name)
expandSelfAliases(records, zone)
grouped := groupRecords(records)
existing := map[string]*route53.ResourceRecordSet{}
if args.replace || args.upsert {
rrsets, err := ListAllRecordSets(ctx, r53, *zone.Id)
fatalIfErr(err)
for _, rrset := range rrsets {
if args.editauth || !isAuthRecord(zone, rrset) {
rrset.Name = aws.String(unescaper.Replace(*rrset.Name))
existing[rrsetKey(rrset)] = rrset
}
}
}
additions := []*route53.Change{}
for _, values := range grouped {
rrset := ConvertBindToRRSet(values)
if rrset != nil && (args.editauth || !isAuthRecord(zone, rrset)) {
key := rrsetKey(rrset)
if _, ok := existing[key]; ok {
// no difference - leave it untouched
delete(existing, key)
} else {
// new record, add or upsert
if args.upsert {
change := route53.Change{
Action: aws.String("UPSERT"),
ResourceRecordSet: rrset,
}
additions = append(additions, &change)
} else {
change := route53.Change{
Action: aws.String("CREATE"),
ResourceRecordSet: rrset,
}
additions = append(additions, &change)
}
}
}
}
// remaining records in existing should be deleted
deletions := []*route53.Change{}
if !args.upsert {
for _, rrset := range existing {
change := route53.Change{
Action: aws.String("DELETE"),
ResourceRecordSet: rrset,
}
deletions = append(deletions, &change)
}
}
if args.dryrun {
if len(additions)+len(deletions) == 0 {
fmt.Println("Dry-run, but no changes would have been made.")
} else {
fmt.Println("Dry-run, changes that would be made:")
for _, addition := range additions {
rrs := ConvertRRSetToBind(addition.ResourceRecordSet)
for _, rr := range rrs {
fmt.Printf("+ %s\n", rr.String())
}
}
for _, deletion := range deletions {
rrs := ConvertRRSetToBind(deletion.ResourceRecordSet)
for _, rr := range rrs {
fmt.Printf("- %s\n", rr.String())
}
}
}
} else {
resp := batchChanges(ctx, additions, deletions, zone)
fmt.Printf("%d records imported (%d changes / %d additions / %d deletions)\n", len(records), len(additions)+len(deletions), len(additions), len(deletions))
if args.wait && resp != nil {
waitForChange(ctx, resp.ChangeInfo)
}
}
}
func batchChanges(ctx context.Context, additions, deletions []*route53.Change, zone *route53.HostedZone) *route53.ChangeResourceRecordSetsOutput {
// sort additions so aliases are last
sort.Sort(changeSorter{additions})
changes := append(deletions, additions...)
var resp *route53.ChangeResourceRecordSetsOutput
for i := 0; i < len(changes); i += ChangeBatchSize {
end := i + ChangeBatchSize
if end > len(changes) {
end = len(changes)
}
batch := route53.ChangeBatch{
Changes: changes[i:end],
}
req := route53.ChangeResourceRecordSetsInput{
HostedZoneId: zone.Id,
ChangeBatch: &batch,
}
var err error
resp, err = r53.ChangeResourceRecordSetsWithContext(ctx, &req)
fatalIfErr(err)
}
return resp
}
func UnexpandSelfAliases(records []dns.RR, zone *route53.HostedZone, full bool) {
id := strings.Replace(*zone.Id, "/hostedzone/", "", 1)
for _, rr := range records {
if awsrr, ok := rr.(*AWSRR); ok {
rr = awsrr.RR
}
if alias, ok := rr.(*dns.PrivateRR); ok {
rdata := alias.Data.(*ALIASRdata)
if rdata.ZoneId == id {
rdata.ZoneId = "$self"
if !full {
rdata.Target = shortenName(rdata.Target, *zone.Name)
}
}
}
}
}
func exportBind(ctx context.Context, name string, full bool, writer io.Writer) {
zone := lookupZone(ctx, name)
ExportBindToWriter(ctx, r53, zone, full, writer)
}
type exportSorter struct {
rrsets []*route53.ResourceRecordSet
zone string
}
func (r exportSorter) Len() int {
return len(r.rrsets)
}
func (r exportSorter) Swap(i, j int) {
r.rrsets[i], r.rrsets[j] = r.rrsets[j], r.rrsets[i]
}
func (r exportSorter) Less(i, j int) bool {
if *r.rrsets[i].Name == *r.rrsets[j].Name {
if *r.rrsets[i].Type == "SOA" {
return true
}
return *r.rrsets[i].Type < *r.rrsets[j].Type
}
if *r.rrsets[i].Name == r.zone {
return true
}
if *r.rrsets[j].Name == r.zone {
return false
}
return *r.rrsets[i].Name < *r.rrsets[j].Name
}
func ExportBindToWriter(ctx context.Context, r53 *route53.Route53, zone *route53.HostedZone, full bool, out io.Writer) {
rrsets, err := ListAllRecordSets(ctx, r53, *zone.Id)
fatalIfErr(err)
sort.Sort(exportSorter{rrsets, *zone.Name})
dnsname := *zone.Name
fmt.Fprintf(out, "$ORIGIN %s\n", dnsname)
for _, rrset := range rrsets {
rrs := ConvertRRSetToBind(rrset)
UnexpandSelfAliases(rrs, zone, full)
for _, rr := range rrs {
line := rr.String()
if !full {
parts := strings.Split(line, "\t")
parts[0] = shortenName(parts[0], dnsname)
if parts[3] == "CNAME" {
parts[4] = shortenName(parts[4], dnsname)
}
line = strings.Join(parts, "\t")
}
fmt.Fprintln(out, line)
}
}
}
type createArgs struct {
name string
records []string
wait bool
append bool
replace bool
identifier string
failover string
healthCheckId string
weight *int
region string
countryCode string
continentCode string
subdivisionCode string
multivalue bool
}
func (args createArgs) validate() bool {
if args.failover != "" && args.failover != "PRIMARY" && args.failover != "SECONDARY" {
fmt.Println("failover must be PRIMARY or SECONDARY")
return false
}
if args.replace && args.append {
fmt.Println("you can only --append or --replace, not both at the same time")
return false
}
extcount := 0
if args.failover != "" {
extcount += 1
}
if args.weight != nil {
extcount += 1
}
if args.region != "" {
extcount += 1
}
if args.countryCode != "" {
extcount += 1
}
if args.continentCode != "" {
extcount += 1
}
if args.multivalue {
extcount += 1
}
if args.subdivisionCode != "" && args.countryCode == "" {
fmt.Println("country-code must be specified if subdivision-code is specified")
return false
}
if extcount > 0 && args.identifier == "" {
fmt.Println("identifier must be set when creating an extended record")
return false
}
if extcount == 0 && args.identifier != "" {
fmt.Println("identifier should only be set when creating an extended record")
return false
}
if extcount > 1 {
fmt.Println("failover, weight, region, country-code and continent-code are mutually exclusive")
return false
}
return true
}
func (args createArgs) applyRRSetParams(rrset *route53.ResourceRecordSet) {
if args.identifier != "" {
rrset.SetIdentifier = aws.String(args.identifier)
}
if args.failover != "" {
rrset.Failover = aws.String(args.failover)
}
if args.healthCheckId != "" {
rrset.HealthCheckId = aws.String(args.healthCheckId)
}
if args.weight != nil {
rrset.Weight = aws.Int64(int64(*args.weight))
}
if args.region != "" {
rrset.Region = aws.String(args.region)
}
if args.continentCode != "" {
rrset.GeoLocation = &route53.GeoLocation{
ContinentCode: aws.String(args.continentCode),
}
}
if args.countryCode != "" {
rrset.GeoLocation = &route53.GeoLocation{
CountryCode: aws.String(args.countryCode),
}
}
if args.countryCode != "" && args.subdivisionCode != "" {
rrset.GeoLocation = &route53.GeoLocation{
CountryCode: aws.String(args.countryCode),
SubdivisionCode: aws.String(args.subdivisionCode),
}
}
if args.multivalue {
rrset.MultiValueAnswer = aws.Bool(true)
}
}
func equalStringPtrs(a, b *string) bool {
if a == nil && b == nil {
return true
} else if a != nil && b != nil {
return *a == *b
} else {
return false
}
}
func equalCaseInsensitiveStringPtrs(a, b *string) bool {
if a == nil && b == nil {
return true
} else if a != nil && b != nil {
return strings.EqualFold(*a, *b)
} else {
return false
}
}
func parseRecordList(args []string, zone *route53.HostedZone) []dns.RR {
records := []dns.RR{}
origin := fmt.Sprintf("$ORIGIN %s\n", *zone.Name)
for _, text := range args {
record, err := dns.NewRR(origin + text)
fatalIfErr(err)
records = append(records, record)
}
return records
}
func createRecords(ctx context.Context, args createArgs) {
zone := lookupZone(ctx, args.name)
records := parseRecordList(args.records, zone)
expandSelfAliases(records, zone)
grouped := groupRecords(records)
var existing []*route53.ResourceRecordSet
if args.replace || args.append {
var err error
existing, err = ListAllRecordSets(ctx, r53, *zone.Id)
fatalIfErr(err)
}
additions := []*route53.Change{}
deletions := []*route53.Change{}
for _, values := range grouped {
rrset := ConvertBindToRRSet(values)
args.applyRRSetParams(rrset)
addChange := &route53.Change{
Action: aws.String("CREATE"),
ResourceRecordSet: rrset,
}
additions = append(additions, addChange)
if args.replace || args.append {
// add DELETE if there is an existing record
for _, candidate := range existing {
if equalCaseInsensitiveStringPtrs(rrset.Name, candidate.Name) &&
equalStringPtrs(rrset.Type, candidate.Type) &&
equalStringPtrs(rrset.SetIdentifier, candidate.SetIdentifier) {
change := route53.Change{
Action: aws.String("DELETE"),
ResourceRecordSet: candidate,
}
deletions = append(deletions, &change)
if args.append {
addChange.ResourceRecordSet.ResourceRecords = append(addChange.ResourceRecordSet.ResourceRecords, candidate.ResourceRecords...)
}
break
}
}
}
}
resp := batchChanges(ctx, additions, deletions, zone)
for _, record := range records {
txt := strings.Replace(record.String(), "\t", " ", -1)
fmt.Printf("Created record: '%s'\n", txt)
}
if args.wait {
waitForChange(ctx, resp.ChangeInfo)
}
}
func batchListAllRecordSets(ctx context.Context, r53 *route53.Route53, id string, callback func(rrsets []*route53.ResourceRecordSet)) error {
req := route53.ListResourceRecordSetsInput{
HostedZoneId: &id,
}
for {
resp, err := r53.ListResourceRecordSetsWithContext(ctx, &req)
if err != nil {
return err
} else {
callback(resp.ResourceRecordSets)
if *resp.IsTruncated {
req.StartRecordName = resp.NextRecordName
req.StartRecordType = resp.NextRecordType
req.StartRecordIdentifier = resp.NextRecordIdentifier
} else {
break
}
}
}
return nil
}
// Paginate request to get all record sets.
func ListAllRecordSets(ctx context.Context, r53 *route53.Route53, id string) (rrsets []*route53.ResourceRecordSet, err error) {
err = batchListAllRecordSets(ctx, r53, id, func(results []*route53.ResourceRecordSet) {
rrsets = append(rrsets, results...)
})
// unescape wildcards
for _, rrset := range rrsets {
rrset.Name = aws.String(unescaper.Replace(*rrset.Name))
}
return
}
func deleteRecord(ctx context.Context, name string, match string, rtype string, wait bool, identifier string) {
zone := lookupZone(ctx, name)
rrsets, err := ListAllRecordSets(ctx, r53, *zone.Id)
fatalIfErr(err)
match = qualifyName(match, *zone.Name)
changes := []*route53.Change{}
for _, rrset := range rrsets {
if *rrset.Name == match && *rrset.Type == rtype && (identifier == "" || *rrset.SetIdentifier == identifier) {
change := &route53.Change{
Action: aws.String("DELETE"),
ResourceRecordSet: rrset,
}
changes = append(changes, change)
}
}
if len(changes) > 0 {
req2 := route53.ChangeResourceRecordSetsInput{
HostedZoneId: zone.Id,
ChangeBatch: &route53.ChangeBatch{
Changes: changes,
},
}
resp, err := r53.ChangeResourceRecordSetsWithContext(ctx, &req2)
fatalIfErr(err)
fmt.Printf("%d record sets deleted\n", len(changes))
if wait {
waitForChange(ctx, resp.ChangeInfo)
}
} else {
fmt.Println("Warning: no records matched - nothing deleted")
}
}
func purgeRecords(ctx context.Context, name string, wait bool) {
zone := lookupZone(ctx, name)
purgeZoneRecords(ctx, zone, wait)
}