Skip to content

Commit

Permalink
code changes to resolve conditional server span creation for WSGI (op…
Browse files Browse the repository at this point in the history
  • Loading branch information
sanketmehta28 committed Feb 5, 2022
1 parent 0b9e96d commit 190f562
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,17 @@ def __call__(self, environ, start_response):
start_response: The WSGI start_response callable.
"""

token = context.attach(extract(environ, getter=wsgi_getter))
token = ctx = None
span_kind = trace.SpanKind.INTERNAL
if trace.get_current_span() is trace.INVALID_SPAN:
ctx = extract(environ, getter=wsgi_getter)
token = context.attach(ctx)
span_kind = trace.SpanKind.SERVER

span = self.tracer.start_span(
get_default_span_name(environ),
kind=trace.SpanKind.SERVER,
context=ctx,
kind=span_kind,
attributes=collect_request_attributes(environ),
)

Expand All @@ -308,7 +314,8 @@ def __call__(self, environ, start_response):
if span.is_recording():
span.set_status(Status(StatusCode.ERROR, str(ex)))
span.end()
context.detach(token)
if token is not None:
context.detach(token)
raise


Expand All @@ -324,7 +331,8 @@ def _end_span_after_iterating(iterable, span, tracer, token):
if close:
close()
span.end()
context.detach(token)
if token is not None:
context.detach(token)


# TODO: inherit from opentelemetry.instrumentation.propagators.Setter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,5 +414,35 @@ def test_basic_wsgi_call(self):
self.validate_response(response, exporter)


class TestWsgiMiddlewareWrappedWithAnotherFramework(WsgiTestBase):
def test_mark_span_internal_in_presence_of_span_from_other_framework(self):
tracer_provider, exporter = TestBase.create_tracer_provider()
tracer = tracer_provider.get_tracer(__name__)

with tracer.start_as_current_span(
"test", kind=trace_api.SpanKind.SERVER
) as parent_span:
app = otel_wsgi.OpenTelemetryMiddleware(
simple_wsgi, tracer_provider=tracer_provider
)
response = app(self.environ, self.start_response)
while True:
try:
value = next(response)
self.assertEqual(value, b"*")
except StopIteration:
break

span_list = exporter.get_finished_spans()

self.assertEqual(trace_api.SpanKind.INTERNAL, span_list[0].kind)
self.assertEqual(trace_api.SpanKind.SERVER, parent_span.kind)

# internal span should be child of the parent span we have provided
self.assertEqual(
parent_span.context.span_id, span_list[0].parent.span_id
)


if __name__ == "__main__":
unittest.main()

0 comments on commit 190f562

Please sign in to comment.