Debian Codegraph @

neutron_fwaas/services/firewall/service_drivers/ovn/firewall_l3_driver.py

raw symbols SCIP
1 # Copyright 2022 EasyStack, Inc.
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.common.ovn import utils as ovn_utils
17 from neutron_lib import constants as const
18 from oslo_log import log as logging
19
20 from neutron_fwaas.services.firewall.service_drivers import driver_api
21 from neutron_fwaas.services.firewall.service_drivers.ovn import \
22 acl as ovn_acl
23 from neutron_fwaas.services.firewall.service_drivers.ovn import \
24 constants as ovn_const
25 from neutron_fwaas.services.firewall.service_drivers.ovn import \
26 exceptions as ovn_fw_exc
27
28 LOG = logging.getLogger(__name__)
29
30
31 class OVNFwaasDriver(driver_api.FirewallDriverDB):
32 """OVN l3 acl driver to implement
33
34 Depends on ml2/ovn, use ovn_client to put acl rules to the lsp which
35 is a peer of the lrp.
36 """
37
38 def __init__(self, service_plugin):
39 super().__init__(service_plugin)
40 self._mech = None
41
42 def is_supported_l2_port(self, port):
43 return False
44
45 def is_supported_l3_port(self, port):
46 return True
47
48 def start_rpc_listener(self):
49 return []
50
51 @property
52 def _nb_ovn(self):
53 return self._mech_driver.nb_ovn
54
55 @property
56 def _mech_driver(self):
57 if self._mech is None:
58 drivers = ('ovn', 'ovn-sync')
59 for driver in drivers:
60 try:
61 self._mech = \
62 self._core_plugin.mechanism_manager.mech_drivers[
63 driver].obj
64 break
65 except KeyError:
66 pass
67 else:
68 raise ovn_fw_exc.MechanismDriverNotFound(
69 mechanism_drivers=drivers)
70 return self._mech
71
72 def _init_firewall_group(self, txn, fwg_id):
73 """Add port_group for firewall_group
74
75 After create port_group for fwg, add default drop acls to it
76 """
77 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
78 ovn_acl.create_pg_for_fwg(self._nb_ovn, fwg_id)
79 ovn_acl.add_default_acls_for_pg(self._nb_ovn, txn, pg_name)
80 LOG.info("Successfully created port_group for firewall_group: %s",
81 fwg_id)
82
83 def _add_rules_for_firewall_group(self, context, txn, fwg_id,
84 rule_id=None):
85 """Add all rules belong to firewall_group
86 """
87 fwg_with_rules = \
88 self.firewall_db.make_firewall_group_dict_with_rules(
89 context, fwg_id)
90 egress_rule_list = fwg_with_rules['egress_rule_list']
91 ingress_rule_list = fwg_with_rules['ingress_rule_list']
92 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
93 rule_map = {const.INGRESS_DIRECTION: ingress_rule_list,
94 const.EGRESS_DIRECTION: egress_rule_list}
95 for dir, rule_list in rule_map.items():
96 position = 0
97 for rule in rule_list:
98 rule['position'] = position
99 position += 1
100 if not rule['enabled']:
101 continue
102 if rule_id:
103 # For specify rule id
104 if rule_id == rule['id']:
105 ovn_acl.process_rule_for_pg(self._nb_ovn, txn,
106 pg_name, rule, dir,
107 op=ovn_const.OP_ADD)
108 LOG.info("Successfully enable rule %(rule)s to "
109 "firewall_group %(fwg)s",
110 {"rule": rule_id,
111 "fwg": fwg_id})
112 break
113 else:
114 ovn_acl.process_rule_for_pg(self._nb_ovn, txn, pg_name,
115 rule, dir,
116 op=ovn_const.OP_ADD)
117 LOG.info("Successfully added rules for firewall_group %s",
118 fwg_id)
119
120 def _clear_rules_for_firewall_group(self, context, txn, fwg_id):
121 """Clear acls belong to firewall_group
122
123 Delete all rule acls but remain the default acls
124 """
125 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
126 default_acls = ovn_acl.get_default_acls_for_pg(self._nb_ovn, pg_name)
127 if len(default_acls) == ovn_const.DEFAULT_ACL_NUM:
128 txn.add(self._nb_ovn.db_set(
129 'Port_Group', pg_name,
130 ('acls', default_acls)))
131 else:
132 ovn_acl.add_default_acls_for_pg(self._nb_ovn, txn, pg_name)
133 LOG.info("Successfully clear rules for firewall_group %s",
134 fwg_id)
135
136 def _process_acls_by_policies_or_rule(self, context, policy_ids,
137 rule_info=None,
138 op=ovn_const.OP_ADD):
139 """Delete/Update/Add the acls by rule or policies
140 """
141 ing_fwg_list = []
142 eg_fwg_list = []
143 if not policy_ids:
144 return
145 for policy_id in policy_ids:
146 ing_fwg_ids, eg_fwg_ids = self.firewall_db.get_fwgs_with_policy(
147 context, policy_id)
148 ing_fwg_list += ing_fwg_ids
149 eg_fwg_list += eg_fwg_ids
150
151 if not rule_info and op == ovn_const.OP_ADD:
152 # Add acls
153 rule_info = {}
154 for fwg_id in list(set(ing_fwg_list + eg_fwg_list)):
155 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
156 with self._nb_ovn.transaction(check_error=True) as txn:
157 if self._nb_ovn.get_port_group(pg_name):
158 self._clear_rules_for_firewall_group(context, txn,
159 fwg_id)
160 else:
161 self._init_firewall_group(txn, fwg_id)
162 self._add_rules_for_firewall_group(context, txn, fwg_id)
163 elif rule_info and op == ovn_const.OP_ADD:
164 # Process the rule when enabled
165 for fwg_id in list(set(ing_fwg_list + eg_fwg_list)):
166 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
167 with self._nb_ovn.transaction(check_error=True) as txn:
168 if self._nb_ovn.get_port_group(pg_name):
169 self._add_rules_for_firewall_group(context, txn,
170 fwg_id,
171 rule_info['id'])
172 elif rule_info:
173 # Delete/Update acls
174 fwg_map = {const.INGRESS_DIRECTION: list(set(ing_fwg_list)),
175 const.EGRESS_DIRECTION: list(set(eg_fwg_list))}
176 for dir, fwg_list in fwg_map.items():
177 for fwg_id in fwg_list:
178 pg_name = ovn_utils.ovn_port_group_name(fwg_id)
179 with self._nb_ovn.transaction(check_error=True) as txn:
180 if not self._nb_ovn.get_port_group(pg_name):
181 LOG.warning("Cannot find Port_Group with name: %s",
182 pg_name)
183 continue
184 ovn_acl.process_rule_for_pg(self._nb_ovn, txn,
185 pg_name, rule_info,
186 dir, op=op)
187 LOG.info("Successfully %(op)s acls by rule %(rule)s "
188 "and policies %(p_ids)s",
189 {"op": op,
190 "rule": rule_info.get('id'),
191 "p_ids": policy_ids})
192
193 def create_firewall_group_precommit(self, context, firewall_group):
194 if not firewall_group['ports']:
195 LOG.info("No ports bound to firewall_group: %s, "
196 "set it to inactive", firewall_group['id'])
197 status = const.INACTIVE
198 else:
199 status = const.PENDING_CREATE
200 with self._nb_ovn.transaction(check_error=True) as txn:
201 self._init_firewall_group(txn, firewall_group['id'])
202 firewall_group['status'] = status
203
204 def create_firewall_group_postcommit(self, context, firewall_group):
205 pg_name = ovn_utils.ovn_port_group_name(firewall_group['id'])
206 try:
207 with self._nb_ovn.transaction(check_error=True) as txn:
208 if (firewall_group['ingress_firewall_policy_id'] or
209 firewall_group['egress_firewall_policy_id']):
210 # Add rule acls to port_group
211 self._add_rules_for_firewall_group(context, txn,
212 firewall_group['id'])
213
214 if firewall_group['ports']:
215 # Add ports to port_group
216 ovn_acl.update_ports_for_pg(self._nb_ovn,
217 txn, pg_name,
218 firewall_group['ports'])
219 firewall_group['status'] = const.ACTIVE
220 LOG.info("Successfully added ports for firewall_group %s",
221 firewall_group['id'])
222 except Exception:
223 with self._nb_ovn.transaction(check_error=True) as txn:
224 if self._nb_ovn.get_port_group(pg_name):
225 txn.add(self._nb_ovn.pg_del(name=pg_name, if_exists=True))
226 LOG.error("Failed to create_firewall_group_postcommit.")
227 raise
228 else:
229 self.firewall_db.update_firewall_group_status(
230 context, firewall_group['id'], firewall_group['status'])
231
232 def update_firewall_group_precommit(self, context, old_firewall_group,
233 new_firewall_group):
234 port_updated = (set(new_firewall_group['ports']) !=
235 set(old_firewall_group['ports']))
236 policies_updated = (
237 new_firewall_group['ingress_firewall_policy_id'] !=
238 old_firewall_group['ingress_firewall_policy_id'] or
239 new_firewall_group['egress_firewall_policy_id'] !=
240 old_firewall_group['egress_firewall_policy_id']
241 )
242 if port_updated or policies_updated:
243 new_firewall_group['status'] = const.PENDING_UPDATE
244
245 def update_firewall_group_postcommit(self, context, old_firewall_group,
246 new_firewall_group):
247 if new_firewall_group['status'] != const.PENDING_UPDATE:
248 return
249 old_ports = set(old_firewall_group['ports'])
250 new_ports = set(new_firewall_group['ports'])
251 old_ing_policy = old_firewall_group['ingress_firewall_policy_id']
252 new_ing_policy = new_firewall_group['ingress_firewall_policy_id']
253 old_eg_policy = old_firewall_group['egress_firewall_policy_id']
254 new_eg_policy = new_firewall_group['egress_firewall_policy_id']
255 pg_name = ovn_utils.ovn_port_group_name(new_firewall_group['id'])
256
257 # We except it would be active
258 # If no ports, set it to inactive
259 new_firewall_group['status'] = const.ACTIVE
260 if not new_ports:
261 LOG.info("No ports bound to firewall_group: %s, "
262 "set it to inactive", new_firewall_group['id'])
263 new_firewall_group['status'] = const.INACTIVE
264
265 # If port_group is not exist, recreate it,
266 # add acls and ports.
267 if not self._nb_ovn.get_port_group(pg_name):
268 with self._nb_ovn.transaction(check_error=True) as txn:
269 self._init_firewall_group(txn, new_firewall_group['id'])
270 if new_ports:
271 ovn_acl.update_ports_for_pg(self._nb_ovn, txn,
272 pg_name, new_ports)
273 if new_ing_policy or new_eg_policy:
274 self._add_rules_for_firewall_group(
275 context, txn, new_firewall_group['id'])
276 else:
277 with self._nb_ovn.transaction(check_error=True) as txn:
278 # Process changes of ports
279 if old_ports != new_ports:
280 ports_add = list(new_ports - old_ports)
281 ports_delete = list(old_ports - new_ports)
282 ovn_acl.update_ports_for_pg(self._nb_ovn, txn, pg_name,
283 ports_add, ports_delete)
284 # Process changes of policies
285 if (old_ing_policy != new_ing_policy or
286 old_eg_policy != new_eg_policy):
287 # Clear rules first
288 self._clear_rules_for_firewall_group(
289 context, txn, new_firewall_group['id'])
290 # Add rules if it has
291 if new_ing_policy or new_eg_policy:
292 self._add_rules_for_firewall_group(
293 context, txn, new_firewall_group['id'])
294
295 self.firewall_db.update_firewall_group_status(
296 context, new_firewall_group['id'],
297 new_firewall_group['status'])
298
299 def delete_firewall_group_precommit(self, context, firewall_group):
300 pg_name = ovn_utils.ovn_port_group_name(firewall_group['id'])
301 with self._nb_ovn.transaction(check_error=True) as txn:
302 if self._nb_ovn.get_port_group(pg_name):
303 txn.add(self._nb_ovn.pg_del(name=pg_name, if_exists=True))
304
305 def update_firewall_policy_postcommit(self, context, old_firewall_policy,
306 new_firewall_policy):
307 old_rules = old_firewall_policy['firewall_rules']
308 new_rules = new_firewall_policy['firewall_rules']
309 if old_rules == new_rules:
310 return
311 self._process_acls_by_policies_or_rule(context,
312 [new_firewall_policy['id']])
313
314 def update_firewall_rule_postcommit(self, context, old_firewall_rule,
315 new_firewall_rule):
316 NEED_UPDATE_FIELDS = ['enabled', 'protocol', 'ip_version',
317 'source_ip_address', 'destination_ip_address',
318 'source_port', 'destination_port', 'action']
319 need_update = False
320 for field in NEED_UPDATE_FIELDS:
321 if old_firewall_rule[field] != new_firewall_rule[field]:
322 need_update = True
323 if not need_update:
324 return
325 firewall_policy_ids = old_firewall_rule.get('firewall_policy_id')
326
327 # If rule is enabled, its acls should be inserted
328 # If rule is disabled, its acls should be removed
329 # If rule is always disabled, nothing to do
330 if not old_firewall_rule['enabled'] and new_firewall_rule['enabled']:
331 self._process_acls_by_policies_or_rule(context,
332 firewall_policy_ids,
333 new_firewall_rule)
334 return
335 elif old_firewall_rule['enabled'] and not new_firewall_rule['enabled']:
336 self._process_acls_by_policies_or_rule(context,
337 firewall_policy_ids,
338 old_firewall_rule,
339 ovn_const.OP_DEL)
340 return
341 elif not new_firewall_rule['enabled']:
342 return
343
344 # Process changes of rule
345 self._process_acls_by_policies_or_rule(
346 context, firewall_policy_ids, new_firewall_rule, ovn_const.OP_MOD)
347 LOG.info("Successfully updated acls for rule: %s",
348 new_firewall_rule['id'])
349
350 def insert_rule_postcommit(self, context, policy_id, rule_info):
351 # Add acls by policy_id
352 self._process_acls_by_policies_or_rule(context, [policy_id])
353
354 def remove_rule_postcommit(self, context, policy_id, rule_info):
355 rule_detail = self.firewall_db.get_firewall_rule(
356 context, rule_info['firewall_rule_id'])
357 self._process_acls_by_policies_or_rule(
358 context, [policy_id], rule_detail, ovn_const.OP_DEL)