Debian Codegraph @

neutron_lib/db/api.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 contextlib
14 import copy
15 import functools
16 import weakref
17
18 from oslo_concurrency import lockutils
19 from oslo_config import cfg
20 from oslo_db import api as oslo_db_api
21 from oslo_db import exception as db_exc
22 from oslo_db.sqlalchemy import enginefacade
23 from oslo_log import log as logging
24 from oslo_utils import excutils
25 from osprofiler import opts as profiler_opts
26 import osprofiler.sqlalchemy
27 from pecan import util as p_util
28 import sqlalchemy
29 from sqlalchemy import event # noqa
30 from sqlalchemy import exc as sql_exc
31 from sqlalchemy import orm
32 from sqlalchemy.orm import exc
33
34 from neutron_lib._i18n import _
35 from neutron_lib.db import model_base
36 from neutron_lib import exceptions
37 from neutron_lib.objects import exceptions as obj_exc
38
39
40 MAX_RETRIES = 20
41 LOG = logging.getLogger(__name__)
42 _synchronized = lockutils.synchronized_with_prefix("neutron-")
43 _CTX_MANAGER = None
44
45
46 @_synchronized("context-manager")
47 def _create_context_manager():
48 global _CTX_MANAGER
49 if _CTX_MANAGER is None:
50 _CTX_MANAGER = enginefacade.transaction_context()
51 _CTX_MANAGER.configure(sqlite_fk=True, flush_on_subtransaction=True)
52
53 return _CTX_MANAGER
54
55
56 def get_context_manager():
57 """Transaction Context Manager accessor.
58
59 :returns: The transaction context manager.
60 """
61 if _CTX_MANAGER is None:
62 return _create_context_manager()
63
64 return _CTX_MANAGER
65
66
67 def _set_hook(engine):
68 if (profiler_opts.is_trace_enabled() and
69 profiler_opts.is_db_trace_enabled()):
70 osprofiler.sqlalchemy.add_tracing(
71 sqlalchemy, engine, "neutron.db")
72
73
74 # TODO(ihrachys) the hook assumes options defined by osprofiler, and the only
75 # public function that is provided by osprofiler that will register them is
76 # set_defaults, that's why we call it here even though we don't need to change
77 # defaults
78 profiler_opts.set_defaults(cfg.CONF)
79 get_context_manager().append_on_engine_create(_set_hook)
80
81
82 def get_reader_session():
83 """Helper to get reader session.
84
85 :returns: The reader session.
86 """
87 return get_context_manager().reader.get_sessionmaker()()
88
89
90 def get_writer_session():
91 """Helper to get writer session.
92
93 :returns: The writer session.
94 """
95 return get_context_manager().writer.get_sessionmaker()()
96
97
98 def _is_nested_instance(e, etypes):
99 """Check if exception or its inner excepts are an instance of etypes."""
100 if isinstance(e, etypes):
101 return True
102 if isinstance(e, exceptions.MultipleExceptions):
103 return any(_is_nested_instance(i, etypes) for i in e.inner_exceptions)
104 if isinstance(e, db_exc.DBError):
105 return _is_nested_instance(e.inner_exception, etypes)
106 return False
107
108
109 def is_retriable(e):
110 """Determine if the exception is retriable.
111
112 :param e: The exception to check.
113 :returns: True if e is retriable and False otherwise.
114 """
115 if getattr(e, '_RETRY_EXCEEDED', False):
116 return False
117 if _is_nested_instance(e, (db_exc.DBDeadlock, exc.StaleDataError,
118 db_exc.DBConnectionError,
119 db_exc.DBDuplicateEntry, db_exc.RetryRequest,
120 obj_exc.NeutronDbObjectDuplicateEntry)):
121 return True
122 # looking savepoints mangled by deadlocks. see bug/1590298 for details.
123 return _is_nested_instance(e, db_exc.DBError) and '1305' in str(e)
124
125
126 def _tag_retriables_as_unretriable(f):
127 """Puts a flag on retriable exceptions so is_retriable returns False.
128
129 This decorator can be used outside of a retry decorator to prevent
130 decorators higher up from retrying again.
131 """
132 @functools.wraps(f)
133 def wrapped(*args, **kwargs):
134 try:
135 return f(*args, **kwargs)
136 except Exception as e:
137 with excutils.save_and_reraise_exception():
138 if is_retriable(e):
139 setattr(e, '_RETRY_EXCEEDED', True)
140 return wrapped
141
142
143 def _copy_if_lds(item):
144 """Deepcopy lists/dicts/sets, leave everything else alone."""
145 return copy.deepcopy(item) if isinstance(item, list | dict | set) else item
146
147
148 _retry_db_errors = oslo_db_api.wrap_db_retry(
149 max_retries=MAX_RETRIES,
150 retry_interval=0.5,
151 inc_retry_interval=True,
152 exception_checker=is_retriable,
153 jitter=True
154 )
155
156
157 def retry_db_errors(f):
158 """Nesting-safe retry decorator with auto-arg-copy and logging.
159
160 Retry decorator for all functions which do not accept a context as an
161 argument. If the function accepts a context, use
162 'retry_if_session_inactive' below.
163
164 If retriable errors are retried and exceed the count, they will be tagged
165 with a flag so is_retriable will no longer recognize them as retriable.
166 This prevents multiple applications of this decorator (and/or the one
167 below) from retrying the same exception.
168 """
169
170 @_tag_retriables_as_unretriable
171 @_retry_db_errors
172 @functools.wraps(f)
173 def wrapped(*args, **kwargs):
174 context_reference = None
175 try:
176 # copy mutable args and kwargs to make retries safe. this doesn't
177 # prevent mutations of complex objects like the context or 'self'
178 context_reference = kwargs.pop('_context_reference', None)
179 dup_args = [_copy_if_lds(a) for a in args]
180 dup_kwargs = {k: _copy_if_lds(v) for k, v in kwargs.items()}
181 return f(*dup_args, **dup_kwargs)
182 except Exception as e:
183 with excutils.save_and_reraise_exception():
184 if is_retriable(e):
185 LOG.debug("Retry wrapper got retriable exception: %s", e)
186 if context_reference and context_reference.session:
187 context_reference.session.rollback()
188 return wrapped
189
190
191 def retry_if_session_inactive(context_var_name='context'):
192 """Retries only if the session in the context is inactive.
193
194 Calls a retry_db_errors wrapped version of the function if the context's
195 session passed in is inactive, otherwise it just calls the function
196 directly. This is useful to avoid retrying things inside of a transaction
197 which is ineffective for DB races/errors.
198
199 This should be used in all cases where retries are desired and the method
200 accepts a context.
201 """
202 def decorator(f):
203 try:
204 # NOTE(kevinbenton): we use pecan's util function here because it
205 # deals with the horrors of finding args of already decorated
206 # functions
207 ctx_arg_index = p_util.getargspec(f).args.index(context_var_name)
208 except ValueError as e:
209 msg = _("Could not find position of var %s") % context_var_name
210 raise RuntimeError(msg) from e
211 f_with_retry = retry_db_errors(f)
212
213 @functools.wraps(f)
214 def wrapped(*args, **kwargs):
215 # only use retry wrapper if we aren't nested in an active
216 # transaction
217 context = kwargs.get(context_var_name)
218 if context is None:
219 context = args[ctx_arg_index]
220 if context.session and is_session_active(context.session):
221 return f(*args, **kwargs)
222 else:
223 return f_with_retry(*args, **kwargs,
224 _context_reference=context)
225 return wrapped
226 return decorator
227
228
229 @contextlib.contextmanager
230 def exc_to_retry(etypes):
231 """Contextually reraise Exceptions as a RetryRequests.
232
233 :param etypes: The class type to check the exception for.
234 :returns: None
235 :raises: A RetryRequest if any exception is caught in the context
236 is a nested instance of etypes.
237 """
238 try:
239 yield
240 except Exception as e:
241 with excutils.save_and_reraise_exception() as ctx:
242 if _is_nested_instance(e, etypes):
243 ctx.reraise = False
244 raise db_exc.RetryRequest(e)
245
246
247 # for convenient access as decorators
248 CONTEXT_READER = get_context_manager().reader
249 CONTEXT_WRITER = get_context_manager().writer
250
251 _REGISTERED_SQLA_EVENTS = []
252
253
254 def sqla_listen(*args):
255 """Wrapper to track subscribers for test teardowns.
256
257 SQLAlchemy has no "unsubscribe all" option for its event listener
258 framework so we need to keep track of the subscribers by having
259 them call through here for test teardowns.
260
261 :param args: The arguments to pass onto the listen call.
262 :returns: None
263 """
264 event.listen(*args)
265 _REGISTERED_SQLA_EVENTS.append(args)
266
267
268 def sqla_remove(*args):
269 """Remove SQLA listeners.
270
271 :param args: The args to pass onto remove.
272 :returns: None.
273 """
274 event.remove(*args)
275 _REGISTERED_SQLA_EVENTS.remove(args)
276
277
278 def sqla_remove_all():
279 """Removes all SQLA listeners.
280
281 :returns: None.
282 """
283 for args in _REGISTERED_SQLA_EVENTS:
284 try:
285 event.remove(*args)
286 except sql_exc.InvalidRequestError:
287 # already removed
288 pass
289 del _REGISTERED_SQLA_EVENTS[:]
290
291
292 @event.listens_for(orm.session.Session, "after_flush")
293 def _add_to_rel_load_list(session, flush_context=None):
294 # keep track of new items to load relationships on during commit
295 session.info.setdefault('_load_rels', weakref.WeakSet()).update(
296 session.new)
297
298
299 @event.listens_for(orm.session.Session, "before_commit")
300 def _load_one_to_manys(session):
301 # TODO(kevinbenton): we should be able to remove this after we
302 # have eliminated all places where related objects are constructed
303 # using a key rather than a relationship.
304
305 # capture any new objects
306 if session.new:
307 session.flush()
308
309 if session.get_transaction().nested:
310 # wait until final commit
311 return
312
313 for new_object in session.info.pop('_load_rels', []):
314 if new_object not in session:
315 # don't load detached objects because that brings them back into
316 # session
317 continue
318 state = sqlalchemy.inspect(new_object)
319
320 # set up relationship loading so that we can call lazy
321 # loaders on the object even though the ".key" is not set up yet
322 # (normally happens by in after_flush_postexec, but we're trying
323 # to do this more succinctly). in this context this is only
324 # setting a simple flag on the object's state.
325 session.enable_relationship_loading(new_object)
326
327 # look for eager relationships and do normal load.
328 # For relationships where the related object is also
329 # in the session these lazy loads will pull from the
330 # identity map and not emit SELECT. Otherwise, we are still
331 # local in the transaction so a normal SELECT load will work fine.
332 for relationship_attr in state.mapper.relationships:
333 if relationship_attr.lazy not in ('joined', 'subquery',
334 'selectin'):
335 # we only want to automatically load relationships that would
336 # automatically load during a lookup operation
337 continue
338 if relationship_attr.key not in state.dict:
339 getattr(new_object, relationship_attr.key)
340 if relationship_attr.key not in state.dict:
341 msg = (f"Relationship {relationship_attr.key} attributes "
342 f"must be loaded in db object {state.dict}")
343 raise AssertionError(msg)
344
345
346 # Expire relationships when foreign key changes.
347 #
348 # NOTE(ihrachys) Arguably, it's a sqlalchemy anti-pattern to access child
349 # models directly and through parent relationships in the same session. But
350 # since OVO mechanism is built around synthetic fields that assume this mixed
351 # access is possible, we keep it here until we find a way to migrate OVO
352 # synthetic fields to better mechanism that would update child models via
353 # parents. Even with that, there are multiple places in plugin code where we
354 # mix access when using models directly; those occurrences would need to be
355 # fixed too to be able to remove this hook and explicit expire() calls.
356 #
357 # Adopted from the following recipe:
358 # https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes
359 # /ExpireRelationshipOnFKChange
360 #
361 # ...then massively changed to actually work for all neutron backref cases.
362 #
363 # TODO(ihrachys) at some point these event handlers should be extended to also
364 # automatically refresh values for expired attributes
365 def _expire_for_fk_change(target, fk_value, relationship_prop, column_attr):
366 """Expire relationship attributes when a many-to-one column changes."""
367
368 sess = orm.object_session(target)
369
370 # subnets and network's many-to-one relationship is used as example in the
371 # comments in this function
372 if sess is not None:
373 # optional behavior #1 - expire the "Network.subnets"
374 # collection on the existing "network" object
375 if relationship_prop.back_populates and \
376 relationship_prop.key in target.__dict__:
377 obj = getattr(target, relationship_prop.key)
378 if obj is not None and sqlalchemy.inspect(obj).persistent:
379 sess.expire(obj, [relationship_prop.back_populates])
380
381 # optional behavior #2 - expire the "Subnet.network"
382 if sqlalchemy.inspect(target).persistent:
383 sess.expire(target, [relationship_prop.key])
384
385 # optional behavior #3 - "trick" the ORM by actually
386 # setting the value ahead of time, then emitting a load
387 # for the attribute so that the *new* Subnet.network
388 # is loaded. Then, expire Network.subnets on *that*.
389 # Other techniques here including looking in the identity
390 # map for "value", if this is a simple many-to-one get.
391 if relationship_prop.back_populates:
392 target.__dict__[column_attr] = fk_value
393 new = getattr(target, relationship_prop.key)
394 if new is not None:
395 if sqlalchemy.inspect(new).persistent:
396 sess.expire(new, [relationship_prop.back_populates])
397 else:
398 # no Session yet, do it later. This path is reached from the 'expire'
399 # listener setup by '_expire_prop_on_col' below, when a foreign key
400 # is directly assigned to in the many to one side of a relationship.
401 # i.e. assigning directly to Subnet.network_id before Subnet is added
402 # to the session
403 if target not in _emit_on_pending:
404 _emit_on_pending[target] = []
405 _emit_on_pending[target].append(
406 (fk_value, relationship_prop, column_attr))
407
408
409 _emit_on_pending = weakref.WeakKeyDictionary()
410
411
412 @event.listens_for(orm.session.Session, "pending_to_persistent")
413 def _pending_callables(session, obj):
414 """Expire relationships when a new object w/ a FK becomes persistent"""
415 if obj is None:
416 return
417 args = _emit_on_pending.pop(obj, [])
418 for a in args:
419 if a is not None:
420 _expire_for_fk_change(obj, *a)
421
422
423 @event.listens_for(orm.session.Session, "persistent_to_deleted")
424 def _persistent_to_deleted(session, obj):
425 """Expire relationships when an object w/ a foreign key becomes deleted"""
426 mapper = sqlalchemy.inspect(obj).mapper
427 for prop in mapper.relationships:
428 if prop.direction is orm.interfaces.MANYTOONE:
429 for col in prop.local_columns:
430 colkey = mapper.get_property_by_column(col).key
431 _expire_for_fk_change(obj, None, prop, colkey)
432
433
434 @event.listens_for(model_base.BASEV2, "attribute_instrument", propagate=True)
435 def _listen_for_changes(cls, key, inst):
436 mapper = sqlalchemy.inspect(cls)
437 if key not in mapper.relationships:
438 return
439 prop = inst.property
440
441 if prop.direction is orm.interfaces.MANYTOONE:
442 for col in prop.local_columns:
443 colkey = mapper.get_property_by_column(col).key
444 _expire_prop_on_col(cls, prop, colkey)
445 elif prop.direction is orm.interfaces.ONETOMANY:
446 remote_mapper = prop.mapper
447 # the collection *has* to have a MANYTOONE backref so we
448 # can look up the parent. so here we make one if it doesn't
449 # have it already, as is the case in this example
450 if not prop.back_populates:
451 name = f"_{prop.key}_backref"
452 backref_prop = orm.relationship(
453 prop.parent, back_populates=prop.key)
454
455 remote_mapper.add_property(name, backref_prop)
456 prop.back_populates = name
457
458
459 def _expire_prop_on_col(cls, prop, colkey):
460 @event.listens_for(getattr(cls, colkey), "set")
461 def expire(target, value, oldvalue, initiator):
462 """Expire relationships when FK attribute on an object changes"""
463 _expire_for_fk_change(target, value, prop, colkey)
464
465
466 def is_session_active(session):
467 """Return if the session is active
468
469 Since sqlalchemy 1.4, "autocommit=False" by default; in sqlalchemy 2.0,
470 that will be the only possible value. If session autocommit is False, the
471 session transaction will not end at the end of a reader/writer context.
472 In this case, a session could have an active transaction even when it is
473 not inside a reader/writer context. In order to mimic the previous
474 behaviour, this method checks if there is a transaction created and if
475 the transaction has any active connection against the database server.
476 """
477 if getattr(session, 'autocommit', None):
478 # old behaviour, to be removed with sqlalchemy 2.0
479 return session.is_active
480 if not session.get_transaction():
481 return False
482 if not session.get_transaction()._connections:
483 return False
484 return True