-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathupload.py
280 lines (227 loc) · 10.4 KB
/
upload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import http.client
import logging
import math
import os
from dataclasses import dataclass
from enum import Enum
from hashlib import md5
from urllib.parse import urlparse
MAX_PAGE_SIZE = 1000
MIN_PART_SIZE = 5 * 1024 * 1024
MAX_FILE_SIZE = 25 * 1000 * 1024 * 1024
class UploadType(Enum):
"""
This class stores the enum values for the different type of uploads.
"""
direct = "direct"
multipart = "multipart"
@dataclass
class UploadContext:
"""
This class stores the structure for an upload context so that it can be resumed later.
"""
def __init__(self, upload_method, upload_id, upload_token, direct_link):
self.upload_method = upload_method
self.upload_id = upload_id
self.upload_token = upload_token
self.direct_link = direct_link
"""
This method evaluates whether an upload can be resumed based on the upload context state
"""
def can_resume(self) -> bool:
return self.upload_token is not None \
and self.upload_method == UploadType.multipart.value \
and self.upload_id is not None
def _upload_to_s3(bytes_chunk, upload_link):
url_metadata = urlparse(upload_link)
if url_metadata.scheme in 'https':
connection = http.client.HTTPSConnection(host=url_metadata.hostname)
else:
connection = http.client.HTTPConnection(host=url_metadata.hostname)
connection.request('PUT', upload_link, body=bytes_chunk)
response = connection.getresponse()
if 200 <= response.status <= 299:
return response
raise S3UploadError(response)
def _get_bytes_hash(bytes_chunk):
return md5(bytes_chunk).hexdigest()
def _get_returned_hash(response):
return response.headers['ETag']
class MultipartUpload:
"""
This class manages the multi-part upload.
"""
def __init__(self, client, file, target_part_size, retry_count, upload_context: UploadContext):
self._upload_id = upload_context.upload_id
self._target_part_size = target_part_size
self._upload_retry_count = retry_count
self._file = file
self._client = client
self._logger = logging.getLogger(self.__class__.__name__)
self._upload_context = upload_context
@property
def upload_context(self):
return self._upload_context
@upload_context.setter
def upload_context(self, value):
self._upload_context = value
def upload(self):
"""
This methods uploads the parts for the multi-part upload.
Returns:
"""
if self._target_part_size < MIN_PART_SIZE:
raise ValueError(f"The part size has to be at least greater than {MIN_PART_SIZE} bytes.")
filename = self._file.name
file_size = os.stat(filename).st_size
part_count = math.ceil(file_size / self._target_part_size)
if part_count > 10000:
raise ValueError("The given file cannot be divided into more than 10000 parts. Please try increasing the "
"target part size.")
# Upload the parts
self._upload_parts(part_count)
# Mark upload as complete
self._mark_upload_completion()
def _upload_parts(self, part_count):
try:
filename = self._file.name
remaining_parts_count = part_count
total_page_count = math.ceil(part_count / MAX_PAGE_SIZE)
for page_number in range(1, total_page_count + 1):
batch_size = min(remaining_parts_count, MAX_PAGE_SIZE)
page_length = MAX_PAGE_SIZE
remaining_parts_count = remaining_parts_count - batch_size
query_params = {'page_length': page_length, 'page': page_number}
self._logger.debug(
f'calling list method with page_number:{page_number} and page_length:{page_length}.')
body = self._retrieve_part_links(query_params)
upload_links = body['parts']
for returned_part in upload_links[:batch_size]:
part_number = returned_part['id']
bytes_chunk = self._file.read(self._target_part_size)
if part_number < batch_size and len(bytes_chunk) != self._target_part_size:
raise IOError("Failed to read enough bytes")
retry_count = 0
for _ in range(self._upload_retry_count):
try:
self._upload_part(bytes_chunk, part_number, returned_part)
self._logger.debug(
f"Successfully uploaded part {(page_number - 1) * MAX_PAGE_SIZE + part_number} "
f"of {part_count} for upload id {self._upload_id}")
break
except (DataIntegrityError, PartUploadError, OSError) as err:
self._logger.warning(err)
retry_count = retry_count + 1
self._logger.warning(
f"Encountered error upload part {(page_number - 1) * MAX_PAGE_SIZE + part_number} "
f"of {part_count} for file {filename}.")
if retry_count >= self._upload_retry_count:
self._file.seek(0, 0)
raise MaxRetriesExceededError(
f"Max retries ({self._upload_retry_count}) exceeded while uploading part"
f" {part_number} of {part_count} for file {filename}.") from err
except Exception as ex:
self._file.seek(0, 0)
self._logger.exception(ex)
raise
def _retrieve_part_links(self, query_params):
resp = self._client.list(upload_id=self._upload_id, query_params=query_params)
return resp.json_body
def _upload_part(self, bytes_chunk, part_number, returned_part):
computed_hash = _get_bytes_hash(bytes_chunk)
# Check if the file has already been uploaded and the hash matches. Return immediately without doing anything
# if the hash matches.
upload_hash = self._get_uploaded_part_hash(returned_part)
if upload_hash and (repr(upload_hash) == repr(f"{computed_hash}")): # returned hash is not surrounded by '"'
self._logger.debug(f"Part number {part_number} already uploaded. Skipping")
return
if upload_hash:
raise UnrecoverableError(f'The file part {part_number} has been uploaded but the hash of the uploaded part '
f'does not match the hash of the current part read. Aborting.')
if "upload_link" not in returned_part:
raise KeyError(f"Invalid upload link for part {part_number}.")
returned_part = returned_part["upload_link"]
response = _upload_to_s3(bytes_chunk, returned_part)
returned_hash = _get_returned_hash(response)
if repr(returned_hash) != repr(f"\"{computed_hash}\""): # The returned hash is surrounded by '"' character
raise DataIntegrityError("The hash of the uploaded file does not match with the hash on the server.")
def _get_uploaded_part_hash(self, upload_link):
upload_hash = upload_link.get("etag")
return upload_hash
def _mark_upload_completion(self):
self._client.complete(self._upload_id)
self._logger.info("Upload successful!")
class SingleUpload:
"""
This class manages the operations related to the upload of a media file via a direct link.
"""
def __init__(self, upload_link, file, retry_count, upload_context: UploadContext):
self._upload_link = upload_link
self._upload_retry_count = retry_count
self._file = file
self._logger = logging.getLogger(self.__class__.__name__)
self._upload_context = upload_context
@property
def upload_context(self):
return self._upload_context
@upload_context.setter
def upload_context(self, value):
self._upload_context = value
def upload(self):
"""
Uploads the media file to the actual location as specified in the direct link.
Returns:
"""
self._logger.debug(f"Starting to upload file:{self._file.name}")
bytes_chunk = self._file.read()
computed_hash = _get_bytes_hash(bytes_chunk)
retry_count = 0
for _ in range(self._upload_retry_count):
try:
response = _upload_to_s3(bytes_chunk, self._upload_link)
returned_hash = _get_returned_hash(response)
# The returned hash is surrounded by '"' character
if repr(returned_hash) != repr(f"\"{computed_hash}\""):
raise DataIntegrityError(
"The hash of the uploaded file does not match with the hash on the server.")
self._logger.debug(f"Successfully uploaded file {self._file.name}.")
return
except (IOError, PartUploadError, DataIntegrityError, OSError) as err:
self._logger.warning(err)
self._logger.exception(err, stack_info=True)
self._logger.warning(f"Encountered error uploading file {self._file.name}.")
retry_count = retry_count + 1
if retry_count >= self._upload_retry_count:
self._file.seek(0, 0)
raise MaxRetriesExceededError(f"Max retries exceeded while uploading file {self._file.name}") \
from err
except Exception as ex:
self._file.seek(0, 0)
self._logger.exception(ex)
raise
class DataIntegrityError(Exception):
"""
This class is used to wrap exceptions when the uploaded data failed a data integrity check with the current file
part hash.
"""
pass
class MaxRetriesExceededError(Exception):
"""
This class is used to wrap exceptions when the number of retries are exceeded while uploading a part.
"""
pass
class PartUploadError(Exception):
"""
This class is used to wrap exceptions that occur because of part upload errors.
"""
pass
class S3UploadError(PartUploadError):
"""
This class extends the PartUploadError exception class when the upload is done via S3.
"""
pass
class UnrecoverableError(Exception):
"""
This class wraps exceptions that should not be recoverable or resumed from.
"""
pass