Skip to content

Commit

Permalink
Fix exception in Urllib3 when dealing with filelike body. (open-telem…
Browse files Browse the repository at this point in the history
  • Loading branch information
isra17 authored and pridhi-arora committed Feb 25, 2023
1 parent 20ea491 commit 92f7a15
Show file tree
Hide file tree
Showing 3 changed files with 222 additions and 146 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

- Fix exception in Urllib3 when dealing with filelike body.
([#1399](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1399))

### Added

- Add connection attributes to sqlalchemy connect span
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ def response_hook(span, request, response):
---
"""

import collections.abc
import contextlib
import io
import typing
from timeit import default_timer
from typing import Collection
Expand Down Expand Up @@ -213,18 +215,20 @@ def instrumented_urlopen(wrapped, instance, args, kwargs):
if callable(response_hook):
response_hook(span, instance, response)

request_size = 0 if body is None else len(body)
request_size = _get_body_size(body)
response_size = int(response.headers.get("Content-Length", 0))

metric_attributes = _create_metric_attributes(
instance, response, method
)

duration_histogram.record(
elapsed_time, attributes=metric_attributes
)
request_size_histogram.record(
request_size, attributes=metric_attributes
)
if request_size is not None:
request_size_histogram.record(
request_size, attributes=metric_attributes
)
response_size_histogram.record(
response_size, attributes=metric_attributes
)
Expand Down Expand Up @@ -268,6 +272,16 @@ def _get_url(
return url


def _get_body_size(body: object) -> typing.Optional[int]:
if body is None:
return 0
if isinstance(body, collections.abc.Sized):
return len(body)
if isinstance(body, io.BytesIO):
return body.getbuffer().nbytes
return None


def _should_append_port(scheme: str, port: typing.Optional[int]) -> bool:
if not port:
return False
Expand Down
Loading

0 comments on commit 92f7a15

Please sign in to comment.