-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path__init__.py
1925 lines (1666 loc) · 69.3 KB
/
__init__.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 collections import OrderedDict, defaultdict
from collections.abc import Mapping
from itertools import chain
from logging import getLogger
from time import sleep
from uuid import uuid4
from ns1 import NS1
from ns1.rest.errors import RateLimitException, ResourceException
from octodns.provider import ProviderException, SupportsException
from octodns.provider.base import BaseProvider
from octodns.record import Create, Record, Update
from octodns.record.geo import GeoCodes
from octodns.record.geo_data import geo_data
# TODO: remove __VERSION__ with the next major version release
__version__ = __VERSION__ = '0.0.7'
def _ensure_endswith_dot(string):
return string if string.endswith('.') else f'{string}.'
class Ns1Exception(ProviderException):
pass
class Ns1Client(object):
log = getLogger('NS1Client')
def __init__(
self, api_key, parallelism=None, retry_count=4, client_config=None
):
self.log.debug(
'__init__: parallelism=%s, retry_count=%d, client_config=%s',
parallelism,
retry_count,
client_config,
)
self.retry_count = retry_count
client = NS1(apiKey=api_key)
# NS1 rate limits via a "token bucket" scheme, and provides information
# about rate limiting in headers on responses. Token bucket can be
# thought of as an initially "full" bucket, where, if not full, tokens
# are added at some rate. This allows "bursting" requests until the
# bucket is empty, after which, you are limited to the rate of token
# replenishment.
# There are a couple of "strategies" built into the SDK to avoid 429s
# from rate limiting. Since octodns operates concurrently via
# `max_workers`, a concurrent strategy seems appropriate.
# This strategy does nothing until the remaining requests are equal to
# or less than our `parallelism`, after which, each process will sleep
# for the token replenishment interval times parallelism.
# For example, if we can make 10 requests in 60 seconds, a token is
# replenished every 6 seconds. If parallelism is 3, we will burst 7
# requests, and subsequently each process will sleep for 18 seconds
# before making another request.
# In general, parallelism should match the number of workers.
if parallelism is not None:
client.config['rate_limit_strategy'] = 'concurrent'
client.config['parallelism'] = parallelism
# The list of records for a zone is paginated at around ~2.5k records,
# this tells the client to handle any of that transparently and ensure
# we get the full list of records.
client.config['follow_pagination'] = True
# additional options or overrides
if isinstance(client_config, Mapping):
for k, v in client_config.items():
client.config[k] = v
self._client = client
self._records = client.records()
self._zones = client.zones()
self._monitors = client.monitors()
self._notifylists = client.notifylists()
self._datasource = client.datasource()
self._datafeed = client.datafeed()
self.reset_caches()
def reset_caches(self):
self._datasource_id = None
self._feeds_for_monitors = None
self._monitors_cache = None
self._notifylists_cache = None
self._zones_cache = {}
self._records_cache = {}
def update_record_cache(func):
def call(self, zone, domain, _type, **params):
if zone in self._zones_cache:
# remove record's zone from cache
del self._zones_cache[zone]
cached = self._records_cache.setdefault(zone, {}).setdefault(
domain, {}
)
if _type in cached:
# remove record from cache
del cached[_type]
# write record to cache if its not a delete
new_record = func(self, zone, domain, _type, **params)
if new_record:
cached[_type] = new_record
return new_record
return call
def read_or_set_record_cache(func):
def call(self, zone, domain, _type):
cached = self._records_cache.setdefault(zone, {}).setdefault(
domain, {}
)
if _type not in cached:
cached[_type] = func(self, zone, domain, _type)
return cached[_type]
return call
@property
def datasource_id(self):
if self._datasource_id is None:
name = 'octoDNS NS1 Data Source'
source = None
for candidate in self.datasource_list():
if candidate['name'] == name:
# Found it
source = candidate
break
if source is None:
self.log.info('datasource_id: creating datasource %s', name)
# We need to create it
source = self.datasource_create(
name=name, sourcetype='nsone_monitoring'
)
self.log.info('datasource_id: id=%s', source['id'])
self._datasource_id = source['id']
return self._datasource_id
@property
def feeds_for_monitors(self):
if self._feeds_for_monitors is None:
self.log.debug('feeds_for_monitors: fetching & building')
self._feeds_for_monitors = {
f['config']['jobid']: f['id']
for f in self.datafeed_list(self.datasource_id)
}
return self._feeds_for_monitors
@property
def monitors(self):
if self._monitors_cache is None:
self.log.debug('monitors: fetching & building')
self._monitors_cache = {m['id']: m for m in self.monitors_list()}
return self._monitors_cache
@property
def notifylists(self):
if self._notifylists_cache is None:
self.log.debug('notifylists: fetching & building')
self._notifylists_cache = {
l['name']: l for l in self.notifylists_list()
}
return self._notifylists_cache
def datafeed_create(self, sourceid, name, config):
ret = self._try(self._datafeed.create, sourceid, name, config)
self.feeds_for_monitors[config['jobid']] = ret['id']
return ret
def datafeed_delete(self, sourceid, feedid):
ret = self._try(self._datafeed.delete, sourceid, feedid)
self._feeds_for_monitors = {
k: v for k, v in self._feeds_for_monitors.items() if v != feedid
}
return ret
def datafeed_list(self, sourceid):
return self._try(self._datafeed.list, sourceid)
def datasource_create(self, **body):
return self._try(self._datasource.create, **body)
def datasource_list(self):
return self._try(self._datasource.list)
def monitors_create(self, **params):
body = {}
ret = self._try(self._monitors.create, body, **params)
self.monitors[ret['id']] = ret
return ret
def monitors_delete(self, jobid):
ret = self._try(self._monitors.delete, jobid)
self.monitors.pop(jobid)
return ret
def monitors_list(self):
return self._try(self._monitors.list)
def monitors_update(self, job_id, **params):
body = {}
ret = self._try(self._monitors.update, job_id, body, **params)
self.monitors[ret['id']] = ret
return ret
def notifylists_delete(self, nlid):
for name, nl in self.notifylists.items():
if nl['id'] == nlid:
del self._notifylists_cache[name]
break
return self._try(self._notifylists.delete, nlid)
def notifylists_create(self, **body):
nl = self._try(self._notifylists.create, body)
# cache it
self.notifylists[nl['name']] = nl
return nl
def notifylists_list(self):
return self._try(self._notifylists.list)
@update_record_cache
def records_create(self, zone, domain, _type, **params):
return self._try(self._records.create, zone, domain, _type, **params)
@update_record_cache
def records_delete(self, zone, domain, _type):
return self._try(self._records.delete, zone, domain, _type)
@read_or_set_record_cache
def records_retrieve(self, zone, domain, _type):
return self._try(self._records.retrieve, zone, domain, _type)
@update_record_cache
def records_update(self, zone, domain, _type, **params):
return self._try(self._records.update, zone, domain, _type, **params)
def zones_create(self, name):
self._zones_cache[name] = self._try(self._zones.create, name)
return self._zones_cache[name]
def zones_retrieve(self, name):
if name not in self._zones_cache:
self._zones_cache[name] = self._try(self._zones.retrieve, name)
return self._zones_cache[name]
def zones_list(self):
# TODO: explore caching all of these if they have sufficient details
return self._try(self._zones.list)
def _try(self, method, *args, **kwargs):
tries = self.retry_count
while True: # We'll raise to break after our tries expire
try:
return method(*args, **kwargs)
except RateLimitException as e:
if tries <= 1:
raise
period = float(e.period)
self.log.warning(
'rate limit encountered, pausing '
'for %ds and trying again, %d remaining',
period,
tries,
)
sleep(period)
tries -= 1
except ResourceException as e:
if not e.response or e.response.status_code != 404:
self.log.exception(
"_try: method=%s, args=%s, response=%s, body=%s",
method.__name__,
str(args),
e.response,
e.body,
)
raise
class Ns1Provider(BaseProvider):
SUPPORTS_GEO = True
SUPPORTS_DYNAMIC = True
SUPPORTS_POOL_VALUE_STATUS = True
SUPPORTS_DYNAMIC_SUBNETS = True
SUPPORTS_MULTIVALUE_PTR = True
SUPPORTS_ROOT_NS = True
SUPPORTS = set(
(
'A',
'AAAA',
'ALIAS',
'CAA',
'CNAME',
'DNAME',
'DS',
'MX',
'NAPTR',
'NS',
'PTR',
'SPF',
'SRV',
'TLSA',
'TXT',
'URLFWD',
)
)
ZONE_NOT_FOUND_MESSAGE = 'server error: zone not found'
SHARED_NOTIFYLIST_NAME = 'octoDNS NS1 Notify List'
@property
def _UP_FILTER(self):
return {'config': {}, 'filter': 'up'}
@property
def _REGION_FILTER(self):
return {
'config': {'remove_no_georegion': True},
'filter': u'geofence_regional',
}
@property
def _COUNTRY_FILTER(self):
return {
'config': {'remove_no_location': True},
'filter': u'geofence_country',
}
@property
def _SUBNET_FILTER(self):
return {
'config': {'remove_no_ip_prefixes': True},
'filter': u'netfence_prefix',
}
# In the NS1 UI/portal, this filter is called "SELECT FIRST GROUP" though
# the filter name in the NS1 api is 'select_first_region'
@property
def _SELECT_FIRST_REGION_FILTER(self):
return {'config': {}, 'filter': u'select_first_region'}
@property
def _PRIORITY_FILTER(self):
return {'config': {'eliminate': u'1'}, 'filter': 'priority'}
@property
def _WEIGHTED_SHUFFLE_FILTER(self):
return {'config': {}, 'filter': u'weighted_shuffle'}
@property
def _SELECT_FIRST_N_FILTER(self):
return {'config': {'N': u'1'}, 'filter': u'select_first_n'}
@property
def _BASIC_FILTER_CHAIN(self):
return [
self._UP_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_REGION(self):
return [
self._UP_FILTER,
self._REGION_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_COUNTRY(self):
return [
self._UP_FILTER,
self._COUNTRY_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_SUBNET(self):
return [
self._UP_FILTER,
self._SUBNET_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_REGION_AND_COUNTRY(self):
return [
self._UP_FILTER,
self._COUNTRY_FILTER,
self._REGION_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_REGION_AND_SUBNET(self):
return [
self._UP_FILTER,
self._SUBNET_FILTER,
self._REGION_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_COUNTRY_AND_SUBNET(self):
return [
self._UP_FILTER,
self._SUBNET_FILTER,
self._COUNTRY_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
@property
def _FILTER_CHAIN_WITH_REGION_AND_COUNTRY_AND_SUBNET(self):
return [
self._UP_FILTER,
self._SUBNET_FILTER,
self._COUNTRY_FILTER,
self._REGION_FILTER,
self._SELECT_FIRST_REGION_FILTER,
self._PRIORITY_FILTER,
self._WEIGHTED_SHUFFLE_FILTER,
self._SELECT_FIRST_N_FILTER,
]
_REGION_TO_CONTINENT = {
'AFRICA': 'AF',
'ASIAPAC': 'AS',
'EUROPE': 'EU',
'SOUTH-AMERICA': 'SA',
# continent NA has been handled as part of Geofence Country filter
# starting from v0.9.13. These below US-* just need to continue to
# exist here so it doesn't break the ugrade path
'US-CENTRAL': 'NA',
'US-EAST': 'NA',
'US-WEST': 'NA',
}
_CONTINENT_TO_REGIONS = {
'AF': ('AFRICA',),
'EU': ('EUROPE',),
'SA': ('SOUTH-AMERICA',),
}
# Necessary for handling unsupported continents in _CONTINENT_TO_REGIONS
_CONTINENT_TO_LIST_OF_COUNTRIES = {
'AS': set(geo_data['AS'].keys()),
'OC': set(geo_data['OC'].keys()),
'NA': set(geo_data['NA'].keys()),
}
def __init__(
self,
id,
api_key,
retry_count=4,
monitor_regions=[],
parallelism=None,
client_config=None,
shared_notifylist=False,
use_http_monitors=False,
default_healthcheck_http_version="HTTP/1.0",
*args,
**kwargs,
):
self.log = getLogger(f'Ns1Provider[{id}]')
self.log.debug(
'__init__: id=%s, api_key=***, retry_count=%d, '
'monitor_regions=%s, parallelism=%s, client_config=%s, '
'shared_notifylist=%s, use_http_monitors=%s, '
'default_healthcheck_http_version=%s',
id,
retry_count,
monitor_regions,
parallelism,
client_config,
shared_notifylist,
use_http_monitors,
default_healthcheck_http_version,
)
super().__init__(id, *args, **kwargs)
self.monitor_regions = monitor_regions
self.shared_notifylist = shared_notifylist
self.use_http_monitors = use_http_monitors
self.record_filters = dict()
self._client = Ns1Client(
api_key, parallelism, retry_count, client_config
)
self.default_healthcheck_http_version = default_healthcheck_http_version
def _sanitize_disabled_in_filter_config(self, filter_cfg):
# remove disabled=False from filters
for filter in filter_cfg:
if 'disabled' in filter and filter['disabled'] is False:
del filter['disabled']
return filter_cfg
def _valid_filter_config(self, filter_cfg):
self._sanitize_disabled_in_filter_config(filter_cfg)
has_region = self._REGION_FILTER in filter_cfg
has_country = self._COUNTRY_FILTER in filter_cfg
has_subnet = self._SUBNET_FILTER in filter_cfg
expected_filter_cfg = self._get_updated_filter_chain(
has_region, has_country, has_subnet
)
return filter_cfg == expected_filter_cfg
def _get_updated_filter_chain(self, has_region, has_country, has_subnet):
if has_region and has_country and has_subnet:
filter_chain = self._FILTER_CHAIN_WITH_REGION_AND_COUNTRY_AND_SUBNET
elif has_region and has_country:
filter_chain = self._FILTER_CHAIN_WITH_REGION_AND_COUNTRY
elif has_region and has_subnet:
filter_chain = self._FILTER_CHAIN_WITH_REGION_AND_SUBNET
elif has_country and has_subnet:
filter_chain = self._FILTER_CHAIN_WITH_COUNTRY_AND_SUBNET
elif has_region:
filter_chain = self._FILTER_CHAIN_WITH_REGION
elif has_country:
filter_chain = self._FILTER_CHAIN_WITH_COUNTRY
elif has_subnet:
filter_chain = self._FILTER_CHAIN_WITH_SUBNET
else:
filter_chain = self._BASIC_FILTER_CHAIN
return filter_chain
def _encode_notes(self, data):
return ' '.join([f'{k}:{v}' for k, v in sorted(data.items())])
def _parse_notes(self, note):
data = {}
if note:
for piece in note.split(' '):
try:
k, v = piece.split(':', 1)
except ValueError:
continue
try:
v = int(v)
except ValueError:
pass
data[k] = v if v != '' else None
return data
def _data_for_geo_A(self, _type, record):
# record meta (which would include geo information is only
# returned when getting a record's detail, not from zone detail
geo = defaultdict(list)
data = {'ttl': record['ttl'], 'type': _type}
values, codes = [], []
for answer in record.get('answers', []):
meta = answer.get('meta', {})
if meta:
# country + state and country + province are allowed
# in that case though, supplying a state/province would
# be redundant since the country would supercede in when
# resolving the record. it is syntactically valid, however.
country = meta.get('country', [])
us_state = meta.get('us_state', [])
ca_province = meta.get('ca_province', [])
for cntry in country:
key = GeoCodes.country_to_code(cntry)
geo[key].extend(answer['answer'])
for state in us_state:
key = f'NA-US-{state}'
geo[key].extend(answer['answer'])
for province in ca_province:
key = f'NA-CA-{province}'
geo[key].extend(answer['answer'])
for code in meta.get('iso_region_code', []):
key = code
geo[key].extend(answer['answer'])
else:
values.extend(answer['answer'])
codes.append([])
values = [str(x) for x in values]
geo = OrderedDict({str(k): [str(x) for x in v] for k, v in geo.items()})
data['values'] = values
data['geo'] = geo
return data
def _parse_dynamic_pool_name(self, pool_name):
catchall_prefix = 'catchall__'
if pool_name.startswith(catchall_prefix):
# Special case for the old-style catchall prefix
return pool_name[len(catchall_prefix) :]
try:
pool_name, _ = pool_name.rsplit('__', 1)
except ValueError:
pass
return pool_name
def _parse_pools(self, answers):
# All regions (pools) will include the list of default values
# (eventually) at higher priorities, we'll just add them to this set to
# we'll have the complete collection.
default = set()
# Fill out the pools by walking the answers and looking at their
# region (< v0.9.11) or notes (> v0.9.11).
pools = defaultdict(lambda: {'fallback': None, 'values': []})
for answer in answers:
meta = answer['meta']
notes = self._parse_notes(meta.get('note', ''))
value = str(answer['answer'][0])
if notes.get('from', False) == '--default--':
# It's a final/default value, record it and move on
default.add(value)
continue
# NS1 pool names can be found in notes > v0.9.11, in order to allow
# us to find fallback-only pools/values. Before that we used
# `region` (group name in the UI) and only paid attention to
# priority=1 (first level)
notes_pool_name = notes.get('pool', None)
if notes_pool_name is None:
# < v0.9.11
if meta['priority'] != 1:
# Ignore all but priority 1
continue
# And use region's name as the pool name
pool_name = self._parse_dynamic_pool_name(answer['region'])
else:
# > v0.9.11, use the notes-based name and consider all values
pool_name = notes_pool_name
pool = pools[pool_name]
value_dict = {'value': value, 'weight': int(meta.get('weight', 1))}
if isinstance(meta['up'], bool):
value_dict['status'] = 'up' if meta['up'] else 'down'
if value_dict not in pool['values']:
# If we haven't seen this value before add it to the pool
pool['values'].append(value_dict)
# If there's a fallback recorded in the value for its pool go ahead
# and use it, another v0.9.11 thing
fallback = notes.get('fallback', None)
if fallback is not None:
pool['fallback'] = fallback
# Order and convert to a list
default = sorted(default)
return default, pools
def _parse_rule_geos(self, meta, notes):
geos = set()
for georegion in meta.get('georegion', []):
geos.add(self._REGION_TO_CONTINENT[georegion])
# Countries are easy enough to map, we just have to find their
# continent
#
# NOTE: Some continents need special handling since NS1
# does not supprt them as regions. These are defined under
# _CONTINENT_TO_LIST_OF_COUNTRIES. So the countries for these
# regions will be present in meta['country']. If all the countries
# in _CONTINENT_TO_LIST_OF_COUNTRIES[<region>] list are found,
# set the continent as the region and remove individual countries
# continents that don't have all countries here because a subset of
# them were used in another rule, but we still need this rule to use
# continent instead of the remaining subset of its countries
continents_from_notes = set(notes.get('continents', '').split(','))
special_continents = dict()
for country in meta.get('country', []):
geo_code = GeoCodes.country_to_code(country)
con = GeoCodes.parse(geo_code)['continent_code']
if con in self._CONTINENT_TO_LIST_OF_COUNTRIES:
special_continents.setdefault(con, set()).add(country)
else:
geos.add(geo_code)
for continent, countries in special_continents.items():
if (
countries == self._CONTINENT_TO_LIST_OF_COUNTRIES[continent]
or continent in continents_from_notes
):
# All countries found or continent in notes, so add it to geos
geos.add(continent)
else:
# Partial countries found, so just add them as-is to geos
for c in countries:
geos.add(f'{continent}-{c}')
# States and provinces are easy too,
# just assume NA-US or NA-CA
for state in meta.get('us_state', []):
geos.add(f'NA-US-{state}')
for province in meta.get('ca_province', []):
geos.add(f'NA-CA-{province}')
return geos
def _parse_rules(self, pools, regions):
# The regions objects map to rules, but it's a bit fuzzy since they're
# tied to pools on the NS1 side, e.g. we can only have 1 rule per pool,
# that may eventually run into problems, but I don't have any use-cases
# examples currently where it would
rules = {}
for pool_name, region in sorted(regions.items()):
# Get the actual pool name by removing the type
pool_name = self._parse_dynamic_pool_name(pool_name)
meta = region['meta']
notes = self._parse_notes(meta.get('note', ''))
# The group notes field in the UI is a `note` on the region here,
# that's where we can find our pool's fallback in < v0.9.11 anyway
if 'fallback' in notes:
# set the fallback pool name
pools[pool_name]['fallback'] = notes['fallback']
rule_order = notes['rule-order']
try:
rule = rules[rule_order]
except KeyError:
rule = {'pool': pool_name, '_order': rule_order}
rules[rule_order] = rule
geos = self._parse_rule_geos(meta, notes)
if geos:
# There are geos, combine them with any existing geos for this
# pool and recorded the sorted unique set of them
rule['geos'] = sorted(set(rule.get('geos', [])) | geos)
subnets = set(meta.get('ip_prefixes', []))
if subnets:
rule['subnets'] = sorted(subnets)
# Convert to list and order
rules = sorted(rules.values(), key=lambda r: (r['_order'], r['pool']))
return rules
def _data_for_dynamic(self, _type, record):
# Cache record filters for later use
record_filters = self.record_filters.setdefault(record['domain'], {})
record_filters[_type] = record['filters']
default, pools = self._parse_pools(record['answers'])
rules = self._parse_rules(pools, record['regions'])
data = {
'dynamic': {'pools': pools, 'rules': rules},
'ttl': record['ttl'],
'type': _type,
}
if _type == 'CNAME':
data['value'] = default[0]
else:
data['values'] = default
return data
def _data_for_A(self, _type, record):
if record.get('tier', 1) > 1:
# Advanced record, see if it's first answer has a note
try:
first_answer_note = record['answers'][0]['meta']['note']
except (IndexError, KeyError):
first_answer_note = ''
# If that note includes a `from` (pool name) it's a dynamic record
if 'from:' in first_answer_note:
return self._data_for_dynamic(_type, record)
# If not it's an old geo record
return self._data_for_geo_A(_type, record)
# This is a basic record, just convert it
return {
'ttl': record['ttl'],
'type': _type,
'values': [str(x) for x in record['short_answers']],
}
_data_for_AAAA = _data_for_A
def _data_for_SPF(self, _type, record):
values = [v.replace(';', '\\;') for v in record['short_answers']]
return {'ttl': record['ttl'], 'type': _type, 'values': values}
_data_for_TXT = _data_for_SPF
def _data_for_CAA(self, _type, record):
values = []
for answer in record['short_answers']:
flags, tag, value = answer.split(' ', 2)
values.append({'flags': flags, 'tag': tag, 'value': value})
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_CNAME(self, _type, record):
if record.get('tier', 1) > 1:
# Advanced record, see if it's first answer has a note
try:
first_answer_note = record['answers'][0]['meta']['note']
except (IndexError, KeyError):
first_answer_note = ''
# If that note includes a `pool` it's a valid dynamic record
if 'pool:' in first_answer_note:
return self._data_for_dynamic(_type, record)
# If not, it can't be parsed. Let it be an empty record
self.log.warning(
'Cannot parse %s dynamic record due to missing '
'pool name in first answer note, treating it as '
'an empty record',
record['domain'],
)
value = None
else:
try:
value = record['short_answers'][0]
except IndexError:
value = None
return {'ttl': record['ttl'], 'type': _type, 'value': value}
_data_for_ALIAS = _data_for_CNAME
_data_for_DNAME = _data_for_CNAME
def _data_for_MX(self, _type, record):
values = []
for answer in record['short_answers']:
preference, exchange = answer.split(' ', 1)
values.append({'preference': preference, 'exchange': exchange})
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_NAPTR(self, _type, record):
values = []
for answer in record['short_answers']:
(order, preference, flags, service, regexp, replacement) = (
answer.split(' ', 5)
)
values.append(
{
'flags': flags,
'order': order,
'preference': preference,
'regexp': regexp,
'replacement': replacement,
'service': service,
}
)
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_NS(self, _type, record):
return {
'ttl': record['ttl'],
'type': _type,
'values': record['short_answers'],
}
_data_for_PTR = _data_for_NS
def _data_for_SRV(self, _type, record):
values = []
for answer in record['short_answers']:
priority, weight, port, target = answer.split(' ', 3)
values.append(
{
'priority': priority,
'weight': weight,
'port': port,
'target': target,
}
)
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_URLFWD(self, _type, record):
values = []
for answer in record['short_answers']:
path, target, code, masking, query = answer.split(' ', 4)
values.append(
{
'path': path,
'target': target,
'code': code,
'masking': masking,
'query': query,
}
)
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_DS(self, _type, record):
values = []
for answer in record['short_answers']:
key_tag, algorithm, digest_type, digest = answer.split(' ', 3)
values.append(
{
'key_tag': key_tag,
'algorithm': algorithm,
'digest_type': digest_type,
'digest': digest,
}
)
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def _data_for_TLSA(self, _type, record):
values = []
for answer in record['short_answers']:
(
certificate_usage,
selector,
matching_type,
certificate_association_data,
) = answer.split(' ', 3)
values.append(
{
'certificate_usage': certificate_usage,
'selector': selector,
'matching_type': matching_type,
'certificate_association_data': certificate_association_data,
}
)
return {'ttl': record['ttl'], 'type': _type, 'values': values}
def list_zones(self):
return sorted([f'{z["zone"]}.' for z in self._client.zones_list()])
def populate(self, zone, target=False, lenient=False):
self.log.debug(
'populate: name=%s, target=%s, lenient=%s',
zone.name,
target,
lenient,
)
try:
ns1_zone_name = zone.name[:-1]
ns1_zone = self._client.zones_retrieve(ns1_zone_name)
records = []
geo_records = []
# change answers for certain types to always be absolute
for record in ns1_zone['records']:
if record['type'] in [
'ALIAS',
'CNAME',
'MX',
'NS',
'PTR',
'SRV',
]:
record['short_answers'] = [
_ensure_endswith_dot(a)
for a in record.get('short_answers', [])
]
if record.get('tier', 1) > 1:
# Need to get the full record data for geo records
record = self._client.records_retrieve(
ns1_zone_name, record['domain'], record['type']
)
geo_records.append(record)
else: