|
| 1 | +from typing import TYPE_CHECKING # noqa:F401 |
| 2 | +from typing import Any # noqa:F401 |
| 3 | +from typing import Dict # noqa:F401 |
| 4 | +from typing import Optional # noqa:F401 |
| 5 | + |
| 6 | +import wrapt |
| 7 | + |
| 8 | +import ddtrace |
| 9 | + |
| 10 | +from ..internal.logger import get_logger |
| 11 | + |
| 12 | + |
| 13 | +log = get_logger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +# To set attributes on wrapt proxy objects use this prefix: |
| 17 | +# http://wrapt.readthedocs.io/en/latest/wrappers.html |
| 18 | +_DD_PIN_NAME = "_datadog_pin" |
| 19 | +_DD_PIN_PROXY_NAME = "_self_" + _DD_PIN_NAME |
| 20 | + |
| 21 | + |
| 22 | +class Pin(object): |
| 23 | + """Pin (a.k.a Patch INfo) is a small class which is used to |
| 24 | + set tracing metadata on a particular traced connection. |
| 25 | + This is useful if you wanted to, say, trace two different |
| 26 | + database clusters. |
| 27 | +
|
| 28 | + >>> conn = sqlite.connect('/tmp/user.db') |
| 29 | + >>> # Override a pin for a specific connection |
| 30 | + >>> pin = Pin.override(conn, service='user-db') |
| 31 | + >>> conn = sqlite.connect('/tmp/image.db') |
| 32 | + """ |
| 33 | + |
| 34 | + __slots__ = ["tags", "tracer", "_target", "_config", "_initialized"] |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + service=None, # type: Optional[str] |
| 39 | + tags=None, # type: Optional[Dict[str, str]] |
| 40 | + tracer=None, |
| 41 | + _config=None, # type: Optional[Dict[str, Any]] |
| 42 | + ): |
| 43 | + # type: (...) -> None |
| 44 | + tracer = tracer or ddtrace.tracer |
| 45 | + self.tags = tags |
| 46 | + self.tracer = tracer |
| 47 | + self._target = None # type: Optional[int] |
| 48 | + # keep the configuration attribute internal because the |
| 49 | + # public API to access it is not the Pin class |
| 50 | + self._config = _config or {} # type: Dict[str, Any] |
| 51 | + # [Backward compatibility]: service argument updates the `Pin` config |
| 52 | + self._config["service_name"] = service |
| 53 | + self._initialized = True |
| 54 | + |
| 55 | + @property |
| 56 | + def service(self): |
| 57 | + # type: () -> str |
| 58 | + """Backward compatibility: accessing to `pin.service` returns the underlying |
| 59 | + configuration value. |
| 60 | + """ |
| 61 | + return self._config["service_name"] |
| 62 | + |
| 63 | + def __setattr__(self, name, value): |
| 64 | + if getattr(self, "_initialized", False) and name != "_target": |
| 65 | + raise AttributeError("can't mutate a pin, use override() or clone() instead") |
| 66 | + super(Pin, self).__setattr__(name, value) |
| 67 | + |
| 68 | + def __repr__(self): |
| 69 | + return "Pin(service=%s, tags=%s, tracer=%s)" % (self.service, self.tags, self.tracer) |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def _find(*objs): |
| 73 | + # type: (Any) -> Optional[Pin] |
| 74 | + """ |
| 75 | + Return the first :class:`ddtrace.trace.Pin` found on any of the provided objects or `None` if none were found |
| 76 | +
|
| 77 | +
|
| 78 | + >>> pin = Pin._find(wrapper, instance, conn) |
| 79 | +
|
| 80 | + :param objs: The objects to search for a :class:`ddtrace.trace.Pin` on |
| 81 | + :type objs: List of objects |
| 82 | + :rtype: :class:`ddtrace.trace.Pin`, None |
| 83 | + :returns: The first found :class:`ddtrace.trace.Pin` or `None` is none was found |
| 84 | + """ |
| 85 | + for obj in objs: |
| 86 | + pin = Pin.get_from(obj) |
| 87 | + if pin: |
| 88 | + return pin |
| 89 | + return None |
| 90 | + |
| 91 | + @staticmethod |
| 92 | + def get_from(obj): |
| 93 | + # type: (Any) -> Optional[Pin] |
| 94 | + """Return the pin associated with the given object. If a pin is attached to |
| 95 | + `obj` but the instance is not the owner of the pin, a new pin is cloned and |
| 96 | + attached. This ensures that a pin inherited from a class is a copy for the new |
| 97 | + instance, avoiding that a specific instance overrides other pins values. |
| 98 | +
|
| 99 | + >>> pin = Pin.get_from(conn) |
| 100 | +
|
| 101 | + :param obj: The object to look for a :class:`ddtrace.trace.Pin` on |
| 102 | + :type obj: object |
| 103 | + :rtype: :class:`ddtrace.trace.Pin`, None |
| 104 | + :returns: :class:`ddtrace.trace.Pin` associated with the object or None |
| 105 | + """ |
| 106 | + if hasattr(obj, "__getddpin__"): |
| 107 | + return obj.__getddpin__() |
| 108 | + |
| 109 | + pin_name = _DD_PIN_PROXY_NAME if isinstance(obj, wrapt.ObjectProxy) else _DD_PIN_NAME |
| 110 | + pin = getattr(obj, pin_name, None) |
| 111 | + # detect if the PIN has been inherited from a class |
| 112 | + if pin is not None and pin._target != id(obj): |
| 113 | + pin = pin.clone() |
| 114 | + pin.onto(obj) |
| 115 | + return pin |
| 116 | + |
| 117 | + @classmethod |
| 118 | + def override( |
| 119 | + cls, |
| 120 | + obj, # type: Any |
| 121 | + service=None, # type: Optional[str] |
| 122 | + tags=None, # type: Optional[Dict[str, str]] |
| 123 | + tracer=None, |
| 124 | + ): |
| 125 | + # type: (...) -> None |
| 126 | + """Override an object with the given attributes. |
| 127 | +
|
| 128 | + That's the recommended way to customize an already instrumented client, without |
| 129 | + losing existing attributes. |
| 130 | +
|
| 131 | + >>> conn = sqlite.connect('/tmp/user.db') |
| 132 | + >>> # Override a pin for a specific connection |
| 133 | + >>> Pin.override(conn, service='user-db') |
| 134 | + """ |
| 135 | + if not obj: |
| 136 | + return |
| 137 | + |
| 138 | + pin = cls.get_from(obj) |
| 139 | + if pin is None: |
| 140 | + Pin(service=service, tags=tags, tracer=tracer).onto(obj) |
| 141 | + else: |
| 142 | + pin.clone(service=service, tags=tags, tracer=tracer).onto(obj) |
| 143 | + |
| 144 | + def enabled(self): |
| 145 | + # type: () -> bool |
| 146 | + """Return true if this pin's tracer is enabled.""" |
| 147 | + # inline to avoid circular imports |
| 148 | + from ddtrace.settings.asm import config as asm_config |
| 149 | + |
| 150 | + return bool(self.tracer) and (self.tracer.enabled or asm_config._apm_opt_out) |
| 151 | + |
| 152 | + def onto(self, obj, send=True): |
| 153 | + # type: (Any, bool) -> None |
| 154 | + """Patch this pin onto the given object. If send is true, it will also |
| 155 | + queue the metadata to be sent to the server. |
| 156 | + """ |
| 157 | + # Actually patch it on the object. |
| 158 | + try: |
| 159 | + if hasattr(obj, "__setddpin__"): |
| 160 | + return obj.__setddpin__(self) |
| 161 | + |
| 162 | + pin_name = _DD_PIN_PROXY_NAME if isinstance(obj, wrapt.ObjectProxy) else _DD_PIN_NAME |
| 163 | + |
| 164 | + # set the target reference; any get_from, clones and retarget the new PIN |
| 165 | + self._target = id(obj) |
| 166 | + if self.service: |
| 167 | + ddtrace.config._add_extra_service(self.service) |
| 168 | + return setattr(obj, pin_name, self) |
| 169 | + except AttributeError: |
| 170 | + log.debug("can't pin onto object. skipping", exc_info=True) |
| 171 | + |
| 172 | + def remove_from(self, obj): |
| 173 | + # type: (Any) -> None |
| 174 | + # Remove pin from the object. |
| 175 | + try: |
| 176 | + pin_name = _DD_PIN_PROXY_NAME if isinstance(obj, wrapt.ObjectProxy) else _DD_PIN_NAME |
| 177 | + |
| 178 | + pin = Pin.get_from(obj) |
| 179 | + if pin is not None: |
| 180 | + delattr(obj, pin_name) |
| 181 | + except AttributeError: |
| 182 | + log.debug("can't remove pin from object. skipping", exc_info=True) |
| 183 | + |
| 184 | + def clone( |
| 185 | + self, |
| 186 | + service=None, # type: Optional[str] |
| 187 | + tags=None, # type: Optional[Dict[str, str]] |
| 188 | + tracer=None, |
| 189 | + ): |
| 190 | + # type: (...) -> Pin |
| 191 | + """Return a clone of the pin with the given attributes replaced.""" |
| 192 | + # do a shallow copy of Pin dicts |
| 193 | + if not tags and self.tags: |
| 194 | + tags = self.tags.copy() |
| 195 | + |
| 196 | + # we use a copy instead of a deepcopy because we expect configurations |
| 197 | + # to have only a root level dictionary without nested objects. Using |
| 198 | + # deepcopy introduces a big overhead: |
| 199 | + # |
| 200 | + # copy: 0.00654911994934082 |
| 201 | + # deepcopy: 0.2787208557128906 |
| 202 | + config = self._config.copy() |
| 203 | + |
| 204 | + return Pin( |
| 205 | + service=service or self.service, |
| 206 | + tags=tags, |
| 207 | + tracer=tracer or self.tracer, # do not clone the Tracer |
| 208 | + _config=config, |
| 209 | + ) |
0 commit comments