Files with multi-byte characters are incompletely uploaded to S3 in python3
This bug was very elusive. I found it while moving our codebase (a large Django project) from Python 2.7 to Python 3.4. Everything seemed to work fine until I ran collectstatic in a production-like environment (one that actually uses boto to upload static files to S3). After several files uploaded successfully, I hit a stack trace ending with:
boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not match what we received.</Message><ExpectedDigest>R6/m+29/k2l39Le20oh0Dw==</ExpectedDigest><CalculatedDigest>A+iwzvzxQCkrYxlBLPqrfQ==</CalculatedDigest><RequestId>833B8C528965ABA7</RequestId><HostId>CT5inl5sUSl69I/pvPjK8ARAUmMNaTtZv0hpgBazmmfRxHLZ3k1YJSLkEGPLdENo</HostId></Error>I made sure there were no network problems, and I made sure the file wasn't changing while I was uploading it. I was stumped, but I knew it had been caused by the py2 to py3 switch, so it was probably related to encoding (bytes vs. text). I opened up the boto source and started using ipdb to catch the exception and poke around (ipython3 --pdb -c "%run manage.py collectstatic").
I found that the file causing the stack trace could not be encoded into ASCII, so I knew I was on the right track. The current chunk looked like it was cut off at the end, and there were four more characters left to be read from fp (even though we had already finished sending data to S3):
ipdb> fp.read()
'em}\n'Incomplete uploads could definitely cause an MD5 mismatch, so I checked the hashes myself. The "expected" digest was equal to the MD5 hash of the entire file, and the "calculated" digest was equal to the MD5 hash of the entire file minus the last 4 bytes:
ipdb> from hashlib import md5
ipdb> from binascii import b2a_base64
ipdb> m = md5(fp.file.getvalue().encode('utf-8'))
ipdb> b2a_base64(m.digest())
b'MfM1IbuOE59u/TYoKmFujQ==\n'
ipdb> m = md5(fp.file.getvalue()[:-4].encode('utf-8'))
ipdb> b2a_base64(m.digest())
b'XWWuj34xbuJ7OubGdyqXmQ==\n'
ipdb> body
b'<?xml version="1.0" encoding="UTF-8"?>\n<Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not match what we received.</Message><ExpectedDigest>MfM1IbuOE59u/TYoKmFujQ==</ExpectedDigest><CalculatedDigest>XWWuj34xbuJ7OubGdyqXmQ==</CalculatedDigest><RequestId>18AB6DDB4EE83FB0</RequestId><HostId>iiYQ2OX6dO/eNTPMYua5PUDzUxaprWzNPlkByxPWt2NNMRdGDn8BhkZ5xyRfMy1FBMw6G+8ay14=</HostId></Error>'So, why were there 4 bytes left in the buffer that we did not upload? Suspecting encoding issues, I checked the count of characters (text) in the file's string representation vs. the count of UTF-8 bytes in the encoded file:
ipdb> len(fp.file.getvalue())
34456
ipdb> len(fp.file.getvalue().encode('utf-8'))
34460There's our culprit. Digging into the boto source, this part of boto.s3.key.Key._send_file_internal() is where things go wrong:
bytes_togo = size
if bytes_togo and bytes_togo < self.BufferSize:
chunk = fp.read(bytes_togo)
else:
chunk = fp.read(self.BufferSize)
if not isinstance(chunk, bytes):
chunk = chunk.encode('utf-8')So, fp.read() takes a number of characters to read (incorrectly named bytes_togo) and returns a string (text), which is assigned as the value of chunk. Then chunk gets encoded into UTF-8, so if it contains any characters that take more than one byte to represent, len(chunk) will be larger after this encoding step. That means, after we send the chunk to S3, when we use bytes_togo -= chunk_len, we are subtracting more than we intended to. bytes_togo reaches zero before it should, and we never send the rest of the file. It's always incomplete by n characters, where n is the number of extra bytes needed to represent all the file's unicode characters in UTF-8.
Source: boto/boto