U
    O8c~j                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZmZ d dlmZmZmZ dZdZdZeeZejeeefZd/d	d
Zdd Zdd Zdd Zd0ddZdd Zdd Z dd Z!G dd dZ"G dd dZ#G dd dZ$G dd  d Z%G d!d" d"Z&G d#d$ d$Z'G d%d& d&Z(G d'd( d(e)Z*G d)d* d*Z+G d+d, d,e+Z,G d-d. d.Z-dS )1    N)defaultdict)IncompleteReadErrorReadTimeoutError)SOCKET_ERROR	fallocaterename_filei'  l        i  P    c                 C   s   d dd t| D S )N c                 s   s   | ]}t tjV  qd S N)randomchoicestring	hexdigits).0_ r   4/tmp/pip-unpacked-wheel-6hpttf6a/s3transfer/utils.py	<genexpr>.   s     z(random_file_extension.<locals>.<genexpr>)joinrange)Z
num_digitsr   r   r   random_file_extension-   s    r   c                 K   s"   |dkrt | jdr| j  d S )NZ	PutObjectZ
UploadPartsignal_not_transferring)hasattrbodyr   requestZoperation_namekwargsr   r   r   r   1   s
    
 r   c                 K   s"   |dkrt | jdr| j  d S )Nr   signal_transferring)r   r   r   r   r   r   r   r   8   s
    
 r   c                 C   s   t t| t| S r
   )intmathceilfloat)size	part_sizer   r   r   calculate_num_parts?   s    r%   c                 C   sN   ||  }||d kr.d}|dk	r:t |d }n||  d }d| d| }|S )a  Calculate 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=-)str)r$   Z
part_index	num_partsZ
total_sizeZstart_rangeZ	end_rangeZrange_paramr   r   r   calculate_range_parameterC   s    r*   c                 C   sD   g }| j jjD ]0}d| }t||r|tjt||| d q|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.
    Zon_)future)metaZ	call_argsZsubscribersr   append	functoolspartialgetattr)Ztransfer_futureZcallback_type	callbacks
subscriberZcallback_namer   r   r   get_callbacksa   s    
 r3   c                 C   s   |r| D ]}||d qdS )a  Calls 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   )r1   r5   callbackr   r   r   invoke_progress_callbacks~   s    r7   c                 C   s*   i }|   D ]\}}||kr|||< q|S )ao  Gets 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_dictZwhitelisted_keysZfiltered_dictkeyvaluer   r   r   get_filtered_dict   s
    
r;   c                   @   s   e Zd Zdd ZdS )CallArgsc                 K   s"   |  D ]\}}t| || qdS )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)r8   setattr)selfr   argr:   r   r   r   __init__   s    zCallArgs.__init__N)__name__
__module____qualname__r@   r   r   r   r   r<      s   r<   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	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.
    c                 O   s   || _ || _|| _d S r
   _func_args_kwargs)r>   funcargsr   r   r   r   r@      s    zFunctionContainer.__init__c                 C   s   d | j| j| jS )Nz'Function: {} with args {} and kwargs {})formatrF   rG   rH   r>   r   r   r   __repr__   s
      zFunctionContainer.__repr__c                 C   s   | j | j| jS r
   rE   rL   r   r   r   __call__   s    zFunctionContainer.__call__N)rA   rB   rC   __doc__r@   rM   rN   r   r   r   r   rD      s   rD   c                   @   s<   e Zd ZdZdd Zedd Zdd Zdd	 Zd
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
    c                 C   s    t  | _|| _d| _d| _d S )Nr   F)	threadingLock_lock	_callback_count_is_finalizedr>   r6   r   r   r   r@      s    
zCountCallbackInvoker.__init__c              
   C   s$   | j  | jW  5 Q R  S Q R X d S r
   rS   rU   rL   r   r   r   current_count   s    z"CountCallbackInvoker.current_countc              	   C   s2   | j " | jrtd|  jd7  _W 5 Q R X dS )zIncrement the count by onez;Counter has been finalized it can no longer be incremented.r&   N)rS   rV   RuntimeErrorrU   rL   r   r   r   	increment   s    zCountCallbackInvoker.incrementc              	   C   sN   | j > | jdkrtd|  jd8  _| jr@| jdkr@|   W 5 Q R X dS )zDecrement the count by oner   z,Counter is at zero. It cannot dip below zeror&   N)rS   rU   rZ   rV   rT   rL   r   r   r   	decrement   s    
zCountCallbackInvoker.decrementc              	   C   s.   | j  d| _| jdkr |   W 5 Q R X dS )zFinalize the counter

        Once finalized, the counter never be incremented and the callback
        can be invoked once the count reaches zero
        Tr   N)rS   rV   rU   rT   rL   r   r   r   finalize   s    
zCountCallbackInvoker.finalizeN)
rA   rB   rC   rO   r@   propertyrY   r[   r\   r]   r   r   r   r   rP      s   

rP   c                   @   sZ   e Zd ZdZdd Zdd ZdddZd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdS )OSUtils   c                 C   s   t j|S r
   )ospathgetsizer>   filenamer   r   r   get_file_size   s    zOSUtils.get_file_sizec                 C   s   t j||||ddS )NF)enable_callbacks)ReadFileChunkfrom_filename)r>   re   
start_byter#   r1   r   r   r   open_file_chunk_reader   s        zOSUtils.open_file_chunk_readerNc                 C   s   t ||||d|dS )NF)r1   rg   close_callbacks)rh   )r>   fileobj
chunk_sizefull_file_sizer1   rl   r   r   r   #open_file_chunk_reader_from_fileobj   s    z+OSUtils.open_file_chunk_reader_from_fileobjc                 C   s
   t ||S r
   )open)r>   re   moder   r   r   rq     s    zOSUtils.openc                 C   s(   zt | W n tk
r"   Y nX dS )z+Remove a file, noop if file does not exist.N)ra   removeOSErrorrd   r   r   r   remove_file  s    zOSUtils.remove_filec                 C   s   t || d S r
   )r   )r>   Zcurrent_filenameZnew_filenamer   r   r   r     s    zOSUtils.rename_filec                 C   sX   t j|sdS t |j}t|r*dS t|r8dS t|rFdS t|rTdS dS )a  Checks 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)	ra   rb   existsstatst_modeS_ISCHRS_ISBLKS_ISFIFOS_ISSOCK)clsre   rr   r   r   r   is_special_file  s    



zOSUtils.is_special_filec                 C   sL   t jt  }t j|}t j|}|d | jt|  | }t j||S r
   )	ra   extsepr   rb   dirnamebasename_MAX_FILENAME_LENlenr   )r>   re   suffixrb   nameZtemp_filenamer   r   r   get_temp_filename;  s
    zOSUtils.get_temp_filenamec              	   C   sL   z&|  |d}t|| W 5 Q R X W n  tk
rF   | |  Y nX d S )Nwb)rq   r   rt   ru   )r>   re   r#   fr   r   r   allocateB  s    
zOSUtils.allocate)N)rA   rB   rC   r   rf   rk   rp   rq   ru   r   r~   r   r   r   r   r   r   r_      s    
	r_   c                   @   sl   e Zd ZddefddZdd Zedd Zdd
dZdd Z	dddZ
dd Zdd Zdd Zdd Zd	S )DeferredOpenFiler   rbc                 C   s"   || _ d| _|| _|| _|| _dS )a  A 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>   re   rj   rr   Zopen_functionr   r   r   r@   L  s
    zDeferredOpenFile.__init__c                 C   s8   | j d kr4| | j| j| _ | jdkr4| j | j d S Nr   )r   r   r   r   r   seekrL   r   r   r   _open_if_neededg  s    

z DeferredOpenFile._open_if_neededc                 C   s   | j S r
   )r   rL   r   r   r   r   m  s    zDeferredOpenFile.nameNc                 C   s   |    | j|S r
   )r   r   read)r>   amountr   r   r   r   q  s    zDeferredOpenFile.readc                 C   s   |    | j| d S r
   )r   r   write)r>   datar   r   r   r   u  s    zDeferredOpenFile.writec                 C   s   |    | j|| d S r
   )r   r   r   )r>   wherewhencer   r   r   r   y  s    zDeferredOpenFile.seekc                 C   s   | j d kr| jS | j  S r
   )r   r   tellrL   r   r   r   r   }  s    
zDeferredOpenFile.tellc                 C   s   | j r| j   d S r
   )r   closerL   r   r   r   r     s    zDeferredOpenFile.closec                 C   s   |    | S r
   )r   rL   r   r   r   	__enter__  s    zDeferredOpenFile.__enter__c                 O   s   |    d S r
   r   r>   rJ   r   r   r   r   __exit__  s    zDeferredOpenFile.__exit__)N)r   )rA   rB   rC   rq   r@   r   r^   r   r   r   r   r   r   r   r   r   r   r   r   r   K  s   


r   c                   @   s   e Zd Zd"ddZed#ddZdd Zd$d	d
Zdd Zdd Z	dd Z
dd Zd%ddZdd Zdd Zdd Zdd Zdd Zd d! ZdS )&rh   NTc                 C   sb   || _ | j  | _| j| j || j|d| _d| _|| _|dkrDg | _|| _|| _|dkr^|| _dS )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_sizerj   actual_file_sizer   N)	r   r   r   _calculate_file_size_size_amount_read
_callbacks_callbacks_enabled_close_callbacks)r>   rm   rn   ro   r1   rg   rl   r   r   r   r@     s     *zReadFileChunk.__init__c                 C   s4   t |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   )rq   r   ra   fstatfilenost_size)r}   re   rj   rn   r1   rg   r   	file_sizer   r   r   ri     s    "

zReadFileChunk.from_filenamec                 C   s   || }t ||S r
   )min)r>   rm   r   rj   r   Zmax_chunk_sizer   r   r   r     s    z"ReadFileChunk._calculate_file_sizec                 C   sl   t | j| j d}|d kr |}n
t||}| j|}|  jt|7  _| jd k	rh| jrht	| jt| |S r   )
maxr   r   r   r   r   r   r   r   r7   )r>   r   Zamount_leftZamount_to_readr   r   r   r   r     s    
zReadFileChunk.readc                 C   s"   |    t| jdr| j  d S )Nr   )enable_callbackr   r   r   rL   r   r   r   r     s    z!ReadFileChunk.signal_transferringc                 C   s"   |    t| jdr| j  d S )Nr   )disable_callbackr   r   r   rL   r   r   r   r   
  s    z%ReadFileChunk.signal_not_transferringc                 C   s
   d| _ d S )NTr   rL   r   r   r   r     s    zReadFileChunk.enable_callbackc                 C   s
   d| _ d S )NFr   rL   r   r   r   r     s    zReadFileChunk.disable_callbackr   c                 C   s   |dkrt d| d|| j7 }|dkr6|| j7 }n|dkrH|| j7 }| jt|| j | jd k	r| jrtt	|| j | jd}t	| j| j}|| }t
| j|d t|| j d| _d S )N)r   r&      zinvalid whence (z, should be 0, 1 or 2)r&   r   r   r4   )
ValueErrorr   r   r   r   r   r   r   r   r   r7   )r>   r   r   Zbounded_whereZbounded_amount_readr   r   r   r   r     s"    

 zReadFileChunk.seekc                 C   s0   | j d k	r"| jr"| j D ]
}|  q| j  d S r
   )r   r   r   r   rW   r   r   r   r   -  s    
zReadFileChunk.closec                 C   s   | j S r
   )r   rL   r   r   r   r   3  s    zReadFileChunk.tellc                 C   s   | j S r
   )r   rL   r   r   r   __len__6  s    zReadFileChunk.__len__c                 C   s   | S r
   r   rL   r   r   r   r   >  s    zReadFileChunk.__enter__c                 O   s   |    d S r
   r   r   r   r   r   r   A  s    zReadFileChunk.__exit__c                 C   s   t g S r
   )iterrL   r   r   r   __iter__D  s    zReadFileChunk.__iter__)NTN)NT)N)r   )rA   rB   rC   r@   classmethodri   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rh     s*      
=  &

rh   c                   @   s"   e Zd ZdZdddZdd ZdS )StreamReaderProgressz<Wrapper for a read only stream that adds progress callbacks.Nc                 C   s   || _ || _|d krg | _d S r
   )_streamr   )r>   streamr1   r   r   r   r@   P  s    zStreamReaderProgress.__init__c                 O   s"   | j j||}t| jt| |S r
   )r   r   r7   r   r   )r>   rJ   r   r:   r   r   r   r   V  s    zStreamReaderProgress.read)N)rA   rB   rC   rO   r@   r   r   r   r   r   r   M  s   
r   c                   @   s   e Zd ZdS )NoResourcesAvailableN)rA   rB   rC   r   r   r   r   r   \  s   r   c                   @   s&   e Zd Zdd Zd	ddZdd ZdS )
TaskSemaphorec                 C   s   t || _dS )zqA semaphore for the purpose of limiting the number of tasks

        :param count: The size of semaphore
        N)rQ   	Semaphore
_semaphorer>   countr   r   r   r@   a  s    zTaskSemaphore.__init__Tc                 C   s(   t d| | j|s$td| dS )a  Acquire 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 acquired.

        :returns: A token (can be None) to use when releasing the semaphore
        Acquiring %sCannot acquire tag '%s'N)loggerdebugr   acquirer   )r>   tagblockingr   r   r   r   h  s    zTaskSemaphore.acquirec                 C   s$   t d| d|  | j  dS )at  Release 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.
        zReleasing acquire /N)r   r   r   release)r>   r   acquire_tokenr   r   r   r   x  s    	zTaskSemaphore.releaseN)T)rA   rB   rC   r@   r   r   r   r   r   r   r   `  s   
r   c                   @   s2   e Zd ZdZdd Zdd ZdddZd	d
 ZdS )SlidingWindowSemaphorea  A 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.

    c                 C   s8   || _ tt| _i | _t | _t| j| _	i | _
d S r
   )rU   r   r   _tag_sequences_lowest_sequencerQ   rR   rS   	Condition
_condition_pending_releaser   r   r   r   r@     s    

zSlidingWindowSemaphore.__init__c              
   C   s$   | j  | jW  5 Q R  S Q R X d S r
   rX   rL   r   r   r   rY     s    z$SlidingWindowSemaphore.current_countTc                 C   s   t d| | j  zv| jdkrJ|s4td| n| jdkrJ| j  q4| j| }|dkrf|| j	|< | j|  d7  < |  jd8  _|W S | j  X d S )Nr   r   r   r&   )
r   r   r   r   r   rU   r   waitr   r   )r>   r   r   sequence_numberr   r   r   r     s    




zSlidingWindowSemaphore.acquirec                 C   s8  |}t d|| | j  z|| jkr6td| | j| }| j| |kr| j|  d7  < |  jd7  _| j	  | j
|g }|r| j| |d kr|  | j|  d7  < |  jd7  _qqqnX| j| |  k r|k rn n(| j
|g | | j
| jdd ntd||f W 5 | j  X d S )NzReleasing acquire %s/%sz$Attempted to release unknown tag: %sr&   T)reversez;Attempted to release unknown sequence number %s for tag: %s)r   r   r   r   r   r   r   r   rU   notifyr   getpop
setdefaultr-   sort)r>   r   r   r   Zmax_sequenceZqueuedr   r   r   r     s:    



 zSlidingWindowSemaphore.releaseN)T)rA   rB   rC   rO   r@   rY   r   r   r   r   r   r   r     s
   

r   c                   @   s6   e Zd ZeeefddZd
ddZdd Zdd	 Z	dS )ChunksizeAdjusterc                 C   s   || _ || _|| _d S r
   )max_sizemin_size	max_parts)r>   r   r   r   r   r   r   r@     s    zChunksizeAdjuster.__init__Nc                 C   s"   |}|dk	r|  ||}| |S )a  Get 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   	chunksizer   r   r   adjust_chunksize  s    z"ChunksizeAdjuster.adjust_chunksizec                 C   sP   || j kr$td| j |f  | j S || jk rHtd| j|f  | jS |S d S )Nz@Chunksize greater than maximum chunksize. Setting to %s from %s.z=Chunksize less than minimum chunksize. Setting to %s from %s.)r   r   r   r   )r>   r   r   r   r   r     s    

z.ChunksizeAdjuster._adjust_for_chunksize_limitsc                 C   sb   |}t t|t| }|| jkrD|d9 }t t|t| }q||kr^td||f  |S )Nr   z[Chunksize would result in the number of parts exceeding the maximum. Setting to %s from %s.)r   r    r!   r"   r   r   r   )r>   r   r   r   r)   r   r   r   r     s    
z'ChunksizeAdjuster._adjust_for_max_parts)N)
rA   rB   rC   MAX_SINGLE_UPLOAD_SIZEMIN_UPLOAD_CHUNKSIZE	MAX_PARTSr@   r   r   r   r   r   r   r   r     s   


r   )r   )N).r.   loggingr    ra   r   socketrw   r   rQ   collectionsr   Zbotocore.exceptionsr   r   Zs3transfer.compatr   r   r   r   r   r   	getLoggerrA   r   timeoutZS3_RETRYABLE_DOWNLOAD_ERRORSr   r   r   r%   r*   r3   r7   r;   r<   rD   rP   r_   r   rh   r   	Exceptionr   r   r   r   r   r   r   r   <module>   sR   

 
2XC @%b