Debian Codegraph @

neutron_lib/db/model_query.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13
14 """
15 NOTE: This module is a temporary shim until networking projects move to
16 versioned objects at which point this module shouldn't be needed.
17 """
18 from oslo_db.sqlalchemy import utils as sa_utils
19 from sqlalchemy.orm import lazyload
20 from sqlalchemy import sql, or_, and_
21
22 from neutron_lib._i18n import _
23 from neutron_lib.api import attributes
24 from neutron_lib import constants
25 from neutron_lib.db import utils as db_utils
26 from neutron_lib import exceptions as n_exc
27 from neutron_lib.objects import utils as obj_utils
28 from neutron_lib.utils import helpers
29
30
31 # Classes implementing extensions will register hooks into this dictionary
32 # for "augmenting" the "core way" of building a query for retrieving objects
33 # from a model class. Hooks are registered by invoking register_hook().
34 _model_query_hooks = {
35 # model1 : {
36 # hook1: {
37 # 'query': query_hook,
38 # 'filter': filter_hook,
39 # 'result_filters': result_filters
40 # 'rbac_actions': rbac_actions
41 # },
42 # hook2: {
43 # 'query': query_hook,
44 # 'filter': filter_hook,
45 # 'result_filters': result_filters
46 # 'rbac_actions': rbac_actions
47 # },
48 # ...
49 # },
50 # model2 : {
51 # hook1: {
52 # 'query': query_hook,
53 # 'filter': filter_hook,
54 # 'result_filters': result_filters
55 # 'rbac_actions': rbac_actions
56 # },
57 # hook2: {
58 # 'query': query_hook,
59 # 'filter': filter_hook,
60 # 'result_filters': result_filters
61 # 'rbac_actions': rbac_actions
62 # },
63 # ...
64 # },
65 # ...
66 }
67
68
69 def register_hook(model, name, query_hook, filter_hook,
70 result_filters=None, rbac_actions=None):
71 """Register a hook to be invoked when a query is executed.
72
73 Adds the hook components to the _model_query_hooks dict. Models are the
74 keys of this dict, whereas the value is another dict mapping hook names
75 to callables performing the hook or in the case of ``rbac_actions``, a set
76 of RBAC actions to filter the model.
77
78 :param model: The DB Model that the hook applies to.
79 :param name: A name for the hook.
80 :param query_hook: The method to be called to augment the query.
81 :param filter_hook: A method to be called to augment the query filter.
82 :param result_filters: A Method to be called to filter the query result.
83 :param rbac_actions: An iterable of RBAC actions or a single one (string).
84 :returns: None.
85 """
86 if callable(query_hook):
87 query_hook = helpers.make_weak_ref(query_hook)
88 if callable(filter_hook):
89 filter_hook = helpers.make_weak_ref(filter_hook)
90 if callable(result_filters):
91 result_filters = helpers.make_weak_ref(result_filters)
92 if rbac_actions is not None:
93 if isinstance(rbac_actions, set | list | tuple):
94 rbac_actions = set(rbac_actions)
95 else:
96 rbac_actions = {rbac_actions}
97 _model_query_hooks.setdefault(model, {})[name] = {
98 'query': query_hook,
99 'filter': filter_hook,
100 'result_filters': result_filters,
101 'rbac_actions': rbac_actions,
102 }
103
104
105 def get_hooks(model):
106 """Retrieve the model query hooks for a model.
107
108 :param model: The DB Model to look up for query hooks.
109 :returns: list of hooks
110 """
111 return _model_query_hooks.get(model, {}).values()
112
113
114 def get_rbac_actions(model):
115 """Retrieve and combine all RBAC actions requested in a model
116
117 :param model: The DB Model to look up for query hooks.
118 :returns: A set of RBAC actions defined in the model or the default RBAC
119 actions ('access_as_shared', 'access_as_readonly')
120 """
121 rbac_actions = None
122 for hook in get_hooks(model):
123 hook_rbac_actions = hook.get('rbac_actions')
124 if hook_rbac_actions is not None:
125 if rbac_actions is None:
126 rbac_actions = set()
127 rbac_actions.update(hook_rbac_actions)
128 return (
129 rbac_actions if rbac_actions is not None else
130 {constants.ACCESS_SHARED}
131 )
132
133
134 def query_with_hooks(context, model, field=None, lazy_fields=None):
135 """Query with hooks using the said context and model.
136
137 :param context: The context to use for the DB session.
138 :param model: The model to query.
139 :param field: The column.
140 :param lazy_fields: list of fields for lazy loading
141 :returns: The query with hooks applied to it.
142 """
143 group_by = None
144 if field:
145 if hasattr(model, field):
146 field = getattr(model, field)
147 else:
148 msg = _("'%s' is not supported as field") % field
149 raise n_exc.InvalidInput(error_message=msg)
150 query = context.session.query(field)
151 else:
152 query = context.session.query(model)
153 # define basic filter condition for model query
154 query_filter = None
155 if db_utils.model_query_scope_is_project(context, model):
156 if hasattr(model, 'rbac_entries'):
157 query = query.outerjoin(model.rbac_entries)
158 rbac_model = model.rbac_entries.property.mapper.class_
159 query_filter = (
160 (model.tenant_id == context.project_id) |
161 (rbac_model.action.in_(get_rbac_actions(model)) &
162 ((rbac_model.target_project == context.project_id) |
163 (rbac_model.target_project == '*'))))
164 # This "group_by" clause will limit the number of registers
165 # returned by the query, avoiding the problem of the low SQL
166 # query cardinality when the RBAC registers are in the requested
167 # project ID.
168 group_by = model.id
169 elif hasattr(model, 'shared'):
170 query_filter = ((model.tenant_id == context.project_id) |
171 (model.shared == sql.true()))
172 else:
173 query_filter = (model.tenant_id == context.project_id)
174 # Execute query hooks registered from mixins and plugins
175 for hook in get_hooks(model):
176 query_hook = helpers.resolve_ref(hook.get('query'))
177 if query_hook:
178 query = query_hook(context, model, query)
179
180 filter_hook = helpers.resolve_ref(hook.get('filter'))
181 if filter_hook:
182 query_filter = filter_hook(context, model, query_filter)
183
184 # NOTE(salvatore-orlando): 'if query_filter' will try to evaluate the
185 # condition, raising an exception
186 if query_filter is not None:
187 query = query.filter(query_filter)
188
189 if group_by:
190 query = query.group_by(group_by)
191
192 if lazy_fields:
193 for lfield in lazy_fields:
194 query = query.options(lazyload(lfield))
195 return query
196
197
198 def get_by_id(context, model, object_id, lazy_fields=None):
199 """Query the said model with the given context for a specific object.
200
201 :param context: The context to use in the query.
202 :param model: The model to query.
203 :param object_id: The ID of the object to query for.
204 :param lazy_fields: list of fields for lazy loading
205 :returns: The object with the give object_id for the said model.
206 """
207 query = query_with_hooks(context=context, model=model,
208 lazy_fields=lazy_fields)
209 return query.filter(model.id == object_id).one()
210
211
212 def apply_filters(query, model, filters, context=None):
213 """Apply filters to a query.
214
215 :param query: The query to apply filters to.
216 :param model: The model for the query.
217 :param filters: The filters to apply.
218 :param context: The context to use for the DB session.
219 :returns: The query with filters applied to it.
220 """
221 if filters:
222 for key, value in filters.items():
223 column = getattr(model, key, None)
224 # NOTE(kevinbenton): if column is a hybrid property that
225 # references another expression, attempting to convert to
226 # a boolean will fail so we must compare to None.
227 # See "An Important Expression Language Gotcha" in:
228 # docs.sqlalchemy.org/en/rel_0_9/changelog/migration_06.html
229 if column is not None:
230 if not value:
231 query = query.filter(sql.false())
232 return query
233 if not hasattr(column, 'in_'):
234 # NOTE(ralonsoh): since SQLAlchemy==1.3.0, a column is an
235 # AssociationProxyInstance and inherits in_() method from
236 # ColumnOperators.
237 # association proxies don't support in_ so we have to
238 # do multiple equals matches
239 query = query.filter(
240 or_(*[column == v for v in value]))
241 elif isinstance(value, obj_utils.FilterObj):
242 query = query.filter(value.filter(column))
243 elif None in value:
244 # in_() operator does not support NULL element so we have
245 # to do multiple equals matches
246 query = query.filter(
247 or_(*[column == v for v in value]))
248 else:
249 # NOTE(frickler): in_() isn't implemented for relations
250 # yet, let this pass so it can be handled by the
251 # result_filter hook
252 try:
253 query = query.filter(column.in_(value))
254 except NotImplementedError:
255 pass
256 elif key == 'shared' and hasattr(model, 'rbac_entries'):
257 # translate a filter on shared into a query against the
258 # object's rbac entries
259 rbac = model.rbac_entries.property.mapper.class_
260 matches = [rbac.target_project == '*']
261 if context:
262 matches.append(rbac.target_project == context.project_id)
263 # any 'access_as_shared' records that match the
264 # wildcard or requesting tenant
265 is_shared = and_(rbac.action == constants.ACCESS_SHARED,
266 or_(*matches))
267 if not value[0]:
268 # NOTE(kevinbenton): we need to find objects that don't
269 # have an entry that matches the criteria above so
270 # we use a subquery to exclude them.
271 # We can't just filter the inverse of the query above
272 # because that will still give us a network shared to
273 # our tenant (or wildcard) if it's shared to another
274 # tenant.
275 # This is the column joining the table to rbac via
276 # the object_id. We can't just use model.id because
277 # subnets join on network.id so we have to inspect the
278 # relationship.
279 join_cols = model.rbac_entries.property.local_columns
280 oid_col = list(join_cols)[0]
281 is_shared = ~oid_col.in_(
282 query.session.query(rbac.object_id).filter(is_shared)
283 )
284 elif (not context or
285 not db_utils.model_query_scope_is_project(
286 context, model)):
287 # we only want to join if we aren't using the subquery
288 # and if we aren't already joined because this is a
289 # scoped query
290 query = query.outerjoin(model.rbac_entries)
291 query = query.filter(is_shared)
292 for hook in get_hooks(model):
293 result_filter = helpers.resolve_ref(
294 hook.get('result_filters', None))
295 if result_filter:
296 query = result_filter(query, filters)
297 return query
298
299
300 def get_collection_query(context, model, filters=None, sorts=None, limit=None,
301 marker_obj=None, page_reverse=False, field=None,
302 lazy_fields=None):
303 """Get a collection query.
304
305 :param context: The context to use for the DB session.
306 :param model: The model to use.
307 :param filters: The filters to apply in the query.
308 :param sorts: The sort keys to use.
309 :param limit: The limit associated with the query.
310 :param marker_obj: The marker object if applicable.
311 :param page_reverse: If reverse paging should be used.
312 :param field: Column, in string format, from the "model"; the query will
313 return only this parameter instead of the full model columns.
314 :param lazy_fields: list of fields for lazy loading
315 :returns: A paginated query for the said model.
316 """
317 collection = query_with_hooks(context, model, field=field,
318 lazy_fields=lazy_fields)
319 collection = apply_filters(collection, model, filters, context)
320 if sorts:
321 sort_keys = db_utils.get_and_validate_sort_keys(sorts, model)
322 sort_dirs = db_utils.get_sort_dirs(sorts, page_reverse)
323 # we always want deterministic results for sorted queries
324 # so add unique keys to limit queries when present.
325 # (http://docs.sqlalchemy.org/en/latest/orm/
326 # loading_relationships.html#subqueryload-ordering)
327 # (http://docs.sqlalchemy.org/en/latest/faq/
328 # ormconfiguration.html#faq-subqueryload-limit-sort)
329 for k in _unique_keys(model):
330 if k not in sort_keys:
331 sort_keys.append(k)
332 sort_dirs.append('asc')
333 collection = sa_utils.paginate_query(collection, model, limit,
334 marker=marker_obj,
335 sort_keys=sort_keys,
336 sort_dirs=sort_dirs)
337 return collection
338
339
340 def _unique_keys(model):
341 # just grab first set of unique keys and use them.
342 # if model has no unqiue sets, 'paginate_query' will
343 # warn if sorting is unstable
344 uk_sets = sa_utils.get_unique_keys(model)
345 return uk_sets[0] if uk_sets else []
346
347
348 def get_collection(context, model, dict_func,
349 filters=None, fields=None,
350 sorts=None, limit=None, marker_obj=None,
351 page_reverse=False, lazy_fields=None):
352 """Get a collection for a said model.
353
354 :param context: The context to use for the DB session.
355 :param model: The model for the collection.
356 :param dict_func: The function used to build the collection dict.
357 :param filters: The filters to apply.
358 :param fields: The fields to collect.
359 :param sorts: The sort keys to use.
360 :param limit: The limit for the query if applicable.
361 :param marker_obj: The marker object if applicable.
362 :param page_reverse: If reverse paging should be used.
363 :param lazy_fields: list of fields for lazy loading
364 :returns: A list of dicts where each dict is an object in the collection.
365 """
366 query = get_collection_query(context, model,
367 filters=filters, sorts=sorts,
368 limit=limit, marker_obj=marker_obj,
369 page_reverse=page_reverse,
370 lazy_fields=lazy_fields)
371 items = [
372 attributes.populate_project_info(
373 dict_func(c, fields) if dict_func else c)
374 for c in query
375 ]
376 if limit and page_reverse:
377 items.reverse()
378 return items
379
380
381 def get_values(context, model, field, filters=None):
382 query = query_with_hooks(context, model, field=field)
383 query = apply_filters(query, model, filters, context)
384 return [c[0] for c in query]
385
386
387 def get_collection_count(context, model, filters=None, query_field=None):
388 """Get the count for a specific collection.
389
390 :param context: The context to use for the DB session.
391 :param model: The model for the query.
392 :param filters: The filters to apply.
393 :param query_field: Column, in string format, from the "model"; the query
394 will return only this parameter instead of the full
395 model columns.
396 :returns: The number of objects for said model with filters applied.
397 """
398 return get_collection_query(context, model, filters=filters,
399 field=query_field).count()