o dn@sddlZddlZddlZddlZddlmZmZddlmZm Z m Z ddl m Z ddl mZddlmZddlmZmZddlmZmZmZmZmZmZdd lmZdd lmZmZm Z m!Z!m"Z"m#Z#m$Z$e%e&Z'Gd d d Z(Gd ddZ)GdddZ*dS)N)BandwidthLimiter LeakyBucket)ALLOWED_DOWNLOAD_ARGSKBMB)CopySubmissionTask)DeleteSubmissionTask)DownloadSubmissionTask)CancelledError FatalError)IN_MEMORY_DOWNLOAD_TAGIN_MEMORY_UPLOAD_TAGBoundedExecutorTransferCoordinatorTransferFuture TransferMeta)UploadSubmissionTask)CallArgsOSUtilsSlidingWindowSemaphore TaskSemaphore get_callbackssignal_not_transferringsignal_transferringc @sBeZdZdededdddddeddddf ddZd d ZdS) TransferConfig iNc CsT||_||_||_||_||_||_||_||_| |_| |_ | |_ | |_ | dS)asConfigurations for the transfer manager :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 transferring 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. :param max_submission_queue_size: The maximum amount of TransferManager method calls that can be queued at a time. :param max_io_queue_size: The maximum amount of read parts that can be queued to be written to disk per download. The default size for each elementin 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 streaming down the data from s3 (i.e. socket errors and read timeouts that occur after receiving 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 download 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) selfrr r!r"r#r$r%r&r'r(r)r*r-m/private/var/folders/v1/_jykv66s6qd26_69j1njbrl80000gr/T/pip-target-p1gutpg6/lib/python/s3transfer/manager.py__init__/sV zTransferConfig.__init__cCs8|jD]\}}|dur|dkrtd||fqdS)Nrz9Provided parameter %s of value %s must be greater than 0.)__dict__items ValueError)r,attrZattr_valr-r-r.r+sz*TransferConfig._validate_attrs_are_nonzero)__name__ __module__ __qualname__rrr/r+r-r-r-r.r.s drc@seZdZeZgdZegdZgdZdZde diZ d,dd Z e d d Z e d d Zd-ddZ d-ddZ   d,ddZd-ddZddZddZ d.ddZddZddZd d!Zd"d#Zd$d%Zd/d(d)Zefd*d+ZdS)0TransferManager)ZACL CacheControlZChecksumAlgorithmZContentDispositionZContentEncodingZContentLanguageZ ContentTypeExpectedBucketOwnerZExpiresZGrantFullControlZ GrantReadZ GrantReadACPZ GrantWriteACPZMetadataZObjectLockLegalHoldStatusZObjectLockModeZObjectLockRetainUntilDate RequestPayerZServerSideEncryptionZ StorageClassZSSECustomerAlgorithmZSSECustomerKeyZSSECustomerKeyMD5Z SSEKMSKeyIdZSSEKMSEncryptionContextZTaggingZWebsiteRedirectLocation) ZCopySourceIfMatchZCopySourceIfModifiedSinceZCopySourceIfNoneMatchZCopySourceIfUnmodifiedSinceZCopySourceSSECustomerAlgorithmZCopySourceSSECustomerKeyZCopySourceSSECustomerKeyMD5ZMetadataDirectiveZTaggingDirective)ZMFAZ VersionIdr:r9TzS3 Object LambdazV^arn:(aws).*:s3-object-lambda:[a-z\-0-9]+:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\-]{1,63}NcCs||_||_|durt|_||_|durt|_t|_d|_t|jj |jj t t |jj tt|jji|d|_t|jj|jj|d|_t|jjd|d|_d|_|jjdurktd|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_osutilrTransferCoordinatorController_coordinator_controller _id_counterrr#r!r rr(r rr)_request_executorr$r"_submission_executorr% _io_executor_bandwidth_limiterr*loggerdebugrr_register_handlers)r,clientconfigosutilr=Z leaky_bucketr-r-r.r/sN     zTransferManager.__init__cC|jSN)r?r,r-r-r.rLzTransferManager.clientcCrOrP)r@rQr-r-r.rMrRzTransferManager.configcCsd|duri}|dur g}|||j||t|||||d}i}|jr+|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_ARGS_validate_if_bucket_supportedrrH_submit_transferr)r,rSrTrUrVrW call_argsextra_main_kwargsr-r-r.upload#s&  zTransferManager.uploadcCsj|duri}|dur g}|||j||t|||||d}d|ji}|jr.|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)rTrUrSrVrWZ io_executorrX)rYrr[rrGrHr\r )r,rTrUrSrVrWr]r^r-r-r.downloadQs&   zTransferManager.downloadcCsx|duri}|dur g}|dur|j}|||jt|tr'||d||t||||||d}||t S)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 NZBucket) copy_sourcerTrUrVrW source_client) r?rYALLOWED_COPY_ARGS isinstancedictr[getrr\r)r,rarTrUrVrWrbr]r-r-r.copys&+   zTransferManager.copycCsL|duri}|dur g}|||j||t||||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)rTrUrVrW)rYALLOWED_DELETE_ARGSr[rr\r)r,rTrUrVrWr]r-r-r.deletes  zTransferManager.deletecCs<|jr|jD]\}}||}|rtd|qdSdS)NzTTransferManager methods do not support %s resource. Use direct client calls instead.) VALIDATE_SUPPORTED_BUCKET_VALUES_UNSUPPORTED_BUCKET_PATTERNSr1matchr2)r,rTresourcepatternrlr-r-r.r[s z-TransferManager._validate_if_bucket_supportedcCs,|D]}||vrtd|d|fqdS)Nz/Invalid extra_args key '%s', must be one of: %sz, )r2join)r,actualallowedkwargr-r-r.rYs z(TransferManager._validate_all_known_argscCsj|si}||\}}t|dD] }|d|q|||}|j||d|d|jd7_|S)Ndone coordinator)transfer_coordinator main_kwargsr>)_get_future_with_componentsradd_done_callback _get_submission_task_main_kwargsrFsubmitrD)r,r]Zsubmission_task_clsr^transfer_future componentscallbackrvr-r-r.r\s$z TransferManager._submit_transfercCsT|j}t|d}|j|||jj|t||d|d}tdi|}||fS)N) transfer_id)metartr-)rDrrCadd_transfer_coordinatorrxremove_transfer_coordinatorrr)r,r]r~rur|r{r-r-r.rws  z+TransferManager._get_future_with_componentscCs&|j|j|j|j|d}|||S)N)rLrMrNZrequest_executorr{)r?r@rArEupdate)r,r{r^rvr-r-r.ry1s z0TransferManager._get_submission_task_main_kwargscCs4d}|jjjj|tdd|jjjj|tdddS)Nzrequest-created.s3zs3upload-not-transferring) unique_idzs3upload-transferring)r?reventsZregister_firstrZ register_lastr)r,Z event_namer-r-r.rK>s   z"TransferManager._register_handlerscCs|SrPr-rQr-r-r. __enter__JszTransferManager.__enter__cGsHd}d}t}|rd}t|}|st|}t|trt}||||dS)NFT)r strreprrdKeyboardInterruptr _shutdown)r,exc_type exc_valueargscancel cancel_msgZcancel_exc_typer-r-r.__exit__Ms zTransferManager.__exit__FrcCs||||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.shutdown^szTransferManager.shutdowncCs|r |j||z(z|jWnty|jdwW|j|j|jdS|j|j|jw)NzKeyboardInterrupt())rCrwaitrrFrrErG)r,rrrr-r-r.ros     zTransferManager._shutdown)NNN)NNrP)Fr)r4r5r6rrZrcrhrjrecompilerkr/propertyrLrMr_r`rgrir[rYr\rwryrKrrrr rr-r-r-r.r7sD   B   / 5 ?$  #   r7c@sFeZdZddZeddZddZddZd efd d Z d d Z dS)rBcCst|_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_coordinatorsrQr-r-r.r/s  z&TransferCoordinatorController.__init__cCs6|jt|jWdS1swYdS)z.The set of transfer coordinators being trackedN)rrgrrQr-r-r.tracked_transfer_coordinatorss $z;TransferCoordinatorController.tracked_transfer_coordinatorscC8|j|j|WddS1swYdS)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)rraddr,rur-r-r.rs"z6TransferCoordinatorController.add_transfer_coordinatorcCr)aRemove a transfer coordinator from cancellation 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)rrremoverr-r-r.rs "z9TransferCoordinatorController.remove_transfer_coordinatorrcCs|jD]}|||qdS)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,msgrrur-r-r.rs z$TransferCoordinatorController.cancelcCs\zd}|jD]}|qWdSty$td|r#td|ty-YdSw)zWait until there are no more inprogress transfers This will not stop when failures are encountered and not propagate 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)rresultrrIrJ Exceptionrr-r-r.rs      z"TransferCoordinatorController.waitN) r4r5r6r/rrrrr rrr-r-r-r.rBs   rB)+rgloggingrrZs3transfer.bandwidthrrZs3transfer.constantsrrrZs3transfer.copiesrZs3transfer.deleterZs3transfer.downloadr Zs3transfer.exceptionsr r Zs3transfer.futuresr r rrrrZs3transfer.uploadrZs3transfer.utilsrrrrrrr getLoggerr4rIrr7rBr-r-r-r.s(      $ no