o y`m@sddlZddlZddlZddlmZddlmZddlmZddl m Z ddl m Z ddl m Z ddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddl mZddlmZddlmZeeZGdddeZGdddeZGdddeZGdddeZGdddeZ 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_executorr5/usr/lib/python3/dist-packages/s3transfer/download.py__init__4s 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()NotImplementedErrorclsdownload_targetrrrr is_compatible9s 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_tagGsz+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_writesOsz/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_taskYs  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/r0r1 main_kwargs) IOWriteTaskrr.rrrr-gsz'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_tasks z'DownloadOutputManager.get_final_io_taskcCs$t|d|jjd}|j|j|S)Nwb)mode open_function)rropenradd_failure_cleanupclose)rfilenamefrrr_get_fileobj_from_filenames  z0DownloadOutputManager._get_fileobj_from_filenameN) __name__ __module__ __qualname____doc__r classmethodr&r(r+r2r-r6r?rrrrr's     rcs@eZdZfddZeddZddZddZd d ZZ S) DownloadFilenameOutputManagercs*tt||||d|_d|_d|_dSr)superrEr_final_filename_temp_filename _temp_fileobjr __class__rrrs  z&DownloadFilenameOutputManager.__init__cCs t|tjSr) isinstancer string_typesr#rrrr&s z+DownloadFilenameOutputManager.is_compatiblecCs.|jjj}||_|j||_||_|jSr) meta call_argsr/rGrget_temp_filenamerH_get_temp_fileobjrI)rr*r/rrrr+s  z7DownloadFilenameOutputManager.get_fileobj_for_io_writescCst|j|j|j|jdddS)N)r/final_filenamerT)rr4is_final)IORenameFileTaskrrIrGrr'rrrr6sz/DownloadFilenameOutputManager.get_final_io_taskcCs$||j}|j|jj|j|Sr)r?rHrr;r remove_file)rr>rrrrQs  z/DownloadFilenameOutputManager._get_temp_fileobj) r@rArBrrDr&r+r6rQ __classcell__rrrJrrEs  rEc@s(eZdZeddZddZddZdS)DownloadSeekableOutputManagercCst|Srrr#rrrr&sz+DownloadSeekableOutputManager.is_compatiblecC |jjjSrrNrOr/r)rrrr+ z7DownloadSeekableOutputManager.get_fileobj_for_io_writescC t|jdSN)rCompleteDownloadNOOPTaskrr'rrrr6sz/DownloadSeekableOutputManager.get_final_io_taskN)r@rArBrDr&r+r6rrrrrWs   rWcsXeZdZ dfdd ZeddZddZdd Zd d Zfd d Z ddZ Z S) DownloadNonSeekableOutputManagerNcs6tt|||||durt}||_t|_dSr)rFr_r DeferQueue _defer_queue threadingLock_io_submit_lockrrrr defer_queuerJrrrs z)DownloadNonSeekableOutputManager.__init__cCs t|dS)Nwrite)hasattrr#rrrr&rZz.DownloadNonSeekableOutputManager.is_compatiblecCstSrrr'rrrr(z6DownloadNonSeekableOutputManager.get_download_task_tagcCrXrrYr)rrrr+s z:DownloadNonSeekableOutputManager.get_fileobj_for_io_writescCr[r\r]r'rrrr6sz2DownloadNonSeekableOutputManager.get_final_io_taskcsr|j,|j||}|D]}|d}td|d|tt||||q WddS1s2wYdS)Nr0z%Queueing IO offset %s for fileobj: %sr1)rdrarequest_writesloggerdebugrFr_r2)rr/r0r1writesrgrJrrr2s"z3DownloadNonSeekableOutputManager.queue_file_io_taskcCst|j||ddS)N)r/r0r3)IOStreamingWriteTaskrr.rrrr-s z2DownloadNonSeekableOutputManager.get_io_write_taskr) r@rArBrrDr&r(r+r6r2r-rVrrrJrr_s   r_cs<eZdZ d fdd ZeddZddZdd ZZS) $DownloadSpecialFilenameOutputManagerNcs tt|||||d|_dSr)rFror_fileobjrerJrrrs  z-DownloadSpecialFilenameOutputManager.__init__cCst|tjo ||Sr)rLrrMis_special_filer#rrrr&s z2DownloadSpecialFilenameOutputManager.is_compatiblecCs|jjj}|||_|jSr)rNrOr/r?rp)rr*r=rrrr+ s  z>DownloadSpecialFilenameOutputManager.get_fileobj_for_io_writescCst|jdd|jidS)NTr/)rrSr4) IOCloseTaskrrpr'rrrr6s z6DownloadSpecialFilenameOutputManager.get_final_io_taskr) r@rArBrrDr&r+r6rVrrrJrros roc@sDeZdZdZddZ dddZddZd d Zd d Zd dZ dS)DownloadSubmissionTaskz/Task for submitting tasks to execute a downloadcCsHttttg}|jjj}|D] }|||r|Sq td|t |f)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.) rorErWr_rNrOr/r& RuntimeErrortype)rr*rdownload_manager_resolver_chainr/download_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 NBucketKey ContentLengthr) rNsize head_objectrObucketkey extra_argsprovide_transfer_sizerxrmultipart_threshold_submit_download_request_submit_ranged_download_request) rclientconfigrrequest_executorrr*bandwidth_limiterresponsedownload_output_managerrrr_submit5s2   zDownloadSubmissionTask._submitc Csp|jj} ||} t|d} |} |} |jj|t|j|| j | j | | j | |j ||j |d | gd| ddS)Nprogress) rrrr/r callbacks max_attemptsr io_chunksizerrr4done_callbackstag)rNrOr+r r(r6rr,ImmediatelyWriteIOGetObjectTaskrrrnum_download_attemptsr)rrrrrrrr*rrOr/progress_callbacksget_object_tag final_taskrrrrks4   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) rrrr/rrr start_indexrrrrr)rNrOr r+multipart_chunksizer r}r(r&_get_final_io_task_submission_callbackranger updater incrementrr, GetObjectTaskrrrr decrementfinalize)rrrrrrrr*rrOrr/ part_size num_partsrfinalize_download_invokerirange_parameterrrrrrsR     z6DownloadSubmissionTask._submit_ranged_download_requestcCs|}t|jj||Sr)r6r rr,)rdownload_managerrrrrrrs z=DownloadSubmissionTask._get_final_io_task_submission_callbackcCs6||}||dkr d}n||d}d||f}|S)Nz bytes=%s-%sr)rr part_indexr start_range end_range range_paramrrr_calculate_range_params    z-DownloadSubmissionTask._calculate_range_paramr) r@rArBrCrxrrrrrrrrrrss 6*? rsc@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 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. NryBodyzCRetrying exception caught (%s), retrying request, (attempt %s / %s)T)exc_infor)r get_objectrget_bandwith_limited_streamrDownloadChunkIteratordone _handle_iolenrrkrlr r)rrrrr/rrrrrrrlast_exceptionr current_indexrstreaming_bodychunkschunkerrr_mainsP      zGetObjectTask._maincCs||||dSr)r2)rrr/rindexrrrr#szGetObjectTask._handle_io)rN)r@rArBrrrrrrrs =rc@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-)rrr/rrtaskrrrr.s z*ImmediatelyWriteIOGetObjectTask._handle_ioN)r@rArBrCrrrrrr's rc@seZdZddZdS)r5cCs||||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)seekrgr.rrrr4s zIOWriteTask._mainN)r@rArBrrrrrr53s r5c@r)rnz/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)rg)rr/r0rrrrBs zIOStreamingWriteTask._mainNr@rArBrCrrrrrrn?s rnc@r)rTaA 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)r< rename_filename)rr/rRrrrrrWszIORenameFileTask._mainNrrrrrrTOs rTc@r)rrziA task to close out a file once the download is complete. :param fileobj: The fileobj to close. cCs |dSr)r<)rr/rrrras zIOCloseTask._mainNrrrrrrr\s rrcs0eZdZdZ   dfdd ZddZZS) r^zA 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)rr4pending_main_kwargsrrS)rFr^r)rrr4rrrSrJrrrks  z!CompleteDownloadNOOPTask.__init__cCsdSrrr'rrrrvrizCompleteDownloadNOOPTask._main)NNNT)r@rArBrCrrrVrrrJrr^es r^c@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{s zDownloadChunkIterator.__init__cCs|Srrr'rrr__iter__rizDownloadChunkIterator.__iter__cCs8|j|j}|jd7_|r|S|jdkr|St)Nr)rreadrr StopIteration)rrrrr__next__s zDownloadChunkIterator.__next__N)r@rArBrrrnextrrrrrzs   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)r1r0) rrheapqheappushraddheappopappendremover)rr1r0rm next_writerrrrjs    zDeferQueue.request_writesN)r@rArBrCrrjrrrrr`s r`)+loggingrbrbotocore.compatrs3transfer.compatrs3transfer.exceptionsrs3transfer.futuresrs3transfer.utilsrr r r r r rrrs3transfer.tasksrr getLoggerr@rkobjectrrErWr_rorsrrr5rnrTrrr^rr`rrrrsF                 q(-PB