-
Notifications
You must be signed in to change notification settings - Fork 0
/
route53.go
294 lines (247 loc) · 7.85 KB
/
route53.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
// Copyright 2017 Qubit Ltd.
//
// 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 dubber
import (
"fmt"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/aws/aws-sdk-go/service/route53/route53iface"
"github.com/miekg/dns"
klog "k8s.io/klog/v2"
)
// Route53Config is used to provide settings for a Route53 provisioner.
// If the ZoneID is not set it will be looked up in the clients default
// region.
type Route53Config struct {
BaseProvisionerConfig `json:",omitempty,inline" yaml:",omitempty,inline"`
ZoneID string `json:"zoneid,omitempty" yaml:"zoneid,omitempty"`
}
// Route53 is an AWS Route53 DNS record provisioner.
// This provision uses the following flags:
// - route53.SetID: Associate these records with a Set
// - route53.Weight: Set a weight for the set
// - route53.Alias: "HOSTEDZONEID:ALIASNAME"
// - route53.EvalTargetHealth: "true" will enable target health evaluation
// on an alias
type Route53 struct {
svc route53iface.Route53API
sync.Mutex
Route53Config
}
// NewRoute53 creates a route53 provisioner. Currently this uses the
// default client setup from the aws-sdk.
func NewRoute53(cfg Route53Config) *Route53 {
sess := session.Must(session.NewSession())
svc := route53.New(sess)
return &Route53{
Route53Config: cfg,
svc: svc,
}
}
// RemoteZone creates a Zone from an AWS Route53 Hosted Zone.
func (r *Route53) GroupFlags() []string {
return []string{"route53.SetID"}
}
// RemoteZone creates a Zone from an AWS Route53 Hosted Zone.
func (r *Route53) RemoteZone() (Zone, error) {
var err error
r.Lock()
defer r.Unlock()
if r.ZoneID == "" {
r.ZoneID, err = zoneIDFromRoute53(r.svc, r.Zone)
if err != nil {
return nil, fmt.Errorf("could not retrieve remote zone, %w", err)
}
}
return zoneFromRoute53(r.svc, r.ZoneID)
}
// UpdateZone updates a Route53 zone, removing the unwanted records, and
// adding any wanted records.
func (r *Route53) UpdateZone(wanted, unwanted, desired, remote Zone) error {
var err error
if r.ZoneID == "" {
r.ZoneID, err = zoneIDFromRoute53(r.svc, r.Zone)
if err != nil {
return fmt.Errorf("could not update zone, %w", err)
}
}
changes := route53.ChangeBatch{
Comment: aws.String(fmt.Sprintf("dubber did it... %s", time.Now())),
}
for _, uw := range unwanted {
awsrrs, err := recordToAWSRRS(uw)
if err != nil {
return fmt.Errorf("generating updating DELETE record, %w", err)
}
change := route53.Change{
Action: aws.String("DELETE"),
ResourceRecordSet: awsrrs,
}
changes.Changes = append(changes.Changes, &change)
}
for _, w := range wanted {
awsrrs, err := recordToAWSRRS(w)
if err != nil {
return fmt.Errorf("generating CREATE record, %w", err)
}
change := route53.Change{
Action: aws.String("CREATE"),
ResourceRecordSet: awsrrs,
}
changes.Changes = append(changes.Changes, &change)
}
klog.V(1).Infof("Route53 Changes to %s: %s", r.ZoneID, changes)
sess := session.Must(session.NewSession())
svc := route53.New(sess)
params := &route53.ChangeResourceRecordSetsInput{
HostedZoneId: aws.String(r.ZoneID),
ChangeBatch: &changes,
}
// Example iterating over at most 3 pages of a ListResourceRecordSets operation.
out, err := svc.ChangeResourceRecordSets(params)
if err != nil {
return err
}
klog.V(1).Infof("Change succeeded:\n %s", out)
return nil
}
func zoneIDFromRoute53(svc route53iface.Route53API, name string) (string, error) {
params := &route53.ListHostedZonesByNameInput{
DNSName: aws.String(name),
MaxItems: aws.String("1"),
}
resp, err := svc.ListHostedZonesByName(params)
if err != nil {
return "", err
}
if len(resp.HostedZones) == 0 {
return "", fmt.Errorf("uknown zone %s", name)
}
if len(resp.HostedZones) > 1 {
return "", fmt.Errorf("too many zones found for %s (%d zones)", name, len((resp.HostedZones)))
}
return *resp.HostedZones[0].Id, nil
}
func zoneFromRoute53(svc route53iface.Route53API, zoneID string) (Zone, error) {
var awsrecs []*route53.ResourceRecordSet
lrrsparams := &route53.ListResourceRecordSetsInput{HostedZoneId: aws.String(zoneID)}
// Example iterating over at most 3 pages of a ListResourceRecordSets operation.
if err := svc.ListResourceRecordSetsPages(lrrsparams,
func(page *route53.ListResourceRecordSetsOutput, lastPage bool) bool {
awsrecs = append(awsrecs, page.ResourceRecordSets...)
return !lastPage
}); err != nil {
return nil, err
}
var z Zone
for i := range awsrecs {
newrs, err := awsRRSToRecord(awsrecs[i])
if err != nil {
return nil, fmt.Errorf("failed rendering record for %#v, %w", awsrecs[i], err)
}
z = append(z, newrs...)
}
sort.Sort(ByRR(z))
return z, nil
}
func awsRRSToRecord(r53 *route53.ResourceRecordSet) (Zone, error) {
var res Zone
var err error
flags := RecordFlags{}
if r53.SetIdentifier != nil {
flags["route53.SetID"] = *r53.SetIdentifier
}
if r53.Weight != nil {
flags["route53.Weight"] = strconv.Itoa(int(*r53.Weight))
}
for i := range r53.ResourceRecords {
rr := r53.ResourceRecords[i]
str := fmt.Sprintf("%s %d IN %s %s", *r53.Name, *r53.TTL, *r53.Type, *rr.Value)
drr, err := dns.NewRR(str)
if err != nil {
klog.Infof("failed parsing record %q, %v", str, err)
continue
}
res = append(res, &Record{RR: drr, Flags: flags})
}
if r53.AliasTarget != nil {
str := fmt.Sprintf("%s 0 IN %s 0.0.0.0", *r53.Name, *r53.Type)
drr, err := dns.NewRR(str)
if err != nil {
return res, err
}
flags["route53.Alias"] = *r53.AliasTarget.HostedZoneId + ":" + *r53.AliasTarget.DNSName
if r53.AliasTarget.EvaluateTargetHealth != nil && *r53.AliasTarget.EvaluateTargetHealth {
flags["route53.EvalTargetHealth"] = "true"
}
res = append(res, &Record{RR: drr, Flags: flags})
}
return res, err
}
func recordToAWSRRS(r *Record) (*route53.ResourceRecordSet, error) {
r53 := &route53.ResourceRecordSet{}
r53.Name = aws.String(r.Header().Name)
rrtype, ok := dns.TypeToString[r.Header().Rrtype]
if !ok {
return nil, fmt.Errorf("unknown dns.Rtype %d", r.Header().Rrtype)
}
r53.Type = aws.String(rrtype)
var evalTargetHealth bool
if evthStr, ok := r.Flags["route53.EvalTargetHealth"]; ok && evthStr == "true" {
evalTargetHealth = true
}
if aliasStr, ok := r.Flags["route53.Alias"]; ok {
aliasStrs := strings.SplitN(aliasStr, ":", 2)
if len(aliasStrs) != 2 {
return nil, fmt.Errorf("could not parse alias, must be HOSTEDZONEID:NAME %d", r.Header().Rrtype)
}
aliasZone := aliasStrs[0]
aliasName := aliasStrs[1]
r53.AliasTarget = &route53.AliasTarget{
HostedZoneId: aws.String(aliasZone),
DNSName: aws.String(aliasName),
EvaluateTargetHealth: aws.Bool(evalTargetHealth),
}
}
if setIDStr, ok := r.Flags["route53.SetID"]; ok {
r53.SetIdentifier = &setIDStr
}
if region, ok := r.Flags["route53.Region"]; ok {
r53.Region = ®ion
}
if weighStr, ok := r.Flags["route53.Weight"]; ok {
w, err := strconv.Atoi(weighStr)
if err != nil {
return nil, fmt.Errorf("failed to parse weight as int, %w", err)
}
wint64 := int64(w)
r53.Weight = &wint64
}
if r53.AliasTarget != nil {
return r53, nil
}
r53.ResourceRecords = []*route53.ResourceRecord{
{Value: aws.String(r.RR.String()[len(r.Header().String()):])},
}
if r.Header().Rrtype != dns.TypeCNAME {
r53.TTL = aws.Int64(int64(r.Header().Ttl))
}
return r53, nil
}