o
    ܀cpq                     @   sl  d 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
Z
ddlZddlmZ ddlmZ ddlmZ ddlZddlmZmZ dZdZG d	d
 d
ejZeeZee  dZe  Z!d%ddZ"dd Z#dd Z$G dd de%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j+Z,G dd  d Z-G d!d" d"Z.G d#d$ d$Z/dS )&a  Abstractions over S3's upload/download operations.

This module provides high level abstractions for efficient
uploads/downloads.  It handles several things for the user:

* Automatically switching to multipart transfers when
  a file is over a specific size threshold
* Uploading/downloading a file in parallel
* Throttling based on max bandwidth
* Progress callbacks to monitor transfers
* Retries.  While botocore handles retries for streaming uploads,
  it is not possible for it to handle retries for streaming
  downloads.  This module handles retries for both cases so
  you don't need to implement any retry logic yourself.

This module has a reasonable set of defaults.  It also allows you
to configure many aspects of the transfer process including:

* Multipart threshold size
* Max parallel downloads
* Max bandwidth
* Socket timeouts
* Retry amounts

There is no support for s3->s3 multipart copies at this
time.


.. _ref_s3transfer_usage:

Usage
=====

The simplest way to use this module is:

.. code-block:: python

    client = boto3.client('s3', 'us-west-2')
    transfer = S3Transfer(client)
    # Upload /tmp/myfile to s3://bucket/key
    transfer.upload_file('/tmp/myfile', 'bucket', 'key')

    # Download s3://bucket/key to /tmp/myfile
    transfer.download_file('bucket', 'key', '/tmp/myfile')

The ``upload_file`` and ``download_file`` methods also accept
``**kwargs``, which will be forwarded through to the corresponding
client operation.  Here are a few examples using ``upload_file``::

    # Making the object public
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         extra_args={'ACL': 'public-read'})

    # Setting metadata
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         extra_args={'Metadata': {'a': 'b', 'c': 'd'}})

    # Setting content type
    transfer.upload_file('/tmp/myfile.json', 'bucket', 'key',
                         extra_args={'ContentType': "application/json"})


The ``S3Transfer`` class also supports progress callbacks so you can
provide transfer progress to users.  Both the ``upload_file`` and
``download_file`` methods take an optional ``callback`` parameter.
Here's an example of how to print a simple progress percentage
to the user:

.. code-block:: python

    class ProgressPercentage(object):
        def __init__(self, filename):
            self._filename = filename
            self._size = float(os.path.getsize(filename))
            self._seen_so_far = 0
            self._lock = threading.Lock()

        def __call__(self, bytes_amount):
            # To simplify we'll assume this is hooked up
            # to a single filename.
            with self._lock:
                self._seen_so_far += bytes_amount
                percentage = (self._seen_so_far / self._size) * 100
                sys.stdout.write(
                    "%s  %s / %s  (%.2f%%)" % (self._filename, self._seen_so_far,
                                                 self._size, percentage))
                sys.stdout.flush()


    transfer = S3Transfer(boto3.client('s3', 'us-west-2'))
    # Upload /tmp/myfile to s3://bucket/key and print upload progress.
    transfer.upload_file('/tmp/myfile', 'bucket', 'key',
                         callback=ProgressPercentage('/tmp/myfile'))



You can also provide a TransferConfig object to the S3Transfer
object that gives you more fine grained control over the
transfer.  For example:

.. code-block:: python

    client = boto3.client('s3', 'us-west-2')
    config = TransferConfig(
        multipart_threshold=8 * 1024 * 1024,
        max_concurrency=10,
        num_download_attempts=10,
    )
    transfer = S3Transfer(client, config)
    transfer.upload_file('/tmp/foo', 'bucket', 'key')


    N)six)IncompleteReadError)ReadTimeoutError)RetriesExceededErrorS3UploadFailedErrorzAmazon Web Servicesz0.6.0c                   @   s   e Zd Zdd ZdS )NullHandlerc                 C   s   d S N )selfrecordr	   r	   >/usr/local/lib/python3.10/dist-packages/s3transfer/__init__.pyemit      zNullHandler.emitN)__name__
__module____qualname__r   r	   r	   r	   r   r      s    r   i      c                 C   s   d dd t| D S )N c                 s   s    | ]	}t tjV  qd S r   )randomchoicestring	hexdigits).0_r	   r	   r   	<genexpr>   s    z(random_file_extension.<locals>.<genexpr>)joinrange)
num_digitsr	   r	   r   random_file_extension   s   r   c                 K   *   |dv rt | jdr| j  d S d S d S )N	PutObject
UploadPartdisable_callback)hasattrbodyr#   requestoperation_namekwargsr	   r	   r   disable_upload_callbacks   
   
