Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Commit

Permalink
Expose opentracing trace id in response headers (#10199)
Browse files Browse the repository at this point in the history
Fixes: #9480
  • Loading branch information
richvdh committed Jun 18, 2021
1 parent 08c8469 commit 91fa9cc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog.d/10199.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Expose opentracing trace id in response headers.
3 changes: 3 additions & 0 deletions synapse/federation/transport/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
parse_string_from_args,
parse_strings_from_args,
)
from synapse.logging import opentracing
from synapse.logging.context import run_in_background
from synapse.logging.opentracing import (
SynapseTags,
Expand Down Expand Up @@ -345,6 +346,8 @@ async def new_func(request, *args, **kwargs):
)

with scope:
opentracing.inject_response_headers(request.responseHeaders)

if origin and self.RATELIMIT:
with ratelimiter.ratelimit(origin) as d:
await d
Expand Down
21 changes: 21 additions & 0 deletions synapse/logging/opentracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
import attr

from twisted.internet import defer
from twisted.web.http_headers import Headers

from synapse.config import ConfigError
from synapse.util import json_decoder, json_encoder
Expand Down Expand Up @@ -668,6 +669,25 @@ def inject_header_dict(
headers[key.encode()] = [value.encode()]


def inject_response_headers(response_headers: Headers) -> None:
"""Inject the current trace id into the HTTP response headers"""
if not opentracing:
return
span = opentracing.tracer.active_span
if not span:
return

# This is a bit implementation-specific.
#
# Jaeger's Spans have a trace_id property; other implementations (including the
# dummy opentracing.span.Span which we use if init_tracer is not called) do not
# expose it
trace_id = getattr(span, "trace_id", None)

if trace_id is not None:
response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")


@ensure_active_span("get the active span context as a dict", ret={})
def get_active_span_text_map(destination=None):
"""
Expand Down Expand Up @@ -843,6 +863,7 @@ def trace_servlet(request: "SynapseRequest", extract_context: bool = False):
scope = start_active_span(request_name)

with scope:
inject_response_headers(request.responseHeaders)
try:
yield
finally:
Expand Down

0 comments on commit 91fa9cc

Please sign in to comment.