/
service.py
2969 lines (2319 loc) · 103 KB
/
service.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
# Copyright 2012 Managed I.T.
# Copyright 2013 - 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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.
import re
import collections
import copy
import functools
import threading
import itertools
import string
import signal
import random
from random import SystemRandom
import time
import six
from eventlet import tpool
from dns import zone as dnszone
from dns import exception as dnsexception
from oslo_config import cfg
import oslo_messaging as messaging
from oslo_log import log as logging
from designate import context as dcontext
from designate import coordination
from designate import exceptions
from designate import dnsutils
from designate import network_api
from designate import notifications
from designate import objects
from designate import policy
from designate import quota
from designate import rpc
from designate import service
from designate import scheduler
from designate import storage
from designate import utils
from designate.mdns import rpcapi as mdns_rpcapi
from designate.storage import transaction
from designate.worker import rpcapi as worker_rpcapi
LOG = logging.getLogger(__name__)
ZONE_LOCKS = threading.local()
NOTIFICATION_BUFFER = threading.local()
def synchronized_zone(zone_arg=1, new_zone=False):
"""Ensures only a single operation is in progress for each zone
A Decorator which ensures only a single operation can be happening
on a single zone at once, within the current designate-central instance
"""
def outer(f):
@functools.wraps(f)
def sync_wrapper(self, *args, **kwargs):
if not hasattr(ZONE_LOCKS, 'held'):
# Create the held set if necessary
ZONE_LOCKS.held = set()
zone_id = None
if 'zone_id' in kwargs:
zone_id = kwargs['zone_id']
elif 'zone' in kwargs:
zone_id = kwargs['zone'].id
elif 'recordset' in kwargs:
zone_id = kwargs['recordset'].zone_id
elif 'record' in kwargs:
zone_id = kwargs['record'].zone_id
# The various objects won't always have an ID set, we should
# attempt to locate an Object containing the ID.
if zone_id is None:
for arg in itertools.chain(kwargs.values(), args):
if isinstance(arg, objects.Zone):
zone_id = arg.id
if zone_id:
break
elif (isinstance(arg, objects.RecordSet) or
isinstance(arg, objects.Record) or
isinstance(arg, objects.ZoneTransferRequest) or
isinstance(arg, objects.ZoneTransferAccept)):
zone_id = arg.zone_id
if zone_id:
break
# If we still don't have an ID, find the Nth argument as
# defined by the zone_arg decorator option.
if not zone_id and len(args) > zone_arg:
zone_id = args[zone_arg]
if isinstance(zone_id, objects.Zone):
# If the value is a Zone object, extract it's ID.
zone_id = zone_id.id
if new_zone and not zone_id:
lock_name = 'create-new-zone'
elif not new_zone and zone_id:
lock_name = 'zone-%s' % zone_id
else:
raise Exception('Failed to determine zone id for '
'synchronized operation')
if zone_id in ZONE_LOCKS.held:
return f(self, *args, **kwargs)
with self.coordination.get_lock(lock_name):
try:
ZONE_LOCKS.held.add(zone_id)
return f(self, *args, **kwargs)
finally:
ZONE_LOCKS.held.remove(zone_id)
sync_wrapper.__wrapped_function = f
sync_wrapper.__wrapper_name = 'synchronized_zone'
return sync_wrapper
return outer
def notification(notification_type):
def outer(f):
@functools.wraps(f)
def notification_wrapper(self, *args, **kwargs):
if not hasattr(NOTIFICATION_BUFFER, 'queue'):
# Create the notifications queue if necessary
NOTIFICATION_BUFFER.stack = 0
NOTIFICATION_BUFFER.queue = collections.deque()
NOTIFICATION_BUFFER.stack += 1
try:
# Find the context argument
context = dcontext.DesignateContext.\
get_context_from_function_and_args(f, args, kwargs)
# Call the wrapped function
result = f(self, *args, **kwargs)
# Feed the args/result to a notification plugin
# to determine what is emitted
payloads = notifications.get_plugin().emit(
notification_type, context, result, args, kwargs)
# Enqueue the notification
for payload in payloads:
LOG.debug('Queueing notification for %(type)s ',
{'type': notification_type})
NOTIFICATION_BUFFER.queue.appendleft(
(context, notification_type, payload,))
return result
finally:
NOTIFICATION_BUFFER.stack -= 1
if NOTIFICATION_BUFFER.stack == 0:
LOG.debug('Emitting %(count)d notifications',
{'count': len(NOTIFICATION_BUFFER.queue)})
# Send the queued notifications, in order.
for value in NOTIFICATION_BUFFER.queue:
LOG.debug('Emitting %(type)s notification',
{'type': value[1]})
self.notifier.info(value[0], value[1], value[2])
# Reset the queue
NOTIFICATION_BUFFER.queue.clear()
return notification_wrapper
return outer
class Service(service.RPCService):
RPC_API_VERSION = '6.2'
target = messaging.Target(version=RPC_API_VERSION)
def __init__(self):
self._scheduler = None
self._storage = None
self._quota = None
super(Service, self).__init__(
self.service_name, cfg.CONF['service:central'].topic,
threads=cfg.CONF['service:central'].threads,
)
self.coordination = coordination.Coordination(
self.service_name, self.tg
)
self.network_api = network_api.get_network_api(cfg.CONF.network_api)
@property
def scheduler(self):
if not self._scheduler:
# Get a scheduler instance
self._scheduler = scheduler.get_scheduler(storage=self.storage)
return self._scheduler
@property
def quota(self):
if not self._quota:
# Get a quota manager instance
self._quota = quota.get_quota()
return self._quota
@property
def storage(self):
if not self._storage:
# Get a storage connection
storage_driver = cfg.CONF['service:central'].storage_driver
self._storage = storage.get_storage(storage_driver)
return self._storage
@property
def service_name(self):
return 'central'
def start(self):
if (cfg.CONF['service:central'].managed_resource_tenant_id ==
"00000000-0000-0000-0000-000000000000"):
LOG.warning("Managed Resource Tenant ID is not properly "
"configured")
super(Service, self).start()
self.coordination.start()
def stop(self, graceful=True):
self.coordination.stop()
super(Service, self).stop(graceful)
@property
def mdns_api(self):
return mdns_rpcapi.MdnsAPI.get_instance()
@property
def worker_api(self):
return worker_rpcapi.WorkerAPI.get_instance()
@property
def zone_api(self):
return self.worker_api
def _is_valid_zone_name(self, context, zone_name):
# Validate zone name length
if zone_name is None:
raise exceptions.InvalidObject
if len(zone_name) > cfg.CONF['service:central'].max_zone_name_len:
raise exceptions.InvalidZoneName('Name too long')
# Break the zone name up into its component labels
zone_labels = zone_name.strip('.').split('.')
# We need more than 1 label.
if len(zone_labels) <= 1:
raise exceptions.InvalidZoneName('More than one label is '
'required')
tlds = self.storage.find_tlds(context)
if tlds:
LOG.debug("Checking if %s has a valid TLD", zone_name)
allowed = False
for i in range(-len(zone_labels), 0):
last_i_labels = zone_labels[i:]
LOG.debug("Checking %s against the TLD list", last_i_labels)
if ".".join(last_i_labels) in tlds:
allowed = True
break
if not allowed:
raise exceptions.InvalidZoneName('Invalid TLD')
# Now check that the zone name is not the same as a TLD
try:
stripped_zone_name = zone_name.rstrip('.').lower()
self.storage.find_tld(
context,
{'name': stripped_zone_name})
except exceptions.TldNotFound:
LOG.debug("%s has a valid TLD", zone_name)
else:
raise exceptions.InvalidZoneName(
'Zone name cannot be the same as a TLD')
# Check zone name blacklist
if self._is_blacklisted_zone_name(context, zone_name):
# Some users are allowed bypass the blacklist.. Is this one?
if not policy.check('use_blacklisted_zone', context,
do_raise=False):
raise exceptions.InvalidZoneName('Blacklisted zone name')
return True
def _is_valid_recordset_name(self, context, zone, recordset_name):
if recordset_name is None:
raise exceptions.InvalidObject
if not recordset_name.endswith('.'):
raise ValueError('Please supply a FQDN')
# Validate record name length
max_len = cfg.CONF['service:central'].max_recordset_name_len
if len(recordset_name) > max_len:
raise exceptions.InvalidRecordSetName('Name too long')
# RecordSets must be contained in the parent zone
if (recordset_name != zone['name'] and
not recordset_name.endswith("." + zone['name'])):
raise exceptions.InvalidRecordSetLocation(
'RecordSet is not contained within it\'s parent zone')
def _is_valid_recordset_placement(self, context, zone, recordset_name,
recordset_type, recordset_id=None):
# CNAME's must not be created at the zone apex.
if recordset_type == 'CNAME' and recordset_name == zone.name:
raise exceptions.InvalidRecordSetLocation(
'CNAME recordsets may not be created at the zone apex')
# CNAME's must not share a name with other recordsets
criterion = {
'zone_id': zone.id,
'name': recordset_name,
}
if recordset_type != 'CNAME':
criterion['type'] = 'CNAME'
recordsets = self.storage.find_recordsets(context, criterion)
if ((len(recordsets) == 1 and recordsets[0].id != recordset_id) or
len(recordsets) > 1):
raise exceptions.InvalidRecordSetLocation(
'CNAME recordsets may not share a name with any other records')
return True
def _is_valid_recordset_placement_subzone(self, context, zone,
recordset_name,
criterion=None):
"""
Check that the placement of the requested rrset belongs to any of the
zones subzones..
"""
LOG.debug("Checking if %s belongs in any of %s subzones",
recordset_name, zone.name)
criterion = criterion or {}
context = context.elevated(all_tenants=True)
if zone.name == recordset_name:
return
child_zones = self.storage.find_zones(
context, {"parent_zone_id": zone.id})
for child_zone in child_zones:
try:
self._is_valid_recordset_name(
context, child_zone, recordset_name)
except Exception:
continue
else:
msg = 'RecordSet belongs in a child zone: %s' % \
child_zone['name']
raise exceptions.InvalidRecordSetLocation(msg)
def _is_valid_recordset_records(self, recordset):
"""
Check to make sure that the records in the recordset
follow the rules, and won't blow up on the nameserver.
"""
try:
recordset.records
except (AttributeError, exceptions.RelationNotLoaded):
pass
else:
if len(recordset.records) > 1 and recordset.type == 'CNAME':
raise exceptions.BadRequest(
'CNAME recordsets may not have more than 1 record'
)
def _is_blacklisted_zone_name(self, context, zone_name):
"""
Ensures the provided zone_name is not blacklisted.
"""
blacklists = self.storage.find_blacklists(context)
class Timeout(Exception):
pass
def _handle_timeout(signum, frame):
raise Timeout()
signal.signal(signal.SIGALRM, _handle_timeout)
try:
for blacklist in blacklists:
signal.setitimer(signal.ITIMER_REAL, 0.02)
try:
if bool(re.search(blacklist.pattern, zone_name)):
return True
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
except Timeout:
LOG.critical(
'Blacklist regex (%(pattern)s) took too long to evaluate '
'against zone name (%(zone_name)s',
{
'pattern': blacklist.pattern,
'zone_name': zone_name
})
return True
return False
def _is_subzone(self, context, zone_name, pool_id):
"""
Ensures the provided zone_name is the subzone
of an existing zone (checks across all tenants)
"""
context = context.elevated(all_tenants=True)
# Break the name up into it's component labels
labels = zone_name.split(".")
criterion = {"pool_id": pool_id}
i = 1
# Starting with label #2, search for matching zone's in the database
while (i < len(labels)):
name = '.'.join(labels[i:])
criterion["name"] = name
try:
zone = self.storage.find_zone(context, criterion)
except exceptions.ZoneNotFound:
i += 1
else:
return zone
return False
def _is_superzone(self, context, zone_name, pool_id):
"""
Ensures the provided zone_name is the parent zone
of an existing subzone (checks across all tenants)
"""
context = context.elevated(all_tenants=True)
# Create wildcard term to catch all subzones
search_term = "%%.%(name)s" % {"name": zone_name}
criterion = {'name': search_term, "pool_id": pool_id}
subzones = self.storage.find_zones(context, criterion)
return subzones
def _is_valid_ttl(self, context, ttl):
if ttl is None:
return
min_ttl = cfg.CONF['service:central'].min_ttl
if min_ttl is not None and ttl < int(min_ttl):
try:
policy.check('use_low_ttl', context)
except exceptions.Forbidden:
raise exceptions.InvalidTTL('TTL is below the minimum: %s'
% min_ttl)
def _increment_zone_serial(self, context, zone, set_delayed_notify=False):
"""Update the zone serial and the SOA record
Optionally set delayed_notify to have PM issue delayed notify
"""
# Increment the serial number
zone.serial = utils.increment_serial(zone.serial)
if set_delayed_notify:
zone.delayed_notify = True
zone = self.storage.update_zone(context, zone)
# Update SOA record
self._update_soa(context, zone)
return zone
# SOA Recordset Methods
def _build_soa_record(self, zone, ns_records):
return "%s %s. %d %d %d %d %d" % (ns_records[0]['hostname'],
zone['email'].replace("@", "."),
zone['serial'],
zone['refresh'],
zone['retry'],
zone['expire'],
zone['minimum'])
def _create_soa(self, context, zone):
pool_ns_records = self._get_pool_ns_records(context, zone.pool_id)
soa_values = [self._build_soa_record(zone, pool_ns_records)]
recordlist = objects.RecordList(objects=[
objects.Record(data=r, managed=True) for r in soa_values])
values = {
'name': zone['name'],
'type': "SOA",
'records': recordlist
}
soa, zone = self._create_recordset_in_storage(
context, zone, objects.RecordSet(**values),
increment_serial=False)
return soa
def _update_soa(self, context, zone):
# NOTE: We should not be updating SOA records when a zone is SECONDARY.
if zone.type != 'PRIMARY':
return
# Get the pool for it's list of ns_records
pool_ns_records = self._get_pool_ns_records(context, zone.pool_id)
soa = self.find_recordset(context,
criterion={'zone_id': zone['id'],
'type': "SOA"})
soa.records[0].data = self._build_soa_record(zone, pool_ns_records)
self._update_recordset_in_storage(context, zone, soa,
increment_serial=False)
# NS Recordset Methods
def _create_ns(self, context, zone, ns_records):
# NOTE: We should not be creating NS records when a zone is SECONDARY.
if zone.type != 'PRIMARY':
return
# Create an NS record for each server
recordlist = objects.RecordList(objects=[
objects.Record(data=r, managed=True) for r in ns_records])
values = {
'name': zone['name'],
'type': "NS",
'records': recordlist
}
ns, zone = self._create_recordset_in_storage(
context, zone, objects.RecordSet(**values),
increment_serial=False)
return ns
def _add_ns(self, context, zone, ns_record):
# Get NS recordset
# If the zone doesn't have an NS recordset yet, create one
recordsets = self.find_recordsets(
context, criterion={'zone_id': zone['id'], 'type': "NS"}
)
managed = []
for rs in recordsets:
if rs.managed:
managed.append(rs)
if len(managed) == 0:
self._create_ns(context, zone, [ns_record])
return
elif len(managed) != 1:
raise exceptions.RecordSetNotFound("No valid recordset found")
ns_recordset = managed[0]
# Add new record to recordset based on the new nameserver
ns_recordset.records.append(
objects.Record(data=ns_record, managed=True))
self._update_recordset_in_storage(context, zone, ns_recordset,
set_delayed_notify=True)
def _delete_ns(self, context, zone, ns_record):
ns_recordset = self.find_recordset(
context, criterion={'zone_id': zone['id'], 'type': "NS"})
for record in copy.deepcopy(ns_recordset.records):
if record.data == ns_record:
ns_recordset.records.remove(record)
self._update_recordset_in_storage(context, zone, ns_recordset,
set_delayed_notify=True)
# Quota Enforcement Methods
def _enforce_zone_quota(self, context, tenant_id):
criterion = {'tenant_id': tenant_id}
count = self.storage.count_zones(context, criterion)
self.quota.limit_check(context, tenant_id, zones=count)
def _enforce_recordset_quota(self, context, zone):
# Ensure the recordsets per zone quota is OK
criterion = {'zone_id': zone.id}
count = self.storage.count_recordsets(context, criterion)
self.quota.limit_check(
context, zone.tenant_id, zone_recordsets=count)
def _enforce_record_quota(self, context, zone, recordset):
# Quotas don't apply to managed records.
if recordset.managed:
return
# Ensure the records per zone quota is OK
zone_criterion = {
'zone_id': zone.id,
'managed': False, # only include non-managed records
}
zone_records = self.storage.count_records(context, zone_criterion)
recordset_criterion = {
'recordset_id': recordset.id,
'managed': False, # only include non-managed records
}
recordset_records = self.storage.count_records(
context, recordset_criterion)
# We need to check the current number of zones + the
# changes that add, so lets get +/- from our recordset
# records based on the action
adjusted_zone_records = (
zone_records - recordset_records + len(recordset.records))
self.quota.limit_check(context, zone.tenant_id,
zone_records=adjusted_zone_records)
# Ensure the records per recordset quota is OK
self.quota.limit_check(context, zone.tenant_id,
recordset_records=recordset_records)
# Misc Methods
@rpc.expected_exceptions()
def get_absolute_limits(self, context):
# NOTE(Kiall): Currently, we only have quota based limits..
return self.quota.get_quotas(context, context.project_id)
# Quota Methods
@rpc.expected_exceptions()
def get_quotas(self, context, tenant_id):
target = {'tenant_id': tenant_id}
policy.check('get_quotas', context, target)
if tenant_id != context.project_id and not context.all_tenants:
raise exceptions.Forbidden()
return self.quota.get_quotas(context, tenant_id)
@rpc.expected_exceptions()
def get_quota(self, context, tenant_id, resource):
target = {'tenant_id': tenant_id, 'resource': resource}
policy.check('get_quota', context, target)
return self.quota.get_quota(context, tenant_id, resource)
@rpc.expected_exceptions()
@transaction
def set_quota(self, context, tenant_id, resource, hard_limit):
target = {
'tenant_id': tenant_id,
'resource': resource,
'hard_limit': hard_limit,
}
policy.check('set_quota', context, target)
if tenant_id != context.project_id and not context.all_tenants:
raise exceptions.Forbidden()
return self.quota.set_quota(context, tenant_id, resource, hard_limit)
@transaction
def reset_quotas(self, context, tenant_id):
target = {'tenant_id': tenant_id}
policy.check('reset_quotas', context, target)
self.quota.reset_quotas(context, tenant_id)
# TLD Methods
@rpc.expected_exceptions()
@notification('dns.tld.create')
@transaction
def create_tld(self, context, tld):
policy.check('create_tld', context)
# The TLD is only created on central's storage and not on the backend.
created_tld = self.storage.create_tld(context, tld)
return created_tld
@rpc.expected_exceptions()
def find_tlds(self, context, criterion=None, marker=None, limit=None,
sort_key=None, sort_dir=None):
policy.check('find_tlds', context)
return self.storage.find_tlds(context, criterion, marker, limit,
sort_key, sort_dir)
@rpc.expected_exceptions()
def get_tld(self, context, tld_id):
policy.check('get_tld', context, {'tld_id': tld_id})
return self.storage.get_tld(context, tld_id)
@rpc.expected_exceptions()
@notification('dns.tld.update')
@transaction
def update_tld(self, context, tld):
target = {
'tld_id': tld.obj_get_original_value('id'),
}
policy.check('update_tld', context, target)
tld = self.storage.update_tld(context, tld)
return tld
@rpc.expected_exceptions()
@notification('dns.tld.delete')
@transaction
def delete_tld(self, context, tld_id):
policy.check('delete_tld', context, {'tld_id': tld_id})
tld = self.storage.delete_tld(context, tld_id)
return tld
# TSIG Key Methods
@rpc.expected_exceptions()
@notification('dns.tsigkey.create')
@transaction
def create_tsigkey(self, context, tsigkey):
policy.check('create_tsigkey', context)
created_tsigkey = self.storage.create_tsigkey(context, tsigkey)
# TODO(Ron): this method needs to do more than update storage.
return created_tsigkey
@rpc.expected_exceptions()
def find_tsigkeys(self, context, criterion=None, marker=None, limit=None,
sort_key=None, sort_dir=None):
policy.check('find_tsigkeys', context)
return self.storage.find_tsigkeys(context, criterion, marker,
limit, sort_key, sort_dir)
@rpc.expected_exceptions()
def get_tsigkey(self, context, tsigkey_id):
policy.check('get_tsigkey', context, {'tsigkey_id': tsigkey_id})
return self.storage.get_tsigkey(context, tsigkey_id)
@rpc.expected_exceptions()
@notification('dns.tsigkey.update')
@transaction
def update_tsigkey(self, context, tsigkey):
target = {
'tsigkey_id': tsigkey.obj_get_original_value('id'),
}
policy.check('update_tsigkey', context, target)
tsigkey = self.storage.update_tsigkey(context, tsigkey)
# TODO(Ron): this method needs to do more than update storage.
return tsigkey
@rpc.expected_exceptions()
@notification('dns.tsigkey.delete')
@transaction
def delete_tsigkey(self, context, tsigkey_id):
policy.check('delete_tsigkey', context, {'tsigkey_id': tsigkey_id})
tsigkey = self.storage.delete_tsigkey(context, tsigkey_id)
# TODO(Ron): this method needs to do more than update storage.
return tsigkey
# Tenant Methods
@rpc.expected_exceptions()
def find_tenants(self, context):
policy.check('find_tenants', context)
return self.storage.find_tenants(context)
@rpc.expected_exceptions()
def get_tenant(self, context, tenant_id):
target = {
'tenant_id': tenant_id
}
policy.check('get_tenant', context, target)
return self.storage.get_tenant(context, tenant_id)
@rpc.expected_exceptions()
def count_tenants(self, context):
policy.check('count_tenants', context)
return self.storage.count_tenants(context)
# Zone Methods
def _generate_soa_refresh_interval(self):
"""Generate a random refresh interval to stagger AXFRs across multiple
zones and resolvers
maximum val: default_soa_refresh_min
minimum val: default_soa_refresh_max
"""
assert cfg.CONF.default_soa_refresh_min is not None
assert cfg.CONF.default_soa_refresh_max is not None
dispersion = (cfg.CONF.default_soa_refresh_max -
cfg.CONF.default_soa_refresh_min) * random.random()
refresh_time = cfg.CONF.default_soa_refresh_min + dispersion
return int(refresh_time)
def _get_pool_ns_records(self, context, pool_id):
"""Get pool ns_records using an elevated context and all_tenants = True
:param pool_id: Pool ID
:returns: ns_records
"""
elevated_context = context.elevated(all_tenants=True)
pool = self.storage.get_pool(elevated_context, pool_id)
return pool.ns_records
@rpc.expected_exceptions()
@notification('dns.domain.create')
@notification('dns.zone.create')
@synchronized_zone(new_zone=True)
def create_zone(self, context, zone):
"""Create zone: perform checks and then call _create_zone()
"""
# Default to creating in the current users tenant
zone.tenant_id = zone.tenant_id or context.project_id
target = {
'tenant_id': zone.tenant_id,
'zone_name': zone.name
}
policy.check('create_zone', context, target)
# Ensure the tenant has enough quota to continue
self._enforce_zone_quota(context, zone.tenant_id)
# Ensure the zone name is valid
self._is_valid_zone_name(context, zone.name)
# Ensure TTL is above the minimum
self._is_valid_ttl(context, zone.ttl)
# Get a pool id
zone.pool_id = self.scheduler.schedule_zone(context, zone)
# Handle sub-zones appropriately
parent_zone = self._is_subzone(
context, zone.name, zone.pool_id)
if parent_zone:
if parent_zone.tenant_id == zone.tenant_id:
# Record the Parent Zone ID
zone.parent_zone_id = parent_zone.id
else:
raise exceptions.IllegalChildZone('Unable to create'
'subzone in another '
'tenants zone')
# Handle super-zones appropriately
subzones = self._is_superzone(context, zone.name, zone.pool_id)
msg = ('Unable to create zone because another tenant owns a subzone '
'of the zone')
if subzones:
LOG.debug("Zone '%s' is a superzone.", zone.name)
for subzone in subzones:
if subzone.tenant_id != zone.tenant_id:
raise exceptions.IllegalParentZone(msg)
# If this succeeds, subzone parent IDs will be updated
# after zone is created
# NOTE(kiall): Fetch the servers before creating the zone, this way
# we can prevent zone creation if no servers are
# configured.
pool_ns_records = self._get_pool_ns_records(context, zone.pool_id)
if len(pool_ns_records) == 0:
LOG.critical('No nameservers configured. Please create at least '
'one nameserver')
raise exceptions.NoServersConfigured()
# End of pre-flight checks, create zone
return self._create_zone(context, zone, subzones)
def _create_zone(self, context, zone, subzones):
"""Create zone straight away
"""
if zone.type == 'SECONDARY' and zone.serial is None:
zone.serial = 1
# randomize the zone refresh time
zone.refresh = self._generate_soa_refresh_interval()
zone = self._create_zone_in_storage(context, zone)
self.zone_api.create_zone(context, zone)
if zone.type == 'SECONDARY':
self.mdns_api.perform_zone_xfr(context, zone)
# If zone is a superzone, update subzones
# with new parent IDs
for subzone in subzones:
LOG.debug("Updating subzone '%s' parent ID using "
"superzone ID '%s'", subzone.name, zone.id)
subzone.parent_zone_id = zone.id
self.update_zone(context, subzone)
return zone
@transaction
def _create_zone_in_storage(self, context, zone):
zone.action = 'CREATE'
zone.status = 'PENDING'
zone = self.storage.create_zone(context, zone)
pool_ns_records = self.get_zone_ns_records(context, zone['id'])
# Create the SOA and NS recordsets for the new zone. The SOA
# record will always be the first 'created_at' record for a zone.
self._create_soa(context, zone)
self._create_ns(context, zone, [n.hostname for n in pool_ns_records])
if zone.obj_attr_is_set('recordsets'):
for rrset in zone.recordsets:
# This allows eventlet to yield, as this looping operation
# can be very long-lived.
time.sleep(0)
self._create_recordset_in_storage(
context, zone, rrset, increment_serial=False)
return zone
@rpc.expected_exceptions()
def get_zone(self, context, zone_id):
"""Get a zone, even if flagged for deletion
"""
zone = self.storage.get_zone(context, zone_id)
target = {
'zone_id': zone_id,
'zone_name': zone.name,
'tenant_id': zone.tenant_id
}
policy.check('get_zone', context, target)
return zone
@rpc.expected_exceptions()
def get_zone_ns_records(self, context, zone_id=None, criterion=None):
if zone_id is None:
policy.check('get_zone_ns_records', context)
pool_id = cfg.CONF['service:central'].default_pool_id
else:
zone = self.storage.get_zone(context, zone_id)
target = {
'zone_id': zone_id,
'zone_name': zone.name,
'tenant_id': zone.tenant_id
}
pool_id = zone.pool_id
policy.check('get_zone_ns_records', context, target)
# Need elevated context to get the pool
elevated_context = context.elevated(all_tenants=True)