PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/boto/gs/resumable_upload_handler.py

https://github.com/d1on/boto
Python | 580 lines | 352 code | 33 blank | 195 comment | 66 complexity | be5345d2fddd2daf5e4299adc052adb0 MD5 | raw file
  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 cgi
  22. import errno
  23. import httplib
  24. import os
  25. import re
  26. import socket
  27. import time
  28. import urlparse
  29. import boto
  30. from boto import config
  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. """
  36. Handler for Google Storage resumable uploads. See
  37. http://code.google.com/apis/storage/docs/developer-guide.html#resumable
  38. for details.
  39. Resumable uploads will retry failed uploads, resuming at the byte
  40. count completed by the last upload attempt. If too many retries happen with
  41. no progress (per configurable num_retries param), the upload will be
  42. aborted in the current process.
  43. The caller can optionally specify a tracker_file_name param in the
  44. ResumableUploadHandler constructor. If you do this, that file will
  45. save the state needed to allow retrying later, in a separate process
  46. (e.g., in a later run of gsutil).
  47. """
  48. class ResumableUploadHandler(object):
  49. BUFFER_SIZE = 8192
  50. RETRYABLE_EXCEPTIONS = (httplib.HTTPException, IOError, socket.error,
  51. socket.gaierror)
  52. # (start, end) response indicating server has nothing (upload protocol uses
  53. # inclusive numbering).
  54. SERVER_HAS_NOTHING = (0, -1)
  55. def __init__(self, tracker_file_name=None, num_retries=None):
  56. """
  57. Constructor. Instantiate once for each uploaded file.
  58. :type tracker_file_name: string
  59. :param tracker_file_name: optional file name to save tracker URI.
  60. If supplied and the current process fails the upload, it can be
  61. retried in a new process. If called with an existing file containing
  62. a valid tracker URI, we'll resume the upload from this URI; else
  63. we'll start a new resumable upload (and write the URI to this
  64. tracker file).
  65. :type num_retries: int
  66. :param num_retries: the number of times we'll re-try a resumable upload
  67. making no progress. (Count resets every time we get progress, so
  68. upload can span many more than this number of retries.)
  69. """
  70. self.tracker_file_name = tracker_file_name
  71. self.num_retries = num_retries
  72. self.server_has_bytes = 0 # Byte count at last server check.
  73. self.tracker_uri = None
  74. if tracker_file_name:
  75. self._load_tracker_uri_from_file()
  76. # Save upload_start_point in instance state so caller can find how
  77. # much was transferred by this ResumableUploadHandler (across retries).
  78. self.upload_start_point = None
  79. def _load_tracker_uri_from_file(self):
  80. f = None
  81. try:
  82. f = open(self.tracker_file_name, 'r')
  83. uri = f.readline().strip()
  84. self._set_tracker_uri(uri)
  85. except IOError, e:
  86. # Ignore non-existent file (happens first time an upload
  87. # is attempted on a file), but warn user for other errors.
  88. if e.errno != errno.ENOENT:
  89. # Will restart because self.tracker_uri == None.
  90. print('Couldn\'t read URI tracker file (%s): %s. Restarting '
  91. 'upload from scratch.' %
  92. (self.tracker_file_name, e.strerror))
  93. except InvalidUriError, e:
  94. # Warn user, but proceed (will restart because
  95. # self.tracker_uri == None).
  96. print('Invalid tracker URI (%s) found in URI tracker file '
  97. '(%s). Restarting upload from scratch.' %
  98. (uri, self.tracker_file_name))
  99. finally:
  100. if f:
  101. f.close()
  102. def _save_tracker_uri_to_file(self):
  103. """
  104. Saves URI to tracker file if one was passed to constructor.
  105. """
  106. if not self.tracker_file_name:
  107. return
  108. f = None
  109. try:
  110. f = open(self.tracker_file_name, 'w')
  111. f.write(self.tracker_uri)
  112. except IOError, e:
  113. raise ResumableUploadException(
  114. 'Couldn\'t write URI tracker file (%s): %s.\nThis can happen'
  115. 'if you\'re using an incorrectly configured upload tool\n'
  116. '(e.g., gsutil configured to save tracker files to an '
  117. 'unwritable directory)' %
  118. (self.tracker_file_name, e.strerror),
  119. ResumableTransferDisposition.ABORT)
  120. finally:
  121. if f:
  122. f.close()
  123. def _set_tracker_uri(self, uri):
  124. """
  125. Called when we start a new resumable upload or get a new tracker
  126. URI for the upload. Saves URI and resets upload state.
  127. Raises InvalidUriError if URI is syntactically invalid.
  128. """
  129. parse_result = urlparse.urlparse(uri)
  130. if (parse_result.scheme.lower() not in ['http', 'https'] or
  131. not parse_result.netloc or not parse_result.query):
  132. raise InvalidUriError('Invalid tracker URI (%s)' % uri)
  133. qdict = cgi.parse_qs(parse_result.query)
  134. if not qdict or not 'upload_id' in qdict:
  135. raise InvalidUriError('Invalid tracker URI (%s)' % uri)
  136. self.tracker_uri = uri
  137. self.tracker_uri_host = parse_result.netloc
  138. self.tracker_uri_path = '%s/?%s' % (parse_result.netloc,
  139. parse_result.query)
  140. self.server_has_bytes = 0
  141. def get_tracker_uri(self):
  142. """
  143. Returns upload tracker URI, or None if the upload has not yet started.
  144. """
  145. return self.tracker_uri
  146. def _remove_tracker_file(self):
  147. if (self.tracker_file_name and
  148. os.path.exists(self.tracker_file_name)):
  149. os.unlink(self.tracker_file_name)
  150. def _build_content_range_header(self, range_spec='*', length_spec='*'):
  151. return 'bytes %s/%s' % (range_spec, length_spec)
  152. def _query_server_state(self, conn, file_length):
  153. """
  154. Queries server to find out state of given upload.
  155. Note that this method really just makes special case use of the
  156. fact that the upload server always returns the current start/end
  157. state whenever a PUT doesn't complete.
  158. Returns HTTP response from sending request.
  159. Raises ResumableUploadException if problem querying server.
  160. """
  161. # Send an empty PUT so that server replies with this resumable
  162. # transfer's state.
  163. put_headers = {}
  164. put_headers['Content-Range'] = (
  165. self._build_content_range_header('*', file_length))
  166. put_headers['Content-Length'] = '0'
  167. return AWSAuthConnection.make_request(conn, 'PUT',
  168. path=self.tracker_uri_path,
  169. auth_path=self.tracker_uri_path,
  170. headers=put_headers,
  171. host=self.tracker_uri_host)
  172. def _query_server_pos(self, conn, file_length):
  173. """
  174. Queries server to find out what bytes it currently has.
  175. Returns (server_start, server_end), where the values are inclusive.
  176. For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2.
  177. Raises ResumableUploadException if problem querying server.
  178. """
  179. resp = self._query_server_state(conn, file_length)
  180. if resp.status == 200:
  181. return (0, file_length) # Completed upload.
  182. if resp.status != 308:
  183. # This means the server didn't have any state for the given
  184. # upload ID, which can happen (for example) if the caller saved
  185. # the tracker URI to a file and then tried to restart the transfer
  186. # after that upload ID has gone stale. In that case we need to
  187. # start a new transfer (and the caller will then save the new
  188. # tracker URI to the tracker file).
  189. raise ResumableUploadException(
  190. 'Got non-308 response (%s) from server state query' %
  191. resp.status, ResumableTransferDisposition.START_OVER)
  192. got_valid_response = False
  193. range_spec = resp.getheader('range')
  194. if range_spec:
  195. # Parse 'bytes=<from>-<to>' range_spec.
  196. m = re.search('bytes=(\d+)-(\d+)', range_spec)
  197. if m:
  198. server_start = long(m.group(1))
  199. server_end = long(m.group(2))
  200. got_valid_response = True
  201. else:
  202. # No Range header, which means the server does not yet have
  203. # any bytes. Note that the Range header uses inclusive 'from'
  204. # and 'to' values. Since Range 0-0 would mean that the server
  205. # has byte 0, omitting the Range header is used to indicate that
  206. # the server doesn't have any bytes.
  207. return self.SERVER_HAS_NOTHING
  208. if not got_valid_response:
  209. raise ResumableUploadException(
  210. 'Couldn\'t parse upload server state query response (%s)' %
  211. str(resp.getheaders()), ResumableTransferDisposition.START_OVER)
  212. if conn.debug >= 1:
  213. print 'Server has: Range: %d - %d.' % (server_start, server_end)
  214. return (server_start, server_end)
  215. def _start_new_resumable_upload(self, key, headers=None):
  216. """
  217. Starts a new resumable upload.
  218. Raises ResumableUploadException if any errors occur.
  219. """
  220. conn = key.bucket.connection
  221. if conn.debug >= 1:
  222. print 'Starting new resumable upload.'
  223. self.server_has_bytes = 0
  224. # Start a new resumable upload by sending a POST request with an
  225. # empty body and the "X-Goog-Resumable: start" header. Include any
  226. # caller-provided headers (e.g., Content-Type) EXCEPT Content-Length
  227. # (and raise an exception if they tried to pass one, since it's
  228. # a semantic error to specify it at this point, and if we were to
  229. # include one now it would cause the server to expect that many
  230. # bytes; the POST doesn't include the actual file bytes We set
  231. # the Content-Length in the subsequent PUT, based on the uploaded
  232. # file size.
  233. post_headers = {}
  234. for k in headers:
  235. if k.lower() == 'content-length':
  236. raise ResumableUploadException(
  237. 'Attempt to specify Content-Length header (disallowed)',
  238. ResumableTransferDisposition.ABORT)
  239. post_headers[k] = headers[k]
  240. post_headers[conn.provider.resumable_upload_header] = 'start'
  241. resp = conn.make_request(
  242. 'POST', key.bucket.name, key.name, post_headers)
  243. # Get tracker URI from response 'Location' header.
  244. body = resp.read()
  245. # Check for various status conditions.
  246. if resp.status in [500, 503]:
  247. # Retry status 500 and 503 errors after a delay.
  248. raise ResumableUploadException(
  249. 'Got status %d from attempt to start resumable upload. '
  250. 'Will wait/retry' % resp.status,
  251. ResumableTransferDisposition.WAIT_BEFORE_RETRY)
  252. elif resp.status != 200 and resp.status != 201:
  253. raise ResumableUploadException(
  254. 'Got status %d from attempt to start resumable upload. '
  255. 'Aborting' % resp.status,
  256. ResumableTransferDisposition.ABORT)
  257. # Else we got 200 or 201 response code, indicating the resumable
  258. # upload was created.
  259. tracker_uri = resp.getheader('Location')
  260. if not tracker_uri:
  261. raise ResumableUploadException(
  262. 'No resumable tracker URI found in resumable initiation '
  263. 'POST response (%s)' % body,
  264. ResumableTransferDisposition.WAIT_BEFORE_RETRY)
  265. self._set_tracker_uri(tracker_uri)
  266. self._save_tracker_uri_to_file()
  267. def _upload_file_bytes(self, conn, http_conn, fp, file_length,
  268. total_bytes_uploaded, cb, num_cb):
  269. """
  270. Makes one attempt to upload file bytes, using an existing resumable
  271. upload connection.
  272. Returns etag from server upon success.
  273. Raises ResumableUploadException if any problems occur.
  274. """
  275. buf = fp.read(self.BUFFER_SIZE)
  276. if cb:
  277. if num_cb > 2:
  278. cb_count = file_length / self.BUFFER_SIZE / (num_cb-2)
  279. elif num_cb < 0:
  280. cb_count = -1
  281. else:
  282. cb_count = 0
  283. i = 0
  284. cb(total_bytes_uploaded, file_length)
  285. # Build resumable upload headers for the transfer. Don't send a
  286. # Content-Range header if the file is 0 bytes long, because the
  287. # resumable upload protocol uses an *inclusive* end-range (so, sending
  288. # 'bytes 0-0/1' would actually mean you're sending a 1-byte file).
  289. put_headers = {}
  290. if file_length:
  291. range_header = self._build_content_range_header(
  292. '%d-%d' % (total_bytes_uploaded, file_length - 1),
  293. file_length)
  294. put_headers['Content-Range'] = range_header
  295. # Set Content-Length to the total bytes we'll send with this PUT.
  296. put_headers['Content-Length'] = str(file_length - total_bytes_uploaded)
  297. http_request = AWSAuthConnection.build_base_http_request(
  298. conn, 'PUT', path=self.tracker_uri_path, auth_path=None,
  299. headers=put_headers, host=self.tracker_uri_host)
  300. http_conn.putrequest('PUT', http_request.path)
  301. for k in put_headers:
  302. http_conn.putheader(k, put_headers[k])
  303. http_conn.endheaders()
  304. # Turn off debug on http connection so upload content isn't included
  305. # in debug stream.
  306. http_conn.set_debuglevel(0)
  307. while buf:
  308. http_conn.send(buf)
  309. total_bytes_uploaded += len(buf)
  310. if cb:
  311. i += 1
  312. if i == cb_count or cb_count == -1:
  313. cb(total_bytes_uploaded, file_length)
  314. i = 0
  315. buf = fp.read(self.BUFFER_SIZE)
  316. if cb:
  317. cb(total_bytes_uploaded, file_length)
  318. if total_bytes_uploaded != file_length:
  319. # Abort (and delete the tracker file) so if the user retries
  320. # they'll start a new resumable upload rather than potentially
  321. # attempting to pick back up later where we left off.
  322. raise ResumableUploadException(
  323. 'File changed during upload: EOF at %d bytes of %d byte file.' %
  324. (total_bytes_uploaded, file_length),
  325. ResumableTransferDisposition.ABORT)
  326. resp = http_conn.getresponse()
  327. body = resp.read()
  328. # Restore http connection debug level.
  329. http_conn.set_debuglevel(conn.debug)
  330. if resp.status == 200:
  331. return resp.getheader('etag') # Success
  332. # Retry timeout (408) and status 500 and 503 errors after a delay.
  333. elif resp.status in [408, 500, 503]:
  334. disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY
  335. else:
  336. # Catch all for any other error codes.
  337. disposition = ResumableTransferDisposition.ABORT
  338. raise ResumableUploadException('Got response code %d while attempting '
  339. 'upload (%s)' %
  340. (resp.status, resp.reason), disposition)
  341. def _attempt_resumable_upload(self, key, fp, file_length, headers, cb,
  342. num_cb):
  343. """
  344. Attempts a resumable upload.
  345. Returns etag from server upon success.
  346. Raises ResumableUploadException if any problems occur.
  347. """
  348. (server_start, server_end) = self.SERVER_HAS_NOTHING
  349. conn = key.bucket.connection
  350. if self.tracker_uri:
  351. # Try to resume existing resumable upload.
  352. try:
  353. (server_start, server_end) = (
  354. self._query_server_pos(conn, file_length))
  355. self.server_has_bytes = server_start
  356. key=key
  357. if conn.debug >= 1:
  358. print 'Resuming transfer.'
  359. except ResumableUploadException, e:
  360. if conn.debug >= 1:
  361. print 'Unable to resume transfer (%s).' % e.message
  362. self._start_new_resumable_upload(key, headers)
  363. else:
  364. self._start_new_resumable_upload(key, headers)
  365. # upload_start_point allows the code that instantiated the
  366. # ResumableUploadHandler to find out the point from which it started
  367. # uploading (e.g., so it can correctly compute throughput).
  368. if self.upload_start_point is None:
  369. self.upload_start_point = server_end
  370. if server_end == file_length:
  371. # Boundary condition: complete file was already uploaded (e.g.,
  372. # user interrupted a previous upload attempt after the upload
  373. # completed but before the gsutil tracker file was deleted). Set
  374. # total_bytes_uploaded to server_end so we'll attempt to upload
  375. # no more bytes but will still make final HTTP request and get
  376. # back the response (which contains the etag we need to compare
  377. # at the end).
  378. total_bytes_uploaded = server_end
  379. else:
  380. total_bytes_uploaded = server_end + 1
  381. fp.seek(total_bytes_uploaded)
  382. conn = key.bucket.connection
  383. # Get a new HTTP connection (vs conn.get_http_connection(), which reuses
  384. # pool connections) because httplib requires a new HTTP connection per
  385. # transaction. (Without this, calling http_conn.getresponse() would get
  386. # "ResponseNotReady".)
  387. http_conn = conn.new_http_connection(self.tracker_uri_host,
  388. conn.is_secure)
  389. http_conn.set_debuglevel(conn.debug)
  390. # Make sure to close http_conn at end so if a local file read
  391. # failure occurs partway through server will terminate current upload
  392. # and can report that progress on next attempt.
  393. try:
  394. return self._upload_file_bytes(conn, http_conn, fp, file_length,
  395. total_bytes_uploaded, cb, num_cb)
  396. except (ResumableUploadException, socket.error):
  397. resp = self._query_server_state(conn, file_length)
  398. if resp.status == 400:
  399. raise ResumableUploadException('Got 400 response from server '
  400. 'state query after failed resumable upload attempt. This '
  401. 'can happen if the file size changed between upload '
  402. 'attempts', ResumableTransferDisposition.ABORT)
  403. else:
  404. raise
  405. finally:
  406. http_conn.close()
  407. def _check_final_md5(self, key, etag):
  408. """
  409. Checks that etag from server agrees with md5 computed before upload.
  410. This is important, since the upload could have spanned a number of
  411. hours and multiple processes (e.g., gsutil runs), and the user could
  412. change some of the file and not realize they have inconsistent data.
  413. """
  414. if key.bucket.connection.debug >= 1:
  415. print 'Checking md5 against etag.'
  416. if key.md5 != etag.strip('"\''):
  417. # Call key.open_read() before attempting to delete the
  418. # (incorrect-content) key, so we perform that request on a
  419. # different HTTP connection. This is neededb because httplib
  420. # will return a "Response not ready" error if you try to perform
  421. # a second transaction on the connection.
  422. key.open_read()
  423. key.close()
  424. key.delete()
  425. raise ResumableUploadException(
  426. 'File changed during upload: md5 signature doesn\'t match etag '
  427. '(incorrect uploaded object deleted)',
  428. ResumableTransferDisposition.ABORT)
  429. def send_file(self, key, fp, headers, cb=None, num_cb=10):
  430. """
  431. Upload a file to a key into a bucket on GS, using GS resumable upload
  432. protocol.
  433. :type key: :class:`boto.s3.key.Key` or subclass
  434. :param key: The Key object to which data is to be uploaded
  435. :type fp: file-like object
  436. :param fp: The file pointer to upload
  437. :type headers: dict
  438. :param headers: The headers to pass along with the PUT request
  439. :type cb: function
  440. :param cb: a callback function that will be called to report progress on
  441. the upload. The callback should accept two integer parameters, the
  442. first representing the number of bytes that have been successfully
  443. transmitted to GS, and the second representing the total number of
  444. bytes that need to be transmitted.
  445. :type num_cb: int
  446. :param num_cb: (optional) If a callback is specified with the cb
  447. parameter, this parameter determines the granularity of the callback
  448. by defining the maximum number of times the callback will be called
  449. during the file transfer. Providing a negative integer will cause
  450. your callback to be called with each buffer read.
  451. Raises ResumableUploadException if a problem occurs during the transfer.
  452. """
  453. if not headers:
  454. headers = {}
  455. fp.seek(0, os.SEEK_END)
  456. file_length = fp.tell()
  457. fp.seek(0)
  458. debug = key.bucket.connection.debug
  459. # Use num-retries from constructor if one was provided; else check
  460. # for a value specified in the boto config file; else default to 5.
  461. if self.num_retries is None:
  462. self.num_retries = config.getint('Boto', 'num_retries', 5)
  463. progress_less_iterations = 0
  464. while True: # Retry as long as we're making progress.
  465. server_had_bytes_before_attempt = self.server_has_bytes
  466. try:
  467. etag = self._attempt_resumable_upload(key, fp, file_length,
  468. headers, cb, num_cb)
  469. # Upload succceded, so remove the tracker file (if have one).
  470. self._remove_tracker_file()
  471. self._check_final_md5(key, etag)
  472. if debug >= 1:
  473. print 'Resumable upload complete.'
  474. return
  475. except self.RETRYABLE_EXCEPTIONS, e:
  476. if debug >= 1:
  477. print('Caught exception (%s)' % e.__repr__())
  478. if isinstance(e, IOError) and e.errno == errno.EPIPE:
  479. # Broken pipe error causes httplib to immediately
  480. # close the socket (http://bugs.python.org/issue5542),
  481. # so we need to close the connection before we resume
  482. # the upload (which will cause a new connection to be
  483. # opened the next time an HTTP request is sent).
  484. key.bucket.connection.connection.close()
  485. except ResumableUploadException, e:
  486. if (e.disposition ==
  487. ResumableTransferDisposition.ABORT_CUR_PROCESS):
  488. if debug >= 1:
  489. print('Caught non-retryable ResumableUploadException '
  490. '(%s); aborting but retaining tracker file' %
  491. e.message)
  492. raise
  493. elif (e.disposition ==
  494. ResumableTransferDisposition.ABORT):
  495. if debug >= 1:
  496. print('Caught non-retryable ResumableUploadException '
  497. '(%s); aborting and removing tracker file' %
  498. e.message)
  499. self._remove_tracker_file()
  500. raise
  501. else:
  502. if debug >= 1:
  503. print('Caught ResumableUploadException (%s) - will '
  504. 'retry' % e.message)
  505. # At this point we had a re-tryable failure; see if made progress.
  506. if self.server_has_bytes > server_had_bytes_before_attempt:
  507. progress_less_iterations = 0
  508. else:
  509. progress_less_iterations += 1
  510. if progress_less_iterations > self.num_retries:
  511. # Don't retry any longer in the current process.
  512. raise ResumableUploadException(
  513. 'Too many resumable upload attempts failed without '
  514. 'progress. You might try this upload again later',
  515. ResumableTransferDisposition.ABORT_CUR_PROCESS)
  516. sleep_time_secs = 2**progress_less_iterations
  517. if debug >= 1:
  518. print ('Got retryable failure (%d progress-less in a row).\n'
  519. 'Sleeping %d seconds before re-trying' %
  520. (progress_less_iterations, sleep_time_secs))
  521. time.sleep(sleep_time_secs)