Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
9 changes: 9 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ Compute
Storage
~~~~~~~

- [Storage] Fix ``upload_object_via_stream`` failing with ``UnicodeEncodeError``
or uploading truncated data when the stream yields text (e.g. a file opened
in text mode) which contains non-ASCII characters. Text is now encoded as
UTF-8 before it's sent, which matches how the object hash is calculated.
This affects drivers which upload a stream in a single request, such as
Google Storage and CloudFiles.
(GITHUB-1802)
[Shayn Hornik - @shaynhornik]

- [Local Storage] Delete the partially written file when ``download_object_range``
fails and ``delete_on_failure`` is set.
(GITHUB-2223)
Expand Down
31 changes: 30 additions & 1 deletion libcloud/storage/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

# Backward compatibility for Python 2.5

import io
import errno
import hashlib
import os.path # pylint: disable-msg=W0404
Expand Down Expand Up @@ -826,7 +827,7 @@ def _upload_object(
response = self.connection.request(
request_path,
method=request_method,
data=stream,
data=self._get_stream_request_data(stream),
headers=headers,
raw=True,
)
Expand Down Expand Up @@ -868,6 +869,34 @@ def _determine_content_type(self, content_type, object_name, file_path=None):

return content_type or DEFAULT_CONTENT_TYPE

def _get_stream_request_data(self, stream):
"""
Return an object which is used as a request body when uploading the
provided stream.

Text (``str``) chunks are encoded as UTF-8, which is the same encoding
that is used when calculating the hash of the uploaded data. Left to
the HTTP client, text is either encoded as latin-1 or sent with a
content length which doesn't match the encoded data.

:param stream: Stream passed to :meth:`_upload_object`.
:type stream: :class:`object`

:return: Provided stream or a generator which yields ``bytes``.
:rtype: :class:`object`
"""
if isinstance(stream, io.TextIOBase):
# File-like object opened in text mode. It's read in chunks so the
# whole stream is never buffered in memory.
chunks = iter(lambda: stream.read(CHUNK_SIZE), "")
elif hasattr(stream, "read"):
# Binary file-like object, it's sent as-is
return stream
else:
chunks = stream

return (b(chunk) if isinstance(chunk, str) else chunk for chunk in chunks)

def _hash_buffered_stream(self, stream, hasher, blocksize=65536):
total_len = 0

Expand Down
62 changes: 62 additions & 0 deletions libcloud/test/storage/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,68 @@ def test_upload_object_via_stream_illegal_seek_errors_are_ignored(self):
stream=iterator,
)

def _upload_object_and_capture_sent_chunks(self, stream):
sent_chunks = []

def mock_request(*args, **kwargs):
sent_chunks.extend(kwargs["data"])
return Mock()

self.driver1.connection = Mock()
self.driver1.connection.request.side_effect = mock_request

result = self.driver1._upload_object(
object_name="test.csv", content_type=None, request_path="/", stream=stream
)

return result, sent_chunks

def test_upload_object_via_stream_text_file_like_object_is_sent_as_utf8(self):
# Text needs to be sent as UTF-8, same as it's hashed, instead of
# leaving the encoding to the HTTP client
content = "id,value\n1,\u201cfoo\u201d\n2,bar\u2019s \u00e9\n" * 1000
expected_data = content.encode("utf-8")
self.assertNotEqual(len(expected_data), len(content))

hasher = hashlib.md5() # nosec
hasher.update(expected_data)
expected_hash = hasher.hexdigest()

with tempfile.TemporaryDirectory() as temp_dir:
file_path = os.path.join(temp_dir, "test.csv")

with open(file_path, "w", encoding="utf-8") as fp:
fp.write(content)

with open(file_path, encoding="utf-8") as text_file:
for stream in [StringIO(content), text_file]:
result, sent_chunks = self._upload_object_and_capture_sent_chunks(stream)

# Stream is read in chunks and not buffered in memory
self.assertGreater(len(sent_chunks), 1)
self.assertTrue(all(isinstance(chunk, bytes) for chunk in sent_chunks))
self.assertEqual(b"".join(sent_chunks), expected_data)
self.assertEqual(result["data_hash"], expected_hash)
self.assertEqual(result["bytes_transferred"], len(expected_data))

def test_upload_object_via_stream_text_iterator_is_sent_as_utf8(self):
chunks = ["id,value\n", "1,\u201cfoo\u201d\n", "2,bar\u2019s \u00e9\n"]
expected_chunks = [chunk.encode("utf-8") for chunk in chunks]

_, sent_chunks = self._upload_object_and_capture_sent_chunks(iter(chunks))
self.assertEqual(sent_chunks, expected_chunks)

def test_upload_object_via_stream_binary_stream_is_sent_as_is(self):
# Binary file-like objects are not wrapped so the HTTP client can
# still determine the content length
stream = BytesIO(b"\xe2\x80\x9cfoo\xe2\x80\x9d")
self._upload_object_and_capture_sent_chunks(stream)
self.assertIs(self.driver1.connection.request.call_args[-1]["data"], stream)

chunks = [b"\xe2\x80\x9cfoo", b"\xe2\x80\x9d"]
_, sent_chunks = self._upload_object_and_capture_sent_chunks(iter(chunks))
self.assertEqual(sent_chunks, chunks)

def test_get_standard_range_str(self):
result = self.driver1._get_standard_range_str(0, 5)
self.assertEqual(result, "bytes=0-4")
Expand Down