B -<`j@szddlZddlZddlZddlmZddlmZmZddlmZddl m Z ddl m Z ddl m Z ddl m Z dd l mZdd l mZdd l mZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddl#m$Z$ddl#m%Z%e&e'Z(Gddde)Z*Gddde)Z+Gddde)Z,dS) N)six)KBMB)ALLOWED_DOWNLOAD_ARGS) get_callbacks)signal_transferring)signal_not_transferring)CallArgs)OSUtils) TaskSemaphore)SlidingWindowSemaphore)CancelledError) FatalError)IN_MEMORY_DOWNLOAD_TAG)IN_MEMORY_UPLOAD_TAG)BoundedExecutor)TransferFuture) TransferMeta)TransferCoordinator)DownloadSubmissionTask)UploadSubmissionTask)CopySubmissionTask)DeleteSubmissionTask) LeakyBucket)BandwidthLimiterc @sBeZdZdededdddddeddddf ddZd d ZdS) TransferConfig iNc CsT||_||_||_||_||_||_||_||_| |_| |_ | |_ | |_ | dS)a(Configurations for the transfer mangager :param multipart_threshold: The threshold for which multipart transfers occur. :param max_request_concurrency: The maximum number of S3 API transfer-related requests that can happen at a time. :param max_submission_concurrency: The maximum number of threads processing a call to a TransferManager method. Processing a call usually entails determining which S3 API requests that need to be enqueued, but does **not** entail making any of the S3 API data transfering requests needed to perform the transfer. The threads controlled by ``max_request_concurrency`` is responsible for that. :param multipart_chunksize: The size of each transfer if a request becomes a multipart transfer. :param max_request_queue_size: The maximum amount of S3 API requests that can be queued at a time. A value of zero means that there is no maximum. :param max_submission_queue_size: The maximum amount of TransferManager method calls that can be queued at a time. A value of zero means that there is no maximum. :param max_io_queue_size: The maximum amount of read parts that can be queued to be written to disk per download. A value of zero means that there is no maximum. The default size for each element in this queue is 8 KB. :param io_chunksize: The max size of each chunk in the io queue. Currently, this is size used when reading from the downloaded stream as well. :param num_download_attempts: The number of download attempts that will be tried upon errors with downloading an object in S3. Note that these retries account for errors that occur when streamming down the data from s3 (i.e. socket errors and read timeouts that occur after recieving an OK response from s3). Other retryable exceptions such as throttling errors and 5xx errors are already retried by botocore (this default is 5). The ``num_download_attempts`` does not take into account the number of exceptions retried by botocore. :param max_in_memory_upload_chunks: The number of chunks that can be stored in memory at a time for all ongoing upload requests. This pertains to chunks of data that need to be stored in memory during an upload if the data is sourced from a file-like object. The total maximum memory footprint due to a in-memory upload chunks is roughly equal to: max_in_memory_upload_chunks * multipart_chunksize + max_submission_concurrency * multipart_chunksize ``max_submission_concurrency`` has an affect on this value because for each thread pulling data off of a file-like object, they may be waiting with a single read chunk to be submitted for upload because the ``max_in_memory_upload_chunks`` value has been reached by the threads making the upload request. :param max_in_memory_download_chunks: The number of chunks that can be buffered in memory and **not** in the io queue at a time for all ongoing dowload requests. This pertains specifically to file-like objects that cannot be seeked. The total maximum memory footprint due to a in-memory download chunks is roughly equal to: max_in_memory_download_chunks * multipart_chunksize :param max_bandwidth: The maximum bandwidth that will be consumed in uploading and downloading file content. The value is in terms of bytes per second. N) multipart_thresholdmultipart_chunksizemax_request_concurrencymax_submission_concurrencymax_request_queue_sizemax_submission_queue_sizemax_io_queue_size io_chunksizenum_download_attemptsmax_in_memory_upload_chunksmax_in_memory_download_chunks max_bandwidth_validate_attrs_are_nonzero) selfr r!r"r#r$r%r&r'r(r)r*r+r.9/tmp/pip-target-7cdyy134/lib/python/s3transfer/manager.py__init__0sWzTransferConfig.__init__cCs<x6|jD](\}}|dk r |dkr td||fq WdS)Nrz9Provided parameter %s of value %s must be greater than 0.)__dict__items ValueError)r-attrZattr_valr.r.r/r,s z*TransferConfig._validate_attrs_are_nonzero)__name__ __module__ __qualname__rrr0r,r.r.r.r/r/s Yrc@seZdZeZddddddddd d d d d dddddddddgZedddddddddg Zd d!d gZdEd#d$Zed%d&Z ed'd(Z dFd)d*Z dGd+d,Z dHd-d.Z dId/d0Zd1d2ZdJd3d4Zd5d6Zd7d8Zd9d:Zd;d<Zd=d>ZdKdAdBZefdCdDZd"S)LTransferManagerZACL CacheControlZContentDispositionZContentEncodingZContentLanguageZ ContentTypeZExpiresZGrantFullControlZ GrantReadZ GrantReadACPZ GrantWriteACPZMetadataZ RequestPayerZServerSideEncryptionZ StorageClassZSSECustomerAlgorithmZSSECustomerKeyZSSECustomerKeyMD5Z SSEKMSKeyIdZSSEKMSEncryptionContextZTaggingZWebsiteRedirectLocationZCopySourceIfMatchZCopySourceIfModifiedSinceZCopySourceIfNoneMatchZCopySourceIfUnmodifiedSinceZCopySourceSSECustomerAlgorithmZCopySourceSSECustomerKeyZCopySourceSSECustomerKeyMD5ZMetadataDirectiveZTaggingDirectiveZMFAZ VersionIdNcCs||_||_|dkrt|_||_|dkr2t|_t|_d|_t|jj |jj t t |jj tt|jji|d|_t|jj|jj|d|_t|jjd|d|_d|_|jjdk rtd|jjt|jj}t||_|dS)aA transfer manager interface for Amazon S3 :param client: Client to be used by the manager :param config: TransferConfig to associate specific configurations :param osutil: OSUtils object to use for os-related behavior when using with transfer manager. :type executor_cls: s3transfer.futures.BaseExecutor :param executor_cls: The class of executor to use with the transfer manager. By default, concurrent.futures.ThreadPoolExecutor is used. Nr)max_sizemax_num_threadsZtag_semaphores executor_cls)r:r;r<zSetting max_bandwidth to %s)_client_configr_osutilr TransferCoordinatorController_coordinator_controller _id_counterrr$r"rr r)rr r*_request_executorr%r#_submission_executorr& _io_executor_bandwidth_limiterr+loggerdebugrr_register_handlers)r-clientconfigosutilr<Z leaky_bucketr.r.r/r0s@         zTransferManager.__init__cCs|jS)N)r>)r-r.r.r/rK szTransferManager.clientcCs|jS)N)r?)r-r.r.r/rLszTransferManager.configcCsZ|dkr i}|dkrg}|||jt|||||d}i}|jrL|j|d<||t|S)aUploads a file to S3 :type fileobj: str or seekable file-like object :param fileobj: The name of a file to upload or a seekable file-like object to upload. It is recommended to use a filename because file-like objects may result in higher memory usage. :type bucket: str :param bucket: The name of the bucket to upload to :type key: str :param key: The name of the key to upload to :type extra_args: dict :param extra_args: Extra arguments that may be passed to the client operation :type subscribers: list(s3transfer.subscribers.BaseSubscriber) :param subscribers: The list of subscribers to be invoked in the order provided based on the event emit during the process of the transfer request. :rtype: s3transfer.futures.TransferFuture :returns: Transfer future representing the upload N)fileobjbucketkey extra_args subscribersbandwidth_limiter)_validate_all_known_argsALLOWED_UPLOAD_ARGSr rG_submit_transferr)r-rNrOrPrQrR call_argsextra_main_kwargsr.r.r/uploads zTransferManager.uploadcCs`|dkr i}|dkrg}|||jt|||||d}d|ji}|jrR|j|d<||t|S)aDownloads a file from S3 :type bucket: str :param bucket: The name of the bucket to download from :type key: str :param key: The name of the key to download from :type fileobj: str or seekable file-like object :param fileobj: The name of a file to download or a seekable file-like object to download. It is recommended to use a filename because file-like objects may result in higher memory usage. :type extra_args: dict :param extra_args: Extra arguments that may be passed to the client operation :type subscribers: list(s3transfer.subscribers.BaseSubscriber) :param subscribers: The list of subscribers to be invoked in the order provided based on the event emit during the process of the transfer request. :rtype: s3transfer.futures.TransferFuture :returns: Transfer future representing the download N)rOrPrNrQrRZ io_executorrS)rTrr rFrGrVr)r-rOrPrNrQrRrWrXr.r.r/download<s  zTransferManager.downloadcCsT|dkr i}|dkrg}|dkr&|j}|||jt||||||d}||tS)aCopies a file in S3 :type copy_source: dict :param copy_source: The name of the source bucket, key name of the source object, and optional version ID of the source object. The dictionary format is: ``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note that the ``VersionId`` key is optional and may be omitted. :type bucket: str :param bucket: The name of the bucket to copy to :type key: str :param key: The name of the key to copy to :type extra_args: dict :param extra_args: Extra arguments that may be passed to the client operation :type subscribers: a list of subscribers :param subscribers: The list of subscribers to be invoked in the order provided based on the event emit during the process of the transfer request. :type source_client: botocore or boto3 Client :param source_client: The client to be used for operation that may happen at the source object. For example, this client is used for the head_object that determines the size of the copy. If no client is provided, the transfer manager's client is used as the client for the source object. :rtype: s3transfer.futures.TransferFuture :returns: Transfer future representing the copy N) copy_sourcerOrPrQrR source_client)r>rTALLOWED_COPY_ARGSr rVr)r-r[rOrPrQrRr\rWr.r.r/copyfs$zTransferManager.copycCsB|dkr i}|dkrg}|||jt||||d}||tS)aDelete an S3 object. :type bucket: str :param bucket: The name of the bucket. :type key: str :param key: The name of the S3 object to delete. :type extra_args: dict :param extra_args: Extra arguments that may be passed to the DeleteObject call. :type subscribers: list :param subscribers: A list of subscribers to be invoked during the process of the transfer request. Note that the ``on_progress`` callback is not invoked during object deletion. :rtype: s3transfer.futures.TransferFuture :return: Transfer future representing the deletion. N)rOrPrQrR)rTALLOWED_DELETE_ARGSr rVr)r-rOrPrQrRrWr.r.r/deleteszTransferManager.deletecCs0x*|D]"}||krtd|d|fqWdS)Nz/Invalid extra_args key '%s', must be one of: %sz, )r3join)r-actualallowedkwargr.r.r/rTs  z(TransferManager._validate_all_known_argscCsn|si}||\}}x t|dD]}|d|q"W|||}|j||d|d|jd7_|S)Ndone coordinator)transfer_coordinator main_kwargsr=)_get_future_with_componentsradd_done_callback _get_submission_task_main_kwargsrEZsubmitrC)r-rWZsubmission_task_clsrXtransfer_future componentscallbackrhr.r.r/rVs  z TransferManager._submit_transfercCsP|j}t|d}|j|||jj|t||d|d}tf|}||fS)N) transfer_id)metarf)rCrrBadd_transfer_coordinatorrjremove_transfer_coordinatorrr)r-rWrorgrmrlr.r.r/ris   z+TransferManager._get_future_with_componentscCs&|j|j|j|j|d}|||S)N)rKrLrMZrequest_executorrl)r>r?r@rDupdate)r-rlrXrhr.r.r/rks z0TransferManager._get_submission_task_main_kwargscCs4d}|jjjj|tdd|jjjj|tdddS)Nzrequest-created.s3zs3upload-not-transferring)Z unique_idzs3upload-transferring)r>rpeventsZregister_firstrZ register_lastr)r-Z event_namer.r.r/rJs  z"TransferManager._register_handlerscCs|S)Nr.)r-r.r.r/ __enter__ szTransferManager.__enter__cGsJd}d}t}|r8d}t|}|s*t|}t|tr8t}||||dS)NFT)rr text_typerepr isinstanceKeyboardInterruptr _shutdown)r-exc_type exc_valueargscancel cancel_msgZcancel_exc_typer.r.r/__exit__ s  zTransferManager.__exit__FrvcCs||||dS)aShutdown the TransferManager It will wait till all transfers complete before it completely shuts down. :type cancel: boolean :param cancel: If True, calls TransferFuture.cancel() for all in-progress in transfers. This is useful if you want the shutdown to happen quicker. :type cancel_msg: str :param cancel_msg: The message to specify if canceling all in-progress transfers. N)r{)r-rrr.r.r/shutdownszTransferManager.shutdowncCsn|r|j||z6y|jWn"tk rD|jdYnXWd|j|j|jXdS)NzKeyboardInterrupt())rBrwaitrzrErrDrF)r-rrr|r.r.r/r{/s    zTransferManager._shutdown)NNN)NN)NN)NNN)NN)N)Frv)r5r6r7rrUr]r_r0propertyrKrLrYrZr^r`rTrVrirkrJrurrr r{r.r.r.r/r8sl @   ) ) 1 !    r8c@sFeZdZddZeddZddZddZd efd d Z d d Z dS)rAcCst|_t|_dS)zAbstraction to control all transfer coordinators This abstraction allows the manager to wait for inprogress transfers to complete and cancel all inprogress transfers. N) threadingLock_lockset_tracked_transfer_coordinators)r-r.r.r/r0Is z&TransferCoordinatorController.__init__c Cs|jt|jSQRXdS)z.The set of transfer coordinators being trackedN)rr^r)r-r.r.r/tracked_transfer_coordinatorsRsz;TransferCoordinatorController.tracked_transfer_coordinatorsc Cs"|j|j|WdQRXdS)zAdds a transfer coordinator of a transfer to be canceled if needed :type transfer_coordinator: s3transfer.futures.TransferCoordinator :param transfer_coordinator: The transfer coordinator for the particular transfer N)rradd)r-rgr.r.r/rq[sz6TransferCoordinatorController.add_transfer_coordinatorc Cs"|j|j|WdQRXdS)aRemove a transfer coordinator from cancelation consideration Typically, this method is invoked by the transfer coordinator itself to remove its self when it completes its transfer. :type transfer_coordinator: s3transfer.futures.TransferCoordinator :param transfer_coordinator: The transfer coordinator for the particular transfer N)rrremove)r-rgr.r.r/rres z9TransferCoordinatorController.remove_transfer_coordinatorrvcCs x|jD]}|||qWdS)aPCancels all inprogress transfers This cancels the inprogress transfers by calling cancel() on all tracked transfer coordinators. :param msg: The message to pass on to each transfer coordinator that gets cancelled. :param exc_type: The type of exception to set for the cancellation N)rr)r-msgr|rgr.r.r/rrs z$TransferCoordinatorController.cancelcCshy d}x|jD] }|qWWnBtk rPtd|rJtd|Yntk rbYnXdS)zWait until there are no more inprogress transfers This will not stop when failures are encountered and not propogate any of these errors from failed transfers, but it can be interrupted with a KeyboardInterrupt. Nz$Received KeyboardInterrupt in wait()z'On KeyboardInterrupt was waiting for %s)rresultrzrHrI Exception)r-rgr.r.r/rs  z"TransferCoordinatorController.waitN) r5r6r7r0rrrqrrr rrr.r.r.r/rAHs    rA)-r^loggingrZbotocore.compatrZs3transfer.constantsrrrZs3transfer.utilsrrrr r r r Zs3transfer.exceptionsr rZs3transfer.futuresrrrrrrZs3transfer.downloadrZs3transfer.uploadrZs3transfer.copiesrZs3transfer.deleterZs3transfer.bandwidthrr getLoggerr5rHobjectrr8rAr.r.r.r/ sB                        n.