Debian Codegraph @

oslo_db/sqlalchemy/enginefacade.py

raw symbols SCIP
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 from __future__ import annotations
13
14 import contextlib
15 from enum import Enum
16 import functools
17 import inspect
18 import operator
19 import threading
20 from typing import ContextManager
21 from typing import Generic
22 from typing import Protocol
23 from typing import TYPE_CHECKING
24 from typing import TypeVar
25 from typing import Union
26 import warnings
27
28 import debtcollector.removals
29 import debtcollector.renames
30 from oslo_config import cfg
31 from oslo_db import exception
32 from oslo_db import options
33 from oslo_db.sqlalchemy import engines
34 from oslo_db.sqlalchemy import orm
35 from oslo_db import warning
36 from oslo_utils import excutils
37
38
39 if TYPE_CHECKING:
40 from typing import Any
41 from typing import Self
42
43 from sqlalchemy.engine import Connection
44 from sqlalchemy.engine import Engine
45 from sqlalchemy.ext.asyncio import async_sessionmaker
46 from sqlalchemy.ext.asyncio import AsyncConnection
47 from sqlalchemy.ext.asyncio import AsyncEngine
48 from sqlalchemy.ext.asyncio import AsyncSession
49 from sqlalchemy.orm import Session
50 from sqlalchemy.orm import sessionmaker
51
52 _AllEngineSessionT = TypeVar(
53 "_AllEngineSessionT",
54 bound=Union[
55 "Connection", "Session", "AsyncConnection", "AsyncSession", None
56 ],
57 )
58
59 _SyncEngineSessionT = TypeVar(
60 "_SyncEngineSessionT", bound=Union["Connection", "Session", None]
61 )
62
63
64 class _FacadeSymbols(Enum):
65 _ASYNC_READER = 1
66 """Represent the transaction state of "async reader".
67
68 This state indicates that the transaction is a read-only and is
69 safe to use on an asynchronously updated slave database.
70 """
71
72 _READER = 2
73 """Represent the transaction state of "reader".
74
75 This state indicates that the transaction is a read-only and is
76 only safe to use on a synchronously updated slave database; otherwise
77 the master database should be used.
78 """
79
80 _WRITER = 3
81 """Represent the transaction state of "writer".
82
83 This state indicates that the transaction writes data and
84 should be directed at the master database.
85 """
86
87
88 _ASYNC_READER, _READER, _WRITER = (
89 _FacadeSymbols._ASYNC_READER,
90 _FacadeSymbols._READER,
91 _FacadeSymbols._WRITER,
92 )
93
94
95 class _NotSet(Enum):
96 NOTSET = 1
97
98
99 class _Default:
100 """Mark a value as a default value.
101
102 A value in the local configuration dictionary wrapped with
103 _Default() will not take precedence over a value that is specified
104 in cfg.CONF. Values that are set after the fact using configure()
105 will supersede those in cfg.CONF.
106 """
107
108 __slots__ = ("value",)
109
110 _notset = _NotSet.NOTSET
111
112 def __init__(self, value=_notset):
113 self.value = value
114
115 @classmethod
116 def resolve(cls, value):
117 if isinstance(value, _Default):
118 v = value.value
119 if v is cls._notset:
120 return None
121 else:
122 return v
123 else:
124 return value
125
126 @classmethod
127 def resolve_w_conf(cls, value, conf, key):
128 if isinstance(value, _Default):
129 v = getattr(conf.database, key, value.value)
130 if v is cls._notset:
131 return None
132 else:
133 return v
134 else:
135 return value
136
137 @classmethod
138 def is_set(cls, value):
139 if not isinstance(value, _Default):
140 return True
141
142 return value.value is not cls._notset
143
144 @classmethod
145 def is_set_w_conf(cls, value, conf, key):
146 if hasattr(conf.database, key):
147 # If the option is set via configuration then we should always
148 # respect it...unless that option is deprecated and hasn't been set
149 # by user, in which case we should ignore it.
150
151 # oslo.config doesn't provide a public API to retrieve the opt
152 # itself, as opposed to the value of the opt :(
153 opt = conf.database._group._opts[key]["opt"]
154 # ditto for the group
155 group = conf.database._group
156 if (
157 opt.deprecated_for_removal and
158 conf.get_location(key, group=group.name).location ==
159 cfg.Locations.opt_default
160 ):
161 return False
162
163 return True
164
165 return cls.is_set(value)
166
167
168 class AlreadyStartedError(TypeError):
169 """Raises when a factory is being asked to initialize a second time.
170
171 Subclasses :class:`.TypeError` for legacy support.
172 """
173
174
175 class _EnterableLock(Protocol):
176 def __enter__(self):
177 ...
178
179 def __exit__(self, *arg, **kw):
180 ...
181
182
183 class _AbstractTransactionFactory:
184 """Abstract base for _TransactionFactory."""
185
186 _start_lock: _EnterableLock
187 _writer_engine: Engine | AsyncEngine
188 _reader_engine: Engine | AsyncEngine
189 _writer_maker: sessionmaker | async_sessionmaker
190 _reader_maker: sessionmaker | async_sessionmaker
191
192 def __init__(self):
193 self._url_cfg = {
194 "connection": _Default(),
195 "slave_connection": _Default(),
196 "asyncio_connection": _Default(),
197 "asyncio_slave_connection": _Default(),
198 }
199 self._engine_cfg = {
200 "sqlite_fk": _Default(False),
201 "mysql_sql_mode": _Default("TRADITIONAL"),
202 "mysql_wsrep_sync_wait": _Default(),
203 "connection_recycle_time": _Default(3600),
204 "connection_debug": _Default(0),
205 "max_pool_size": _Default(),
206 "max_overflow": _Default(),
207 "pool_timeout": _Default(),
208 "sqlite_synchronous": _Default(True),
209 "connection_trace": _Default(False),
210 "max_retries": _Default(10),
211 "retry_interval": _Default(10),
212 "thread_checkin": _Default(True),
213 "json_serializer": _Default(None),
214 "json_deserializer": _Default(None),
215 "logging_name": _Default(None),
216 "connection_parameters": _Default(None),
217 }
218 self._maker_cfg = {
219 "expire_on_commit": _Default(False),
220 }
221 self._transaction_ctx_cfg = {
222 "rollback_reader_sessions": False,
223 "flush_on_subtransaction": False,
224 }
225 self._facade_cfg = {
226 "synchronous_reader": _Default(True),
227 "on_engine_create": [],
228 }
229
230 # other options that are defined in oslo_db.options.database_opts
231 # but do not apply to the standard enginefacade arguments (most seem
232 # to apply to api.DBAPI).
233 self._ignored_cfg = {
234 k: _Default(None)
235 for k in [
236 "db_max_retries",
237 "db_inc_retry_interval",
238 "use_db_reconnect",
239 "db_retry_interval",
240 "db_max_retry_interval",
241 "backend",
242 ]
243 }
244
245 self._started = False
246 self._start_lock = self._make_lock()
247
248 def _make_lock(self) -> _EnterableLock:
249 raise NotImplementedError()
250
251 def _setup_for_connection(
252 self,
253 sql_connection,
254 engine_kwargs,
255 maker_kwargs,
256 ):
257 raise NotImplementedError()
258
259 def configure_defaults(self, **kw: Any) -> None:
260 """Apply default configurational options.
261
262 This method can only be called before any specific
263 transaction-beginning methods have been called.
264
265 Configurational options are within a fixed set of keys, and fall
266 under three categories: URL configuration, engine configuration,
267 and session configuration. Each key given will be tested against
268 these three configuration sets to see which one is applicable; if
269 it is not applicable to any set, an exception is raised.
270
271 The configurational options given here act as **defaults**
272 when the :class:`._TransactionFactory` is configured using
273 a :class:`oslo_config.cfg.ConfigOpts` object; the options
274 present within the :class:`oslo_config.cfg.ConfigOpts` **take
275 precedence** versus the arguments passed here. By default,
276 the :class:`._TransactionFactory` loads in the configuration from
277 :data:`oslo_config.cfg.CONF`, after applying the
278 :data:`oslo_db.options.database_opts` configurational defaults to it.
279
280 :param connection: database URL
281 :param slave_connection: database URL
282 :param asyncio_connection: database URL
283 :param asyncio_slave_connection: database URL
284 :param sqlite_fk: whether to enable SQLite foreign key pragma; default
285 False
286 :param mysql_sql_mode: MySQL SQL mode, defaults to TRADITIONAL
287 :param mysql_wsrep_sync_wait: MySQL wsrep_sync_wait, defaults to None,
288 which indicates no setting will be passed
289 :param connection_recycle_time: connection pool recycle time,
290 defaults to 3600. Note the connection does not actually have to be
291 "idle" to be recycled.
292 :param connection_debug: engine logging level, defaults to 0. set to
293 50 for INFO, 100 for DEBUG.
294 :param connection_parameters: additional parameters to append onto the
295 database URL query string, pass as
296 "param1=value1&param2=value2&..."
297 :param max_pool_size: max size of connection pool, uses CONF for
298 default
299 :param max_overflow: max overflow for connection pool, uses CONF for
300 default
301 :param sqlite_synchronous: disable SQLite SYNCHRONOUS pragma if False;
302 defaults to True
303 :param connection_trace: enable tracing comments in logging
304 :param max_retries: max retries to connect, defaults to !0
305 :param retry_interval: time in seconds between retries, defaults to 10
306 :param thread_checkin: add sleep(0) on connection checkin to allow
307 greenlet yields, defaults to True
308 :param json_serializer: JSON serializer for PostgreSQL connections
309 :param json_deserializer: JSON deserializer for PostgreSQL connections
310 :param logging_name: logging name for engine
311 :param expire_on_commit: sets expire_on_commit for SQLAlchemy
312 sessionmaker; defaults to False
313 :param rollback_reader_sessions: if True, a :class:`.Session` object
314 will have its :meth:`.Session.rollback` method invoked at the end
315 of a ``@reader`` block, actively rolling back the transaction and
316 expiring the objects within, before the :class:`.Session` moves on
317 to be closed, which has the effect of releasing connection
318 resources back to the connection pool and detaching all objects.
319 If False, the :class:`.Session` is not affected at the end of a
320 ``@reader`` block; the underlying connection referred to by this
321 :class:`.Session` will still be released in the enclosing context
322 via the :meth:`.Session.close` method, which still ensures that the
323 DBAPI connection is rolled back, however the objects associated
324 with the :class:`.Session` retain their database-persisted contents
325 after they are detached.
326
327 .. seealso::
328
329 http://docs.sqlalchemy.org/en/rel_0_9/glossary.html#term-released\
330 SQLAlchemy documentation on what "releasing resources" means.
331 :param synchronous_reader: whether or not to assume a "reader" context
332 needs to guarantee it can read data committed by a "writer"
333 assuming replication lag is present; defaults to True. When False,
334 a @reader context works the same as @async_reader and will select
335 the "slave" database if present.
336 :param flush_on_subtransaction: if True, a :class:`.Session` object
337 will have its :meth:`.Session.flush` method invoked whenever a
338 context manager or decorator that is not itself the originator of
339 the top- level or savepoint :class:`.Session` transaction exits -
340 in this way it behaves like a "subtransaction" from a
341 :class:`.Session` perspective.
342
343 .. seealso::
344
345 :meth:`._TransactionFactory.configure`
346 """
347 self._configure(True, kw)
348
349 def configure(self, **kw: Any) -> None:
350 """Apply configurational options.
351
352 This method can only be called before any specific
353 transaction-beginning methods have been called.
354
355 Behavior here is the same as that of
356 :meth:`._TransactionFactory.configure_defaults`,
357 with the exception that values specified here will **supersede** those
358 setup in the :class:`oslo_config.cfg.ConfigOpts` options. See
359 that method for a listing of all keyword arguments.
360
361 .. seealso::
362
363 :meth:`._TransactionFactory.configure_defaults`
364 """
365 self._configure(False, kw)
366
367 def _configure(self, as_defaults, kw):
368 if self._started:
369 raise AlreadyStartedError(
370 "this TransactionFactory is already started"
371 )
372
373 not_supported = []
374 for k, v in kw.items():
375 for dict_ in (
376 self._url_cfg,
377 self._engine_cfg,
378 self._maker_cfg,
379 self._ignored_cfg,
380 self._facade_cfg,
381 self._transaction_ctx_cfg,
382 ):
383 if k in dict_:
384 dict_[k] = _Default(v) if as_defaults else v
385 break
386 else:
387 not_supported.append(k)
388
389 if not_supported:
390 # would like to raise ValueError here, but there are just
391 # too many unrecognized (obsolete?) configuration options
392 # coming in from projects
393 warnings.warn(
394 "Configuration option(s) %r not supported"
395 % sorted(not_supported),
396 warning.NotSupportedWarning,
397 )
398
399 def get_writer_engine(self) -> Engine | AsyncEngine:
400 """Return the writer engine for this factory.
401
402 Implies start.
403 """
404 if not self._started:
405 self._start()
406 return self._writer_engine
407
408 def get_reader_engine(self) -> Engine | AsyncEngine:
409 """Return the reader engine for this factory.
410
411 Implies start.
412 """
413 if not self._started:
414 self._start()
415 return self._reader_engine
416
417 def get_writer_maker(self) -> sessionmaker | async_sessionmaker:
418 """Return the writer sessionmaker for this factory.
419
420 Implies start.
421 """
422 if not self._started:
423 self._start()
424 return self._writer_maker
425
426 def get_reader_maker(self) -> sessionmaker | async_sessionmaker:
427 """Return the reader sessionmaker for this factory.
428
429 Implies start.
430 """
431 if not self._started:
432 self._start()
433 return self._reader_maker
434
435 def _create_factory_copy(self) -> Self:
436 factory = self.__class__()
437 factory._url_cfg.update(self._url_cfg)
438 factory._engine_cfg.update(self._engine_cfg)
439 factory._maker_cfg.update(self._maker_cfg)
440 factory._transaction_ctx_cfg.update(self._transaction_ctx_cfg)
441 factory._facade_cfg.update(self._facade_cfg)
442 return factory
443
444 def _create_connection(self, mode):
445 if not self._started:
446 self._start()
447 if mode is _WRITER:
448 return self._writer_engine.connect()
449 elif mode is _ASYNC_READER or (
450 mode is _READER and not self.synchronous_reader
451 ):
452 return self._reader_engine.connect()
453 else:
454 return self._writer_engine.connect()
455
456 def _create_session(self, mode, bind=None):
457 if not self._started:
458 self._start()
459 kw = {}
460 # don't pass 'bind' if bind is None; the sessionmaker
461 # already has a bind to the engine.
462 if bind:
463 kw["bind"] = bind
464 if mode is _WRITER:
465 return self._writer_maker(**kw)
466 elif mode is _ASYNC_READER or (
467 mode is _READER and not self.synchronous_reader
468 ):
469 return self._reader_maker(**kw)
470 else:
471 return self._writer_maker(**kw)
472
473 def _args_for_conf(self, default_cfg, conf):
474 if conf is None:
475 return {
476 key: _Default.resolve(value)
477 for key, value in default_cfg.items()
478 if _Default.is_set(value)
479 }
480 else:
481 return {
482 key: _Default.resolve_w_conf(value, conf, key)
483 for key, value in default_cfg.items()
484 if _Default.is_set_w_conf(value, conf, key)
485 }
486
487 def _url_args_for_conf(self, conf):
488 return self._args_for_conf(self._url_cfg, conf)
489
490 def _engine_args_for_conf(self, conf):
491 return self._args_for_conf(self._engine_cfg, conf)
492
493 def _maker_args_for_conf(self, conf):
494 maker_args = self._args_for_conf(self._maker_cfg, conf)
495 return maker_args
496
497 def _facade_args_for_conf(self, conf):
498 return self._args_for_conf(self._facade_cfg, conf)
499
500 @property
501 def is_started(self):
502 """True if this :class:`._TransactionFactory` is already started."""
503 return self._started
504
505 def _start(self, conf=False, connection=None, slave_connection=None):
506 with self._start_lock:
507 # self._started has been checked on the outside
508 # when _start() was called. Within the lock,
509 # check the flag once more to detect the case where
510 # the start process proceeded while this thread was waiting
511 # for the lock.
512 if self._started:
513 return
514 if conf is False:
515 conf = cfg.CONF
516
517 # perform register_opts() local to actually using
518 # the cfg.CONF to maintain exact compatibility with
519 # the legacy EngineFacade design. This can be changed if needed.
520 if conf is not None:
521 conf.register_opts(options.database_opts, "database")
522
523 url_args = self._url_args_for_conf(conf)
524 if connection:
525 url_args["connection"] = connection
526 if slave_connection:
527 url_args["slave_connection"] = slave_connection
528 engine_args = self._engine_args_for_conf(conf)
529 maker_args = self._maker_args_for_conf(conf)
530
531 self._writer_engine, self._writer_maker = (
532 self._setup_for_connection(
533 url_args["connection"], engine_args, maker_args
534 )
535 )
536
537 if url_args.get("slave_connection"):
538 self._reader_engine, self._reader_maker = (
539 self._setup_for_connection(
540 url_args["slave_connection"], engine_args, maker_args
541 )
542 )
543 else:
544 self._reader_engine, self._reader_maker = (
545 self._writer_engine,
546 self._writer_maker,
547 )
548
549 facade_args = self._facade_args_for_conf(conf)
550 self.synchronous_reader = facade_args["synchronous_reader"]
551
552 # set up _started last, so that in case of exceptions
553 # we try the whole thing again and report errors
554 # correctly
555 self._started = True
556
557
558 class _TransactionFactory(_AbstractTransactionFactory):
559 """A factory for :class:`._TransactionContext` objects.
560
561 By default, there is just one of these, set up
562 based on CONF, however instance-level :class:`._TransactionFactory`
563 objects can be made, as is the case with the
564 :class:`._TestTransactionFactory` subclass used by the oslo.db test suite.
565 """
566
567 _start_lock: threading.Lock
568 _writer_engine: Engine
569 _reader_engine: Engine
570 _writer_maker: sessionmaker
571 _reader_maker: sessionmaker
572
573 def _make_lock(self) -> threading.Lock:
574 return threading.Lock()
575
576 if TYPE_CHECKING:
577
578 def get_writer_engine(self) -> Engine:
579 """Return the writer engine for this factory.
580
581 Implies start.
582 """
583 ...
584
585 def get_reader_engine(self) -> Engine:
586 """Return the reader engine for this factory.
587
588 Implies start.
589 """
590 ...
591
592 def get_writer_maker(self) -> sessionmaker:
593 """Return the writer sessionmaker for this factory.
594
595 Implies start.
596 """
597 ...
598
599 def get_reader_maker(self) -> sessionmaker:
600 """Return the reader sessionmaker for this factory.
601
602 Implies start.
603 """
604 ...
605
606 def _create_factory_copy(self):
607 factory = _TransactionFactory()
608 factory._url_cfg.update(self._url_cfg)
609 factory._engine_cfg.update(self._engine_cfg)
610 factory._maker_cfg.update(self._maker_cfg)
611 factory._transaction_ctx_cfg.update(self._transaction_ctx_cfg)
612 factory._facade_cfg.update(self._facade_cfg)
613 return factory
614
615 def dispose_pool(self):
616 """Call engine.pool.dispose() on underlying Engine objects."""
617 with self._start_lock:
618 if not self._started:
619 return
620
621 self._writer_engine.pool.dispose()
622 if self._reader_engine is not self._writer_engine:
623 self._reader_engine.pool.dispose()
624
625 def _setup_for_connection(
626 self,
627 sql_connection,
628 engine_kwargs,
629 maker_kwargs,
630 ):
631 if sql_connection is None:
632 raise exception.CantStartEngineError(
633 "No sql_connection parameter is established"
634 )
635 engine = engines.create_engine(
636 sql_connection=sql_connection, **engine_kwargs
637 )
638 for hook in self._facade_cfg["on_engine_create"]:
639 hook(engine)
640 sessionmaker = orm.get_maker(engine=engine, **maker_kwargs)
641 return engine, sessionmaker
642
643
644 class _TestTransactionFactory(_TransactionFactory):
645 """A :class:`._TransactionFactory` used by test suites.
646
647 This is a :class:`._TransactionFactory` that can be directly injected
648 with an existing engine and sessionmaker.
649
650 Note that while this is used by oslo.db's own tests of
651 the enginefacade system, it is also exported for use by
652 the test suites of other projects, first as an element of the
653 oslo_db.sqlalchemy.test_fixtures module, and secondly may be used by
654 external test suites directly.
655
656 Includes a feature to inject itself temporarily as the factory
657 within the global :class:`._TransactionContextManager`.
658
659 """
660
661 @debtcollector.removals.removed_kwarg(
662 "synchronous_reader",
663 "argument value is propagated from the parent _TransactionFactory",
664 )
665 def __init__(self, engine, maker, apply_global, from_factory=None, **kw):
666 # NOTE(zzzeek): **kw needed for backwards compability
667 self._reader_engine = self._writer_engine = engine
668 self._reader_maker = self._writer_maker = maker
669 self._started = True
670
671 if from_factory is None:
672 from_factory = _context_manager._factory
673
674 self._facade_cfg = from_factory._facade_cfg
675 self._transaction_ctx_cfg = from_factory._transaction_ctx_cfg
676
677 self.synchronous_reader = self._facade_cfg["synchronous_reader"]
678
679 if apply_global:
680 self.existing_factory = _context_manager._factory
681 _context_manager._root_factory = self
682
683 def dispose_global(self):
684 _context_manager._root_factory = self.existing_factory
685
686
687 class _AbstractTransactionContext:
688 """Represent a single database transaction in progress."""
689
690 def __init__(self, factory, global_factory=None):
691 """Construct a new :class:`.TransactionContext`.
692
693 :param factory: the :class:`.TransactionFactory` which will
694 serve as a source of connectivity.
695 :param global_factory: the "global" factory which will be used
696 by the global ``_context_manager`` for new ``_TransactionContext``
697 objects created under this one. When left as None the actual
698 "global" factory is used.
699 """
700 self.factory = factory
701 self.global_factory = global_factory
702 self.mode = None
703 self.session = None
704 self.connection = None
705 self.transaction = None
706 kw = self.factory._transaction_ctx_cfg
707 self.rollback_reader_sessions = kw["rollback_reader_sessions"]
708 self.flush_on_subtransaction = kw["flush_on_subtransaction"]
709
710 @contextlib.contextmanager
711 def _add_context(self, connection, context):
712 restore_context = connection.info.get("using_context")
713 connection.info["using_context"] = context
714 yield connection
715 connection.info["using_context"] = restore_context
716
717 def _writer(self):
718 if self.mode is None:
719 self.mode = _WRITER
720 elif self.mode is _READER:
721 raise TypeError(
722 "Can't upgrade a READER transaction "
723 "to a WRITER mid-transaction"
724 )
725 elif self.mode is _ASYNC_READER:
726 raise TypeError(
727 "Can't upgrade an ASYNC_READER transaction "
728 "to a WRITER mid-transaction"
729 )
730
731 def _reader(self, allow_async=False):
732 if self.mode is None:
733 self.mode = _READER
734 elif self.mode is _ASYNC_READER and not allow_async:
735 raise TypeError(
736 "Can't upgrade an ASYNC_READER transaction "
737 "to a READER mid-transaction"
738 )
739
740 def _async_reader(self):
741 if self.mode is None:
742 self.mode = _ASYNC_READER
743
744
745 class _TransactionContext(_AbstractTransactionContext):
746 def _end_session_transaction(self, session):
747 if self.mode is _WRITER:
748 session.commit()
749 elif self.rollback_reader_sessions:
750 session.rollback()
751 # In the absence of calling session.rollback(),
752 # the next call is session.close(). This releases all
753 # objects from the session into the detached state, and
754 # releases the connection as well; the connection when returned
755 # to the pool is either rolled back in any case, or closed fully.
756
757 def _end_connection_transaction(self, transaction):
758 if self.mode is _WRITER:
759 transaction.commit()
760 else:
761 transaction.rollback()
762
763 def _produce_block(
764 self, mode, connection, savepoint, allow_async=False, context=None
765 ):
766 if mode is _WRITER:
767 self._writer()
768 elif mode is _ASYNC_READER:
769 self._async_reader()
770 else:
771 self._reader(allow_async)
772 if connection:
773 return self._connection(savepoint, context=context)
774 else:
775 return self._session(savepoint, context=context)
776
777 @contextlib.contextmanager
778 def _connection(self, savepoint=False, context=None):
779 if self.connection is None:
780 try:
781 if self.session is not None:
782 # use existing session, which is outer to us
783 self.connection = self.session.connection()
784 if savepoint:
785 with self.connection.begin_nested(), self._add_context(
786 self.connection, context
787 ):
788 yield self.connection
789 else:
790 with self._add_context(self.connection, context):
791 yield self.connection
792 else:
793 # is outermost
794 self.connection = self.factory._create_connection(
795 mode=self.mode
796 )
797 self.transaction = self.connection.begin()
798 try:
799 with self._add_context(self.connection, context):
800 yield self.connection
801 self._end_connection_transaction(self.transaction)
802 except Exception:
803 self.transaction.rollback()
804 # TODO(zzzeek) do we need save_and_reraise() here,
805 # or do newer eventlets not have issues? we are using
806 # raw "raise" in many other places in oslo.db already
807 raise
808 finally:
809 self.transaction = None
810 self.connection.close()
811 finally:
812 self.connection = None
813
814 else:
815 # use existing connection, which is outer to us
816 if savepoint:
817 with self.connection.begin_nested(), self._add_context(
818 self.connection, context
819 ):
820 yield self.connection
821 else:
822 with self._add_context(self.connection, context):
823 yield self.connection
824
825 @contextlib.contextmanager
826 def _session(self, savepoint=False, context=None):
827 if self.session is None:
828 self.session = self.factory._create_session(
829 bind=self.connection, mode=self.mode
830 )
831 try:
832 self.session.begin()
833 with self._add_context(self.session, context):
834 yield self.session
835 self._end_session_transaction(self.session)
836 except Exception:
837 with excutils.save_and_reraise_exception():
838 self.session.rollback()
839 finally:
840 self.session.close()
841 self.session = None
842 else:
843 # use existing session, which is outer to us
844 if savepoint:
845 with self.session.begin_nested():
846 with self._add_context(self.session, context):
847 yield self.session
848 else:
849 with self._add_context(self.session, context):
850 yield self.session
851 if self.flush_on_subtransaction:
852 self.session.flush()
853
854
855 class _TransactionContextTLocal(threading.local):
856 def __deepcopy__(self, memo):
857 return self
858
859 def __reduce__(self):
860 return _TransactionContextTLocal, ()
861
862
863 class _AbstractTransactionContextManager(Generic[_AllEngineSessionT]):
864 """Provide context-management and decorator patterns for transactions.
865
866 This object integrates user-defined "context" objects with the
867 :class:`._TransactionContext` class, on behalf of a
868 contained :class:`._TransactionFactory`.
869
870 """
871
872 def __init__(
873 self,
874 root=None,
875 mode=None,
876 independent=False,
877 savepoint=False,
878 connection=False,
879 replace_global_factory=None,
880 _is_global_manager=False,
881 allow_async=False,
882 ):
883
884 if root is None:
885 self._root = self
886 self._root_factory = self._create_root_factory()
887 else:
888 self._root = root
889
890 self._replace_global_factory = replace_global_factory
891 self._is_global_manager = _is_global_manager
892 self._mode = mode
893 self._independent = independent
894 self._savepoint = savepoint
895 if self._savepoint and self._independent:
896 raise TypeError(
897 "setting savepoint and independent makes no sense."
898 )
899 self._connection = connection
900 self._allow_async = allow_async
901
902 def _create_root_factory(self):
903 return _TransactionFactory()
904
905 def _create_transaction_context(self, use_factory, global_factory):
906 return _TransactionContext(use_factory, global_factory=global_factory)
907
908 @property
909 def _factory(self):
910 """The :class:`._TransactionFactory` associated with this context."""
911 return self._root._root_factory
912
913 @property
914 def is_started(self):
915 """True if this manager is already started."""
916 return self._factory.is_started
917
918 def configure(self, **kw):
919 """Apply configurational options to the factory.
920
921 This method can only be called before any specific
922 transaction-beginning methods have been called.
923
924
925 """
926 self._factory.configure(**kw)
927
928 def append_on_engine_create(self, fn):
929 """Append a listener function to _facade_cfg["on_engine_create"]"""
930 self._factory._facade_cfg["on_engine_create"].append(fn)
931
932 def get_engine(self):
933 """Return the Engine in use.
934
935 This will be based on the state being WRITER or READER.
936
937 This implies a start operation.
938
939 """
940 if self._mode is _WRITER:
941 return self._factory.get_writer_engine()
942 elif self._mode is _READER:
943 return self._factory.get_reader_engine()
944 else:
945 raise ValueError("mode should be WRITER or READER")
946
947 def get_sessionmaker(self):
948 """Return the sessionmaker in use.
949
950 This will be based on the state being WRITER or READER.
951
952 This implies a start operation.
953
954 """
955 if self._mode is _WRITER:
956 return self._factory.get_writer_maker()
957 elif self._mode is _READER:
958 return self._factory.get_reader_maker()
959 else:
960 raise ValueError("mode should be WRITER or READER")
961
962 def dispose_pool(self):
963 """Call engine.pool.dispose() on underlying Engine objects."""
964 self._factory.dispose_pool()
965
966 def make_new_manager(self):
967 """Create a new, independent _TransactionContextManager from this one.
968
969 Copies the underlying _TransactionFactory to a new one, so that
970 it can be further configured with new options.
971
972 Used for test environments where the application-wide
973 _TransactionContextManager may be used as a factory for test-local
974 managers.
975
976 """
977 new = self._clone()
978 new._root = new
979 new._root_factory = self._root_factory._create_factory_copy()
980 if new._factory._started:
981 raise AssertionError("TransactionFactory is already started")
982 return new
983
984 def patch_factory(self, factory_or_manager):
985 """Patch a _TransactionFactory into this manager.
986
987 Replaces this manager's factory with the given one, and returns
988 a callable that will reset the factory back to what we
989 started with.
990
991 Only works for root factories. Is intended for test suites
992 that need to patch in alternate database configurations.
993
994 The given argument may be a _TransactionContextManager or a
995 _TransactionFactory.
996
997 """
998
999 if isinstance(factory_or_manager, _TransactionContextManager):
1000 factory = factory_or_manager._factory
1001 elif isinstance(factory_or_manager, _TransactionFactory):
1002 factory = factory_or_manager
1003 else:
1004 raise ValueError(
1005 "_TransactionContextManager or "
1006 "_TransactionFactory expected."
1007 )
1008 if self._root is not self:
1009 raise AssertionError("patch_factory only works for root factory.")
1010 existing_factory = self._root_factory
1011 self._root_factory = factory
1012
1013 def reset():
1014 self._root_factory = existing_factory
1015
1016 return reset
1017
1018 def patch_engine(self, engine):
1019 """Patch an Engine into this manager.
1020
1021 Replaces this manager's factory with a _TestTransactionFactory
1022 that will use the given Engine, and returns
1023 a callable that will reset the factory back to what we
1024 started with.
1025
1026 Only works for root factories. Is intended for test suites
1027 that need to patch in alternate database configurations.
1028
1029 """
1030
1031 existing_factory = self._factory
1032 if not existing_factory._started:
1033 existing_factory._start()
1034 maker = existing_factory._writer_maker
1035 maker_kwargs = existing_factory._maker_args_for_conf(cfg.CONF)
1036 maker = orm.get_maker(engine=engine, **maker_kwargs)
1037
1038 factory = _TestTransactionFactory(
1039 engine, maker, apply_global=False, from_factory=existing_factory
1040 )
1041 return self.patch_factory(factory)
1042
1043 @property
1044 def replace(self) -> Self:
1045 """Modifier to replace the global transaction factory with this one."""
1046 return self._clone(replace_global_factory=self._factory)
1047
1048 @property
1049 def writer(self) -> Self:
1050 """Modifier to set the transaction to WRITER."""
1051 return self._clone(mode=_WRITER)
1052
1053 @property
1054 def reader(self) -> Self:
1055 """Modifier to set the transaction to READER."""
1056 return self._clone(mode=_READER)
1057
1058 @property
1059 def allow_async(self) -> Self:
1060 """Modifier to allow async operations
1061
1062 Allows async operations if asynchronous session is already
1063 started in this context. Marking DB API methods with READER would make
1064 it impossible to use them in ASYNC_READER transactions, and marking
1065 them with ASYNC_READER would require a modification of all the places
1066 these DB API methods are called to force READER mode, where the latest
1067 DB state is required.
1068
1069 In Nova DB API methods should have a 'safe' default (i.e. READER),
1070 so that they can start sessions on their own, but it would also be
1071 useful for them to be able to participate in an existing ASYNC_READER
1072 session, if one was started up the stack.
1073 """
1074
1075 if self._mode is _WRITER:
1076 raise TypeError("Setting async on a WRITER makes no sense")
1077 return self._clone(allow_async=True)
1078
1079 @property
1080 def independent(self) -> Self:
1081 """Modifier to start a transaction independent from any enclosing."""
1082 return self._clone(independent=True)
1083
1084 @property
1085 def savepoint(self) -> Self:
1086 """Modifier to start a SAVEPOINT if a transaction already exists."""
1087 return self._clone(savepoint=True)
1088
1089 @property
1090 def async_(self) -> Self:
1091 """Modifier to set a READER operation to ASYNC_READER."""
1092
1093 if self._mode is _WRITER:
1094 raise TypeError("Setting async on a WRITER makes no sense")
1095 return self._clone(mode=_ASYNC_READER)
1096
1097 def _clone(self, **kw) -> Any:
1098 default_kw = {
1099 "independent": self._independent,
1100 "mode": self._mode,
1101 "connection": self._connection,
1102 }
1103 default_kw.update(kw)
1104 return self.__class__(root=self._root, **default_kw)
1105
1106 def _transaction_scope_impl(self, transaction_contexts_concurrent) -> Any:
1107
1108 new_transaction = self._independent
1109
1110 current = restore = getattr(
1111 transaction_contexts_concurrent, "current", None
1112 )
1113
1114 use_factory = self._factory
1115 global_factory = None
1116
1117 if self._replace_global_factory:
1118 use_factory = global_factory = self._replace_global_factory
1119 elif current is not None and current.global_factory:
1120 global_factory = current.global_factory
1121
1122 if self._root._is_global_manager:
1123 use_factory = global_factory
1124
1125 if current is not None and (
1126 new_transaction or current.factory is not use_factory
1127 ):
1128 current = None
1129
1130 if current is None:
1131 current = transaction_contexts_concurrent.current = (
1132 self._create_transaction_context(
1133 use_factory, global_factory=global_factory
1134 )
1135 )
1136
1137 return current, restore
1138
1139
1140 class _TransactionContextManager(
1141 _AbstractTransactionContextManager[_SyncEngineSessionT]
1142 ):
1143 def __call__(self, fn):
1144 """Decorate a function."""
1145 argspec = inspect.getfullargspec(fn)
1146 if argspec.args[0] == "self" or argspec.args[0] == "cls":
1147 context_index = 1
1148 else:
1149 context_index = 0
1150 context_kw = argspec.args[context_index]
1151
1152 @functools.wraps(fn)
1153 def wrapper(*args, **kwargs):
1154 context = kwargs.get(context_kw, None)
1155 if not context:
1156 context = args[context_index]
1157
1158 with self._transaction_scope(context):
1159 return fn(*args, **kwargs)
1160
1161 return wrapper
1162
1163 @contextlib.contextmanager
1164 def _transaction_scope(self, context) -> Any:
1165 transaction_contexts_by_thread = _transaction_contexts_by_thread(
1166 context
1167 )
1168
1169 current, restore = self._transaction_scope_impl(
1170 transaction_contexts_by_thread
1171 )
1172
1173 try:
1174 if self._mode is not None:
1175 with current._produce_block(
1176 mode=self._mode,
1177 connection=self._connection,
1178 savepoint=self._savepoint,
1179 allow_async=self._allow_async,
1180 context=context,
1181 ) as resource:
1182 yield resource
1183 else:
1184 yield
1185 finally:
1186 if restore is None:
1187 del transaction_contexts_by_thread.current
1188 elif current is not restore:
1189 transaction_contexts_by_thread.current = restore
1190
1191 @property
1192 def connection(self) -> _TransactionContextManager[Connection]:
1193 """Modifier to return a core Connection object instead of Session."""
1194 return self._clone(connection=True)
1195
1196 def using(self, context) -> ContextManager[_SyncEngineSessionT]:
1197 """Provide a context manager block that will use the given context."""
1198 return self._transaction_scope(context)
1199
1200
1201 def _context_descriptor(
1202 attr=None, transaction_ctx_getter=operator.attrgetter("transaction_ctx")
1203 ):
1204 getter = operator.attrgetter(attr)
1205
1206 def _property_for_context(context):
1207 try:
1208 transaction_context = transaction_ctx_getter(context)
1209 except exception.NoEngineContextEstablished:
1210 raise exception.NoEngineContextEstablished(
1211 "No TransactionContext is established for "
1212 "this %s object within the current thread; "
1213 "the %r attribute is unavailable. "
1214 "Ensure this Context class participates in the "
1215 "transaction_context_provider() class decorator."
1216 % (context, attr)
1217 )
1218 else:
1219 result = getter(transaction_context)
1220 if result is None:
1221 raise exception.ContextNotRequestedError(
1222 "The '%s' context attribute was requested but "
1223 "it has not been established for this context." % attr
1224 )
1225 return result
1226
1227 return property(_property_for_context)
1228
1229
1230 def _transaction_ctx_for_context(context):
1231 by_thread = _transaction_contexts_by_thread(context)
1232 try:
1233 return by_thread.current
1234 except AttributeError:
1235 raise exception.NoEngineContextEstablished(
1236 "No TransactionContext is established for "
1237 "this %s object within the current thread. "
1238 "Ensure this Context class participates in the "
1239 "transaction_context_provider() class decorator." % context
1240 )
1241
1242
1243 def _transaction_contexts_by_thread(context):
1244 transaction_contexts_by_thread = getattr(
1245 context, "_enginefacade_context", None
1246 )
1247 if transaction_contexts_by_thread is None:
1248 transaction_contexts_by_thread = context._enginefacade_context = (
1249 _TransactionContextTLocal()
1250 )
1251
1252 return transaction_contexts_by_thread
1253
1254
1255 def transaction_context_provider(klass):
1256 """Decorate a class with ``session`` and ``connection`` attributes."""
1257
1258 setattr(klass, "transaction_ctx", property(_transaction_ctx_for_context))
1259
1260 # Graft transaction context attributes as context properties
1261 for attr in ("session", "connection", "transaction"):
1262 setattr(klass, attr, _context_descriptor(attr))
1263
1264 return klass
1265
1266
1267 _context_manager: _TransactionContextManager[Session] = (
1268 _TransactionContextManager(_is_global_manager=True)
1269 )
1270 """default context manager."""
1271
1272
1273 def transaction_context():
1274 """Construct a local transaction context."""
1275 return _TransactionContextManager()
1276
1277
1278 def configure(**kw):
1279 """Apply configurational options to the global factory.
1280
1281 This method can only be called before any specific transaction-beginning
1282 methods have been called.
1283
1284 .. seealso::
1285
1286 :meth:`._TransactionFactory.configure`
1287
1288 """
1289 _context_manager._factory.configure(**kw)
1290
1291
1292 reader = _context_manager.reader
1293 """The global 'reader' starting point."""
1294
1295
1296 writer = _context_manager.writer
1297 """The global 'writer' starting point."""