|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +This library allows tracing PostgreSQL queries made by the |
| 17 | +`asyncpg <https://magicstack.github.io/asyncpg/current/>`_ library. |
| 18 | +
|
| 19 | +Usage |
| 20 | +----- |
| 21 | +
|
| 22 | +.. code-block:: python |
| 23 | +
|
| 24 | + import asyncpg |
| 25 | + from opentelemetry.ext.asyncpg import AsyncPGInstrumentor |
| 26 | +
|
| 27 | + # You can optionally pass a custom TracerProvider to AsyncPGInstrumentor.instrument() |
| 28 | + AsyncPGInstrumentor().instrument() |
| 29 | + conn = await asyncpg.connect(user='user', password='password', |
| 30 | + database='database', host='127.0.0.1') |
| 31 | + values = await conn.fetch('''SELECT 42;''') |
| 32 | +
|
| 33 | +API |
| 34 | +--- |
| 35 | +""" |
| 36 | + |
| 37 | +import asyncpg |
| 38 | +import wrapt |
| 39 | +from asyncpg import exceptions |
| 40 | + |
| 41 | +from opentelemetry import trace |
| 42 | +from opentelemetry.ext.asyncpg.version import __version__ |
| 43 | +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor |
| 44 | +from opentelemetry.instrumentation.utils import unwrap |
| 45 | +from opentelemetry.trace import SpanKind |
| 46 | +from opentelemetry.trace.status import Status, StatusCanonicalCode |
| 47 | + |
| 48 | +_APPLIED = "_opentelemetry_tracer" |
| 49 | + |
| 50 | + |
| 51 | +def _exception_to_canonical_code(exc: Exception) -> StatusCanonicalCode: |
| 52 | + if isinstance( |
| 53 | + exc, (exceptions.InterfaceError, exceptions.SyntaxOrAccessError), |
| 54 | + ): |
| 55 | + return StatusCanonicalCode.INVALID_ARGUMENT |
| 56 | + if isinstance(exc, exceptions.IdleInTransactionSessionTimeoutError): |
| 57 | + return StatusCanonicalCode.DEADLINE_EXCEEDED |
| 58 | + return StatusCanonicalCode.UNKNOWN |
| 59 | + |
| 60 | + |
| 61 | +def _hydrate_span_from_args(connection, query, parameters) -> dict: |
| 62 | + span_attributes = {"db.type": "sql"} |
| 63 | + |
| 64 | + params = getattr(connection, "_params", None) |
| 65 | + span_attributes["db.instance"] = getattr(params, "database", None) |
| 66 | + span_attributes["db.user"] = getattr(params, "user", None) |
| 67 | + |
| 68 | + if query is not None: |
| 69 | + span_attributes["db.statement"] = query |
| 70 | + |
| 71 | + if parameters is not None and len(parameters) > 0: |
| 72 | + span_attributes["db.statement.parameters"] = str(parameters) |
| 73 | + |
| 74 | + return span_attributes |
| 75 | + |
| 76 | + |
| 77 | +async def _do_execute(func, instance, args, kwargs): |
| 78 | + span_attributes = _hydrate_span_from_args(instance, args[0], args[1:]) |
| 79 | + tracer = getattr(asyncpg, _APPLIED) |
| 80 | + |
| 81 | + exception = None |
| 82 | + |
| 83 | + with tracer.start_as_current_span( |
| 84 | + "postgresql", kind=SpanKind.CLIENT |
| 85 | + ) as span: |
| 86 | + |
| 87 | + for attribute, value in span_attributes.items(): |
| 88 | + span.set_attribute(attribute, value) |
| 89 | + |
| 90 | + try: |
| 91 | + result = await func(*args, **kwargs) |
| 92 | + except Exception as exc: # pylint: disable=W0703 |
| 93 | + exception = exc |
| 94 | + raise |
| 95 | + finally: |
| 96 | + if exception is not None: |
| 97 | + span.set_status( |
| 98 | + Status(_exception_to_canonical_code(exception)) |
| 99 | + ) |
| 100 | + else: |
| 101 | + span.set_status(Status(StatusCanonicalCode.OK)) |
| 102 | + |
| 103 | + return result |
| 104 | + |
| 105 | + |
| 106 | +class AsyncPGInstrumentor(BaseInstrumentor): |
| 107 | + def _instrument(self, **kwargs): |
| 108 | + tracer_provider = kwargs.get( |
| 109 | + "tracer_provider", trace.get_tracer_provider() |
| 110 | + ) |
| 111 | + setattr( |
| 112 | + asyncpg, |
| 113 | + _APPLIED, |
| 114 | + tracer_provider.get_tracer("asyncpg", __version__), |
| 115 | + ) |
| 116 | + for method in [ |
| 117 | + "Connection.execute", |
| 118 | + "Connection.executemany", |
| 119 | + "Connection.fetch", |
| 120 | + "Connection.fetchval", |
| 121 | + "Connection.fetchrow", |
| 122 | + ]: |
| 123 | + wrapt.wrap_function_wrapper( |
| 124 | + "asyncpg.connection", method, _do_execute |
| 125 | + ) |
| 126 | + |
| 127 | + def _uninstrument(self, **__): |
| 128 | + delattr(asyncpg, _APPLIED) |
| 129 | + for method in [ |
| 130 | + "execute", |
| 131 | + "executemany", |
| 132 | + "fetch", |
| 133 | + "fetchval", |
| 134 | + "fetchrow", |
| 135 | + ]: |
| 136 | + unwrap(asyncpg.Connection, method) |
0 commit comments