Skip to content

Commit befea19

Browse files
committed
Fix exception in Urllib3 when dealing with filelike body.
1 parent a7bd563 commit befea19

File tree

3 files changed

+222
-146
lines changed

3 files changed

+222
-146
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## Unreleased
99

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

1215
- Add connection attributes to sqlalchemy connect span

instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py

+18-4
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ def response_hook(span, request, response):
6464
---
6565
"""
6666

67+
import collections.abc
6768
import contextlib
69+
import io
6870
import typing
6971
from timeit import default_timer
7072
from typing import Collection
@@ -213,18 +215,20 @@ def instrumented_urlopen(wrapped, instance, args, kwargs):
213215
if callable(response_hook):
214216
response_hook(span, instance, response)
215217

216-
request_size = 0 if body is None else len(body)
218+
request_size = _get_body_size(body)
217219
response_size = int(response.headers.get("Content-Length", 0))
220+
218221
metric_attributes = _create_metric_attributes(
219222
instance, response, method
220223
)
221224

222225
duration_histogram.record(
223226
elapsed_time, attributes=metric_attributes
224227
)
225-
request_size_histogram.record(
226-
request_size, attributes=metric_attributes
227-
)
228+
if request_size is not None:
229+
request_size_histogram.record(
230+
request_size, attributes=metric_attributes
231+
)
228232
response_size_histogram.record(
229233
response_size, attributes=metric_attributes
230234
)
@@ -268,6 +272,16 @@ def _get_url(
268272
return url
269273

270274

275+
def _get_body_size(body: object) -> typing.Optional[int]:
276+
if body is None:
277+
return 0
278+
if isinstance(body, collections.abc.Sized):
279+
return len(body)
280+
if isinstance(body, io.BytesIO):
281+
return body.getbuffer().nbytes
282+
return None
283+
284+
271285
def _should_append_port(scheme: str, port: typing.Optional[int]) -> bool:
272286
if not port:
273287
return False

0 commit comments

Comments
 (0)