r*   c                 K   r   )Nr    enable_callback)r$   r%   r,   r&   r	   r	   r   enable_upload_callbacks   r+   r-   c                   @   s   e Zd ZdS )QueueShutdownErrorN)r   r   r   r	   r	   r	   r   r.      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 Zdd Zdd Zdd Zdd ZdS )ReadFileChunkNTc                 C   sF   || _ || _| j| j |||d| _| j | j d| _|| _|| _dS )a  

        Given a file object shown below:

            |___________________________________________________|
            0          |                 |                 full_file_size
                       |----chunk_size---|
                 start_byte

        :type fileobj: file
        :param fileobj: File like object

        :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 callback: function(amount_read)
        :param callback: Called whenever data is read from this object.

        )requested_size
start_byteactual_file_sizer   N)_fileobj_start_byte_calculate_file_size_sizeseek_amount_read	_callback_callback_enabled)r
   fileobjr1   
chunk_sizefull_file_sizecallbackr,   r	   r	   r   __init__   s   %
zReadFileChunk.__init__c                 C   s,   t |d}t| j}| ||||||S )aW  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 callback: function(amount_read)
        :param callback: Called whenever data is read from this object.

        :type enable_callback: bool
        :param enable_callback: Indicate whether to invoke callback
            during read() calls.

        :rtype: ``ReadFileChunk``
        :return: A new instance of ``ReadFileChunk``

        rb)openosfstatfilenost_size)clsfilenamer1   r<   r>   r,   f	file_sizer	   r	   r   from_filename   s
   
"zReadFileChunk.from_filenamec                 C   s   || }t ||S r   )min)r
   r;   r0   r1   r2   max_chunk_sizer	   r	   r   r5     s   
z"ReadFileChunk._calculate_file_sizec                 C   sh   |d u r| j | j }n	t| j | j |}| j|}|  jt|7  _| jd ur2| jr2| t| |S r   )r6   r8   rK   r3   readlenr9   r:   )r
   amountamount_to_readdatar	   r	   r   rM     s   zReadFileChunk.readc                 C   
   d| _ d S NTr:   r
   r	   r	   r   r,   $     
zReadFileChunk.enable_callbackc                 C   rR   NFrT   rU   r	   r	   r   r#   '  rV   zReadFileChunk.disable_callbackc                 C   s<   | j | j|  | jd ur| jr| || j  || _d S r   )r3   r7   r4   r9   r:   r8   )r
   wherer	   r	   r   r7   *  s   
zReadFileChunk.seekc                 C   s   | j   d S r   )r3   closerU   r	   r	   r   rY   1  s   zReadFileChunk.closec                 C      | j S r   )r8   rU   r	   r	   r   tell4  s   zReadFileChunk.tellc                 C   rZ   r   )r6   rU   r	   r	   r   __len__7  s   zReadFileChunk.__len__c                 C   s   | S r   r	   rU   r	   r	   r   	__enter__?  r   zReadFileChunk.__enter__c                 O   s   |    d S r   )rY   )r
   argsr)   r	   r	   r   __exit__B     zReadFileChunk.__exit__c                 C   s   t g S r   )iterrU   r	   r	   r   __iter__E  s   zReadFileChunk.__iter__rS   r   )r   r   r   r?   classmethodrJ   r5   rM   r,   r#   r7   rY   r[   r\   r]   r_   rb   r	   r	   r	   r   r/      s&    
2'
r/   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 S r   )_streamr9   )r
   streamr>   r	   r	   r   r?   Q  s   
zStreamReaderProgress.__init__c                 O   s.   | j j|i |}| jd ur| t| |S r   )re   rM   r9   rN   )r
   r^   r)   valuer	   r	   r   rM   U  s   
zStreamReaderProgress.readr   )r   r   r   __doc__r?   rM   r	   r	   r	   r   rd   N  s    
rd   c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )OSUtilsc                 C   s   t j|S r   )rB   pathgetsizer
   rG   r	   r	   r   get_file_size]  r`   zOSUtils.get_file_sizec                 C   s   t j||||ddS )NF)r,   )r/   rJ   )r
   rG   r1   sizer>   r	   r	   r   open_file_chunk_reader`  s   
