|
| 1 | +import yaaredis |
| 2 | + |
| 3 | +from ddtrace import config |
| 4 | +from ddtrace.vendor import wrapt |
| 5 | + |
| 6 | +from ...internal.utils.wrappers import unwrap |
| 7 | +from ...pin import Pin |
| 8 | +from ..redis.util import _trace_redis_cmd |
| 9 | +from ..redis.util import _trace_redis_execute_pipeline |
| 10 | +from ..redis.util import format_command_args |
| 11 | + |
| 12 | + |
| 13 | +config._add("yaaredis", dict(_default_service="redis")) |
| 14 | + |
| 15 | + |
| 16 | +def patch(): |
| 17 | + """Patch the instrumented methods""" |
| 18 | + if getattr(yaaredis, "_datadog_patch", False): |
| 19 | + return |
| 20 | + setattr(yaaredis, "_datadog_patch", True) |
| 21 | + |
| 22 | + _w = wrapt.wrap_function_wrapper |
| 23 | + |
| 24 | + _w("yaaredis.client", "StrictRedis.execute_command", traced_execute_command) |
| 25 | + _w("yaaredis.client", "StrictRedis.pipeline", traced_pipeline) |
| 26 | + _w("yaaredis.pipeline", "StrictPipeline.execute", traced_execute_pipeline) |
| 27 | + _w("yaaredis.pipeline", "StrictPipeline.immediate_execute_command", traced_execute_command) |
| 28 | + Pin().onto(yaaredis.StrictRedis) |
| 29 | + |
| 30 | + |
| 31 | +def unpatch(): |
| 32 | + if getattr(yaaredis, "_datadog_patch", False): |
| 33 | + setattr(yaaredis, "_datadog_patch", False) |
| 34 | + |
| 35 | + unwrap(yaaredis.client.StrictRedis, "execute_command") |
| 36 | + unwrap(yaaredis.client.StrictRedis, "pipeline") |
| 37 | + unwrap(yaaredis.pipeline.StrictPipeline, "execute") |
| 38 | + unwrap(yaaredis.pipeline.StrictPipeline, "immediate_execute_command") |
| 39 | + |
| 40 | + |
| 41 | +async def traced_execute_command(func, instance, args, kwargs): |
| 42 | + pin = Pin.get_from(instance) |
| 43 | + if not pin or not pin.enabled(): |
| 44 | + return await func(*args, **kwargs) |
| 45 | + |
| 46 | + with _trace_redis_cmd(pin, config.yaaredis, instance, args): |
| 47 | + return await func(*args, **kwargs) |
| 48 | + |
| 49 | + |
| 50 | +async def traced_pipeline(func, instance, args, kwargs): |
| 51 | + pipeline = await func(*args, **kwargs) |
| 52 | + pin = Pin.get_from(instance) |
| 53 | + if pin: |
| 54 | + pin.onto(pipeline) |
| 55 | + return pipeline |
| 56 | + |
| 57 | + |
| 58 | +async def traced_execute_pipeline(func, instance, args, kwargs): |
| 59 | + pin = Pin.get_from(instance) |
| 60 | + if not pin or not pin.enabled(): |
| 61 | + return await func(*args, **kwargs) |
| 62 | + |
| 63 | + cmds = [format_command_args(c) for c, _ in instance.command_stack] |
| 64 | + resource = "\n".join(cmds) |
| 65 | + with _trace_redis_execute_pipeline(pin, config.yaaredis, resource, instance): |
| 66 | + return await func(*args, **kwargs) |
0 commit comments