|
| 1 | +from typing import TYPE_CHECKING |
| 2 | + |
| 3 | +from ddtrace import Pin |
| 4 | +from ddtrace import config |
| 5 | +from ddtrace.vendor import wrapt |
| 6 | + |
| 7 | +from ...constants import SPAN_MEASURED_KEY |
| 8 | +from ...ext import SpanTypes |
| 9 | +from ...ext import db |
| 10 | +from ...ext import net |
| 11 | +from ...internal.logger import get_logger |
| 12 | +from ...internal.utils import get_argument_value |
| 13 | +from ..trace_utils import ext_service |
| 14 | +from ..trace_utils import unwrap |
| 15 | +from ..trace_utils import wrap |
| 16 | +from ..trace_utils_async import with_traced_module |
| 17 | + |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from types import ModuleType |
| 21 | + from typing import Dict |
| 22 | + from typing import Union |
| 23 | + |
| 24 | + import asyncpg |
| 25 | + from asyncpg.prepared_stmt import PreparedStatement |
| 26 | + |
| 27 | + |
| 28 | +config._add( |
| 29 | + "asyncpg", |
| 30 | + dict( |
| 31 | + _default_service="postgres", |
| 32 | + ), |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +log = get_logger(__name__) |
| 37 | + |
| 38 | + |
| 39 | +def _get_connection_tags(conn): |
| 40 | + # type: (asyncpg.Connection) -> Dict[str, str] |
| 41 | + addr = conn._addr |
| 42 | + params = conn._params |
| 43 | + host = port = "" |
| 44 | + if isinstance(addr, tuple) and len(addr) == 2: |
| 45 | + host, port = addr |
| 46 | + return { |
| 47 | + net.TARGET_HOST: host, |
| 48 | + net.TARGET_PORT: port, |
| 49 | + db.USER: params.user, |
| 50 | + db.NAME: params.database, |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +class _TracedConnection(wrapt.ObjectProxy): |
| 55 | + def __init__(self, conn, pin): |
| 56 | + super(_TracedConnection, self).__init__(conn) |
| 57 | + conn_pin = pin.clone(tags=_get_connection_tags(conn)) |
| 58 | + # Keep the pin on the protocol |
| 59 | + conn_pin.onto(self._protocol) |
| 60 | + |
| 61 | + def __setddpin__(self, pin): |
| 62 | + pin.onto(self._protocol) |
| 63 | + |
| 64 | + def __getddpin__(self): |
| 65 | + return Pin.get_from(self._protocol) |
| 66 | + |
| 67 | + |
| 68 | +@with_traced_module |
| 69 | +async def _traced_connect(asyncpg, pin, func, instance, args, kwargs): |
| 70 | + """Traced asyncpg.connect(). |
| 71 | +
|
| 72 | + connect() is instrumented and patched to return a connection proxy. |
| 73 | + """ |
| 74 | + with pin.tracer.trace( |
| 75 | + "postgres.connect", span_type=SpanTypes.SQL, service=ext_service(pin, config.asyncpg) |
| 76 | + ) as span: |
| 77 | + # Need an ObjectProxy since Connection uses slots |
| 78 | + conn = _TracedConnection(await func(*args, **kwargs), pin) |
| 79 | + span.set_tags(_get_connection_tags(conn)) |
| 80 | + return conn |
| 81 | + |
| 82 | + |
| 83 | +async def _traced_query(pin, method, query, args, kwargs): |
| 84 | + with pin.tracer.trace( |
| 85 | + "postgres.query", resource=query, service=ext_service(pin, config.asyncpg), span_type=SpanTypes.SQL |
| 86 | + ) as span: |
| 87 | + span.set_tag(SPAN_MEASURED_KEY) |
| 88 | + span.set_tags(pin.tags) |
| 89 | + return await method(*args, **kwargs) |
| 90 | + |
| 91 | + |
| 92 | +@with_traced_module |
| 93 | +async def _traced_protocol_execute(asyncpg, pin, func, instance, args, kwargs): |
| 94 | + state = get_argument_value(args, kwargs, 0, "state") # type: Union[str, PreparedStatement] |
| 95 | + query = state if isinstance(state, str) else state.query |
| 96 | + return await _traced_query(pin, func, query, args, kwargs) |
| 97 | + |
| 98 | + |
| 99 | +def _patch(asyncpg): |
| 100 | + # type: (ModuleType) -> None |
| 101 | + wrap(asyncpg, "connect", _traced_connect(asyncpg)) |
| 102 | + for method in ("execute", "bind_execute", "query", "bind_execute_many"): |
| 103 | + wrap(asyncpg.protocol, "Protocol.%s" % method, _traced_protocol_execute(asyncpg)) |
| 104 | + |
| 105 | + |
| 106 | +def patch(): |
| 107 | + # type: () -> None |
| 108 | + import asyncpg |
| 109 | + |
| 110 | + if getattr(asyncpg, "_datadog_patch", False): |
| 111 | + return |
| 112 | + |
| 113 | + Pin().onto(asyncpg) |
| 114 | + _patch(asyncpg) |
| 115 | + |
| 116 | + setattr(asyncpg, "_datadog_patch", True) |
| 117 | + |
| 118 | + |
| 119 | +def _unpatch(asyncpg): |
| 120 | + # type: (ModuleType) -> None |
| 121 | + unwrap(asyncpg, "connect") |
| 122 | + for method in ("execute", "bind_execute", "query", "bind_execute_many"): |
| 123 | + unwrap(asyncpg.protocol.Protocol, method) |
| 124 | + |
| 125 | + |
| 126 | +def unpatch(): |
| 127 | + # type: () -> None |
| 128 | + import asyncpg |
| 129 | + |
| 130 | + if not getattr(asyncpg, "_datadog_patch", False): |
| 131 | + return |
| 132 | + |
| 133 | + _unpatch(asyncpg) |
| 134 | + |
| 135 | + setattr(asyncpg, "_datadog_patch", False) |
0 commit comments