o dm@spddlZddlZddlZddlmZddlmZddlmZddl m Z m Z ddl m Z mZmZmZmZmZmZmZmZeeZGdddZGd d d eZGd d d eZGd ddeZGdddeZGddde ZGddde ZGdddeZ Gddde Z!Gddde Z"Gddde Z#Gddde Z$Gdd d e Z%Gd!d"d"Z&Gd#d$d$Z'dS)%Nseekable)RetriesExceededErrorIN_MEMORY_DOWNLOAD_TAG)SubmissionTaskTask) S3_RETRYABLE_DOWNLOAD_ERRORSCountCallbackInvokerDeferredOpenFileFunctionContainerStreamReaderProgresscalculate_num_partscalculate_range_parameter get_callbacksinvoke_progress_callbacksc@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_executorrn/private/var/folders/v1/_jykv66s6qd26_69j1njbrl80000gr/T/pip-target-p1gutpg6/lib/python/s3transfer/download.py__init__2s zDownloadOutputManager.__init__cCtd)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()NotImplementedErrorclsZdownload_targetrrrr is_compatible7s 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_tagEsz+DownloadOutputManager.get_download_task_tagcCr)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()r rtransfer_futurerrrget_fileobj_for_io_writesMsz/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_taskWs 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+dsz'DownloadOutputManager.get_io_write_taskcCr)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()r r%rrrget_final_io_task~s z'DownloadOutputManager.get_final_io_taskcCs$t|d|jjd}|j|j|S)Nwb)modeZ open_function)r ropenradd_failure_cleanupclose)rfilenamefrrr_get_fileobj_from_filenames  z0DownloadOutputManager._get_fileobj_from_filenameN) __name__ __module__ __qualname____doc__r classmethodr$r&r)r0r+r4r<rrrrr$s      rcs@eZdZfddZeddZddZddZd d ZZ S) DownloadFilenameOutputManagercs&t|||d|_d|_d|_dSr)superr_final_filename_temp_filename _temp_fileobjr __class__rrrs z&DownloadFilenameOutputManager.__init__cCs t|tSr) isinstancestrr"rrrr$ z+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;rrrrNs  z/DownloadFilenameOutputManager._get_temp_fileobj) r=r>r?rrAr$r)r4rN __classcell__rrrGrrBs  rBc@s(eZdZeddZddZddZdS)DownloadSeekableOutputManagercCst|Srrr"rrrr$sz+DownloadSeekableOutputManager.is_compatiblecC |jjjSrrLrMr-r'rrrr)rKz7DownloadSeekableOutputManager.get_fileobj_for_io_writescC t|jdSN)rCompleteDownloadNOOPTaskrr%rrrr4sz/DownloadSeekableOutputManager.get_final_io_taskN)r=r>r?rAr$r)r4rrrrrSs   rScsXeZdZ dfdd ZeddZddZdd Zd d Zfd d Z ddZ Z S) DownloadNonSeekableOutputManagerNcs2t||||durt}||_t|_dSr)rCr DeferQueue _defer_queue threadingLock_io_submit_lockrrrrZ defer_queuerGrrrs z)DownloadNonSeekableOutputManager.__init__cCs t|dS)Nwrite)hasattrr"rrrr$rKz.DownloadNonSeekableOutputManager.is_compatiblecCstSrrr%rrrr&z6DownloadNonSeekableOutputManager.get_download_task_tagcCrTrrUr'rrrr)s z:DownloadNonSeekableOutputManager.get_fileobj_for_io_writescCrVrWrXr%rrrr4sz2DownloadNonSeekableOutputManager.get_final_io_taskcsn|j*|j||}|D]}|d}td|d|t|||q WddS1s0wYdS)Nr.z%Queueing IO offset %s for fileobj: %sr/)r_r\request_writesloggerdebugrCr0)rr-r.r/writesrarGrrr0s"z3DownloadNonSeekableOutputManager.queue_file_io_taskcCst|j||ddS)N)r-r.r1)IOStreamingWriteTaskrr,rrrr+s z2DownloadNonSeekableOutputManager.get_io_write_taskr) r=r>r?rrAr$r&r)r4r0r+rRrrrGrrZs   rZcs<eZdZ d fdd ZeddZddZdd ZZS) $DownloadSpecialFilenameOutputManagerNcst||||d|_dSr)rCr_fileobjr`rGrrrs z-DownloadSpecialFilenameOutputManager.__init__cCst|to ||Sr)rIrJZis_special_filer"rrrr$sz2DownloadSpecialFilenameOutputManager.is_compatiblecCs|jjj}|||_|jSr)rLrMr-r<rj)rr(r:rrrr) s  z>DownloadSpecialFilenameOutputManager.get_fileobj_for_io_writescCst|jdd|jidS)NTr-)rrPr2) IOCloseTaskrrjr%rrrr4s z6DownloadSpecialFilenameOutputManager.get_final_io_taskr) r=r>r?rrAr$r)r4rRrrrGrris ric@sDeZdZdZddZ dddZddZd d Zd d Zd dZ dS)DownloadSubmissionTaskz/Task for submitting tasks to execute a downloadcCsHttttg}|jjj}|D] }|||r|Sq td |t |)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 {} of type: {} is not supported.) rirBrSrZrLrMr-r$ RuntimeErrorformattype)rr(rZdownload_manager_resolver_chainr-Zdownload_manager_clsrrr _get_download_output_manager_clss  z7DownloadSubmissionTask._get_download_output_manager_clsNc Cs|jjdur"|jd|jjj|jjjd|jjj}|j|d|||||j |} |jj|j krB| |||||| ||dS| |||||| ||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 NZBucketKeyZ ContentLengthr) rLsizeZ head_objectrMbucketkey extra_argsZprovide_transfer_sizerprZmultipart_threshold_submit_download_request_submit_ranged_download_request) rclientconfigrrequest_executorrr(bandwidth_limiterresponsedownload_output_managerrrr_submit;sH $ zDownloadSubmissionTask._submitc Csp|jj} ||} t|d} |} |} |jj|t|j|| j | j | | j | |j ||j |d | gd| ddS)Nprogress) ryrtrur-rv callbacks max_attemptsr~ io_chunksizer|rr2done_callbackstag)rLrMr)rr&r4rr*ImmediatelyWriteIOGetObjectTaskrtrurvnum_download_attemptsr)rryrzrr{rr~r(r|rMr-progress_callbacksget_object_tag final_taskrrrrws4    z/DownloadSubmissionTask._submit_download_requestc Cs|jj} t|d} ||} |j} t|jj| } |}t| ||}t | D]9}t | || }d|i}| | j ||jj|t|j|| j| j| || |j|| ||j|d |jgd|dq(|dS)NrRange) ryrtrur-rvrr start_indexr~rr|rr)rLrMrr)Zmultipart_chunksizerrsr&r &_get_final_io_task_submission_callbackrangerupdaterv incrementrr* GetObjectTaskrtrurrZ decrementfinalize)rryrzrr{rr~r(r|rMrr- part_size num_partsrZfinalize_download_invokeriZrange_parameterrvrrrrxsR     z6DownloadSubmissionTask._submit_ranged_download_requestcCs|}t|jj||Sr)r4r rr*)rZdownload_managerrrrrrrs z=DownloadSubmissionTask._get_final_io_task_submission_callbackcCs:||}||dkr d}n||d}d|d|}|S)Nzbytes=-r)rrZ part_indexrZ start_rangeZ end_rangeZ range_paramrrr_calculate_range_param s   z-DownloadSubmissionTask._calculate_range_paramr) r=r>r?r@rprrwrxrrrrrrrls& M2G rlc@s"eZdZ  dddZddZdS)rrNc  Csd} t|D]j} zC| }|jd||d|}t|d|}| r&| ||j}t|| }|D]}|jsC||||||t|7}q-WdSWdSt yp}zt j d|| |dd|} t || |WYd}~qd}~wwt | )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 arguments 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. NrqZBodyzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)exc_infor)rZ get_objectr Zget_bandwith_limited_streamrDownloadChunkIteratordone _handle_iolenr rerfrr)rryrtrur-rvrrr~rrr|Zlast_exceptionrZ current_indexr}Zstreaming_bodychunkschunkerrr_mainsZ     zGetObjectTask._maincCs||||dSr)r0)rr~r-rindexrrrriszGetObjectTask._handle_io)rN)r=r>r?rrrrrrrs   Trc@eZdZdZddZdS)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+)rr~r-rrtaskrrrrus z*ImmediatelyWriteIOGetObjectTask._handle_ioN)r=r>r?r@rrrrrrms rc@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)seekrar,rrrr{s zIOWriteTask._mainN)r=r>r?rrrrrr3zs r3c@r)rhz/Task for writing data to a non-seekable stream.cCs||dS)zWrite data to a fileobj. Data will be written directly to the fileobj without any prior seeking. :param fileobj: The fileobj to write content to :param data: The data to write N)ra)rr-r.rrrrs zIOStreamingWriteTask._mainNr=r>r?r@rrrrrrhs rhc@r)rQaA 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-rOrrrrrszIORenameFileTask._mainNrrrrrrQs rQc@r)rkziA task to close out a file once the download is complete. :param fileobj: The fileobj to close. cCs |dSr)r9)rr-rrrrs zIOCloseTask._mainNrrrrrrks rkcs2eZdZdZ    dfdd ZddZZS) rYzA 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. NTcstj|||||ddS)N)rr2pending_main_kwargsrrP)rCr)rrr2rrrPrGrrrs z!CompleteDownloadNOOPTask.__init__cCsdSrrr%rrrrrczCompleteDownloadNOOPTask._main)NNNT)r=r>r?r@rrrRrrrGrrYs rYc@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 chunksizerrrrs zDownloadChunkIterator.__init__cCs|Srrr%rrr__iter__rczDownloadChunkIterator.__iter__cCs8|j|j}|jd7_|r|S|jdkr|St)Nr)rreadrr StopIteration)rrrrr__next__s zDownloadChunkIterator.__next__N)r=r>r?rrrnextrrrrrs   rc@s eZdZdZddZddZdS)r[a"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%rrrrs zDeferQueue.__init__cCs||jkrgSg}||jvrgSt|j||f|j||jr^|jdd|jkr^t|j}||d|dd|j|d|jt |d7_|jr^|jdd|jks,|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.rgZ next_writerrrrds    zDeferQueue.request_writesN)r=r>r?r@rrdrrrrr[s r[)(rloggingr]Zs3transfer.compatrZs3transfer.exceptionsrZs3transfer.futuresrZs3transfer.tasksrrZs3transfer.utilsr r r r r rrrr getLoggerr=rerrBrSrZrirlrrr3rhrQrkrYrr[rrrrs2    , q(/{Y