Debian Codegraph @

neutron_lib/db/utils.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 import functools
14
15 from oslo_db import exception as db_exc
16 from oslo_utils import excutils
17 import sqlalchemy
18 from sqlalchemy.ext import associationproxy
19 from sqlalchemy.orm import exc
20 from sqlalchemy.orm import properties
21
22 from neutron_lib._i18n import _
23 from neutron_lib.api import attributes
24 from neutron_lib import exceptions as n_exc
25
26
27 def get_and_validate_sort_keys(sorts, model):
28 """Extract sort keys from sorts and ensure they are valid for the model.
29
30 :param sorts: A list of (key, direction) tuples.
31 :param model: A sqlalchemy ORM model class.
32 :returns: A list of the extracted sort keys.
33 :raises BadRequest: If a sort key attribute references another resource
34 and cannot be used in the sort.
35 """
36
37 sort_keys = [s[0] for s in sorts]
38 for sort_key in sort_keys:
39 try:
40 sort_key_attr = getattr(model, sort_key)
41 except AttributeError as e:
42 # Extension attributes don't support sorting. Because it
43 # existed in attr_info, it will be caught here.
44 msg = _("'%s' is an invalid attribute for sort key") % sort_key
45 raise n_exc.BadRequest(
46 resource=model.__tablename__, msg=msg) from e
47 if isinstance(sort_key_attr.property,
48 properties.RelationshipProperty):
49 msg = _("Attribute '%(attr)s' references another resource and "
50 "cannot be used to sort '%(resource)s' resources"
51 ) % {'attr': sort_key, 'resource': model.__tablename__}
52 raise n_exc.BadRequest(resource=model.__tablename__, msg=msg)
53
54 return sort_keys
55
56
57 def get_sort_dirs(sorts, page_reverse=False):
58 """Extract sort directions from sorts, possibly reversed.
59
60 :param sorts: A list of (key, direction) tuples.
61 :param page_reverse: True if sort direction is reversed.
62 :returns: The list of extracted sort directions optionally reversed.
63 """
64 if page_reverse:
65 return ['desc' if s[1] else 'asc' for s in sorts]
66 return ['asc' if s[1] else 'desc' for s in sorts]
67
68
69 def _is_nested_instance(exception, etypes):
70 """Check if exception or its inner excepts are an instance of etypes."""
71 return (isinstance(exception, etypes) or
72 isinstance(exception, n_exc.MultipleExceptions) and
73 any(_is_nested_instance(i, etypes)
74 for i in exception.inner_exceptions))
75
76
77 def is_retriable(exception):
78 """Determine if the said exception is retriable.
79
80 :param exception: The exception to check.
81 :returns: True if 'exception' is retriable, otherwise False.
82 """
83 if _is_nested_instance(exception,
84 (db_exc.DBDeadlock, exc.StaleDataError,
85 db_exc.DBConnectionError,
86 db_exc.DBDuplicateEntry, db_exc.RetryRequest)):
87 return True
88 # Look for savepoints mangled by deadlocks. See bug/1590298 for details.
89 return (_is_nested_instance(exception, db_exc.DBError) and
90 '1305' in str(exception))
91
92
93 def reraise_as_retryrequest(function):
94 """Wrap the said function with a RetryRequest upon error.
95
96 :param function: The function to wrap/decorate.
97 :returns: The 'function' wrapped in a try block that will reraise any
98 Exception's as a RetryRequest.
99 :raises RetryRequest: If the wrapped function raises retriable exception.
100 """
101 @functools.wraps(function)
102 def _wrapped(*args, **kwargs):
103 try:
104 return function(*args, **kwargs)
105 except Exception as e:
106 with excutils.save_and_reraise_exception() as ctx:
107 if is_retriable(e):
108 ctx.reraise = False
109 raise db_exc.RetryRequest(e)
110 return _wrapped
111
112
113 def get_marker_obj(plugin, context, resource, limit, marker):
114 """Retrieve a resource marker object.
115
116 This function is used to invoke
117 plugin._get_<resource>(context, marker) and is used for pagination.
118
119 :param plugin: The plugin processing the request.
120 :param context: The request context.
121 :param resource: The resource name.
122 :param limit: Indicates if pagination is in effect.
123 :param marker: The id of the marker object.
124 :returns: The marker object associated with the plugin if limit and marker
125 are given.
126 """
127 if limit and marker:
128 return getattr(plugin, f'_get_{resource}')(context, marker)
129
130
131 def resource_fields(resource, fields):
132 """Return only the resource items that are in fields.
133
134 :param resource: A resource dict.
135 :param fields: A list of fields to select from the resource.
136 :returns: A new dict that contains only fields from resource as well
137 as its attribute project info.
138 """
139 if fields:
140 resource = {key: item for key, item in resource.items()
141 if key in fields}
142 return attributes.populate_project_info(resource)
143
144
145 def filter_non_model_columns(data, model):
146 """Return the attributes from data which are model columns.
147
148 :param data: The dict containing the data to filter.
149 :param model: The model who's column names are used when filtering data.
150 :returns: A new dict who's keys are columns in model or are association
151 proxies of the model.
152 """
153 mapper = sqlalchemy.inspect(model)
154 columns = {c.name for c in mapper.columns}
155 try:
156 _association_proxy = associationproxy.ASSOCIATION_PROXY
157 except AttributeError:
158 # SQLAlchemy 2.0
159 _association_proxy = (
160 associationproxy.AssociationProxyExtensionType.ASSOCIATION_PROXY)
161 columns.update(d.value_attr for d in mapper.all_orm_descriptors
162 if d.extension_type is _association_proxy)
163 return {k: v for (k, v)
164 in data.items() if k in columns}
165
166
167 def model_query_scope_is_project(context, model):
168 """Determine if a model should be scoped to a project.
169
170 :param context: The context to check for admin and advsvc rights.
171 :param model: The model to check the project_id of.
172 :returns: True if the context has no global access and is not advsvc
173 and the model has a project_id. False otherwise.
174 """
175 if not hasattr(model, 'project_id'):
176 # If model doesn't have project_id, there is no need to scope query to
177 # just one project
178 return False
179 if context.is_service_role:
180 # For context which has 'advanced-service' rights the
181 # query will not be scoped to a single project_id
182 return False
183 # Unless context has 'global' access the
184 # resources from the database query will be scoped to a single project_id
185 # context with 'admin' rights is treated as it has global access always.
186 return not context.has_global_access
187
188
189 def model_query(context, model):
190 """Query the context for the said model.
191
192 :param context: The context to use for the query.
193 :param model: The model to query for.
194 :returns: A query from the said context for the said model.
195 """
196 query = context.session.query(model)
197 # define basic filter condition for model query
198 query_filter = None
199 if model_query_scope_is_project(context, model):
200 query_filter = (model.tenant_id == context.project_id)
201
202 if query_filter is not None:
203 query = query.filter(query_filter)
204 return query