U n^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)sixseekable)RetriesExceededErrorIN_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||_||_||_dSN)_osutil_transfer_coordinator _io_executorselfosutiltransfer_coordinator io_executorro/private/var/folders/sd/whlwsn6x1_qgglc0mjv25_695qk2gl/T/pip-install-4zq3fp6i/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()NNotImplementedErrorclsZdownload_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 Nrrrrrget_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()Nr 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_taskrfileobjdataoffsetrrrqueue_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) IOWriteTaskrr,rrrr+isz'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()Nr r%rrrget_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 classmethodr$r&r)r0r+r4r<rrrrr)s   rcs@eZdZfddZeddZddZddZd d ZZ S) DownloadFilenameOutputManagercs*tt||||d|_d|_d|_dSr)superrBr_final_filename_temp_filename _temp_fileobjr __class__rrrs z&DownloadFilenameOutputManager.__init__cCs t|tjSr) isinstancer string_typesr"rrrr$sz+DownloadFilenameOutputManager.is_compatiblecCs.|jjj}||_|j||_||_|jSr) meta call_argsr-rDrZget_temp_filenamerE_get_temp_fileobjrF)rr(r-rrrr)s   z7DownloadFilenameOutputManager.get_fileobj_for_io_writescCst|j|j|j|jdddS)N)r-final_filenamerT)rr2is_final)IORenameFileTaskrrFrDrr%rrrr4sz/DownloadFilenameOutputManager.get_final_io_taskcCs$||j}|j|jj|j|Sr)r<rErr8rZ remove_file)rr;rrrrMs  z/DownloadFilenameOutputManager._get_temp_fileobj) r=r>r?rrAr$r)r4rM __classcell__rrrGrrBs   rBc@s(eZdZeddZddZddZdS)DownloadSeekableOutputManagercCst|Srrr"rrrr$sz+DownloadSeekableOutputManager.is_compatiblecCs |jjjSrrKrLr-r'rrrr)sz7DownloadSeekableOutputManager.get_fileobj_for_io_writescCs t|jdSN)rCompleteDownloadNOOPTaskrr%rrrr4sz/DownloadSeekableOutputManager.get_final_io_taskN)r=r>r?rAr$r)r4rrrrrRs rRcsVeZdZdfdd ZeddZddZdd Zd d Zfd d Z ddZ Z S) DownloadNonSeekableOutputManagerNcs6tt|||||dkr"t}||_t|_dSr)rCrWr DeferQueue _defer_queue threadingLock_io_submit_lockrrrrZ defer_queuerGrrrs z)DownloadNonSeekableOutputManager.__init__cCs t|dS)Nwrite)hasattrr"rrrr$sz.DownloadNonSeekableOutputManager.is_compatiblecCstSrrr%rrrr&sz6DownloadNonSeekableOutputManager.get_download_task_tagcCs |jjjSrrSr'rrrr)sz:DownloadNonSeekableOutputManager.get_fileobj_for_io_writescCs t|jdSrTrUr%rrrr4sz2DownloadNonSeekableOutputManager.get_final_io_taskc s\|jL|j||}|D]2}|d}td|d|tt||||qW5QRXdS)Nr.z%Queueing IO offset %s for fileobj: %sr/)r\rYrequest_writesloggerdebugrCrWr0)rr-r.r/writesr^rGrrr0s z3DownloadNonSeekableOutputManager.queue_file_io_taskcCst|j||ddS)N)r-r.r1)IOStreamingWriteTaskrr,rrrr+s z2DownloadNonSeekableOutputManager.get_io_write_task)N) r=r>r?rrAr$r&r)r4r0r+rQrrrGrrWs   rWcs:eZdZd fdd ZeddZddZdd ZZS) $DownloadSpecialFilenameOutputManagerNcs tt|||||d|_dSr)rCrer_fileobjr]rGrrrs z-DownloadSpecialFilenameOutputManager.__init__cCst|tjo||Sr)rIrrJZis_special_filer"rrrr$s z2DownloadSpecialFilenameOutputManager.is_compatiblecCs|jjj}|||_|jSr)rKrLr-r<rf)rr(r:rrrr) s  z>DownloadSpecialFilenameOutputManager.get_fileobj_for_io_writescCst|jdd|jidS)NTr-)rrOr2) IOCloseTaskrrfr%rrrr4s z6DownloadSpecialFilenameOutputManager.get_final_io_task)N) r=r>r?rrAr$r)r4rQrrrGrres  rec@sBeZdZdZddZdddZddZd d Zd d Zd dZ dS)DownloadSubmissionTaskz/Task for submitting tasks to execute a downloadcCsLttttg}|jjj}|D]}|||r|Sqtd|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) rerBrRrWrKrLr-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 NZBucketZKeyZ ContentLength) rKsizeZ head_objectrLbucketkey extra_argsZprovide_transfer_sizerkrZmultipart_threshold_submit_download_request_submit_ranged_download_request) rclientconfigrrequest_executorrr(bandwidth_limiterresponsedownload_output_managerrrr_submit7sN zDownloadSubmissionTask._submitc Csp|jj} ||} t|d} |} |} |jj|t|j|| j | j | | j | |j ||j |d | gd| ddS)Nprogress) rsrnror-rp callbacks max_attemptsrx io_chunksizervrr2done_callbackstag)rKrLr)r r&r4rr*ImmediatelyWriteIOGetObjectTaskrnrorpnum_download_attemptsr})rrsrtrrurrxr(rvrLr-progress_callbacksget_object_tag final_taskrrrrqms4  z/DownloadSubmissionTask._submit_download_requestc Cs|jj} t|d} ||} |j} t|jj| } |}t| ||}t | D]r}t | || }d|i}| | j ||jj|t|j|| j| j| || |j|| ||j|d |jgd|dqP|dS)NrzZRange) rsrnror-rpr{r| start_indexrxr}rvr~r)rKrLr r)Zmultipart_chunksizer rmr&r&_get_final_io_task_submission_callbackranger updaterp incrementrr* GetObjectTaskrnrorr}Z decrementfinalize)rrsrtrrurrxr(rvrLrr- part_size num_partsrZfinalize_download_invokeriZrange_parameterrprrrrrsX    z6DownloadSubmissionTask._submit_ranged_download_requestcCs|}t|jj||Sr)r4r rr*)rZdownload_managerrrrrrrs z=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) r=r>r?r@rkryrqrrrrrrrrrhs 6*?rhc@seZdZdddZddZdS)rrNc  Csd} t|D]} z|jf||d|}t|d|}| rH| ||j}| }t|| }|D]6}|js||||||t|7}qZWdSqZWdSt k r}z2t j d|| |dd|} t || |WYq W5d}~XYq Xq t | 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. NrlZBodyzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)exc_info)rZ get_objectrZget_bandwith_limited_streamrDownloadChunkIteratordone _handle_iolenrrarbr r)rrsrnror-rpr{r|rxr}rrvZlast_exceptionrrwZstreaming_bodyZ current_indexchunkschunkerrr_mains\    zGetObjectTask._maincCs||||dSr)r0)rrxr-rindexrrrr%szGetObjectTask._handle_io)rN)r=r>r?rrrrrrrs =rc@seZdZdZddZdS)raGetObjectTask 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||||}|dSr)r+)rrxr-rrZtaskrrrr0sz*ImmediatelyWriteIOGetObjectTask._handle_ioN)r=r>r?r@rrrrrr)src@seZdZddZdS)r3cCs||||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)seekr^r,rrrr6s zIOWriteTask._mainN)r=r>r?rrrrrr35sr3c@seZdZdZddZdS)rdz/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)r^)rr-r.rrrrDs zIOStreamingWriteTask._mainNr=r>r?r@rrrrrrdAsrdc@seZdZdZddZdS)rPaA 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|dSr)r9Z rename_filename)rr-rNrrrrrYszIORenameFileTask._mainNrrrrrrPQsrPc@seZdZdZddZdS)rgziA task to close out a file once the download is complete. :param fileobj: The fileobj to close. cCs |dSr)r9)rr-rrrrcszIOCloseTask._mainNrrrrrrg^srgcs*eZdZdZdfdd ZddZZS) rVzA 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)rr2pending_main_kwargsrrO)rCrVr)rrr2rrrOrGrrrms z!CompleteDownloadNOOPTask.__init__cCsdSrrr%rrrrxszCompleteDownloadNOOPTask._main)NNNT)r=r>r?r@rrrQrrrGrrVgs rVc@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|Srrr%rrr__iter__szDownloadChunkIterator.__iter__cCs<|j|j}|jd7_|r$|S|jdkr2|StdS)Nr)rreadrr StopIteration)rrrrr__next__s zDownloadChunkIterator.__next__N)r=r>r?rrrnextrrrrr|s  rc@s eZdZdZddZddZdS)rXa"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_offsetr%rrrrszDeferQueue.__init__cCs||jkrgSg}||jkr gSt|j||f|j||jr|jdd|jkrt|j}||d|dd|j|d|jt |d7_q>|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.rcZ next_writerrrr`s    zDeferQueue.request_writesN)r=r>r?r@rr`rrrrrXsrX)-loggingossocketrZrZbotocore.compatrZs3transfer.compatrZs3transfer.exceptionsrZs3transfer.futuresrZs3transfer.utilsrr r r r r rrrZs3transfer.tasksrr getLoggerr=raobjectrrBrRrWrerhrrr3rdrPrgrVrrXrrrr sH                q(-PB