@@ -94,8 +94,10 @@ def init_tracer(config):
94
94
The config used by the homserver. Here it's used to set the service
95
95
name to the homeserver's.
96
96
"""
97
+ global opentracing
97
98
if not config .tracer_config .get ("tracer_enabled" , False ):
98
99
# We don't have a tracer
100
+ opentracing = None
99
101
return
100
102
101
103
if not opentracing :
@@ -148,7 +150,7 @@ def start_active_span(
148
150
finish_on_close = True ,
149
151
):
150
152
if opentracing is None :
151
- return _noop_context_manager
153
+ return _noop_context_manager ()
152
154
else :
153
155
# We need to enter the scope here for the logcontext to become active
154
156
return opentracing .tracer .start_active_span (
@@ -232,6 +234,9 @@ def start_active_span_from_context(
232
234
# Twisted encodes the values as lists whereas opentracing doesn't.
233
235
# So, we take the first item in the list.
234
236
# Also, twisted uses byte arrays while opentracing expects strings.
237
+ if opentracing is None :
238
+ return _noop_context_manager ()
239
+
235
240
header_dict = {k .decode (): v [0 ].decode () for k , v in headers .getAllRawHeaders ()}
236
241
context = opentracing .tracer .extract (opentracing .Format .HTTP_HEADERS , header_dict )
237
242
@@ -313,7 +318,7 @@ def trace_servlet(func):
313
318
@wraps (func )
314
319
@defer .inlineCallbacks
315
320
def f (request , * args , ** kwargs ):
316
- with start_active_span_from_context (
321
+ scope = start_active_span_from_context (
317
322
request .requestHeaders ,
318
323
"incoming-client-request" ,
319
324
tags = {
@@ -323,8 +328,16 @@ def f(request, *args, **kwargs):
323
328
tags .HTTP_URL : request .get_redacted_uri (),
324
329
tags .PEER_HOST_IPV6 : request .getClientIP (),
325
330
},
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 :
327
338
result = yield defer .maybeDeferred (func , request , * args , ** kwargs )
328
339
defer .returnValue (result )
340
+ finally :
341
+ scope .__exit__ (None , None , None )
329
342
330
343
return f
0 commit comments