Debian Codegraph @

neutron_taas/db/taas_db.py

raw
1 # Copyright (C) 2018 AT&T
2 # Copyright (C) 2015 Ericsson AB
3 # Copyright (c) 2015 Gigamon
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
18 import sqlalchemy as sa
19 from sqlalchemy import orm
20 from sqlalchemy.orm import exc
21
22 from neutron.db.models import segment
23 from neutron_lib import constants
24 from neutron_lib.db import api as db_api
25 from neutron_lib.db import model_base
26 from neutron_lib.db import model_query
27 from neutron_lib.db import utils as db_utils
28 from neutron_lib.exceptions import taas as taas_exc
29 from neutron_lib.plugins import directory
30 from oslo_config import cfg
31 from oslo_log import log as logging
32 from oslo_utils import uuidutils
33
34 from neutron_taas.extensions import taas as taas_extension
35
36 LOG = logging.getLogger(__name__)
37
38
39 class TapService(model_base.BASEV2, model_base.HasId,
40 model_base.HasProjectNoIndex):
41
42 # Represents a V2 TapService Object
43 __tablename__ = 'tap_services'
44 name = sa.Column(sa.String(255), nullable=True)
45 description = sa.Column(sa.String(1024), nullable=True)
46 port_id = sa.Column(sa.String(36), nullable=False)
47 status = sa.Column(sa.String(16), nullable=False,
48 server_default=constants.ACTIVE)
49
50
51 class TapFlow(model_base.BASEV2, model_base.HasId,
52 model_base.HasProjectNoIndex):
53
54 # Represents a V2 TapFlow Object
55 __tablename__ = 'tap_flows'
56 name = sa.Column(sa.String(255), nullable=True)
57 description = sa.Column(sa.String(1024), nullable=True)
58 tap_service_id = sa.Column(sa.String(36),
59 sa.ForeignKey("tap_services.id",
60 ondelete="CASCADE"),
61 nullable=False)
62 source_port = sa.Column(sa.String(36), nullable=False)
63 direction = sa.Column(sa.Enum('IN', 'OUT', 'BOTH',
64 name='tapflows_direction'),
65 nullable=False)
66 status = sa.Column(sa.String(16), nullable=False,
67 server_default=constants.ACTIVE)
68 vlan_filter = sa.Column(sa.String(1024), nullable=True)
69
70
71 class TapIdAssociation(model_base.BASEV2):
72
73 # Internal mapping between a TAP Service and
74 # id to be used by the Agents
75 __tablename__ = 'tap_id_associations'
76 tap_service_id = sa.Column(sa.String(36),
77 sa.ForeignKey("tap_services.id",
78 ondelete='SET NULL'),
79 nullable=True)
80 taas_id = sa.Column(sa.Integer, primary_key=True, unique=True)
81 tap_service = orm.relationship(
82 TapService,
83 backref=orm.backref("tap_service_id",
84 lazy="joined"),
85 primaryjoin='TapService.id==TapIdAssociation.tap_service_id')
86
87
88 class Taas_db_Mixin(taas_extension.TaasPluginBase):
89
90 def _core_plugin(self):
91 return directory.get_plugin()
92
93 @db_api.retry_if_session_inactive()
94 @db_api.CONTEXT_READER
95 def _get_tap_service(self, context, id):
96 try:
97 return model_query.get_by_id(context, TapService, id)
98 except exc.NoResultFound:
99 raise taas_exc.TapServiceNotFound(tap_id=id)
100
101 @db_api.retry_if_session_inactive()
102 @db_api.CONTEXT_READER
103 def _get_tap_id_association(self, context, tap_service_id):
104 try:
105 query = model_query.query_with_hooks(context, TapIdAssociation)
106 return query.filter(TapIdAssociation.tap_service_id ==
107 tap_service_id).one()
108 except exc.NoResultFound:
109 raise taas_exc.TapServiceNotFound(tap_id=tap_service_id)
110
111 @db_api.CONTEXT_READER
112 def _get_tap_flow(self, context, id):
113 try:
114 return model_query.get_by_id(context, TapFlow, id)
115 except exc.NoResultFound:
116 raise taas_exc.TapFlowNotFound(flow_id=id)
117
118 def _make_tap_service_dict(self, tap_service, fields=None):
119 res = {'id': tap_service['id'],
120 'tenant_id': tap_service['tenant_id'],
121 'name': tap_service['name'],
122 'description': tap_service['description'],
123 'port_id': tap_service['port_id'],
124 'status': tap_service['status']}
125
126 return db_utils.resource_fields(res, fields)
127
128 def _make_tap_id_association_dict(self, tap_id_association):
129 res = {'tap_service_id': tap_id_association['tap_service_id'],
130 'taas_id': tap_id_association['taas_id']}
131
132 return res
133
134 def _make_tap_flow_dict(self, tap_flow, fields=None):
135 res = {'id': tap_flow['id'],
136 'tenant_id': tap_flow['tenant_id'],
137 'tap_service_id': tap_flow['tap_service_id'],
138 'name': tap_flow['name'],
139 'description': tap_flow['description'],
140 'source_port': tap_flow['source_port'],
141 'direction': tap_flow['direction'],
142 'status': tap_flow['status'],
143 'vlan_filter': tap_flow['vlan_filter']}
144
145 return db_utils.resource_fields(res, fields)
146
147 @db_api.retry_if_session_inactive()
148 @db_api.CONTEXT_READER
149 def get_port_network_data(self, context, port):
150 ns = context.session.query(
151 segment.NetworkSegment.network_id,
152 segment.NetworkSegment.physical_network,
153 segment.NetworkSegment.network_type
154 ).filter(
155 segment.NetworkSegment.network_id == port['network_id']
156 ).first()
157
158 if not ns:
159 LOG.debug("No Network Segment found for network_id %s",
160 port['network_id'])
161 return
162
163 ns_data = {
164 'physical_network': ns[1],
165 'network_type': ns[2]
166 }
167 return ns_data
168
169 @db_api.retry_if_session_inactive()
170 @db_api.CONTEXT_WRITER
171 def create_tap_service(self, context, tap_service):
172 LOG.debug("create_tap_service() called")
173 t_s = tap_service['tap_service']
174 tenant_id = t_s['tenant_id']
175 tap_service_db = TapService(
176 id=uuidutils.generate_uuid(),
177 tenant_id=tenant_id,
178 name=t_s['name'],
179 description=t_s['description'],
180 port_id=t_s['port_id'],
181 status=constants.DOWN,
182 )
183 context.session.add(tap_service_db)
184
185 return self._make_tap_service_dict(tap_service_db)
186
187 def _rebuild_taas_id_allocation_range(self, context):
188 query = context.session.query(
189 TapIdAssociation).all()
190
191 allocate_taas_id_list = [_q.taas_id for _q in query]
192 first_taas_id = cfg.CONF.taas.vlan_range_start
193 # Exclude range end
194 last_taas_id = cfg.CONF.taas.vlan_range_end
195 all_taas_id_set = set(range(first_taas_id, last_taas_id))
196 vaild_taas_id_set = all_taas_id_set - set(allocate_taas_id_list)
197
198 for _id in vaild_taas_id_set:
199 # new taas id
200 context.session.add(TapIdAssociation(
201 taas_id=_id))
202
203 def _allocate_taas_id_with_tap_service_id(self, context, tap_service_id):
204 query = context.session.query(TapIdAssociation).filter_by(
205 tap_service_id=None).first()
206 if not query:
207 self._rebuild_taas_id_allocation_range(context)
208 # try again
209 query = context.session.query(TapIdAssociation).filter_by(
210 tap_service_id=None).first()
211
212 if query:
213 query.update({"tap_service_id": tap_service_id})
214 return query
215 # not found
216 raise taas_exc.TapServiceLimitReached()
217
218 @db_api.retry_if_session_inactive()
219 @db_api.CONTEXT_WRITER
220 def create_tap_id_association(self, context, tap_service_id):
221 LOG.debug("create_tap_id_association() called")
222 # create the TapIdAssociation object
223 # allocate Taas id.
224 # if conflict happened, it will raise db.DBDuplicateEntry.
225 # this will be retry request again in neutron controller framework.
226 # so we just make sure TapIdAssociation field taas_id is unique
227 tap_id_association_db = self._allocate_taas_id_with_tap_service_id(
228 context, tap_service_id)
229
230 return self._make_tap_id_association_dict(tap_id_association_db)
231
232 @db_api.retry_if_session_inactive()
233 @db_api.CONTEXT_WRITER
234 def create_tap_flow(self, context, tap_flow):
235 LOG.debug("create_tap_flow() called")
236 t_f = tap_flow['tap_flow']
237 tenant_id = t_f['tenant_id']
238 # TODO(Vinay): Check for the tenant_id validation
239 # TODO(Vinay): Check for the source port validation
240 tap_flow_db = TapFlow(
241 id=uuidutils.generate_uuid(),
242 tenant_id=tenant_id,
243 name=t_f['name'],
244 description=t_f['description'],
245 tap_service_id=t_f['tap_service_id'],
246 source_port=t_f['source_port'],
247 direction=t_f['direction'],
248 status=constants.DOWN,
249 vlan_filter=t_f['vlan_filter'],
250 )
251 context.session.add(tap_flow_db)
252
253 return self._make_tap_flow_dict(tap_flow_db)
254
255 @db_api.retry_if_session_inactive()
256 @db_api.CONTEXT_WRITER
257 def delete_tap_service(self, context, id):
258 LOG.debug("delete_tap_service() called")
259
260 count = context.session.query(TapService).filter_by(id=id).delete()
261
262 if not count:
263 raise taas_exc.TapServiceNotFound(tap_id=id)
264
265 @db_api.CONTEXT_WRITER
266 def delete_tap_flow(self, context, id):
267 LOG.debug("delete_tap_flow() called")
268 count = context.session.query(TapFlow).filter_by(id=id).delete()
269
270 if not count:
271 raise taas_exc.TapFlowNotFound(flow_id=id)
272
273 def get_tap_service(self, context, id, fields=None):
274 LOG.debug("get_tap_service() called")
275
276 t_s = self._get_tap_service(context, id)
277 return self._make_tap_service_dict(t_s, fields)
278
279 def get_tap_id_association(self, context, tap_service_id):
280 LOG.debug("get_tap_id_association() called")
281
282 t_a = self._get_tap_id_association(context, tap_service_id)
283 return self._make_tap_id_association_dict(t_a)
284
285 @db_api.CONTEXT_READER
286 def get_tap_flow(self, context, id, fields=None):
287 LOG.debug("get_tap_flow() called")
288
289 t_f = self._get_tap_flow(context, id)
290 return self._make_tap_flow_dict(t_f, fields)
291
292 @db_api.retry_if_session_inactive()
293 @db_api.CONTEXT_READER
294 def get_tap_services(self, context, filters=None, fields=None,
295 sorts=None, limit=None, marker=None,
296 page_reverse=False):
297 LOG.debug("get_tap_services() called")
298 return model_query.get_collection(context, TapService,
299 self._make_tap_service_dict,
300 filters=filters, fields=fields)
301
302 @db_api.retry_if_session_inactive()
303 @db_api.CONTEXT_READER
304 def get_tap_flows(self, context, filters=None, fields=None,
305 sorts=None, limit=None, marker=None,
306 page_reverse=False):
307 LOG.debug("get_tap_flows() called")
308 return model_query.get_collection(context, TapFlow,
309 self._make_tap_flow_dict,
310 filters=filters, fields=fields)
311
312 @db_api.retry_if_session_inactive()
313 @db_api.CONTEXT_READER
314 def get_port_details(self, context, port_id):
315 port = self._core_plugin().get_port(context, port_id)
316
317 return port
318
319 @db_api.retry_if_session_inactive()
320 @db_api.CONTEXT_WRITER
321 def update_tap_service(self, context, id, tap_service):
322 LOG.debug("update_tap_service() called")
323 t_s = tap_service['tap_service']
324 tap_service_db = self._get_tap_service(context, id)
325 tap_service_db.update(t_s)
326 return self._make_tap_service_dict(tap_service_db)
327
328 @db_api.retry_if_session_inactive()
329 @db_api.CONTEXT_WRITER
330 def update_tap_flow(self, context, id, tap_flow):
331 LOG.debug("update_tap_flow() called")
332 t_f = tap_flow['tap_flow']
333 tap_flow_db = self._get_tap_flow(context, id)
334 tap_flow_db.update(t_f)
335 return self._make_tap_flow_dict(tap_flow_db)