forked from octodns/octodns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route53.py
1413 lines (1214 loc) · 55.9 KB
/
route53.py
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from boto3 import client
from botocore.config import Config
from collections import defaultdict
from ipaddress import AddressValueError, ip_address
from pycountry_convert import country_alpha2_to_continent_code
from uuid import uuid4
import logging
import re
from six import text_type
from ..equality import EqualityTupleMixin
from ..record import Record, Update
from ..record.geo import GeoCodes
from .base import BaseProvider
octal_re = re.compile(r'\\(\d\d\d)')
def _octal_replace(s):
# See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/
# DomainNameFormat.html
return octal_re.sub(lambda m: chr(int(m.group(1), 8)), s)
class _Route53Record(EqualityTupleMixin):
@classmethod
def _new_dynamic(cls, provider, record, hosted_zone_id, creating):
# Creates the RRSets that correspond to the given dynamic record
ret = set()
# HostedZoneId wants just the last bit, but the place we're getting
# this from looks like /hostedzone/Z424CArX3BB224
hosted_zone_id = hosted_zone_id.split('/', 2)[-1]
# Create the default pool which comes from the base `values` of the
# record object. Its only used if all other values fail their
# healthchecks, which hopefully never happens.
fqdn = record.fqdn
ret.add(_Route53Record(provider, record, creating,
'_octodns-default-pool.{}'.format(fqdn)))
# Pools
for pool_name, pool in record.dynamic.pools.items():
# Create the primary, this will be the rrset that geo targeted
# rrsets will point to when they want to use a pool of values. It's
# a primary and observes target health so if all the values for
# this pool go red, we'll use the fallback/SECONDARY just below
ret.add(_Route53DynamicPool(provider, hosted_zone_id, record,
pool_name, creating))
# Create the fallback for this pool
fallback = pool.data.get('fallback', False)
if fallback:
# We have an explicitly configured fallback, another pool to
# use if all our values go red. This RRSet configures that pool
# as the next best option
ret.add(_Route53DynamicPool(provider, hosted_zone_id, record,
pool_name, creating,
target_name=fallback))
else:
# We fallback on the default, no explicit fallback so if all of
# this pool's values go red we'll fallback to the base
# (non-health-checked) default pool of values
ret.add(_Route53DynamicPool(provider, hosted_zone_id, record,
pool_name, creating,
target_name='default'))
# Create the values for this pool. These are health checked and in
# general each unique value will have an associated healthcheck.
# The PRIMARY pool up above will point to these RRSets which will
# be served out according to their weights
for i, value in enumerate(pool.data['values']):
weight = value['weight']
value = value['value']
ret.add(_Route53DynamicValue(provider, record, pool_name,
value, weight, i, creating))
# Rules
for i, rule in enumerate(record.dynamic.rules):
pool_name = rule.data['pool']
geos = rule.data.get('geos', [])
if geos:
for geo in geos:
# Create a RRSet for each geo in each rule that uses the
# desired target pool
ret.add(_Route53DynamicRule(provider, hosted_zone_id,
record, pool_name, i,
creating, geo=geo))
else:
# There's no geo's for this rule so it's the catchall that will
# just point things that don't match any geo rules to the
# specified pool
ret.add(_Route53DynamicRule(provider, hosted_zone_id, record,
pool_name, i, creating))
return ret
@classmethod
def _new_geo(cls, provider, record, creating):
# Creates the RRSets that correspond to the given geo record
ret = set()
ret.add(_Route53GeoDefault(provider, record, creating))
for ident, geo in record.geo.items():
ret.add(_Route53GeoRecord(provider, record, ident, geo,
creating))
return ret
@classmethod
def new(cls, provider, record, hosted_zone_id, creating):
# Creates the RRSets that correspond to the given record
if getattr(record, 'dynamic', False):
ret = cls._new_dynamic(provider, record, hosted_zone_id, creating)
return ret
elif getattr(record, 'geo', False):
return cls._new_geo(provider, record, creating)
# Its a simple record that translates into a single RRSet
return set((_Route53Record(provider, record, creating),))
def __init__(self, provider, record, creating, fqdn_override=None):
self.fqdn = fqdn_override or record.fqdn
self._type = record._type
self.ttl = record.ttl
values_for = getattr(self, '_values_for_{}'.format(self._type))
self.values = values_for(record)
def mod(self, action, existing_rrsets):
return {
'Action': action,
'ResourceRecordSet': {
'Name': self.fqdn,
'ResourceRecords': [{'Value': v} for v in self.values],
'TTL': self.ttl,
'Type': self._type,
}
}
# NOTE: we're using __hash__ and ordering methods that consider
# _Route53Records equivalent if they have the same class, fqdn, and _type.
# Values are ignored. This is useful when computing diffs/changes.
def __hash__(self):
'sub-classes should never use this method'
return '{}:{}'.format(self.fqdn, self._type).__hash__()
def _equality_tuple(self):
'''Sub-classes should call up to this and return its value and add
any additional fields they need to hav considered.'''
return (self.__class__.__name__, self.fqdn, self._type)
def __repr__(self):
return '_Route53Record<{} {} {} {}>'.format(self.fqdn, self._type,
self.ttl, self.values)
def _value_convert_value(self, value, record):
return value
_value_convert_A = _value_convert_value
_value_convert_AAAA = _value_convert_value
_value_convert_NS = _value_convert_value
_value_convert_CNAME = _value_convert_value
_value_convert_PTR = _value_convert_value
def _values_for_values(self, record):
return record.values
_values_for_A = _values_for_values
_values_for_AAAA = _values_for_values
_values_for_NS = _values_for_values
def _value_convert_CAA(self, value, record):
return '{} {} "{}"'.format(value.flags, value.tag, value.value)
def _values_for_CAA(self, record):
return [self._value_convert_CAA(v, record) for v in record.values]
def _values_for_value(self, record):
return [record.value]
_values_for_CNAME = _values_for_value
_values_for_PTR = _values_for_value
def _value_convert_MX(self, value, record):
return '{} {}'.format(value.preference, value.exchange)
def _values_for_MX(self, record):
return [self._value_convert_MX(v, record) for v in record.values]
def _value_convert_NAPTR(self, value, record):
return '{} {} "{}" "{}" "{}" {}' \
.format(value.order, value.preference,
value.flags if value.flags else '',
value.service if value.service else '',
value.regexp if value.regexp else '',
value.replacement)
def _values_for_NAPTR(self, record):
return [self._value_convert_NAPTR(v, record) for v in record.values]
def _value_convert_quoted(self, value, record):
return record.chunked_value(value)
_value_convert_SPF = _value_convert_quoted
_value_convert_TXT = _value_convert_quoted
def _values_for_quoted(self, record):
return record.chunked_values
_values_for_SPF = _values_for_quoted
_values_for_TXT = _values_for_quoted
def _value_for_SRV(self, value, record):
return '{} {} {} {}'.format(value.priority, value.weight,
value.port, value.target)
def _values_for_SRV(self, record):
return [self._value_for_SRV(v, record) for v in record.values]
class _Route53DynamicPool(_Route53Record):
def __init__(self, provider, hosted_zone_id, record, pool_name, creating,
target_name=None):
fqdn_override = '_octodns-{}-pool.{}'.format(pool_name, record.fqdn)
super(_Route53DynamicPool, self) \
.__init__(provider, record, creating, fqdn_override=fqdn_override)
self.hosted_zone_id = hosted_zone_id
self.pool_name = pool_name
self.target_name = target_name
if target_name:
# We're pointing down the chain
self.target_dns_name = '_octodns-{}-pool.{}'.format(target_name,
record.fqdn)
else:
# We're a paimary, point at our values
self.target_dns_name = '_octodns-{}-value.{}'.format(pool_name,
record.fqdn)
@property
def mode(self):
return 'Secondary' if self.target_name else 'Primary'
@property
def identifer(self):
if self.target_name:
return '{}-{}-{}'.format(self.pool_name, self.mode,
self.target_name)
return '{}-{}'.format(self.pool_name, self.mode)
def mod(self, action, existing_rrsets):
return {
'Action': action,
'ResourceRecordSet': {
'AliasTarget': {
'DNSName': self.target_dns_name,
'EvaluateTargetHealth': True,
'HostedZoneId': self.hosted_zone_id,
},
'Failover': 'SECONDARY' if self.target_name else 'PRIMARY',
'Name': self.fqdn,
'SetIdentifier': self.identifer,
'Type': self._type,
}
}
def __hash__(self):
return '{}:{}:{}'.format(self.fqdn, self._type,
self.identifer).__hash__()
def __repr__(self):
return '_Route53DynamicPool<{} {} {} {}>' \
.format(self.fqdn, self._type, self.mode, self.target_dns_name)
class _Route53DynamicRule(_Route53Record):
def __init__(self, provider, hosted_zone_id, record, pool_name, index,
creating, geo=None):
super(_Route53DynamicRule, self).__init__(provider, record, creating)
self.hosted_zone_id = hosted_zone_id
self.geo = geo
self.pool_name = pool_name
self.index = index
self.target_dns_name = '_octodns-{}-pool.{}'.format(pool_name,
record.fqdn)
@property
def identifer(self):
return '{}-{}-{}'.format(self.index, self.pool_name, self.geo)
def mod(self, action, existing_rrsets):
rrset = {
'AliasTarget': {
'DNSName': self.target_dns_name,
'EvaluateTargetHealth': True,
'HostedZoneId': self.hosted_zone_id,
},
'GeoLocation': {
'CountryCode': '*'
},
'Name': self.fqdn,
'SetIdentifier': self.identifer,
'Type': self._type,
}
if self.geo:
geo = GeoCodes.parse(self.geo)
if geo['province_code']:
rrset['GeoLocation'] = {
'CountryCode': geo['country_code'],
'SubdivisionCode': geo['province_code'],
}
elif geo['country_code']:
rrset['GeoLocation'] = {
'CountryCode': geo['country_code']
}
else:
rrset['GeoLocation'] = {
'ContinentCode': geo['continent_code'],
}
return {
'Action': action,
'ResourceRecordSet': rrset,
}
def __hash__(self):
return '{}:{}:{}'.format(self.fqdn, self._type,
self.identifer).__hash__()
def __repr__(self):
return '_Route53DynamicRule<{} {} {} {} {}>' \
.format(self.fqdn, self._type, self.index, self.geo,
self.target_dns_name)
class _Route53DynamicValue(_Route53Record):
def __init__(self, provider, record, pool_name, value, weight, index,
creating):
fqdn_override = '_octodns-{}-value.{}'.format(pool_name, record.fqdn)
super(_Route53DynamicValue, self).__init__(provider, record, creating,
fqdn_override=fqdn_override)
self.pool_name = pool_name
self.index = index
value_convert = getattr(self, '_value_convert_{}'.format(record._type))
self.value = value_convert(value, record)
self.weight = weight
self.health_check_id = provider.get_health_check_id(record, self.value,
creating)
@property
def identifer(self):
return '{}-{:03d}'.format(self.pool_name, self.index)
def mod(self, action, existing_rrsets):
if action == 'DELETE':
# When deleting records try and find the original rrset so that
# we're 100% sure to have the complete & accurate data (this mostly
# ensures we have the right health check id when there's multiple
# potential matches)
for existing in existing_rrsets:
if self.fqdn == existing.get('Name') and \
self.identifer == existing.get('SetIdentifier', None):
return {
'Action': action,
'ResourceRecordSet': existing,
}
return {
'Action': action,
'ResourceRecordSet': {
'HealthCheckId': self.health_check_id,
'Name': self.fqdn,
'ResourceRecords': [{'Value': self.value}],
'SetIdentifier': self.identifer,
'TTL': self.ttl,
'Type': self._type,
'Weight': self.weight,
}
}
def __hash__(self):
return '{}:{}:{}'.format(self.fqdn, self._type,
self.identifer).__hash__()
def __repr__(self):
return '_Route53DynamicValue<{} {} {} {}>' \
.format(self.fqdn, self._type, self.identifer, self.value)
class _Route53GeoDefault(_Route53Record):
def mod(self, action, existing_rrsets):
return {
'Action': action,
'ResourceRecordSet': {
'Name': self.fqdn,
'GeoLocation': {
'CountryCode': '*'
},
'ResourceRecords': [{'Value': v} for v in self.values],
'SetIdentifier': 'default',
'TTL': self.ttl,
'Type': self._type,
}
}
def __hash__(self):
return '{}:{}:default'.format(self.fqdn, self._type).__hash__()
def __repr__(self):
return '_Route53GeoDefault<{} {} {} {}>'.format(self.fqdn, self._type,
self.ttl, self.values)
class _Route53GeoRecord(_Route53Record):
def __init__(self, provider, record, ident, geo, creating):
super(_Route53GeoRecord, self).__init__(provider, record, creating)
self.geo = geo
value = geo.values[0]
self.health_check_id = provider.get_health_check_id(record, value,
creating)
def mod(self, action, existing_rrsets):
geo = self.geo
set_identifier = geo.code
fqdn = self.fqdn
if action == 'DELETE':
# When deleting records try and find the original rrset so that
# we're 100% sure to have the complete & accurate data (this mostly
# ensures we have the right health check id when there's multiple
# potential matches)
for existing in existing_rrsets:
if fqdn == existing.get('Name') and \
set_identifier == existing.get('SetIdentifier', None):
return {
'Action': action,
'ResourceRecordSet': existing,
}
rrset = {
'Name': self.fqdn,
'GeoLocation': {
'CountryCode': '*'
},
'ResourceRecords': [{'Value': v} for v in geo.values],
'SetIdentifier': set_identifier,
'TTL': self.ttl,
'Type': self._type,
}
if self.health_check_id:
rrset['HealthCheckId'] = self.health_check_id
if geo.subdivision_code:
rrset['GeoLocation'] = {
'CountryCode': geo.country_code,
'SubdivisionCode': geo.subdivision_code
}
elif geo.country_code:
rrset['GeoLocation'] = {
'CountryCode': geo.country_code
}
else:
rrset['GeoLocation'] = {
'ContinentCode': geo.continent_code
}
return {
'Action': action,
'ResourceRecordSet': rrset,
}
def __hash__(self):
return '{}:{}:{}'.format(self.fqdn, self._type,
self.geo.code).__hash__()
def _equality_tuple(self):
return super(_Route53GeoRecord, self)._equality_tuple() + \
(self.geo.code,)
def __repr__(self):
return '_Route53GeoRecord<{} {} {} {} {}>'.format(self.fqdn,
self._type, self.ttl,
self.geo.code,
self.values)
def _mod_keyer(mod):
rrset = mod['ResourceRecordSet']
# Route53 requires that changes are ordered such that a target of an
# AliasTarget is created or upserted prior to the record that targets it.
# This is complicated by "UPSERT" appearing to be implemented as "DELETE"
# before all changes, followed by a "CREATE", internally in the AWS API.
# Because of this, we order changes as follows:
# - Delete any records that we wish to delete that are GEOS
# (because they are never targeted by anything)
# - Delete any records that we wish to delete that are SECONDARY
# (because they are no longer targeted by GEOS)
# - Delete any records that we wish to delete that are PRIMARY
# (because they are no longer targeted by SECONDARY)
# - Delete any records that we wish to delete that are VALUES
# (because they are no longer targeted by PRIMARY)
# - CREATE/UPSERT any records that are VALUES
# (because they don't depend on other records)
# - CREATE/UPSERT any records that are PRIMARY
# (because they always point to VALUES which now exist)
# - CREATE/UPSERT any records that are SECONDARY
# (because they now have PRIMARY records to target)
# - CREATE/UPSERT any records that are GEOS
# (because they now have all their PRIMARY pools to target)
# - :tada:
#
# In theory we could also do this based on actual target reference
# checking, but that's more complex. Since our rules have a known
# dependency order, we just rely on that.
# Get the unique ID from the name/id to get a consistent ordering.
if rrset.get('GeoLocation', False):
unique_id = rrset['SetIdentifier']
else:
if 'SetIdentifier' in rrset:
unique_id = '{}-{}'.format(rrset['Name'], rrset['SetIdentifier'])
else:
unique_id = rrset['Name']
# Prioritise within the action_priority, ensuring targets come first.
if rrset.get('GeoLocation', False):
# Geos reference pools, so they come last.
record_priority = 3
elif rrset.get('AliasTarget', False):
# We use an alias
if rrset.get('Failover', False) == 'SECONDARY':
# We're a secondary, which reference the primary (failover, P1).
record_priority = 2
else:
# We're a primary, we reference values (P0).
record_priority = 1
else:
# We're just a plain value, has no dependencies so first.
record_priority = 0
if mod['Action'] == 'DELETE':
# Delete things first, so we can never trounce our own additions
action_priority = 0
# Delete in the reverse order of priority, e.g. start with the deepest
# reference and work back to the values, rather than starting at the
# values (still ref'd).
record_priority = -record_priority
else:
# For CREATE and UPSERT, Route53 seems to treat them the same, so
# interleave these, keeping the reference order described above.
action_priority = 1
return (action_priority, record_priority, unique_id)
def _parse_pool_name(n):
# Parse the pool name out of _octodns-<pool-name>-pool...
return n.split('.', 1)[0][9:-5]
class Route53Provider(BaseProvider):
'''
AWS Route53 Provider
route53:
class: octodns.provider.route53.Route53Provider
# The AWS access key id
access_key_id:
# The AWS secret access key
secret_access_key:
# The AWS session token (optional)
# Only needed if using temporary security credentials
session_token:
Alternatively, you may leave out access_key_id, secret_access_key
and session_token.
This will result in boto3 deciding authentication dynamically.
In general the account used will need full permissions on Route53.
'''
SUPPORTS_GEO = True
SUPPORTS_DYNAMIC = True
SUPPORTS = set(('A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NAPTR', 'NS', 'PTR',
'SPF', 'SRV', 'TXT'))
# This should be bumped when there are underlying changes made to the
# health check config.
HEALTH_CHECK_VERSION = '0001'
def __init__(self, id, access_key_id=None, secret_access_key=None,
max_changes=1000, client_max_attempts=None,
session_token=None, delegation_set_id=None, *args, **kwargs):
self.max_changes = max_changes
self.delegation_set_id = delegation_set_id
_msg = 'access_key_id={}, secret_access_key=***, ' \
'session_token=***'.format(access_key_id)
use_fallback_auth = access_key_id is None and \
secret_access_key is None and session_token is None
if use_fallback_auth:
_msg = 'auth=fallback'
self.log = logging.getLogger('Route53Provider[{}]'.format(id))
self.log.debug('__init__: id=%s, %s', id, _msg)
super(Route53Provider, self).__init__(id, *args, **kwargs)
config = None
if client_max_attempts is not None:
self.log.info('__init__: setting max_attempts to %d',
client_max_attempts)
config = Config(retries={'max_attempts': client_max_attempts})
if use_fallback_auth:
self._conn = client('route53', config=config)
else:
self._conn = client('route53', aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key,
aws_session_token=session_token,
config=config)
self._r53_zones = None
self._r53_rrsets = {}
self._health_checks = None
@property
def r53_zones(self):
if self._r53_zones is None:
self.log.debug('r53_zones: loading')
zones = {}
more = True
start = {}
while more:
resp = self._conn.list_hosted_zones(**start)
for z in resp['HostedZones']:
zones[z['Name']] = z['Id']
more = resp['IsTruncated']
start['Marker'] = resp.get('NextMarker', None)
self._r53_zones = zones
return self._r53_zones
def _get_zone_id(self, name, create=False):
self.log.debug('_get_zone_id: name=%s', name)
if name in self.r53_zones:
id = self.r53_zones[name]
self.log.debug('_get_zone_id: id=%s', id)
return id
if create:
ref = uuid4().hex
del_set = self.delegation_set_id
self.log.debug('_get_zone_id: no matching zone, creating, '
'ref=%s', ref)
if del_set:
resp = self._conn.create_hosted_zone(Name=name,
CallerReference=ref,
DelegationSetId=del_set)
else:
resp = self._conn.create_hosted_zone(Name=name,
CallerReference=ref)
self.r53_zones[name] = id = resp['HostedZone']['Id']
return id
return None
def _parse_geo(self, rrset):
try:
loc = rrset['GeoLocation']
except KeyError:
# No geo loc
return
try:
return loc['ContinentCode']
except KeyError:
# Must be country
cc = loc['CountryCode']
if cc == '*':
# This is the default
return
cn = country_alpha2_to_continent_code(cc)
try:
return '{}-{}-{}'.format(cn, cc, loc['SubdivisionCode'])
except KeyError:
return '{}-{}'.format(cn, cc)
def _data_for_geo(self, rrset):
ret = {
'type': rrset['Type'],
'values': [v['Value'] for v in rrset['ResourceRecords']],
'ttl': int(rrset['TTL'])
}
geo = self._parse_geo(rrset)
if geo:
ret['geo'] = geo
return ret
_data_for_A = _data_for_geo
_data_for_AAAA = _data_for_geo
def _data_for_CAA(self, rrset):
values = []
for rr in rrset['ResourceRecords']:
flags, tag, value = rr['Value'].split()
values.append({
'flags': flags,
'tag': tag,
'value': value[1:-1],
})
return {
'type': rrset['Type'],
'values': values,
'ttl': int(rrset['TTL'])
}
def _data_for_single(self, rrset):
return {
'type': rrset['Type'],
'value': rrset['ResourceRecords'][0]['Value'],
'ttl': int(rrset['TTL'])
}
_data_for_PTR = _data_for_single
_data_for_CNAME = _data_for_single
_fix_semicolons = re.compile(r'(?<!\\);')
def _data_for_quoted(self, rrset):
return {
'type': rrset['Type'],
'values': [self._fix_semicolons.sub('\\;', rr['Value'][1:-1])
for rr in rrset['ResourceRecords']],
'ttl': int(rrset['TTL'])
}
_data_for_TXT = _data_for_quoted
_data_for_SPF = _data_for_quoted
def _data_for_MX(self, rrset):
values = []
for rr in rrset['ResourceRecords']:
preference, exchange = rr['Value'].split()
values.append({
'preference': preference,
'exchange': exchange,
})
return {
'type': rrset['Type'],
'values': values,
'ttl': int(rrset['TTL'])
}
def _data_for_NAPTR(self, rrset):
values = []
for rr in rrset['ResourceRecords']:
order, preference, flags, service, regexp, replacement = \
rr['Value'].split()
flags = flags[1:-1]
service = service[1:-1]
regexp = regexp[1:-1]
values.append({
'order': order,
'preference': preference,
'flags': flags,
'service': service,
'regexp': regexp,
'replacement': replacement,
})
return {
'type': rrset['Type'],
'values': values,
'ttl': int(rrset['TTL'])
}
def _data_for_NS(self, rrset):
return {
'type': rrset['Type'],
'values': [v['Value'] for v in rrset['ResourceRecords']],
'ttl': int(rrset['TTL'])
}
def _data_for_SRV(self, rrset):
values = []
for rr in rrset['ResourceRecords']:
priority, weight, port, target = rr['Value'].split()
values.append({
'priority': priority,
'weight': weight,
'port': port,
'target': target,
})
return {
'type': rrset['Type'],
'values': values,
'ttl': int(rrset['TTL'])
}
def _load_records(self, zone_id):
if zone_id not in self._r53_rrsets:
self.log.debug('_load_records: zone_id=%s loading', zone_id)
rrsets = []
more = True
start = {}
while more:
resp = \
self._conn.list_resource_record_sets(HostedZoneId=zone_id,
**start)
rrsets += resp['ResourceRecordSets']
more = resp['IsTruncated']
if more:
start = {
'StartRecordName': resp['NextRecordName'],
'StartRecordType': resp['NextRecordType'],
}
try:
start['StartRecordIdentifier'] = \
resp['NextRecordIdentifier']
except KeyError:
pass
self._r53_rrsets[zone_id] = rrsets
return self._r53_rrsets[zone_id]
def _data_for_dynamic(self, name, _type, rrsets):
# This converts a bunch of RRSets into their corresponding dynamic
# Record. It's used by populate.
pools = defaultdict(lambda: {'values': []})
# Data to build our rules will be collected here and "converted" into
# their final form below
rules = defaultdict(lambda: {'pool': None, 'geos': []})
# Base/empty data
data = {
'dynamic': {
'pools': pools,
'rules': [],
}
}
# For all the rrsets that comprise this dynamic record
for rrset in rrsets:
name = rrset['Name']
if '-pool.' in name:
# This is a pool rrset
pool_name = _parse_pool_name(name)
if pool_name == 'default':
# default becomes the base for the record and its
# value(s) will fill the non-dynamic values
data_for = getattr(self, '_data_for_{}'.format(_type))
data.update(data_for(rrset))
elif rrset['Failover'] == 'SECONDARY':
# This is a failover record, we'll ignore PRIMARY, but
# SECONDARY will tell us what the pool's fallback is
fallback_name = \
_parse_pool_name(rrset['AliasTarget']['DNSName'])
# Don't care about default fallbacks, anything else
# we'll record
if fallback_name != 'default':
pools[pool_name]['fallback'] = fallback_name
elif 'GeoLocation' in rrset:
# These are rules
_id = rrset['SetIdentifier']
# We record rule index as the first part of set-id, the 2nd
# part just ensures uniqueness across geos and is ignored
i = int(_id.split('-', 1)[0])
target_pool = _parse_pool_name(rrset['AliasTarget']['DNSName'])
# Record the pool
rules[i]['pool'] = target_pool
# Record geo if we have one
geo = self._parse_geo(rrset)
if geo:
rules[i]['geos'].append(geo)
else:
# These are the pool value(s)
# Grab the pool name out of the SetIdentifier, format looks
# like ...-000 where 000 is a zero-padded index for the value
# it's ignored only used to make sure the value is unique
pool_name = rrset['SetIdentifier'][:-4]
value = rrset['ResourceRecords'][0]['Value']
pools[pool_name]['values'].append({
'value': value,
'weight': rrset['Weight'],
})
# Convert our map of rules into an ordered list now that we have all
# the data
for _, rule in sorted(rules.items()):
r = {
'pool': rule['pool'],
}
geos = sorted(rule['geos'])
if geos:
r['geos'] = geos
data['dynamic']['rules'].append(r)
return data
def populate(self, zone, target=False, lenient=False):
self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name,
target, lenient)
before = len(zone.records)
exists = False
zone_id = self._get_zone_id(zone.name)
if zone_id:
exists = True
records = defaultdict(lambda: defaultdict(list))
dynamic = defaultdict(lambda: defaultdict(list))
for rrset in self._load_records(zone_id):
record_name = zone.hostname_from_fqdn(rrset['Name'])
record_name = _octal_replace(record_name)
record_type = rrset['Type']
if record_type not in self.SUPPORTS:
# Skip stuff we don't support
continue
if record_name.startswith('_octodns-'):
# Part of a dynamic record
try:
record_name = record_name.split('.', 1)[1]
except IndexError:
record_name = ''
dynamic[record_name][record_type].append(rrset)
continue
elif 'AliasTarget' in rrset:
if rrset['AliasTarget']['DNSName'].startswith('_octodns-'):
# Part of a dynamic record
dynamic[record_name][record_type].append(rrset)
else:
# Alias records are Route53 specific and are not
# portable, so we need to skip them
self.log.warning("%s is an Alias record. Skipping..."
% rrset['Name'])
continue
# A basic record (potentially including geo)
data = getattr(self, '_data_for_{}'.format(record_type))(rrset)
records[record_name][record_type].append(data)
# Convert the dynamic rrsets to Records
for name, types in dynamic.items():
for _type, rrsets in types.items():
data = self._data_for_dynamic(name, _type, rrsets)
record = Record.new(zone, name, data, source=self,
lenient=lenient)
zone.add_record(record, lenient=lenient)
# Convert the basic (potentially with geo) rrsets to records
for name, types in records.items():
for _type, data in types.items():
if len(data) > 1:
# Multiple data indicates a record with GeoDNS, convert
# them data into the format we need
geo = {}
for d in data:
try:
geo[d['geo']] = d['values']
except KeyError:
primary = d
data = primary
data['geo'] = geo
else:
data = data[0]
record = Record.new(zone, name, data, source=self,
lenient=lenient)
zone.add_record(record, lenient=lenient)
self.log.info('populate: found %s records, exists=%s',
len(zone.records) - before, exists)
return exists
def _gen_mods(self, action, records, existing_rrsets):
'''
Turns `_Route53*`s in to `change_resource_record_sets` `Changes`
'''