|
| 1 | +from __future__ import absolute_import |
| 2 | + |
| 3 | +from sentry_sdk import Hub |
| 4 | +from sentry_sdk.consts import OP |
| 5 | +from sentry_sdk.utils import capture_internal_exceptions, logger |
| 6 | +from sentry_sdk.integrations import Integration, DidNotEnable |
| 7 | + |
| 8 | +from sentry_sdk._types import MYPY |
| 9 | + |
| 10 | +if MYPY: |
| 11 | + from typing import Any, Sequence |
| 12 | + from sentry_sdk.tracing import Span |
| 13 | + |
| 14 | +_SINGLE_KEY_COMMANDS = frozenset( |
| 15 | + ["decr", "decrby", "get", "incr", "incrby", "pttl", "set", "setex", "setnx", "ttl"] |
| 16 | +) |
| 17 | +_MULTI_KEY_COMMANDS = frozenset(["del", "touch", "unlink"]) |
| 18 | + |
| 19 | +#: Trim argument lists to this many values |
| 20 | +_MAX_NUM_ARGS = 10 |
| 21 | + |
| 22 | + |
| 23 | +def _set_pipeline_data( |
| 24 | + span, is_cluster, get_command_args_fn, is_transaction, command_stack |
| 25 | +): |
| 26 | + # type: (Span, bool, Any, bool, Sequence[Any]) -> None |
| 27 | + span.set_tag("redis.is_cluster", is_cluster) |
| 28 | + transaction = is_transaction if not is_cluster else False |
| 29 | + span.set_tag("redis.transaction", transaction) |
| 30 | + |
| 31 | + commands = [] |
| 32 | + for i, arg in enumerate(command_stack): |
| 33 | + if i > _MAX_NUM_ARGS: |
| 34 | + break |
| 35 | + command_args = [] |
| 36 | + for j, command_arg in enumerate(get_command_args_fn(arg)): |
| 37 | + if j > 0: |
| 38 | + command_arg = repr(command_arg) |
| 39 | + command_args.append(command_arg) |
| 40 | + commands.append(" ".join(command_args)) |
| 41 | + |
| 42 | + span.set_data( |
| 43 | + "redis.commands", |
| 44 | + {"count": len(command_stack), "first_ten": commands}, |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def patch_redis_pipeline(pipeline_cls, is_cluster, get_command_args_fn): |
| 49 | + # type: (Any, bool, Any) -> None |
| 50 | + old_execute = pipeline_cls.execute |
| 51 | + |
| 52 | + def sentry_patched_execute(self, *args, **kwargs): |
| 53 | + # type: (Any, *Any, **Any) -> Any |
| 54 | + hub = Hub.current |
| 55 | + |
| 56 | + if hub.get_integration(RedisIntegration) is None: |
| 57 | + return old_execute(self, *args, **kwargs) |
| 58 | + |
| 59 | + with hub.start_span( |
| 60 | + op=OP.DB_REDIS, description="redis.pipeline.execute" |
| 61 | + ) as span: |
| 62 | + with capture_internal_exceptions(): |
| 63 | + _set_pipeline_data( |
| 64 | + span, |
| 65 | + is_cluster, |
| 66 | + get_command_args_fn, |
| 67 | + self.transaction, |
| 68 | + self.command_stack, |
| 69 | + ) |
| 70 | + |
| 71 | + return old_execute(self, *args, **kwargs) |
| 72 | + |
| 73 | + pipeline_cls.execute = sentry_patched_execute |
| 74 | + |
| 75 | + |
| 76 | +def _get_redis_command_args(command): |
| 77 | + # type: (Any) -> Sequence[Any] |
| 78 | + return command[0] |
| 79 | + |
| 80 | + |
| 81 | +def _parse_rediscluster_command(command): |
| 82 | + # type: (Any) -> Sequence[Any] |
| 83 | + return command.args |
| 84 | + |
| 85 | + |
| 86 | +def _patch_redis(redis): |
| 87 | + # type: (Any) -> None |
| 88 | + patch_redis_client(redis.StrictRedis, is_cluster=False) |
| 89 | + patch_redis_pipeline(redis.client.Pipeline, False, _get_redis_command_args) |
| 90 | + try: |
| 91 | + strict_pipeline = redis.client.StrictPipeline |
| 92 | + except AttributeError: |
| 93 | + pass |
| 94 | + else: |
| 95 | + patch_redis_pipeline(strict_pipeline, False, _get_redis_command_args) |
| 96 | + try: |
| 97 | + import redis.asyncio # type: ignore |
| 98 | + except ImportError: |
| 99 | + pass |
| 100 | + else: |
| 101 | + from sentry_sdk.integrations.redis.asyncio import ( |
| 102 | + patch_redis_async_client, |
| 103 | + patch_redis_async_pipeline, |
| 104 | + ) |
| 105 | + |
| 106 | + patch_redis_async_client(redis.asyncio.client.StrictRedis) |
| 107 | + patch_redis_async_pipeline(redis.asyncio.client.Pipeline) |
| 108 | + |
| 109 | + |
| 110 | +def _patch_rb(): |
| 111 | + # type: () -> None |
| 112 | + try: |
| 113 | + import rb.clients # type: ignore |
| 114 | + except ImportError: |
| 115 | + pass |
| 116 | + else: |
| 117 | + patch_redis_client(rb.clients.FanoutClient, is_cluster=False) |
| 118 | + patch_redis_client(rb.clients.MappingClient, is_cluster=False) |
| 119 | + patch_redis_client(rb.clients.RoutingClient, is_cluster=False) |
| 120 | + |
| 121 | + |
| 122 | +def _patch_rediscluster(): |
| 123 | + # type: () -> None |
| 124 | + try: |
| 125 | + import rediscluster # type: ignore |
| 126 | + except ImportError: |
| 127 | + return |
| 128 | + |
| 129 | + patch_redis_client(rediscluster.RedisCluster, is_cluster=True) |
| 130 | + |
| 131 | + # up to v1.3.6, __version__ attribute is a tuple |
| 132 | + # from v2.0.0, __version__ is a string and VERSION a tuple |
| 133 | + version = getattr(rediscluster, "VERSION", rediscluster.__version__) |
| 134 | + |
| 135 | + # StrictRedisCluster was introduced in v0.2.0 and removed in v2.0.0 |
| 136 | + # https://github.com/Grokzen/redis-py-cluster/blob/master/docs/release-notes.rst |
| 137 | + if (0, 2, 0) < version < (2, 0, 0): |
| 138 | + pipeline_cls = rediscluster.pipeline.StrictClusterPipeline |
| 139 | + patch_redis_client(rediscluster.StrictRedisCluster, is_cluster=True) |
| 140 | + else: |
| 141 | + pipeline_cls = rediscluster.pipeline.ClusterPipeline |
| 142 | + |
| 143 | + patch_redis_pipeline(pipeline_cls, True, _parse_rediscluster_command) |
| 144 | + |
| 145 | + |
| 146 | +class RedisIntegration(Integration): |
| 147 | + identifier = "redis" |
| 148 | + |
| 149 | + @staticmethod |
| 150 | + def setup_once(): |
| 151 | + # type: () -> None |
| 152 | + try: |
| 153 | + import redis |
| 154 | + except ImportError: |
| 155 | + raise DidNotEnable("Redis client not installed") |
| 156 | + |
| 157 | + _patch_redis(redis) |
| 158 | + _patch_rb() |
| 159 | + |
| 160 | + try: |
| 161 | + _patch_rediscluster() |
| 162 | + except Exception: |
| 163 | + logger.exception("Error occurred while patching `rediscluster` library") |
| 164 | + |
| 165 | + |
| 166 | +def _get_span_description(name, *args): |
| 167 | + # type: (str, *Any) -> str |
| 168 | + description = name |
| 169 | + |
| 170 | + with capture_internal_exceptions(): |
| 171 | + description_parts = [name] |
| 172 | + for i, arg in enumerate(args): |
| 173 | + if i > _MAX_NUM_ARGS: |
| 174 | + break |
| 175 | + |
| 176 | + description_parts.append(repr(arg)) |
| 177 | + |
| 178 | + description = " ".join(description_parts) |
| 179 | + |
| 180 | + return description |
| 181 | + |
| 182 | + |
| 183 | +def _set_client_data(span, is_cluster, name, *args): |
| 184 | + # type: (Span, bool, str, *Any) -> None |
| 185 | + span.set_tag("redis.is_cluster", is_cluster) |
| 186 | + if name: |
| 187 | + span.set_tag("redis.command", name) |
| 188 | + |
| 189 | + if name and args: |
| 190 | + name_low = name.lower() |
| 191 | + if (name_low in _SINGLE_KEY_COMMANDS) or ( |
| 192 | + name_low in _MULTI_KEY_COMMANDS and len(args) == 1 |
| 193 | + ): |
| 194 | + span.set_tag("redis.key", args[0]) |
| 195 | + |
| 196 | + |
| 197 | +def patch_redis_client(cls, is_cluster): |
| 198 | + # type: (Any, bool) -> None |
| 199 | + """ |
| 200 | + This function can be used to instrument custom redis client classes or |
| 201 | + subclasses. |
| 202 | + """ |
| 203 | + old_execute_command = cls.execute_command |
| 204 | + |
| 205 | + def sentry_patched_execute_command(self, name, *args, **kwargs): |
| 206 | + # type: (Any, str, *Any, **Any) -> Any |
| 207 | + hub = Hub.current |
| 208 | + |
| 209 | + if hub.get_integration(RedisIntegration) is None: |
| 210 | + return old_execute_command(self, name, *args, **kwargs) |
| 211 | + |
| 212 | + description = _get_span_description(name, *args) |
| 213 | + |
| 214 | + with hub.start_span(op=OP.DB_REDIS, description=description) as span: |
| 215 | + _set_client_data(span, is_cluster, name, *args) |
| 216 | + |
| 217 | + return old_execute_command(self, name, *args, **kwargs) |
| 218 | + |
| 219 | + cls.execute_command = sentry_patched_execute_command |
0 commit comments