otlp.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from sentry_sdk import get_client, capture_event
  2. from sentry_sdk.integrations import Integration, DidNotEnable
  3. from sentry_sdk.scope import register_external_propagation_context
  4. from sentry_sdk.utils import (
  5. Dsn,
  6. logger,
  7. event_from_exception,
  8. capture_internal_exceptions,
  9. )
  10. from sentry_sdk.consts import VERSION, EndpointType
  11. from sentry_sdk.tracing_utils import Baggage
  12. from sentry_sdk.tracing import (
  13. BAGGAGE_HEADER_NAME,
  14. SENTRY_TRACE_HEADER_NAME,
  15. )
  16. try:
  17. from opentelemetry.propagate import set_global_textmap
  18. from opentelemetry.sdk.trace import TracerProvider, Span
  19. from opentelemetry.sdk.trace.export import BatchSpanProcessor
  20. from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
  21. from opentelemetry.trace import (
  22. get_current_span,
  23. get_tracer_provider,
  24. set_tracer_provider,
  25. format_trace_id,
  26. format_span_id,
  27. SpanContext,
  28. INVALID_SPAN_ID,
  29. INVALID_TRACE_ID,
  30. )
  31. from opentelemetry.context import (
  32. Context,
  33. get_current,
  34. get_value,
  35. )
  36. from opentelemetry.propagators.textmap import (
  37. CarrierT,
  38. Setter,
  39. default_setter,
  40. )
  41. from sentry_sdk.integrations.opentelemetry.propagator import SentryPropagator
  42. from sentry_sdk.integrations.opentelemetry.consts import SENTRY_BAGGAGE_KEY
  43. except ImportError:
  44. raise DidNotEnable("opentelemetry-distro[otlp] is not installed")
  45. from typing import TYPE_CHECKING
  46. if TYPE_CHECKING:
  47. from typing import Optional, Dict, Any, Tuple
  48. def otel_propagation_context() -> "Optional[Tuple[str, str]]":
  49. """
  50. Get the (trace_id, span_id) from opentelemetry if exists.
  51. """
  52. ctx = get_current_span().get_span_context()
  53. if ctx.trace_id == INVALID_TRACE_ID or ctx.span_id == INVALID_SPAN_ID:
  54. return None
  55. return (format_trace_id(ctx.trace_id), format_span_id(ctx.span_id))
  56. def setup_otlp_traces_exporter(dsn: "Optional[str]" = None) -> None:
  57. tracer_provider = get_tracer_provider()
  58. if not isinstance(tracer_provider, TracerProvider):
  59. logger.debug("[OTLP] No TracerProvider configured by user, creating a new one")
  60. tracer_provider = TracerProvider()
  61. set_tracer_provider(tracer_provider)
  62. endpoint = None
  63. headers = None
  64. if dsn:
  65. auth = Dsn(dsn).to_auth(f"sentry.python/{VERSION}")
  66. endpoint = auth.get_api_url(EndpointType.OTLP_TRACES)
  67. headers = {"X-Sentry-Auth": auth.to_header()}
  68. logger.debug(f"[OTLP] Sending traces to {endpoint}")
  69. otlp_exporter = OTLPSpanExporter(endpoint=endpoint, headers=headers)
  70. span_processor = BatchSpanProcessor(otlp_exporter)
  71. tracer_provider.add_span_processor(span_processor)
  72. _sentry_patched_exception = False
  73. def setup_capture_exceptions() -> None:
  74. """
  75. Intercept otel's Span.record_exception to automatically capture those exceptions in Sentry.
  76. """
  77. global _sentry_patched_exception
  78. _original_record_exception = Span.record_exception
  79. if _sentry_patched_exception:
  80. return
  81. def _sentry_patched_record_exception(
  82. self: "Span", exception: "BaseException", *args: "Any", **kwargs: "Any"
  83. ) -> None:
  84. otlp_integration = get_client().get_integration(OTLPIntegration)
  85. if otlp_integration and otlp_integration.capture_exceptions:
  86. with capture_internal_exceptions():
  87. event, hint = event_from_exception(
  88. exception,
  89. client_options=get_client().options,
  90. mechanism={"type": OTLPIntegration.identifier, "handled": False},
  91. )
  92. capture_event(event, hint=hint)
  93. _original_record_exception(self, exception, *args, **kwargs)
  94. Span.record_exception = _sentry_patched_record_exception # type: ignore[method-assign]
  95. _sentry_patched_exception = True
  96. class SentryOTLPPropagator(SentryPropagator):
  97. """
  98. We need to override the inject of the older propagator since that
  99. is SpanProcessor based.
  100. !!! Note regarding baggage:
  101. We cannot meaningfully populate a new baggage as a head SDK
  102. when we are using OTLP since we don't have any sort of transaction semantic to
  103. track state across a group of spans.
  104. For incoming baggage, we just pass it on as is so that case is correctly handled.
  105. """
  106. def inject(
  107. self,
  108. carrier: "CarrierT",
  109. context: "Optional[Context]" = None,
  110. setter: "Setter[CarrierT]" = default_setter,
  111. ) -> None:
  112. otlp_integration = get_client().get_integration(OTLPIntegration)
  113. if otlp_integration is None:
  114. return
  115. if context is None:
  116. context = get_current()
  117. current_span = get_current_span(context)
  118. current_span_context = current_span.get_span_context()
  119. if not current_span_context.is_valid:
  120. return
  121. sentry_trace = _to_traceparent(current_span_context)
  122. setter.set(carrier, SENTRY_TRACE_HEADER_NAME, sentry_trace)
  123. baggage = get_value(SENTRY_BAGGAGE_KEY, context)
  124. if baggage is not None and isinstance(baggage, Baggage):
  125. baggage_data = baggage.serialize()
  126. if baggage_data:
  127. setter.set(carrier, BAGGAGE_HEADER_NAME, baggage_data)
  128. def _to_traceparent(span_context: "SpanContext") -> str:
  129. """
  130. Helper method to generate the sentry-trace header.
  131. """
  132. span_id = format_span_id(span_context.span_id)
  133. trace_id = format_trace_id(span_context.trace_id)
  134. sampled = span_context.trace_flags.sampled
  135. return f"{trace_id}-{span_id}-{'1' if sampled else '0'}"
  136. class OTLPIntegration(Integration):
  137. """
  138. Automatically setup OTLP ingestion from the DSN.
  139. :param setup_otlp_traces_exporter: Automatically configure an Exporter to send OTLP traces from the DSN, defaults to True.
  140. Set to False if using a custom collector or to setup the TracerProvider manually.
  141. :param setup_propagator: Automatically configure the Sentry Propagator for Distributed Tracing, defaults to True.
  142. Set to False to configure propagators manually or to disable propagation.
  143. :param capture_exceptions: Intercept and capture exceptions on the OpenTelemetry Span in Sentry as well, defaults to False.
  144. Set to True to turn on capturing but be aware that since Sentry captures most exceptions, duplicate exceptions might be dropped by DedupeIntegration in many cases.
  145. """
  146. identifier = "otlp"
  147. def __init__(
  148. self,
  149. setup_otlp_traces_exporter: bool = True,
  150. setup_propagator: bool = True,
  151. capture_exceptions: bool = False,
  152. ) -> None:
  153. self.setup_otlp_traces_exporter = setup_otlp_traces_exporter
  154. self.setup_propagator = setup_propagator
  155. self.capture_exceptions = capture_exceptions
  156. @staticmethod
  157. def setup_once() -> None:
  158. logger.debug("[OTLP] Setting up trace linking for all events")
  159. register_external_propagation_context(otel_propagation_context)
  160. def setup_once_with_options(
  161. self, options: "Optional[Dict[str, Any]]" = None
  162. ) -> None:
  163. if self.setup_otlp_traces_exporter:
  164. logger.debug("[OTLP] Setting up OTLP exporter")
  165. dsn: "Optional[str]" = options.get("dsn") if options else None
  166. setup_otlp_traces_exporter(dsn)
  167. if self.setup_propagator:
  168. logger.debug("[OTLP] Setting up propagator for distributed tracing")
  169. # TODO-neel better propagator support, chain with existing ones if possible instead of replacing
  170. set_global_textmap(SentryOTLPPropagator())
  171. setup_capture_exceptions()