Debian Codegraph @

neutron_vpnaas/services/vpn/service_drivers/ovn_ipsec.py

raw
1 # Copyright 2016, Yi Jing Zhu, IBM.
2 # Copyright 2023, SysEleven GmbH
3 # All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
17 import netaddr
18
19 from neutron_lib.api.definitions import portbindings
20 from neutron_lib.callbacks import events
21 from neutron_lib.callbacks import registry
22 from neutron_lib.callbacks import resources
23 from neutron_lib import constants as lib_constants
24 from neutron_lib import context as nctx
25 from neutron_lib.db import api as db_api
26 from neutron_lib import exceptions as n_exc
27 from neutron_lib.plugins import constants as plugin_constants
28 from neutron_lib.plugins import directory
29 from neutron_lib.plugins import utils as p_utils
30 from neutron_lib import rpc as n_rpc
31
32 from oslo_config import cfg
33 from oslo_db import exception as o_exc
34 from oslo_log import log as logging
35
36 from neutron_vpnaas.db.vpn import vpn_agentschedulers_db as agent_db
37 from neutron_vpnaas.db.vpn.vpn_ext_gw_db import RouterIsNotVPNExternal
38 from neutron_vpnaas.db.vpn import vpn_models
39 from neutron_vpnaas.extensions import vpnaas
40 from neutron_vpnaas.services.vpn.common import topics
41 from neutron_vpnaas.services.vpn.service_drivers import base_ipsec
42
43
44 LOG = logging.getLogger(__name__)
45
46 IPSEC = 'ipsec'
47 BASE_IPSEC_VERSION = '1.0'
48
49 TRANSIT_NETWORK_PREFIX = 'vpn-transit-network-'
50 TRANSIT_SUBNET_PREFIX = 'vpn-transit-subnet-'
51 TRANSIT_PORT_PREFIX = 'vpn-ns-'
52 VPN_GW_PORT_PREFIX = 'vpn-gw-'
53 VPN_TRANSIT_LIP = '169.254.0.1'
54 VPN_TRANSIT_RIP = '169.254.0.2'
55 VPN_TRANSIT_CIDR = '169.254.0.0/28'
56 HIDDEN_PROJECT_ID = ''
57
58
59 class IPsecVpnOvnDriverCallBack(base_ipsec.IPsecVpnDriverCallBack):
60 def __init__(self, driver):
61 super().__init__(driver)
62 self.admin_ctx = nctx.get_admin_context()
63
64 @property
65 def core_plugin(self):
66 return self.driver.core_plugin
67
68 @property
69 def service_plugin(self):
70 return self.driver.service_plugin
71
72 def _get_vpn_gateway(self, context, router_id):
73 return self.service_plugin.get_vpn_gw_by_router_id(context, router_id)
74
75 def get_vpn_transit_network_details(self, context, router_id):
76 vpn_gw = self._get_vpn_gateway(context, router_id)
77 network_id = vpn_gw.gw_port['network_id']
78 external_network = self.core_plugin.get_network(context, network_id)
79
80 details = {
81 'gw_port': vpn_gw.gw_port,
82 'transit_port': vpn_gw.transit_port,
83 'transit_gateway_ip': VPN_TRANSIT_LIP,
84 'external_network': external_network,
85 }
86 return details
87
88 def get_subnet_info(self, context, subnet_id=None):
89 try:
90 return self.core_plugin.get_subnet(context, subnet_id)
91 except n_exc.SubnetNotFound:
92 return None
93
94 def _get_agent_hosting_vpn_services(self, context, host):
95 agent = self.service_plugin.get_vpn_agent_on_host(context, host)
96 if not agent:
97 return []
98
99 # We're here because a VPN agent asked for the VPN services it's
100 # hosting. This means, the agent is alive. This is a chance to
101 # schedule VPN services of routers that are still unscheduled.
102 if cfg.CONF.vpn_auto_schedule:
103 self.service_plugin.auto_schedule_routers(context, agent)
104
105 query = context.session.query(vpn_models.VPNService)
106 query = query.join(vpn_models.IPsecSiteConnection)
107 query = query.join(agent_db.RouterVPNAgentBinding,
108 agent_db.RouterVPNAgentBinding.router_id ==
109 vpn_models.VPNService.router_id)
110 query = query.filter(
111 agent_db.RouterVPNAgentBinding.vpn_agent_id == agent['id'])
112 return query
113
114
115 @registry.has_registry_receivers
116 class BaseOvnIPsecVPNDriver(base_ipsec.BaseIPsecVPNDriver):
117 def __init__(self, service_plugin):
118 self._l3_plugin = None
119 self._core_plugin = None
120 super().__init__(service_plugin)
121
122 @property
123 def l3_plugin(self):
124 if self._l3_plugin is None:
125 self._l3_plugin = directory.get_plugin(plugin_constants.L3)
126 return self._l3_plugin
127
128 @property
129 def core_plugin(self):
130 if self._core_plugin is None:
131 self._core_plugin = directory.get_plugin()
132 return self._core_plugin
133
134 @registry.receives(resources.ROUTER, [events.PRECOMMIT_UPDATE])
135 def _handle_router_precommit_update(self, resource, event, trigger,
136 payload):
137 """Check that a router update won't remove routes we need for VPN."""
138 LOG.debug("Router %s PRECOMMIT_UPDATE event: %s",
139 payload.resource_id, payload.request_body)
140 router_id = payload.resource_id
141 context = payload.context
142 router_data = payload.request_body
143 routes_removed = router_data.get('routes_removed')
144
145 if not routes_removed:
146 return
147
148 removed_cidrs = {r['destination'] for r in routes_removed}
149 vpn_cidrs = set(
150 self.service_plugin.get_peer_cidrs_for_router(context, router_id))
151 conflict_cidrs = removed_cidrs.intersection(vpn_cidrs)
152
153 if conflict_cidrs:
154 raise vpnaas.RouteInUseByVPN(
155 destinations=", ".join(conflict_cidrs))
156
157 def get_vpn_gw_port_name(self, router_id):
158 return VPN_GW_PORT_PREFIX + router_id
159
160 def get_vpn_namespace_port_name(self, router_id):
161 return TRANSIT_PORT_PREFIX + router_id
162
163 def get_transit_network_name(self, router_id):
164 return TRANSIT_NETWORK_PREFIX + router_id
165
166 def get_transit_subnet_name(self, router_id):
167 return TRANSIT_SUBNET_PREFIX + router_id
168
169 def make_transit_network(self, router_id, project_id, agent_host,
170 gateway_update):
171 context = nctx.get_admin_context()
172 network_data = {
173 'project_id': HIDDEN_PROJECT_ID,
174 'name': self.get_transit_network_name(router_id),
175 'admin_state_up': True,
176 'shared': False,
177 }
178 network = p_utils.create_network(self.core_plugin, context,
179 {'network': network_data})
180 gateway_update['transit_network_id'] = network['id']
181
182 # The subnet project_id must be of the user, otherwise updating the
183 # router by the user may fail (it needs access to all subnets)
184 subnet_data = {
185 'project_id': project_id,
186 'name': self.get_transit_subnet_name(router_id),
187 'gateway_ip': VPN_TRANSIT_LIP,
188 'cidr': VPN_TRANSIT_CIDR,
189 'network_id': network['id'],
190 'ip_version': 4,
191 'enable_dhcp': False,
192 }
193 subnet = p_utils.create_subnet(self.core_plugin, context,
194 {'subnet': subnet_data})
195 gateway_update['transit_subnet_id'] = subnet['id']
196
197 self.l3_plugin.add_router_interface(context, router_id,
198 {'subnet_id': subnet['id']})
199
200 fixed_ip = {'subnet_id': subnet['id'], 'ip_address': VPN_TRANSIT_RIP}
201 port_data = {
202 'project_id': HIDDEN_PROJECT_ID,
203 'network_id': network['id'],
204 'fixed_ips': [fixed_ip],
205 'device_id': subnet['id'],
206 'device_owner': lib_constants.DEVICE_OWNER_VPN_TRANSIT_NETWORK,
207 'admin_state_up': True,
208 portbindings.HOST_ID: agent_host,
209 'name': self.get_vpn_namespace_port_name(router_id)
210 }
211 port = p_utils.create_port(self.core_plugin, context,
212 {"port": port_data})
213 gateway_update['transit_port_id'] = port['id']
214
215 def _del_port(self, context, port_id):
216 try:
217 self.core_plugin.delete_port(context, port_id, l3_port_check=False)
218 except n_exc.PortNotFound:
219 pass
220
221 def _remove_router_interface(self, context, router_id, subnet_id):
222 try:
223 self.l3_plugin.remove_router_interface(
224 context, router_id, {'subnet_id': subnet_id})
225 except (n_exc.l3.RouterInterfaceNotFoundForSubnet,
226 n_exc.SubnetNotFound):
227 pass
228
229 def _del_subnet(self, context, subnet_id):
230 try:
231 self.core_plugin.delete_subnet(context, subnet_id)
232 except n_exc.SubnetNotFound:
233 pass
234
235 def _del_network(self, context, network_id):
236 try:
237 self.core_plugin.delete_network(context, network_id)
238 except n_exc.NetworkNotFound:
239 pass
240
241 def del_transit_network(self, gw):
242 context = nctx.get_admin_context()
243 router_id = gw['router_id']
244
245 port_id = gw.get('transit_port_id')
246 if port_id:
247 self._del_port(context, port_id)
248
249 subnet_id = gw.get('transit_subnet_id')
250 if subnet_id:
251 self._remove_router_interface(context, router_id, subnet_id)
252 self._del_subnet(context, subnet_id)
253
254 network_id = gw.get('transit_network_id')
255 if network_id:
256 self._del_network(context, network_id)
257
258 def make_gw_port(self, router_id, network_id, agent_host, gateway_update):
259 context = nctx.get_admin_context()
260 port_data = {'project_id': HIDDEN_PROJECT_ID,
261 'network_id': network_id,
262 'fixed_ips': lib_constants.ATTR_NOT_SPECIFIED,
263 'device_id': router_id,
264 'device_owner': lib_constants.DEVICE_OWNER_VPN_ROUTER_GW,
265 'admin_state_up': True,
266 portbindings.HOST_ID: agent_host,
267 'name': self.get_vpn_gw_port_name(router_id)}
268 gw_port = p_utils.create_port(self.core_plugin, context.elevated(),
269 {'port': port_data})
270
271 if not gw_port['fixed_ips']:
272 LOG.debug('No IPs available for external network %s', network_id)
273 gateway_update['gw_port_id'] = gw_port['id']
274
275 def del_gw_port(self, gateway):
276 context = nctx.get_admin_context()
277 port_id = gateway.get('gw_port_id')
278 if port_id:
279 self._del_port(context, port_id)
280
281 def _get_peer_cidrs(self, vpnservice):
282 cidrs = []
283 for ipsec_site_connection in vpnservice.ipsec_site_connections:
284 if ipsec_site_connection.peer_cidrs:
285 for peer_cidr in ipsec_site_connection.peer_cidrs:
286 cidrs.append(peer_cidr.cidr)
287 if ipsec_site_connection.peer_ep_group is not None:
288 for ep in ipsec_site_connection.peer_ep_group.endpoints:
289 cidrs.append(ep.endpoint)
290 return cidrs
291
292 def _routes_update(self, cidrs, nexthop):
293 routes = [{'destination': cidr, 'nexthop': nexthop}
294 for cidr in cidrs]
295 return {'router': {'routes': routes}}
296
297 def _update_static_routes(self, context, ipsec_site_connection):
298 vpnservice = self.service_plugin.get_vpnservice(
299 context, ipsec_site_connection['vpnservice_id'])
300 router_id = vpnservice['router_id']
301 gw = self.service_plugin.get_vpn_gw_by_router_id(context, router_id)
302
303 nexthop = gw.transit_port['fixed_ips'][0]['ip_address']
304
305 router = self.l3_plugin.get_router(context, router_id)
306 old_routes = router.get('routes', [])
307
308 old_cidrs = {r['destination'] for r in old_routes
309 if r['nexthop'] == nexthop}
310 new_cidrs = set(
311 self.service_plugin.get_peer_cidrs_for_router(context, router_id))
312
313 to_remove = old_cidrs - new_cidrs
314 if to_remove:
315 self.l3_plugin.remove_extraroutes(
316 context, router_id, self._routes_update(to_remove, nexthop))
317
318 to_add = new_cidrs - old_cidrs
319 if to_add:
320 self.l3_plugin.add_extraroutes(
321 context, router_id, self._routes_update(to_add, nexthop))
322
323 def _get_gateway_ips(self, router):
324 """Obtain the IPv4 and/or IPv6 GW IP for the router.
325
326 If there are multiples, (arbitrarily) use the first one.
327 """
328 gateway = self.service_plugin.get_vpn_gw_dict_by_router_id(
329 nctx.get_admin_context(),
330 router['id'])
331 if gateway is None or gateway['external_fixed_ips'] is None:
332 raise RouterIsNotVPNExternal(router_id=router['id'])
333
334 v4_ip = v6_ip = None
335 for fixed_ip in gateway['external_fixed_ips']:
336 addr = fixed_ip['ip_address']
337 vers = netaddr.IPAddress(addr).version
338 if vers == lib_constants.IP_VERSION_4:
339 if v4_ip is None:
340 v4_ip = addr
341 elif v6_ip is None:
342 v6_ip = addr
343 return v4_ip, v6_ip
344
345 def _update_gateway(self, context, gateway_id, **kwargs):
346 gateway = {'gateway': kwargs}
347 return self.service_plugin.update_gateway(context, gateway_id, gateway)
348
349 @db_api.retry_if_session_inactive()
350 def _ensure_gateway(self, context, vpnservice):
351 gw = self.service_plugin.get_vpn_gw_dict_by_router_id(
352 context, vpnservice['router_id'], refresh=True)
353 if not gw:
354 gateway = {'gateway': {
355 'router_id': vpnservice['router_id'],
356 'tenant_id': vpnservice['tenant_id'],
357 }}
358 # create_gateway may raise oslo_db.exception.DBDuplicateEntry
359 # if someone else created one in the meantime
360 return self.service_plugin.create_gateway(context, gateway)
361
362 if gw['status'] == lib_constants.ERROR:
363 raise vpnaas.VPNGatewayInError()
364
365 # Raise an exception if an existing gateway is in status
366 # PENDING_CREATE or PENDING_DELETE.
367 # One of the next retries should succeed.
368 if gw['status'] != lib_constants.ACTIVE:
369 raise o_exc.RetryRequest(vpnaas.VPNGatewayNotReady())
370 return gw
371
372 @db_api.CONTEXT_WRITER
373 def _setup(self, context, vpnservice_dict):
374 router_id = vpnservice_dict['router_id']
375 agent = self.service_plugin.schedule_router(context, router_id)
376 if not agent:
377 raise vpnaas.NoVPNAgentAvailable
378 agent_host = agent['host']
379
380 gateway = self._ensure_gateway(context, vpnservice_dict)
381
382 # If the gateway status is ACTIVE the ports have been created already
383 if gateway['status'] == lib_constants.ACTIVE:
384 return
385
386 vpnservice = self.service_plugin._get_vpnservice(context,
387 vpnservice_dict['id'])
388 network_id = vpnservice.router.gw_port.network_id
389 gateway_update = {} # keeps track of already-created IDs
390 try:
391 self.make_gw_port(router_id, network_id, agent_host,
392 gateway_update)
393 self.make_transit_network(router_id,
394 vpnservice_dict['tenant_id'],
395 agent_host,
396 gateway_update)
397 except Exception:
398 self._update_gateway(context, gateway['id'],
399 status=lib_constants.ERROR,
400 **gateway_update)
401 raise
402
403 self._update_gateway(context, gateway['id'],
404 status=lib_constants.ACTIVE,
405 **gateway_update)
406
407 def _cleanup(self, context, router_id):
408 gw = self.service_plugin.get_vpn_gw_dict_by_router_id(context,
409 router_id)
410 if not gw:
411 return
412 self._update_gateway(context, gw['id'],
413 status=lib_constants.PENDING_DELETE)
414 try:
415 self.del_gw_port(gw)
416 self.del_transit_network(gw)
417 self.service_plugin.delete_gateway(context, gw['id'])
418 except Exception:
419 LOG.exception("Cleanup of VPN gateway for router %s failed.",
420 router_id)
421 self._update_gateway(context, gw['id'],
422 status=lib_constants.ERROR)
423 raise
424
425 def create_vpnservice(self, context, vpnservice_dict):
426 try:
427 self._setup(context, vpnservice_dict)
428 except Exception:
429 LOG.exception("Setting up the VPN gateway for router %s failed.",
430 vpnservice_dict['router_id'])
431 self.service_plugin.set_vpnservice_status(
432 context, vpnservice_dict['id'], lib_constants.ERROR,
433 updated_pending_status=True)
434 raise
435 super().create_vpnservice(context, vpnservice_dict)
436
437 def delete_vpnservice(self, context, vpnservice):
438 router_id = vpnservice['router_id']
439 super().delete_vpnservice(context, vpnservice)
440 services = self.service_plugin.get_vpnservices(context)
441 router_ids = [s['router_id'] for s in services]
442 if router_id not in router_ids:
443 self._cleanup(context, router_id)
444
445 def create_ipsec_site_connection(self, context, ipsec_site_connection):
446 self._update_static_routes(context, ipsec_site_connection)
447 super().create_ipsec_site_connection(context, ipsec_site_connection)
448
449 def delete_ipsec_site_connection(self, context, ipsec_site_connection):
450 self._update_static_routes(context, ipsec_site_connection)
451 super().delete_ipsec_site_connection(context, ipsec_site_connection)
452
453 def update_ipsec_site_connection(
454 self, context, old_ipsec_site_connection, ipsec_site_connection):
455 self._update_static_routes(context, ipsec_site_connection)
456 super().update_ipsec_site_connection(
457 context, old_ipsec_site_connection, ipsec_site_connection)
458
459 def _update_port_binding(self, context, port_id, host):
460 port_data = {'binding:host_id': host}
461 self.core_plugin.update_port(context, port_id, {'port': port_data})
462
463 def update_port_bindings(self, context, router_id, host):
464 gw = self.service_plugin.get_vpn_gw_dict_by_router_id(context,
465 router_id)
466 if not gw:
467 return
468 port_id = gw.get('gw_port_id')
469 if port_id:
470 self._update_port_binding(context, port_id, host)
471 port_id = gw.get('transit_port_id')
472 if port_id:
473 self._update_port_binding(context, port_id, host)
474
475
476 class IPsecOvnVpnAgentApi(base_ipsec.IPsecVpnAgentApi):
477 def _agent_notification(self, context, method, router_id,
478 version=None, **kwargs):
479 """Notify update for the agent.
480
481 This method will find where is the router, and
482 dispatch notification for the agent.
483 """
484 admin_context = context if context.is_admin else context.elevated()
485 if not version:
486 version = self.target.version
487
488 vpn_agents = self.driver.service_plugin.get_vpn_agents_hosting_routers(
489 admin_context, [router_id], active=True)
490
491 for vpn_agent in vpn_agents:
492 LOG.debug('Notify agent at %(topic)s.%(host)s the message '
493 '%(method)s %(args)s',
494 {'topic': self.topic,
495 'host': vpn_agent['host'],
496 'method': method,
497 'args': kwargs})
498 cctxt = self.client.prepare(server=vpn_agent['host'],
499 version=version)
500 cctxt.cast(context, method, **kwargs)
501
502
503 class IPsecOvnVPNDriver(BaseOvnIPsecVPNDriver):
504 """VPN Service Driver class for IPsec."""
505
506 def create_rpc_conn(self):
507 self.agent_rpc = IPsecOvnVpnAgentApi(
508 topics.IPSEC_AGENT_TOPIC, BASE_IPSEC_VERSION, self)
509
510 def start_rpc_listeners(self):
511 self.endpoints = [IPsecVpnOvnDriverCallBack(self)]
512 self.conn = n_rpc.Connection()
513 self.conn.create_consumer(
514 topics.IPSEC_DRIVER_TOPIC, self.endpoints, fanout=False)
515 return self.conn.consume_in_threads()