Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

opentelemetry-instrumentation-asgi: always set status code on duration attributes #2627

Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#2612](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2612))
- `opentelemetry-instrumentation-system-metrics` Permit to use psutil 6.0+.
([#2630](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2630))
- `opentelemetry-instrumentation-asgi` Bugfix: Middleware did not set status code attribute on duration metrics for non-recording spans.
([#2627](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/2627))


### Added

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,19 @@ def get_host_port_url_tuple(scope):
return server_host, port, http_url


def maybe_inject_context(message, server_span, setter):
lzchen marked this conversation as resolved.
Show resolved Hide resolved
"""Inject the context if there's a global propagator."""
propagator = get_global_response_propagator()
if propagator:
propagator.inject(
message,
context=set_span_in_context(
server_span, trace.context_api.Context()
),
setter=setter,
)


def set_status_code(span, status_code):
"""Adds HTTP response attributes to span using the status_code argument."""
if not span.is_recording():
Expand Down Expand Up @@ -696,19 +709,23 @@ async def otel_send(message: dict[str, Any]):
) as send_span:
if callable(self.client_response_hook):
self.client_response_hook(send_span, scope, message)

status_code = None
if message["type"] == "http.response.start":
status_code = message["status"]
elif message["type"] == "websocket.send":
status_code = 200
Comment on lines +841 to +842
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anything... It should be 101, not 200.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please open an issue or a PR, I don't think many people will see a comment on a PR closed months ago.

if status_code:
xrmx marked this conversation as resolved.
Show resolved Hide resolved
duration_attrs[SpanAttributes.HTTP_STATUS_CODE] = (
status_code
)

if send_span.is_recording():
if message["type"] == "http.response.start":
status_code = message["status"]
duration_attrs[SpanAttributes.HTTP_STATUS_CODE] = (
status_code
)
expecting_trailers = message.get("trailers", False)
if status_code:
set_status_code(server_span, status_code)
set_status_code(send_span, status_code)

expecting_trailers = message.get("trailers", False)
elif message["type"] == "websocket.send":
set_status_code(server_span, 200)
set_status_code(send_span, 200)
send_span.set_attribute("asgi.event.type", message["type"])
if (
server_span.is_recording()
Expand All @@ -730,15 +747,11 @@ async def otel_send(message: dict[str, Any]):
custom_response_attributes
)

propagator = get_global_response_propagator()
if propagator:
propagator.inject(
message,
context=set_span_in_context(
server_span, trace.context_api.Context()
),
setter=asgi_setter,
)
maybe_inject_context(
message,
server_span=server_span,
setter=asgi_setter,
)

content_length = asgi_getter.get(message, "content-length")
if content_length:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,9 @@ def test_asgi_not_recording(self):
mock_span = mock.Mock()
mock_span.is_recording.return_value = False
mock_tracer.start_as_current_span.return_value = mock_span
mock_tracer.start_as_current_span.return_value.__enter__ = mock_span
mock_tracer.start_as_current_span.return_value.__enter__ = mock.Mock(
return_value=mock_span
)
mock_tracer.start_as_current_span.return_value.__exit__ = mock_span
with mock.patch("opentelemetry.trace.get_tracer") as tracer:
tracer.return_value = mock_tracer
Expand Down Expand Up @@ -799,6 +801,65 @@ def test_basic_metric_success(self):
)
self.assertEqual(point.value, 0)

def test_basic_metric_success_nonrecording_span(self):
mock_tracer = mock.Mock()
mock_span = mock.Mock()
mock_span.is_recording.return_value = False
mock_tracer.start_as_current_span.return_value = mock_span
mock_tracer.start_as_current_span.return_value.__enter__ = mock.Mock(
return_value=mock_span
)
mock_tracer.start_as_current_span.return_value.__exit__ = mock_span
with mock.patch("opentelemetry.trace.get_tracer") as tracer:
tracer.return_value = mock_tracer
app = otel_asgi.OpenTelemetryMiddleware(simple_asgi)
self.seed_app(app)
start = default_timer()
self.send_default_request()
duration = max(round((default_timer() - start) * 1000), 0)
expected_duration_attributes = {
"http.method": "GET",
"http.host": "127.0.0.1",
"http.scheme": "http",
"http.flavor": "1.0",
"net.host.port": 80,
"http.status_code": 200,
}
expected_requests_count_attributes = {
"http.method": "GET",
"http.host": "127.0.0.1",
"http.scheme": "http",
"http.flavor": "1.0",
}
metrics_list = self.memory_metrics_reader.get_metrics_data()
# pylint: disable=too-many-nested-blocks
for resource_metric in metrics_list.resource_metrics:
for scope_metrics in resource_metric.scope_metrics:
for metric in scope_metrics.metrics:
for point in list(metric.data.data_points):
if isinstance(point, HistogramDataPoint):
self.assertDictEqual(
expected_duration_attributes,
dict(point.attributes),
)
self.assertEqual(point.count, 1)
if metric.name == "http.server.duration":
self.assertAlmostEqual(
duration, point.sum, delta=5
)
elif (
metric.name == "http.server.response.size"
):
self.assertEqual(1024, point.sum)
elif metric.name == "http.server.request.size":
self.assertEqual(128, point.sum)
elif isinstance(point, NumberDataPoint):
self.assertDictEqual(
expected_requests_count_attributes,
dict(point.attributes),
)
self.assertEqual(point.value, 0)

def test_metric_target_attribute(self):
expected_target = "/api/user/{id}"

Expand Down