Debian Codegraph @

neutron_fwaas/services/firewall/service_drivers/agents/l3reference/firewall_l3_agent_v2.py

raw symbols SCIP
1 # Copyright (c) 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 from neutron.agent.linux import ip_lib
17 from neutron_lib.agent import l3_extension
18 from neutron_lib import constants as nl_constants
19 from neutron_lib import context
20 from neutron_lib.exceptions import firewall_v2 as fw_ext
21 from neutron_lib import rpc as n_rpc
22 from oslo_config import cfg
23 from oslo_log import helpers as log_helpers
24 from oslo_log import log as logging
25
26 from neutron_fwaas.common import fwaas_constants
27 from neutron_fwaas.common import resources as f_resources
28 from neutron_fwaas.services.firewall.service_drivers.agents import\
29 firewall_agent_api as api
30 from neutron_fwaas.services.firewall.service_drivers.agents import\
31 firewall_service
32
33
34 LOG = logging.getLogger(__name__)
35
36
37 class FWaaSL3PluginApi(api.FWaaSPluginApiMixin):
38 """Agent side of the FWaaS agent-to-plugin RPC API."""
39 def __init__(self, topic, host):
40 super().__init__(topic, host)
41
42 def get_firewall_groups_for_project(self, context, **kwargs):
43 """Fetches a project's firewall groups from the plugin."""
44 LOG.debug("Fetch firewall groups from plugin")
45 cctxt = self.client.prepare()
46 return cctxt.call(context, 'get_firewall_groups_for_project',
47 host=self.host)
48
49 def get_projects_with_firewall_groups(self, context, **kwargs):
50 """Fetches from the plugin all projects that have firewall groups
51 configured.
52 """
53 LOG.debug("Fetch from plugin projects that have firewall groups "
54 "configured")
55 cctxt = self.client.prepare()
56 return cctxt.call(context,
57 'get_projects_with_firewall_groups', host=self.host)
58
59 def firewall_group_deleted(self, context, fwg_id, **kwargs):
60 """Notifies the plugin that a firewall group has been deleted."""
61 LOG.debug("Notify plugin that firewall group has been deleted")
62 cctxt = self.client.prepare()
63 return cctxt.call(context, 'firewall_group_deleted', fwg_id=fwg_id,
64 host=self.host)
65
66 def set_firewall_group_status(self, context, fwg_id, status, **kwargs):
67 """Sets firewall group's status on the plugin."""
68 LOG.debug("Set firewall groups from plugin")
69 cctxt = self.client.prepare()
70 return cctxt.call(context, 'set_firewall_group_status',
71 fwg_id=fwg_id, status=status, host=self.host)
72
73
74 class FWaaSL3AgentExtension(l3_extension.L3AgentExtension):
75 """FWaaS agent extension."""
76
77 SUPPORTED_RESOURCE_TYPES = [f_resources.FIREWALL_GROUP,
78 f_resources.FIREWALL_POLICY,
79 f_resources.FIREWALL_RULE]
80
81 def initialize(self, connection, driver_type):
82 self._register_rpc_consumers(connection)
83
84 def consume_api(self, agent_api):
85 LOG.debug("FWaaS consume_api call occurred with %s", agent_api)
86 self.agent_api = agent_api
87
88 def _register_rpc_consumers(self, connection):
89 # TODO(njohnston): Add RPC consumer connection loading here.
90 pass
91
92 def start_rpc_listeners(self, host, conf):
93 self.endpoints = [self]
94
95 self.conn = n_rpc.Connection()
96 self.conn.create_consumer(
97 fwaas_constants.FW_AGENT, self.endpoints, fanout=False)
98 return self.conn.consume_in_threads()
99
100 def __init__(self, host, conf):
101 LOG.debug("Initializing firewall group agent")
102 self.agent_api = None
103 self.neutron_service_plugins = None
104 self.conf = conf
105 self.fwaas_enabled = cfg.CONF.fwaas.enabled
106
107 self.start_rpc_listeners(host, conf)
108 # None means l3-agent has no information on the server
109 # configuration due to the lack of RPC support.
110 if self.neutron_service_plugins is not None:
111 fwaas_plugin_configured = (fwaas_constants.FIREWALL
112 in self.neutron_service_plugins)
113 if fwaas_plugin_configured and not self.fwaas_enabled:
114 msg = ("FWaaS plugin is configured in the server side, but "
115 "FWaaS is disabled in L3-agent.")
116 LOG.error(msg)
117 raise SystemExit(1)
118 self.fwaas_enabled = self.fwaas_enabled and fwaas_plugin_configured
119
120 if self.fwaas_enabled:
121 # NOTE: Temp location for creating service and loading driver
122 self.fw_service = firewall_service.FirewallService()
123 self.fwaas_driver = self.fw_service.load_device_drivers()
124
125 self.services_sync_needed = False
126 self.fwplugin_rpc = FWaaSL3PluginApi(fwaas_constants.FIREWALL_PLUGIN,
127 host)
128 super().__init__()
129
130 @property
131 def _local_namespaces(self):
132 local_ns_list = ip_lib.list_network_namespaces()
133 return local_ns_list
134
135 def _has_port_insertion_fields(self, firewall_group):
136 """The presence of the 'add-port-ids' key in the firewall group dict
137 shows we are using the current version of the plugin. If this key
138 is absent, we are in an upgrade and message is from an older
139 version of the plugin.
140 """
141 return 'add-port-ids' in firewall_group
142
143 def _get_firewall_group_ports(self, context, firewall_group,
144 to_delete=False, require_new_plugin=False):
145 """Returns in-namespace ports, either from firewall group dict if ports
146 update or from project routers otherwise if only policies update.
147
148 NOTE: Vernacular move from "tenant" to "project" doesn't yet appear
149 as a key in router or firewall group objects.
150 """
151 fwg_port_ids = []
152 if self._has_port_insertion_fields(firewall_group):
153 if to_delete:
154 fwg_port_ids = firewall_group['del-port-ids']
155 else:
156 fwg_port_ids = firewall_group['add-port-ids']
157 if not require_new_plugin and not fwg_port_ids:
158 routers = self.agent_api.get_routers_in_project(
159 firewall_group['tenant_id'])
160 for router in routers:
161 if router.router['tenant_id'] == firewall_group['tenant_id']:
162 fwg_port_ids.extend([p['id'] for p in
163 router.internal_ports])
164
165 # Return in-namespace port objects.
166 return self._get_in_ns_ports(fwg_port_ids)
167
168 def _get_in_ns_ports(self, port_ids):
169 """Get ports in namespace by their IDs.
170
171 Returns port objects in the local namespace, along with their
172 router_info.
173
174 :param port_ids: IDs of router ports (set, list or tuple)
175 """
176 in_ns_ports = {} # This will be converted to a list later.
177 if port_ids and self.agent_api:
178 for port_id in port_ids:
179 # This fetched router_info is guaranteed to be in_namespace.
180 router_info = self.agent_api.get_router_hosting_port(port_id)
181 if router_info:
182 if router_info in in_ns_ports:
183 in_ns_ports[router_info].append(port_id)
184 else:
185 in_ns_ports[router_info] = [port_id]
186 return list(in_ns_ports.items())
187
188 def _invoke_driver_for_sync_from_plugin(self, ctx, ports, firewall_group):
189 """Call driver to sync firewall group.
190
191 Calls the FWaaS driver's delete_firewall_group method if firewall
192 group has status of PENDING_DELETE; calls driver's
193 update_firewall_group method for all other statuses. Both of these
194 methods are idempotent.
195
196 :param ctx: RPC context
197 :param ports: IDs of ports associated with a firewall group
198 (set, list or tuple)
199 :param firewall_group: Dictionary describing the firewall group object
200
201 """
202 port_list = self._get_in_ns_ports(ports)
203 if firewall_group['status'] == nl_constants.PENDING_DELETE:
204 try:
205 self.fwaas_driver.delete_firewall_group(
206 self.conf.agent_mode, port_list, firewall_group)
207 self.fwplugin_rpc.firewall_group_deleted(
208 ctx, firewall_group['id'])
209 except fw_ext.FirewallInternalDriverError:
210 msg = ("FWaaS driver error on %(status)s "
211 "for firewall group: %(fwg_id)s")
212 LOG.exception(msg, {'status': firewall_group['status'],
213 'fwg_id': firewall_group['id']})
214 self.fwplugin_rpc.set_firewall_group_status(
215 ctx, firewall_group['id'], nl_constants.ERROR)
216 else: # PENDING_UPDATE, PENDING_CREATE, ...
217
218 # Prepare firewall group status to return to plugin; may be
219 # overwritten if call to driver fails.
220 if firewall_group['admin_state_up']:
221 status = nl_constants.ACTIVE
222 else:
223 status = nl_constants.DOWN
224
225 # Call the driver.
226 try:
227 self.fwaas_driver.update_firewall_group(
228 self.conf.agent_mode, port_list, firewall_group)
229 except fw_ext.FirewallInternalDriverError:
230 msg = ("FWaaS driver error on %(status)s for firewall "
231 "group: %(fwg_id)s")
232 LOG.exception(msg, {'status': firewall_group['status'],
233 'fwg_id': firewall_group['id']})
234 status = nl_constants.ERROR
235 if firewall_group['status'] != status:
236 # Notify the plugin of firewall group's status.
237 self.fwplugin_rpc.set_firewall_group_status(
238 ctx, firewall_group['id'], status)
239
240 def _process_router_update(self, updated_router):
241 """If a new or existing router in the local namespace is updated,
242 queries the plugin to get the firewall groups for the project in
243 question and then sees if the router has any ports for any firewall
244 group that is configured for that project. If so, installs firewall
245 group rules on the requested ports on this router.
246 """
247 LOG.debug("Process router update, router_id: %s tenant: %s.",
248 updated_router['id'], updated_router['tenant_id'])
249 router_id = updated_router['id']
250 if not self.agent_api.is_router_in_namespace(router_id):
251 return
252
253 # Get the firewall groups for the new router's project.
254 # NOTE: Vernacular move from "tenant" to "project" doesn't yet appear
255 # as a key in router or firewall group objects.
256 ctx = context.Context('', updated_router['tenant_id'])
257 fwg_list = self.fwplugin_rpc.get_firewall_groups_for_project(ctx)
258
259 if nl_constants.INTERFACE_KEY not in updated_router:
260 return
261
262 # Apply a firewall group, as requested, to ports on the new router.
263 all_router_ports = {
264 p['id'] for p in updated_router[nl_constants.INTERFACE_KEY]
265 }
266 processed_ports = set()
267 for firewall_group in fwg_list:
268 if not self._has_port_insertion_fields(firewall_group):
269 continue
270
271 ports_to_process = (set(firewall_group['add-port-ids'] +
272 firewall_group['del-port-ids']) &
273 all_router_ports)
274 # ensure no port in router is associated with the firewall group
275 if not ports_to_process:
276 continue
277 # A port can have at most one firewall group.
278 port_ids_to_exclude = ports_to_process & processed_ports
279 if port_ids_to_exclude:
280 LOG.warning("Port(s) %s is associated with "
281 "more than one firewall group(s).",
282 port_ids_to_exclude)
283 ports_to_process -= port_ids_to_exclude
284 self._invoke_driver_for_sync_from_plugin(
285 ctx, ports_to_process, firewall_group)
286 processed_ports |= ports_to_process
287
288 def add_router(self, context, new_router):
289 """Handles agent restart and router add. Fetches firewall groups from
290 plugin and updates driver.
291 """
292 if not self.fwaas_enabled:
293 return
294
295 try:
296 self._process_router_update(new_router)
297 except Exception:
298 LOG.exception("FWaaS router add RPC info call failed for %s",
299 new_router['id'])
300 self.services_sync_needed = True
301
302 def update_router(self, context, updated_router):
303 """Handles agent restart and router update. Fetches firewall groups
304 from plugin and updates driver.
305 """
306 if not self.fwaas_enabled:
307 return
308
309 try:
310 self._process_router_update(updated_router)
311 except Exception:
312 # TODO(njohnston): This repr should be replaced.
313 LOG.exception(
314 "FWaaS router update RPC info call failed for %s",
315 repr(updated_router))
316 self.services_sync_needed = True
317
318 def delete_router(self, context, new_router):
319 """Handles router deletion. There is basically nothing to do for this
320 in the context of FWaaS with an IPTables driver; the namespace will
321 already have been deleted, taking the IPTables rules with it.
322 """
323 # TODO(njohnston): When another firewall driver is implemented, look at
324 # expanding this out so that the driver can handle deletion calls.
325 pass
326
327 def update_network(self, context, data):
328 pass
329
330 def process_services_sync(self, ctx):
331 """Syncs with plugin and applies the sync data.
332 """
333
334 if not self.services_sync_needed or not self.fwaas_enabled:
335 return
336
337 try:
338 # Fetch from the plugin the list of projects with firewall groups.
339 project_ids = \
340 self.fwplugin_rpc.get_projects_with_firewall_groups(ctx)
341 LOG.debug("Projects with firewall groups: %s",
342 ', '.join(project_ids))
343 for project_id in project_ids:
344 ctx = context.Context('', project_id)
345 fwg_list = \
346 self.fwplugin_rpc.get_firewall_groups_for_project(ctx)
347 for firewall_group in fwg_list:
348 if firewall_group['status'] == nl_constants.PENDING_DELETE:
349 self.delete_firewall_group(ctx, firewall_group,
350 self.host)
351 # No need to apply sync data for ACTIVE firewall group.
352 elif firewall_group['status'] != nl_constants.ACTIVE:
353 self.update_firewall_group(ctx, firewall_group,
354 self.host)
355 self.services_sync_needed = False
356 except Exception:
357 LOG.exception("Failed FWaaS process services sync.")
358 self.services_sync_needed = True
359
360 @log_helpers.log_method_call
361 def create_firewall_group(self, context, firewall_group, host):
362 """Handles RPC from plugin to create a firewall group.
363 """
364
365 # Get the in-namespace ports to which to add the firewall group.
366 ports_for_fwg = self._get_firewall_group_ports(context, firewall_group)
367 if not ports_for_fwg:
368 return
369
370 LOG.debug("Create firewall group %(fwg_id)s on ports: %(ports)s",
371 {'fwg_id': firewall_group['id'],
372 'ports': ', '.join([p for ri_ports in ports_for_fwg
373 for p in ri_ports[1]])})
374
375 # Set firewall group status; will be overwritten if call to driver
376 # fails.
377 if firewall_group['admin_state_up']:
378 status = nl_constants.ACTIVE
379 else:
380 status = nl_constants.DOWN
381
382 # Call the driver.
383 try:
384 self.fwaas_driver.create_firewall_group(self.conf.agent_mode,
385 ports_for_fwg,
386 firewall_group)
387 except fw_ext.FirewallInternalDriverError:
388 msg = ("FWaaS driver error in create_firewall_group "
389 "for firewall group: %(fwg_id)s")
390 LOG.exception(msg, {'fwg_id': firewall_group['id']})
391 status = nl_constants.ERROR
392
393 # Send firewall group's status to plugin.
394 try:
395 self.fwplugin_rpc.set_firewall_group_status(
396 context, firewall_group['id'], status)
397 except Exception:
398 msg = ("FWaaS RPC failure in create_firewall_group "
399 "for firewall group: %(fwg_id)s")
400 LOG.exception(msg, {'fwg_id': firewall_group['id']})
401 self.services_sync_needed = True
402
403 @log_helpers.log_method_call
404 def update_firewall_group(self, context, firewall_group, host):
405 """Handles RPC from plugin to update a firewall group.
406 """
407
408 # Initialize firewall group status.
409 status = ""
410
411 # Get the list of in-namespace ports from which to delete the firewall
412 # group.
413 del_fwg_ports = self._get_firewall_group_ports(
414 context, firewall_group, to_delete=True, require_new_plugin=True)
415 add_fwg_ports = self._get_firewall_group_ports(context, firewall_group)
416
417 port_ids = (firewall_group.get('del-port-ids') +
418 firewall_group.get('add-port-ids'))
419
420 if port_ids and not (del_fwg_ports or add_fwg_ports):
421 LOG.debug("All ports are not router port."
422 "No need to update firewall driver.")
423 return
424
425 # Remove firewall group from ports if requested.
426 if del_fwg_ports:
427 fw_ports = [p for ri_port in del_fwg_ports for p in ri_port[1]]
428 LOG.debug("Update (delete) firewall group %(fwg_id)s on ports: "
429 "%(ports)s",
430 {'fwg_id': firewall_group['id'],
431 'ports': ', '.join(fw_ports)})
432
433 # Set firewall group's status; will be overwritten if call to
434 # driver fails.
435
436 if firewall_group['admin_state_up']:
437 status = nl_constants.ACTIVE
438 if firewall_group['last-port']:
439 status = nl_constants.INACTIVE
440 else:
441 status = nl_constants.DOWN
442
443 # Call the driver.
444 try:
445 self.fwaas_driver.delete_firewall_group(self.conf.agent_mode,
446 del_fwg_ports,
447 firewall_group)
448 except fw_ext.FirewallInternalDriverError:
449 msg = ("FWaaS driver error in update_firewall_group "
450 "(add) for firewall group: %s")
451 LOG.exception(msg, firewall_group['id'])
452 status = nl_constants.ERROR
453
454 # Handle the add router and/or rule, policy, firewall group attribute
455 # updates.
456 if status not in (nl_constants.ERROR, nl_constants.INACTIVE):
457 if add_fwg_ports:
458 fw_ports = [p for ri_port in add_fwg_ports
459 for p in ri_port[1]]
460 LOG.debug("Update (create) firewall group %(fwg_id)s on "
461 "ports: %(ports)s",
462 {'fwg_id': firewall_group['id'],
463 'ports': ', '.join(fw_ports)})
464
465 # Set firewall group status, which will be overwritten if call
466 # to driver fails.
467 if firewall_group['admin_state_up']:
468 status = nl_constants.ACTIVE
469 else:
470 status = nl_constants.DOWN
471
472 # Call the driver.
473 try:
474 self.fwaas_driver.update_firewall_group(
475 self.conf.agent_mode, add_fwg_ports,
476 firewall_group)
477 except fw_ext.FirewallInternalDriverError:
478 msg = ("FWaaS driver error in update_firewall_group "
479 "for firewall group: %s")
480 LOG.exception(msg, firewall_group['id'])
481 status = nl_constants.ERROR
482 elif not status:
483 # if status not set by now, set it to INACTIVE
484 status = nl_constants.INACTIVE
485
486 # Return status to plugin.
487 try:
488 self.fwplugin_rpc.set_firewall_group_status(
489 context, firewall_group['id'], status)
490 except Exception:
491 LOG.exception("FWaaS RPC failure in update_firewall_group "
492 "for firewall group: %s", firewall_group['id'])
493 self.services_sync_needed = True
494
495 @log_helpers.log_method_call
496 def delete_firewall_group(self, context, firewall_group, host):
497 """Handles RPC from plugin to delete a firewall group.
498 """
499
500 ports_for_fwg = self._get_firewall_group_ports(context, firewall_group,
501 to_delete=True)
502
503 if not ports_for_fwg:
504 return
505
506 fw_ports = [p for ri_ports in ports_for_fwg for p in ri_ports[1]]
507 LOG.debug("Delete firewall group %(fwg_id)s on ports: %(ports)s",
508 {'fwg_id': firewall_group['id'],
509 'ports': ', '.join(fw_ports)})
510
511 # Set the firewall group's status to return to plugin; status may be
512 # overwritten if call to driver fails.
513 if firewall_group['admin_state_up']:
514 status = nl_constants.ACTIVE
515 else:
516 status = nl_constants.DOWN
517 try:
518 self.fwaas_driver.delete_firewall_group(self.conf.agent_mode,
519 ports_for_fwg,
520 firewall_group)
521 # Call the driver.
522 except fw_ext.FirewallInternalDriverError:
523 LOG.exception("FWaaS driver error in delete_firewall_group "
524 "for firewall group: %s", firewall_group['id'])
525 status = nl_constants.ERROR
526
527 # Notify plugin of deletion or return firewall group's status to
528 # plugin, as appropriate.
529 try:
530 if status in [nl_constants.ACTIVE, nl_constants.DOWN]:
531 self.fwplugin_rpc.firewall_group_deleted(
532 context, firewall_group['id'])
533 else:
534 self.fwplugin_rpc.set_firewall_group_status(
535 context, firewall_group['id'], status)
536 except Exception:
537 LOG.exception("FWaaS RPC failure in delete_firewall_group "
538 "for firewall group: %s", firewall_group['id'])
539 self.services_sync_needed = True
540
541 def ha_state_change(self, context, data):
542 pass
543
544
545 class L3WithFWaaS(FWaaSL3AgentExtension):
546
547 def __init__(self, conf=None):
548 if conf:
549 self.conf = conf
550 else:
551 self.conf = cfg.CONF
552 super().__init__(host=self.conf.host, conf=self.conf)