| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
"""Core SQLAlchemy connectivity routines. |
| 17 |
""" |
| 18 |
|
| 19 |
import itertools |
| 20 |
import logging |
| 21 |
import os |
| 22 |
import re |
| 23 |
import time |
| 24 |
|
| 25 |
import debtcollector.removals |
| 26 |
import debtcollector.renames |
| 27 |
import sqlalchemy |
| 28 |
from sqlalchemy import exc |
| 29 |
from sqlalchemy import pool |
| 30 |
|
| 31 |
from oslo_db import exception |
| 32 |
|
| 33 |
from oslo_db.sqlalchemy import exc_filters |
| 34 |
from oslo_db.sqlalchemy import utils |
| 35 |
|
| 36 |
LOG = logging.getLogger(__name__) |
| 37 |
|
| 38 |
|
| 39 |
def _thread_yield(dbapi_con, con_record): |
| 40 |
"""Ensure other greenthreads get a chance to be executed. |
| 41 |
|
| 42 |
If we use eventlet.monkey_patch(), eventlet.greenthread.sleep(0) will |
| 43 |
execute instead of time.sleep(0). |
| 44 |
Force a context switch. With common database backends (eg MySQLdb and |
| 45 |
sqlite), there is no implicit yield caused by network I/O since they are |
| 46 |
implemented by C libraries that eventlet cannot monkey patch. |
| 47 |
""" |
| 48 |
time.sleep(0) |
| 49 |
|
| 50 |
|
| 51 |
def _setup_logging(connection_debug=0): |
| 52 |
"""setup_logging function maps SQL debug level to Python log level. |
| 53 |
|
| 54 |
Connection_debug is a verbosity of SQL debugging information. |
| 55 |
0=None(default value), |
| 56 |
1=Processed only messages with WARNING level or higher |
| 57 |
50=Processed only messages with INFO level or higher |
| 58 |
100=Processed only messages with DEBUG level |
| 59 |
""" |
| 60 |
if connection_debug >= 0: |
| 61 |
logger = logging.getLogger("sqlalchemy.engine") |
| 62 |
if connection_debug == 100: |
| 63 |
logger.setLevel(logging.DEBUG) |
| 64 |
elif connection_debug >= 50: |
| 65 |
logger.setLevel(logging.INFO) |
| 66 |
else: |
| 67 |
logger.setLevel(logging.WARNING) |
| 68 |
|
| 69 |
|
| 70 |
def _vet_url(url): |
| 71 |
if "+" not in url.drivername and not url.drivername.startswith("sqlite"): |
| 72 |
if url.drivername.startswith("mysql"): |
| 73 |
LOG.warning( |
| 74 |
"URL %r does not contain a '+drivername' portion, " |
| 75 |
"and will make use of a default driver. " |
| 76 |
"A full dbname+drivername:// protocol is recommended. " |
| 77 |
"For MySQL, it is strongly recommended that mysql+pymysql:// " |
| 78 |
"be specified for maximum service compatibility", |
| 79 |
url, |
| 80 |
) |
| 81 |
else: |
| 82 |
LOG.warning( |
| 83 |
"URL %r does not contain a '+drivername' portion, " |
| 84 |
"and will make use of a default driver. " |
| 85 |
"A full dbname+drivername:// protocol is recommended.", |
| 86 |
url, |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
def _create_engine(url, **engine_args): |
| 91 |
engine = sqlalchemy.create_engine(url, **engine_args) |
| 92 |
return engine, engine |
| 93 |
|
| 94 |
|
| 95 |
def _test_connection(engine, max_retries, retry_interval, _close=True): |
| 96 |
if max_retries == -1: |
| 97 |
attempts = itertools.count() |
| 98 |
else: |
| 99 |
attempts = range(max_retries) |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
de_ref = conn = None |
| 104 |
for attempt in attempts: |
| 105 |
try: |
| 106 |
conn = engine.connect() |
| 107 |
except exception.DBConnectionError as de: |
| 108 |
msg = "SQL connection failed. %s attempts left." |
| 109 |
LOG.warning(msg, max_retries - attempt) |
| 110 |
time.sleep(retry_interval) |
| 111 |
de_ref = de |
| 112 |
else: |
| 113 |
if _close: |
| 114 |
conn.close() |
| 115 |
break |
| 116 |
else: |
| 117 |
if de_ref is not None: |
| 118 |
raise de_ref |
| 119 |
|
| 120 |
return conn |
| 121 |
|
| 122 |
|
| 123 |
@debtcollector.renames.renamed_kwarg( |
| 124 |
"idle_timeout", |
| 125 |
"connection_recycle_time", |
| 126 |
replace=True, |
| 127 |
) |
| 128 |
def create_engine( |
| 129 |
sql_connection, |
| 130 |
sqlite_fk=False, |
| 131 |
mysql_sql_mode=None, |
| 132 |
mysql_wsrep_sync_wait=None, |
| 133 |
connection_recycle_time=3600, |
| 134 |
connection_debug=0, |
| 135 |
max_pool_size=None, |
| 136 |
max_overflow=None, |
| 137 |
pool_timeout=None, |
| 138 |
sqlite_synchronous=True, |
| 139 |
connection_trace=False, |
| 140 |
max_retries=10, |
| 141 |
retry_interval=10, |
| 142 |
thread_checkin=True, |
| 143 |
logging_name=None, |
| 144 |
json_serializer=None, |
| 145 |
json_deserializer=None, |
| 146 |
connection_parameters=None, |
| 147 |
_engine_target=_create_engine, |
| 148 |
_test_connection=_test_connection, |
| 149 |
): |
| 150 |
"""Return a new SQLAlchemy engine.""" |
| 151 |
|
| 152 |
url = utils.make_url(sql_connection) |
| 153 |
|
| 154 |
if connection_parameters: |
| 155 |
url = url.update_query_string(connection_parameters, append=True) |
| 156 |
|
| 157 |
_vet_url(url) |
| 158 |
|
| 159 |
engine_args = { |
| 160 |
"pool_recycle": connection_recycle_time, |
| 161 |
"pool_pre_ping": True, |
| 162 |
"connect_args": {}, |
| 163 |
"logging_name": logging_name, |
| 164 |
} |
| 165 |
|
| 166 |
_setup_logging(connection_debug) |
| 167 |
|
| 168 |
_init_connection_args( |
| 169 |
url, |
| 170 |
engine_args, |
| 171 |
dict( |
| 172 |
max_pool_size=max_pool_size, |
| 173 |
max_overflow=max_overflow, |
| 174 |
pool_timeout=pool_timeout, |
| 175 |
json_serializer=json_serializer, |
| 176 |
json_deserializer=json_deserializer, |
| 177 |
), |
| 178 |
) |
| 179 |
|
| 180 |
engine, engine_event_target = _engine_target(url, **engine_args) |
| 181 |
|
| 182 |
_init_events( |
| 183 |
engine_event_target, |
| 184 |
mysql_sql_mode=mysql_sql_mode, |
| 185 |
mysql_wsrep_sync_wait=mysql_wsrep_sync_wait, |
| 186 |
sqlite_synchronous=sqlite_synchronous, |
| 187 |
sqlite_fk=sqlite_fk, |
| 188 |
thread_checkin=thread_checkin, |
| 189 |
connection_trace=connection_trace, |
| 190 |
) |
| 191 |
|
| 192 |
|
| 193 |
exc_filters.register_engine(engine_event_target) |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
if max_retries: |
| 199 |
_test_connection(engine_event_target, max_retries, retry_interval) |
| 200 |
|
| 201 |
return engine |
| 202 |
|
| 203 |
|
| 204 |
@utils.dispatch_for_dialect("*", multiple=True) |
| 205 |
def _init_connection_args(url, engine_args, kw): |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
max_pool_size = kw.get("max_pool_size", None) |
| 213 |
max_overflow = kw.get("max_overflow", None) |
| 214 |
pool_timeout = kw.get("pool_timeout", None) |
| 215 |
|
| 216 |
pool_class = url.get_dialect().get_pool_class(url) |
| 217 |
if issubclass(pool_class, pool.QueuePool): |
| 218 |
if max_pool_size is not None: |
| 219 |
engine_args["pool_size"] = max_pool_size |
| 220 |
if max_overflow is not None: |
| 221 |
engine_args["max_overflow"] = max_overflow |
| 222 |
if pool_timeout is not None: |
| 223 |
engine_args["pool_timeout"] = pool_timeout |
| 224 |
|
| 225 |
|
| 226 |
@_init_connection_args.dispatch_for("sqlite") |
| 227 |
def _init_connection_args(url, engine_args, kw): |
| 228 |
pool_class = url.get_dialect().get_pool_class(url) |
| 229 |
if issubclass(pool_class, pool.SingletonThreadPool): |
| 230 |
|
| 231 |
|
| 232 |
engine_args["poolclass"] = pool.StaticPool |
| 233 |
engine_args["connect_args"]["check_same_thread"] = False |
| 234 |
|
| 235 |
engine_args["connect_args"]["cached_statements"] = 0 |
| 236 |
elif issubclass(pool_class, pool.QueuePool): |
| 237 |
|
| 238 |
|
| 239 |
kw.pop("max_pool_size", None) |
| 240 |
kw.pop("max_overflow", None) |
| 241 |
engine_args.pop("max_pool_size", None) |
| 242 |
engine_args.pop("max_overflow", None) |
| 243 |
engine_args["poolclass"] = pool.NullPool |
| 244 |
|
| 245 |
|
| 246 |
@_init_connection_args.dispatch_for("postgresql") |
| 247 |
def _init_connection_args(url, engine_args, kw): |
| 248 |
if "client_encoding" not in url.query: |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
engine_args["client_encoding"] = "utf8" |
| 253 |
engine_args["json_serializer"] = kw.get("json_serializer") |
| 254 |
engine_args["json_deserializer"] = kw.get("json_deserializer") |
| 255 |
|
| 256 |
|
| 257 |
@_init_connection_args.dispatch_for("mysql") |
| 258 |
def _init_connection_args(url, engine_args, kw): |
| 259 |
if "charset" not in url.query: |
| 260 |
engine_args["connect_args"]["charset"] = "utf8" |
| 261 |
|
| 262 |
|
| 263 |
@_init_connection_args.dispatch_for("mysql+mysqlconnector") |
| 264 |
def _init_connection_args(url, engine_args, kw): |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
if "raise_on_warnings" not in url.query: |
| 269 |
engine_args["connect_args"]["raise_on_warnings"] = False |
| 270 |
|
| 271 |
|
| 272 |
@_init_connection_args.dispatch_for("mysql+mysqldb") |
| 273 |
def _init_connection_args(url, engine_args, kw): |
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
if "use_unicode" not in url.query: |
| 278 |
engine_args["connect_args"]["use_unicode"] = 1 |
| 279 |
|
| 280 |
|
| 281 |
@utils.dispatch_for_dialect("*", multiple=True) |
| 282 |
def _init_events(engine, thread_checkin=True, connection_trace=False, **kw): |
| 283 |
"""Set up event listeners for all database backends.""" |
| 284 |
|
| 285 |
_add_process_guards(engine) |
| 286 |
|
| 287 |
if connection_trace: |
| 288 |
_add_trace_comments(engine) |
| 289 |
|
| 290 |
if thread_checkin: |
| 291 |
sqlalchemy.event.listen(engine, "checkin", _thread_yield) |
| 292 |
|
| 293 |
|
| 294 |
@_init_events.dispatch_for("mysql") |
| 295 |
def _init_events( |
| 296 |
engine, mysql_sql_mode=None, mysql_wsrep_sync_wait=None, **kw |
| 297 |
): |
| 298 |
"""Set up event listeners for MySQL.""" |
| 299 |
|
| 300 |
if mysql_sql_mode is not None or mysql_wsrep_sync_wait is not None: |
| 301 |
|
| 302 |
@sqlalchemy.event.listens_for(engine, "connect") |
| 303 |
def _set_session_variables(dbapi_con, connection_rec): |
| 304 |
cursor = dbapi_con.cursor() |
| 305 |
if mysql_sql_mode is not None: |
| 306 |
cursor.execute("SET SESSION sql_mode = %s", [mysql_sql_mode]) |
| 307 |
if mysql_wsrep_sync_wait is not None: |
| 308 |
cursor.execute( |
| 309 |
"SET SESSION wsrep_sync_wait = %s", [mysql_wsrep_sync_wait] |
| 310 |
) |
| 311 |
|
| 312 |
@sqlalchemy.event.listens_for(engine, "first_connect") |
| 313 |
def _check_effective_sql_mode(dbapi_con, connection_rec): |
| 314 |
if mysql_sql_mode is not None or mysql_wsrep_sync_wait is not None: |
| 315 |
_set_session_variables(dbapi_con, connection_rec) |
| 316 |
|
| 317 |
cursor = dbapi_con.cursor() |
| 318 |
cursor.execute("SHOW VARIABLES LIKE 'sql_mode'") |
| 319 |
realmode = cursor.fetchone() |
| 320 |
|
| 321 |
if realmode is None: |
| 322 |
LOG.warning("Unable to detect effective SQL mode") |
| 323 |
else: |
| 324 |
realmode = realmode[1] |
| 325 |
LOG.debug("MySQL server mode set to %s", realmode) |
| 326 |
if ( |
| 327 |
"TRADITIONAL" not in realmode.upper() and |
| 328 |
"STRICT_ALL_TABLES" not in realmode.upper() |
| 329 |
): |
| 330 |
LOG.warning( |
| 331 |
"MySQL SQL mode is '%s', " |
| 332 |
"consider enabling TRADITIONAL or STRICT_ALL_TABLES", |
| 333 |
realmode, |
| 334 |
) |
| 335 |
|
| 336 |
|
| 337 |
@_init_events.dispatch_for("sqlite") |
| 338 |
def _init_events(engine, sqlite_synchronous=True, sqlite_fk=False, **kw): |
| 339 |
"""Set up event listeners for SQLite. |
| 340 |
|
| 341 |
This includes several settings made on connections as they are |
| 342 |
created, as well as transactional control extensions. |
| 343 |
|
| 344 |
""" |
| 345 |
|
| 346 |
def regexp(expr, item): |
| 347 |
reg = re.compile(expr) |
| 348 |
return reg.search(str(item)) is not None |
| 349 |
|
| 350 |
@sqlalchemy.event.listens_for(engine, "connect") |
| 351 |
def _sqlite_connect_events(dbapi_con, con_record): |
| 352 |
|
| 353 |
|
| 354 |
dbapi_con.create_function("regexp", 2, regexp) |
| 355 |
|
| 356 |
if not sqlite_synchronous: |
| 357 |
|
| 358 |
dbapi_con.execute("PRAGMA synchronous = OFF") |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
dbapi_con.isolation_level = None |
| 366 |
|
| 367 |
if sqlite_fk: |
| 368 |
|
| 369 |
dbapi_con.execute("pragma foreign_keys=ON") |
| 370 |
|
| 371 |
@sqlalchemy.event.listens_for(engine, "begin") |
| 372 |
def _sqlite_emit_begin(conn): |
| 373 |
|
| 374 |
|
| 375 |
if "in_transaction" not in conn.info: |
| 376 |
conn.execute(sqlalchemy.text("BEGIN")) |
| 377 |
conn.info["in_transaction"] = True |
| 378 |
|
| 379 |
@sqlalchemy.event.listens_for(engine, "rollback") |
| 380 |
@sqlalchemy.event.listens_for(engine, "commit") |
| 381 |
def _sqlite_end_transaction(conn): |
| 382 |
|
| 383 |
conn.info.pop("in_transaction", None) |
| 384 |
|
| 385 |
|
| 386 |
def _add_process_guards(engine): |
| 387 |
"""Add multiprocessing guards. |
| 388 |
|
| 389 |
Forces a connection to be reconnected if it is detected |
| 390 |
as having been shared to a sub-process. |
| 391 |
|
| 392 |
""" |
| 393 |
|
| 394 |
@sqlalchemy.event.listens_for(engine, "connect") |
| 395 |
def connect(dbapi_connection, connection_record): |
| 396 |
connection_record.info["pid"] = os.getpid() |
| 397 |
|
| 398 |
@sqlalchemy.event.listens_for(engine, "checkout") |
| 399 |
def checkout(dbapi_connection, connection_record, connection_proxy): |
| 400 |
pid = os.getpid() |
| 401 |
if connection_record.info["pid"] != pid: |
| 402 |
LOG.debug( |
| 403 |
"Parent process %(orig)s forked (%(newproc)s) with an open " |
| 404 |
"database connection, " |
| 405 |
"which is being discarded and recreated.", |
| 406 |
{"newproc": pid, "orig": connection_record.info["pid"]}, |
| 407 |
) |
| 408 |
raise exc.DisconnectionError( |
| 409 |
"Connection record belongs to pid %s, " |
| 410 |
"attempting to check out in pid %s" |
| 411 |
% (connection_record.info["pid"], pid) |
| 412 |
) |
| 413 |
|
| 414 |
|
| 415 |
def _add_trace_comments(engine): |
| 416 |
"""Add trace comments. |
| 417 |
|
| 418 |
Augment statements with a trace of the immediate calling code |
| 419 |
for a given statement. |
| 420 |
""" |
| 421 |
|
| 422 |
import os |
| 423 |
import sys |
| 424 |
import traceback |
| 425 |
|
| 426 |
target_paths = { |
| 427 |
os.path.dirname(sys.modules["oslo_db"].__file__), |
| 428 |
os.path.dirname(sys.modules["sqlalchemy"].__file__), |
| 429 |
} |
| 430 |
try: |
| 431 |
skip_paths = { |
| 432 |
os.path.dirname(sys.modules["oslo_db.tests"].__file__), |
| 433 |
} |
| 434 |
except KeyError: |
| 435 |
skip_paths = set() |
| 436 |
|
| 437 |
@sqlalchemy.event.listens_for(engine, "before_cursor_execute", retval=True) |
| 438 |
def before_cursor_execute( |
| 439 |
conn, cursor, statement, parameters, context, executemany |
| 440 |
): |
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
stack = traceback.extract_stack() |
| 445 |
our_line = None |
| 446 |
|
| 447 |
for idx, (filename, line, method, function) in enumerate(stack): |
| 448 |
for tgt in skip_paths: |
| 449 |
if filename.startswith(tgt): |
| 450 |
break |
| 451 |
else: |
| 452 |
for tgt in target_paths: |
| 453 |
if filename.startswith(tgt): |
| 454 |
our_line = idx |
| 455 |
break |
| 456 |
if our_line: |
| 457 |
break |
| 458 |
|
| 459 |
if our_line: |
| 460 |
trace = "; ".join( |
| 461 |
f"File: {line[0]} ({line[1]}) {line[2]}" |
| 462 |
|
| 463 |
for line in stack[our_line - 3: our_line] |
| 464 |
) |
| 465 |
statement = f"{statement} -- {trace}" |
| 466 |
|
| 467 |
return statement, parameters |