zOSUtils.open_file_chunk_readerc                 C   s
   t ||S r   )rA   )r
   rG   moder	   r	   r   rA   e  rV   zOSUtils.openc                 C   s&   zt | W dS  ty   Y dS w )z+Remove a file, noop if file does not exist.N)rB   removeOSErrorrl   r	   r	   r   remove_fileh  s
   zOSUtils.remove_filec                 C   s   t j|| d S r   )
s3transfercompatrename_file)r
   current_filenamenew_filenamer	   r	   r   rv   q  s   zOSUtils.rename_fileN)r   r   r   rm   ro   rA   rs   rv   r	   r	   r	   r   ri   \  s    	ri   c                   @   sD   e Zd Zg dZejjfddZdd Zdd Z	dd	 Z
d
d ZdS )MultipartUploader)SSECustomerKeySSECustomerAlgorithmSSECustomerKeyMD5RequestPayerc                 C   s   || _ || _|| _|| _d S r   )_client_config_os_executor_clsr
   clientconfigosutilexecutor_clsr	   r	   r   r?     s   
zMultipartUploader.__init__c                 C   s,   i }|  D ]\}}|| jv r|||< q|S r   )itemsUPLOAD_PART_ARGS)r
   
extra_argsupload_parts_argskeyrg   r	   r	   r   _extra_upload_part_args  s   
z)MultipartUploader._extra_upload_part_argsc           
      C   s   | j jd||d|}|d }z| ||||||}W n* tyF }	 ztjddd | j j|||d td|d	||g|	d }	~	ww | j j
|||d	|id
 d S )NBucketKeyUploadIdzBException raised while uploading parts, aborting multipart upload.Texc_info)r   r   r   zFailed to upload {} to {}: {}/Parts)r   r   r   MultipartUploadr	   )r~   create_multipart_upload_upload_parts	Exceptionloggerdebugabort_multipart_uploadr   formatr   complete_multipart_upload)
r
   rG   bucketr   r>   r   response	upload_idpartser	   r	   r   upload_file  s>   
zMultipartUploader.upload_filec                 C   s   |  |}g }| jj}	tt| j|t|	 }
| jj	}| j
|d)}t| j|||||	||}||td|
d D ]}|| q=W d    |S 1 sPw   Y  |S )Nmax_workers   )r   r   multipart_chunksizeintmathceilr   rm   floatmax_concurrencyr   	functoolspartial_upload_one_partmapr   append)r
   r   rG   r   r   r>   r   upload_parts_extra_argsr   	part_size	num_partsr   executorupload_partialpartr	   r	   r   r     s2   


zMultipartUploader._upload_partsc	              	   C   sr   | j j}	|	|||d  || }
| jjd|||||
d|}|d }||dW  d    S 1 s2w   Y  d S )Nr   )r   r   r   
PartNumberBodyETag)r   r   r	   )r   ro   r~   upload_part)r
   rG   r   r   r   r   r   r>   part_numberopen_chunk_readerr%   r   etagr	   r	   r   r     s"   $z"MultipartUploader._upload_one_partN)r   r   r   r   
concurrentfuturesThreadPoolExecutorr?   r   r   r   r   r	   r	   r	   r   ry   u  s    
	ry   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ShutdownQueueaY  A queue implementation that can be shutdown.

    Shutting down a queue means that this class adds a
    trigger_shutdown method that will trigger all subsequent
    calls to put() to fail with a ``QueueShutdownError``.

    It purposefully deviates from queue.Queue, and is *not* meant
    to be a drop in replacement for ``queue.Queue``.

    c                 C   s   d| _ t | _tj| |S rW   )	_shutdown	threadingLock_shutdown_lockqueueQueue_init)r
   maxsizer	   r	   r   r     s   
zShutdownQueue._initc                 C   s<   | j  d| _td W d    d S 1 sw   Y  d S )NTzThe IO queue is now shutdown.)r   r   r   r   rU   r	   r	   r   trigger_shutdown  s   "zShutdownQueue.trigger_shutdownc                 C   sB   | j  | jrtdW d    n1 sw   Y  tj| |S )Nz6Cannot put item to queue when queue has been shutdown.)r   r   r.   r   r   put)r
   itemr	   r	   r   r     s   zShutdownQueue.putN)r   r   r   rh   r   r   r   r	   r	   r	   r   r     s
    r   c                   @   sP   e Zd ZejjfddZ	dddZdd Zdd	 Z	d
