utils.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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 functools
  14. import logging
  15. import math
  16. import os
  17. import random
  18. import socket
  19. import stat
  20. import string
  21. import threading
  22. from collections import defaultdict
  23. from botocore.exceptions import IncompleteReadError, ReadTimeoutError
  24. from s3transfer.compat import SOCKET_ERROR, fallocate, rename_file
  25. MAX_PARTS = 10000
  26. # The maximum file size you can upload via S3 per request.
  27. # See: http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  28. # and: http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html
  29. MAX_SINGLE_UPLOAD_SIZE = 5 * (1024**3)
  30. MIN_UPLOAD_CHUNKSIZE = 5 * (1024**2)
  31. logger = logging.getLogger(__name__)
  32. S3_RETRYABLE_DOWNLOAD_ERRORS = (
  33. socket.timeout,
  34. SOCKET_ERROR,
  35. ReadTimeoutError,
  36. IncompleteReadError,
  37. )
  38. def random_file_extension(num_digits=8):
  39. return ''.join(random.choice(string.hexdigits) for _ in range(num_digits))
  40. def signal_not_transferring(request, operation_name, **kwargs):
  41. if operation_name in ['PutObject', 'UploadPart'] and hasattr(
  42. request.body, 'signal_not_transferring'
  43. ):
  44. request.body.signal_not_transferring()
  45. def signal_transferring(request, operation_name, **kwargs):
  46. if operation_name in ['PutObject', 'UploadPart'] and hasattr(
  47. request.body, 'signal_transferring'
  48. ):
  49. request.body.signal_transferring()
  50. def calculate_num_parts(size, part_size):
  51. return int(math.ceil(size / float(part_size)))
  52. def calculate_range_parameter(
  53. part_size, part_index, num_parts, total_size=None
  54. ):
  55. """Calculate the range parameter for multipart downloads/copies
  56. :type part_size: int
  57. :param part_size: The size of the part
  58. :type part_index: int
  59. :param part_index: The index for which this parts starts. This index starts
  60. at zero
  61. :type num_parts: int
  62. :param num_parts: The total number of parts in the transfer
  63. :returns: The value to use for Range parameter on downloads or
  64. the CopySourceRange parameter for copies
  65. """
  66. # Used to calculate the Range parameter
  67. start_range = part_index * part_size
  68. if part_index == num_parts - 1:
  69. end_range = ''
  70. if total_size is not None:
  71. end_range = str(total_size - 1)
  72. else:
  73. end_range = start_range + part_size - 1
  74. range_param = f'bytes={start_range}-{end_range}'
  75. return range_param
  76. def get_callbacks(transfer_future, callback_type):
  77. """Retrieves callbacks from a subscriber
  78. :type transfer_future: s3transfer.futures.TransferFuture
  79. :param transfer_future: The transfer future the subscriber is associated
  80. to.
  81. :type callback_type: str
  82. :param callback_type: The type of callback to retrieve from the subscriber.
  83. Valid types include:
  84. * 'queued'
  85. * 'progress'
  86. * 'done'
  87. :returns: A list of callbacks for the type specified. All callbacks are
  88. preinjected with the transfer future.
  89. """
  90. callbacks = []
  91. for subscriber in transfer_future.meta.call_args.subscribers:
  92. callback_name = 'on_' + callback_type
  93. if hasattr(subscriber, callback_name):
  94. callbacks.append(
  95. functools.partial(
  96. getattr(subscriber, callback_name), future=transfer_future
  97. )
  98. )
  99. return callbacks
  100. def invoke_progress_callbacks(callbacks, bytes_transferred):
  101. """Calls all progress callbacks
  102. :param callbacks: A list of progress callbacks to invoke
  103. :param bytes_transferred: The number of bytes transferred. This is passed
  104. to the callbacks. If no bytes were transferred the callbacks will not
  105. be invoked because no progress was achieved. It is also possible
  106. to receive a negative amount which comes from retrying a transfer
  107. request.
  108. """
  109. # Only invoke the callbacks if bytes were actually transferred.
  110. if bytes_transferred:
  111. for callback in callbacks:
  112. callback(bytes_transferred=bytes_transferred)
  113. def get_filtered_dict(original_dict, whitelisted_keys):
  114. """Gets a dictionary filtered by whitelisted keys
  115. :param original_dict: The original dictionary of arguments to source keys
  116. and values.
  117. :param whitelisted_key: A list of keys to include in the filtered
  118. dictionary.
  119. :returns: A dictionary containing key/values from the original dictionary
  120. whose key was included in the whitelist
  121. """
  122. filtered_dict = {}
  123. for key, value in original_dict.items():
  124. if key in whitelisted_keys:
  125. filtered_dict[key] = value
  126. return filtered_dict
  127. class CallArgs:
  128. def __init__(self, **kwargs):
  129. """A class that records call arguments
  130. The call arguments must be passed as keyword arguments. It will set
  131. each keyword argument as an attribute of the object along with its
  132. associated value.
  133. """
  134. for arg, value in kwargs.items():
  135. setattr(self, arg, value)
  136. class FunctionContainer:
  137. """An object that contains a function and any args or kwargs to call it
  138. When called the provided function will be called with provided args
  139. and kwargs.
  140. """
  141. def __init__(self, func, *args, **kwargs):
  142. self._func = func
  143. self._args = args
  144. self._kwargs = kwargs
  145. def __repr__(self):
  146. return 'Function: {} with args {} and kwargs {}'.format(
  147. self._func, self._args, self._kwargs
  148. )
  149. def __call__(self):
  150. return self._func(*self._args, **self._kwargs)
  151. class CountCallbackInvoker:
  152. """An abstraction to invoke a callback when a shared count reaches zero
  153. :param callback: Callback invoke when finalized count reaches zero
  154. """
  155. def __init__(self, callback):
  156. self._lock = threading.Lock()
  157. self._callback = callback
  158. self._count = 0
  159. self._is_finalized = False
  160. @property
  161. def current_count(self):
  162. with self._lock:
  163. return self._count
  164. def increment(self):
  165. """Increment the count by one"""
  166. with self._lock:
  167. if self._is_finalized:
  168. raise RuntimeError(
  169. 'Counter has been finalized it can no longer be '
  170. 'incremented.'
  171. )
  172. self._count += 1
  173. def decrement(self):
  174. """Decrement the count by one"""
  175. with self._lock:
  176. if self._count == 0:
  177. raise RuntimeError(
  178. 'Counter is at zero. It cannot dip below zero'
  179. )
  180. self._count -= 1
  181. if self._is_finalized and self._count == 0:
  182. self._callback()
  183. def finalize(self):
  184. """Finalize the counter
  185. Once finalized, the counter never be incremented and the callback
  186. can be invoked once the count reaches zero
  187. """
  188. with self._lock:
  189. self._is_finalized = True
  190. if self._count == 0:
  191. self._callback()
  192. class OSUtils:
  193. _MAX_FILENAME_LEN = 255
  194. def get_file_size(self, filename):
  195. return os.path.getsize(filename)
  196. def open_file_chunk_reader(self, filename, start_byte, size, callbacks):
  197. return ReadFileChunk.from_filename(
  198. filename, start_byte, size, callbacks, enable_callbacks=False
  199. )
  200. def open_file_chunk_reader_from_fileobj(
  201. self,
  202. fileobj,
  203. chunk_size,
  204. full_file_size,
  205. callbacks,
  206. close_callbacks=None,
  207. ):
  208. return ReadFileChunk(
  209. fileobj,
  210. chunk_size,
  211. full_file_size,
  212. callbacks=callbacks,
  213. enable_callbacks=False,
  214. close_callbacks=close_callbacks,
  215. )
  216. def open(self, filename, mode):
  217. return open(filename, mode)
  218. def remove_file(self, filename):
  219. """Remove a file, noop if file does not exist."""
  220. # Unlike os.remove, if the file does not exist,
  221. # then this method does nothing.
  222. try:
  223. os.remove(filename)
  224. except OSError:
  225. pass
  226. def rename_file(self, current_filename, new_filename):
  227. rename_file(current_filename, new_filename)
  228. def is_special_file(cls, filename):
  229. """Checks to see if a file is a special UNIX file.
  230. It checks if the file is a character special device, block special
  231. device, FIFO, or socket.
  232. :param filename: Name of the file
  233. :returns: True if the file is a special file. False, if is not.
  234. """
  235. # If it does not exist, it must be a new file so it cannot be
  236. # a special file.
  237. if not os.path.exists(filename):
  238. return False
  239. mode = os.stat(filename).st_mode
  240. # Character special device.
  241. if stat.S_ISCHR(mode):
  242. return True
  243. # Block special device
  244. if stat.S_ISBLK(mode):
  245. return True
  246. # Named pipe / FIFO
  247. if stat.S_ISFIFO(mode):
  248. return True
  249. # Socket.
  250. if stat.S_ISSOCK(mode):
  251. return True
  252. return False
  253. def get_temp_filename(self, filename):
  254. suffix = os.extsep + random_file_extension()
  255. path = os.path.dirname(filename)
  256. name = os.path.basename(filename)
  257. temp_filename = name[: self._MAX_FILENAME_LEN - len(suffix)] + suffix
  258. return os.path.join(path, temp_filename)
  259. def allocate(self, filename, size):
  260. try:
  261. with self.open(filename, 'wb') as f:
  262. fallocate(f, size)
  263. except OSError:
  264. self.remove_file(filename)
  265. raise
  266. class DeferredOpenFile:
  267. def __init__(self, filename, start_byte=0, mode='rb', open_function=open):
  268. """A class that defers the opening of a file till needed
  269. This is useful for deferring opening of a file till it is needed
  270. in a separate thread, as there is a limit of how many open files
  271. there can be in a single thread for most operating systems. The
  272. file gets opened in the following methods: ``read()``, ``seek()``,
  273. and ``__enter__()``
  274. :type filename: str
  275. :param filename: The name of the file to open
  276. :type start_byte: int
  277. :param start_byte: The byte to seek to when the file is opened.
  278. :type mode: str
  279. :param mode: The mode to use to open the file
  280. :type open_function: function
  281. :param open_function: The function to use to open the file
  282. """
  283. self._filename = filename
  284. self._fileobj = None
  285. self._start_byte = start_byte
  286. self._mode = mode
  287. self._open_function = open_function
  288. def _open_if_needed(self):
  289. if self._fileobj is None:
  290. self._fileobj = self._open_function(self._filename, self._mode)
  291. if self._start_byte != 0:
  292. self._fileobj.seek(self._start_byte)
  293. @property
  294. def name(self):
  295. return self._filename
  296. def read(self, amount=None):
  297. self._open_if_needed()
  298. return self._fileobj.read(amount)
  299. def write(self, data):
  300. self._open_if_needed()
  301. self._fileobj.write(data)
  302. def seek(self, where, whence=0):
  303. self._open_if_needed()
  304. self._fileobj.seek(where, whence)
  305. def tell(self):
  306. if self._fileobj is None:
  307. return self._start_byte
  308. return self._fileobj.tell()
  309. def close(self):
  310. if self._fileobj:
  311. self._fileobj.close()
  312. def __enter__(self):
  313. self._open_if_needed()
  314. return self
  315. def __exit__(self, *args, **kwargs):
  316. self.close()
  317. class ReadFileChunk:
  318. def __init__(
  319. self,
  320. fileobj,
  321. chunk_size,
  322. full_file_size,
  323. callbacks=None,
  324. enable_callbacks=True,
  325. close_callbacks=None,
  326. ):
  327. """
  328. Given a file object shown below::
  329. |___________________________________________________|
  330. 0 | | full_file_size
  331. |----chunk_size---|
  332. f.tell()
  333. :type fileobj: file
  334. :param fileobj: File like object
  335. :type chunk_size: int
  336. :param chunk_size: The max chunk size to read. Trying to read
  337. pass the end of the chunk size will behave like you've
  338. reached the end of the file.
  339. :type full_file_size: int
  340. :param full_file_size: The entire content length associated
  341. with ``fileobj``.
  342. :type callbacks: A list of function(amount_read)
  343. :param callbacks: Called whenever data is read from this object in the
  344. order provided.
  345. :type enable_callbacks: boolean
  346. :param enable_callbacks: True if to run callbacks. Otherwise, do not
  347. run callbacks
  348. :type close_callbacks: A list of function()
  349. :param close_callbacks: Called when close is called. The function
  350. should take no arguments.
  351. """
  352. self._fileobj = fileobj
  353. self._start_byte = self._fileobj.tell()
  354. self._size = self._calculate_file_size(
  355. self._fileobj,
  356. requested_size=chunk_size,
  357. start_byte=self._start_byte,
  358. actual_file_size=full_file_size,
  359. )
  360. # _amount_read represents the position in the chunk and may exceed
  361. # the chunk size, but won't allow reads out of bounds.
  362. self._amount_read = 0
  363. self._callbacks = callbacks
  364. if callbacks is None:
  365. self._callbacks = []
  366. self._callbacks_enabled = enable_callbacks
  367. self._close_callbacks = close_callbacks
  368. if close_callbacks is None:
  369. self._close_callbacks = close_callbacks
  370. @classmethod
  371. def from_filename(
  372. cls,
  373. filename,
  374. start_byte,
  375. chunk_size,
  376. callbacks=None,
  377. enable_callbacks=True,
  378. ):
  379. """Convenience factory function to create from a filename.
  380. :type start_byte: int
  381. :param start_byte: The first byte from which to start reading.
  382. :type chunk_size: int
  383. :param chunk_size: The max chunk size to read. Trying to read
  384. pass the end of the chunk size will behave like you've
  385. reached the end of the file.
  386. :type full_file_size: int
  387. :param full_file_size: The entire content length associated
  388. with ``fileobj``.
  389. :type callbacks: function(amount_read)
  390. :param callbacks: Called whenever data is read from this object.
  391. :type enable_callbacks: bool
  392. :param enable_callbacks: Indicate whether to invoke callback
  393. during read() calls.
  394. :rtype: ``ReadFileChunk``
  395. :return: A new instance of ``ReadFileChunk``
  396. """
  397. f = open(filename, 'rb')
  398. f.seek(start_byte)
  399. file_size = os.fstat(f.fileno()).st_size
  400. return cls(f, chunk_size, file_size, callbacks, enable_callbacks)
  401. def _calculate_file_size(
  402. self, fileobj, requested_size, start_byte, actual_file_size
  403. ):
  404. max_chunk_size = actual_file_size - start_byte
  405. return min(max_chunk_size, requested_size)
  406. def read(self, amount=None):
  407. amount_left = max(self._size - self._amount_read, 0)
  408. if amount is None:
  409. amount_to_read = amount_left
  410. else:
  411. amount_to_read = min(amount_left, amount)
  412. data = self._fileobj.read(amount_to_read)
  413. self._amount_read += len(data)
  414. if self._callbacks is not None and self._callbacks_enabled:
  415. invoke_progress_callbacks(self._callbacks, len(data))
  416. return data
  417. def signal_transferring(self):
  418. self.enable_callback()
  419. if hasattr(self._fileobj, 'signal_transferring'):
  420. self._fileobj.signal_transferring()
  421. def signal_not_transferring(self):
  422. self.disable_callback()
  423. if hasattr(self._fileobj, 'signal_not_transferring'):
  424. self._fileobj.signal_not_transferring()
  425. def enable_callback(self):
  426. self._callbacks_enabled = True
  427. def disable_callback(self):
  428. self._callbacks_enabled = False
  429. def seek(self, where, whence=0):
  430. if whence not in (0, 1, 2):
  431. # Mimic io's error for invalid whence values
  432. raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)")
  433. # Recalculate where based on chunk attributes so seek from file
  434. # start (whence=0) is always used
  435. where += self._start_byte
  436. if whence == 1:
  437. where += self._amount_read
  438. elif whence == 2:
  439. where += self._size
  440. self._fileobj.seek(max(where, self._start_byte))
  441. if self._callbacks is not None and self._callbacks_enabled:
  442. # To also rewind the callback() for an accurate progress report
  443. bounded_where = max(min(where - self._start_byte, self._size), 0)
  444. bounded_amount_read = min(self._amount_read, self._size)
  445. amount = bounded_where - bounded_amount_read
  446. invoke_progress_callbacks(
  447. self._callbacks, bytes_transferred=amount
  448. )
  449. self._amount_read = max(where - self._start_byte, 0)
  450. def close(self):
  451. if self._close_callbacks is not None and self._callbacks_enabled:
  452. for callback in self._close_callbacks:
  453. callback()
  454. self._fileobj.close()
  455. def tell(self):
  456. return self._amount_read
  457. def __len__(self):
  458. # __len__ is defined because requests will try to determine the length
  459. # of the stream to set a content length. In the normal case
  460. # of the file it will just stat the file, but we need to change that
  461. # behavior. By providing a __len__, requests will use that instead
  462. # of stat'ing the file.
  463. return self._size
  464. def __enter__(self):
  465. return self
  466. def __exit__(self, *args, **kwargs):
  467. self.close()
  468. def __iter__(self):
  469. # This is a workaround for http://bugs.python.org/issue17575
  470. # Basically httplib will try to iterate over the contents, even
  471. # if its a file like object. This wasn't noticed because we've
  472. # already exhausted the stream so iterating over the file immediately
  473. # stops, which is what we're simulating here.
  474. return iter([])
  475. class StreamReaderProgress:
  476. """Wrapper for a read only stream that adds progress callbacks."""
  477. def __init__(self, stream, callbacks=None):
  478. self._stream = stream
  479. self._callbacks = callbacks
  480. if callbacks is None:
  481. self._callbacks = []
  482. def read(self, *args, **kwargs):
  483. value = self._stream.read(*args, **kwargs)
  484. invoke_progress_callbacks(self._callbacks, len(value))
  485. return value
  486. class NoResourcesAvailable(Exception):
  487. pass
  488. class TaskSemaphore:
  489. def __init__(self, count):
  490. """A semaphore for the purpose of limiting the number of tasks
  491. :param count: The size of semaphore
  492. """
  493. self._semaphore = threading.Semaphore(count)
  494. def acquire(self, tag, blocking=True):
  495. """Acquire the semaphore
  496. :param tag: A tag identifying what is acquiring the semaphore. Note
  497. that this is not really needed to directly use this class but is
  498. needed for API compatibility with the SlidingWindowSemaphore
  499. implementation.
  500. :param block: If True, block until it can be acquired. If False,
  501. do not block and raise an exception if cannot be acquired.
  502. :returns: A token (can be None) to use when releasing the semaphore
  503. """
  504. logger.debug("Acquiring %s", tag)
  505. if not self._semaphore.acquire(blocking):
  506. raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag)
  507. def release(self, tag, acquire_token):
  508. """Release the semaphore
  509. :param tag: A tag identifying what is releasing the semaphore
  510. :param acquire_token: The token returned from when the semaphore was
  511. acquired. Note that this is not really needed to directly use this
  512. class but is needed for API compatibility with the
  513. SlidingWindowSemaphore implementation.
  514. """
  515. logger.debug(f"Releasing acquire {tag}/{acquire_token}")
  516. self._semaphore.release()
  517. class SlidingWindowSemaphore(TaskSemaphore):
  518. """A semaphore used to coordinate sequential resource access.
  519. This class is similar to the stdlib BoundedSemaphore:
  520. * It's initialized with a count.
  521. * Each call to ``acquire()`` decrements the counter.
  522. * If the count is at zero, then ``acquire()`` will either block until the
  523. count increases, or if ``blocking=False``, then it will raise
  524. a NoResourcesAvailable exception indicating that it failed to acquire the
  525. semaphore.
  526. The main difference is that this semaphore is used to limit
  527. access to a resource that requires sequential access. For example,
  528. if I want to access resource R that has 20 subresources R_0 - R_19,
  529. this semaphore can also enforce that you only have a max range of
  530. 10 at any given point in time. You must also specify a tag name
  531. when you acquire the semaphore. The sliding window semantics apply
  532. on a per tag basis. The internal count will only be incremented
  533. when the minimum sequence number for a tag is released.
  534. """
  535. def __init__(self, count):
  536. self._count = count
  537. # Dict[tag, next_sequence_number].
  538. self._tag_sequences = defaultdict(int)
  539. self._lowest_sequence = {}
  540. self._lock = threading.Lock()
  541. self._condition = threading.Condition(self._lock)
  542. # Dict[tag, List[sequence_number]]
  543. self._pending_release = {}
  544. def current_count(self):
  545. with self._lock:
  546. return self._count
  547. def acquire(self, tag, blocking=True):
  548. logger.debug("Acquiring %s", tag)
  549. self._condition.acquire()
  550. try:
  551. if self._count == 0:
  552. if not blocking:
  553. raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag)
  554. else:
  555. while self._count == 0:
  556. self._condition.wait()
  557. # self._count is no longer zero.
  558. # First, check if this is the first time we're seeing this tag.
  559. sequence_number = self._tag_sequences[tag]
  560. if sequence_number == 0:
  561. # First time seeing the tag, so record we're at 0.
  562. self._lowest_sequence[tag] = sequence_number
  563. self._tag_sequences[tag] += 1
  564. self._count -= 1
  565. return sequence_number
  566. finally:
  567. self._condition.release()
  568. def release(self, tag, acquire_token):
  569. sequence_number = acquire_token
  570. logger.debug("Releasing acquire %s/%s", tag, sequence_number)
  571. self._condition.acquire()
  572. try:
  573. if tag not in self._tag_sequences:
  574. raise ValueError("Attempted to release unknown tag: %s" % tag)
  575. max_sequence = self._tag_sequences[tag]
  576. if self._lowest_sequence[tag] == sequence_number:
  577. # We can immediately process this request and free up
  578. # resources.
  579. self._lowest_sequence[tag] += 1
  580. self._count += 1
  581. self._condition.notify()
  582. queued = self._pending_release.get(tag, [])
  583. while queued:
  584. if self._lowest_sequence[tag] == queued[-1]:
  585. queued.pop()
  586. self._lowest_sequence[tag] += 1
  587. self._count += 1
  588. else:
  589. break
  590. elif self._lowest_sequence[tag] < sequence_number < max_sequence:
  591. # We can't do anything right now because we're still waiting
  592. # for the min sequence for the tag to be released. We have
  593. # to queue this for pending release.
  594. self._pending_release.setdefault(tag, []).append(
  595. sequence_number
  596. )
  597. self._pending_release[tag].sort(reverse=True)
  598. else:
  599. raise ValueError(
  600. "Attempted to release unknown sequence number "
  601. "%s for tag: %s" % (sequence_number, tag)
  602. )
  603. finally:
  604. self._condition.release()
  605. class ChunksizeAdjuster:
  606. def __init__(
  607. self,
  608. max_size=MAX_SINGLE_UPLOAD_SIZE,
  609. min_size=MIN_UPLOAD_CHUNKSIZE,
  610. max_parts=MAX_PARTS,
  611. ):
  612. self.max_size = max_size
  613. self.min_size = min_size
  614. self.max_parts = max_parts
  615. def adjust_chunksize(self, current_chunksize, file_size=None):
  616. """Get a chunksize close to current that fits within all S3 limits.
  617. :type current_chunksize: int
  618. :param current_chunksize: The currently configured chunksize.
  619. :type file_size: int or None
  620. :param file_size: The size of the file to upload. This might be None
  621. if the object being transferred has an unknown size.
  622. :returns: A valid chunksize that fits within configured limits.
  623. """
  624. chunksize = current_chunksize
  625. if file_size is not None:
  626. chunksize = self._adjust_for_max_parts(chunksize, file_size)
  627. return self._adjust_for_chunksize_limits(chunksize)
  628. def _adjust_for_chunksize_limits(self, current_chunksize):
  629. if current_chunksize > self.max_size:
  630. logger.debug(
  631. "Chunksize greater than maximum chunksize. "
  632. "Setting to %s from %s." % (self.max_size, current_chunksize)
  633. )
  634. return self.max_size
  635. elif current_chunksize < self.min_size:
  636. logger.debug(
  637. "Chunksize less than minimum chunksize. "
  638. "Setting to %s from %s." % (self.min_size, current_chunksize)
  639. )
  640. return self.min_size
  641. else:
  642. return current_chunksize
  643. def _adjust_for_max_parts(self, current_chunksize, file_size):
  644. chunksize = current_chunksize
  645. num_parts = int(math.ceil(file_size / float(chunksize)))
  646. while num_parts > self.max_parts:
  647. chunksize *= 2
  648. num_parts = int(math.ceil(file_size / float(chunksize)))
  649. if chunksize != current_chunksize:
  650. logger.debug(
  651. "Chunksize would result in the number of parts exceeding the "
  652. "maximum. Setting to %s from %s."
  653. % (chunksize, current_chunksize)
  654. )
  655. return chunksize