Skip to content

Commit

Permalink
Fix exception in Urllib3 when dealing with filelike body.
Browse files Browse the repository at this point in the history
  • Loading branch information
isra17 committed Oct 23, 2022
1 parent 99f29b4 commit 5432fbb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#1252](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1252))
- Fix bug in Falcon instrumentation
([#1377](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1377))
- Fix exception in Urllib3 when dealing with filelike body.
([#1399](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1399))


### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def response_hook(span, request, response):
---
"""

import collections.abc
import contextlib
import typing
from timeit import default_timer
Expand Down Expand Up @@ -212,7 +213,11 @@ 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 = None
if body is None:
request_size = 0
elif isinstance(body, collections.abc.Sized):
request_size = len(body)
response_size = int(response.headers.get("Content-Length", 0))
metric_attributes = _create_metric_attributes(
instance, response, method
Expand All @@ -221,9 +226,10 @@ def instrumented_urlopen(wrapped, instance, args, kwargs):
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
import json
import typing
from io import BytesIO
from unittest import mock

import httpretty
Expand Down Expand Up @@ -309,3 +310,11 @@ def request_hook(span, request, headers, body):
)
self.assertIn("request_hook_body", span.attributes)
self.assertEqual(span.attributes["request_hook_body"], body)

def test_request_body_stream(self):
URLLib3Instrumentor().uninstrument()
URLLib3Instrumentor().instrument()
body = BytesIO(b"123")

pool = urllib3.HTTPConnectionPool("httpbin.org")
pool.request("POST", "/status/200", body=body)

0 comments on commit 5432fbb

Please sign in to comment.