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

Commit 386285b

Browse files
Return noop context manager if not tracing
1 parent 24b3834 commit 386285b

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

synapse/util/tracerutils.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,10 @@ def init_tracer(config):
9494
The config used by the homserver. Here it's used to set the service
9595
name to the homeserver's.
9696
"""
97+
global opentracing
9798
if not config.tracer_config.get("tracer_enabled", False):
9899
# We don't have a tracer
100+
opentracing = None
99101
return
100102

101103
if not opentracing:
@@ -148,7 +150,7 @@ def start_active_span(
148150
finish_on_close=True,
149151
):
150152
if opentracing is None:
151-
return _noop_context_manager
153+
return _noop_context_manager()
152154
else:
153155
# We need to enter the scope here for the logcontext to become active
154156
return opentracing.tracer.start_active_span(
@@ -232,6 +234,9 @@ def start_active_span_from_context(
232234
# Twisted encodes the values as lists whereas opentracing doesn't.
233235
# So, we take the first item in the list.
234236
# Also, twisted uses byte arrays while opentracing expects strings.
237+
if opentracing is None:
238+
return _noop_context_manager()
239+
235240
header_dict = {k.decode(): v[0].decode() for k, v in headers.getAllRawHeaders()}
236241
context = opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)
237242

@@ -313,7 +318,7 @@ def trace_servlet(func):
313318
@wraps(func)
314319
@defer.inlineCallbacks
315320
def f(request, *args, **kwargs):
316-
with start_active_span_from_context(
321+
scope = start_active_span_from_context(
317322
request.requestHeaders,
318323
"incoming-client-request",
319324
tags={
@@ -323,8 +328,16 @@ def f(request, *args, **kwargs):
323328
tags.HTTP_URL: request.get_redacted_uri(),
324329
tags.PEER_HOST_IPV6: request.getClientIP(),
325330
},
326-
):
331+
)
332+
# A context manager would be the most logical here but defer.returnValue
333+
# raises an exception in order to provide the return value. This causes
334+
# opentracing to mark each request as erroring, in order to avoid this we
335+
# need to give the finally clause explicitly.
336+
scope.__enter__()
337+
try:
327338
result = yield defer.maybeDeferred(func, request, *args, **kwargs)
328339
defer.returnValue(result)
340+
finally:
341+
scope.__exit__(None, None, None)
329342

330343
return f

0 commit comments

Comments
 (0)