-
Notifications
You must be signed in to change notification settings - Fork 390
/
neutron_plugin_db.py
4017 lines (3425 loc) · 161 KB
/
neutron_plugin_db.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, Contrail Systems, Inc.
#
"""
.. attention:: Fix the license string
"""
import requests
import re
import uuid
import json
import time
import socket
import netaddr
from netaddr import IPNetwork, IPSet, IPAddress
import gevent
import bottle
from neutron.common import constants
from neutron.common import exceptions
from neutron.api.v2 import attributes as attr
from cfgm_common import exceptions as vnc_exc
from vnc_api.vnc_api import *
_DEFAULT_HEADERS = {
'Content-type': 'application/json; charset="UTF-8"', }
# TODO find if there is a common definition
CREATE = 1
READ = 2
UPDATE = 3
DELETE = 4
IP_PROTOCOL_MAP = {constants.PROTO_NAME_TCP: constants.PROTO_NUM_TCP,
constants.PROTO_NAME_UDP: constants.PROTO_NUM_UDP,
constants.PROTO_NAME_ICMP: constants.PROTO_NUM_ICMP,
constants.PROTO_NAME_ICMP_V6: constants.PROTO_NUM_ICMP_V6}
# SNAT defines
SNAT_SERVICE_TEMPLATE_FQ_NAME = ['default-domain', 'netns-snat-template']
# Security group Exceptions
class SecurityGroupInvalidPortRange(exceptions.InvalidInput):
message = _("For TCP/UDP protocols, port_range_min must be "
"<= port_range_max")
class SecurityGroupInvalidPortValue(exceptions.InvalidInput):
message = _("Invalid value for port %(port)s")
class SecurityGroupInvalidIcmpValue(exceptions.InvalidInput):
message = _("Invalid value for ICMP %(field)s (%(attr)s) "
"%(value)s. It must be 0 to 255.")
class SecurityGroupMissingIcmpType(exceptions.InvalidInput):
message = _("ICMP code (port-range-max) %(value)s is provided"
" but ICMP type (port-range-min) is missing.")
class SecurityGroupInUse(exceptions.InUse):
message = _("Security Group %(id)s in use.")
class SecurityGroupCannotRemoveDefault(exceptions.InUse):
message = _("Removing default security group not allowed.")
class SecurityGroupCannotUpdateDefault(exceptions.InUse):
message = _("Updating default security group not allowed.")
class SecurityGroupDefaultAlreadyExists(exceptions.InUse):
message = _("Default security group already exists.")
class SecurityGroupRuleInvalidProtocol(exceptions.InvalidInput):
message = _("Security group rule protocol %(protocol)s not supported. "
"Only protocol values %(values)s and their integer "
"representation (0 to 255) are supported.")
class SecurityGroupRulesNotSingleTenant(exceptions.InvalidInput):
message = _("Multiple tenant_ids in bulk security group rule create"
" not allowed")
class SecurityGroupRemoteGroupAndRemoteIpPrefix(exceptions.InvalidInput):
message = _("Only remote_ip_prefix or remote_group_id may "
"be provided.")
class SecurityGroupProtocolRequiredWithPorts(exceptions.InvalidInput):
message = _("Must also specify protocol if port range is given.")
class SecurityGroupNotSingleGroupRules(exceptions.InvalidInput):
message = _("Only allowed to update rules for "
"one security profile at a time")
class SecurityGroupNotFound(exceptions.NotFound):
message = _("Security group %(id)s does not exist")
class SecurityGroupRuleNotFound(exceptions.NotFound):
message = _("Security group rule %(id)s does not exist")
class DuplicateSecurityGroupRuleInPost(exceptions.InUse):
message = _("Duplicate Security Group Rule in POST.")
class SecurityGroupRuleExists(exceptions.InUse):
message = _("Security group rule already exists. Group id is %(id)s.")
class SecurityGroupRuleParameterConflict(exceptions.InvalidInput):
message = _("Conflicting value ethertype %(ethertype)s for CIDR %(cidr)s")
# L3 Exceptions
class RouterNotFound(exceptions.NotFound):
message = _("Router %(router_id)s could not be found")
class RouterInUse(exceptions.InUse):
message = _("Router %(router_id)s still has ports")
class RouterInterfaceNotFound(exceptions.NotFound):
message = _("Router %(router_id)s does not have "
"an interface with id %(port_id)s")
class RouterInterfaceNotFoundForSubnet(exceptions.NotFound):
message = _("Router %(router_id)s has no interface "
"on subnet %(subnet_id)s")
class RouterInterfaceInUseByFloatingIP(exceptions.InUse):
message = _("Router interface for subnet %(subnet_id)s on router "
"%(router_id)s cannot be deleted, as it is required "
"by one or more floating IPs.")
class FloatingIPNotFound(exceptions.NotFound):
message = _("Floating IP %(floatingip_id)s could not be found")
class ExternalGatewayForFloatingIPNotFound(exceptions.NotFound):
message = _("External network %(external_network_id)s is not reachable "
"from subnet %(subnet_id)s. Therefore, cannot associate "
"Port %(port_id)s with a Floating IP.")
class FloatingIPPortAlreadyAssociated(exceptions.InUse):
message = _("Cannot associate floating IP %(floating_ip_address)s "
"(%(fip_id)s) with port %(port_id)s "
"using fixed IP %(fixed_ip)s, as that fixed IP already "
"has a floating IP on external network %(net_id)s.")
class L3PortInUse(exceptions.InUse):
message = _("Port %(port_id)s has owner %(device_owner)s and therefore"
" cannot be deleted directly via the port API.")
class RouterExternalGatewayInUseByFloatingIp(exceptions.InUse):
message = _("Gateway cannot be updated for router %(router_id)s, since a "
"gateway to external network %(net_id)s is required by one or "
"more floating IPs.")
# Allowed Address Pair
class AddressPairMatchesPortFixedIPAndMac(exceptions.InvalidInput):
message = _("Port's Fixed IP and Mac Address match an address pair entry.")
class DBInterface(object):
"""
An instance of this class forwards requests to vnc cfg api (web)server
"""
Q_URL_PREFIX = '/extensions/ct'
def __init__(self, admin_name, admin_password, admin_tenant_name,
api_srvr_ip, api_srvr_port, user_info=None,
contrail_extensions_enabled=True,
list_optimization_enabled=False):
self._api_srvr_ip = api_srvr_ip
self._api_srvr_port = api_srvr_port
self._db_cache = {}
self._db_cache['q_networks'] = {}
self._db_cache['q_subnets'] = {}
self._db_cache['q_subnet_maps'] = {}
self._db_cache['q_policies'] = {}
self._db_cache['q_ipams'] = {}
self._db_cache['q_routers'] = {}
self._db_cache['q_floatingips'] = {}
self._db_cache['q_ports'] = {}
self._db_cache['q_fixed_ip_to_subnet'] = {}
#obj-uuid to tenant-uuid mapping
self._db_cache['q_obj_to_tenant'] = {}
self._db_cache['q_tenant_to_def_sg'] = {}
#port count per tenant-id
self._db_cache['q_tenant_port_count'] = {}
self._db_cache['vnc_networks'] = {}
self._db_cache['vnc_ports'] = {}
self._db_cache['vnc_projects'] = {}
self._db_cache['vnc_instance_ips'] = {}
self._db_cache['vnc_routers'] = {}
self._contrail_extensions_enabled = contrail_extensions_enabled
self._list_optimization_enabled = list_optimization_enabled
# Retry till a api-server is up
connected = False
while not connected:
try:
# TODO remove hardcode
self._vnc_lib = VncApi(admin_name, admin_password,
admin_tenant_name, api_srvr_ip,
api_srvr_port, '/', user_info=user_info)
connected = True
except requests.exceptions.RequestException as e:
gevent.sleep(3)
# TODO remove this backward compat code eventually
# changes 'net_fq_name_str pfx/len' key to 'net_id pfx/len' key
subnet_map = self._vnc_lib.kv_retrieve(key=None)
for kv_dict in subnet_map:
key = kv_dict['key']
if len(key.split()) == 1:
subnet_id = key
# uuid key, fixup value portion to 'net_id pfx/len' format
# if not already so
if len(kv_dict['value'].split(':')) == 1:
# new format already, skip
continue
net_fq_name = kv_dict['value'].split()[0].split(':')
try:
net_obj = self._virtual_network_read(fq_name=net_fq_name)
except NoIdError:
self._vnc_lib.kv_delete(subnet_id)
continue
new_subnet_key = '%s %s' % (net_obj.uuid,
kv_dict['value'].split()[1])
self._vnc_lib.kv_store(subnet_id, new_subnet_key)
else: # subnet key
if len(key.split()[0].split(':')) == 1:
# new format already, skip
continue
# delete old key, convert to new key format and save
old_subnet_key = key
self._vnc_lib.kv_delete(old_subnet_key)
subnet_id = kv_dict['value']
net_fq_name = key.split()[0].split(':')
try:
net_obj = self._virtual_network_read(fq_name=net_fq_name)
except NoIdError:
continue
new_subnet_key = '%s %s' % (net_obj.uuid, key.split()[1])
self._vnc_lib.kv_store(new_subnet_key, subnet_id)
#end __init__
# Helper routines
def _request_api_server(self, url, method, data=None, headers=None):
if method == 'GET':
return requests.get(url)
if method == 'POST':
return requests.post(url, data=data, headers=headers)
if method == 'DELETE':
return requests.delete(url)
#end _request_api_server
def _relay_request(self, request):
"""
Send received request to api server
"""
# chop neutron parts of url and add api server address
url_path = re.sub(self.Q_URL_PREFIX, '', request.environ['PATH_INFO'])
url = "http://%s:%s%s" % (self._api_srvr_ip, self._api_srvr_port,
url_path)
return self._request_api_server(
url, request.environ['REQUEST_METHOD'],
request.body, {'Content-type': request.environ['CONTENT_TYPE']})
#end _relay_request
def _validate_project_ids(self, context, project_ids):
if context and not context['is_admin']:
return [context['tenant']]
return_project_ids = []
for project_id in project_ids:
try:
return_project_ids.append(str(uuid.UUID(project_id)))
except ValueError:
continue
return return_project_ids
def _obj_to_dict(self, obj):
return self._vnc_lib.obj_to_dict(obj)
#end _obj_to_dict
def _get_plugin_property(self, property_in):
fq_name=['default-global-system-config'];
gsc_obj = self._vnc_lib.global_system_config_read(fq_name);
plugin_settings = gsc_obj.plugin_tuning.plugin_property
for each_setting in plugin_settings:
if each_setting.property == property_in:
return each_setting.value
return None
#end _get_plugin_property
def _ensure_instance_exists(self, instance_id):
instance_name = instance_id
instance_obj = VirtualMachine(instance_name)
try:
id = self._vnc_lib.obj_to_id(instance_obj)
instance_obj = self._vnc_lib.virtual_machine_read(id=id)
except NoIdError: # instance doesn't exist, create it
# check if instance_id is a uuid value or not
try:
uuid.UUID(instance_id)
instance_obj.uuid = instance_id
except ValueError:
# if instance_id is not a valid uuid, let
# virtual_machine_create generate uuid for the vm
pass
self._vnc_lib.virtual_machine_create(instance_obj)
return instance_obj
#end _ensure_instance_exists
def _ensure_default_security_group_exists(self, proj_id):
# check in cache
sg_uuid = self._db_cache_read('q_tenant_to_def_sg', proj_id)
if sg_uuid:
return
# check in api server
proj_obj = self._vnc_lib.project_read(id=proj_id)
sg_groups = proj_obj.get_security_groups()
for sg_group in sg_groups or []:
if sg_group['to'][-1] == 'default':
self._db_cache_write('q_tenant_to_def_sg',
proj_id, sg_group['uuid'])
return
# does not exist hence create and add cache
sg_uuid = str(uuid.uuid4())
self._db_cache_write('q_tenant_to_def_sg', proj_id, sg_uuid)
sg_obj = SecurityGroup(name='default', parent_obj=proj_obj)
sg_obj.uuid = sg_uuid
self._vnc_lib.security_group_create(sg_obj)
#allow all egress traffic
def_rule = {}
def_rule['port_range_min'] = 0
def_rule['port_range_max'] = 65535
def_rule['direction'] = 'egress'
def_rule['remote_ip_prefix'] = '0.0.0.0/0'
def_rule['remote_group_id'] = None
def_rule['protocol'] = 'any'
rule = self._security_group_rule_neutron_to_vnc(def_rule, CREATE)
self._security_group_rule_create(sg_obj.uuid, rule)
#allow ingress traffic from within default security group
def_rule = {}
def_rule['port_range_min'] = 0
def_rule['port_range_max'] = 65535
def_rule['direction'] = 'ingress'
def_rule['remote_ip_prefix'] = '0.0.0.0/0'
def_rule['remote_group_id'] = None
def_rule['protocol'] = 'any'
rule = self._security_group_rule_neutron_to_vnc(def_rule, CREATE)
self._security_group_rule_create(sg_obj.uuid, rule)
#end _ensure_default_security_group_exists
def _db_cache_read(self, table, key):
try:
return self._db_cache[table][key]
except KeyError:
return None
#end _db_cache_read
def _db_cache_write(self, table, key, val):
self._db_cache[table][key] = val
#end _db_cache_write
def _db_cache_delete(self, table, key):
try:
del self._db_cache[table][key]
except Exception:
pass
#end _db_cache_delete
def _db_cache_flush(self, table):
self._db_cache[table] = {}
#end _db_cache_delete
def _get_obj_tenant_id(self, q_type, obj_uuid):
# Get the mapping from cache, else seed cache and return
try:
return self._db_cache['q_obj_to_tenant'][obj_uuid]
except KeyError:
# Seed the cache and return
if q_type == 'port':
port_obj = self._virtual_machine_interface_read(obj_uuid)
if port_obj.parent_type != "project":
net_id = port_obj.get_virtual_network_refs()[0]['uuid']
# recurse up type-hierarchy
tenant_id = self._get_obj_tenant_id('network', net_id)
else:
tenant_id = port_obj.parent_uuid.replace('-', '')
self._set_obj_tenant_id(obj_uuid, tenant_id)
return tenant_id
if q_type == 'network':
net_obj = self._virtual_network_read(net_id=obj_uuid)
tenant_id = net_obj.parent_uuid.replace('-', '')
self._set_obj_tenant_id(obj_uuid, tenant_id)
return tenant_id
return None
#end _get_obj_tenant_id
def _set_obj_tenant_id(self, obj_uuid, tenant_uuid):
self._db_cache['q_obj_to_tenant'][obj_uuid] = tenant_uuid
#end _set_obj_tenant_id
def _del_obj_tenant_id(self, obj_uuid):
try:
del self._db_cache['q_obj_to_tenant'][obj_uuid]
except Exception:
pass
#end _del_obj_tenant_id
def _project_read(self, proj_id=None, fq_name=None):
if proj_id:
try:
# disable cache for now as fip pool might be put without
# neutron knowing it
raise KeyError
#return self._db_cache['vnc_projects'][proj_id]
except KeyError:
proj_obj = self._vnc_lib.project_read(id=proj_id)
fq_name_str = json.dumps(proj_obj.get_fq_name())
self._db_cache['vnc_projects'][proj_id] = proj_obj
self._db_cache['vnc_projects'][fq_name_str] = proj_obj
return proj_obj
if fq_name:
fq_name_str = json.dumps(fq_name)
try:
# disable cache for now as fip pool might be put without
# neutron knowing it
raise KeyError
#return self._db_cache['vnc_projects'][fq_name_str]
except KeyError:
proj_obj = self._vnc_lib.project_read(fq_name=fq_name)
self._db_cache['vnc_projects'][fq_name_str] = proj_obj
self._db_cache['vnc_projects'][proj_obj.uuid] = proj_obj
return proj_obj
#end _project_read
def _get_tenant_id_for_create(self, context, resource):
if context['is_admin'] and 'tenant_id' in resource:
tenant_id = resource['tenant_id']
elif ('tenant_id' in resource and
resource['tenant_id'] != context['tenant_id']):
reason = _('Cannot create resource for another tenant')
self._raise_contrail_exception(400, exceptions.AdminRequired(reason=reason))
else:
tenant_id = context['tenant_id']
return tenant_id
def _raise_contrail_exception(self, code, exc):
exc_info = {'message': str(exc)}
bottle.abort(code, json.dumps(exc_info))
def _security_group_rule_create(self, sg_id, sg_rule):
try:
sg_vnc = self._vnc_lib.security_group_read(id=sg_id)
except NoIdError:
self._raise_contrail_exception(404, SecurityGroupNotFound(id=sg_id))
rules = sg_vnc.get_security_group_entries()
if rules is None:
rules = PolicyEntriesType([sg_rule])
else:
rules.add_policy_rule(sg_rule)
sg_vnc.set_security_group_entries(rules)
self._vnc_lib.security_group_update(sg_vnc)
return
#end _security_group_rule_create
def _security_group_rule_find(self, sgr_id):
dom_projects = self._project_list_domain(None)
for project in dom_projects:
proj_id = project['uuid']
project_sgs = self._security_group_list_project(proj_id)
for sg_obj in project_sgs:
sgr_entries = sg_obj.get_security_group_entries()
if sgr_entries == None:
continue
for sg_rule in sgr_entries.get_policy_rule():
if sg_rule.get_rule_uuid() == sgr_id:
return sg_obj, sg_rule
return None, None
#end _security_group_rule_find
def _security_group_rule_delete(self, sg_obj, sg_rule):
rules = sg_obj.get_security_group_entries()
rules.get_policy_rule().remove(sg_rule)
sg_obj.set_security_group_entries(rules)
self._vnc_lib.security_group_update(sg_obj)
return
#end _security_group_rule_delete
def _security_group_delete(self, sg_id):
self._vnc_lib.security_group_delete(id=sg_id)
#end _security_group_delete
def _svc_instance_create(self, si_obj):
si_uuid = self._vnc_lib.service_instance_create(si_obj)
st_fq_name = ['default-domain', 'nat-template']
st_obj = self._vnc_lib.service_template_read(fq_name=st_fq_name)
si_obj.set_service_template(st_obj)
self._vnc_lib.service_instance_update(si_obj)
return si_uuid
#end _svc_instance_create
def _svc_instance_delete(self, si_id):
self._vnc_lib.service_instance_delete(id=si_id)
#end _svc_instance_delete
def _route_table_create(self, rt_obj):
rt_uuid = self._vnc_lib.route_table_create(rt_obj)
return rt_uuid
#end _route_table_create
def _route_table_delete(self, rt_id):
self._vnc_lib.route_table_delete(id=rt_id)
#end _route_table_delete
def _resource_create(self, resource_type, obj):
try:
obj_uuid = getattr(self._vnc_lib, resource_type + '_create')(obj)
except RefsExistError:
obj.uuid = str(uuid.uuid4())
obj.name += '-' + obj.uuid
obj.fq_name[-1] += '-' + obj.uuid
obj_uuid = getattr(self._vnc_lib, resource_type + '_create')(obj)
except PermissionDenied as e:
exc_info = {'type': 'BadRequest', 'message': str(e)}
bottle.abort(400, json.dumps(exc_info))
return obj_uuid
#end _resource_create
def _virtual_network_read(self, net_id=None, fq_name=None, fields=None):
if net_id:
try:
# return self._db_cache['vnc_networks'][net_id]
raise KeyError
except KeyError:
net_obj = self._vnc_lib.virtual_network_read(id=net_id,
fields=fields)
fq_name_str = json.dumps(net_obj.get_fq_name())
self._db_cache['vnc_networks'][net_id] = net_obj
self._db_cache['vnc_networks'][fq_name_str] = net_obj
return net_obj
if fq_name:
fq_name_str = json.dumps(fq_name)
try:
# return self._db_cache['vnc_networks'][fq_name_str]
raise KeyError
except KeyError:
net_obj = self._vnc_lib.virtual_network_read(fq_name=fq_name,
fields=fields)
self._db_cache['vnc_networks'][fq_name_str] = net_obj
self._db_cache['vnc_networks'][net_obj.uuid] = net_obj
return net_obj
#end _virtual_network_read
def _virtual_network_update(self, net_obj):
try:
self._vnc_lib.virtual_network_update(net_obj)
except PermissionDenied as e:
exc_info = {'type': 'BadRequest', 'message': str(e)}
bottle.abort(400, json.dumps(exc_info))
except RefsExistError as e:
self._raise_contrail_exception(400, exceptions.BadRequest(
resource='network', msg=str(e)))
# read back to get subnet gw allocated by api-server
fq_name_str = json.dumps(net_obj.get_fq_name())
self._db_cache['vnc_networks'][net_obj.uuid] = net_obj
self._db_cache['vnc_networks'][fq_name_str] = net_obj
#end _virtual_network_update
def _virtual_network_delete(self, net_id):
fq_name_str = None
try:
net_obj = self._db_cache['vnc_networks'][net_id]
fq_name_str = json.dumps(net_obj.get_fq_name())
except KeyError:
net_obj = None
try:
if net_obj and net_obj.get_floating_ip_pools():
fip_pools = net_obj.get_floating_ip_pools()
for fip_pool in fip_pools:
self._floating_ip_pool_delete(fip_pool_id=fip_pool['uuid'])
self._vnc_lib.virtual_network_delete(id=net_id)
except RefsExistError:
self._raise_contrail_exception(404, exceptions.NetworkInUse(net_id=net_id))
try:
del self._db_cache['vnc_networks'][net_id]
if fq_name_str:
del self._db_cache['vnc_networks'][fq_name_str]
except KeyError:
pass
#end _virtual_network_delete
def _virtual_network_list(self, parent_id=None, obj_uuids=None,
fields=None, detail=False, count=False):
return self._vnc_lib.virtual_networks_list(
parent_id=parent_id,
obj_uuids=obj_uuids,
fields=fields,
detail=detail,
count=count)
#end _virtual_network_list
def _virtual_machine_interface_read(self, port_id=None, fq_name=None,
fields=None):
back_ref_fields = ['logical_router_back_refs', 'instance_ip_back_refs', 'floating_ip_back_refs']
if fields:
n_extra_fields = list(set(fields + back_ref_fields))
else:
n_extra_fields = back_ref_fields
if port_id:
try:
# return self._db_cache['vnc_ports'][port_id]
raise KeyError
except KeyError:
port_obj = self._vnc_lib.virtual_machine_interface_read(
id=port_id, fields=n_extra_fields)
fq_name_str = json.dumps(port_obj.get_fq_name())
self._db_cache['vnc_ports'][port_id] = port_obj
self._db_cache['vnc_ports'][fq_name_str] = port_obj
return port_obj
if fq_name:
fq_name_str = json.dumps(fq_name)
try:
# return self._db_cache['vnc_ports'][fq_name_str]
raise KeyError
except KeyError:
port_obj = self._vnc_lib.virtual_machine_interface_read(
fq_name=fq_name, fields=n_extra_fields)
self._db_cache['vnc_ports'][fq_name_str] = port_obj
self._db_cache['vnc_ports'][port_obj.uuid] = port_obj
return port_obj
#end _virtual_machine_interface_read
def _virtual_machine_interface_update(self, port_obj):
self._vnc_lib.virtual_machine_interface_update(port_obj)
fq_name_str = json.dumps(port_obj.get_fq_name())
self._db_cache['vnc_ports'][port_obj.uuid] = port_obj
self._db_cache['vnc_ports'][fq_name_str] = port_obj
#end _virtual_machine_interface_update
def _virtual_machine_interface_delete(self, port_id):
fq_name_str = None
try:
port_obj = self._db_cache['vnc_ports'][port_id]
fq_name_str = json.dumps(port_obj.get_fq_name())
except KeyError:
port_obj = None
self._vnc_lib.virtual_machine_interface_delete(id=port_id)
try:
del self._db_cache['vnc_ports'][port_id]
if fq_name_str:
del self._db_cache['vnc_ports'][fq_name_str]
except KeyError:
pass
#end _virtual_machine_interface_delete
def _virtual_machine_interface_list(self, parent_id=None, back_ref_id=None,
obj_uuids=None, fields=None):
back_ref_fields = ['logical_router_back_refs', 'instance_ip_back_refs', 'floating_ip_back_refs']
if fields:
n_extra_fields = list(set(fields + back_ref_fields))
else:
n_extra_fields = back_ref_fields
vmi_objs = self._vnc_lib.virtual_machine_interfaces_list(
parent_id=parent_id,
back_ref_id=back_ref_id,
obj_uuids=obj_uuids,
detail=True,
fields=n_extra_fields)
return vmi_objs
#end _virtual_machine_interface_list
def _instance_ip_create(self, iip_obj):
iip_uuid = self._vnc_lib.instance_ip_create(iip_obj)
return iip_uuid
#end _instance_ip_create
def _instance_ip_read(self, instance_ip_id=None, fq_name=None):
if instance_ip_id:
try:
# return self._db_cache['vnc_instance_ips'][instance_ip_id]
raise KeyError
except KeyError:
iip_obj = self._vnc_lib.instance_ip_read(id=instance_ip_id)
fq_name_str = json.dumps(iip_obj.get_fq_name())
self._db_cache['vnc_instance_ips'][instance_ip_id] = iip_obj
self._db_cache['vnc_instance_ips'][fq_name_str] = iip_obj
return iip_obj
if fq_name:
fq_name_str = json.dumps(fq_name)
try:
# return self._db_cache['vnc_instance_ips'][fq_name_str]
raise KeyError
except KeyError:
iip_obj = self._vnc_lib.instance_ip_read(fq_name=fq_name)
self._db_cache['vnc_instance_ips'][fq_name_str] = iip_obj
self._db_cache['vnc_instance_ips'][iip_obj.uuid] = iip_obj
return iip_obj
#end _instance_ip_read
def _instance_ip_update(self, iip_obj):
self._vnc_lib.instance_ip_update(iip_obj)
fq_name_str = json.dumps(iip_obj.get_fq_name())
self._db_cache['vnc_instance_ips'][iip_obj.uuid] = iip_obj
self._db_cache['vnc_instance_ips'][fq_name_str] = iip_obj
#end _instance_ip_update
def _instance_ip_delete(self, instance_ip_id):
fq_name_str = None
try:
iip_obj = self._db_cache['vnc_instance_ips'][instance_ip_id]
fq_name_str = json.dumps(iip_obj.get_fq_name())
except KeyError:
iip_obj = None
self._vnc_lib.instance_ip_delete(id=instance_ip_id)
try:
del self._db_cache['vnc_instance_ips'][instance_ip_id]
if fq_name_str:
del self._db_cache['vnc_instance_ips'][fq_name_str]
except KeyError:
pass
#end _instance_ip_delete
def _instance_ip_list(self, back_ref_id=None, obj_uuids=None, fields=None):
iip_objs = self._vnc_lib.instance_ips_list(detail=True,
back_ref_id=back_ref_id,
obj_uuids=obj_uuids,
fields=fields)
return iip_objs
#end _instance_ip_list
def _floating_ip_pool_create(self, fip_pool_obj):
fip_pool_uuid = self._vnc_lib.floating_ip_pool_create(fip_pool_obj)
return fip_pool_uuid
# end _floating_ip_pool_create
def _floating_ip_pool_delete(self, fip_pool_id):
fip_pool_uuid = self._vnc_lib.floating_ip_pool_delete(id=fip_pool_id)
# end _floating_ip_pool_delete
# find projects on a given domain
def _project_list_domain(self, domain_id):
# TODO till domain concept is not present in keystone
fq_name = ['default-domain']
resp_dict = self._vnc_lib.projects_list(parent_fq_name=fq_name)
return resp_dict['projects']
#end _project_list_domain
# find network ids on a given project
def _network_list_project(self, project_id, count=False):
if project_id:
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
else:
project_uuid = None
if count:
ret_val = self._virtual_network_list(parent_id=project_uuid,
count=True)
else:
ret_val = self._virtual_network_list(parent_id=project_uuid,
detail=True)
return ret_val
#end _network_list_project
# find router ids on a given project
def _router_list_project(self, project_id=None):
if project_id:
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
return []
else:
project_uuid = None
resp_dict = self._vnc_lib.logical_routers_list(parent_id=project_uuid)
return resp_dict['logical-routers']
#end _router_list_project
def _ipam_list_project(self, project_id):
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
resp_dict = self._vnc_lib.network_ipams_list(parent_id=project_uuid)
return resp_dict['network-ipams']
#end _ipam_list_project
def _security_group_list_project(self, project_id):
if project_id:
try:
project_uuid = str(uuid.UUID(project_id))
# Trigger a project read to ensure project sync
project_obj = self._project_read(proj_id=project_uuid)
except Exception:
print "Error in converting uuid %s" % (project_id)
else:
project_uuid = None
sg_objs = self._vnc_lib.security_groups_list(parent_id=project_uuid,
detail=True)
return sg_objs
#end _security_group_list_project
def _security_group_entries_list_sg(self, sg_id):
try:
sg_uuid = str(uuid.UUID(sg_id))
except Exception:
print "Error in converting SG uuid %s" % (sg_id)
resp_dict = self._vnc_lib.security_groups_list(obj_uuids=[sg_uuid])
return resp_dict['security-groups']
#end _security_group_entries_list_sg
def _route_table_list_project(self, project_id):
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
resp_dict = self._vnc_lib.route_tables_list(parent_id=project_uuid)
return resp_dict['route-tables']
#end _route_table_list_project
def _svc_instance_list_project(self, project_id):
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
resp_dict = self._vnc_lib.service_instances_list(parent_id=project_id)
return resp_dict['service-instances']
#end _svc_instance_list_project
def _policy_list_project(self, project_id):
try:
project_uuid = str(uuid.UUID(project_id))
except Exception:
print "Error in converting uuid %s" % (project_id)
resp_dict = self._vnc_lib.network_policys_list(parent_id=project_uuid)
return resp_dict['network-policys']
#end _policy_list_project
def _logical_router_read(self, rtr_id=None, fq_name=None):
if rtr_id:
try:
# return self._db_cache['vnc_routers'][rtr_id]
raise KeyError
except KeyError:
rtr_obj = self._vnc_lib.logical_router_read(id=rtr_id)
fq_name_str = json.dumps(rtr_obj.get_fq_name())
self._db_cache['vnc_routers'][rtr_id] = rtr_obj
self._db_cache['vnc_routers'][fq_name_str] = rtr_obj
return rtr_obj
if fq_name:
fq_name_str = json.dumps(fq_name)
try:
# return self._db_cache['vnc_routers'][fq_name_str]
raise KeyError
except KeyError:
rtr_obj = self._vnc_lib.logical_router_read(fq_name=fq_name)
self._db_cache['vnc_routers'][fq_name_str] = rtr_obj
self._db_cache['vnc_routers'][rtr_obj.uuid] = rtr_obj
return rtr_obj
#end _logical_router_read
def _logical_router_update(self, rtr_obj):
self._vnc_lib.logical_router_update(rtr_obj)
fq_name_str = json.dumps(rtr_obj.get_fq_name())
self._db_cache['vnc_routers'][rtr_obj.uuid] = rtr_obj
self._db_cache['vnc_routers'][fq_name_str] = rtr_obj
#end _logical_router_update
def _logical_router_delete(self, rtr_id):
fq_name_str = None
try:
rtr_obj = self._db_cache['vnc_routers'][rtr_id]
fq_name_str = json.dumps(rtr_obj.get_fq_name())
except KeyError:
pass
try:
self._vnc_lib.logical_router_delete(id=rtr_id)
except RefsExistError:
self._raise_contrail_exception(409, RouterInUse(router_id=rtr_id))
try:
del self._db_cache['vnc_routers'][rtr_id]
if fq_name_str:
del self._db_cache['vnc_routers'][fq_name_str]
except KeyError:
pass
#end _logical_router_delete
def _floatingip_list(self, back_ref_id=None):
return self._vnc_lib.floating_ips_list(back_ref_id=back_ref_id,
detail=True)
#end _floatingip_list
# find floating ip pools a project has access to
def _fip_pool_refs_project(self, project_id):
project_obj = self._project_read(proj_id=project_id)
return project_obj.get_floating_ip_pool_refs()
#end _fip_pool_refs_project
def _network_list_shared_and_ext(self):
ret_list = []
nets = self._network_list_project(project_id=None)
for net in nets:
if net.get_router_external() and net.get_is_shared():
ret_list.append(net)
return ret_list
# end _network_list_router_external
def _network_list_router_external(self):
ret_list = []
nets = self._network_list_project(project_id=None)
for net in nets:
if not net.get_router_external():
continue
ret_list.append(net)