B -<`g@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZddl mZddlmZddlmZddlmZddlmZd Zd Zd ZeeZejeeefZd3d dZddZddZddZ d4ddZ!ddZ"ddZ#ddZ$Gddde%Z&Gdd d e%Z'Gd!d"d"e%Z(Gd#d$d$e%Z)Gd%d&d&e%Z*Gd'd(d(e%Z+Gd)d*d*e%Z,Gd+d,d,e-Z.Gd-d.d.e%Z/Gd/d0d0e/Z0Gd1d2d2e%Z1dS)5N) defaultdict)IncompleteReadError)ReadTimeoutError) SOCKET_ERROR) rename_file)seekable) fallocatei'liPcCsdddt|DS)Ncss|]}ttjVqdS)N)randomchoicestring hexdigits).0_r7/tmp/pip-target-7cdyy134/lib/python/s3transfer/utils.py 2sz(random_file_extension..)joinrange)Z num_digitsrrrrandom_file_extension1srcKs"|dkrt|jdr|jdS)N) PutObject UploadPartsignal_not_transferring)hasattrbodyr)requestoperation_namekwargsrrrr5s rcKs"|dkrt|jdr|jdS)N)rrsignal_transferring)rrr)rrrrrrr;s rcCstt|t|S)N)intmathceilfloat)size part_sizerrrcalculate_num_partsAsr&cCsJ||}||dkr.d}|dk r:t|d}n ||d}d||f}|S)aCalculate the range parameter for multipart downloads/copies :type part_size: int :param part_size: The size of the part :type part_index: int :param part_index: The index for which this parts starts. This index starts at zero :type num_parts: int :param num_parts: The total number of parts in the transfer :returns: The value to use for Range parameter on downloads or the CopySourceRange parameter for copies r Nz bytes=%s-%s)str)r%Z part_index num_partsZ total_sizeZ start_rangeZ end_rangeZ range_paramrrrcalculate_range_parameterEs   r*cCsHg}x>|jjjD]0}d|}t||r|tjt|||dqW|S)a Retrieves callbacks from a subscriber :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future the subscriber is associated to. :type callback_type: str :param callback_type: The type of callback to retrieve from the subscriber. Valid types include: * 'queued' * 'progress' * 'done' :returns: A list of callbacks for the type specified. All callbacks are preinjected with the transfer future. Zon_)future)meta call_argsZ subscribersrappend functoolspartialgetattr)Ztransfer_futureZ callback_type callbacks subscriberZ callback_namerrr get_callbacksbs r4cCs |rx|D]}||dq WdS)aCalls all progress callbacks :param callbacks: A list of progress callbacks to invoke :param bytes_transferred: The number of bytes transferred. This is passed to the callbacks. If no bytes were transferred the callbacks will not be invoked because no progress was achieved. It is also possible to receive a negative amount which comes from retrying a transfer request. )bytes_transferredNr)r2r5callbackrrrinvoke_progress_callbackss  r7cCs.i}x$|D]\}}||kr|||<qW|S)aoGets a dictionary filtered by whitelisted keys :param original_dict: The original dictionary of arguments to source keys and values. :param whitelisted_key: A list of keys to include in the filtered dictionary. :returns: A dictionary containing key/values from the original dictionary whose key was included in the whitelist )items)Z original_dictZwhitelisted_keysZ filtered_dictkeyvaluerrrget_filtered_dicts  r;c@seZdZddZdS)CallArgscKs&x |D]\}}t|||q WdS)zA class that records call arguments The call arguments must be passed as keyword arguments. It will set each keyword argument as an attribute of the object along with its associated value. N)r8setattr)selfrargr:rrr__init__szCallArgs.__init__N)__name__ __module__ __qualname__r@rrrrr<sr<c@s(eZdZdZddZddZddZdS) FunctionContainerzAn object that contains a function and any args or kwargs to call it When called the provided function will be called with provided args and kwargs. cOs||_||_||_dS)N)_func_args_kwargs)r>funcargsrrrrr@szFunctionContainer.__init__cCsd|j|j|jfS)Nz'Function: %s with args %s and kwargs %s)rErFrG)r>rrr__repr__szFunctionContainer.__repr__cCs|j|j|jS)N)rErFrG)r>rrr__call__szFunctionContainer.__call__N)rArBrC__doc__r@rJrKrrrrrDsrDc@s<eZdZdZddZeddZddZdd Zd d Z d S) CountCallbackInvokerzAn abstraction to invoke a callback when a shared count reaches zero :param callback: Callback invoke when finalized count reaches zero cCs t|_||_d|_d|_dS)NrF) threadingLock_lock _callback_count _is_finalized)r>r6rrrr@s zCountCallbackInvoker.__init__c Cs|j|jSQRXdS)N)rPrR)r>rrr current_countsz"CountCallbackInvoker.current_countc Cs2|j"|jrtd|jd7_WdQRXdS)zIncrement the count by onez;Counter has been finalized it can no longer be incremented.r'N)rPrS RuntimeErrorrR)r>rrr increments zCountCallbackInvoker.incrementc CsN|j>|jdkrtd|jd8_|jr@|jdkr@|WdQRXdS)zDecrement the count by onerz,Counter is at zero. It cannot dip below zeror'N)rPrRrUrSrQ)r>rrr decrements zCountCallbackInvoker.decrementc Cs.|jd|_|jdkr |WdQRXdS)zFinalize the counter Once finalized, the counter never be incremented and the callback can be invoked once the count reaches zero TrN)rPrSrRrQ)r>rrrfinalizes zCountCallbackInvoker.finalizeN) rArBrCrLr@propertyrTrVrWrXrrrrrMs    rMc@sZeZdZdZddZddZdddZd d Zd d Zd dZ ddZ ddZ ddZ dS)OSUtilscCs tj|S)N)ospathgetsize)r>filenamerrr get_file_sizeszOSUtils.get_file_sizecCstj||||ddS)NF)enable_callbacks) ReadFileChunk from_filename)r>r_ start_byter$r2rrropen_file_chunk_readerszOSUtils.open_file_chunk_readerNcCst||||d|dS)NF)r2raclose_callbacks)rb)r>fileobj chunk_sizefull_file_sizer2rfrrr#open_file_chunk_reader_from_fileobjsz+OSUtils.open_file_chunk_reader_from_fileobjcCs t||S)N)open)r>r_moderrrrksz OSUtils.opencCs(yt|Wntk r"YnXdS)z+Remove a file, noop if file does not exist.N)r\removeOSError)r>r_rrr remove_fileszOSUtils.remove_filecCst||dS)N)r)r>Zcurrent_filenameZ new_filenamerrrrszOSUtils.rename_filecCsXtj|sdSt|j}t|r*dSt|r8dSt|rFdSt|rTdSdS)aChecks to see if a file is a special UNIX file. It checks if the file is a character special device, block special device, FIFO, or socket. :param filename: Name of the file :returns: True if the file is a special file. False, if is not. FT) r\r]existsstatst_modeS_ISCHRS_ISBLKS_ISFIFOS_ISSOCK)clsr_rlrrris_special_files      zOSUtils.is_special_filecCsLtjt}tj|}tj|}|d|jt||}tj||S)N) r\extseprr]dirnamebasename_MAX_FILENAME_LENlenr)r>r_suffixr]nameZ temp_filenamerrrget_temp_filename0s    zOSUtils.get_temp_filenamec CsPy&||d}t||WdQRXWn$ttfk rJ||YnXdS)Nwb)rkrrnIOErrorro)r>r_r$frrrallocate7s  zOSUtils.allocate)N) rArBrCr|r`rerjrkrorrxrrrrrrrZs  rZc@sjeZdZddefddZddZeddZdd d Zd d Z ddZ ddZ ddZ ddZ ddZd S)DeferredOpenFilerrbcCs"||_d|_||_||_||_dS)aA class that defers the opening of a file till needed This is useful for deferring opening of a file till it is needed in a separate thread, as there is a limit of how many open files there can be in a single thread for most operating systems. The file gets opened in the following methods: ``read()``, ``seek()``, and ``__enter__()`` :type filename: str :param filename: The name of the file to open :type start_byte: int :param start_byte: The byte to seek to when the file is opened. :type mode: str :param mode: The mode to use to open the file :type open_function: function :param open_function: The function to use to open the file N) _filename_fileobj _start_byte_mode_open_function)r>r_rdrlZ open_functionrrrr@As zDeferredOpenFile.__init__cCs8|jdkr4||j|j|_|jdkr4|j|jdS)Nr)rrrrrseek)r>rrr_open_if_needed\s  z DeferredOpenFile._open_if_neededcCs|jS)N)r)r>rrrrbszDeferredOpenFile.nameNcCs||j|S)N)rrread)r>amountrrrrfszDeferredOpenFile.readcCs||j|dS)N)rrwrite)r>datarrrrjszDeferredOpenFile.writecCs||j|dS)N)rrr)r>whererrrrnszDeferredOpenFile.seekcCs|jdkr|jS|jS)N)rrtell)r>rrrrrs zDeferredOpenFile.tellcCs|jr|jdS)N)rclose)r>rrrrwszDeferredOpenFile.closecCs ||S)N)r)r>rrr __enter__{szDeferredOpenFile.__enter__cOs |dS)N)r)r>rIrrrr__exit__szDeferredOpenFile.__exit__)N)rArBrCrkr@rrYrrrrrrrrrrrrr@s  rc@seZdZd!ddZed"ddZddZd#d d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd ZdS)$rbNTcCsb||_|j|_|j|j||j|d|_d|_||_|dkrDg|_||_||_|dkr^||_dS)a Given a file object shown below:: |___________________________________________________| 0 | | full_file_size |----chunk_size---| f.tell() :type fileobj: file :param fileobj: File like object :type chunk_size: int :param chunk_size: The max chunk size to read. Trying to read pass the end of the chunk size will behave like you've reached the end of the file. :type full_file_size: int :param full_file_size: The entire content length associated with ``fileobj``. :type callbacks: A list of function(amount_read) :param callbacks: Called whenever data is read from this object in the order provided. :type enable_callbacks: boolean :param enable_callbacks: True if to run callbacks. Otherwise, do not run callbacks :type close_callbacks: A list of function() :param close_callbacks: Called when close is called. The function should take no arguments. )requested_sizerdactual_file_sizerN) rrr_calculate_file_size_size _amount_read _callbacks_callbacks_enabled_close_callbacks)r>rgrhrir2rarfrrrr@s# zReadFileChunk.__init__cCs4t|d}||t|j}||||||S)a[Convenience factory function to create from a filename. :type start_byte: int :param start_byte: The first byte from which to start reading. :type chunk_size: int :param chunk_size: The max chunk size to read. Trying to read pass the end of the chunk size will behave like you've reached the end of the file. :type full_file_size: int :param full_file_size: The entire content length associated with ``fileobj``. :type callbacks: function(amount_read) :param callbacks: Called whenever data is read from this object. :type enable_callbacks: bool :param enable_callbacks: Indicate whether to invoke callback during read() calls. :rtype: ``ReadFileChunk`` :return: A new instance of ``ReadFileChunk`` r)rkrr\fstatfilenost_size)rwr_rdrhr2rar file_sizerrrrcs  zReadFileChunk.from_filenamecCs||}t||S)N)min)r>rgrrdrZmax_chunk_sizerrrrsz"ReadFileChunk._calculate_file_sizecCsj|dkr|j|j}nt|j|j|}|j|}|jt|7_|jdk rf|jrft|jt||S)N) rrrrrr}rrr7)r>rZamount_to_readrrrrrs zReadFileChunk.readcCs"|t|jdr|jdS)Nr)enable_callbackrrr)r>rrrrs z!ReadFileChunk.signal_transferringcCs"|t|jdr|jdS)Nr)disable_callbackrrr)r>rrrrs z%ReadFileChunk.signal_not_transferringcCs d|_dS)NT)r)r>rrrrszReadFileChunk.enable_callbackcCs d|_dS)NF)r)r>rrrrszReadFileChunk.disable_callbackcCs@|j|j||jdk r6|jr6t|j||jd||_dS)N)r5)rrrrrr7r)r>rrrrrs zReadFileChunk.seekcCs4|jdk r&|jr&x|jD] }|qW|jdS)N)rrrr)r>r6rrrrs  zReadFileChunk.closecCs|jS)N)r)r>rrrrszReadFileChunk.tellcCs|jS)N)r)r>rrr__len__szReadFileChunk.__len__cCs|S)Nr)r>rrrrszReadFileChunk.__enter__cOs |dS)N)r)r>rIrrrrrszReadFileChunk.__exit__cCstgS)N)iter)r>rrr__iter__szReadFileChunk.__iter__)NTN)NT)N)rArBrCr@ classmethodrcrrrrrrrrrrrrrrrrrrbs" 0  rbc@s"eZdZdZdddZddZdS)StreamReaderProgresszstreamr2rrrr@ szStreamReaderProgress.__init__cOs"|jj||}t|jt||S)N)rrr7rr})r>rIrr:rrrr&szStreamReaderProgress.read)N)rArBrCrLr@rrrrrrs rc@s eZdZdS)NoResourcesAvailableN)rArBrCrrrrr,src@s&eZdZddZd ddZddZdS) TaskSemaphorecCst||_dS)zqA semaphore for the purpose of limiting the number of tasks :param count: The size of semaphore N)rN Semaphore _semaphore)r>countrrrr@1szTaskSemaphore.__init__TcCs(td||j|s$td|dS)aAcquire the semaphore :param tag: A tag identifying what is acquiring the semaphore. Note that this is not really needed to directly use this class but is needed for API compatibility with the SlidingWindowSemaphore implementation. :param block: If True, block until it can be acquired. If False, do not block and raise an exception if cannot be aquired. :returns: A token (can be None) to use when releasing the semaphore z Acquiring %szCannot acquire tag '%s'N)loggerdebugracquirer)r>tagblockingrrrr8s  zTaskSemaphore.acquirecCs td||f|jdS)atRelease the semaphore :param tag: A tag identifying what is releasing the semaphore :param acquire_token: The token returned from when the semaphore was acquired. Note that this is not really needed to directly use this class but is needed for API compatibility with the SlidingWindowSemaphore implementation. zReleasing acquire %s/%sN)rrrrelease)r>r acquire_tokenrrrrHs zTaskSemaphore.releaseN)T)rArBrCr@rrrrrrr0s rc@s2eZdZdZddZddZd ddZd d Zd S) SlidingWindowSemaphoreaA semaphore used to coordinate sequential resource access. This class is similar to the stdlib BoundedSemaphore: * It's initialized with a count. * Each call to ``acquire()`` decrements the counter. * If the count is at zero, then ``acquire()`` will either block until the count increases, or if ``blocking=False``, then it will raise a NoResourcesAvailable exception indicating that it failed to acquire the semaphore. The main difference is that this semaphore is used to limit access to a resource that requires sequential access. For example, if I want to access resource R that has 20 subresources R_0 - R_19, this semaphore can also enforce that you only have a max range of 10 at any given point in time. You must also specify a tag name when you acquire the semaphore. The sliding window semantics apply on a per tag basis. The internal count will only be incremented when the minimum sequence number for a tag is released. cCs8||_tt|_i|_t|_t|j|_ i|_ dS)N) rRrr _tag_sequences_lowest_sequencerNrOrP Condition _condition_pending_release)r>rrrrr@ks   zSlidingWindowSemaphore.__init__c Cs|j|jSQRXdS)N)rPrR)r>rrrrTusz$SlidingWindowSemaphore.current_countTcCstd||jzv|jdkrN|s4td|nx|jdkrL|jq6W|j|}|dkrj||j|<|j|d7<|jd8_|S|j XdS)Nz Acquiring %srzCannot acquire tag '%s'r') rrrrrRrwaitrrr)r>rrsequence_numberrrrrys      zSlidingWindowSemaphore.acquirecCs<|}td|||jz ||jkr6td||j|}|j||kr|j|d7<|jd7_|j|j |g}x|r|j||dkr| |j|d7<|jd7_qPqWnX|j||kr|krnn(|j |g ||j |jddntd||fWd|jXdS)NzReleasing acquire %s/%sz$Attempted to release unknown tag: %sr'T)reversez;Attempted to release unknown sequence number %s for tag: %s)rrrrr ValueErrorrrRnotifyrgetpop setdefaultr.sortr)r>rrrZ max_sequenceZqueuedrrrrs4      zSlidingWindowSemaphore.releaseN)T)rArBrCrLr@rTrrrrrrrUs   rc@s6eZdZeeefddZd ddZddZdd Z dS) ChunksizeAdjustercCs||_||_||_dS)N)max_sizemin_size max_parts)r>rrrrrrr@szChunksizeAdjuster.__init__NcCs"|}|dk r|||}||S)aGet a chunksize close to current that fits within all S3 limits. :type current_chunksize: int :param current_chunksize: The currently configured chunksize. :type file_size: int or None :param file_size: The size of the file to upload. This might be None if the object being transferred has an unknown size. :returns: A valid chunksize that fits within configured limits. N)_adjust_for_max_parts_adjust_for_chunksize_limits)r>current_chunksizer chunksizerrradjust_chunksizes  z"ChunksizeAdjuster.adjust_chunksizecCsP||jkr$td|j|f|jS||jkrHtd|j|f|jS|SdS)Nz@Chunksize greater than maximum chunksize. Setting to %s from %s.z=Chunksize less than minimum chunksize. Setting to %s from %s.)rrrr)r>rrrrrs  z.ChunksizeAdjuster._adjust_for_chunksize_limitscCsf|}tt|t|}x,||jkrF|d9}tt|t|}qW||krbtd||f|S)Nz[Chunksize would result in the number of parts exceeding the maximum. Setting to %s from %s.)r r!r"r#rrr)r>rrrr)rrrrs  z'ChunksizeAdjuster._adjust_for_max_parts)N) rArBrCMAX_SINGLE_UPLOAD_SIZEMIN_UPLOAD_CHUNKSIZE MAX_PARTSr@rrrrrrrrs  r)r )N)2r timer/r!r\socketrqr loggingrNio collectionsrZbotocore.exceptionsrrZs3transfer.compatrrrrrrr getLoggerrArtimeoutZS3_RETRYABLE_DOWNLOAD_ERRORSrrrr&r*r4r7r;objectr<rDrMrZrrbr Exceptionrrrrrrrr sT           0OC%_