authentik.lib.tracing.otel

authentik OpenTelemetry integration

  1"""authentik OpenTelemetry integration"""
  2
  3from contextlib import contextmanager
  4from os import environ
  5from platform import machine
  6from socket import gethostname
  7from typing import Any
  8
  9from django.conf import settings
 10from opentelemetry import trace
 11from opentelemetry.baggage.propagation import W3CBaggagePropagator
 12from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
 13from opentelemetry.instrumentation.django import DjangoInstrumentor
 14from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
 15from opentelemetry.instrumentation.requests import RequestsInstrumentor
 16from opentelemetry.instrumentation.structlog import StructlogInstrumentor
 17from opentelemetry.instrumentation.threading import ThreadingInstrumentor
 18from opentelemetry.propagate import inject, set_global_textmap
 19from opentelemetry.propagators.b3 import B3MultiFormat
 20from opentelemetry.propagators.composite import CompositePropagator
 21from opentelemetry.sdk.resources import HOST_ARCH, HOST_NAME, Resource
 22from opentelemetry.sdk.trace import TracerProvider
 23from opentelemetry.sdk.trace.export import BatchSpanProcessor
 24from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
 25from opentelemetry.trace import Span as OtelSpan
 26from opentelemetry.trace import Status, StatusCode
 27from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
 28from structlog.stdlib import get_logger
 29
 30from authentik import authentik_build_hash, authentik_version
 31from authentik.lib.config import CONFIG
 32from authentik.lib.tracing.common import Tracer
 33from authentik.lib.utils.reflection import get_env
 34
 35LOGGER = get_logger()
 36_root_path = CONFIG.get("web.path", "/")
 37
 38tracer = trace.get_tracer("authentik")
 39
 40
 41class _Span:
 42    """Thin wrapper around an OpenTelemetry span exposing a sentry_sdk-like API"""
 43
 44    def __init__(self, span: OtelSpan):
 45        self._span = span
 46        self._description: str | None = None
 47
 48    def set_data(self, key: str, value: Any) -> None:
 49        self._span.set_attribute(key, str(value))
 50
 51    @property
 52    def description(self) -> str | None:
 53        return self._description
 54
 55    @description.setter
 56    def description(self, value: str) -> None:
 57        self._description = value
 58        self._span.set_attribute("description", str(value))
 59
 60
 61class OpenTelemetryTracer(Tracer):
 62    """Tracer backed by OpenTelemetry, exporting spans over OTLP to
 63    error_reporting.otel_endpoint"""
 64
 65    def setup_pre_fork(self) -> None:
 66        """Wire up automatic instrumentation. Safe to call
 67        before a fork; must run after Django settings have fully loaded, since
 68        DjangoInstrumentor patches MIDDLEWARE.
 69
 70        Needs opentelemetry-instrumentation-asgi installed (never imported directly
 71        here), or DjangoInstrumentor silently falls back to WSGI-only, which authentik
 72        never uses."""
 73        set_global_textmap(
 74            CompositePropagator(
 75                [TraceContextTextMapPropagator(), W3CBaggagePropagator(), B3MultiFormat()]
 76            )
 77        )
 78        ThreadingInstrumentor().instrument()
 79        RequestsInstrumentor().instrument()
 80        StructlogInstrumentor().instrument()
 81        PsycopgInstrumentor().instrument()
 82        DjangoInstrumentor().instrument(
 83            excluded_urls=f"{_root_path}-/health,{_root_path}-/metrics",
 84            is_sql_commentor_enabled=True,
 85        )
 86
 87    def setup_post_fork(self) -> None:
 88        """Create and set the real OpenTelemetry TracerProvider and span exporter.
 89
 90        Must run after any fork: BatchSpanProcessor's background export thread doesn't
 91        survive fork() safely. Under gunicorn's preload_app, call this from a post_fork
 92        hook, after setup_pre_fork() has run pre-fork."""
 93        sample_rate = 1 if settings.DEBUG else float(CONFIG.get("error_reporting.sample_rate", 0.1))
 94        provider = TracerProvider(
 95            resource=Resource.create(
 96                {
 97                    "service.name": "authentik",
 98                    "service.version": authentik_version(),
 99                    "deployment.environment": CONFIG.get("error_reporting.environment", "customer"),
100                    "authentik.build_hash": authentik_build_hash("tagged"),
101                    "authentik.env": get_env(),
102                    "authentik.component": "backend",
103                    HOST_NAME: gethostname(),
104                    HOST_ARCH: machine(),
105                }
106            ),
107            sampler=ParentBased(TraceIdRatioBased(sample_rate)),
108        )
109        # error_reporting.otel_endpoint is the base OTLP endpoint (matching the standard
110        # OTEL_EXPORTER_OTLP_ENDPOINT convention), so the per-signal path must be appended here;
111        # unlike OTEL_EXPORTER_OTLP_ENDPOINT, passing `endpoint=` directly skips that step
112        endpoint = CONFIG.get("error_reporting.otel_endpoint")
113        exporter = (
114            OTLPSpanExporter(endpoint=f"{endpoint.rstrip('/')}/v1/traces")
115            if endpoint
116            else OTLPSpanExporter()
117        )
118        if environ.get("AUTHENTIK_PYROSCOPE_HOST"):
119            try:
120                from pyroscope.otel import PyroscopeSpanProcessor
121            except ModuleNotFoundError:
122                pass
123
124            provider.add_span_processor(PyroscopeSpanProcessor())
125        provider.add_span_processor(BatchSpanProcessor(exporter))
126        trace.set_tracer_provider(provider)
127        LOGGER.info("Enabled Open Telemetry tracing")
128
129    def record_exception(self, exc: Exception) -> None:
130        span = trace.get_current_span()
131        span.record_exception(exc)
132        span.set_status(Status(StatusCode.ERROR))
133
134    def get_http_meta(self) -> dict[str, str]:
135        carrier: dict[str, str] = {}
136        inject(carrier)
137        return carrier
138
139    def set_tag(self, key: str, value: Any) -> None:
140        trace.get_current_span().set_attribute(key, str(value))
141
142    @contextmanager
143    def start_span(self, op: str, name: str | None = None):
144        with tracer.start_as_current_span(op, attributes={"name": name or op}) as span:
145            yield _Span(span)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
tracer = <opentelemetry.trace.ProxyTracer object>
class OpenTelemetryTracer(authentik.lib.tracing.common.Tracer):
 62class OpenTelemetryTracer(Tracer):
 63    """Tracer backed by OpenTelemetry, exporting spans over OTLP to
 64    error_reporting.otel_endpoint"""
 65
 66    def setup_pre_fork(self) -> None:
 67        """Wire up automatic instrumentation. Safe to call
 68        before a fork; must run after Django settings have fully loaded, since
 69        DjangoInstrumentor patches MIDDLEWARE.
 70
 71        Needs opentelemetry-instrumentation-asgi installed (never imported directly
 72        here), or DjangoInstrumentor silently falls back to WSGI-only, which authentik
 73        never uses."""
 74        set_global_textmap(
 75            CompositePropagator(
 76                [TraceContextTextMapPropagator(), W3CBaggagePropagator(), B3MultiFormat()]
 77            )
 78        )
 79        ThreadingInstrumentor().instrument()
 80        RequestsInstrumentor().instrument()
 81        StructlogInstrumentor().instrument()
 82        PsycopgInstrumentor().instrument()
 83        DjangoInstrumentor().instrument(
 84            excluded_urls=f"{_root_path}-/health,{_root_path}-/metrics",
 85            is_sql_commentor_enabled=True,
 86        )
 87
 88    def setup_post_fork(self) -> None:
 89        """Create and set the real OpenTelemetry TracerProvider and span exporter.
 90
 91        Must run after any fork: BatchSpanProcessor's background export thread doesn't
 92        survive fork() safely. Under gunicorn's preload_app, call this from a post_fork
 93        hook, after setup_pre_fork() has run pre-fork."""
 94        sample_rate = 1 if settings.DEBUG else float(CONFIG.get("error_reporting.sample_rate", 0.1))
 95        provider = TracerProvider(
 96            resource=Resource.create(
 97                {
 98                    "service.name": "authentik",
 99                    "service.version": authentik_version(),
100                    "deployment.environment": CONFIG.get("error_reporting.environment", "customer"),
101                    "authentik.build_hash": authentik_build_hash("tagged"),
102                    "authentik.env": get_env(),
103                    "authentik.component": "backend",
104                    HOST_NAME: gethostname(),
105                    HOST_ARCH: machine(),
106                }
107            ),
108            sampler=ParentBased(TraceIdRatioBased(sample_rate)),
109        )
110        # error_reporting.otel_endpoint is the base OTLP endpoint (matching the standard
111        # OTEL_EXPORTER_OTLP_ENDPOINT convention), so the per-signal path must be appended here;
112        # unlike OTEL_EXPORTER_OTLP_ENDPOINT, passing `endpoint=` directly skips that step
113        endpoint = CONFIG.get("error_reporting.otel_endpoint")
114        exporter = (
115            OTLPSpanExporter(endpoint=f"{endpoint.rstrip('/')}/v1/traces")
116            if endpoint
117            else OTLPSpanExporter()
118        )
119        if environ.get("AUTHENTIK_PYROSCOPE_HOST"):
120            try:
121                from pyroscope.otel import PyroscopeSpanProcessor
122            except ModuleNotFoundError:
123                pass
124
125            provider.add_span_processor(PyroscopeSpanProcessor())
126        provider.add_span_processor(BatchSpanProcessor(exporter))
127        trace.set_tracer_provider(provider)
128        LOGGER.info("Enabled Open Telemetry tracing")
129
130    def record_exception(self, exc: Exception) -> None:
131        span = trace.get_current_span()
132        span.record_exception(exc)
133        span.set_status(Status(StatusCode.ERROR))
134
135    def get_http_meta(self) -> dict[str, str]:
136        carrier: dict[str, str] = {}
137        inject(carrier)
138        return carrier
139
140    def set_tag(self, key: str, value: Any) -> None:
141        trace.get_current_span().set_attribute(key, str(value))
142
143    @contextmanager
144    def start_span(self, op: str, name: str | None = None):
145        with tracer.start_as_current_span(op, attributes={"name": name or op}) as span:
146            yield _Span(span)

