/
sg_res_handler.py
336 lines (282 loc) · 12.9 KB
/
sg_res_handler.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
# Copyright 2015. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
from cfgm_common import exceptions as vnc_exc
from vnc_api import vnc_api
import contrail_res_handler as res_handler
import sgrule_res_handler as sgrule_handler
class SecurityGroupMixin(object):
def _security_group_vnc_to_neutron(self, sg_obj,
contrail_extensions_enabled=False,
fields=None):
sg_q_dict = {}
extra_dict = {}
extra_dict['contrail:fq_name'] = sg_obj.get_fq_name()
# replace field names
sg_q_dict['id'] = sg_obj.uuid
sg_q_dict['tenant_id'] = self._project_id_vnc_to_neutron(
sg_obj.parent_uuid)
if not sg_obj.display_name:
# for security groups created directly via vnc_api
sg_q_dict['name'] = sg_obj.get_fq_name()[-1]
else:
sg_q_dict['name'] = sg_obj.display_name
sg_q_dict['description'] = sg_obj.get_id_perms().get_description()
# get security group rules
sg_q_dict['security_group_rules'] = []
rule_list = sgrule_handler.SecurityGroupRuleHandler(
self._vnc_lib).security_group_rules_read(sg_obj)
if rule_list:
for rule in rule_list:
sg_q_dict['security_group_rules'].append(rule)
if contrail_extensions_enabled:
sg_q_dict.update(extra_dict)
if fields:
sg_q_dict = self._filter_res_dict(sg_q_dict, fields)
return sg_q_dict
# end _security_group_vnc_to_neutron
def _security_group_neutron_to_vnc(self, sg_q, sg_vnc):
if 'name' in sg_q and sg_q['name']:
sg_vnc.display_name = sg_q['name']
if 'description' in sg_q:
id_perms = sg_vnc.get_id_perms()
id_perms.set_description(sg_q['description'])
sg_vnc.set_id_perms(id_perms)
return sg_vnc
# end _security_group_neutron_to_vnc
def _create_default_security_group(self, proj_obj):
def _get_rule(ingress, sg, prefix, ethertype):
sgr_uuid = str(uuid.uuid4())
if sg:
addr = vnc_api.AddressType(
security_group=proj_obj.get_fq_name_str() + ':' + sg)
elif prefix:
addr = vnc_api.AddressType(
subnet=vnc_api.SubnetType(prefix, 0))
local_addr = vnc_api.AddressType(security_group='local')
if ingress:
src_addr = addr
dst_addr = local_addr
else:
src_addr = local_addr
dst_addr = addr
rule = vnc_api.PolicyRuleType(
rule_uuid=sgr_uuid, direction='>', protocol='any',
src_addresses=[src_addr],
src_ports=[vnc_api.PortType(0, 65535)],
dst_addresses=[dst_addr],
dst_ports=[vnc_api.PortType(0, 65535)],
ethertype=ethertype)
return rule
rules = [_get_rule(True, 'default', None, 'IPv4'),
_get_rule(True, 'default', None, 'IPv6'),
_get_rule(False, None, '0.0.0.0', 'IPv4'),
_get_rule(False, None, '::', 'IPv6')]
sg_rules = vnc_api.PolicyEntriesType(rules)
# create security group
id_perms = vnc_api.IdPermsType(enable=True,
description='Default security group')
sg_obj = vnc_api.SecurityGroup(
name='default', parent_obj=proj_obj,
id_perms=id_perms,
security_group_entries=sg_rules)
self._vnc_lib.security_group_create(sg_obj)
return sg_obj.uuid
def _ensure_default_security_group_exists(self, proj_id):
if proj_id is None:
projects = self._vnc_lib.projects_list()['projects']
for project in projects:
self._ensure_default_security_group_exists(project['uuid'])
return
proj_id = self._project_id_neutron_to_vnc(proj_id)
proj_obj = self._vnc_lib.project_read(id=proj_id,
fields=['security_groups'])
sg_groups = proj_obj.get_security_groups()
for sg_group in sg_groups or []:
if sg_group['to'][-1] == 'default':
return sg_group['uuid']
return self._create_default_security_group(proj_obj)
# end _ensure_default_security_group_exists
class SecurityGroupBaseGet(res_handler.ResourceGetHandler):
resource_get_method = "security_group_read"
class SecurityGroupGetHandler(SecurityGroupBaseGet, SecurityGroupMixin):
resource_list_method = "security_groups_list"
def get_sg_obj(self, id=None, fq_name_str=None):
return self._resource_get(id=id, fq_name_str=fq_name_str)
def resource_get(self, context, sg_id, fields=None):
contrail_extensions_enabled = self._kwargs.get(
'contrail_extensions_enabled', False)
try:
sg_obj = self._resource_get(id=sg_id)
except vnc_exc.NoIdError:
self._raise_contrail_exception(
'SecurityGroupNotFound', id=sg_id, resource='security_group')
return self._security_group_vnc_to_neutron(
sg_obj, contrail_extensions_enabled, fields=fields)
def resource_list_by_project(self, project_id):
if project_id:
try:
project_uuid = self._project_id_neutron_to_vnc(project_id)
# Trigger a project read to ensure project sync
self._project_read(proj_id=project_uuid)
except Exception:
raise
else:
project_uuid = None
sg_objs = self._resource_list(parent_id=project_uuid,
detail=True)
return sg_objs
def resource_list(self, context, filters=None, fields=None):
ret_list = []
contrail_extensions_enabled = self._kwargs.get(
'contrail_extensions_enabled', False)
# collect phase
self._ensure_default_security_group_exists(context['tenant'])
all_sgs = [] # all sgs in all projects
if context and not context['is_admin']:
project_sgs = self.resource_list_by_project(
self._project_id_neutron_to_vnc(context['tenant']))
all_sgs.append(project_sgs)
else: # admin context
if filters and 'tenant_id' in filters:
project_ids = self._validate_project_ids(
context, filters['tenant_id'])
for p_id in project_ids:
project_sgs = self.resource_list_by_project(p_id)
all_sgs.append(project_sgs)
else: # no filters
all_sgs.append(self.resource_list_by_project(None))
# prune phase
no_rule = res_handler.SGHandler(
self._vnc_lib).get_no_rule_security_group(create=False)
for project_sgs in all_sgs:
for sg_obj in project_sgs:
if no_rule and sg_obj.uuid == no_rule.uuid:
continue
if not self._filters_is_present(
filters, 'id', sg_obj.uuid):
continue
if not self._filters_is_present(
filters, 'name',
sg_obj.get_display_name() or sg_obj.name):
continue
if not self._filters_is_present(
filters, 'description',
sg_obj.get_id_perms().get_description()):
continue
sg_info = self._security_group_vnc_to_neutron(
sg_obj, contrail_extensions_enabled, fields=fields)
ret_list.append(sg_info)
return ret_list
class SecurityGroupDeleteHandler(SecurityGroupBaseGet,
res_handler.ResourceDeleteHandler):
resource_delete_method = "security_group_delete"
def resource_delete(self, context, sg_id):
try:
sg_obj = self._resource_get(id=sg_id)
if sg_obj.name == 'default' and (
self._project_id_neutron_to_vnc(context['tenant']) ==
sg_obj.parent_uuid):
# Deny delete if the security group name is default and
# the owner of the SG is deleting it.
self._raise_contrail_exception(
'SecurityGroupCannotRemoveDefault')
except vnc_exc.NoIdError:
return
try:
self._resource_delete(sg_id)
except vnc_exc.RefsExistError:
self._raise_contrail_exception(
'SecurityGroupInUse', id=sg_id, resource='security_group')
class SecurityGroupUpdateHandler(res_handler.ResourceUpdateHandler,
SecurityGroupBaseGet,
SecurityGroupMixin):
resource_update_method = "security_group_update"
def resource_update_obj(self, sg_obj):
self._resource_update(sg_obj)
def resource_update(self, context, sg_id, sg_q):
sg_q['id'] = sg_id
contrail_extensions_enabled = self._kwargs.get(
'contrail_extensions_enabled', False)
try:
sg_obj = self._security_group_neutron_to_vnc(
sg_q,
self._resource_get(id=sg_id))
except vnc_exc.NoIdError:
self._raise_contrail_exception(
'SecurityGroupNotFound', id=sg_id, resource='security_group')
self._resource_update(sg_obj)
ret_sg_q = self._security_group_vnc_to_neutron(
sg_obj, contrail_extensions_enabled)
return ret_sg_q
class SecurityGroupCreateHandler(res_handler.ResourceCreateHandler,
SecurityGroupMixin):
resource_create_method = "security_group_create"
def _create_security_group(self, sg_q):
project_id = self._project_id_neutron_to_vnc(sg_q['tenant_id'])
try:
project_obj = self._project_read(proj_id=project_id)
except vnc_exc.NoIdError:
raise self._raise_contrail_exception(
'ProjectNotFound', project_id=project_id,
resource='security_group')
id_perms = vnc_api.IdPermsType(enable=True,
description=sg_q.get('description'))
sg_vnc = vnc_api.SecurityGroup(name=sg_q['name'],
parent_obj=project_obj,
id_perms=id_perms)
return sg_vnc
def resource_create(self, context, sg_q):
contrail_extensions_enabled = self._kwargs.get(
'contrail_extensions_enabled', False)
sg_obj = self._security_group_neutron_to_vnc(
sg_q,
self._create_security_group(sg_q))
# ensure default SG and deny create if the group name is default
if sg_q['name'] == 'default':
self._ensure_default_security_group_exists(sg_q['tenant_id'])
self._raise_contrail_exception(
"SecurityGroupAlreadyExists", resource='security_group')
sg_uuid = self._resource_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'
def_rule['ethertype'] = 'IPv4'
def_rule['security_group_id'] = sg_uuid
sgrule_handler.SecurityGroupRuleHandler(
self._vnc_lib).resource_create(context, def_rule)
def_rule = {}
def_rule['port_range_min'] = 0
def_rule['port_range_max'] = 65535
def_rule['direction'] = 'egress'
def_rule['remote_ip_prefix'] = None
def_rule['remote_group_id'] = None
def_rule['protocol'] = 'any'
def_rule['ethertype'] = 'IPv6'
def_rule['security_group_id'] = sg_uuid
sgrule_handler.SecurityGroupRuleHandler(
self._vnc_lib).resource_create(context, def_rule)
ret_sg_q = self._security_group_vnc_to_neutron(
sg_obj, contrail_extensions_enabled)
return ret_sg_q
class SecurityGroupHandler(SecurityGroupGetHandler,
SecurityGroupCreateHandler,
SecurityGroupUpdateHandler,
SecurityGroupDeleteHandler):
pass