-
Notifications
You must be signed in to change notification settings - Fork 390
/
vnc_cfg_types.py
1264 lines (1075 loc) · 50 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 is built up from an autogenerated template resource_server.py and
# 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 json
import re
import cfgm_common
import netaddr
import uuid
from vnc_quota import QuotaHelper
from gen.resource_xsd import *
from gen.resource_common import *
from gen.resource_server import *
from netaddr import IPNetwork
from pprint import pformat
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
class GlobalSystemConfigServer(GlobalSystemConfigServerGen):
@classmethod
def _check_asn(cls, obj_dict, db_conn):
global_asn = obj_dict.get('autonomous_system')
if not global_asn:
return (True, '')
(ok, result) = db_conn.dbe_list('virtual-network')
if not ok:
return (ok, result)
for vn_name, vn_uuid in result:
ok, result = db_conn.dbe_read('virtual-network', {'uuid': vn_uuid},
obj_fields=['route_target_list'])
if not ok:
return ok, result
rt_dict = result.get('route_target_list', {})
for rt in rt_dict.get('route_target', []):
(_, asn, target) = rt.split(':')
if (int(asn) == global_asn and
int(target) >= cfgm_common.BGP_RTGT_MIN_ID):
return (False, (400, "Virtual network %s is configured "
"with a route target with this ASN and route "
"target value in the same range as used by "
"automatically allocated route targets" % vn_name))
return (True, '')
# end _check_asn
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
ok, result = cls._check_asn(obj_dict, db_conn)
if not ok:
return ok, result
return True, ''
# end http_post_collection
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
ok, result = cls._check_asn(obj_dict, db_conn)
if not ok:
return ok, result
return True, ''
# end http_put
# end class GlobalSystemConfigServer
class FloatingIpServer(FloatingIpServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
proj_dict = obj_dict['project_refs'][0]
if 'uuid' in proj_dict:
proj_uuid = proj_dict['uuid']
else:
proj_uuid = db_conn.fq_name_to_uuid('project', proj_dict['to'])
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'floating_ip_back_refs',
'obj_type': 'floating-ip',
'user_visibility': user_visibility,
'proj_uuid': proj_uuid}
(ok, response) = QuotaHelper.verify_quota_for_resource(
**verify_quota_kwargs)
if not ok:
return (ok, response)
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, (403, 'Ip address already in use'))
try:
fip_addr = cls.addr_mgmt.ip_alloc_req(vn_fq_name,
asked_ip_addr=req_ip)
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 http_post_collection
@classmethod
def http_post_collection_fail(cls, tenant_name, obj_dict, db_conn):
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 tenant=%s, on post fail'
% (fip_addr, vn_fq_name, tenant_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(fip_addr, vn_fq_name)
return True, ""
# end http_post_collection_fail
@classmethod
def http_delete(cls, id, obj_dict, db_conn):
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)
return True, ""
# end http_delete
@classmethod
def http_delete_fail(cls, id, obj_dict, db_conn):
vn_fq_name = obj_dict['fq_name'][:-2]
req_ip = obj_dict.get("floating_ip_address", None)
if req_ip is None:
return True, ""
try:
cls.addr_mgmt.ip_alloc_req(vn_fq_name, asked_ip_addr=req_ip)
except Exception as e:
return (False, (500, str(e)))
db_conn.config_log('AddrMgmt: alloc %s FIP for vn=%s to recover DELETE failure'
% (obj_dict['floating_ip_address'], vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
return True, ""
# end http_delete_fail
@classmethod
def dbe_create_notification(cls, obj_ids, obj_dict):
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_ids, obj_dict):
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)
# end dbe_delete_notification
# end class FloatingIpServer
class InstanceIpServer(InstanceIpServerGen):
generate_default_instance = False
@classmethod
def _get_subnet_name(cls, vn_dict, subnet_uuid):
ipam_refs = vn_dict.get('network_ipam_refs', [])
subnet_name = None
for ipam in ipam_refs:
ipam_subnets = ipam['attr'].get('ipam_subnets', [])
for subnet in ipam_subnets:
if subnet['subnet_uuid'] == subnet_uuid:
subnet_dict = subnet['subnet']
subnet_name = subnet_dict['ip_prefix'] + '/' + str(
subnet_dict['ip_prefix_len'])
return subnet_name
@classmethod
def _is_gateway_ip(cls, vn_dict, ip_addr):
ipam_refs = vn_dict.get('network_ipam_refs', [])
for ipam in ipam_refs:
ipam_subnets = ipam['attr'].get('ipam_subnets', [])
for subnet in ipam_subnets:
if subnet['default_gateway'] == ip_addr:
return True
return False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
if ((vn_fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(vn_fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric and link-local address allocations
return True, ""
req_ip = obj_dict.get("instance_ip_address", None)
vn_id = {'uuid': db_conn.fq_name_to_uuid('virtual-network', vn_fq_name)}
(read_ok, vn_dict) = db_conn.dbe_read('virtual-network', vn_id,
obj_fields=['router_external', 'network_ipam_refs'])
if not read_ok:
return (False, (500, 'Internal error : ' + pformat(vn_dict)))
subnet_uuid = obj_dict.get('subnet_uuid', None)
sub = cls._get_subnet_name(vn_dict, subnet_uuid) if subnet_uuid else None
if subnet_uuid and not sub:
return (False, (404, "Subnet id " + subnet_uuid + " not found"))
req_ip_family = obj_dict.get("instance_ip_family", None)
if req_ip is None and subnet_uuid:
# pickup the version from subnet
req_ip_version = IPNetwork(sub).version
else:
req_ip_version = 4 # default ip v4
if req_ip_family == "v6": req_ip_version = 6
# If its an external network, check whether floating IP equivalent to
# requested fixed-IP is already reserved.
router_external = vn_dict.get('router_external', None)
if req_ip and router_external and \
not cls._is_gateway_ip(vn_dict, req_ip) and \
cls.addr_mgmt.is_ip_allocated(req_ip, vn_fq_name):
return (False, (403, 'Ip address already in use'))
try:
ip_addr = cls.addr_mgmt.ip_alloc_req(
vn_fq_name, vn_dict=vn_dict, sub=sub, asked_ip_addr=req_ip,
asked_ip_version=req_ip_version)
except Exception as e:
return (False, (500, str(e)))
obj_dict['instance_ip_address'] = ip_addr
db_conn.config_log('AddrMgmt: alloc %s for vn=%s, tenant=%s, askip=%s'
% (obj_dict['instance_ip_address'],
vn_fq_name, tenant_name, req_ip),
level=SandeshLevel.SYS_DEBUG)
return True, ""
# end http_post_collection
@classmethod
def http_post_collection_fail(cls, tenant_name, obj_dict, db_conn):
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
if ((vn_fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(vn_fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric and link-local address allocations
return True, ""
ip_addr = obj_dict['instance_ip_address']
db_conn.config_log('AddrMgmt: free IP %s, vn=%s tenant=%s on post fail'
% (ip_addr, vn_fq_name, tenant_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(ip_addr, vn_fq_name)
return True, ""
# end http_post_collection_fail
@classmethod
def http_delete(cls, id, obj_dict, db_conn):
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
if ((vn_fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(vn_fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric and link-local address allocations
return True, ""
try:
ip_addr = obj_dict['instance_ip_address']
except KeyError:
db_conn.config_log('AddrMgmt: IP Not allocated to iip = %s, vn=%s'
% (id, vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
return True, ""
db_conn.config_log('AddrMgmt: free IP %s, vn=%s'
% (ip_addr, vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
cls.addr_mgmt.ip_free_req(ip_addr, vn_fq_name)
return True, ""
# end http_delete
@classmethod
def http_delete_fail(cls, id, obj_dict, db_conn):
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
if ((vn_fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(vn_fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric and link-local address allocations
return True, ""
req_ip = obj_dict.get("instance_ip_address", None)
if req_ip is None:
return True, ""
try:
cls.addr_mgmt.ip_alloc_req(vn_fq_name, asked_ip_addr=req_ip)
except Exception as e:
return (False, (500, str(e)))
db_conn.config_log('AddrMgmt: alloc %s for vn=%s to recover DELETE failure'
% (obj_dict['instance_ip_address'], vn_fq_name),
level=SandeshLevel.SYS_DEBUG)
return True, ""
# end http_delete_fail
@classmethod
def dbe_create_notification(cls, obj_ids, obj_dict):
ip_addr = obj_dict['instance_ip_address']
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
cls.addr_mgmt.ip_alloc_notify(ip_addr, vn_fq_name)
# end dbe_create_notification
@classmethod
def dbe_delete_notification(cls, obj_ids, obj_dict):
try:
ip_addr = obj_dict['instance_ip_address']
except KeyError:
return
vn_fq_name = obj_dict['virtual_network_refs'][0]['to']
cls.addr_mgmt.ip_free_notify(ip_addr, vn_fq_name)
# end dbe_delete_notification
# end class InstanceIpServer
class LogicalRouterServer(LogicalRouterServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'logical_routers',
'obj_type': 'logical-router',
'user_visibility': user_visibility}
return QuotaHelper.verify_quota_for_resource(**verify_quota_kwargs)
# end http_post_collection
# end class LogicalRouterServer
class VirtualMachineInterfaceServer(VirtualMachineInterfaceServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
vn_dict = obj_dict['virtual_network_refs'][0]
vn_uuid = vn_dict.get('uuid')
if not vn_uuid:
vn_fq_name = vn_dict.get('to')
if not vn_fq_name:
return (False, (500, 'Internal error : ' + pformat(vn_dict)))
vn_uuid = db_conn.fq_name_to_uuid('virtual-network', vn_fq_name)
(ok, vn_dict) = db_conn.dbe_read('virtual-network', {'uuid':vn_uuid},
obj_fields=['parent_uuid'])
if not ok:
return (False, (500, 'Internal error : ' + pformat(vn_dict)))
proj_uuid = vn_dict['parent_uuid']
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'virtual_machine_interfaces',
'obj_type': 'virtual-machine-interface',
'user_visibility': user_visibility,
'proj_uuid': proj_uuid}
(ok, response) = QuotaHelper.verify_quota_for_resource(
**verify_quota_kwargs)
if not ok:
return (ok, response)
inmac = None
if 'virtual_machine_interface_mac_addresses' in obj_dict:
mc = obj_dict['virtual_machine_interface_mac_addresses']
if 'mac_address' in mc:
if len(mc['mac_address'])==1:
inmac = [m.replace("-",":") for m in mc['mac_address']]
if inmac!=None:
mac_addrs_obj = MacAddressesType(inmac)
else:
mac_addr = cls.addr_mgmt.mac_alloc(obj_dict)
mac_addrs_obj = MacAddressesType([mac_addr])
mac_addrs_json = json.dumps(
mac_addrs_obj,
default=lambda o: dict((k, v)
for k, v in o.__dict__.iteritems()))
mac_addrs_dict = json.loads(mac_addrs_json)
obj_dict['virtual_machine_interface_mac_addresses'] = mac_addrs_dict
if 'virtual_machine_interface_allowed_address_pairs' in obj_dict:
aap_config = obj_dict['virtual_machine_interface_allowed_address_pairs']
if 'allowed_address_pair' in aap_config:
aaps = aap_config['allowed_address_pair']
for aap in aaps or []:
if aap['mac'] == "":
aap['mac'] = obj_dict['virtual_machine_interface_mac_addresses']['mac_address']
return True, ""
# end http_post_collection
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
if 'virtual_machine_interface_allowed_address_pairs' in obj_dict:
vmi_id = {'uuid': id}
(read_ok, read_result) = db_conn.dbe_read('virtual-machine-interface', vmi_id)
if not read_ok:
return (False, (500, read_result))
aap_config = obj_dict['virtual_machine_interface_allowed_address_pairs']
if 'allowed_address_pair' in aap_config:
aaps = aap_config['allowed_address_pair']
for aap in aaps or []:
if aap['mac'] == "":
aap['mac'] = read_result['virtual_machine_interface_mac_addresses']['mac_address']
return True, ""
# end http_put
# end class VirtualMachineInterfaceServer
class VirtualNetworkServer(VirtualNetworkServerGen):
@classmethod
def _check_route_targets(cls, obj_dict, db_conn):
if 'route_target_list' not in obj_dict:
return (True, '')
config_uuid = db_conn.fq_name_to_uuid('global_system_config', ['default-global-system-config'])
config = db_conn.uuid_to_obj_dict(config_uuid)
global_asn = config.get('prop:autonomous_system')
if not global_asn:
return (True, '')
global_asn = json.loads(global_asn)
rt_dict = obj_dict.get('route_target_list')
if not rt_dict:
return (True, '')
for rt in rt_dict.get('route_target', []):
try:
(prefix, asn, target) = rt.split(':')
if prefix != 'target':
raise ValueError()
target = int(target)
if not asn.isdigit():
netaddr.IPAddress(asn)
except (ValueError, netaddr.core.AddrFormatError) as e:
return (False, "Route target must be of the format "
"'target:<asn>:<number>' or 'target:<ip>:number'")
if asn == global_asn and target >= cfgm_common.BGP_RTGT_MIN_ID:
return (False, "Configured route target must use ASN that is "
"different from global ASN or route target value must"
" be less than %d" % cfgm_common.BGP_RTGT_MIN_ID)
return (True, '')
# end _check_route_targets
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'virtual_networks',
'obj_type': 'virtual-network',
'user_visibility': user_visibility}
(ok, response) = QuotaHelper.verify_quota_for_resource(
**verify_quota_kwargs)
if not ok:
return (ok, response)
db_conn.update_subnet_uuid(obj_dict)
(ok, error) = cls._check_route_targets(obj_dict, db_conn)
if not ok:
return (False, (400, error))
try:
cls.addr_mgmt.net_create_req(obj_dict)
except Exception as e:
return (False, (500, str(e)))
return True, ""
# end http_post_collection
@classmethod
def http_post_collection_fail(cls, tenant_name, obj_dict, db_conn):
cls.addr_mgmt.net_delete_req(obj_dict)
return True, ""
# end post_collection_fail
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
if ((fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric subnet updates
return True, ""
if 'network_ipam_refs' not in obj_dict:
# NOP for addr-mgmt module
return True, ""
vn_id = {'uuid': id}
(read_ok, read_result) = db_conn.dbe_read('virtual-network', vn_id,
obj_fields=['network_ipam_refs'])
if not read_ok:
return (False, (500, read_result))
(ok, result) = cls.addr_mgmt.net_check_subnet(read_result, obj_dict)
if not ok:
return (ok, (409, result))
(ok, result) = cls.addr_mgmt.net_check_subnet_quota(read_result,
obj_dict, db_conn)
if not ok:
return (ok, (403, result))
(ok, result) = cls.addr_mgmt.net_check_subnet_overlap(read_result,
obj_dict)
if not ok:
return (ok, (409, result))
(ok, result) = cls.addr_mgmt.net_check_subnet_delete(read_result,
obj_dict)
if not ok:
return (ok, (409, result))
try:
cls.addr_mgmt.net_update_req(fq_name, read_result, obj_dict, id)
except Exception as e:
return (False, (500, str(e)))
db_conn.update_subnet_uuid(obj_dict)
(ok, error) = cls._check_route_targets(obj_dict, db_conn)
if not ok:
return (False, (400, error))
return True, ""
# end http_put
@classmethod
def http_put_fail(cls, id, fq_name, obj_dict, db_conn):
if ((fq_name == cfgm_common.IP_FABRIC_VN_FQ_NAME) or
(fq_name == cfgm_common.LINK_LOCAL_VN_FQ_NAME)):
# Ignore ip-fabric subnet updates
return True, ""
ipam_refs = obj_dict.get('network_ipam_refs', None)
if not ipam_refs:
# NOP for addr-mgmt module
return True, ""
vn_id = {'uuid': id}
(read_ok, read_result) = db_conn.dbe_read('virtual-network', vn_id,
obj_fields=['network_ipam_refs'])
if not read_ok:
return (False, (500, read_result))
cls.addr_mgmt.net_update_req(fq_name, obj_dict, read_result, id)
# end http_put_fail
@classmethod
def http_delete(cls, id, obj_dict, db_conn):
cls.addr_mgmt.net_delete_req(obj_dict)
return True, ""
# end http_delete
@classmethod
def http_delete_fail(cls, id, obj_dict, db_conn):
cls.addr_mgmt.net_create_req(obj_dict)
return True, ""
# end http_delete_fail
@classmethod
def ip_alloc(cls, vn_fq_name, subnet_name, count):
ip_list = [cls.addr_mgmt.ip_alloc_req(vn_fq_name, sub=subnet_name)
for i in range(count)]
msg = 'AddrMgmt: reserve %d IP for vn=%s, subnet=%s - %s' \
% (count, vn_fq_name, subnet_name if subnet_name else '', ip_list)
cls.addr_mgmt.config_log(msg, level=SandeshLevel.SYS_DEBUG)
return {'ip_addr': ip_list}
# end ip_alloc
@classmethod
def ip_free(cls, vn_fq_name, subnet_name, ip_list):
msg = 'AddrMgmt: release IP %s for vn=%s, subnet=%s' \
% (ip_list, vn_fq_name, subnet_name if subnet_name else '')
cls.addr_mgmt.config_log(msg, level=SandeshLevel.SYS_DEBUG)
for ip_addr in ip_list:
cls.addr_mgmt.ip_free_req(ip_addr, vn_fq_name, sub=subnet_name)
# end ip_free
@classmethod
def subnet_ip_count(cls, obj_dict, subnet_list):
ip_count_list = []
for item in subnet_list:
ip_count_list.append(cls.addr_mgmt.ip_count(obj_dict, item))
return {'ip_count_list': ip_count_list}
# end subnet_ip_count
@classmethod
def dbe_create_notification(cls, obj_ids, obj_dict):
cls.addr_mgmt.net_create_notify(obj_ids, obj_dict)
# end dbe_create_notification
@classmethod
def dbe_update_notification(cls, obj_ids):
cls.addr_mgmt.net_update_notify(obj_ids)
# end dbe_update_notification
@classmethod
def dbe_delete_notification(cls, obj_ids, obj_dict):
cls.addr_mgmt.net_delete_notify(obj_ids, obj_dict)
# end dbe_update_notification
# end class VirtualNetworkServer
class NetworkIpamServer(NetworkIpamServerGen):
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
ipam_uuid = obj_dict['uuid']
ipam_id = {'uuid': ipam_uuid}
(read_ok, read_result) = db_conn.dbe_read('network-ipam', ipam_id)
if not read_ok:
return (False, (500, "Internal error : IPAM is not valid"))
old_ipam_mgmt = read_result.get('network_ipam_mgmt')
new_ipam_mgmt = obj_dict.get('network_ipam_mgmt')
if not old_ipam_mgmt or not new_ipam_mgmt:
return True, ""
old_dns_method = old_ipam_mgmt.get('ipam_dns_method')
new_dns_method = new_ipam_mgmt.get('ipam_dns_method')
if not cls.is_change_allowed(old_dns_method, new_dns_method, obj_dict,
db_conn):
return (False, (409, "Cannot change DNS Method from " +
old_dns_method + " to " + new_dns_method +
" with active VMs referring to the IPAM"))
return True, ""
# end http_put
@classmethod
def http_put_fail(cls, id, fq_name, obj_dict, db_conn):
# undo any state change done by http_put function
return True, ""
# end http_put_fail
@classmethod
def is_change_allowed(cls, old, new, obj_dict, db_conn):
if (old == "default-dns-server" or old == "virtual-dns-server"):
if ((new == "tenant-dns-server" or new == "none") and
cls.is_active_vm_present(obj_dict, db_conn)):
return False
if (old == "tenant-dns-server" and new != old and
cls.is_active_vm_present(obj_dict, db_conn)):
return False
if (old == "none" and new != old and
cls.is_active_vm_present(obj_dict, db_conn)):
return False
return True
# end is_change_allowed
@classmethod
def is_active_vm_present(cls, obj_dict, db_conn):
if 'virtual_network_back_refs' in obj_dict:
vn_backrefs = obj_dict['virtual_network_back_refs']
for vn in vn_backrefs:
vn_uuid = vn['uuid']
vn_id = {'uuid': vn_uuid}
(read_ok, read_result) = db_conn.dbe_read('virtual-network',
vn_id)
if not read_ok:
continue
if 'virtual_machine_interface_back_refs' in read_result:
return True
return False
# end is_active_vm_present
# end class NetworkIpamServer
class VirtualDnsServer(VirtualDnsServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
return cls.validate_dns_server(obj_dict, db_conn)
# end http_post_collection
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
return cls.validate_dns_server(obj_dict, db_conn)
# end http_put
@classmethod
def http_put_fail(cls, id, fq_name, obj_dict, db_conn):
# undo any state change done by http_put function
return True, ""
# end http_put_fail
@classmethod
def http_delete(cls, id, obj_dict, db_conn):
vdns_name = ":".join(obj_dict['fq_name'])
if 'parent_uuid' in obj_dict:
domain_uuid = obj_dict['parent_uuid']
domain_id = {'uuid': domain_uuid}
(read_ok, read_result) = db_conn.dbe_read('domain', domain_id)
if not read_ok:
return (
False,
(500, "Internal error : Virtual DNS is not in a domain"))
virtual_DNSs = read_result.get('virtual_DNSs', [])
for vdns in virtual_DNSs:
vdns_uuid = vdns['uuid']
vdns_id = {'uuid': vdns_uuid}
(read_ok, read_result) = db_conn.dbe_read('virtual-DNS',
vdns_id)
if not read_ok:
return (
False,
(500,
"Internal error : Unable to read Virtual DNS data"))
vdns_data = read_result['virtual_DNS_data']
if 'next_virtual_DNS' in vdns_data:
if vdns_data['next_virtual_DNS'] == vdns_name:
return (
False,
(403,
"Virtual DNS server is referred"
" by other virtual DNS servers"))
return True, ""
# end http_delete
@classmethod
def http_delete_fail(cls, id, obj_dict, db_conn):
# undo any state change done by http_delete function
return True, ""
# end http_delete_fail
@classmethod
def is_valid_dns_name(cls, name):
if len(name) > 255:
return False
if name.endswith("."): # A single trailing dot is legal
# strip exactly one dot from the right, if present
name = name[:-1]
disallowed = re.compile("[^A-Z\d-]", re.IGNORECASE)
return all( # Split by labels and verify individually
(label and len(label) <= 63 # length is within proper range
# no bordering hyphens
and not label.startswith("-") and not label.endswith("-")
and not disallowed.search(label)) # contains only legal char
for label in name.split("."))
# end is_valid_dns_name
@classmethod
def is_valid_ipv4_address(cls, address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
try:
if not 0 <= int(item) <= 255:
return False
except ValueError:
return False
return True
# end is_valid_ipv4_address
@classmethod
def validate_dns_server(cls, obj_dict, db_conn):
if 'fq_name' in obj_dict:
virtual_dns = obj_dict['fq_name'][1]
disallowed = re.compile("[^A-Z\d-]", re.IGNORECASE)
if disallowed.search(virtual_dns) or virtual_dns.startswith("-"):
return (False, (403,
"Special characters are not allowed in " +
"Virtual DNS server name"))
vdns_data = obj_dict['virtual_DNS_data']
if not cls.is_valid_dns_name(vdns_data['domain_name']):
return (
False,
(403, "Domain name does not adhere to DNS name requirements"))
record_order = ["fixed", "random", "round-robin"]
if not str(vdns_data['record_order']).lower() in record_order:
return (False, (403, "Invalid value for record order"))
ttl = vdns_data['default_ttl_seconds']
if ttl < 0 or ttl > 2147483647:
return (False, (403, "Invalid value for TTL"))
if 'next_virtual_DNS' in vdns_data:
vdns_next = vdns_data['next_virtual_DNS']
if not vdns_next or vdns_next is None:
return True, ""
next_vdns = vdns_data['next_virtual_DNS'].split(":")
# check that next vdns exists
try:
next_vdns_uuid = db_conn.fq_name_to_uuid(
'virtual_DNS', next_vdns)
except Exception as e:
if not cls.is_valid_ipv4_address(
vdns_data['next_virtual_DNS']):
return (
False,
(403,
"Invalid Virtual Forwarder(next virtual dns server)"))
else:
return True, ""
# check that next virtual dns servers arent referring to each other
# above check doesnt allow during create, but entry could be
# modified later
next_vdns_id = {'uuid': next_vdns_uuid}
(read_ok, read_result) = db_conn.dbe_read(
'virtual-DNS', next_vdns_id)
if read_ok:
next_vdns_data = read_result['virtual_DNS_data']
if 'next_virtual_DNS' in next_vdns_data:
vdns_name = ":".join(obj_dict['fq_name'])
if next_vdns_data['next_virtual_DNS'] == vdns_name:
return (
False,
(403,
"Cannot have Virtual DNS Servers "
"referring to each other"))
return True, ""
# end validate_dns_server
# end class VirtualDnsServer
class VirtualDnsRecordServer(VirtualDnsRecordServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
return cls.validate_dns_record(obj_dict, db_conn)
# end http_post_collection
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
return cls.validate_dns_record(obj_dict, db_conn)
# end http_put
@classmethod
def http_put_fail(cls, id, fq_name, obj_dict, db_conn):
# undo any state change done by http_put function
return True, ""
# end http_put_fail
@classmethod
def http_delete(cls, id, obj_dict, db_conn):
return True, ""
# end http_delete
@classmethod
def http_delete_fail(cls, id, obj_dict, db_conn):
# undo any state change done by http_delete function
return True, ""
# end http_delete_fail
@classmethod
def validate_dns_record(cls, obj_dict, db_conn):
rec_data = obj_dict['virtual_DNS_record_data']
rec_types = ["a", "cname", "ptr", "ns"]
rec_type = str(rec_data['record_type']).lower()
if not rec_type in rec_types:
return (False, (403, "Invalid record type"))
if str(rec_data['record_class']).lower() != "in":
return (False, (403, "Invalid record class"))
rec_name = rec_data['record_name']
rec_value = rec_data['record_data']
# check rec_name validity
if rec_type == "ptr":
if (not VirtualDnsServer.is_valid_ipv4_address(rec_name) and
not "in-addr.arpa" in rec_name.lower()):
return (
False,
(403,
"PTR Record name has to be IP address"
" or reverse.ip.in-addr.arpa"))
elif not VirtualDnsServer.is_valid_dns_name(rec_name):
return (
False,
(403, "Record name does not adhere to DNS name requirements"))
# check rec_data validity
if rec_type == "a":
if not VirtualDnsServer.is_valid_ipv4_address(rec_value):
return (False, (403, "Invalid IP address"))
elif rec_type == "cname" or rec_type == "ptr" or rec_type == "mx":
if not VirtualDnsServer.is_valid_dns_name(rec_value):
return (
False,
(403,
"Record data does not adhere to DNS name requirements"))
elif rec_type == "ns":
try:
vdns_name = rec_value.split(":")
vdns_uuid = db_conn.fq_name_to_uuid('virtual_DNS', vdns_name)
except Exception as e:
if (not VirtualDnsServer.is_valid_ipv4_address(rec_value) and
not VirtualDnsServer.is_valid_dns_name(rec_value)):
return (
False,
(403, "Invalid virtual dns server in record data"))
ttl = rec_data['record_ttl_seconds']
if ttl < 0 or ttl > 2147483647:
return (False, (403, "Invalid value for TTL"))
if rec_type == "mx":
preference = rec_data['record_mx_preference']
if preference < 0 or preference > 65535:
return (False, (403, "Invalid value for MX record preference"))
return True, ""
# end validate_dns_record
# end class VirtualDnsRecordServer
def _check_policy_rule_uuid(entries):
if not entries:
return
for rule in entries.get('policy_rule') or []:
if not rule.get('rule_uuid'):
rule['rule_uuid'] = str(uuid.uuid4())
# end _check_policy_rule_uuid
class SecurityGroupServer(SecurityGroupServerGen):
generate_default_instance = False
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'security_groups',
'obj_type': 'security-group',
'user_visibility': user_visibility}
(ok, response) = QuotaHelper.verify_quota_for_resource(
**verify_quota_kwargs)
if not ok:
return (ok, response)
_check_policy_rule_uuid(obj_dict.get('security_group_entries'))
return True, ""
# end http_post_collection
@classmethod
def http_put(cls, id, fq_name, obj_dict, db_conn):
(ok, sec_dict) = db_conn.dbe_read('security-group', {'uuid': id})
if not ok:
return (False, (500, 'Bad Security Group error : ' + pformat(sec_dict)))
(ok, proj_dict) = QuotaHelper.get_project_dict_for_quota(
sec_dict['parent_uuid'], db_conn)
if not ok:
return (False, (500, 'Bad Project error : ' + pformat(proj_dict)))
obj_type = 'security-group-rule'
if ('security_group_entries' in obj_dict and
QuotaHelper.get_quota_limit(proj_dict, obj_type) >= 0):
rule_count = len(obj_dict['security_group_entries']['policy_rule'])
for sg in proj_dict.get('security_groups', []):
if sg['uuid'] == sec_dict['uuid']:
continue
ok, sg_dict = db_conn.dbe_read('security-group', sg)
if not ok:
continue
sge = sg_dict.get('security_group_entries', {})
rule_count += len(sge.get('policy_rule', []))
if sec_dict['id_perms'].get('user_visible', True) is not False:
(ok, quota_limit) = QuotaHelper.check_quota_limit(
proj_dict, obj_type, rule_count-1)
if not ok:
return (False, (403, pformat(fq_name) + ' : ' + quota_limit))
_check_policy_rule_uuid(obj_dict.get('security_group_entries'))
return True, ""
# end http_put
# end class SecurityGroupServer
class NetworkPolicyServer(NetworkPolicyServerGen):
@classmethod
def http_post_collection(cls, tenant_name, obj_dict, db_conn):
user_visibility = obj_dict['id_perms'].get('user_visible', True)
verify_quota_kwargs = {'db_conn': db_conn,
'fq_name': obj_dict['fq_name'],
'resource': 'network_policys',
'obj_type': 'network-policy',
'user_visibility': user_visibility}
(ok, response) = QuotaHelper.verify_quota_for_resource(
**verify_quota_kwargs)
if not ok:
return (ok, response)
_check_policy_rule_uuid(obj_dict.get('network_policy_entries'))
try: