You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

721 lines
28 KiB

4 years ago
  1. # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import logging
  14. import os
  15. import socket
  16. import math
  17. import threading
  18. import heapq
  19. from botocore.compat import six
  20. from botocore.exceptions import IncompleteReadError
  21. from botocore.vendored.requests.packages.urllib3.exceptions import \
  22. ReadTimeoutError
  23. from s3transfer.compat import SOCKET_ERROR
  24. from s3transfer.compat import seekable
  25. from s3transfer.exceptions import RetriesExceededError
  26. from s3transfer.futures import IN_MEMORY_DOWNLOAD_TAG
  27. from s3transfer.utils import random_file_extension
  28. from s3transfer.utils import get_callbacks
  29. from s3transfer.utils import invoke_progress_callbacks
  30. from s3transfer.utils import calculate_range_parameter
  31. from s3transfer.utils import FunctionContainer
  32. from s3transfer.utils import CountCallbackInvoker
  33. from s3transfer.utils import StreamReaderProgress
  34. from s3transfer.utils import DeferredOpenFile
  35. from s3transfer.tasks import Task
  36. from s3transfer.tasks import SubmissionTask
  37. logger = logging.getLogger(__name__)
  38. S3_RETRYABLE_ERRORS = (
  39. socket.timeout, SOCKET_ERROR, ReadTimeoutError, IncompleteReadError
  40. )
  41. class DownloadOutputManager(object):
  42. """Base manager class for handling various types of files for downloads
  43. This class is typically used for the DownloadSubmissionTask class to help
  44. determine the following:
  45. * Provides the fileobj to write to downloads to
  46. * Get a task to complete once everything downloaded has been written
  47. The answers/implementations differ for the various types of file outputs
  48. that may be accepted. All implementations must subclass and override
  49. public methods from this class.
  50. """
  51. def __init__(self, osutil, transfer_coordinator, io_executor):
  52. self._osutil = osutil
  53. self._transfer_coordinator = transfer_coordinator
  54. self._io_executor = io_executor
  55. @classmethod
  56. def is_compatible(cls, download_target, osutil):
  57. """Determines if the target for the download is compatible with manager
  58. :param download_target: The target for which the upload will write
  59. data to.
  60. :param osutil: The os utility to be used for the transfer
  61. :returns: True if the manager can handle the type of target specified
  62. otherwise returns False.
  63. """
  64. raise NotImplementedError('must implement is_compatible()')
  65. def get_download_task_tag(self):
  66. """Get the tag (if any) to associate all GetObjectTasks
  67. :rtype: s3transfer.futures.TaskTag
  68. :returns: The tag to associate all GetObjectTasks with
  69. """
  70. return None
  71. def get_fileobj_for_io_writes(self, transfer_future):
  72. """Get file-like object to use for io writes in the io executor
  73. :type transfer_future: s3transfer.futures.TransferFuture
  74. :param transfer_future: The future associated with upload request
  75. returns: A file-like object to write to
  76. """
  77. raise NotImplementedError('must implement get_fileobj_for_io_writes()')
  78. def queue_file_io_task(self, fileobj, data, offset):
  79. """Queue IO write for submission to the IO executor.
  80. This method accepts an IO executor and information about the
  81. downloaded data, and handles submitting this to the IO executor.
  82. This method may defer submission to the IO executor if necessary.
  83. """
  84. self._transfer_coordinator.submit(
  85. self._io_executor,
  86. self.get_io_write_task(fileobj, data, offset)
  87. )
  88. def get_io_write_task(self, fileobj, data, offset):
  89. """Get an IO write task for the requested set of data
  90. This task can be ran immediately or be submitted to the IO executor
  91. for it to run.
  92. :type fileobj: file-like object
  93. :param fileobj: The file-like object to write to
  94. :type data: bytes
  95. :param data: The data to write out
  96. :type offset: integer
  97. :param offset: The offset to write the data to in the file-like object
  98. :returns: An IO task to be used to write data to a file-like object
  99. """
  100. return IOWriteTask(
  101. self._transfer_coordinator,
  102. main_kwargs={
  103. 'fileobj': fileobj,
  104. 'data': data,
  105. 'offset': offset,
  106. }
  107. )
  108. def get_final_io_task(self):
  109. """Get the final io task to complete the download
  110. This is needed because based on the architecture of the TransferManager
  111. the final tasks will be sent to the IO executor, but the executor
  112. needs a final task for it to signal that the transfer is done and
  113. all done callbacks can be run.
  114. :rtype: s3transfer.tasks.Task
  115. :returns: A final task to completed in the io executor
  116. """
  117. raise NotImplementedError(
  118. 'must implement get_final_io_task()')
  119. def _get_fileobj_from_filename(self, filename):
  120. f = DeferredOpenFile(
  121. filename, mode='wb', open_function=self._osutil.open)
  122. # Make sure the file gets closed and we remove the temporary file
  123. # if anything goes wrong during the process.
  124. self._transfer_coordinator.add_failure_cleanup(f.close)
  125. return f
  126. class DownloadFilenameOutputManager(DownloadOutputManager):
  127. def __init__(self, osutil, transfer_coordinator, io_executor):
  128. super(DownloadFilenameOutputManager, self).__init__(
  129. osutil, transfer_coordinator, io_executor)
  130. self._final_filename = None
  131. self._temp_filename = None
  132. self._temp_fileobj = None
  133. @classmethod
  134. def is_compatible(cls, download_target, osutil):
  135. return isinstance(download_target, six.string_types)
  136. def get_fileobj_for_io_writes(self, transfer_future):
  137. fileobj = transfer_future.meta.call_args.fileobj
  138. self._final_filename = fileobj
  139. self._temp_filename = fileobj + os.extsep + random_file_extension()
  140. self._temp_fileobj = self._get_temp_fileobj()
  141. return self._temp_fileobj
  142. def get_final_io_task(self):
  143. # A task to rename the file from the temporary file to its final
  144. # location is needed. This should be the last task needed to complete
  145. # the download.
  146. return IORenameFileTask(
  147. transfer_coordinator=self._transfer_coordinator,
  148. main_kwargs={
  149. 'fileobj': self._temp_fileobj,
  150. 'final_filename': self._final_filename,
  151. 'osutil': self._osutil
  152. },
  153. is_final=True
  154. )
  155. def _get_temp_fileobj(self):
  156. f = self._get_fileobj_from_filename(self._temp_filename)
  157. self._transfer_coordinator.add_failure_cleanup(
  158. self._osutil.remove_file, self._temp_filename)
  159. return f
  160. class DownloadSeekableOutputManager(DownloadOutputManager):
  161. @classmethod
  162. def is_compatible(cls, download_target, osutil):
  163. return seekable(download_target)
  164. def get_fileobj_for_io_writes(self, transfer_future):
  165. # Return the fileobj provided to the future.
  166. return transfer_future.meta.call_args.fileobj
  167. def get_final_io_task(self):
  168. # This task will serve the purpose of signaling when all of the io
  169. # writes have finished so done callbacks can be called.
  170. return CompleteDownloadNOOPTask(
  171. transfer_coordinator=self._transfer_coordinator)
  172. class DownloadNonSeekableOutputManager(DownloadOutputManager):
  173. def __init__(self, osutil, transfer_coordinator, io_executor,
  174. defer_queue=None):
  175. super(DownloadNonSeekableOutputManager, self).__init__(
  176. osutil, transfer_coordinator, io_executor)
  177. if defer_queue is None:
  178. defer_queue = DeferQueue()
  179. self._defer_queue = defer_queue
  180. self._io_submit_lock = threading.Lock()
  181. @classmethod
  182. def is_compatible(cls, download_target, osutil):
  183. return hasattr(download_target, 'write')
  184. def get_download_task_tag(self):
  185. return IN_MEMORY_DOWNLOAD_TAG
  186. def get_fileobj_for_io_writes(self, transfer_future):
  187. return transfer_future.meta.call_args.fileobj
  188. def get_final_io_task(self):
  189. return CompleteDownloadNOOPTask(
  190. transfer_coordinator=self._transfer_coordinator)
  191. def queue_file_io_task(self, fileobj, data, offset):
  192. with self._io_submit_lock:
  193. writes = self._defer_queue.request_writes(offset, data)
  194. for write in writes:
  195. data = write['data']
  196. logger.debug("Queueing IO offset %s for fileobj: %s",
  197. write['offset'], fileobj)
  198. super(
  199. DownloadNonSeekableOutputManager, self).queue_file_io_task(
  200. fileobj, data, offset)
  201. def get_io_write_task(self, fileobj, data, offset):
  202. return IOStreamingWriteTask(
  203. self._transfer_coordinator,
  204. main_kwargs={
  205. 'fileobj': fileobj,
  206. 'data': data,
  207. }
  208. )
  209. class DownloadSpecialFilenameOutputManager(DownloadNonSeekableOutputManager):
  210. def __init__(self, osutil, transfer_coordinator, io_executor,
  211. defer_queue=None):
  212. super(DownloadSpecialFilenameOutputManager, self).__init__(
  213. osutil, transfer_coordinator, io_executor, defer_queue)
  214. self._fileobj = None
  215. @classmethod
  216. def is_compatible(cls, download_target, osutil):
  217. return isinstance(download_target, six.string_types) and \
  218. osutil.is_special_file(download_target)
  219. def get_fileobj_for_io_writes(self, transfer_future):
  220. filename = transfer_future.meta.call_args.fileobj
  221. self._fileobj = self._get_fileobj_from_filename(filename)
  222. return self._fileobj
  223. def get_final_io_task(self):
  224. # Make sure the file gets closed once the transfer is done.
  225. return IOCloseTask(
  226. transfer_coordinator=self._transfer_coordinator,
  227. is_final=True,
  228. main_kwargs={'fileobj': self._fileobj})
  229. class DownloadSubmissionTask(SubmissionTask):
  230. """Task for submitting tasks to execute a download"""
  231. def _get_download_output_manager_cls(self, transfer_future, osutil):
  232. """Retrieves a class for managing output for a download
  233. :type transfer_future: s3transfer.futures.TransferFuture
  234. :param transfer_future: The transfer future for the request
  235. :type osutil: s3transfer.utils.OSUtils
  236. :param osutil: The os utility associated to the transfer
  237. :rtype: class of DownloadOutputManager
  238. :returns: The appropriate class to use for managing a specific type of
  239. input for downloads.
  240. """
  241. download_manager_resolver_chain = [
  242. DownloadSpecialFilenameOutputManager,
  243. DownloadFilenameOutputManager,
  244. DownloadSeekableOutputManager,
  245. DownloadNonSeekableOutputManager,
  246. ]
  247. fileobj = transfer_future.meta.call_args.fileobj
  248. for download_manager_cls in download_manager_resolver_chain:
  249. if download_manager_cls.is_compatible(fileobj, osutil):
  250. return download_manager_cls
  251. raise RuntimeError(
  252. 'Output %s of type: %s is not supported.' % (
  253. fileobj, type(fileobj)))
  254. def _submit(self, client, config, osutil, request_executor, io_executor,
  255. transfer_future, bandwidth_limiter=None):
  256. """
  257. :param client: The client associated with the transfer manager
  258. :type config: s3transfer.manager.TransferConfig
  259. :param config: The transfer config associated with the transfer
  260. manager
  261. :type osutil: s3transfer.utils.OSUtil
  262. :param osutil: The os utility associated to the transfer manager
  263. :type request_executor: s3transfer.futures.BoundedExecutor
  264. :param request_executor: The request executor associated with the
  265. transfer manager
  266. :type io_executor: s3transfer.futures.BoundedExecutor
  267. :param io_executor: The io executor associated with the
  268. transfer manager
  269. :type transfer_future: s3transfer.futures.TransferFuture
  270. :param transfer_future: The transfer future associated with the
  271. transfer request that tasks are being submitted for
  272. :type bandwidth_limiter: s3transfer.bandwidth.BandwidthLimiter
  273. :param bandwidth_limiter: The bandwidth limiter to use when
  274. downloading streams
  275. """
  276. if transfer_future.meta.size is None:
  277. # If a size was not provided figure out the size for the
  278. # user.
  279. response = client.head_object(
  280. Bucket=transfer_future.meta.call_args.bucket,
  281. Key=transfer_future.meta.call_args.key,
  282. **transfer_future.meta.call_args.extra_args
  283. )
  284. transfer_future.meta.provide_transfer_size(
  285. response['ContentLength'])
  286. download_output_manager = self._get_download_output_manager_cls(
  287. transfer_future, osutil)(osutil, self._transfer_coordinator,
  288. io_executor)
  289. # If it is greater than threshold do a ranged download, otherwise
  290. # do a regular GetObject download.
  291. if transfer_future.meta.size < config.multipart_threshold:
  292. self._submit_download_request(
  293. client, config, osutil, request_executor, io_executor,
  294. download_output_manager, transfer_future, bandwidth_limiter)
  295. else:
  296. self._submit_ranged_download_request(
  297. client, config, osutil, request_executor, io_executor,
  298. download_output_manager, transfer_future, bandwidth_limiter)
  299. def _submit_download_request(self, client, config, osutil,
  300. request_executor, io_executor,
  301. download_output_manager, transfer_future,
  302. bandwidth_limiter):
  303. call_args = transfer_future.meta.call_args
  304. # Get a handle to the file that will be used for writing downloaded
  305. # contents
  306. fileobj = download_output_manager.get_fileobj_for_io_writes(
  307. transfer_future)
  308. # Get the needed callbacks for the task
  309. progress_callbacks = get_callbacks(transfer_future, 'progress')
  310. # Get any associated tags for the get object task.
  311. get_object_tag = download_output_manager.get_download_task_tag()
  312. # Get the final io task to run once the download is complete.
  313. final_task = download_output_manager.get_final_io_task()
  314. # Submit the task to download the object.
  315. self._transfer_coordinator.submit(
  316. request_executor,
  317. ImmediatelyWriteIOGetObjectTask(
  318. transfer_coordinator=self._transfer_coordinator,
  319. main_kwargs={
  320. 'client': client,
  321. 'bucket': call_args.bucket,
  322. 'key': call_args.key,
  323. 'fileobj': fileobj,
  324. 'extra_args': call_args.extra_args,
  325. 'callbacks': progress_callbacks,
  326. 'max_attempts': config.num_download_attempts,
  327. 'download_output_manager': download_output_manager,
  328. 'io_chunksize': config.io_chunksize,
  329. 'bandwidth_limiter': bandwidth_limiter
  330. },
  331. done_callbacks=[final_task]
  332. ),
  333. tag=get_object_tag
  334. )
  335. def _submit_ranged_download_request(self, client, config, osutil,
  336. request_executor, io_executor,
  337. download_output_manager,
  338. transfer_future,
  339. bandwidth_limiter):
  340. call_args = transfer_future.meta.call_args
  341. # Get the needed progress callbacks for the task
  342. progress_callbacks = get_callbacks(transfer_future, 'progress')
  343. # Get a handle to the file that will be used for writing downloaded
  344. # contents
  345. fileobj = download_output_manager.get_fileobj_for_io_writes(
  346. transfer_future)
  347. # Determine the number of parts
  348. part_size = config.multipart_chunksize
  349. num_parts = int(
  350. math.ceil(transfer_future.meta.size / float(part_size)))
  351. # Get any associated tags for the get object task.
  352. get_object_tag = download_output_manager.get_download_task_tag()
  353. # Callback invoker to submit the final io task once all downloads
  354. # are complete.
  355. finalize_download_invoker = CountCallbackInvoker(
  356. self._get_final_io_task_submission_callback(
  357. download_output_manager, io_executor
  358. )
  359. )
  360. for i in range(num_parts):
  361. # Calculate the range parameter
  362. range_parameter = calculate_range_parameter(
  363. part_size, i, num_parts)
  364. # Inject the Range parameter to the parameters to be passed in
  365. # as extra args
  366. extra_args = {'Range': range_parameter}
  367. extra_args.update(call_args.extra_args)
  368. finalize_download_invoker.increment()
  369. # Submit the ranged downloads
  370. self._transfer_coordinator.submit(
  371. request_executor,
  372. GetObjectTask(
  373. transfer_coordinator=self._transfer_coordinator,
  374. main_kwargs={
  375. 'client': client,
  376. 'bucket': call_args.bucket,
  377. 'key': call_args.key,
  378. 'fileobj': fileobj,
  379. 'extra_args': extra_args,
  380. 'callbacks': progress_callbacks,
  381. 'max_attempts': config.num_download_attempts,
  382. 'start_index': i * part_size,
  383. 'download_output_manager': download_output_manager,
  384. 'io_chunksize': config.io_chunksize,
  385. 'bandwidth_limiter': bandwidth_limiter
  386. },
  387. done_callbacks=[finalize_download_invoker.decrement]
  388. ),
  389. tag=get_object_tag
  390. )
  391. finalize_download_invoker.finalize()
  392. def _get_final_io_task_submission_callback(self, download_manager,
  393. io_executor):
  394. final_task = download_manager.get_final_io_task()
  395. return FunctionContainer(
  396. self._transfer_coordinator.submit, io_executor, final_task)
  397. def _calculate_range_param(self, part_size, part_index, num_parts):
  398. # Used to calculate the Range parameter
  399. start_range = part_index * part_size
  400. if part_index == num_parts - 1:
  401. end_range = ''
  402. else:
  403. end_range = start_range + part_size - 1
  404. range_param = 'bytes=%s-%s' % (start_range, end_range)
  405. return range_param
  406. class GetObjectTask(Task):
  407. def _main(self, client, bucket, key, fileobj, extra_args, callbacks,
  408. max_attempts, download_output_manager, io_chunksize,
  409. start_index=0, bandwidth_limiter=None):
  410. """Downloads an object and places content into io queue
  411. :param client: The client to use when calling GetObject
  412. :param bucket: The bucket to download from
  413. :param key: The key to download from
  414. :param fileobj: The file handle to write content to
  415. :param exta_args: Any extra arguements to include in GetObject request
  416. :param callbacks: List of progress callbacks to invoke on download
  417. :param max_attempts: The number of retries to do when downloading
  418. :param download_output_manager: The download output manager associated
  419. with the current download.
  420. :param io_chunksize: The size of each io chunk to read from the
  421. download stream and queue in the io queue.
  422. :param start_index: The location in the file to start writing the
  423. content of the key to.
  424. :param bandwidth_limiter: The bandwidth limiter to use when throttling
  425. the downloading of data in streams.
  426. """
  427. last_exception = None
  428. for i in range(max_attempts):
  429. try:
  430. response = client.get_object(
  431. Bucket=bucket, Key=key, **extra_args)
  432. streaming_body = StreamReaderProgress(
  433. response['Body'], callbacks)
  434. if bandwidth_limiter:
  435. streaming_body = \
  436. bandwidth_limiter.get_bandwith_limited_stream(
  437. streaming_body, self._transfer_coordinator)
  438. current_index = start_index
  439. chunks = DownloadChunkIterator(streaming_body, io_chunksize)
  440. for chunk in chunks:
  441. # If the transfer is done because of a cancellation
  442. # or error somewhere else, stop trying to submit more
  443. # data to be written and break out of the download.
  444. if not self._transfer_coordinator.done():
  445. self._handle_io(
  446. download_output_manager, fileobj, chunk,
  447. current_index
  448. )
  449. current_index += len(chunk)
  450. else:
  451. return
  452. return
  453. except S3_RETRYABLE_ERRORS as e:
  454. logger.debug("Retrying exception caught (%s), "
  455. "retrying request, (attempt %s / %s)", e, i,
  456. max_attempts, exc_info=True)
  457. last_exception = e
  458. # Also invoke the progress callbacks to indicate that we
  459. # are trying to download the stream again and all progress
  460. # for this GetObject has been lost.
  461. invoke_progress_callbacks(
  462. callbacks, start_index - current_index)
  463. continue
  464. raise RetriesExceededError(last_exception)
  465. def _handle_io(self, download_output_manager, fileobj, chunk, index):
  466. download_output_manager.queue_file_io_task(fileobj, chunk, index)
  467. class ImmediatelyWriteIOGetObjectTask(GetObjectTask):
  468. """GetObjectTask that immediately writes to the provided file object
  469. This is useful for downloads where it is known only one thread is
  470. downloading the object so there is no reason to go through the
  471. overhead of using an IO queue and executor.
  472. """
  473. def _handle_io(self, download_output_manager, fileobj, chunk, index):
  474. task = download_output_manager.get_io_write_task(fileobj, chunk, index)
  475. task()
  476. class IOWriteTask(Task):
  477. def _main(self, fileobj, data, offset):
  478. """Pulls off an io queue to write contents to a file
  479. :param f: The file handle to write content to
  480. :param data: The data to write
  481. :param offset: The offset to write the data to.
  482. """
  483. fileobj.seek(offset)
  484. fileobj.write(data)
  485. class IOStreamingWriteTask(Task):
  486. """Task for writing data to a non-seekable stream."""
  487. def _main(self, fileobj, data):
  488. """Write data to a fileobj.
  489. Data will be written directly to the fileboj without
  490. any prior seeking.
  491. :param fileobj: The fileobj to write content to
  492. :param data: The data to write
  493. """
  494. fileobj.write(data)
  495. class IORenameFileTask(Task):
  496. """A task to rename a temporary file to its final filename
  497. :param f: The file handle that content was written to.
  498. :param final_filename: The final name of the file to rename to
  499. upon completion of writing the contents.
  500. :param osutil: OS utility
  501. """
  502. def _main(self, fileobj, final_filename, osutil):
  503. fileobj.close()
  504. osutil.rename_file(fileobj.name, final_filename)
  505. class IOCloseTask(Task):
  506. """A task to close out a file once the download is complete.
  507. :param fileobj: The fileobj to close.
  508. """
  509. def _main(self, fileobj):
  510. fileobj.close()
  511. class CompleteDownloadNOOPTask(Task):
  512. """A NOOP task to serve as an indicator that the download is complete
  513. Note that the default for is_final is set to True because this should
  514. always be the last task.
  515. """
  516. def __init__(self, transfer_coordinator, main_kwargs=None,
  517. pending_main_kwargs=None, done_callbacks=None,
  518. is_final=True):
  519. super(CompleteDownloadNOOPTask, self).__init__(
  520. transfer_coordinator=transfer_coordinator,
  521. main_kwargs=main_kwargs,
  522. pending_main_kwargs=pending_main_kwargs,
  523. done_callbacks=done_callbacks,
  524. is_final=is_final
  525. )
  526. def _main(self):
  527. pass
  528. class DownloadChunkIterator(object):
  529. def __init__(self, body, chunksize):
  530. """Iterator to chunk out a downloaded S3 stream
  531. :param body: A readable file-like object
  532. :param chunksize: The amount to read each time
  533. """
  534. self._body = body
  535. self._chunksize = chunksize
  536. self._num_reads = 0
  537. def __iter__(self):
  538. return self
  539. def __next__(self):
  540. chunk = self._body.read(self._chunksize)
  541. self._num_reads += 1
  542. if chunk:
  543. return chunk
  544. elif self._num_reads == 1:
  545. # Even though the response may have not had any
  546. # content, we still want to account for an empty object's
  547. # existance so return the empty chunk for that initial
  548. # read.
  549. return chunk
  550. raise StopIteration()
  551. next = __next__
  552. class DeferQueue(object):
  553. """IO queue that defers write requests until they are queued sequentially.
  554. This class is used to track IO data for a *single* fileobj.
  555. You can send data to this queue, and it will defer any IO write requests
  556. until it has the next contiguous block available (starting at 0).
  557. """
  558. def __init__(self):
  559. self._writes = []
  560. self._pending_offsets = set()
  561. self._next_offset = 0
  562. def request_writes(self, offset, data):
  563. """Request any available writes given new incoming data.
  564. You call this method by providing new data along with the
  565. offset associated with the data. If that new data unlocks
  566. any contiguous writes that can now be submitted, this
  567. method will return all applicable writes.
  568. This is done with 1 method call so you don't have to
  569. make two method calls (put(), get()) which acquires a lock
  570. each method call.
  571. """
  572. if offset < self._next_offset:
  573. # This is a request for a write that we've already
  574. # seen. This can happen in the event of a retry
  575. # where if we retry at at offset N/2, we'll requeue
  576. # offsets 0-N/2 again.
  577. return []
  578. writes = []
  579. if offset in self._pending_offsets:
  580. # We've already queued this offset so this request is
  581. # a duplicate. In this case we should ignore
  582. # this request and prefer what's already queued.
  583. return []
  584. heapq.heappush(self._writes, (offset, data))
  585. self._pending_offsets.add(offset)
  586. while self._writes and self._writes[0][0] == self._next_offset:
  587. next_write = heapq.heappop(self._writes)
  588. writes.append({'offset': next_write[0], 'data': next_write[1]})
  589. self._pending_offsets.remove(next_write[0])
  590. self._next_offset += len(next_write[1])
  591. return writes