diff --git a/CHANGES.rst b/CHANGES.rst index 048d163435..123facf07b 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -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) diff --git a/libcloud/storage/base.py b/libcloud/storage/base.py index 0c872bb830..596b9ebd8f 100644 --- a/libcloud/storage/base.py +++ b/libcloud/storage/base.py @@ -19,6 +19,7 @@ # Backward compatibility for Python 2.5 +import io import errno import hashlib import os.path # pylint: disable-msg=W0404 @@ -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, ) @@ -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 diff --git a/libcloud/test/storage/test_base.py b/libcloud/test/storage/test_base.py index 17ff2c2a53..9b7286c230 100644 --- a/libcloud/test/storage/test_base.py +++ b/libcloud/test/storage/test_base.py @@ -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")