| 1 |
import logging |
| 2 |
import importlib |
| 3 |
|
| 4 |
from django.db import connections |
| 5 |
|
| 6 |
from aws_xray_sdk.ext.dbapi2 import XRayTracedCursor |
| 7 |
|
| 8 |
log = logging.getLogger(__name__) |
| 9 |
|
| 10 |
|
| 11 |
def patch_db(): |
| 12 |
|
| 13 |
for conn in connections.all(): |
| 14 |
module = importlib.import_module(conn.__module__) |
| 15 |
_patch_conn(getattr(module, conn.__class__.__name__)) |
| 16 |
|
| 17 |
|
| 18 |
def _patch_conn(conn): |
| 19 |
|
| 20 |
attr = '_xray_original_cursor' |
| 21 |
|
| 22 |
if hasattr(conn, attr): |
| 23 |
log.debug('django built-in db already patched') |
| 24 |
return |
| 25 |
|
| 26 |
setattr(conn, attr, conn.cursor) |
| 27 |
|
| 28 |
meta = {} |
| 29 |
|
| 30 |
if hasattr(conn, 'vendor'): |
| 31 |
meta['database_type'] = conn.vendor |
| 32 |
|
| 33 |
def cursor(self, *args, **kwargs): |
| 34 |
|
| 35 |
host = None |
| 36 |
user = None |
| 37 |
|
| 38 |
if hasattr(self, 'settings_dict'): |
| 39 |
settings = self.settings_dict |
| 40 |
host = settings.get('HOST', None) |
| 41 |
user = settings.get('USER', None) |
| 42 |
|
| 43 |
if host: |
| 44 |
meta['name'] = host |
| 45 |
if user: |
| 46 |
meta['user'] = user |
| 47 |
|
| 48 |
return XRayTracedCursor( |
| 49 |
self._xray_original_cursor(*args, **kwargs), meta) |
| 50 |
|
| 51 |
conn.cursor = cursor |