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

Commit 91fa9cc

Browse files
authored
Expose opentracing trace id in response headers (#10199)
Fixes: #9480
1 parent 08c8469 commit 91fa9cc

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

changelog.d/10199.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Expose opentracing trace id in response headers.

synapse/federation/transport/server.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
parse_string_from_args,
3636
parse_strings_from_args,
3737
)
38+
from synapse.logging import opentracing
3839
from synapse.logging.context import run_in_background
3940
from synapse.logging.opentracing import (
4041
SynapseTags,
@@ -345,6 +346,8 @@ async def new_func(request, *args, **kwargs):
345346
)
346347

347348
with scope:
349+
opentracing.inject_response_headers(request.responseHeaders)
350+
348351
if origin and self.RATELIMIT:
349352
with ratelimiter.ratelimit(origin) as d:
350353
await d

synapse/logging/opentracing.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
173173
import attr
174174

175175
from twisted.internet import defer
176+
from twisted.web.http_headers import Headers
176177

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

670671

672+
def inject_response_headers(response_headers: Headers) -> None:
673+
"""Inject the current trace id into the HTTP response headers"""
674+
if not opentracing:
675+
return
676+
span = opentracing.tracer.active_span
677+
if not span:
678+
return
679+
680+
# This is a bit implementation-specific.
681+
#
682+
# Jaeger's Spans have a trace_id property; other implementations (including the
683+
# dummy opentracing.span.Span which we use if init_tracer is not called) do not
684+
# expose it
685+
trace_id = getattr(span, "trace_id", None)
686+
687+
if trace_id is not None:
688+
response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")
689+
690+
671691
@ensure_active_span("get the active span context as a dict", ret={})
672692
def get_active_span_text_map(destination=None):
673693
"""
@@ -843,6 +863,7 @@ def trace_servlet(request: "SynapseRequest", extract_context: bool = False):
843863
scope = start_active_span(request_name)
844864

845865
with scope:
866+
inject_response_headers(request.responseHeaders)
846867
try:
847868
yield
848869
finally:

0 commit comments

Comments
 (0)