Debian Codegraph @

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

raw symbols SCIP
1 # Copyright (c) 2013 OpenStack Foundation
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_lib.api.definitions import portbindings as pb_def
17 from neutron_lib import constants as nl_constants
18 from neutron_lib import context as neutron_context
19 from neutron_lib.db import api as db_api
20 from neutron_lib.exceptions import firewall_v2 as f_exc
21 from neutron_lib.plugins import constants as plugin_const
22 from neutron_lib.plugins import directory
23 from neutron_lib import rpc as n_rpc
24 from oslo_config import cfg
25 from oslo_log import helpers as log_helpers
26 from oslo_log import log as logging
27 import oslo_messaging
28
29 from neutron_fwaas.common import fwaas_constants as constants
30 from neutron_fwaas.services.firewall.service_drivers import driver_api
31 from neutron_fwaas.services.logapi.agents.drivers.iptables \
32 import driver as logging_driver
33
34
35 LOG = logging.getLogger(__name__)
36
37
38 class FirewallAgentCallbacks:
39 target = oslo_messaging.Target(version='1.0')
40
41 def __init__(self, firewall_db):
42 self.firewall_db = firewall_db
43
44 @log_helpers.log_method_call
45 @db_api.CONTEXT_WRITER
46 def set_firewall_group_status(self, context, fwg_id, status, **kwargs):
47 """Agent uses this to set a firewall_group's status."""
48 # Sanitize status first
49 if status in (nl_constants.ACTIVE, nl_constants.DOWN,
50 nl_constants.INACTIVE):
51 to_update = status
52 else:
53 to_update = nl_constants.ERROR
54 # ignore changing status if firewall_group expects to be deleted
55 # That case means that while some pending operation has been
56 # performed on the backend, neutron server received delete request
57 # and changed firewall status to PENDING_DELETE
58 updated = self.firewall_db.update_firewall_group_status(
59 context, fwg_id, to_update, not_in=(nl_constants.PENDING_DELETE,))
60 if updated:
61 LOG.debug("firewall %s status set: %s", fwg_id, to_update)
62 return updated and to_update != nl_constants.ERROR
63
64 @log_helpers.log_method_call
65 @db_api.CONTEXT_WRITER
66 def firewall_group_deleted(self, context, fwg_id, **kwargs):
67 """Agent uses this to indicate firewall is deleted."""
68 try:
69 fwg = self.firewall_db.get_firewall_group(context, fwg_id)
70 # allow to delete firewalls in ERROR state
71 if fwg['status'] in (nl_constants.PENDING_DELETE,
72 nl_constants.ERROR):
73 self.firewall_db.delete_firewall_group(context, fwg_id)
74 return True
75 LOG.warning('Firewall %(fwg)s unexpectedly deleted by agent, '
76 'status was %(status)s',
77 {'fwg': fwg_id, 'status': fwg['status']})
78 fwg['status'] = nl_constants.ERROR
79 self.firewall_db.update_firewall_group(context, fwg_id, fwg)
80 return False
81 except f_exc.FirewallGroupNotFound:
82 LOG.info('Firewall group %s already deleted', fwg_id)
83 return True
84
85 @log_helpers.log_method_call
86 @db_api.CONTEXT_WRITER
87 def get_firewall_groups_for_project(self, context, **kwargs):
88 """Gets all firewall_groups and rules on a project."""
89 fwg_list = []
90 for fwg in self.firewall_db.get_firewall_groups(context):
91 fwg_with_rules =\
92 self.firewall_db.make_firewall_group_dict_with_rules(
93 context, fwg['id'])
94 if fwg['status'] == nl_constants.PENDING_DELETE:
95 fwg_with_rules['add-port-ids'] = []
96 fwg_with_rules['del-port-ids'] = (
97 self.firewall_db.get_ports_in_firewall_group(
98 context, fwg['id']))
99 else:
100 fwg_with_rules['add-port-ids'] = (
101 self.firewall_db.get_ports_in_firewall_group(
102 context, fwg['id']))
103 fwg_with_rules['del-port-ids'] = []
104 fwg_list.append(fwg_with_rules)
105 return fwg_list
106
107 @log_helpers.log_method_call
108 @db_api.CONTEXT_WRITER
109 def get_projects_with_firewall_groups(self, context, **kwargs):
110 """Get all projects that have firewall_groups."""
111 ctx = neutron_context.get_admin_context()
112 fwg_list = self.firewall_db.get_firewall_groups(ctx)
113 fwg_project_list = list({fwg['tenant_id'] for fwg in fwg_list})
114 return fwg_project_list
115
116 @log_helpers.log_method_call
117 @db_api.CONTEXT_WRITER
118 def get_firewall_group_for_port(self, context, **kwargs):
119 """Get firewall_group is associated with a port."""
120 ctx = context.elevated()
121 # Only one Firewall Group can be associated to a port at a time
122 fwg_port_binding = self.firewall_db.get_firewall_groups(
123 ctx, filters={'ports': [kwargs.get('port_id')]})
124 if len(fwg_port_binding) != 1:
125 return
126 fwg = fwg_port_binding[0]
127
128 fwg['ingress_rule_list'] = []
129 for rule_id in self.firewall_db.get_firewall_policy(
130 context, fwg['ingress_firewall_policy_id'],
131 fields=['firewall_rules'])['firewall_rules']:
132 fwg['ingress_rule_list'].append(
133 self.firewall_db.get_firewall_rule(context, rule_id))
134 fwg['egress_rule_list'] = []
135 for rule_id in self.firewall_db.get_firewall_policy(
136 context, fwg['egress_firewall_policy_id'],
137 fields=['firewall_rules'])['firewall_rules']:
138 fwg['egress_rule_list'].append(
139 self.firewall_db.get_firewall_rule(context, rule_id))
140 return fwg
141
142
143 class FirewallAgentApi:
144 """Plugin side of plugin to agent RPC API"""
145
146 def __init__(self, topic, host):
147 self.host = host
148 target = oslo_messaging.Target(topic=topic, version='1.0')
149 self.client = n_rpc.get_client(target)
150
151 def create_firewall_group(self, context, firewall_group):
152 cctxt = self.client.prepare(fanout=True)
153 cctxt.cast(context, 'create_firewall_group',
154 firewall_group=firewall_group, host=self.host)
155
156 def update_firewall_group(self, context, firewall_group):
157 cctxt = self.client.prepare(fanout=True)
158 cctxt.cast(context, 'update_firewall_group',
159 firewall_group=firewall_group, host=self.host)
160
161 def delete_firewall_group(self, context, firewall_group):
162 cctxt = self.client.prepare(fanout=True)
163 cctxt.cast(context, 'delete_firewall_group',
164 firewall_group=firewall_group, host=self.host)
165
166
167 class FirewallAgentDriver(driver_api.FirewallDriverDB,
168 driver_api.FirewallDriverRPCMixin):
169 """Firewall driver to implement agent messages and callback methods
170
171 Implement RPC Firewall v2 API and callback methods for agents based on
172 Neutron DB model.
173 """
174
175 def __init__(self, service_plugin):
176 super().__init__(service_plugin)
177 self.agent_rpc = FirewallAgentApi(constants.FW_AGENT, cfg.CONF.host)
178
179 def register_logging_driver(self):
180 log_plugin = directory.get_plugin(plugin_const.LOG_API)
181 logging_driver.register()
182 # If log_plugin was loaded before firewall plugin
183 if log_plugin:
184 # Register logging driver with LoggingServiceDriverManager again
185 log_plugin.driver_manager.register_driver(logging_driver.DRIVER)
186
187 def is_supported_l2_port(self, port):
188 if port[pb_def.VIF_TYPE] == pb_def.VIF_TYPE_OVS:
189 if not port['port_security_enabled']:
190 return True
191
192 # TODO(annp): remove these lines after we fully support for hybrid
193 # port
194 if not port[pb_def.VIF_DETAILS][pb_def.OVS_HYBRID_PLUG]:
195 return True
196 LOG.warning("Doesn't support hybrid port at the moment")
197 else:
198 LOG.warning("Doesn't support vif type %s", port[pb_def.VIF_TYPE])
199 return False
200
201 def is_supported_l3_port(self, port):
202 return True
203
204 def start_rpc_listener(self):
205 self.endpoints = [FirewallAgentCallbacks(self.firewall_db)]
206 self.rpc_connection = n_rpc.Connection()
207 self.rpc_connection.create_consumer(constants.FIREWALL_PLUGIN,
208 self.endpoints, fanout=False)
209 return self.rpc_connection.consume_in_threads()
210
211 def _rpc_update_firewall_group(self, context, fwg_id):
212 fw_ports = self.firewall_db.get_ports_in_firewall_group(
213 context, fwg_id)
214 if not fw_ports:
215 return
216 status_update = {"status": nl_constants.PENDING_UPDATE}
217 self.update_firewall_group(context, fwg_id, status_update)
218 fwg_with_rules = self.firewall_db.make_firewall_group_dict_with_rules(
219 context, fwg_id)
220 # this is triggered on an update to fwg rule or policy, no
221 # change in associated ports.
222 fwg_with_rules['add-port-ids'] = fw_ports
223 fwg_with_rules['del-port-ids'] = []
224 fwg_with_rules['port_details'] = self._get_fwg_port_details(
225 context, fwg_with_rules['add-port-ids'])
226 self.agent_rpc.update_firewall_group(context, fwg_with_rules)
227
228 def _rpc_update_firewall_policy(self, context, firewall_policy_id):
229 firewall_policy = self.get_firewall_policy(context, firewall_policy_id)
230 if firewall_policy:
231 ing_fwg_ids, eg_fwg_ids = self.firewall_db.get_fwgs_with_policy(
232 context, firewall_policy_id)
233 for fwg_id in list(set(ing_fwg_ids + eg_fwg_ids)):
234 self._rpc_update_firewall_group(context, fwg_id)
235
236 def _get_fwg_port_details(self, context, fwg_ports):
237 """Returns a dictionary list of port details. """
238 port_details = {}
239 for port_id in fwg_ports:
240 port_db = self._core_plugin.get_port(context, port_id)
241 # Add more parameters below based on requirement.
242 device_owner = port_db['device_owner']
243 port_details[port_id] = {
244 'device_owner': device_owner,
245 'device': port_db['id'],
246 'network_id': port_db['network_id'],
247 'fixed_ips': port_db['fixed_ips'],
248 'allowed_address_pairs':
249 port_db.get('allowed_address_pairs', []),
250 'port_security_enabled':
251 port_db.get('port_security_enabled', True),
252 'id': port_db['id'],
253 'status': port_db['status'],
254 }
255 if device_owner.startswith(
256 nl_constants.DEVICE_OWNER_COMPUTE_PREFIX):
257 port_details[port_id].update(
258 {'host': port_db[pb_def.HOST_ID]})
259 return port_details
260
261 def create_firewall_group_precommit(self, context, firewall_group):
262 ports = firewall_group['ports']
263
264 if (not ports or (not firewall_group['ingress_firewall_policy_id'] and
265 not firewall_group['egress_firewall_policy_id'])):
266 # no messaging to agent needed and fw needs to go to INACTIVE state
267 # as no associated ports and/or no policy configured.
268 status = nl_constants.INACTIVE
269 else:
270 status = (nl_constants.CREATED if cfg.CONF.router_distributed
271 else nl_constants.PENDING_CREATE)
272 firewall_group['status'] = status
273
274 def create_firewall_group_postcommit(self, context, firewall_group):
275 if firewall_group['status'] != nl_constants.INACTIVE:
276 fwg_with_rules =\
277 self.firewall_db.make_firewall_group_dict_with_rules(
278 context, firewall_group['id'])
279 fwg_with_rules['add-port-ids'] = firewall_group['ports']
280 fwg_with_rules['del-ports-id'] = []
281 fwg_with_rules['port_details'] = self._get_fwg_port_details(
282 context, firewall_group['ports'])
283 self.agent_rpc.create_firewall_group(context, fwg_with_rules)
284
285 def _need_pending_update(self, old_firewall_group, new_firewall_group):
286 port_updated = (set(new_firewall_group['ports']) !=
287 set(old_firewall_group['ports']))
288 policies_updated = (
289 new_firewall_group['ingress_firewall_policy_id'] !=
290 old_firewall_group['ingress_firewall_policy_id'] or
291 new_firewall_group['egress_firewall_policy_id'] !=
292 old_firewall_group['egress_firewall_policy_id']
293 )
294 if (port_updated and
295 (new_firewall_group['ingress_firewall_policy_id'] or
296 new_firewall_group['egress_firewall_policy_id'])):
297 return True
298 if policies_updated and new_firewall_group['ports']:
299 return True
300 return False
301
302 def update_firewall_group_precommit(self, context, old_firewall_group,
303 new_firewall_group):
304 if self._need_pending_update(old_firewall_group, new_firewall_group):
305 new_firewall_group['status'] = nl_constants.PENDING_UPDATE
306
307 def update_firewall_group_postcommit(self, context, old_firewall_group,
308 new_firewall_group):
309 if not self._need_pending_update(old_firewall_group,
310 new_firewall_group):
311 return
312
313 fwg_with_rules = self.firewall_db.make_firewall_group_dict_with_rules(
314 context, new_firewall_group['id'])
315
316 # determine ports to add fw to and del from
317 fwg_with_rules['add-port-ids'] = list(
318 set(new_firewall_group['ports']) - set(old_firewall_group['ports'])
319 )
320 fwg_with_rules['del-port-ids'] = list(
321 set(old_firewall_group['ports']) - set(new_firewall_group['ports'])
322 )
323
324 # last-port drives agent to ack with status to set state to INACTIVE
325 # Set last-port to True if there are no ports in the new group and
326 # the old group had the same number of ports that need to be deleted.
327 fwg_with_rules['last-port'] = (len(old_firewall_group['ports']) == len(
328 fwg_with_rules['del-port-ids']) and
329 not new_firewall_group['ports'])
330
331 LOG.debug("update_firewall_group %s: Add Ports: %s, Del Ports: %s",
332 new_firewall_group['id'],
333 fwg_with_rules['add-port-ids'],
334 fwg_with_rules['del-port-ids'])
335
336 fwg_with_rules['port_details'] = self._get_fwg_port_details(
337 context, fwg_with_rules['del-port-ids'])
338 fwg_with_rules['port_details'].update(self._get_fwg_port_details(
339 context, fwg_with_rules['add-port-ids']))
340
341 if (new_firewall_group['name'] == constants.DEFAULT_FWG and
342 len(fwg_with_rules['add-port-ids']) == 1 and
343 not fwg_with_rules['del-port-ids']):
344 port_id = fwg_with_rules['add-port-ids'][0]
345 if (fwg_with_rules['port_details'][port_id].get('status') !=
346 nl_constants.ACTIVE):
347 # If port not yet active, just associate to default firewall
348 # group. When agent will set it to UP, it'll found FG
349 # association and enforce default policies
350 return
351 # Warn agents Firewall Group port list updated
352 self.agent_rpc.update_firewall_group(context, fwg_with_rules)
353
354 def update_firewall_policy_postcommit(self, context, old_firewall_policy,
355 new_firewall_group):
356 self._rpc_update_firewall_policy(context, new_firewall_group['id'])
357
358 def update_firewall_rule_postcommit(self, context, old_firewall_rule,
359 new_firewall_rule):
360 firewall_policy_ids = self.firewall_db.get_policies_with_rule(
361 context, new_firewall_rule['id'])
362 for firewall_policy_id in firewall_policy_ids:
363 self._rpc_update_firewall_policy(context, firewall_policy_id)
364
365 def insert_rule_postcommit(self, context, policy_id, rule_info):
366 self._rpc_update_firewall_policy(context, policy_id)
367
368 def remove_rule_postcommit(self, context, policy_id, rule_info):
369 self._rpc_update_firewall_policy(context, policy_id)