Tracer backed by OpenTelemetry, exporting spans over OTLP to error_reporting.otel_endpoint

def setup_pre_fork(self) -> None:
66    def setup_pre_fork(self) -> None:
67        """Wire up automatic instrumentation. Safe to call
68        before a fork; must run after Django settings have fully loaded, since
69        DjangoInstrumentor patches MIDDLEWARE.
70
71        Needs opentelemetry-instrumentation-asgi installed (never imported directly
72        here), or DjangoInstrumentor silently falls back to WSGI-only, which authentik
73        never uses."""
74        set_global_textmap(
75            CompositePropagator(
76                [TraceContextTextMapPropagator(), W3CBaggagePropagator(), B3MultiFormat()]
77            )
78        )
79        ThreadingInstrumentor().instrument()
80        RequestsInstrumentor().instrument()
81        StructlogInstrumentor().instrument()
82        PsycopgInstrumentor().instrument()
83        DjangoInstrumentor().instrument(
84            excluded_urls=f"{_root_path}-/health,{_root_path}-/metrics",
85            is_sql_commentor_enabled=True,
86        )

Wire up automatic instrumentation. Safe to call before a fork; must run after Django settings have fully loaded, since DjangoInstrumentor patches MIDDLEWARE.

Needs opentelemetry-instrumentation-asgi installed (never imported directly here), or DjangoInstrumentor silently falls back to WSGI-only, which authentik never uses.

