Debian Codegraph @

neutron_vpnaas/db/vpn/vpn_ext_gw_db.py

raw
1 # (c) Copyright 2016 IBM Corporation, All Rights Reserved.
2 # (c) 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 from neutron.db.models import l3 as l3_models
18 from neutron.db import models_v2
19 from neutron_lib.callbacks import events
20 from neutron_lib.callbacks import registry
21 from neutron_lib.callbacks import resources
22 from neutron_lib import constants as lib_constants
23 from neutron_lib.db import api as db_api
24 from neutron_lib.db import model_base
25 from neutron_lib.db import model_query
26 from neutron_lib import exceptions as n_exc
27 from neutron_lib.plugins import constants as plugin_const
28 from neutron_lib.plugins import directory
29 from oslo_log import log as logging
30 from oslo_utils import uuidutils
31 import sqlalchemy as sa
32 from sqlalchemy import orm
33 from sqlalchemy.orm import exc
34
35 from neutron_vpnaas._i18n import _
36
37
38 LOG = logging.getLogger(__name__)
39
40
41 class RouterIsNotVPNExternal(n_exc.BadRequest):
42 message = _("Router %(router_id)s has no VPN external network gateway set")
43
44
45 class RouterHasVPNExternal(n_exc.BadRequest):
46 message = _(
47 "Router %(router_id)s already has VPN external network gateway")
48
49
50 class VPNNetworkInUse(n_exc.NetworkInUse):
51 message = _("Network %(network_id)s is used by VPN service")
52
53
54 class VPNExtGW(model_base.BASEV2, model_base.HasId, model_base.HasProject):
55 __tablename__ = 'vpn_ext_gws'
56 router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id'),
57 nullable=False, unique=True)
58 status = sa.Column(sa.String(16), nullable=False)
59 gw_port_id = sa.Column(
60 sa.String(36),
61 sa.ForeignKey('ports.id', ondelete='SET NULL'))
62 transit_port_id = sa.Column(
63 sa.String(36),
64 sa.ForeignKey('ports.id', ondelete='SET NULL'))
65 transit_network_id = sa.Column(
66 sa.String(36),
67 sa.ForeignKey('networks.id', ondelete='SET NULL'))
68 transit_subnet_id = sa.Column(
69 sa.String(36),
70 sa.ForeignKey('subnets.id', ondelete='SET NULL'))
71
72 gw_port = orm.relationship(models_v2.Port, lazy='joined',
73 foreign_keys=[gw_port_id])
74 transit_port = orm.relationship(models_v2.Port, lazy='joined',
75 foreign_keys=[transit_port_id])
76 transit_network = orm.relationship(models_v2.Network)
77 transit_subnet = orm.relationship(models_v2.Subnet)
78 router = orm.relationship(l3_models.Router)
79
80
81 @registry.has_registry_receivers
82 class VPNExtGWPlugin_db:
83 """DB class to support vpn external ports configuration."""
84
85 @property
86 def _core_plugin(self):
87 return directory.get_plugin()
88
89 @property
90 def _vpn_plugin(self):
91 return directory.get_plugin(plugin_const.VPN)
92
93 @staticmethod
94 @registry.receives(resources.PORT, [events.BEFORE_DELETE])
95 def _prevent_vpn_port_delete_callback(resource, event,
96 trigger, payload=None):
97 vpn_plugin = directory.get_plugin(plugin_const.VPN)
98 if vpn_plugin:
99 vpn_plugin.prevent_vpn_port_deletion(payload.context,
100 payload.resource_id)
101
102 @db_api.CONTEXT_READER
103 def _id_used(self, context, id_column, resource_id):
104 return context.session.query(VPNExtGW).filter(
105 sa.and_(
106 id_column == resource_id,
107 VPNExtGW.status != lib_constants.PENDING_DELETE
108 )
109 ).count() > 0
110
111 def prevent_vpn_port_deletion(self, context, port_id):
112 """Checks to make sure a port is allowed to be deleted.
113
114 Raises an exception if this is not the case. This should be called by
115 any plugin when the API requests the deletion of a port, since some
116 ports for L3 are not intended to be deleted directly via a DELETE
117 to /ports, but rather via other API calls that perform the proper
118 deletion checks.
119 """
120 try:
121 port = self._core_plugin.get_port(context, port_id)
122 except n_exc.PortNotFound:
123 # non-existent ports don't need to be protected from deletion
124 return
125
126 port_id_column = {
127 lib_constants.DEVICE_OWNER_VPN_ROUTER_GW: VPNExtGW.gw_port_id,
128 lib_constants.DEVICE_OWNER_VPN_TRANSIT_NETWORK:
129 VPNExtGW.transit_port_id,
130 }.get(port['device_owner'])
131
132 if not port_id_column:
133 # This is not a VPN port
134 return
135
136 if self._id_used(context, port_id_column, port_id):
137 reason = _('has device owner %s') % port['device_owner']
138 raise n_exc.ServicePortInUse(port_id=port['id'], reason=reason)
139
140 @staticmethod
141 @registry.receives(resources.SUBNET, [events.BEFORE_DELETE])
142 def _prevent_vpn_subnet_delete_callback(resource, event,
143 trigger, payload=None):
144 vpn_plugin = directory.get_plugin(plugin_const.VPN)
145 if vpn_plugin:
146 vpn_plugin.prevent_vpn_subnet_deletion(payload.context,
147 payload.resource_id)
148
149 def prevent_vpn_subnet_deletion(self, context, subnet_id):
150 if self._id_used(context, VPNExtGW.transit_subnet_id, subnet_id):
151 reason = _('Subnet is used by VPN service')
152 raise n_exc.SubnetInUse(subnet_id=subnet_id, reason=reason)
153
154 @staticmethod
155 @registry.receives(resources.NETWORK, [events.BEFORE_DELETE])
156 def _prevent_vpn_network_delete_callback(resource, event,
157 trigger, payload=None):
158 vpn_plugin = directory.get_plugin(plugin_const.VPN)
159 if vpn_plugin:
160 vpn_plugin.prevent_vpn_network_deletion(payload.context,
161 payload.resource_id)
162
163 def prevent_vpn_network_deletion(self, context, network_id):
164 if self._id_used(context, VPNExtGW.transit_network_id, network_id):
165 raise VPNNetworkInUse(network_id=network_id)
166
167 def _make_vpn_ext_gw_dict(self, gateway_db):
168 if not gateway_db:
169 return None
170 gateway = {
171 'id': gateway_db['id'],
172 'tenant_id': gateway_db['tenant_id'],
173 'router_id': gateway_db['router_id'],
174 'status': gateway_db['status'],
175 }
176 if gateway_db.gw_port:
177 gateway['network_id'] = gateway_db.gw_port['network_id']
178 gateway['external_fixed_ips'] = [
179 {'subnet_id': ip["subnet_id"], 'ip_address': ip["ip_address"]}
180 for ip in gateway_db.gw_port['fixed_ips']
181 ]
182 for key in ('gw_port_id', 'transit_port_id', 'transit_network_id',
183 'transit_subnet_id'):
184 value = gateway_db.get(key)
185 if value:
186 gateway[key] = value
187 return gateway
188
189 def _get_vpn_gw_by_router_id(self, context, router_id):
190 try:
191 gateway_db = context.session.query(VPNExtGW).filter(
192 VPNExtGW.router_id == router_id).one()
193 except exc.NoResultFound:
194 return None
195 return gateway_db
196
197 @db_api.CONTEXT_READER
198 def get_vpn_gw_by_router_id(self, context, router_id):
199 return self._get_vpn_gw_by_router_id(context, router_id)
200
201 @db_api.CONTEXT_READER
202 def get_vpn_gw_dict_by_router_id(self, context, router_id, refresh=False):
203 gateway_db = self._get_vpn_gw_by_router_id(context, router_id)
204 if gateway_db and refresh:
205 context.session.refresh(gateway_db)
206 return self._make_vpn_ext_gw_dict(gateway_db)
207
208 def create_gateway(self, context, gateway):
209 info = gateway['gateway']
210
211 with db_api.CONTEXT_WRITER.using(context):
212 gateway_db = VPNExtGW(
213 id=uuidutils.generate_uuid(),
214 tenant_id=info['tenant_id'],
215 router_id=info['router_id'],
216 status=lib_constants.PENDING_CREATE,
217 gw_port_id=info.get('gw_port_id'),
218 transit_port_id=info.get('transit_port_id'),
219 transit_network_id=info.get('transit_network_id'),
220 transit_subnet_id=info.get('transit_subnet_id'))
221 context.session.add(gateway_db)
222
223 return self._make_vpn_ext_gw_dict(gateway_db)
224
225 def update_gateway(self, context, gateway_id, gateway):
226 info = gateway['gateway']
227 with db_api.CONTEXT_WRITER.using(context):
228 gateway_db = model_query.get_by_id(context, VPNExtGW, gateway_id)
229 gateway_db.update(info)
230 return self._make_vpn_ext_gw_dict(gateway_db)
231
232 def delete_gateway(self, context, gateway_id):
233 with db_api.CONTEXT_WRITER.using(context):
234 query = context.session.query(VPNExtGW)
235 return query.filter(VPNExtGW.id == gateway_id).delete()