/
vnc_cfg_types.py
5768 lines (4959 loc) · 233 KB
/
vnc_cfg_types.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 (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# This file contains code/hooks at different point during processing a request,
# specific to type of resource. For eg. allocation of mac/ip-addr for a port
# during its creation.
import copy
from functools import wraps
import itertools
import re
import socket
import netaddr
import uuid
from cfgm_common import jsonutils as json
from cfgm_common import get_lr_internal_vn_name
from cfgm_common import _obj_serializer_all
import cfgm_common
from cfgm_common.utils import _DEFAULT_ZK_COUNTER_PATH_PREFIX
import cfgm_common.exceptions
import vnc_quota
from vnc_quota import QuotaHelper
from provision_defaults import PERMS_RWX
from provision_defaults import PERMS_RX
from context import get_context
from context import is_internal_request
from vnc_api.gen.resource_xsd import *
from vnc_api.gen.resource_common import *
from netaddr import IPNetwork, IPAddress, IPRange
from pprint import pformat
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns import constants
class ResourceDbMixin(object):
@classmethod
def get_project_id_for_resource(cls, obj_dict, obj_type, db_conn):
proj_uuid = None
if 'project_refs' in obj_dict:
proj_dict = obj_dict['project_refs'][0]
proj_uuid = proj_dict.get('uuid')
if not proj_uuid:
proj_uuid = db_conn.fq_name_to_uuid('project', proj_dict['to'])
elif 'parent_type' in obj_dict and obj_dict['parent_type'] == 'project':
proj_uuid = obj_dict['parent_uuid']
elif (obj_type == 'loadbalancer_member' or
obj_type == 'floating_ip_pool' and 'parent_uuid' in obj_dict):
# loadbalancer_member and floating_ip_pool have only one parent type
ok, proj_res = cls.dbe_read(db_conn, cls.parent_types[0],
obj_dict['parent_uuid'],
obj_fields=['parent_uuid'])
if not ok:
return proj_uuid # None
proj_uuid = proj_res['parent_uuid']
return proj_uuid
@classmethod
def get_quota_for_resource(cls, obj_type, obj_dict, db_conn):
user_visible = obj_dict['id_perms'].get('user_visible', True)
if not user_visible or obj_type not in QuotaType.attr_fields:
return True, -1, None
proj_uuid = cls.get_project_id_for_resource(obj_dict, obj_type, db_conn)
if proj_uuid is None:
return True, -1, None
(ok, proj_dict) = QuotaHelper.get_project_dict_for_quota(proj_uuid, db_conn)
if not ok:
return (False, (500, 'Internal error : ' + pformat(proj_dict)), None)
quota_limit = QuotaHelper.get_quota_limit(proj_dict, obj_type)
return True, quota_limit, proj_uuid
@classmethod
def pending_dbe_create(cls, obj_dict):
return True, ''
@classmethod
def pre_dbe_alloc(cls, obj_dict):
return True, ''
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
return True, ''
@classmethod
def post_dbe_create(cls, tenant_name, obj_dict, db_conn):
return True, ''
@classmethod
def pending_dbe_update(cls, obj_dict, delta_obj_dict=None,
prop_collection_updates=None):
return True, ''
@classmethod
def pre_dbe_update(cls, id, fq_name, obj_dict, db_conn,
prop_collection_updates=None, ref_update=None):
return True, ''
@classmethod
def post_dbe_update(cls, id, fq_name, obj_dict, db_conn,
prop_collection_updates=None, ref_update=None):
return True, ''
@classmethod
def pending_dbe_delete(cls, obj_dict):
return True, ''
@classmethod
def pre_dbe_delete(cls, id, obj_dict, db_conn):
return True, ''
@classmethod
def post_dbe_delete(cls, id, obj_dict, db_conn):
return True, ''
@classmethod
def dbe_create_notification(cls, db_conn, obj_id, obj_dict):
pass
@classmethod
def dbe_update_notification(cls, obj_id, extra_dict=None):
pass
@classmethod
def dbe_delete_notification(cls, obj_id, obj_dict):
pass
@classmethod
def pre_dbe_read(cls, id, fq_name, db_conn):
return True, ''
@classmethod
def post_dbe_read(cls, obj_dict, db_conn):
return True, ''
@classmethod
def pre_dbe_list(cls, obj_uuids, db_conn):
return True, ''
@classmethod
def post_dbe_list(cls, obj_dict_list, db_conn):
return True, ''
# end class ResourceDbMixin
class Resource(ResourceDbMixin):
server = None
class __metaclass__(type):
@property
def db_conn(cls):
return cls.server.get_db_connection()
@property
def addr_mgmt(cls):
return cls.server._addr_mgmt
@property
def vnc_zk_client(cls):
return cls.db_conn._zk_db
@classmethod
def dbe_read(cls, db_conn, res_type, obj_uuid, obj_fields=None):
try:
ok, result = db_conn.dbe_read(res_type, obj_uuid, obj_fields)
except cfgm_common.exceptions.NoIdError:
return (False, (404, 'No %s: %s' %(res_type, obj_uuid)))
if not ok:
return (False, (500, 'Error in dbe_read of %s %s: %s' %(
res_type, obj_uuid, pformat(result))))
return (True, result)
# end dbe_read
@classmethod
def locate(cls, fq_name=None, uuid=None, create_it=True, **kwargs):
if fq_name is not None and uuid is None:
try:
uuid = cls.db_conn.fq_name_to_uuid(cls.object_type, fq_name)
except cfgm_common.exceptions.NoIdError as e:
if create_it:
pass
else:
return False, (404, str(e))
if uuid:
try:
ok, result = cls.db_conn.dbe_read(
cls.object_type, uuid, obj_fields=kwargs.get('fields'))
except cfgm_common.exceptions.NoIdError as e:
if create_it:
pass
else:
return False, (404, str(e))
if not ok:
return False, result
else:
return ok, result
# Does not exist, create it. Need at least an fq_name
if fq_name is None or fq_name == []:
msg = ("Cannot create %s without at least a FQ name" %
cls.object_type.replace('_', ' ').title())
return False, (400, msg)
parent_obj = None
if kwargs.get('parent_type') is not None:
parent_class = cls.server.get_resource_class(kwargs['parent_type'])
parent_obj = parent_class(fq_name=fq_name[:-1])
parent_obj.uuid = kwargs.get('parent_uuid')
obj = cls(parent_obj=parent_obj, **kwargs)
obj.fq_name = fq_name
obj.uuid = kwargs.get('uuid')
obj_dict = json.loads(json.dumps(obj, default=_obj_serializer_all))
for ref_name in cls.ref_fields & set(kwargs.keys()):
obj_dict[ref_name] = copy.deepcopy(kwargs[ref_name])
try:
cls.server.internal_request_create(cls.resource_type, obj_dict)
except cfgm_common.exceptions.HttpError as e:
return False, (e.status_code, e.content)
try:
uuid = cls.db_conn.fq_name_to_uuid(cls.object_type, fq_name)
except cfgm_common.exceptions.NoIdError as e:
return False, (404, str(e))
return cls.db_conn.dbe_read(cls.object_type, obj_id=uuid)
def draft_mode_sanity_checks(func):
@wraps(func)
def wrapper(cls, obj_dict, *args, **kwargs):
if cls.object_type not in constants.SECURITY_OBJECT_TYPES:
return True, ''
if is_internal_request():
# Ignore all internal calls to not pending pending actions
return True, ''
ok, result = cls._get_dedicated_draft_policy_management(obj_dict)
if not ok:
return False, result
# if nothing returned without error, that means security draft mode
# is NOT enabled
if result == '':
return True, ''
draft_pm = result
# if a commit or discard is on going in that scope, forbidden any
# security resource modification in that scope
scope_type = draft_pm.get('parent_type',
GlobalSystemConfigServer.object_type)
scope_uuid = draft_pm.get('parent_uuid', 'unknown UUID')
scope_fq_name = draft_pm['fq_name'][:-1]
if not scope_fq_name:
scope_fq_name = [GlobalSystemConfigServer().name]
scope_read_lock = cls.vnc_zk_client._zk_client.read_lock(
'%s/%s/%s' % (
cls.server.security_lock_prefix,
scope_type,
':'.join(scope_fq_name),
),
)
if not scope_read_lock.acquire(blocking=False):
contenders = scope_read_lock.contenders()
for contender in contenders:
_, action_in_progress = contender.split()
if action_in_progress:
break
else:
action_in_progress = '<unknown action>'
msg = ("Action '%s' on %s '%s' (%s) scope is under progress. "
"Cannot modify %s security resource." %
(action_in_progress, scope_type.replace('_', ' ').title(),
':'.join(scope_fq_name), scope_uuid,
cls.object_type.replace('_', ' ').title()))
return False, (400, msg)
try:
return func(cls, draft_pm, obj_dict, *args, **kwargs)
finally:
scope_read_lock.release()
return wrapper
class SecurityResourceBase(Resource):
@classmethod
def check_associated_firewall_resource_in_same_scope(cls, id, fq_name,
obj_dict, ref_class):
# NOTE(ethuleau): this method is simply based on the fact global
# firewall resource (draft or not) have a FQ name length equal to two
# and scoped one (draft or not) have a FQ name longer than 2 to
# distinguish a scoped firewall resource to a global one. If that
# assumption disappear, all that method will need to be re-worked
ref_name = '%s_refs' % ref_class.object_type
if ref_name not in obj_dict:
return True, ''
scoped_resource = True
if len(fq_name) == 2:
scoped_resource = False
# Scoped firewall resource can reference global or scoped resources
if scoped_resource:
return True, ''
# In case of global firewall resource check if it reference global
# firewall resource only
for ref in obj_dict.get(ref_name, []):
ref_scoped_resource = True
if len(ref['to']) == 2:
ref_scoped_resource = False
# Global firewall resource can reference global firewall resources
if not ref_scoped_resource:
continue
# Global firewall resource cannot reference scoped resources
msg = ("Global %s %s (%s) cannot reference a scoped %s %s (%s)" %
(cls.object_type.replace('_', ' ').title(),
':'.join(fq_name), id,
ref_class.object_type.replace('_', ' ').title(),
':'.join(ref['to']), ref['uuid']))
return False, (400, msg)
return True, ''
@staticmethod
def check_draft_mode_state(obj_dict):
if is_internal_request():
# system only property
return True, ''
if 'draft_mode_state' in obj_dict:
msg = ("Security resource property 'draft_mode_state' is only "
"readable")
return False, (400, msg)
return True, ''
@classmethod
def set_policy_management_for_security_draft(cls, scope, obj_dict,
draft_mode_enabled=False):
if 'enable_security_policy_draft' not in obj_dict:
return True, ''
draft_mode_set = obj_dict.get('enable_security_policy_draft', False)
draft_pm_name = constants.POLICY_MANAGEMENT_NAME_FOR_SECURITY_DRAFT
if obj_dict['fq_name'][-1:] == draft_pm_name:
# This is the policy management dedicated for draft security
# resources, should already exist we can return it
return PolicyManagementServer.locate(obj_dict['fq_name'],
create_it=False)
if scope == GlobalSystemConfigServer.resource_type:
parent_type = None
parent_uuid = None
draft_pm_fq_name = [draft_pm_name]
else:
parent_type = scope
parent_uuid = obj_dict['uuid']
draft_pm_fq_name = obj_dict['fq_name'] + [draft_pm_name]
# Disabling draft mode
if not draft_mode_set and draft_mode_enabled:
try:
draft_pm_uuid = cls.db_conn.fq_name_to_uuid(
PolicyManagementServer.object_type, draft_pm_fq_name)
except cfgm_common.exceptions.NoIdError:
return True, ''
try:
# If pending security modification, it fails to delete the
# draft PM
cls.server.internal_request_delete(
PolicyManagementServer.resource_type, draft_pm_uuid)
except cfgm_common.exceptions.HttpError as e:
if e.status_code == 404:
pass
elif e.status_code == 409:
ok, result = PolicyManagementServer.locate(
uuid=draft_pm_uuid, create_it=False)
if not ok:
return False, result
draft_pm = result
if scope == GlobalSystemConfigServer.resource_type:
msg = ("Cannot disable security draft mode on global "
"scope as some pending security resource(s) "
"need to be reviewed:\n")
else:
msg = ("Cannot disable security draft mode on scope "
"%s (%s) as some pending security resource(s) "
"need to be reviewed:\n" % (
':'.join(obj_dict['fq_name']),
parent_uuid))
children_left = []
for type in ['%ss' % type for type in
constants.SECURITY_OBJECT_TYPES]:
children = ["%s (%s)" % (':'.join(c['to']), c['uuid'])
for c in draft_pm.get(type, [])]
if children:
children_left.append(
"\t- %s: %s" % (
type.replace('_', ' ').title(),
', '.join(children),
),
)
if children_left:
msg += '\n'.join(children_left)
return False, (409, msg)
else:
return False, (e.status_code, e.content)
else:
return False, (e.status_code, e.content)
# Enabling draft mode
elif draft_mode_set and not draft_mode_enabled:
attrs = {
'parent_type': parent_type,
'parent_uuid': parent_uuid,
'name': draft_pm_name,
'enable_security_policy_draft': True,
}
return PolicyManagementServer.locate(draft_pm_fq_name, **attrs)
return True, ''
@classmethod
def _get_dedicated_draft_policy_management(cls, obj_dict):
parent_type = obj_dict.get('parent_type')
if parent_type == PolicyManagementServer.resource_type:
if (obj_dict['fq_name'][-2] ==
constants.POLICY_MANAGEMENT_NAME_FOR_SECURITY_DRAFT):
# Could be already the dedicated draft policy management, in
# that case it is updating an already pending resource. Return
# it directly
return PolicyManagementServer.locate(
fq_name=obj_dict.get('fq_name')[:-1],
uuid=obj_dict.get('parent_uuid'),
create_it=False,
)
# if not a dedicated draft policy management, it is a global
# security resources owned by the global policy management
elif obj_dict['fq_name'][:-1] == PolicyManagementServer().fq_name:
parent_class = GlobalSystemConfigServer
parent_fq_name = GlobalSystemConfigServer().fq_name
parent_uuid = None
else:
return True, ''
elif parent_type == ProjectServer.resource_type:
parent_class = ProjectServer
parent_fq_name = obj_dict['fq_name'][:-1]
parent_uuid = obj_dict.get('parent_uuid')
else:
return True, ''
# check from parent if security draft mode is enabled
ok, result = parent_class.locate(
fq_name=parent_fq_name,
uuid=parent_uuid,
create_it=False,
fields=['enable_security_policy_draft']
)
if not ok:
return False, result
parent_dict = result
# get scoped policy management dedicated to own pending security
# resource
return cls.set_policy_management_for_security_draft(
parent_class.resource_type, parent_dict)
@classmethod
@draft_mode_sanity_checks
def pending_dbe_create(cls, draft_pm, obj_dict):
return cls._pending_update(draft_pm, obj_dict, 'created')
@classmethod
@draft_mode_sanity_checks
def pending_dbe_update(cls, draft_pm, obj_dict, delta_obj_dict=None,
prop_collection_updates=None):
return cls._pending_update(draft_pm, obj_dict, 'updated',
delta_obj_dict, prop_collection_updates)
@classmethod
@draft_mode_sanity_checks
def pending_dbe_delete(cls, draft_pm, obj_dict):
uuid = obj_dict['uuid']
exist_refs = set()
relaxed_refs = set(cls.db_conn.dbe_get_relaxed_refs(uuid))
for backref_field in cls.backref_fields:
ref_type, _, is_derived = cls.backref_field_types[backref_field]
if is_derived:
continue
exist_refs = {(ref_type, backref['uuid'])
for backref in obj_dict.get(backref_field, [])
if backref['uuid'] not in relaxed_refs}
ref_exits_error = set()
for ref_type, ref_uuid in exist_refs:
ref_class = cls.server.get_resource_class(ref_type)
ref_field = '%s_refs' % cls.object_type
ok, result = ref_class.locate(
uuid=ref_uuid,
create_it=False,
fields=['fq_name', 'parent_type', 'draft_mode_state',
ref_field],
)
if not ok:
return False, result
ref = result
if (ref['fq_name'][-2] !=
constants.POLICY_MANAGEMENT_NAME_FOR_SECURITY_DRAFT):
ok, result = ref_class.get_pending_resource(
ref, fields=['draft_mode_state', ref_field])
if ok and result == '':
# no draft version of the back-referenced resource,
# draft mode not enabled, abandon and let classic code
# operate
return True, ''
elif not ok and isinstance(result, tuple) and result[0] == 404:
# draft mode enabled, but no draft version of the
# back-referenced resource, resource still referenced
# cannot delete it
ref_exits_error.add((ref_type, ref_uuid))
continue
elif not ok:
return False, result
draft_ref = result
else:
draft_ref = ref
if draft_ref['draft_mode_state'] in ['create', 'updated']:
if uuid in {r['uuid'] for r in draft_ref.get(ref_field, [])}:
# draft version of the back-referenced resource still
# referencing resource, resource cannot delete it
ref_exits_error.add((ref_type, ref_uuid))
continue
# draft version of the back-referenced resource is in pending
# delete, resource could be deleted
if ref_exits_error:
return False, (409, ref_exits_error)
return cls._pending_update(draft_pm, obj_dict, 'deleted')
@classmethod
def _pending_update(cls, draft_pm, obj_dict, draft_mode_state,
delta_obj_dict=None, prop_collection_updates=None):
if not delta_obj_dict:
delta_obj_dict = {}
delta_obj_dict.pop('uuid', None)
# if the parent is already the draft policy management, its updating
# the draft version of the resource. We can ignore it and let classic
# update code operated
if (obj_dict['fq_name'][-2] ==
constants.POLICY_MANAGEMENT_NAME_FOR_SECURITY_DRAFT):
if obj_dict['draft_mode_state'] == 'deleted':
# Cannot update a pending deleted resource
msg = ("%s %s is in pending delete, cannot be updated" %
(cls.object_type.replace('_', ' ').title(),
':'.join(obj_dict['fq_name'])))
return False, (400, msg)
return True, ''
# Locate draft version of the resource, if does not exits, create it
draft_fq_name = draft_pm['fq_name'] + obj_dict['fq_name'][-1:]
# Check if it's trying to create a resource already in pending create
if draft_mode_state == 'created':
try:
cls.db_conn.fq_name_to_uuid(cls.object_type, draft_fq_name)
msg = ("%s named %s was already created and it is pending to "
"be committed or discarded. You cannot create it again"
% (cls.object_type.replace('_', ' ').title(),
':'.join(obj_dict['fq_name'])))
return False, (400, msg)
except cfgm_common.exceptions.NoIdError as e:
pass
obj_dict['parent_type'] = PolicyManagementServer.resource_type
obj_dict['parent_uuid'] = draft_pm['uuid']
obj_dict.pop('fq_name', None)
obj_dict.pop('uuid', None)
if 'id_perms' in obj_dict:
obj_dict['id_perms'].pop('uuid', None)
# Set draft mode to created, if draft resource already exists, property
# will be read from the DB, if not state need to be set to 'created'
obj_dict['draft_mode_state'] = draft_mode_state
if draft_mode_state == 'deleted':
# remove all resource references
[obj_dict.pop(ref_field, None) for ref_field in cls.ref_fields]
ok, result = cls.locate(fq_name=draft_fq_name, **obj_dict)
if not ok:
return False, result
draft_obj_dict = result
# Allow to update pending created or updated security resources
if draft_mode_state == 'updated':
if draft_obj_dict['draft_mode_state'] == 'deleted':
# Disallow to update a pending deleted security resource
msg = ("%s %s is in pending delete, cannot be updated" %
(cls.object_type.replace('_', ' ').title(),
':'.join(obj_dict['fq_name'])))
return False, (400, msg)
elif delta_obj_dict:
try:
cls.server.internal_request_update(
cls.resource_type,
draft_obj_dict['uuid'],
delta_obj_dict,
)
except cfgm_common.exceptions.HttpError as e:
return False, (e.status_code, e.content)
elif prop_collection_updates:
try:
cls.server.internal_request_prop_collection(
draft_obj_dict['uuid'], prop_collection_updates)
except cfgm_common.exceptions.HttpError as e:
return False, (e.status_code, e.content)
elif (draft_mode_state == 'deleted' and
draft_obj_dict['draft_mode_state'] == 'updated'):
cls.server.internal_request_update(
cls.resource_type,
draft_obj_dict['uuid'],
{'draft_mode_state': 'deleted'},
)
draft_obj_dict.update(delta_obj_dict)
return True, (202, draft_obj_dict)
@classmethod
def get_pending_resource(cls, obj_dict, fields=None):
ok, result = cls._get_dedicated_draft_policy_management(obj_dict)
if not ok:
return False, result
# if nothing returned without error, that means security draft mode is
# NOT enabled or this is an internal pending security resource update
if result == '':
return True, ''
draft_pm_dict = result
pending_fq_name = draft_pm_dict['fq_name'] + obj_dict['fq_name'][-1:]
# return pending resource if already exists
return cls.locate(pending_fq_name, create_it=False, fields=fields)
class GlobalSystemConfigServer(Resource, GlobalSystemConfig):
@classmethod
def _get_global_system_config(cls, fields=None):
return cls.locate(fq_name=['default-global-system-config'],
create_it=False, fields=fields)
@classmethod
def _check_valid_port_range(cls, port_start, port_end):
if int(port_start) > int(port_end):
return (False, (400, 'Invalid Port range specified'))
return True, ''
@classmethod
def _check_bgpaas_ports(cls, obj_dict, db_conn):
bgpaas_ports = obj_dict.get('bgpaas_parameters')
if not bgpaas_ports:
return (True, '')
ok, msg = cls._check_valid_port_range(bgpaas_ports['port_start'],
bgpaas_ports['port_end'])
if not ok:
return ok, msg
ok, result = cls._get_global_system_config(['bgpaas_parameters'])
if not ok:
return False, result
global_sys_cfg = result
cur_bgpaas_ports = global_sys_cfg.get('bgpaas_parameters') or\
{'port_start': 50000, 'port_end': 50512}
(ok, bgpaas_list, _) = db_conn.dbe_list('bgp_as_a_service', is_count=True)
if not ok:
return (ok, bgpaas_list)
if bgpaas_list:
if (int(bgpaas_ports['port_start']) >
int(cur_bgpaas_ports['port_start']) or
int(bgpaas_ports['port_end']) <
int(cur_bgpaas_ports['port_end'])):
return (False, (400, 'BGP Port range cannot be shrunk'))
return (True, '')
# end _check_bgpaas_ports
@classmethod
def _check_asn(cls, obj_dict):
global_asn = obj_dict.get('autonomous_system')
if not global_asn:
return True, ''
ok, result, _ = cls.db_conn.dbe_list('virtual_network',
field_names=['route_target_list'])
if not ok:
return False, (500, 'Error in dbe_list: %s' % result)
vn_list = result
founded_vn_using_asn = []
for vn in vn_list:
rt_dict = vn.get('route_target_list', {})
for rt in rt_dict.get('route_target', []):
ok, result = RouteTargetServer.is_user_defined(rt, global_asn)
if not ok:
return False, result
user_defined_rt = result
if not user_defined_rt:
founded_vn_using_asn.append((':'.join(vn['fq_name']),
vn['uuid'], rt))
if not founded_vn_using_asn:
return True, ''
msg = ("Virtual networks are configured with a route target with this "
"ASN %d and route target value in the same range as used by "
"automatically allocated route targets:\n" % global_asn)
for fq_name, id, rt in founded_vn_using_asn:
msg += ("\t- %s (%s) have route target %s configured\n" %
(':'.join(vn['fq_name']), vn['uuid'], rt[7:]))
return False, (400, msg)
@classmethod
def _check_udc(cls, obj_dict, udcs):
udcl = []
for udc in udcs:
if all (k in udc.get('value') or {} for k in ('name', 'pattern')):
udcl.append(udc['value'])
udck = obj_dict.get('user_defined_log_statistics')
if udck:
udcl += udck['statlist']
for udc in udcl:
try:
re.compile(udc['pattern'])
except Exception as e:
return False, (400, 'Regex error in '
'user-defined-log-statistics at %s: %s (Error: %s)' % (
udc['name'], udc['pattern'], str(e)))
return True, ''
# end _check_udc
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
ok, result = cls._get_global_system_config(['fq_name', 'uuid'])
if not ok:
return False, result
gsc = result
msg = ("Global System Config already exists with name %s (%s)" %
(':'.join(gsc['fq_name']), gsc['uuid']))
return False, (400, msg)
@classmethod
def pre_dbe_update(cls, id, fq_name, obj_dict, db_conn, **kwargs):
ok, result = cls._check_udc(obj_dict, filter(lambda x: x.get('field',
'') == 'user_defined_log_statistics' and x.get(
'operation', '') == 'set', kwargs.get(
'prop_collection_updates') or []))
if not ok:
return ok, result
ok, result = cls._check_asn(obj_dict)
if not ok:
return ok, result
ok, result = cls._check_bgpaas_ports(obj_dict, db_conn)
if not ok:
return ok, result
if 'enable_security_policy_draft' in obj_dict:
fields = ['fq_name', 'uuid', 'enable_security_policy_draft']
ok, result = cls._get_global_system_config(fields)
if not ok:
return False, result
db_obj_dict = result
obj_dict['fq_name'] = db_obj_dict['fq_name']
obj_dict['uuid'] = db_obj_dict['uuid']
SecurityResourceBase.server = cls.server
return SecurityResourceBase.\
set_policy_management_for_security_draft(
cls.resource_type,
obj_dict,
draft_mode_enabled=db_obj_dict.get(
'enable_security_policy_draft', False),
)
return True, ''
@classmethod
def post_dbe_update(cls, id, fq_name, obj_dict, db_conn, **kwargs):
if 'autonomous_system' in obj_dict:
cls.server.global_autonomous_system = obj_dict['autonomous_system']
return True, ''
class FloatingIpServer(Resource, FloatingIp):
@classmethod
def _get_fip_pool_subnets(cls, fip_obj_dict, db_conn):
fip_subnets = None
# Get floating-ip-pool object.
fip_pool_fq_name = fip_obj_dict['fq_name'][:-1]
fip_pool_uuid = db_conn.fq_name_to_uuid('floating_ip_pool',
fip_pool_fq_name)
ok, res = cls.dbe_read(db_conn, 'floating_ip_pool', fip_pool_uuid)
if ok:
# Successful read returns fip pool.
fip_pool_dict = res
else:
return ok, res
# Get any subnets configured on the floating-ip-pool.
try:
fip_subnets = fip_pool_dict['floating_ip_pool_subnets']
except KeyError, TypeError:
# It is acceptable that the prefixes and subnet_list may be absent
# or may be None.
pass
return True, fip_subnets
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
if obj_dict['parent_type'] == 'instance-ip':
return True, ""
vn_fq_name = obj_dict['fq_name'][:-2]
req_ip = obj_dict.get("floating_ip_address")
if req_ip and cls.addr_mgmt.is_ip_allocated(req_ip, vn_fq_name):
return (False, (409, 'Ip address already in use'))
try:
#
# Parse through floating-ip-pool config to see if there are any
# guidelines laid for allocation of this floating-ip.
#
fip_subnets = None
ok, ret_val = cls._get_fip_pool_subnets(obj_dict, db_conn)
# On a successful fip-pool subnet get, the subnet list is returned.
# Otherwise, returned value has appropriate reason string.
if ok:
fip_subnets = ret_val
else:
return (ok, (400, "Floating-ip-pool lookup failed with error:"\
+ ret_val))
if not fip_subnets:
# Subnet specification was not found on the floating-ip-pool.
# Proceed to allocated floating-ip from any of the subnets
# on the virtual-network.
(fip_addr, sn_uuid) = cls.addr_mgmt.ip_alloc_req(vn_fq_name,
asked_ip_addr=req_ip,
alloc_id=obj_dict['uuid'])
else:
subnets_tried = []
# Iterate through configured subnets on floating-ip-pool.
# We will try to allocate floating-ip by iterating through
# the list of configured subnets.
for fip_pool_subnet in fip_subnets['subnet_uuid']:
try:
# Record the subnets that we try to allocate from.
subnets_tried.append(fip_pool_subnet)
(fip_addr, sn_uuid) = cls.addr_mgmt.ip_alloc_req(
vn_fq_name,
sub = fip_pool_subnet,
asked_ip_addr=req_ip,
alloc_id=obj_dict['uuid'])
except cls.addr_mgmt.AddrMgmtSubnetExhausted:
# This subnet is exhausted. Try next subnet.
continue
if not fip_addr:
# Floating-ip could not be allocated from any of the
# configured subnets. Raise an exception.
raise cls.addr_mgmt.AddrMgmtSubnetExhausted(vn_fq_name,
subnets_tried)
def undo():
db_conn.config_log(
'AddrMgmt: free FIP %s for vn=%s tenant=%s, on undo'
% (fip_addr, vn_fq_name, tenant_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(fip_addr, vn_fq_name,
alloc_id=obj_dict['uuid'])
return True, ""
# end undo
get_context().push_undo(undo)
except Exception as e:
return (False, (500, str(e)))
obj_dict['floating_ip_address'] = fip_addr
db_conn.config_log('AddrMgmt: alloc %s FIP for vn=%s, tenant=%s, askip=%s' \
% (obj_dict['floating_ip_address'], vn_fq_name, tenant_name,
req_ip), level=SandeshLevel.SYS_DEBUG)
return True, ""
# end pre_dbe_create
@classmethod
def post_dbe_delete(cls, id, obj_dict, db_conn):
if obj_dict['parent_type'] == 'instance-ip':
return True, ""
vn_fq_name = obj_dict['fq_name'][:-2]
fip_addr = obj_dict['floating_ip_address']
db_conn.config_log('AddrMgmt: free FIP %s for vn=%s'
% (fip_addr, vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(fip_addr, vn_fq_name,
alloc_id=obj_dict['uuid'])
return True, ""
# end post_dbe_delete
@classmethod
def dbe_create_notification(cls, db_conn, obj_id, obj_dict):
if obj_dict['parent_type'] == 'instance-ip':
return
fip_addr = obj_dict['floating_ip_address']
vn_fq_name = obj_dict['fq_name'][:-2]
cls.addr_mgmt.ip_alloc_notify(fip_addr, vn_fq_name)
# end dbe_create_notification
@classmethod
def dbe_delete_notification(cls, obj_id, obj_dict):
if obj_dict['parent_type'] == 'instance-ip':
return
fip_addr = obj_dict['floating_ip_address']
vn_fq_name = obj_dict['fq_name'][:-2]
cls.addr_mgmt.ip_free_notify(fip_addr, vn_fq_name,
alloc_id=obj_dict['uuid'])
# end dbe_delete_notification
# end class FloatingIpServer
class AliasIpServer(Resource, AliasIp):
@classmethod
def pre_dbe_create(cls, tenant_name, obj_dict, db_conn):
vn_fq_name = obj_dict['fq_name'][:-2]
req_ip = obj_dict.get("alias_ip_address")
if req_ip and cls.addr_mgmt.is_ip_allocated(req_ip, vn_fq_name):
return (False, (409, 'Ip address already in use'))
try:
(aip_addr, sn_uuid) = cls.addr_mgmt.ip_alloc_req(vn_fq_name,
asked_ip_addr=req_ip,
alloc_id=obj_dict['uuid'])
def undo():
db_conn.config_log(
'AddrMgmt: free FIP %s for vn=%s tenant=%s, on undo'
% (fip_addr, vn_fq_name, tenant_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(aip_addr, vn_fq_name,
alloc_id=obj_dict['uuid'])
return True, ""
# end undo
get_context().push_undo(undo)
except Exception as e:
return (False, (500, str(e)))
obj_dict['alias_ip_address'] = aip_addr
db_conn.config_log('AddrMgmt: alloc %s AIP for vn=%s, tenant=%s, askip=%s' \
% (obj_dict['alias_ip_address'], vn_fq_name, tenant_name,
req_ip), level=SandeshLevel.SYS_DEBUG)
return True, ""
# end pre_dbe_create
@classmethod
def post_dbe_delete(cls, id, obj_dict, db_conn):
vn_fq_name = obj_dict['fq_name'][:-2]
aip_addr = obj_dict['alias_ip_address']
db_conn.config_log('AddrMgmt: free AIP %s for vn=%s'
% (aip_addr, vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(aip_addr, vn_fq_name,
alloc_id=obj_dict['uuid'])
return True, ""
# end post_dbe_delete
@classmethod
def dbe_create_notification(cls, db_conn, obj_id, obj_dict):
aip_addr = obj_dict['alias_ip_address']
vn_fq_name = obj_dict['fq_name'][:-2]
cls.addr_mgmt.ip_alloc_notify(aip_addr, vn_fq_name)
# end dbe_create_notification
@classmethod
def dbe_delete_notification(cls, obj_id, obj_dict):