|
| 1 | +# BSD 3-Clause License |
| 2 | +# |
| 3 | +# Copyright (c) 2019, Elasticsearch BV |
| 4 | +# All rights reserved. |
| 5 | +# |
| 6 | +# Redistribution and use in source and binary forms, with or without |
| 7 | +# modification, are permitted provided that the following conditions are met: |
| 8 | +# |
| 9 | +# * Redistributions of source code must retain the above copyright notice, this |
| 10 | +# list of conditions and the following disclaimer. |
| 11 | +# |
| 12 | +# * Redistributions in binary form must reproduce the above copyright notice, |
| 13 | +# this list of conditions and the following disclaimer in the documentation |
| 14 | +# and/or other materials provided with the distribution. |
| 15 | +# |
| 16 | +# * Neither the name of the copyright holder nor the names of its |
| 17 | +# contributors may be used to endorse or promote products derived from |
| 18 | +# this software without specific prior written permission. |
| 19 | +# |
| 20 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 21 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 22 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 23 | +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 24 | +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 25 | +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 26 | +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 27 | +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 28 | +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 29 | +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 30 | + |
| 31 | +"""Provides classes to instrument dbapi2 providers |
| 32 | +
|
| 33 | +https://www.python.org/dev/peps/pep-0249/ |
| 34 | +""" |
| 35 | + |
| 36 | +import wrapt |
| 37 | + |
| 38 | +from elasticapm.contrib.asyncio.traces import async_capture_span |
| 39 | +from elasticapm.instrumentation.packages.asyncio.base import AsyncAbstractInstrumentedModule |
| 40 | +from elasticapm.instrumentation.packages.dbapi2 import EXEC_ACTION, QUERY_ACTION |
| 41 | +from elasticapm.utils.encoding import shorten |
| 42 | + |
| 43 | + |
| 44 | +class AsyncCursorProxy(wrapt.ObjectProxy): |
| 45 | + provider_name = None |
| 46 | + DML_QUERIES = ("INSERT", "DELETE", "UPDATE") |
| 47 | + |
| 48 | + def __init__(self, wrapped, destination_info=None): |
| 49 | + super(AsyncCursorProxy, self).__init__(wrapped) |
| 50 | + self._self_destination_info = destination_info or {} |
| 51 | + |
| 52 | + async def callproc(self, procname, params=None): |
| 53 | + return await self._trace_sql(self.__wrapped__.callproc, procname, params, action=EXEC_ACTION) |
| 54 | + |
| 55 | + async def execute(self, sql, params=None): |
| 56 | + return await self._trace_sql(self.__wrapped__.execute, sql, params) |
| 57 | + |
| 58 | + async def executemany(self, sql, param_list): |
| 59 | + return await self._trace_sql(self.__wrapped__.executemany, sql, param_list) |
| 60 | + |
| 61 | + def _bake_sql(self, sql): |
| 62 | + """ |
| 63 | + Method to turn the "sql" argument into a string. Most database backends simply return |
| 64 | + the given object, as it is already a string |
| 65 | + """ |
| 66 | + return sql |
| 67 | + |
| 68 | + async def _trace_sql(self, method, sql, params, action=QUERY_ACTION): |
| 69 | + sql_string = self._bake_sql(sql) |
| 70 | + if action == EXEC_ACTION: |
| 71 | + signature = sql_string + "()" |
| 72 | + else: |
| 73 | + signature = self.extract_signature(sql_string) |
| 74 | + |
| 75 | + # Truncate sql_string to 10000 characters to prevent large queries from |
| 76 | + # causing an error to APM server. |
| 77 | + sql_string = shorten(sql_string, string_length=10000) |
| 78 | + |
| 79 | + async with async_capture_span( |
| 80 | + signature, |
| 81 | + span_type="db", |
| 82 | + span_subtype=self.provider_name, |
| 83 | + span_action=action, |
| 84 | + extra={ |
| 85 | + "db": {"type": "sql", "statement": sql_string, "instance": getattr(self, "_self_database", None)}, |
| 86 | + "destination": self._self_destination_info, |
| 87 | + }, |
| 88 | + skip_frames=1, |
| 89 | + leaf=True, |
| 90 | + ) as span: |
| 91 | + if params is None: |
| 92 | + result = await method(sql) |
| 93 | + else: |
| 94 | + result = await method(sql, params) |
| 95 | + # store "rows affected", but only for DML queries like insert/update/delete |
| 96 | + if span and self.rowcount not in (-1, None) and signature.startswith(self.DML_QUERIES): |
| 97 | + span.update_context("db", {"rows_affected": self.rowcount}) |
| 98 | + return result |
| 99 | + |
| 100 | + def extract_signature(self, sql): |
| 101 | + raise NotImplementedError() |
| 102 | + |
| 103 | + |
| 104 | +class AsyncConnectionProxy(wrapt.ObjectProxy): |
| 105 | + cursor_proxy = AsyncCursorProxy |
| 106 | + |
| 107 | + def __init__(self, wrapped, destination_info=None): |
| 108 | + super(AsyncConnectionProxy, self).__init__(wrapped) |
| 109 | + self._self_destination_info = destination_info |
| 110 | + |
| 111 | + def cursor(self, *args, **kwargs): |
| 112 | + return self.cursor_proxy(self.__wrapped__.cursor(*args, **kwargs), self._self_destination_info) |
| 113 | + |
| 114 | + |
| 115 | +class AsyncDbApi2Instrumentation(AsyncAbstractInstrumentedModule): |
| 116 | + connect_method = None |
| 117 | + |
| 118 | + async def call(self, module, method, wrapped, instance, args, kwargs): |
| 119 | + return AsyncConnectionProxy(await wrapped(*args, **kwargs)) |
| 120 | + |
| 121 | + async def call_if_sampling(self, module, method, wrapped, instance, args, kwargs): |
| 122 | + # Contrasting to the superclass implementation, we *always* want to |
| 123 | + # return a proxied connection, even if there is no ongoing elasticapm |
| 124 | + # transaction yet. This ensures that we instrument the cursor once |
| 125 | + # the transaction started. |
| 126 | + return await self.call(module, method, wrapped, instance, args, kwargs) |
0 commit comments