B -<`5n@szdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl mZddlmZddlZddlmZmZdZdZGd d d ejZeeZeee jjZd Z e!Z"d%d dZ#ddZ$ddZ%Gddde&Z'Gddde!Z(Gddde!Z)Gddde!Z*Gddde!Z+Gdddej,Z-Gdd d e!Z.Gd!d"d"e!Z/Gd#d$d$e!Z0dS)&aAbstractions 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`` clas 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)ReadTimeoutError)IncompleteReadError)RetriesExceededErrorS3UploadFailedErrorzAmazon Web Servicesz0.3.4c@seZdZddZdS) NullHandlercCsdS)N)selfrecordrr:/tmp/pip-target-7cdyy134/lib/python/s3transfer/__init__.pyemitszNullHandler.emitN)__name__ __module__ __qualname__r rrrr rsricCsdddt|DS)Ncss|]}ttjVqdS)N)randomchoicestring hexdigits).0_rrr sz(random_file_extension..)joinrange)Z num_digitsrrr random_file_extensionsrcKs"|dkrt|jdr|jdS)N) PutObject UploadPartdisable_callback)hasattrbodyr)requestoperation_namekwargsrrr disable_upload_callbackss r$cKs"|dkrt|jdr|jdS)N)rrenable_callback)rr r%)r!r"r#rrr enable_upload_callbackss r&c@s eZdZdS)QueueShutdownErrorN)r rrrrrr r'sr'c@s~eZdZdddZedddZddZdd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZdS) ReadFileChunkNTcCsF||_||_|j|j|||d|_|j|jd|_||_||_dS)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_byteactual_file_sizerN)_fileobj _start_byte_calculate_file_size_sizeseek _amount_read _callback_callback_enabled)r fileobjr* chunk_sizeZfull_file_sizecallbackr%rrr __init__s zReadFileChunk.__init__cCs,t|d}t|j}|||||||S)aWConvenience 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)openosfstatfilenost_size)clsfilenamer*r5r6r%f file_sizerrr from_filenames  zReadFileChunk.from_filenamecCs||}t||S)N)min)r r4r)r*r+Zmax_chunk_sizerrr r.sz"ReadFileChunk._calculate_file_sizecCsh|dkr|j|j}nt|j|j|}|j|}|jt|7_|jdk rd|jrd|t||S)N)r/r1rCr,readlenr2r3)r amountZamount_to_readdatarrr rDs zReadFileChunk.readcCs d|_dS)NT)r3)r rrr r%szReadFileChunk.enable_callbackcCs d|_dS)NF)r3)r rrr rszReadFileChunk.disable_callbackcCs<|j|j||jdk r2|jr2|||j||_dS)N)r,r0r-r2r3r1)r whererrr r0szReadFileChunk.seekcCs|jdS)N)r,close)r rrr rIszReadFileChunk.closecCs|jS)N)r1)r rrr tell!szReadFileChunk.tellcCs|jS)N)r/)r rrr __len__$szReadFileChunk.__len__cCs|S)Nr)r rrr __enter__,szReadFileChunk.__enter__cOs |dS)N)rI)r argsr#rrr __exit__/szReadFileChunk.__exit__cCstgS)N)iter)r rrr __iter__2szReadFileChunk.__iter__)NT)NT)N)r rrr7 classmethodrBr.rDr%rr0rIrJrKrLrNrPrrrr r(s '  r(c@s"eZdZdZdddZddZdS)StreamReaderProgresszz5MultipartDownloader._download_range..rzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)ryz$EXITING _download_range for part: %s)rrjnum_download_attemptsrr}r~ri get_objectrRrOrrrEsockettimeouterrorrrr)r rrtr?rrr6rr max_attemptslast_exceptionirZ current_indexchunkrr)rrr rs8        z#MultipartDownloader._download_rangec Cs|j|d}x|j}|tkr2tddSy |\}}||||Wqt k r}z tjd|dd|j Wdd}~XYqXqWWdQRXdS)NwbzCShutdown sentinel received in IO handler, shutting down IO handler.z!Caught exception in IO thread: %sT)ry) rkr9rgetrr}r~r0writer|r)r r?r@ZtaskoffsetrGrrrr r$s     z&MultipartDownloader._perform_io_writes)N) r rrrrrr7rrrrrrrrrr rs  !rc@s(eZdZdeddeddfddZdS)TransferConfigr dcCs"||_||_||_||_||_dS)N)multipart_thresholdrrrr)r rrrrrrrr r79s zTransferConfig.__init__N)r rrMBr7rrrr r8s rc@seZdZdddddgZdddd d d d d dddddddddddddgZd.ddZd/ddZddZd0ddZd d!Z d"d#Z d$d%Z d&d'Z d(d)Z d*d+Zd,d-ZdS)1 S3TransferZ VersionIdrfrergrhZACL CacheControlZContentDispositionZContentEncodingZContentLanguageZ ContentTypeZExpiresZGrantFullControlZ GrantReadZ GrantReadACPZ GrantWriteACLZMetadataZServerSideEncryptionZ StorageClassZ SSEKMSKeyIdZSSEKMSEncryptionContextZTaggingNcCs2||_|dkrt}||_|dkr(t}||_dS)N)rirrjrW_osutil)r rmrnrorrr r7hszS3Transfer.__init__cCs|dkr i}|||j|jjj}|jdtdd|jdtdd|j ||j j krl| |||||n||||||dS)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. Nzrequest-created.s3zs3upload-callback-disable)Z unique_idzs3upload-callback-enable)_validate_all_known_argsALLOWED_UPLOAD_ARGSrimetaeventsZregister_firstr$Z register_lastr&rrZrjr_multipart_upload _put_object)r r?rrtr6rsrrrr rqs   zS3Transfer.upload_filec CsJ|jj}||d|j||d }|jjf|||d|WdQRXdS)Nr)r6)rvrwr)rr\rZriZ put_object)r r?rrtr6rsrr rrr rs   zS3Transfer._put_objectcCs|dkr i}|||j||||}|tjt}y|||||||Wn2tk rtj d|dd|j |YnX|j ||dS)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.r)rirrRrr9rOr) r rrtr?rsr6rr@rr)rr rs zS3Transfer._do_get_objectcCs|jjf||d|dS)N)rvrwZ ContentLength)riZ head_object)r rrtrsrrr rszS3Transfer._object_sizecCs(t|j|j|j}||||||dS)N)rdrirjrr)r r?rrtr6rsZuploaderrrr rszS3Transfer._multipart_upload)NN)NN)NN)r rrrrr7rrrrrrrrrrrrrr rFsL    r)r)1rVr:rrloggingrrrrconcurrent.futuresrZbotocore.compatrZ6botocore.vendored.requests.packages.urllib3.exceptionsrZbotocore.exceptionsrZs3transfer.compatraZs3transfer.exceptionsrr __author__ __version__Handlerr getLoggerr r} addHandlermovesrrobjectrrr$r&r|r'r(rRrWrdrrrrrrrrr }sF       K l