resumable_upload_handler.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. # Copyright 2010 Google Inc.
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a
  4. # copy of this software and associated documentation files (the
  5. # "Software"), to deal in the Software without restriction, including
  6. # without limitation the rights to use, copy, modify, merge, publish, dis-
  7. # tribute, sublicense, and/or sell copies of the Software, and to permit
  8. # persons to whom the Software is furnished to do so, subject to the fol-
  9. # lowing conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included
  12. # in all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  16. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  17. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. # IN THE SOFTWARE.
  21. import errno
  22. import httplib
  23. import os
  24. import random
  25. import re
  26. import socket
  27. import time
  28. import urlparse
  29. from hashlib import md5
  30. from boto import config, UserAgent
  31. from boto.connection import AWSAuthConnection
  32. from boto.exception import InvalidUriError
  33. from boto.exception import ResumableTransferDisposition
  34. from boto.exception import ResumableUploadException
  35. from boto.s3.keyfile import KeyFile
  36. """
  37. Handler for Google Cloud Storage resumable uploads. See
  38. http://code.google.com/apis/storage/docs/developer-guide.html#resumable
  39. for details.
  40. Resumable uploads will retry failed uploads, resuming at the byte
  41. count completed by the last upload attempt. If too many retries happen with
  42. no progress (per configurable num_retries param), the upload will be
  43. aborted in the current process.
  44. The caller can optionally specify a tracker_file_name param in the
  45. ResumableUploadHandler constructor. If you do this, that file will
  46. save the state needed to allow retrying later, in a separate process
  47. (e.g., in a later run of gsutil).
  48. """
  49. class ResumableUploadHandler(object):
  50. BUFFER_SIZE = 8192
  51. RETRYABLE_EXCEPTIONS = (httplib.HTTPException, IOError, socket.error,
  52. socket.gaierror)
  53. # (start, end) response indicating server has nothing (upload protocol uses
  54. # inclusive numbering).
  55. SERVER_HAS_NOTHING = (0, -1)
  56. def __init__(self, tracker_file_name=None, num_retries=None):
  57. """
  58. Constructor. Instantiate once for each uploaded file.
  59. :type tracker_file_name: string
  60. :param tracker_file_name: optional file name to save tracker URI.
  61. If supplied and the current process fails the upload, it can be
  62. retried in a new process. If called with an existing file containing
  63. a valid tracker URI, we'll resume the upload from this URI; else
  64. we'll start a new resumable upload (and write the URI to this
  65. tracker file).
  66. :type num_retries: int
  67. :param num_retries: the number of times we'll re-try a resumable upload
  68. making no progress. (Count resets every time we get progress, so
  69. upload can span many more than this number of retries.)
  70. """
  71. self.tracker_file_name = tracker_file_name
  72. self.num_retries = num_retries
  73. self.server_has_bytes = 0 # Byte count at last server check.
  74. self.tracker_uri = None
  75. if tracker_file_name:
  76. self._load_tracker_uri_from_file()
  77. # Save upload_start_point in instance state so caller can find how
  78. # much was transferred by this ResumableUploadHandler (across retries).
  79. self.upload_start_point = None
  80. def _load_tracker_uri_from_file(self):
  81. f = None
  82. try:
  83. f = open(self.tracker_file_name, 'r')
  84. uri = f.readline().strip()
  85. self._set_tracker_uri(uri)
  86. except IOError as e:
  87. # Ignore non-existent file (happens first time an upload
  88. # is attempted on a file), but warn user for other errors.
  89. if e.errno != errno.ENOENT:
  90. # Will restart because self.tracker_uri is None.
  91. print('Couldn\'t read URI tracker file (%s): %s. Restarting '
  92. 'upload from scratch.' %
  93. (self.tracker_file_name, e.strerror))
  94. except InvalidUriError as e:
  95. # Warn user, but proceed (will restart because
  96. # self.tracker_uri is None).
  97. print('Invalid tracker URI (%s) found in URI tracker file '
  98. '(%s). Restarting upload from scratch.' %
  99. (uri, self.tracker_file_name))
  100. finally:
  101. if f:
  102. f.close()
  103. def _save_tracker_uri_to_file(self):
  104. """
  105. Saves URI to tracker file if one was passed to constructor.
  106. """
  107. if not self.tracker_file_name:
  108. return
  109. f = None
  110. try:
  111. with os.fdopen(os.open(self.tracker_file_name,
  112. os.O_WRONLY | os.O_CREAT, 0o600), 'w') as f:
  113. f.write(self.tracker_uri)
  114. except IOError as e:
  115. raise ResumableUploadException(
  116. 'Couldn\'t write URI tracker file (%s): %s.\nThis can happen'
  117. 'if you\'re using an incorrectly configured upload tool\n'
  118. '(e.g., gsutil configured to save tracker files to an '
  119. 'unwritable directory)' %
  120. (self.tracker_file_name, e.strerror),
  121. ResumableTransferDisposition.ABORT)
  122. def _set_tracker_uri(self, uri):
  123. """
  124. Called when we start a new resumable upload or get a new tracker
  125. URI for the upload. Saves URI and resets upload state.
  126. Raises InvalidUriError if URI is syntactically invalid.
  127. """
  128. parse_result = urlparse.urlparse(uri)
  129. if (parse_result.scheme.lower() not in ['http', 'https'] or
  130. not parse_result.netloc):
  131. raise InvalidUriError('Invalid tracker URI (%s)' % uri)
  132. self.tracker_uri = uri
  133. self.tracker_uri_host = parse_result.netloc
  134. self.tracker_uri_path = '%s?%s' % (
  135. parse_result.path, parse_result.query)
  136. self.server_has_bytes = 0
  137. def get_tracker_uri(self):
  138. """
  139. Returns upload tracker URI, or None if the upload has not yet started.
  140. """
  141. return self.tracker_uri
  142. def get_upload_id(self):
  143. """
  144. Returns the upload ID for the resumable upload, or None if the upload
  145. has not yet started.
  146. """
  147. # We extract the upload_id from the tracker uri. We could retrieve the
  148. # upload_id from the headers in the response but this only works for
  149. # the case where we get the tracker uri from the service. In the case
  150. # where we get the tracker from the tracking file we need to do this
  151. # logic anyway.
  152. delim = '?upload_id='
  153. if self.tracker_uri and delim in self.tracker_uri:
  154. return self.tracker_uri[self.tracker_uri.index(delim) + len(delim):]
  155. else:
  156. return None
  157. def _remove_tracker_file(self):
  158. if (self.tracker_file_name and
  159. os.path.exists(self.tracker_file_name)):
  160. os.unlink(self.tracker_file_name)
  161. def _build_content_range_header(self, range_spec='*', length_spec='*'):
  162. return 'bytes %s/%s' % (range_spec, length_spec)
  163. def _query_server_state(self, conn, file_length):
  164. """
  165. Queries server to find out state of given upload.
  166. Note that this method really just makes special case use of the
  167. fact that the upload server always returns the current start/end
  168. state whenever a PUT doesn't complete.
  169. Returns HTTP response from sending request.
  170. Raises ResumableUploadException if problem querying server.
  171. """
  172. # Send an empty PUT so that server replies with this resumable
  173. # transfer's state.
  174. put_headers = {}
  175. put_headers['Content-Range'] = (
  176. self._build_content_range_header('*', file_length))
  177. put_headers['Content-Length'] = '0'
  178. return AWSAuthConnection.make_request(conn, 'PUT',
  179. path=self.tracker_uri_path,
  180. auth_path=self.tracker_uri_path,
  181. headers=put_headers,
  182. host=self.tracker_uri_host)
  183. def _query_server_pos(self, conn, file_length):
  184. """
  185. Queries server to find out what bytes it currently has.
  186. Returns (server_start, server_end), where the values are inclusive.
  187. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2.
  188. Raises ResumableUploadException if problem querying server.
  189. """
  190. resp = self._query_server_state(conn, file_length)
  191. if resp.status == 200:
  192. # To handle the boundary condition where the server has the complete
  193. # file, we return (server_start, file_length-1). That way the
  194. # calling code can always simply read up through server_end. (If we
  195. # didn't handle this boundary condition here, the caller would have
  196. # to check whether server_end == file_length and read one fewer byte
  197. # in that case.)
  198. return (0, file_length - 1) # Completed upload.
  199. if resp.status != 308:
  200. # This means the server didn't have any state for the given
  201. # upload ID, which can happen (for example) if the caller saved
  202. # the tracker URI to a file and then tried to restart the transfer
  203. # after that upload ID has gone stale. In that case we need to
  204. # start a new transfer (and the caller will then save the new
  205. # tracker URI to the tracker file).
  206. raise ResumableUploadException(
  207. 'Got non-308 response (%s) from server state query' %
  208. resp.status, ResumableTransferDisposition.START_OVER)
  209. got_valid_response = False
  210. range_spec = resp.getheader('range')
  211. if range_spec:
  212. # Parse 'bytes=<from>-<to>' range_spec.
  213. m = re.search('bytes=(\d+)-(\d+)', range_spec)
  214. if m:
  215. server_start = long(m.group(1))
  216. server_end = long(m.group(2))
  217. got_valid_response = True
  218. else:
  219. # No Range header, which means the server does not yet have
  220. # any bytes. Note that the Range header uses inclusive 'from'
  221. # and 'to' values. Since Range 0-0 would mean that the server
  222. # has byte 0, omitting the Range header is used to indicate that
  223. # the server doesn't have any bytes.
  224. return self.SERVER_HAS_NOTHING
  225. if not got_valid_response:
  226. raise ResumableUploadException(
  227. 'Couldn\'t parse upload server state query response (%s)' %
  228. str(resp.getheaders()), ResumableTransferDisposition.START_OVER)
  229. if conn.debug >= 1:
  230. print('Server has: Range: %d - %d.' % (server_start, server_end))
  231. return (server_start, server_end)
  232. def _start_new_resumable_upload(self, key, headers=None):
  233. """
  234. Starts a new resumable upload.
  235. Raises ResumableUploadException if any errors occur.
  236. """
  237. conn = key.bucket.connection
  238. if conn.debug >= 1:
  239. print('Starting new resumable upload.')
  240. self.server_has_bytes = 0
  241. # Start a new resumable upload by sending a POST request with an
  242. # empty body and the "X-Goog-Resumable: start" header. Include any
  243. # caller-provided headers (e.g., Content-Type) EXCEPT Content-Length
  244. # (and raise an exception if they tried to pass one, since it's
  245. # a semantic error to specify it at this point, and if we were to
  246. # include one now it would cause the server to expect that many
  247. # bytes; the POST doesn't include the actual file bytes We set
  248. # the Content-Length in the subsequent PUT, based on the uploaded
  249. # file size.
  250. post_headers = {}
  251. for k in headers:
  252. if k.lower() == 'content-length':
  253. raise ResumableUploadException(
  254. 'Attempt to specify Content-Length header (disallowed)',
  255. ResumableTransferDisposition.ABORT)
  256. post_headers[k] = headers[k]
  257. post_headers[conn.provider.resumable_upload_header] = 'start'
  258. resp = conn.make_request(
  259. 'POST', key.bucket.name, key.name, post_headers)
  260. # Get tracker URI from response 'Location' header.
  261. body = resp.read()
  262. # Check for various status conditions.
  263. if resp.status in [500, 503]:
  264. # Retry status 500 and 503 errors after a delay.
  265. raise ResumableUploadException(
  266. 'Got status %d from attempt to start resumable upload. '
  267. 'Will wait/retry' % resp.status,
  268. ResumableTransferDisposition.WAIT_BEFORE_RETRY)
  269. elif resp.status != 200 and resp.status != 201:
  270. raise ResumableUploadException(
  271. 'Got status %d from attempt to start resumable upload. '
  272. 'Aborting' % resp.status,
  273. ResumableTransferDisposition.ABORT)
  274. # Else we got 200 or 201 response code, indicating the resumable
  275. # upload was created.
  276. tracker_uri = resp.getheader('Location')
  277. if not tracker_uri:
  278. raise ResumableUploadException(
  279. 'No resumable tracker URI found in resumable initiation '
  280. 'POST response (%s)' % body,
  281. ResumableTransferDisposition.WAIT_BEFORE_RETRY)
  282. self._set_tracker_uri(tracker_uri)
  283. self._save_tracker_uri_to_file()
  284. def _upload_file_bytes(self, conn, http_conn, fp, file_length,
  285. total_bytes_uploaded, cb, num_cb, headers):
  286. """
  287. Makes one attempt to upload file bytes, using an existing resumable
  288. upload connection.
  289. Returns (etag, generation, metageneration) from server upon success.
  290. Raises ResumableUploadException if any problems occur.
  291. """
  292. buf = fp.read(self.BUFFER_SIZE)
  293. if cb:
  294. # The cb_count represents the number of full buffers to send between
  295. # cb executions.
  296. if num_cb > 2:
  297. cb_count = file_length / self.BUFFER_SIZE / (num_cb-2)
  298. elif num_cb < 0:
  299. cb_count = -1
  300. else:
  301. cb_count = 0
  302. i = 0
  303. cb(total_bytes_uploaded, file_length)
  304. # Build resumable upload headers for the transfer. Don't send a
  305. # Content-Range header if the file is 0 bytes long, because the
  306. # resumable upload protocol uses an *inclusive* end-range (so, sending
  307. # 'bytes 0-0/1' would actually mean you're sending a 1-byte file).
  308. if not headers:
  309. put_headers = {}
  310. else:
  311. put_headers = headers.copy()
  312. if file_length:
  313. if total_bytes_uploaded == file_length:
  314. range_header = self._build_content_range_header(
  315. '*', file_length)
  316. else:
  317. range_header = self._build_content_range_header(
  318. '%d-%d' % (total_bytes_uploaded, file_length - 1),
  319. file_length)
  320. put_headers['Content-Range'] = range_header
  321. # Set Content-Length to the total bytes we'll send with this PUT.
  322. put_headers['Content-Length'] = str(file_length - total_bytes_uploaded)
  323. http_request = AWSAuthConnection.build_base_http_request(
  324. conn, 'PUT', path=self.tracker_uri_path, auth_path=None,
  325. headers=put_headers, host=self.tracker_uri_host)
  326. http_conn.putrequest('PUT', http_request.path)
  327. for k in put_headers:
  328. http_conn.putheader(k, put_headers[k])
  329. http_conn.endheaders()
  330. # Turn off debug on http connection so upload content isn't included
  331. # in debug stream.
  332. http_conn.set_debuglevel(0)
  333. while buf:
  334. http_conn.send(buf)
  335. for alg in self.digesters:
  336. self.digesters[alg].update(buf)
  337. total_bytes_uploaded += len(buf)
  338. if cb:
  339. i += 1
  340. if i == cb_count or cb_count == -1:
  341. cb(total_bytes_uploaded, file_length)
  342. i = 0
  343. buf = fp.read(self.BUFFER_SIZE)
  344. http_conn.set_debuglevel(conn.debug)
  345. if cb:
  346. cb(total_bytes_uploaded, file_length)
  347. if total_bytes_uploaded != file_length:
  348. # Abort (and delete the tracker file) so if the user retries
  349. # they'll start a new resumable upload rather than potentially
  350. # attempting to pick back up later where we left off.
  351. raise ResumableUploadException(
  352. 'File changed during upload: EOF at %d bytes of %d byte file.' %
  353. (total_bytes_uploaded, file_length),
  354. ResumableTransferDisposition.ABORT)
  355. resp = http_conn.getresponse()
  356. # Restore http connection debug level.
  357. http_conn.set_debuglevel(conn.debug)
  358. if resp.status == 200:
  359. # Success.
  360. return (resp.getheader('etag'),
  361. resp.getheader('x-goog-generation'),
  362. resp.getheader('x-goog-metageneration'))
  363. # Retry timeout (408) and status 500 and 503 errors after a delay.
  364. elif resp.status in [408, 500, 503]:
  365. disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY
  366. else:
  367. # Catch all for any other error codes.
  368. disposition = ResumableTransferDisposition.ABORT
  369. raise ResumableUploadException('Got response code %d while attempting '
  370. 'upload (%s)' %
  371. (resp.status, resp.reason), disposition)
  372. def _attempt_resumable_upload(self, key, fp, file_length, headers, cb,
  373. num_cb):
  374. """
  375. Attempts a resumable upload.
  376. Returns (etag, generation, metageneration) from server upon success.
  377. Raises ResumableUploadException if any problems occur.
  378. """
  379. (server_start, server_end) = self.SERVER_HAS_NOTHING
  380. conn = key.bucket.connection
  381. if self.tracker_uri:
  382. # Try to resume existing resumable upload.
  383. try:
  384. (server_start, server_end) = (
  385. self._query_server_pos(conn, file_length))
  386. self.server_has_bytes = server_start
  387. if server_end:
  388. # If the server already has some of the content, we need to
  389. # update the digesters with the bytes that have already been
  390. # uploaded to ensure we get a complete hash in the end.
  391. print('Catching up hash digest(s) for resumed upload')
  392. fp.seek(0)
  393. # Read local file's bytes through position server has. For
  394. # example, if server has (0, 3) we want to read 3-0+1=4 bytes.
  395. bytes_to_go = server_end + 1
  396. while bytes_to_go:
  397. chunk = fp.read(min(key.BufferSize, bytes_to_go))
  398. if not chunk:
  399. raise ResumableUploadException(
  400. 'Hit end of file during resumable upload hash '
  401. 'catchup. This should not happen under\n'
  402. 'normal circumstances, as it indicates the '
  403. 'server has more bytes of this transfer\nthan'
  404. ' the current file size. Restarting upload.',
  405. ResumableTransferDisposition.START_OVER)
  406. for alg in self.digesters:
  407. self.digesters[alg].update(chunk)
  408. bytes_to_go -= len(chunk)
  409. if conn.debug >= 1:
  410. print('Resuming transfer.')
  411. except ResumableUploadException as e:
  412. if conn.debug >= 1:
  413. print('Unable to resume transfer (%s).' % e.message)
  414. self._start_new_resumable_upload(key, headers)
  415. else:
  416. self._start_new_resumable_upload(key, headers)
  417. # upload_start_point allows the code that instantiated the
  418. # ResumableUploadHandler to find out the point from which it started
  419. # uploading (e.g., so it can correctly compute throughput).
  420. if self.upload_start_point is None:
  421. self.upload_start_point = server_end
  422. total_bytes_uploaded = server_end + 1
  423. # Corner case: Don't attempt to seek if we've already uploaded the
  424. # entire file, because if the file is a stream (e.g., the KeyFile
  425. # wrapper around input key when copying between providers), attempting
  426. # to seek to the end of file would result in an InvalidRange error.
  427. if file_length < total_bytes_uploaded:
  428. fp.seek(total_bytes_uploaded)
  429. conn = key.bucket.connection
  430. # Get a new HTTP connection (vs conn.get_http_connection(), which reuses
  431. # pool connections) because httplib requires a new HTTP connection per
  432. # transaction. (Without this, calling http_conn.getresponse() would get
  433. # "ResponseNotReady".)
  434. http_conn = conn.new_http_connection(self.tracker_uri_host, conn.port,
  435. conn.is_secure)
  436. http_conn.set_debuglevel(conn.debug)
  437. # Make sure to close http_conn at end so if a local file read
  438. # failure occurs partway through server will terminate current upload
  439. # and can report that progress on next attempt.
  440. try:
  441. return self._upload_file_bytes(conn, http_conn, fp, file_length,
  442. total_bytes_uploaded, cb, num_cb,
  443. headers)
  444. except (ResumableUploadException, socket.error):
  445. resp = self._query_server_state(conn, file_length)
  446. if resp.status == 400:
  447. raise ResumableUploadException('Got 400 response from server '
  448. 'state query after failed resumable upload attempt. This '
  449. 'can happen for various reasons, including specifying an '
  450. 'invalid request (e.g., an invalid canned ACL) or if the '
  451. 'file size changed between upload attempts',
  452. ResumableTransferDisposition.ABORT)
  453. else:
  454. raise
  455. finally:
  456. http_conn.close()
  457. def _check_final_md5(self, key, etag):
  458. """
  459. Checks that etag from server agrees with md5 computed before upload.
  460. This is important, since the upload could have spanned a number of
  461. hours and multiple processes (e.g., gsutil runs), and the user could
  462. change some of the file and not realize they have inconsistent data.
  463. """
  464. if key.bucket.connection.debug >= 1:
  465. print('Checking md5 against etag.')
  466. if key.md5 != etag.strip('"\''):
  467. # Call key.open_read() before attempting to delete the
  468. # (incorrect-content) key, so we perform that request on a
  469. # different HTTP connection. This is neededb because httplib
  470. # will return a "Response not ready" error if you try to perform
  471. # a second transaction on the connection.
  472. key.open_read()
  473. key.close()
  474. key.delete()
  475. raise ResumableUploadException(
  476. 'File changed during upload: md5 signature doesn\'t match etag '
  477. '(incorrect uploaded object deleted)',
  478. ResumableTransferDisposition.ABORT)
  479. def handle_resumable_upload_exception(self, e, debug):
  480. if (e.disposition == ResumableTransferDisposition.ABORT_CUR_PROCESS):
  481. if debug >= 1:
  482. print('Caught non-retryable ResumableUploadException (%s); '
  483. 'aborting but retaining tracker file' % e.message)
  484. raise
  485. elif (e.disposition == ResumableTransferDisposition.ABORT):
  486. if debug >= 1:
  487. print('Caught non-retryable ResumableUploadException (%s); '
  488. 'aborting and removing tracker file' % e.message)
  489. self._remove_tracker_file()
  490. raise
  491. else:
  492. if debug >= 1:
  493. print('Caught ResumableUploadException (%s) - will retry' %
  494. e.message)
  495. def track_progress_less_iterations(self, server_had_bytes_before_attempt,
  496. roll_back_md5=True, debug=0):
  497. # At this point we had a re-tryable failure; see if made progress.
  498. if self.server_has_bytes > server_had_bytes_before_attempt:
  499. self.progress_less_iterations = 0 # If progress, reset counter.
  500. else:
  501. self.progress_less_iterations += 1
  502. if roll_back_md5:
  503. # Rollback any potential hash updates, as we did not
  504. # make any progress in this iteration.
  505. self.digesters = self.digesters_before_attempt
  506. if self.progress_less_iterations > self.num_retries:
  507. # Don't retry any longer in the current process.
  508. raise ResumableUploadException(
  509. 'Too many resumable upload attempts failed without '
  510. 'progress. You might try this upload again later',
  511. ResumableTransferDisposition.ABORT_CUR_PROCESS)
  512. # Use binary exponential backoff to desynchronize client requests.
  513. sleep_time_secs = random.random() * (2**self.progress_less_iterations)
  514. if debug >= 1:
  515. print('Got retryable failure (%d progress-less in a row).\n'
  516. 'Sleeping %3.1f seconds before re-trying' %
  517. (self.progress_less_iterations, sleep_time_secs))
  518. time.sleep(sleep_time_secs)
  519. def send_file(self, key, fp, headers, cb=None, num_cb=10, hash_algs=None):
  520. """
  521. Upload a file to a key into a bucket on GS, using GS resumable upload
  522. protocol.
  523. :type key: :class:`boto.s3.key.Key` or subclass
  524. :param key: The Key object to which data is to be uploaded
  525. :type fp: file-like object
  526. :param fp: The file pointer to upload
  527. :type headers: dict
  528. :param headers: The headers to pass along with the PUT request
  529. :type cb: function
  530. :param cb: a callback function that will be called to report progress on
  531. the upload. The callback should accept two integer parameters, the
  532. first representing the number of bytes that have been successfully
  533. transmitted to GS, and the second representing the total number of
  534. bytes that need to be transmitted.
  535. :type num_cb: int
  536. :param num_cb: (optional) If a callback is specified with the cb
  537. parameter, this parameter determines the granularity of the callback
  538. by defining the maximum number of times the callback will be called
  539. during the file transfer. Providing a negative integer will cause
  540. your callback to be called with each buffer read.
  541. :type hash_algs: dictionary
  542. :param hash_algs: (optional) Dictionary mapping hash algorithm
  543. descriptions to corresponding state-ful hashing objects that
  544. implement update(), digest(), and copy() (e.g. hashlib.md5()).
  545. Defaults to {'md5': md5()}.
  546. Raises ResumableUploadException if a problem occurs during the transfer.
  547. """
  548. if not headers:
  549. headers = {}
  550. # If Content-Type header is present and set to None, remove it.
  551. # This is gsutil's way of asking boto to refrain from auto-generating
  552. # that header.
  553. CT = 'Content-Type'
  554. if CT in headers and headers[CT] is None:
  555. del headers[CT]
  556. headers['User-Agent'] = UserAgent
  557. # Determine file size different ways for case where fp is actually a
  558. # wrapper around a Key vs an actual file.
  559. if isinstance(fp, KeyFile):
  560. file_length = fp.getkey().size
  561. else:
  562. fp.seek(0, os.SEEK_END)
  563. file_length = fp.tell()
  564. fp.seek(0)
  565. debug = key.bucket.connection.debug
  566. # Compute the MD5 checksum on the fly.
  567. if hash_algs is None:
  568. hash_algs = {'md5': md5}
  569. self.digesters = dict(
  570. (alg, hash_algs[alg]()) for alg in hash_algs or {})
  571. # Use num-retries from constructor if one was provided; else check
  572. # for a value specified in the boto config file; else default to 5.
  573. if self.num_retries is None:
  574. self.num_retries = config.getint('Boto', 'num_retries', 6)
  575. self.progress_less_iterations = 0
  576. while True: # Retry as long as we're making progress.
  577. server_had_bytes_before_attempt = self.server_has_bytes
  578. self.digesters_before_attempt = dict(
  579. (alg, self.digesters[alg].copy())
  580. for alg in self.digesters)
  581. try:
  582. # Save generation and metageneration in class state so caller
  583. # can find these values, for use in preconditions of future
  584. # operations on the uploaded object.
  585. (etag, self.generation, self.metageneration) = (
  586. self._attempt_resumable_upload(key, fp, file_length,
  587. headers, cb, num_cb))
  588. # Get the final digests for the uploaded content.
  589. for alg in self.digesters:
  590. key.local_hashes[alg] = self.digesters[alg].digest()
  591. # Upload succceded, so remove the tracker file (if have one).
  592. self._remove_tracker_file()
  593. self._check_final_md5(key, etag)
  594. key.generation = self.generation
  595. if debug >= 1:
  596. print('Resumable upload complete.')
  597. return
  598. except self.RETRYABLE_EXCEPTIONS as e:
  599. if debug >= 1:
  600. print('Caught exception (%s)' % e.__repr__())
  601. if isinstance(e, IOError) and e.errno == errno.EPIPE:
  602. # Broken pipe error causes httplib to immediately
  603. # close the socket (http://bugs.python.org/issue5542),
  604. # so we need to close the connection before we resume
  605. # the upload (which will cause a new connection to be
  606. # opened the next time an HTTP request is sent).
  607. key.bucket.connection.connection.close()
  608. except ResumableUploadException as e:
  609. self.handle_resumable_upload_exception(e, debug)
  610. self.track_progress_less_iterations(server_had_bytes_before_attempt,
  611. True, debug)