| 1 |
import logging |
| 2 |
import importlib |
| 3 |
|
| 4 |
log = logging.getLogger(__name__) |
| 5 |
|
| 6 |
SUPPORTED_MODULES = ( |
| 7 |
'aiobotocore', |
| 8 |
'botocore', |
| 9 |
'requests', |
| 10 |
'sqlite3', |
| 11 |
'mysql', |
| 12 |
) |
| 13 |
|
| 14 |
_PATCHED_MODULES = set() |
| 15 |
|
| 16 |
|
| 17 |
def patch_all(): |
| 18 |
patch(SUPPORTED_MODULES, raise_errors=False) |
| 19 |
|
| 20 |
|
| 21 |
def patch(modules_to_patch, raise_errors=True): |
| 22 |
for m in modules_to_patch: |
| 23 |
_patch_module(m, raise_errors) |
| 24 |
|
| 25 |
|
| 26 |
def _patch_module(module_to_patch, raise_errors=True): |
| 27 |
# boto3 depends on botocore and patching botocore is sufficient |
| 28 |
if module_to_patch == 'boto3': |
| 29 |
module_to_patch = 'botocore' |
| 30 |
|
| 31 |
# aioboto3 depends on aiobotocore and patching aiobotocore is sufficient |
| 32 |
if module_to_patch == 'aioboto3': |
| 33 |
module_to_patch = 'aiobotocore' |
| 34 |
|
| 35 |
if module_to_patch not in SUPPORTED_MODULES: |
| 36 |
raise Exception('module %s is currently not supported for patching' |
| 37 |
% module_to_patch) |
| 38 |
|
| 39 |
try: |
| 40 |
_patch(module_to_patch) |
| 41 |
except Exception: |
| 42 |
if raise_errors: |
| 43 |
raise |
| 44 |
log.debug('failed to patch module %s', module_to_patch) |
| 45 |
|
| 46 |
|
| 47 |
def _patch(module_to_patch): |
| 48 |
|
| 49 |
path = 'aws_xray_sdk.ext.%s' % module_to_patch |
| 50 |
|
| 51 |
if module_to_patch in _PATCHED_MODULES: |
| 52 |
log.debug('%s already patched', module_to_patch) |
| 53 |
|
| 54 |
imported_module = importlib.import_module(path) |
| 55 |
imported_module.patch() |
| 56 |
|
| 57 |
_PATCHED_MODULES.add(module_to_patch) |
| 58 |
log.info('successfully patched module %s', module_to_patch) |