def setup_post_fork(self) -> None:
 88    def setup_post_fork(self) -> None:
 89        """Create and set the real OpenTelemetry TracerProvider and span exporter.
 90
 91        Must run after any fork: BatchSpanProcessor's background export thread doesn't
 92        survive fork() safely. Under gunicorn's preload_app, call this from a post_fork
 93        hook, after setup_pre_fork() has run pre-fork."""
 94        sample_rate = 1 if settings.DEBUG else float(CONFIG.get("error_reporting.sample_rate", 0.1))
 95        provider = TracerProvider(
 96            resource=Resource.create(
 97                {
 98                    "service.name": "authentik",
 99                    "service.version": authentik_version(),
100                    "deployment.environment": CONFIG.get("error_reporting.environment", "customer"),
101                    "authentik.build_hash": authentik_build_hash("tagged"),
102                    "authentik.env": get_env(),
103                    "authentik.component": "backend",
104                    HOST_NAME: gethostname(),
105                    HOST_ARCH: machine(),
106                }
107            ),
108            sampler=ParentBased(TraceIdRatioBased(sample_rate)),
109        )
110        # error_reporting.otel_endpoint is the base OTLP endpoint (matching the standard
111        # OTEL_EXPORTER_OTLP_ENDPOINT convention), so the per-signal path must be appended here;
112        # unlike OTEL_EXPORTER_OTLP_ENDPOINT, passing `endpoint=` directly skips that step
113        endpoint = CONFIG.get("error_reporting.otel_endpoint")
114        exporter = (
115            OTLPSpanExporter(endpoint=f"{endpoint.rstrip('/')}/v1/traces")
116            if endpoint
117            else OTLPSpanExporter()
118        )
119        if environ.get("AUTHENTIK_PYROSCOPE_HOST"):
120            try:
121                from pyroscope.otel import PyroscopeSpanProcessor
122            except ModuleNotFoundError:
123                pass
124
125            provider.add_span_processor(PyroscopeSpanProcessor())
126        provider.add_span_processor(BatchSpanProcessor(exporter))
127        trace.set_tracer_provider(provider)
128        LOGGER.info("Enabled Open Telemetry tracing")

Create and set the real OpenTelemetry TracerProvider and span exporter.

Must run after any fork: BatchSpanProcessor's background export thread doesn't survive fork() safely. Under gunicorn's preload_app, call this from a post_fork hook, after setup_pre_fork() has run pre-fork.

def record_exception(self, exc: Exception) -> None:
130    def record_exception(self, exc: Exception) -> None:
131        span = trace.get_current_span()
132        span.record_exception(exc)
133        span.set_status(Status(StatusCode.ERROR))
def get_http_meta(self) -> dict[str, str]:
135    def get_http_meta(self) -> dict[str, str]:
136        carrier: dict[str, str] = {}
137        inject(carrier)
138        return carrier
def set_tag(self, key: str, value: Any) -> None:
140    def set_tag(self, key: str, value: Any) -> None:
141        trace.get_current_span().set_attribute(key, str(value))
@contextmanager
def start_span(self, op: str, name: str | None = None):
143    @contextmanager
144    def start_span(self, op: str, name: str | None = None):
145        with tracer.start_as_current_span(op, attributes={"name": name or op}) as span:
146            yield _Span(span)