Debian Codegraph @

neutron_fwaas/tests/unit/services/firewall/test_fwaas_plugin_v2.py

raw symbols SCIP
1 # Copyright 2016
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import contextlib
17
18 from unittest import mock
19 import webob.exc
20
21 from neutron.api import extensions as api_ext
22 from neutron.db import servicetype_db as sdb
23 from neutron.tests.common import test_db_base_plugin_v2 as test_db_plugin
24 from neutron_lib.api.definitions import firewall_v2
25 from neutron_lib.callbacks import events
26 from neutron_lib import constants as nl_constants
27 from neutron_lib import context
28 from neutron_lib.exceptions import firewall_v2 as f_exc
29 from neutron_lib.plugins import directory
30 from oslo_utils import importutils
31
32 from neutron_fwaas.common import fwaas_constants
33 from neutron_fwaas import extensions
34 from neutron_fwaas.services.firewall import fwaas_plugin_v2
35 from neutron_fwaas.services.firewall.service_drivers.driver_api import \
36 FirewallDriverDB
37
38
39 def http_client_error(req, res):
40 explanation = "Request '{} {} {}' failed: {}".format(req.method, req.url,
41 req.body, res.body)
42 return webob.exc.HTTPClientError(code=res.status_int,
43 explanation=explanation)
44
45
46 class DummyDriverDB(FirewallDriverDB):
47 def is_supported_l2_port(self, port):
48 return True
49
50 def is_supported_l3_port(self, port):
51 return True
52
53
54 class FirewallPluginV2TestCase(test_db_plugin.NeutronDbPluginV2TestCase):
55 DESCRIPTION = 'default description'
56 PROTOCOL = 'tcp'
57 IP_VERSION = 4
58 SOURCE_IP_ADDRESS_RAW = '1.1.1.1'
59 DESTINATION_IP_ADDRESS_RAW = '2.2.2.2'
60 SOURCE_PORT = '55000:56000'
61 DESTINATION_PORT = '56000:57000'
62 ACTION = 'allow'
63 AUDITED = True
64 ENABLED = True
65 ADMIN_STATE_UP = True
66 SHARED = True
67
68 resource_prefix_map = {
69 k: firewall_v2.API_PREFIX
70 for k in firewall_v2.RESOURCE_ATTRIBUTE_MAP.keys()
71 }
72
73 def setUp(self, service_provider=None, core_plugin=None,
74 extra_service_plugins=None, extra_extension_paths=None):
75 provider = fwaas_constants.FIREWALL_V2
76 if not service_provider:
77 provider += (':dummy:neutron_fwaas.tests.unit.services.firewall.'
78 'test_fwaas_plugin_v2.DummyDriverDB:default')
79 else:
80 provider += ':test:' + service_provider + ':default'
81
82 bits = provider.split(':')
83 provider = {
84 'service_type': bits[0],
85 'name': bits[1],
86 'driver': bits[2],
87 'default': True,
88 }
89 # override the default service provider
90 self.service_providers = (
91 mock.patch.object(sdb.ServiceTypeManager,
92 'get_service_providers').start())
93 self.service_providers.return_value = [provider]
94
95 plugin_str = ('neutron_fwaas.services.firewall.fwaas_plugin_v2.'
96 'FirewallPluginV2')
97 service_plugins = {'fw_plugin_name': plugin_str}
98 service_plugins.update(extra_service_plugins or {})
99
100 # we need to provide a plugin instance, although the extension manager
101 # will create a new instance of the plugin
102 plugins = {
103 fwaas_constants.FIREWALL_V2: fwaas_plugin_v2.FirewallPluginV2(),
104 }
105 for plugin_name, plugin_str in (extra_service_plugins or {}).items():
106 plugins[plugin_name] = importutils.import_object(plugin_str)
107 ext_mgr = api_ext.PluginAwareExtensionManager(
108 ':'.join(extensions.__path__ + (extra_extension_paths or [])),
109 plugins,
110 )
111
112 super().setUp(
113 plugin=core_plugin,
114 service_plugins=service_plugins,
115 ext_mgr=ext_mgr,
116 )
117
118 # find the Firewall plugin that was instantiated by the extension
119 # manager
120 self.plugin = directory.get_plugin(fwaas_constants.FIREWALL_V2)
121
122 def _get_admin_context(self):
123 # FIXME NOTE(ivasilevskaya) seems that test framework treats context
124 # with user_id=None/project_id=None (return value of
125 # context._get_admin_context() method) in a somewhat special way.
126 # So as a workaround to have the framework behave properly right now
127 # let's implement our own _get_admin_context method and look into the
128 # matter some other time.
129 return context.Context(user_id='admin',
130 project_id='admin-tenant',
131 is_admin=True).elevated()
132
133 def _get_nonadmin_context(self, user_id='non-admin', project_id='tenant1'):
134 return context.Context(user_id=user_id, project_id=project_id,
135 roles=['member', 'reader'])
136
137 def _test_list_resources(self, resource, items, neutron_context=None,
138 query_params=None, as_admin=False):
139 if resource.endswith('y'):
140 resource_plural = resource.replace('y', 'ies')
141 else:
142 resource_plural = resource + 's'
143
144 res = self._list(resource_plural, query_params=query_params,
145 as_admin=as_admin)
146 resource = resource.replace('-', '_')
147 self.assertEqual(
148 sorted([i[resource]['id'] for i in items]),
149 sorted([i['id'] for i in res[resource_plural]]))
150
151 def _list_req(self, resource_plural, ctx=None, as_admin=False):
152 if not ctx:
153 ctx = self._get_admin_context()
154 req = self.new_list_request(resource_plural, as_admin=as_admin)
155 req.environ['neutron.context'] = ctx
156 return self.deserialize(
157 self.fmt, req.get_response(self.ext_api))[resource_plural]
158
159 def _show_req(self, resource_plural, obj_id, ctx=None):
160 req = self.new_show_request(resource_plural, obj_id, fmt=self.fmt)
161 if not ctx:
162 ctx = self._get_admin_context()
163 req.environ['neutron.context'] = ctx
164 res = self.deserialize(
165 self.fmt, req.get_response(self.ext_api))
166 return res
167
168 def _build_default_fwg(self, ctx=None, is_one=True, as_admin=False):
169 res = self._list_req('firewall_groups', ctx=ctx, as_admin=as_admin)
170 if is_one:
171 self.assertEqual(1, len(res))
172 return res[0]
173 return res
174
175 def _get_test_firewall_rule_attrs(self, name='firewall_rule1'):
176 attrs = {'name': name,
177 'tenant_id': self._project_id,
178 'project_id': self._project_id,
179 'protocol': self.PROTOCOL,
180 'ip_version': self.IP_VERSION,
181 'source_ip_address': self.SOURCE_IP_ADDRESS_RAW,
182 'destination_ip_address': self.DESTINATION_IP_ADDRESS_RAW,
183 'source_port': self.SOURCE_PORT,
184 'destination_port': self.DESTINATION_PORT,
185 'action': self.ACTION,
186 'enabled': self.ENABLED,
187 'shared': self.SHARED}
188 return attrs
189
190 def _get_test_firewall_policy_attrs(self, name='firewall_policy1',
191 audited=AUDITED):
192 attrs = {'name': name,
193 'description': self.DESCRIPTION,
194 'tenant_id': self._project_id,
195 'project_id': self._project_id,
196 'firewall_rules': [],
197 'audited': audited,
198 'shared': self.SHARED}
199 return attrs
200
201 def _get_test_firewall_group_attrs(self, name='firewall_1',
202 status=nl_constants.CREATED):
203 attrs = {'name': name,
204 'tenant_id': self._project_id,
205 'project_id': self._project_id,
206 'admin_state_up': self.ADMIN_STATE_UP,
207 'status': status}
208
209 return attrs
210
211 def _create_firewall_policy(self, fmt, name, description, shared,
212 firewall_rules, audited,
213 expected_res_status=None, as_admin=False,
214 **kwargs):
215 data = {'firewall_policy': {'name': name,
216 'description': description,
217 'firewall_rules': firewall_rules,
218 'audited': audited,
219 'shared': shared}}
220 ctx = kwargs.get('context', None)
221 if ctx is None or ctx.is_admin:
222 project_id = kwargs.get('project_id', self._project_id)
223 data['firewall_policy'].update({'tenant_id': project_id})
224 data['firewall_policy'].update({'project_id': project_id})
225
226 req = self.new_create_request('firewall_policies', data, fmt,
227 context=ctx, as_admin=as_admin)
228 res = req.get_response(self.ext_api)
229 if expected_res_status:
230 self.assertEqual(expected_res_status, res.status_int)
231 elif res.status_int >= 400:
232 raise http_client_error(req, res)
233
234 return res
235
236 def _replace_firewall_status(self, attrs, old_status, new_status):
237 if attrs['status'] is old_status:
238 attrs['status'] = new_status
239 return attrs
240
241 @contextlib.contextmanager
242 def firewall_policy(self, fmt=None, name='firewall_policy1',
243 description=DESCRIPTION, shared=SHARED,
244 firewall_rules=None, audited=True,
245 do_delete=True, as_admin=False, **kwargs):
246 if firewall_rules is None:
247 firewall_rules = []
248 if not fmt:
249 fmt = self.fmt
250 res = self._create_firewall_policy(fmt, name, description, shared,
251 firewall_rules, audited,
252 as_admin=as_admin, **kwargs)
253 if res.status_int >= 400:
254 raise webob.exc.HTTPClientError(code=res.status_int)
255 firewall_policy = self.deserialize(fmt or self.fmt, res)
256 yield firewall_policy
257 if do_delete:
258 self._delete('firewall_policies',
259 firewall_policy['firewall_policy']['id'],
260 as_admin=True)
261
262 def _create_firewall_rule(self, fmt, name, shared, protocol,
263 ip_version, source_ip_address,
264 destination_ip_address, source_port,
265 destination_port, action, enabled,
266 expected_res_status=None, as_admin=False,
267 **kwargs):
268 project_id = kwargs.get('project_id', self._project_id)
269 data = {'firewall_rule': {'name': name,
270 'protocol': protocol,
271 'ip_version': ip_version,
272 'source_ip_address': source_ip_address,
273 'destination_ip_address':
274 destination_ip_address,
275 'source_port': source_port,
276 'destination_port': destination_port,
277 'action': action,
278 'enabled': enabled,
279 'shared': shared}}
280 ctx = kwargs.get('context', None)
281 if ctx is None or ctx.is_admin:
282 project_id = kwargs.get('project_id', self._project_id)
283 data['firewall_rule'].update({'tenant_id': project_id})
284 data['firewall_rule'].update({'project_id': project_id})
285
286 req = self.new_create_request('firewall_rules', data, fmt, context=ctx,
287 as_admin=as_admin)
288 res = req.get_response(self.ext_api)
289 if expected_res_status:
290 self.assertEqual(expected_res_status, res.status_int)
291 elif res.status_int >= 400:
292 raise http_client_error(req, res)
293
294 return res
295
296 @contextlib.contextmanager
297 def firewall_rule(self, fmt=None, name='firewall_rule1',
298 shared=SHARED, protocol=PROTOCOL, ip_version=IP_VERSION,
299 source_ip_address=SOURCE_IP_ADDRESS_RAW,
300 destination_ip_address=DESTINATION_IP_ADDRESS_RAW,
301 source_port=SOURCE_PORT,
302 destination_port=DESTINATION_PORT,
303 action=ACTION, enabled=ENABLED,
304 do_delete=True, as_admin=False, **kwargs):
305 if not fmt:
306 fmt = self.fmt
307 res = self._create_firewall_rule(fmt, name, shared, protocol,
308 ip_version, source_ip_address,
309 destination_ip_address,
310 source_port, destination_port,
311 action, enabled, as_admin=as_admin,
312 **kwargs)
313 if res.status_int >= 400:
314 raise webob.exc.HTTPClientError(code=res.status_int)
315 firewall_rule = self.deserialize(fmt or self.fmt, res)
316 yield firewall_rule
317 if do_delete:
318 self._delete('firewall_rules',
319 firewall_rule['firewall_rule']['id'],
320 as_admin=True)
321
322 def _create_firewall_group(self, fmt, name, description,
323 ingress_firewall_policy_id=None,
324 egress_firewall_policy_id=None,
325 ports=None, admin_state_up=True,
326 expected_res_status=None,
327 as_admin=False, **kwargs):
328 if ingress_firewall_policy_id is None:
329 default_policy = kwargs.get('default_policy', True)
330 if default_policy:
331 res = self._create_firewall_policy(
332 fmt,
333 'fwp',
334 description=self.DESCRIPTION,
335 shared=self.SHARED,
336 firewall_rules=[],
337 audited=self.AUDITED,
338 as_admin=as_admin,
339 )
340 firewall_policy = self.deserialize(fmt or self.fmt, res)
341 fwp_id = firewall_policy["firewall_policy"]["id"]
342 ingress_firewall_policy_id = fwp_id
343 data = {'firewall_group': {
344 'name': name,
345 'description': description,
346 'ingress_firewall_policy_id': ingress_firewall_policy_id,
347 'egress_firewall_policy_id': egress_firewall_policy_id,
348 'admin_state_up': admin_state_up}}
349 ctx = kwargs.get('context', None)
350 if ctx is None or ctx.is_admin:
351 project_id = kwargs.get('project_id', self._project_id)
352 data['firewall_group'].update({'tenant_id': project_id})
353 data['firewall_group'].update({'project_id': project_id})
354 if ports is not None:
355 data['firewall_group'].update({'ports': ports})
356
357 req = self.new_create_request('firewall_groups', data, fmt,
358 context=ctx, as_admin=as_admin)
359 res = req.get_response(self.ext_api)
360 if expected_res_status:
361 self.assertEqual(expected_res_status, res.status_int)
362 elif res.status_int >= 400:
363 raise http_client_error(req, res)
364 return res
365
366 @contextlib.contextmanager
367 def firewall_group(self, fmt=None, name='firewall_1',
368 description=DESCRIPTION,
369 ingress_firewall_policy_id=None,
370 egress_firewall_policy_id=None,
371 ports=None, admin_state_up=True,
372 do_delete=True, as_admin=False, **kwargs):
373 if not fmt:
374 fmt = self.fmt
375 res = self._create_firewall_group(fmt, name, description,
376 ingress_firewall_policy_id,
377 egress_firewall_policy_id,
378 ports=ports,
379 admin_state_up=admin_state_up,
380 as_admin=as_admin,
381 **kwargs)
382 if res.status_int >= 400:
383 raise webob.exc.HTTPClientError(code=res.status_int)
384 firewall_group = self.deserialize(fmt or self.fmt, res)
385 yield firewall_group
386 if do_delete:
387 self.plugin.driver.firewall_db.update_firewall_group_status(
388 context.get_admin_context(),
389 firewall_group['firewall_group']['id'],
390 nl_constants.ACTIVE)
391 data = {
392 'firewall_group': {
393 'ports': [],
394 },
395 }
396 req = self.new_update_request(
397 'firewall_groups',
398 data,
399 firewall_group['firewall_group']['id'],
400 as_admin=True,
401 )
402 req.get_response(self.ext_api)
403 self._delete('firewall_groups',
404 firewall_group['firewall_group']['id'],
405 as_admin=True)
406
407 def _rule_action(self, action, id, firewall_rule_id, insert_before=None,
408 insert_after=None, expected_code=webob.exc.HTTPOk.code,
409 expected_body=None, body_data=None, as_admin=False):
410 # We intentionally do this check for None since we want to distinguish
411 # from empty dictionary
412 if body_data is None:
413 if action == 'insert':
414 body_data = {'firewall_rule_id': firewall_rule_id,
415 'insert_before': insert_before,
416 'insert_after': insert_after}
417 else:
418 body_data = {'firewall_rule_id': firewall_rule_id}
419
420 req = self.new_action_request('firewall_policies',
421 body_data, id,
422 "%s_rule" % action, as_admin=as_admin)
423 res = req.get_response(self.ext_api)
424 self.assertEqual(expected_code, res.status_int)
425 response = self.deserialize(self.fmt, res)
426 if 'standard_attr_id' in response:
427 del response['standard_attr_id']
428 if expected_body:
429 self.assertEqual(expected_body, response)
430 return response
431
432 def _compare_firewall_rule_lists(self, firewall_policy_id,
433 observed_list, expected_list):
434 position = 0
435 for r1, r2 in zip(observed_list, expected_list):
436 rule = r1['firewall_rule']
437 rule['firewall_policy_id'] = firewall_policy_id
438 position += 1
439 rule['position'] = position
440 for k in rule:
441 self.assertEqual(r2[k], rule[k])
442
443 def _test_create_firewall_group(self, attrs):
444 with self.firewall_policy(as_admin=True) as fwp:
445 fwp_id = fwp['firewall_policy']['id']
446 attrs['ingress_firewall_policy_id'] = fwp_id
447 attrs['egress_firewall_policy_id'] = fwp_id
448 with self.firewall_group(
449 name=attrs['name'],
450 ingress_firewall_policy_id=fwp_id,
451 egress_firewall_policy_id=fwp_id,
452 admin_state_up=self.ADMIN_STATE_UP,
453 ports=attrs['ports'] if 'ports' in attrs else None,
454 ) as firewall_group:
455 for k, v in attrs.items():
456 self.assertEqual(v, firewall_group['firewall_group'][k])
457
458
459 class TestFirewallPluginBasev2(FirewallPluginV2TestCase):
460
461 def _test_fwg_with_port(self, device_owner):
462 with self.port(device_owner=device_owner) as port:
463 with self.firewall_rule(as_admin=True) as fwr:
464 fwr_id = fwr['firewall_rule']['id']
465 with self.firewall_policy(firewall_rules=[fwr_id],
466 as_admin=True) as fwp:
467 fwp_id = fwp['firewall_policy']['id']
468 self.firewall_group(
469 self.fmt,
470 "firewall_group",
471 self.DESCRIPTION,
472 ports=[port['port']['id']],
473 ingress_firewall_policy_id=fwp_id,
474 )
475
476 def test_create_fwg_with_l3_ports(self):
477 for device_owner_for_l3 in nl_constants.ROUTER_INTERFACE_OWNERS:
478 self._test_fwg_with_port(device_owner_for_l3)
479
480 def test_create_fwg_with_l2_port(self):
481 device_owner_for_l2 = nl_constants.DEVICE_OWNER_COMPUTE_PREFIX + 'nova'
482 self._test_fwg_with_port(device_owner_for_l2)
483
484 def test_create_firewall_group_with_with_wrong_type_port(self):
485 with self.port(device_owner="wrong port type") as port:
486 self._create_firewall_group(
487 self.fmt,
488 "firewall_group1",
489 self.DESCRIPTION,
490 ports=[port['port']['id']],
491 expected_res_status=webob.exc.HTTPConflict.code,
492 as_admin=True,
493 )
494
495 def test_update_firewall_group_with_with_wrong_type_port(self):
496 with self.firewall_group(as_admin=True) as firewall_group:
497 with self.port(device_owner="wrong port type") as port:
498 data = {
499 'firewall_group': {
500 'ports': [port['port']['id']],
501 },
502 }
503 req = self.new_update_request(
504 'firewall_groups',
505 data,
506 firewall_group['firewall_group']['id'],
507 )
508 res = req.get_response(self.ext_api)
509 self.assertEqual(webob.exc.HTTPConflict.code, res.status_int)
510
511 def test_create_firewall_group_with_router_port_already_in_use(self):
512 with self.port(
513 device_owner=nl_constants.DEVICE_OWNER_ROUTER_INTF) as port:
514 with self.firewall_group(ports=[port['port']['id']],
515 as_admin=True):
516 self._create_firewall_group(
517 self.fmt,
518 "firewall_group2",
519 self.DESCRIPTION,
520 ports=[port['port']['id']],
521 expected_res_status=webob.exc.HTTPConflict.code,
522 as_admin=True,
523 )
524
525 def test_create_firewall_group_with_dvr_port_already_in_use(self):
526 with self.port(
527 device_owner=nl_constants.DEVICE_OWNER_DVR_INTERFACE) as port:
528 with self.firewall_group(ports=[port['port']['id']],
529 as_admin=True):
530 self._create_firewall_group(
531 self.fmt,
532 "firewall_group2",
533 self.DESCRIPTION,
534 ports=[port['port']['id']],
535 expected_res_status=webob.exc.HTTPConflict.code,
536 as_admin=True,
537 )
538
539 def test_update_firewall_group_with_port_already_in_use(self):
540 with self.port(
541 device_owner=nl_constants.DEVICE_OWNER_ROUTER_INTF) as port:
542 with self.firewall_group(ports=[port['port']['id']],
543 as_admin=True):
544 with self.firewall_group(as_admin=True) as firewall_group:
545 data = {
546 'firewall_group': {
547 'ports': [port['port']['id']],
548 },
549 }
550 req = self.new_update_request(
551 'firewall_groups',
552 data,
553 firewall_group['firewall_group']['id'],
554 )
555 res = req.get_response(self.ext_api)
556 self.assertEqual(webob.exc.HTTPConflict.code,
557 res.status_int)
558
559 def test_firewall_group_policy_rule_can_be_updated(self):
560 pending_status = [nl_constants.PENDING_CREATE,
561 nl_constants.PENDING_UPDATE,
562 nl_constants.PENDING_DELETE]
563
564 for status in pending_status:
565 with self.firewall_rule(as_admin=True) as fwr:
566 fwr_id = fwr['firewall_rule']['id']
567 with self.firewall_policy(firewall_rules=[fwr_id],
568 as_admin=True) as fwp:
569 fwp_id = fwp['firewall_policy']['id']
570 with self.firewall_group(
571 ingress_firewall_policy_id=fwp_id) as fwg:
572 self.plugin.driver.firewall_db.\
573 update_firewall_group_status(
574 context.get_admin_context(),
575 fwg['firewall_group']['id'],
576 status
577 )
578 data = {
579 'firewall_rule': {
580 'name': 'new_name',
581 },
582 }
583 req = self.new_update_request(
584 'firewall_rules',
585 data,
586 fwr_id,
587 )
588 res = req.get_response(self.ext_api)
589 self.assertEqual(webob.exc.HTTPConflict.code,
590 res.status_int)
591
592 def test_create_firewall_policy_with_other_project_not_shared_rule(self):
593 project1_context = self._get_nonadmin_context(project_id='project1')
594 project2_context = self._get_nonadmin_context(project_id='project2')
595 with self.firewall_rule(context=project1_context, shared=False) as fwr:
596 fwr_id = fwr['firewall_rule']['id']
597 self.firewall_policy(
598 context=project2_context,
599 firewall_rules=[fwr_id],
600 expected_res_status=webob.exc.HTTPNotFound.code,
601 )
602
603 def test_update_firewall_policy_with_other_project_not_shared_rule(self):
604 project1_context = self._get_nonadmin_context(project_id='project1')
605 project2_context = self._get_nonadmin_context(project_id='project2')
606 with self.firewall_rule(context=project1_context, shared=False) as fwr:
607 with self.firewall_policy(context=project2_context,
608 shared=False) as fwp:
609 fwr_id = fwr['firewall_rule']['id']
610 fwp_id = fwp['firewall_policy']['id']
611 data = {
612 'firewall_policy': {
613 'firewall_rules': [fwr_id],
614 },
615 }
616 req = self.new_update_request('firewall_policy', data, fwp_id)
617 res = req.get_response(self.ext_api)
618 self.assertEqual(webob.exc.HTTPNotFound.code, res.status_int)
619
620 def test_create_firewall_policy_with_other_project_shared_rule(self):
621 admin_context = self._get_admin_context()
622 project1_context = self._get_nonadmin_context(project_id='project1')
623 with self.firewall_rule(context=admin_context, shared=True,
624 as_admin=True) as fwr:
625 fwr_id = fwr['firewall_rule']['id']
626 self.firewall_policy(
627 context=project1_context,
628 firewall_rules=[fwr_id],
629 expected_res_status=webob.exc.HTTPOk.code,
630 )
631
632
633 class TestAutomaticAssociation(TestFirewallPluginBasev2):
634 def setUp(self):
635 # TODO(yushiro): Replace constant value for this test class
636 # Set auto association fwg
637 super().setUp()
638
639 def test_vm_port(self):
640 port = {
641 "id": "fake_port",
642 "device_owner": "compute:nova",
643 "binding:vif_type": "ovs",
644 "binding:vif_details": {"ovs_hybrid_plug": False},
645 "project_id": "fake_project",
646 "port_security_enabled": True,
647 }
648 self.plugin._core_plugin.get_port = mock.Mock(return_value=port)
649 fake_default_fwg = {
650 'id': 'fake_id',
651 'name': 'default',
652 'ports': ['fake_port_id1'],
653 }
654 self.plugin.get_firewall_groups = \
655 mock.Mock(return_value=[fake_default_fwg])
656 self.plugin.update_firewall_group = mock.Mock()
657 kwargs = {
658 "context": mock.ANY,
659 "port": port,
660 "original_port": {"binding:vif_type": "unbound"}
661 }
662 states = (kwargs['original_port'], kwargs['port'])
663 payload = events.DBEventPayload(mock.ANY, states=states)
664 self.plugin.handle_update_port(
665 "PORT", "after_update", "test_plugin", payload=payload)
666 self.plugin.get_firewall_groups.assert_called_once_with(
667 mock.ANY,
668 filters={
669 'tenant_id': [kwargs['port']['project_id']],
670 'name': [fake_default_fwg['name']],
671 },
672 fields=['id', 'ports'],
673 )
674 port_ids = fake_default_fwg['ports'] + [kwargs['port']['id']]
675 self.plugin.update_firewall_group.assert_called_once_with(
676 mock.ANY,
677 fake_default_fwg['id'],
678 {'firewall_group': {'ports': port_ids}},
679 )
680
681 def test_vm_port_not_newly_created(self):
682 self.plugin.get_firewall_group = mock.Mock()
683 self.plugin.update_firewall_group = mock.Mock()
684 # Just updated for VM port(name or description...etc.)
685 kwargs = {
686 "context": mock.ANY,
687 "port": {
688 "id": "fake_port",
689 "device_owner": "compute:nova",
690 "binding:vif_type": "ovs",
691 "project_id": "fake_project"
692 },
693 "original_port": {
694 "device_owner": "compute:nova",
695 "binding:vif_type": "ovs",
696 "project_id": "fake_project"
697 }
698 }
699 states = (kwargs['original_port'], kwargs['port'])
700 payload = events.DBEventPayload(mock.ANY, states=states)
701 self.plugin.handle_update_port(
702 "PORT", "after_update", "test_plugin", payload=payload)
703 self.plugin.get_firewall_group.assert_not_called()
704 self.plugin.update_firewall_group.assert_not_called()
705
706 def test_not_vm_port(self):
707 self.plugin.get_firewall_group = mock.Mock()
708 self.plugin.update_firewall_group = mock.Mock()
709 for device_owner in ["network:router_interface",
710 "network:router_gateway",
711 "network:dhcp"]:
712
713 states = ({"device_owner": device_owner,
714 "binding:vif_type": "unbound",
715 "project_id": "fake_project"},
716 {"id": "fake_port",
717 "device_owner": device_owner,
718 "project_id": "fake_project"})
719 payload = events.DBEventPayload(mock.ANY, states=states)
720 self.plugin.handle_update_port(
721 "PORT", "after_update", "test_plugin", payload=payload)
722 self.plugin.get_firewall_group.assert_not_called()
723 self.plugin.update_firewall_group.assert_not_called()
724
725 def test_set_port_for_default_firewall_group_raised_port_in_use(self):
726 port_id = 'fake_port_id_already_associated_to_default_fw'
727 port = {
728 "id": port_id,
729 "device_owner": "compute:nova",
730 "binding:vif_type": "ovs",
731 "binding:vif_details": {"ovs_hybrid_plug": False},
732 "project_id": "fake_project",
733 "port_security_enabled": True,
734 }
735 self.plugin._core_plugin.get_port = mock.Mock(return_value=port)
736 self.plugin.get_firewall_groups = mock.Mock(return_value=[])
737 self.plugin.update_firewall_group = mock.Mock(
738 side_effect=f_exc.FirewallGroupPortInUse(port_ids=[port_id]))
739 states = ({"binding:vif_type": "unbound"}, port)
740 payload = events.DBEventPayload(mock.ANY, states=states)
741 try:
742 self.plugin.handle_update_port("PORT", "after_update",
743 "test_plugin", payload=payload)
744 except f_exc.FirewallGroupPortInUse:
745 self.fail("Associating port to default firewall group raises "
746 "'FirewallGroupPortInUse' while it should ignore it")