B \m@sddlZddlZddlZddlZddlZddlmZddlmZddl m Z ddl m Z ddl mZddl mZddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddl mZddlmZddlmZeeZGdddeZGdddeZGdddeZ GdddeZ!Gddde!Z"GdddeZ#GdddeZ$Gdd d e$Z%Gd!d"d"eZ&Gd#d$d$eZ'Gd%d&d&eZ(Gd'd(d(eZ)Gd)d*d*eZ*Gd+d,d,eZ+Gd-d.d.eZ,dS)/N)six)seekable)RetriesExceededError)IN_MEMORY_DOWNLOAD_TAG)S3_RETRYABLE_DOWNLOAD_ERRORS) get_callbacks)invoke_progress_callbacks)calculate_num_parts)calculate_range_parameter)FunctionContainer)CountCallbackInvoker)StreamReaderProgress)DeferredOpenFile)Task)SubmissionTaskc@sTeZdZdZddZeddZddZdd Zd d Z d d Z ddZ ddZ dS)DownloadOutputManageraBase manager class for handling various types of files for downloads This class is typically used for the DownloadSubmissionTask class to help determine the following: * Provides the fileobj to write to downloads to * Get a task to complete once everything downloaded has been written The answers/implementations differ for the various types of file outputs that may be accepted. All implementations must subclass and override public methods from this class. cCs||_||_||_dS)N)_osutil_transfer_coordinator _io_executor)selfosutiltransfer_coordinator io_executorr9/tmp/pip-build-uw_ogi45/s3transfer/s3transfer/download.py__init__6szDownloadOutputManager.__init__cCs tddS)aeDetermines if the target for the download is compatible with manager :param download_target: The target for which the upload will write data to. :param osutil: The os utility to be used for the transfer :returns: True if the manager can handle the type of target specified otherwise returns False. zmust implement is_compatible()N)NotImplementedError)clsdownload_targetrrrr is_compatible;s z#DownloadOutputManager.is_compatiblecCsdS)zGet the tag (if any) to associate all GetObjectTasks :rtype: s3transfer.futures.TaskTag :returns: The tag to associate all GetObjectTasks with Nr)rrrrget_download_task_tagIsz+DownloadOutputManager.get_download_task_tagcCs tddS)aGet file-like object to use for io writes in the io executor :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The future associated with upload request returns: A file-like object to write to z*must implement get_fileobj_for_io_writes()N)r)rtransfer_futurerrrget_fileobj_for_io_writesQsz/DownloadOutputManager.get_fileobj_for_io_writescCs|j|j||||dS)aQueue IO write for submission to the IO executor. This method accepts an IO executor and information about the downloaded data, and handles submitting this to the IO executor. This method may defer submission to the IO executor if necessary. N)rsubmitrget_io_write_task)rfileobjdataoffsetrrrqueue_file_io_task[s z(DownloadOutputManager.queue_file_io_taskcCst|j|||ddS)aGet an IO write task for the requested set of data This task can be ran immediately or be submitted to the IO executor for it to run. :type fileobj: file-like object :param fileobj: The file-like object to write to :type data: bytes :param data: The data to write out :type offset: integer :param offset: The offset to write the data to in the file-like object :returns: An IO task to be used to write data to a file-like object )r%r&r') main_kwargs) IOWriteTaskr)rr%r&r'rrrr$is z'DownloadOutputManager.get_io_write_taskcCs tddS)aGet the final io task to complete the download This is needed because based on the architecture of the TransferManager the final tasks will be sent to the IO executor, but the executor needs a final task for it to signal that the transfer is done and all done callbacks can be run. :rtype: s3transfer.tasks.Task :returns: A final task to completed in the io executor z"must implement get_final_io_task()N)r)rrrrget_final_io_tasks z'DownloadOutputManager.get_final_io_taskcCs$t|d|jjd}|j|j|S)Nwb)modeZ open_function)rropenradd_failure_cleanupclose)rfilenamefrrr_get_fileobj_from_filenamesz0DownloadOutputManager._get_fileobj_from_filenameN) __name__ __module__ __qualname____doc__r classmethodrr r"r(r$r+r3rrrrr)s   rcs@eZdZfddZeddZddZddZd d ZZ S) DownloadFilenameOutputManagercs*tt||||d|_d|_d|_dS)N)superr9r_final_filename_temp_filename _temp_fileobj)rrrr) __class__rrrs   z&DownloadFilenameOutputManager.__init__cCs t|tjS)N) isinstancer string_types)rrrrrrrsz+DownloadFilenameOutputManager.is_compatiblecCs.|jjj}||_|j||_||_|jS)N) meta call_argsr%r;rZget_temp_filenamer<_get_temp_fileobjr=)rr!r%rrrr"s   z7DownloadFilenameOutputManager.get_fileobj_for_io_writescCst|j|j|j|jdddS)N)r%final_filenamerT)rr)is_final)IORenameFileTaskrr=r;r)rrrrr+s z/DownloadFilenameOutputManager.get_final_io_taskcCs$||j}|j|jj|j|S)N)r3r<rr/rZ remove_file)rr2rrrrCs z/DownloadFilenameOutputManager._get_temp_fileobj) r4r5r6rr8rr"r+rC __classcell__rr)r>rr9s   r9c@s(eZdZeddZddZddZdS)DownloadSeekableOutputManagercCst|S)N)r)rrrrrrrsz+DownloadSeekableOutputManager.is_compatiblecCs |jjjS)N)rArBr%)rr!rrrr"sz7DownloadSeekableOutputManager.get_fileobj_for_io_writescCs t|jdS)N)r)CompleteDownloadNOOPTaskr)rrrrr+sz/DownloadSeekableOutputManager.get_final_io_taskN)r4r5r6r8rr"r+rrrrrHs rHcsVeZdZdfdd ZeddZddZdd Zd d Zfd d Z ddZ Z S) DownloadNonSeekableOutputManagerNcs6tt|||||dkr"t}||_t|_dS)N)r:rJr DeferQueue _defer_queue threadingLock_io_submit_lock)rrrr defer_queue)r>rrrs   z)DownloadNonSeekableOutputManager.__init__cCs t|dS)Nwrite)hasattr)rrrrrrrsz.DownloadNonSeekableOutputManager.is_compatiblecCstS)N)r)rrrrr sz6DownloadNonSeekableOutputManager.get_download_task_tagcCs |jjjS)N)rArBr%)rr!rrrr"sz:DownloadNonSeekableOutputManager.get_fileobj_for_io_writescCs t|jdS)N)r)rIr)rrrrr+sz2DownloadNonSeekableOutputManager.get_final_io_taskc s`|jP|j||}x:|D]2}|d}td|d|tt||||qWWdQRXdS)Nr&z%Queueing IO offset %s for fileobj: %sr')rOrLrequest_writesloggerdebugr:rJr()rr%r&r'writesrQ)r>rrr(s  z3DownloadNonSeekableOutputManager.queue_file_io_taskcCst|j||ddS)N)r%r&)r))IOStreamingWriteTaskr)rr%r&r'rrrr$sz2DownloadNonSeekableOutputManager.get_io_write_task)N) r4r5r6rr8rr r"r+r(r$rGrr)r>rrJs  rJcs:eZdZd fdd ZeddZddZdd ZZS) $DownloadSpecialFilenameOutputManagerNcs tt|||||d|_dS)N)r:rXr_fileobj)rrrrrP)r>rrrs  z-DownloadSpecialFilenameOutputManager.__init__cCst|tjo||S)N)r?rr@Zis_special_file)rrrrrrrs z2DownloadSpecialFilenameOutputManager.is_compatiblecCs|jjj}|||_|jS)N)rArBr%r3rY)rr!r1rrrr" s  z>DownloadSpecialFilenameOutputManager.get_fileobj_for_io_writescCst|jdd|jidS)NTr%)rrEr)) IOCloseTaskrrY)rrrrr+sz6DownloadSpecialFilenameOutputManager.get_final_io_task)N) r4r5r6rr8rr"r+rGrr)r>rrXs rXc@sBeZdZdZddZdddZddZd d Zd d Zd dZ dS)DownloadSubmissionTaskz/Task for submitting tasks to execute a downloadcCsLttttg}|jjj}x|D]}|||r|SqWtd|t |fdS)aRetrieves a class for managing output for a download :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future for the request :type osutil: s3transfer.utils.OSUtils :param osutil: The os utility associated to the transfer :rtype: class of DownloadOutputManager :returns: The appropriate class to use for managing a specific type of input for downloads. z'Output %s of type: %s is not supported.N) rXr9rHrJrArBr%r RuntimeErrortype)rr!rZdownload_manager_resolver_chainr%Zdownload_manager_clsrrr _get_download_output_manager_clss   z7DownloadSubmissionTask._get_download_output_manager_clsNc Cs|jjdkrD|jf|jjj|jjjd|jjj}|j|d|||||j |} |jj|j kr| |||||| ||n| |||||| ||dS)a :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type io_executor: s3transfer.futures.BoundedExecutor :param io_executor: The io executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for :type bandwidth_limiter: s3transfer.bandwidth.BandwidthLimiter :param bandwidth_limiter: The bandwidth limiter to use when downloading streams N)BucketKeyZ ContentLength) rAsizeZ head_objectrBbucketkey extra_argsZprovide_transfer_sizer^rZmultipart_threshold_submit_download_request_submit_ranged_download_request) rclientconfigrrequest_executorrr!bandwidth_limiterresponsedownload_output_managerrrr_submit7s"       zDownloadSubmissionTask._submitc Csp|jj} ||} t|d} |} |} |jj|t|j|| j | j | | j | |j ||j |d | gd| ddS)Nprogress) rgrbrcr%rd callbacks max_attemptsrl io_chunksizerj)rr)done_callbacks)tag)rArBr"rr r+rr#ImmediatelyWriteIOGetObjectTaskrbrcrdnum_download_attemptsrq)rrgrhrrirrlr!rjrBr%progress_callbacksget_object_tag final_taskrrrrems, z/DownloadSubmissionTask._submit_download_requestc Cs|jj} t|d} ||} |j} t|jj| } |}t| ||}x~t | D]r}t | || }d|i}| | j ||jj|t|j|| j| j| || |j|| ||j|d |jgd|dqRW|dS)NrnZRange) rgrbrcr%rdrorp start_indexrlrqrj)rr)rr)rs)rArBrr"Zmultipart_chunksizer rar r &_get_final_io_task_submission_callbackranger updaterd incrementrr# GetObjectTaskrbrcrurqZ decrementfinalize)rrgrhrrirrlr!rjrBrvr% part_size num_partsrwZfinalize_download_invokeriZrange_parameterrdrrrrfsD      z6DownloadSubmissionTask._submit_ranged_download_requestcCs|}t|jj||S)N)r+r rr#)rZdownload_managerrrxrrrrzsz=DownloadSubmissionTask._get_final_io_task_submission_callbackcCs6||}||dkrd}n ||d}d||f}|S)Nz bytes=%s-%sr)rrZ part_indexrZ start_rangeZ end_rangeZ range_paramrrr_calculate_range_params    z-DownloadSubmissionTask._calculate_range_param)N) r4r5r6r7r^rmrerfrzrrrrrr[s 5*?r[c@seZdZdddZddZdS)r~rNc  Csd} xt|D]} y|jf||d|}t|d|}| rJ| ||j}| }t|| }x8|D]0}|js||||||t|7}q^dSq^WdSt k r}z,t j d|| |dd|} t || |wWdd}~XYqXqWt | dS)aDownloads an object and places content into io queue :param client: The client to use when calling GetObject :param bucket: The bucket to download from :param key: The key to download from :param fileobj: The file handle to write content to :param exta_args: Any extra arguements to include in GetObject request :param callbacks: List of progress callbacks to invoke on download :param max_attempts: The number of retries to do when downloading :param download_output_manager: The download output manager associated with the current download. :param io_chunksize: The size of each io chunk to read from the download stream and queue in the io queue. :param start_index: The location in the file to start writing the content of the key to. :param bandwidth_limiter: The bandwidth limiter to use when throttling the downloading of data in streams. N)r_r`ZBodyzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)exc_info)r{Z get_objectr Zget_bandwith_limited_streamrDownloadChunkIteratordone _handle_iolenrrTrUrr)rrgrbrcr%rdrorprlrqryrjZlast_exceptionrrkZstreaming_bodyZ current_indexchunkschunkerrr_mains:       zGetObjectTask._maincCs||||dS)N)r()rrlr%rindexrrrr%szGetObjectTask._handle_io)rN)r4r5r6rrrrrrr~s ;r~c@seZdZdZddZdS)rtaGetObjectTask that immediately writes to the provided file object This is useful for downloads where it is known only one thread is downloading the object so there is no reason to go through the overhead of using an IO queue and executor. cCs||||}|dS)N)r$)rrlr%rrZtaskrrrr0sz*ImmediatelyWriteIOGetObjectTask._handle_ioN)r4r5r6r7rrrrrrt)srtc@seZdZddZdS)r*cCs||||dS)zPulls off an io queue to write contents to a file :param fileobj: The file handle to write content to :param data: The data to write :param offset: The offset to write the data to. N)seekrQ)rr%r&r'rrrr6s zIOWriteTask._mainN)r4r5r6rrrrrr*5sr*c@seZdZdZddZdS)rWz/Task for writing data to a non-seekable stream.cCs||dS)zWrite data to a fileobj. Data will be written directly to the fileboj without any prior seeking. :param fileobj: The fileobj to write content to :param data: The data to write N)rQ)rr%r&rrrrDs zIOStreamingWriteTask._mainN)r4r5r6r7rrrrrrWAsrWc@seZdZdZddZdS)rFaA task to rename a temporary file to its final filename :param fileobj: The file handle that content was written to. :param final_filename: The final name of the file to rename to upon completion of writing the contents. :param osutil: OS utility cCs|||j|dS)N)r0Z rename_filename)rr%rDrrrrrYszIORenameFileTask._mainN)r4r5r6r7rrrrrrFQsrFc@seZdZdZddZdS)rZziA task to close out a file once the download is complete. :param fileobj: The fileobj to close. cCs |dS)N)r0)rr%rrrrcszIOCloseTask._mainN)r4r5r6r7rrrrrrZ^srZcs*eZdZdZdfdd ZddZZS) rIzA NOOP task to serve as an indicator that the download is complete Note that the default for is_final is set to True because this should always be the last task. NTcstt|j|||||ddS)N)rr)pending_main_kwargsrrrE)r:rIr)rrr)rrrrE)r>rrrms  z!CompleteDownloadNOOPTask.__init__cCsdS)Nr)rrrrrxszCompleteDownloadNOOPTask._main)NNNT)r4r5r6r7rrrGrr)r>rrIgs  rIc@s(eZdZddZddZddZeZdS)rcCs||_||_d|_dS)zIterator to chunk out a downloaded S3 stream :param body: A readable file-like object :param chunksize: The amount to read each time rN)_body _chunksize _num_reads)rbody chunksizerrrr}szDownloadChunkIterator.__init__cCs|S)Nr)rrrr__iter__szDownloadChunkIterator.__iter__cCs<|j|j}|jd7_|r$|S|jdkr2|StdS)Nr)rreadrr StopIteration)rrrrr__next__s zDownloadChunkIterator.__next__N)r4r5r6rrrnextrrrrr|s  rc@s eZdZdZddZddZdS)rKa"IO queue that defers write requests until they are queued sequentially. This class is used to track IO data for a *single* fileobj. You can send data to this queue, and it will defer any IO write requests until it has the next contiguous block available (starting at 0). cCsg|_t|_d|_dS)Nr)_writesset_pending_offsets _next_offset)rrrrrszDeferQueue.__init__cCs||jkrgSg}||jkr gSt|j||f|j|xh|jr|jdd|jkrt|j}||d|dd|j|d|jt |d7_q@W|S)aRequest any available writes given new incoming data. You call this method by providing new data along with the offset associated with the data. If that new data unlocks any contiguous writes that can now be submitted, this method will return all applicable writes. This is done with 1 method call so you don't have to make two method calls (put(), get()) which acquires a lock each method call. rr)r'r&) rrheapqheappushraddheappopappendremover)rr'r&rVZ next_writerrrrSs    zDeferQueue.request_writesN)r4r5r6r7rrSrrrrrKsrK)-loggingossocketrMrZbotocore.compatrZs3transfer.compatrZs3transfer.exceptionsrZs3transfer.futuresrZs3transfer.utilsrrrr r r r r rZs3transfer.tasksrr getLoggerr4rTobjectrr9rHrJrXr[r~rtr*rWrFrZrIrrKrrrr sH                q(-PB