d Z
dd Zdd ZdS )MultipartDownloaderc                 C   s*   || _ || _|| _|| _t| jj| _d S r   )r~   r   r   r   r   max_io_queue_ioqueuer   r	   r	   r   r?   	  s
   zMultipartDownloader.__init__Nc              	   C   s   | j dd6}t| j|||||}||}	t| j|}
||
}tjj|	|gtjj	d}| 
| W d    d S 1 s?w   Y  d S )N   r   )return_when)r   r   r   _download_file_as_futuresubmit_perform_io_writesr   r   waitFIRST_EXCEPTION_process_future_results)r
   r   r   rG   object_sizer   r>   
controllerdownload_parts_handlerparts_futureio_writes_handler	io_futureresultsr	   r	   r   download_file  s(   

"z!MultipartDownloader.download_filec                 C   s   |\}}|D ]}|   qd S r   )result)r
   r   finished
unfinishedfuturer	   r	   r   r   0  s   
z+MultipartDownloader._process_future_resultsc              	   C   s   | j j}tt|t| }| j j}t| j	||||||}	z2| j
|d}
t|
|	t| W d    n1 s;w   Y  W | jt d S W | jt d S | jt w )Nr   )r   r   r   r   r   r   r   r   r   _download_ranger   listr   r   r   r   SHUTDOWN_SENTINEL)r
   r   r   rG   r   r>   r   r   r   download_partialr   r	   r	   r   r   5  s&   	z,MultipartDownloader._download_file_as_futurec                 C   s:   || }||d krd}n|| d }d| d| }|S )Nr   r   zbytes=-r	   )r
   r   
part_indexr   start_range	end_rangerange_paramr	   r	   r   _calculate_range_paramJ  s   z*MultipartDownloader._calculate_range_paramc                    s  z||  |||}| jj}	d }
t|	D ]f}zAtd | jj|||d}t|d |d || }t	 fdddD ]}| j
||f |t|7 }q:W  W td| d S  tjtttfyx } ztjd	|||	d
d |}
W Y d }~qd }~ww t|
td| w )NzMaking get_object call.)r   r   Ranger   i @  c                      s
     S r   rM   r	   buffer_sizestreaming_bodyr	   r   <lambda>i     
 z5MultipartDownloader._download_range.<locals>.<lambda>    z$EXITING _download_range for part: %sCRetrying exception caught (%s), retrying request, (attempt %s / %s)Tr   )r   r   num_download_attemptsr   r   r   r~   
get_objectrd   ra   r   r   rN   sockettimeoutrr   r   r   r   )r
   r   r   rG   r   r   r>   r   r   max_attemptslast_exceptionir   current_indexchunkr   r	   r   r   r   S  sV   
z#MultipartDownloader._download_rangec                 C   s   | j |dE}	 | j }|tu r td 	 W d    d S z|\}}|| || W n t	yJ } ztjd|dd | j
   d }~ww q	1 sOw   Y  d S )NwbTzCShutdown sentinel received in IO handler, shutting down IO handler.z!Caught exception in IO thread: %sr   )r   rA   r   getr   r   r   r7   writer   r   )r
   rG   rH   taskoffsetrQ   r   r	   r	   r   r     s2   



z&MultipartDownloader._perform_io_writesr   )r   r   r   r   r   r   r?   r   r   r   r   r   r   r	   r	   r	   r   r     s    

	/r   c                   @   s(   e Zd Zde dde ddfddZdS )TransferConfigr   
      d   c                 C   s"   || _ || _|| _|| _|| _d S r   )multipart_thresholdr   r   r   r   )r
   r
  r   r   r   r   r	   r	   r   r?     s
   
zTransferConfig.__init__N)r   r   r   MBr?   r	   r	   r	   r   r    s    r  c                   @   s~   e Zd Zg dZg dZd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d Zdd Zdd ZdS )
S3Transfer)	VersionIdr{   rz   r|   r}   )ACLCacheControlContentDispositionContentEncodingContentLanguageContentTypeExpiresGrantFullControl	GrantReadGrantReadACPGrantWriteACLMetadatar}   ServerSideEncryptionStorageClassr{   rz   r|   SSEKMSKeyIdSSEKMSEncryptionContextTaggingNc                 C   s2   || _ |d u r
t }|| _|d u rt }|| _d S r   )r~   r  r   ri   _osutil)r
   r   r   r   r	   r	   r   r?     s   
