| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import asyncio |
| 15 |
from collections.abc import AsyncIterator |
| 16 |
import contextlib |
| 17 |
import contextvars |
| 18 |
import functools |
| 19 |
import inspect |
| 20 |
import itertools |
| 21 |
import logging |
| 22 |
import operator |
| 23 |
from typing import AsyncContextManager |
| 24 |
from typing import TYPE_CHECKING |
| 25 |
from typing import TypeVar |
| 26 |
from typing import Union |
| 27 |
|
| 28 |
from oslo_db import exception |
| 29 |
from oslo_db.sqlalchemy import engines |
| 30 |
from oslo_utils import excutils |
| 31 |
from sqlalchemy.ext.asyncio import async_sessionmaker |
| 32 |
from sqlalchemy.ext.asyncio import AsyncEngine |
| 33 |
from sqlalchemy.ext.asyncio import create_async_engine |
| 34 |
from sqlalchemy.util.concurrency import await_only |
| 35 |
from sqlalchemy.util.concurrency import greenlet_spawn |
| 36 |
|
| 37 |
from . import enginefacade as _sync_facade |
| 38 |
from .enginefacade import _AbstractTransactionContext |
| 39 |
from .enginefacade import _AbstractTransactionContextManager |
| 40 |
from .enginefacade import _AbstractTransactionFactory |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from sqlalchemy.ext.asyncio import AsyncConnection |
| 44 |
from sqlalchemy.ext.asyncio import AsyncSession |
| 45 |
|
| 46 |
_AES = TypeVar("_AES", bound=Union["AsyncConnection", "AsyncSession", None]) |
| 47 |
|
| 48 |
LOG = logging.getLogger(__name__) |
| 49 |
|
| 50 |
|
| 51 |
def _create_async_engine(url, **engine_args): |
| 52 |
async_engine = create_async_engine(url, **engine_args) |
| 53 |
return async_engine, async_engine.engine |
| 54 |
|
| 55 |
|
| 56 |
def _test_async_connection(engine, max_retries, retry_interval): |
| 57 |
if max_retries == -1: |
| 58 |
attempts = itertools.count() |
| 59 |
else: |
| 60 |
attempts = range(max_retries) |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
de_ref = None |
| 65 |
for attempt in attempts: |
| 66 |
try: |
| 67 |
conn = engine.connect() |
| 68 |
except exception.DBConnectionError as de: |
| 69 |
msg = "SQL async connection failed. %s attempts left." |
| 70 |
LOG.warning(msg, max_retries - attempt) |
| 71 |
await_only(asyncio.sleep(retry_interval)) |
| 72 |
de_ref = de |
| 73 |
else: |
| 74 |
conn.close() |
| 75 |
else: |
| 76 |
if de_ref is not None: |
| 77 |
raise de_ref |
| 78 |
|
| 79 |
|
| 80 |
class _GreenletAdaptedLock: |
| 81 |
def __init__(self): |
| 82 |
self._lock = asyncio.Lock() |
| 83 |
|
| 84 |
def __enter__(self): |
| 85 |
await_only(self._lock.acquire()) |
| 86 |
|
| 87 |
def __exit__(self, *arg, **kw): |
| 88 |
self._lock.release() |
| 89 |
|
| 90 |
|
| 91 |
class _AsyncioTransactionFactory(_AbstractTransactionFactory): |
| 92 |
"""A factory for :class:`._AsyncioTransactionContext` objects. |
| 93 |
|
| 94 |
By default, there is just one of these, set up |
| 95 |
based on CONF, however instance-level :class:`._TransactionFactory` |
| 96 |
objects can be made, as is the case with the |
| 97 |
:class:`._TestTransactionFactory` subclass used by the oslo.db test suite. |
| 98 |
""" |
| 99 |
|
| 100 |
_start_lock: _GreenletAdaptedLock |
| 101 |
|
| 102 |
_writer_engine: AsyncEngine |
| 103 |
_reader_engine: AsyncEngine |
| 104 |
_writer_maker: async_sessionmaker |
| 105 |
_reader_maker: async_sessionmaker |
| 106 |
|
| 107 |
def _make_lock(self): |
| 108 |
return _GreenletAdaptedLock() |
| 109 |
|
| 110 |
if TYPE_CHECKING: |
| 111 |
|
| 112 |
def get_writer_engine(self) -> AsyncEngine: |
| 113 |
"""Return the writer engine for this factory. |
| 114 |
|
| 115 |
Implies start. |
| 116 |
""" |
| 117 |
... |
| 118 |
|
| 119 |
def get_reader_engine(self) -> AsyncEngine: |
| 120 |
"""Return the reader engine for this factory. |
| 121 |
|
| 122 |
Implies start. |
| 123 |
""" |
| 124 |
... |
| 125 |
|
| 126 |
def get_writer_maker(self) -> async_sessionmaker: |
| 127 |
"""Return the writer sessionmaker for this factory. |
| 128 |
|
| 129 |
Implies start. |
| 130 |
""" |
| 131 |
... |
| 132 |
|
| 133 |
def get_reader_maker(self) -> async_sessionmaker: |
| 134 |
"""Return the reader sessionmaker for this factory. |
| 135 |
|
| 136 |
Implies start. |
| 137 |
""" |
| 138 |
... |
| 139 |
|
| 140 |
async def dispose_pool_async(self): |
| 141 |
"""Call engine.dispose() on underlying AsyncEngine objects.""" |
| 142 |
|
| 143 |
async with self._start_lock._lock: |
| 144 |
if not self._started: |
| 145 |
return |
| 146 |
|
| 147 |
await self._writer_engine.dispose() |
| 148 |
if self._reader_engine is not self._writer_engine: |
| 149 |
await self._reader_engine.dispose() |
| 150 |
|
| 151 |
def _setup_for_connection( |
| 152 |
self, |
| 153 |
sql_connection, |
| 154 |
engine_kwargs, |
| 155 |
maker_kwargs, |
| 156 |
): |
| 157 |
if sql_connection is None: |
| 158 |
raise exception.CantStartEngineError( |
| 159 |
"No async sql_connection parameter is established" |
| 160 |
) |
| 161 |
|
| 162 |
engine = engines.create_engine( |
| 163 |
sql_connection=sql_connection, |
| 164 |
_engine_target=_create_async_engine, |
| 165 |
_test_connection=_test_async_connection, |
| 166 |
**engine_kwargs, |
| 167 |
) |
| 168 |
for hook in self._facade_cfg["on_engine_create"]: |
| 169 |
hook(engine) |
| 170 |
sessionmaker = async_sessionmaker(bind=engine, **maker_kwargs) |
| 171 |
return engine, sessionmaker |
| 172 |
|
| 173 |
async def _create_async_connection(self, mode): |
| 174 |
if not self._started: |
| 175 |
await greenlet_spawn(self._start) |
| 176 |
if mode is _sync_facade._WRITER: |
| 177 |
return await self._writer_engine.connect() |
| 178 |
elif mode is _sync_facade._ASYNC_READER or ( |
| 179 |
mode is _sync_facade._READER and not self.synchronous_reader |
| 180 |
): |
| 181 |
return await self._reader_engine.connect() |
| 182 |
else: |
| 183 |
return await self._writer_engine.connect() |
| 184 |
|
| 185 |
async def _create_async_session(self, mode, bind=None): |
| 186 |
if not self._started: |
| 187 |
await greenlet_spawn(self._start) |
| 188 |
kw = {} |
| 189 |
|
| 190 |
|
| 191 |
if bind: |
| 192 |
kw["bind"] = bind |
| 193 |
if mode is _sync_facade._WRITER: |
| 194 |
return self._writer_maker(**kw) |
| 195 |
elif mode is _sync_facade._ASYNC_READER or ( |
| 196 |
mode is _sync_facade._READER and not self.synchronous_reader |
| 197 |
): |
| 198 |
return self._reader_maker(**kw) |
| 199 |
else: |
| 200 |
return self._writer_maker(**kw) |
| 201 |
|
| 202 |
|
| 203 |
class _TransactionContextContextVar: |
| 204 |
__slots__ = ("_context_vars",) |
| 205 |
|
| 206 |
def __init__(self): |
| 207 |
object.__setattr__(self, "_context_vars", {}) |
| 208 |
|
| 209 |
def _get_context_var(self, key): |
| 210 |
if key not in self._context_vars: |
| 211 |
self._context_vars[key] = var = contextvars.ContextVar(key) |
| 212 |
else: |
| 213 |
var = self._context_vars[key] |
| 214 |
return var |
| 215 |
|
| 216 |
def __getattr__(self, key): |
| 217 |
context_var = self._get_context_var(key) |
| 218 |
try: |
| 219 |
return context_var.get() |
| 220 |
except LookupError as le: |
| 221 |
raise AttributeError(key) from le |
| 222 |
|
| 223 |
def __setattr__(self, key, value): |
| 224 |
context_var = self._get_context_var(key) |
| 225 |
context_var.set(value) |
| 226 |
|
| 227 |
def __delattr__(self, key): |
| 228 |
context_var = self._get_context_var(key) |
| 229 |
context_var.set(None) |
| 230 |
|
| 231 |
def __deepcopy__(self, memo): |
| 232 |
return self |
| 233 |
|
| 234 |
def __reduce__(self): |
| 235 |
return _TransactionContextContextVar, () |
| 236 |
|
| 237 |
|
| 238 |
def _async_transaction_ctx_for_context(context): |
| 239 |
by_coroutine = _transaction_contexts_by_coroutine(context) |
| 240 |
try: |
| 241 |
return by_coroutine.current |
| 242 |
except AttributeError: |
| 243 |
raise exception.NoEngineContextEstablished( |
| 244 |
"No AsyncTransactionContext is established for " |
| 245 |
f"this {context} object within the current thread. " |
| 246 |
"Ensure this Context class participates in the " |
| 247 |
"async_transaction_context_provider() class decorator." |
| 248 |
) |
| 249 |
|
| 250 |
|
| 251 |
def _transaction_contexts_by_coroutine(context): |
| 252 |
transaction_contexts_by_coroutine = getattr( |
| 253 |
context, "_asyncio_facade_context", None |
| 254 |
) |
| 255 |
if transaction_contexts_by_coroutine is None: |
| 256 |
transaction_contexts_by_coroutine = context._asyncio_facade_context = ( |
| 257 |
_TransactionContextContextVar() |
| 258 |
) |
| 259 |
|
| 260 |
return transaction_contexts_by_coroutine |
| 261 |
|
| 262 |
|
| 263 |
class _AsyncTransactionContextManager( |
| 264 |
_AbstractTransactionContextManager[_AES] |
| 265 |
): |
| 266 |
|
| 267 |
def using(self, context) -> AsyncContextManager[_AES]: |
| 268 |
"""Provide a context manager block that will use the given context.""" |
| 269 |
return self._async_transaction_scope(context) |
| 270 |
|
| 271 |
@property |
| 272 |
def connection(self) -> _AsyncTransactionContextManager[AsyncConnection]: |
| 273 |
"""Modifier to return a core Connection object instead of Session.""" |
| 274 |
return self._clone(connection=True) |
| 275 |
|
| 276 |
def __call__(self, fn): |
| 277 |
"""Decorate an awaitable function.""" |
| 278 |
argspec = inspect.getfullargspec(fn) |
| 279 |
if argspec.args[0] == "self" or argspec.args[0] == "cls": |
| 280 |
context_index = 1 |
| 281 |
else: |
| 282 |
context_index = 0 |
| 283 |
context_kw = argspec.args[context_index] |
| 284 |
|
| 285 |
@functools.wraps(fn) |
| 286 |
async def wrapper(*args, **kwargs): |
| 287 |
context = kwargs.get(context_kw, None) |
| 288 |
if not context: |
| 289 |
context = args[context_index] |
| 290 |
|
| 291 |
async with self._async_transaction_scope(context): |
| 292 |
return await fn(*args, **kwargs) |
| 293 |
|
| 294 |
return wrapper |
| 295 |
|
| 296 |
@contextlib.asynccontextmanager |
| 297 |
async def _async_transaction_scope(self, context) -> AsyncIterator[_AES]: |
| 298 |
transaction_contexts_by_coroutine = _transaction_contexts_by_coroutine( |
| 299 |
context |
| 300 |
) |
| 301 |
|
| 302 |
current, restore = self._transaction_scope_impl( |
| 303 |
transaction_contexts_by_coroutine |
| 304 |
) |
| 305 |
|
| 306 |
try: |
| 307 |
if self._mode is not None: |
| 308 |
async with current._produce_asyncio_block( |
| 309 |
mode=self._mode, |
| 310 |
connection=self._connection, |
| 311 |
savepoint=self._savepoint, |
| 312 |
allow_async=self._allow_async, |
| 313 |
context=context, |
| 314 |
) as resource: |
| 315 |
yield resource |
| 316 |
else: |
| 317 |
yield |
| 318 |
finally: |
| 319 |
if restore is None: |
| 320 |
del transaction_contexts_by_coroutine.current |
| 321 |
elif current is not restore: |
| 322 |
transaction_contexts_by_coroutine.current = restore |
| 323 |
|
| 324 |
def _create_root_factory(self): |
| 325 |
return _AsyncioTransactionFactory() |
| 326 |
|
| 327 |
def _create_transaction_context(self, use_factory, global_factory): |
| 328 |
return _AsyncTransactionContext( |
| 329 |
use_factory, global_factory=global_factory |
| 330 |
) |
| 331 |
|
| 332 |
|
| 333 |
class _AsyncTransactionContext(_AbstractTransactionContext): |
| 334 |
|
| 335 |
@property |
| 336 |
def async_connection(self): |
| 337 |
return self.connection |
| 338 |
|
| 339 |
@property |
| 340 |
def async_session(self): |
| 341 |
return self.session |
| 342 |
|
| 343 |
async def _end_async_session_transaction(self, session): |
| 344 |
if self.mode is _sync_facade._WRITER: |
| 345 |
await session.commit() |
| 346 |
elif self.rollback_reader_sessions: |
| 347 |
await session.rollback() |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
async def _end_async_connection_transaction(self, transaction): |
| 355 |
if self.mode is _sync_facade._WRITER: |
| 356 |
await transaction.commit() |
| 357 |
else: |
| 358 |
await transaction.rollback() |
| 359 |
|
| 360 |
def _produce_asyncio_block( |
| 361 |
self, mode, connection, savepoint, allow_async=False, context=None |
| 362 |
): |
| 363 |
if mode is _sync_facade._WRITER: |
| 364 |
self._writer() |
| 365 |
elif mode is _sync_facade._ASYNC_READER: |
| 366 |
self._async_reader() |
| 367 |
else: |
| 368 |
self._reader(allow_async) |
| 369 |
if connection: |
| 370 |
return self._async_connection(savepoint, context=context) |
| 371 |
else: |
| 372 |
return self._async_session(savepoint, context=context) |
| 373 |
|
| 374 |
@contextlib.asynccontextmanager |
| 375 |
async def _async_connection(self, savepoint=False, context=None): |
| 376 |
if self.connection is None: |
| 377 |
try: |
| 378 |
if self.session is not None: |
| 379 |
|
| 380 |
self.connection = await self.session.connection() |
| 381 |
if savepoint: |
| 382 |
with self.connection.begin_nested(), self._add_context( |
| 383 |
self.connection, context |
| 384 |
): |
| 385 |
yield self.connection |
| 386 |
else: |
| 387 |
with self._add_context(self.connection, context): |
| 388 |
yield self.connection |
| 389 |
else: |
| 390 |
|
| 391 |
self.connection = ( |
| 392 |
await self.factory._create_async_connection( |
| 393 |
mode=self.mode |
| 394 |
) |
| 395 |
) |
| 396 |
self.transaction = await self.connection.begin() |
| 397 |
try: |
| 398 |
with self._add_context(self.connection, context): |
| 399 |
yield self.connection |
| 400 |
await self._end_async_connection_transaction( |
| 401 |
self.transaction |
| 402 |
) |
| 403 |
except Exception: |
| 404 |
await self.transaction.rollback() |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
raise |
| 409 |
finally: |
| 410 |
self.transaction = None |
| 411 |
await self.connection.close() |
| 412 |
finally: |
| 413 |
self.connection = None |
| 414 |
|
| 415 |
else: |
| 416 |
|
| 417 |
if savepoint: |
| 418 |
async with self.connection.begin_nested(): |
| 419 |
with self._add_context(self.connection, context): |
| 420 |
yield self.connection |
| 421 |
else: |
| 422 |
with self._add_context(self.connection, context): |
| 423 |
yield self.connection |
| 424 |
|
| 425 |
@contextlib.asynccontextmanager |
| 426 |
async def _async_session(self, savepoint=False, context=None): |
| 427 |
if self.session is None: |
| 428 |
self.session = await self.factory._create_async_session( |
| 429 |
bind=self.connection, mode=self.mode |
| 430 |
) |
| 431 |
try: |
| 432 |
await self.session.begin() |
| 433 |
with self._add_context(self.session, context): |
| 434 |
yield self.session |
| 435 |
await self._end_async_session_transaction(self.session) |
| 436 |
except Exception: |
| 437 |
with excutils.save_and_reraise_exception(): |
| 438 |
await self.session.rollback() |
| 439 |
finally: |
| 440 |
await self.session.close() |
| 441 |
self.session = None |
| 442 |
else: |
| 443 |
|
| 444 |
if savepoint: |
| 445 |
async with self.session.begin_nested(): |
| 446 |
with self._add_context(self.session, context): |
| 447 |
yield self.session |
| 448 |
else: |
| 449 |
with self._add_context(self.session, context): |
| 450 |
yield self.session |
| 451 |
if self.flush_on_subtransaction: |
| 452 |
await self.session.flush() |
| 453 |
|
| 454 |
|
| 455 |
def configure(**kw): |
| 456 |
"""Apply configurational options to the global factory. |
| 457 |
|
| 458 |
This method can only be called before any specific transaction-beginning |
| 459 |
methods have been called. |
| 460 |
|
| 461 |
.. seealso:: |
| 462 |
|
| 463 |
:meth:`._TransactionFactory.configure` |
| 464 |
|
| 465 |
""" |
| 466 |
_async_context_manager._factory.configure(**kw) |
| 467 |
|
| 468 |
|
| 469 |
def async_transaction_context_provider(klass): |
| 470 |
"""Decorate a class with ``session`` and ``connection`` attributes.""" |
| 471 |
|
| 472 |
setattr( |
| 473 |
klass, |
| 474 |
"async_transaction_ctx", |
| 475 |
property(_async_transaction_ctx_for_context), |
| 476 |
) |
| 477 |
|
| 478 |
|
| 479 |
for attr in ("async_session", "async_connection", "async_transaction"): |
| 480 |
setattr( |
| 481 |
klass, |
| 482 |
attr, |
| 483 |
_sync_facade._context_descriptor( |
| 484 |
attr, |
| 485 |
transaction_ctx_getter=operator.attrgetter( |
| 486 |
"async_transaction_ctx" |
| 487 |
), |
| 488 |
), |
| 489 |
) |
| 490 |
|
| 491 |
return klass |
| 492 |
|
| 493 |
|
| 494 |
_async_context_manager: _AsyncTransactionContextManager[AsyncSession] = ( |
| 495 |
_AsyncTransactionContextManager(_is_global_manager=True) |
| 496 |
) |
| 497 |
"""default context manager.""" |
| 498 |
|
| 499 |
|
| 500 |
def transaction_context(): |
| 501 |
"""Construct a local transaction context.""" |
| 502 |
return _AsyncTransactionContextManager() |
| 503 |
|
| 504 |
|
| 505 |
reader = _async_context_manager.reader |
| 506 |
"""The global 'reader' starting point.""" |
| 507 |
|
| 508 |
|
| 509 |
writer = _async_context_manager.writer |
| 510 |
"""The global 'writer' starting point.""" |