zS3Transfer.__init__c                 C   s   |du ri }|  || j | jjj}|jdtdd |jdtdd | j	
|| jjkr7| ||||| dS | ||||| dS )zUpload a file to an S3 object.

        Variants have also been injected into S3 client, Bucket and Object.
        You don't have to use S3Transfer.upload_file() directly.
        Nzrequest-created.s3zs3upload-callback-disable)	unique_idzs3upload-callback-enable)_validate_all_known_argsALLOWED_UPLOAD_ARGSr~   metaeventsregister_firstr*   register_lastr-   r  rm   r   r
  _multipart_upload_put_object)r
   rG   r   r   r>   r   r$  r	   r	   r   r     s(   

zS3Transfer.upload_filec                 C   s`   | j j}||d| j ||d}| jjd|||d| W d    d S 1 s)w   Y  d S )Nr   )r>   )r   r   r   r	   )r  ro   rm   r~   
put_object)r
   rG   r   r   r>   r   r   r%   r	   r	   r   r(    s   
"zS3Transfer._put_objectc                 C   s   |du ri }|  || j | |||}|tj t  }z| |||||| W n ty>   tj	d|dd | j
|  w | j
|| dS )zDownload an S3 object to a file.

        Variants have also been injected into S3 client, Bucket and Object.
        You don't have to use S3Transfer.download_file() directly.
        Nz<Exception caught in download_file, removing partial file: %sTr   )r!  ALLOWED_DOWNLOAD_ARGS_object_sizerB   extsepr   _download_filer   r   r   r  rs   rv   )r
   r   r   rG   r   r>   r   temp_filenamer	   r	   r   r     s&   
zS3Transfer.download_filec                 C   s:   || j jkr| |||||| d S | ||||| d S r   )r   r
  _ranged_download_get_object)r
   r   r   rG   r   r   r>   r	   r	   r   r-  "  s
   zS3Transfer._download_filec                 C   s,   |D ]}||vrt d|d|f qd S )Nz/Invalid extra_args key '%s', must be one of: %sz, )
ValueErrorr   )r
   actualallowedkwargr	   r	   r   r!  ,  s   z#S3Transfer._validate_all_known_argsc                 C   s*   t | j| j| j}||||||| d S r   )r   r~   r   r  r   )r
   r   r   rG   r   r   r>   
downloaderr	   r	   r   r/  4  s   zS3Transfer._ranged_downloadc           
      C   s   | j j}d }t|D ]1}z| |||||W   S  tjtttfy; }	 zt	j
d|	||dd |	}W Y d }	~	q
d }	~	ww t|)Nr   Tr   )r   r   r   _do_get_objectr   r   rr   r   r   r   r   r   )
r
   r   r   rG   r   r>   r   r   r   r   r	   r	   r   r0  >  s2   

zS3Transfer._get_objectc           	         s|   | j jd||d|}t|d | | j|d}t fdddD ]}|| q$W d    d S 1 s7w   Y  d S )Nr   r   r  c                      s
     dS )Ni    r   r	   r   r	   r   r   a  r   z+S3Transfer._do_get_object.<locals>.<lambda>r   r	   )r~   r   rd   r  rA   ra   r  )	r
   r   r   rG   r   r>   r   rH   r   r	   r7  r   r6  [  s   "zS3Transfer._do_get_objectc                 C   s   | j jd||d|d S )Nr   ContentLengthr	   )r~   head_object)r
   r   r   r   r	   r	   r   r+  d  s   zS3Transfer._object_sizec                 C   s(   t | j| j| j}|||||| d S r   )ry   r~   r   r  r   )r
   rG   r   r   r>   r   uploaderr	   r	   r   r'  i  s   zS3Transfer._multipart_upload)NN)r   r   r   r*  r"  r?   r   r(  r   r-  r!  r/  r0  r6  r+  r'  r	   r	   r	   r   r    s     



 

	r  )r   )0rh   concurrent.futuresr   r   loggingr   rB   r   r   r   r   r   botocore.compatr   botocore.exceptionsr   6botocore.vendored.requests.packages.urllib3.exceptionsr   s3transfer.compatrt   s3transfer.exceptionsr   r   
__author____version__Handlerr   	getLoggerr   r   
addHandlerr  objectr   r   r*   r-   r   r.   r/   rd   ri   ry   r   r   r   r  r  r	   r	   r	   r   <module>   sJ   q

 q" 