B
    è?F[YC  ã               @   sê   d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlZd dl	m
Z
mZmZmZmZ d dlmZmZmZ eƒ Ze d¡ZG dd„ deƒZG dd	„ d	eƒZG d
d„ dejƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZdS )é    N)ÚQueue)ÚDEFAULT_PART_SIZEÚminimum_part_sizeÚchunk_hashesÚ	tree_hashÚbytes_to_hex)ÚUploadArchiveErrorÚDownloadArchiveErrorÚTreeHashDoesNotMatchErrorzboto.glacier.concurrentc               @   s2   e Zd Zedfdd„Zdd„ Zdd„ Zdd	„ Zd
S )ÚConcurrentTransfereré
   c             C   s   || _ || _g | _d S )N)Ú
_part_sizeÚ_num_threadsÚ_threads)ÚselfÚ	part_sizeÚnum_threads© r   ú6lib/python3.7/site-packages/boto/glacier/concurrent.pyÚ__init__+   s    zConcurrentTransferer.__init__c             C   sL   t |ƒ}| j|kr| j}n|}t d| j|¡ tt |t|ƒ ¡ƒ}||fS )NzfThe part size specified (%s) is smaller than the minimum required part size.  Using a part size of: %s)r   r   ÚlogÚdebugÚintÚmathZceilÚfloat)r   Ú
total_sizeZmin_part_size_requiredr   Útotal_partsr   r   r   Ú_calculate_required_part_size0   s    

z2ConcurrentTransferer._calculate_required_part_sizec             C   sF   t  d¡ x| jD ]
}d|_qW x| jD ]}| ¡  q(W t  d¡ d S )NzShutting down threads.FzThreads have exited.)r   r   r   Úshould_continueÚjoin)r   Úthreadr   r   r   Ú_shutdown_threads<   s    

z&ConcurrentTransferer._shutdown_threadsc             C   sL   t  d¡ xt|ƒD ]}| ||f¡ qW xt| jƒD ]}| t¡ q6W d S )NzAdding work items to queue.)r   r   ÚrangeÚputr   Ú_END_SENTINEL)r   r   Úworker_queuer   Úir   r   r   Ú_add_work_items_to_queueD   s
    
z-ConcurrentTransferer._add_work_items_to_queueN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r!   r'   r   r   r   r   r   *   s   r   c                   s@   e Zd ZdZedf‡ fdd„	Zddd„Zdd	„ Zd
d„ Z‡  Z	S )ÚConcurrentUploadera  Concurrently upload an archive to glacier.

    This class uses a thread pool to concurrently upload an archive
    to glacier using the multipart upload API.

    The threadpool is completely managed by this class and is
    transparent to the users of this class.

    r   c                s"   t t| ƒ ||¡ || _|| _dS )au  
        :type api: :class:`boto.glacier.layer1.Layer1`
        :param api: A layer1 glacier object.

        :type vault_name: str
        :param vault_name: The name of the vault.

        :type part_size: int
        :param part_size: The size, in bytes, of the chunks to use when uploading
            the archive parts.  The part size must be a megabyte multiplied by
            a power of two.

        :type num_threads: int
        :param num_threads: The number of threads to spawn for the thread pool.
            The number of threads will control how much parts are being
            concurrently uploaded.

        N)Úsuperr+   r   Ú_apiÚ_vault_name)r   ÚapiÚ
vault_namer   r   )Ú	__class__r   r   r   V   s    zConcurrentUploader.__init__Nc          
   C   sô   t  |¡j}|  |¡\}}dg| }tƒ }tƒ }| j | j||¡}	|	d }
|  |||¡ |  	||
||¡ y|  
|||¡ W n@ tk
rº } z"t d¡ | j | j|
¡ |‚W dd}~X Y nX t d¡ | j | j|
tt|ƒƒ|¡}	t d¡ |	d S )a^  Concurrently create an archive.

        The part_size value specified when the class was constructed
        will be used *unless* it is smaller than the minimum required
        part size needed for the size of the given file.  In that case,
        the part size used will be the minimum part size required
        to properly upload the given file.

        :type file: str
        :param file: The filename to upload

        :type description: str
        :param description: The description of the archive.

        :rtype: str
        :return: The archive id of the newly created archive.

        NZUploadIdzHAn error occurred while uploading an archive, aborting multipart upload.zCompleting upload.zUpload finished.Z	ArchiveId)ÚosÚstatÚst_sizer   r   r-   Zinitiate_multipart_uploadr.   r'   Ú_start_upload_threadsÚ_wait_for_upload_threadsr   r   r   Zabort_multipart_uploadZcomplete_multipart_uploadr   r   )r   ÚfilenameZdescriptionr   r   r   Úhash_chunksr%   Úresult_queueÚresponseÚ	upload_idÚer   r   r   Úuploadn   s2    





zConcurrentUploader.uploadc             C   s`   xRt |ƒD ]F}| ¡ }t|tƒr@t d|¡ |  ¡  td| ƒ‚|\}}|||< q
W |  ¡  d S )Nz?An error was found in the result queue, terminating threads: %sz0An error occurred while uploading an archive: %s)r"   ÚgetÚ
isinstanceÚ	Exceptionr   r   r!   r   )r   r8   r9   r   Ú_ÚresultÚpart_numberZtree_sha256r   r   r   r6       s    
z+ConcurrentUploader._wait_for_upload_threadsc             C   sV   t  d¡ xFt| jƒD ]8}t| j| j||||ƒ}t d¡ | 	¡  | j
 |¡ qW d S )NzStarting threads.gš™™™™™É?)r   r   r"   r   ÚUploadWorkerThreadr-   r.   ÚtimeÚsleepÚstartr   Úappend)r   r9   r;   r%   r7   rA   r    r   r   r   r5   °   s    


z(ConcurrentUploader._start_upload_threads)N)
r(   r)   r*   Ú__doc__r   r   r=   r6   r5   Ú__classcell__r   r   )r1   r   r+   L   s   	
2r+   c                   s4   e Zd Z‡ fdd„Zdd„ Zdd„ Zdd„ Z‡  ZS )	ÚTransferThreadc                s$   t t| ƒ ¡  || _|| _d| _d S )NT)r,   rK   r   Ú_worker_queueÚ_result_queuer   )r   r%   r9   )r1   r   r   r   ¼   s    zTransferThread.__init__c             C   sl   x^| j r^y| jjdd}W n tk
r0   wY nX |tkrF|  ¡  d S |  |¡}| j |¡ qW |  ¡  d S )Né   )Ztimeout)	r   rL   r>   ZEmptyr$   Ú_cleanupÚ_process_chunkrM   r#   )r   ÚworkrB   r   r   r   ÚrunÄ   s    
zTransferThread.runc             C   s   d S )Nr   )r   rQ   r   r   r   rP   Ñ   s    zTransferThread._process_chunkc             C   s   d S )Nr   )r   r   r   r   rO   Ô   s    zTransferThread._cleanup)r(   r)   r*   r   rR   rP   rO   rJ   r   r   )r1   r   rK   »   s   rK   c                   s<   e Zd Zddef‡ fdd„	Zdd„ Zdd„ Zdd	„ Z‡  ZS )
rD   é   c
       
         sL   t t| ƒ ||¡ || _|| _|| _t|dƒ| _|| _|| _	|| _
|	| _d S )NÚrb)r,   rD   r   r-   r.   Ú	_filenameÚopenÚ_fileobjÚ
_upload_idÚ_num_retriesÚ_time_between_retriesÚ_retry_exceptions)
r   r/   r0   r7   r;   r%   r9   Únum_retriesÚtime_between_retriesÚretry_exceptions)r1   r   r   r   Ù   s    zUploadWorkerThread.__init__c             C   s’   d }xˆt | jd ƒD ]v}y|  |¡}P W q | jk
rˆ } z@t d|d | j|d | jd | j|j|¡ t	 
| j¡ |}W d d }~X Y qX qW |S )NrN   zpException caught uploading part number %s for vault %s, attempt: (%s / %s), filename: %s, exception: %s, msg: %sr   )r"   rY   Ú_upload_chunkr[   r   Úerrorr.   rU   r1   rE   rF   rZ   )r   rQ   rB   r&   r<   r   r   r   rP   ç   s    
z!UploadWorkerThread._process_chunkc       
      C   s’   |\}}|| }| j  |¡ | j  |¡}t |¡ ¡ }tt|ƒƒ}||t|ƒ d f}t	 
d||¡ | j | j| j|t|ƒ||¡}	|	 ¡  ||fS )NrN   zUploading chunk %s of size %s)rW   ÚseekÚreadÚhashlibZsha256Z	hexdigestr   r   Úlenr   r   r-   Zupload_partr.   rX   r   )
r   rQ   rC   r   Ú
start_byteÚcontentsZlinear_hashZtree_hash_bytesÚ
byte_ranger:   r   r   r   r_   ÷   s    z UploadWorkerThread._upload_chunkc             C   s   | j  ¡  d S )N)rW   Úclose)r   r   r   r   rO     s    zUploadWorkerThread._cleanup)	r(   r)   r*   r@   r   rP   r_   rO   rJ   r   r   )r1   r   rD   Ø   s   rD   c                   s>   e Zd ZdZedf‡ fdd„	Zdd„ Zdd„ Zd	d
„ Z‡  Z	S )ÚConcurrentDownloaderzý
    Concurrently download an archive from glacier.

    This class uses a thread pool to concurrently download an archive
    from glacier.

    The threadpool is completely managed by this class and is
    transparent to the users of this class.

    r   c                s   t t| ƒ ||¡ || _dS )a  
        :param job: A layer2 job object for archive retrieval object.

        :param part_size: The size, in bytes, of the chunks to use when uploading
            the archive parts.  The part size must be a megabyte multiplied by
            a power of two.

        N)r,   ri   r   Ú_job)r   Újobr   r   )r1   r   r   r     s    
zConcurrentDownloader.__init__c          
   C   s   | j j}|  |¡\}}tƒ }tƒ }|  |||¡ |  ||¡ y|  |||¡ W n2 tk
r€ } zt 	d|¡ |‚W dd}~X Y nX t 	d¡ dS )z’
        Concurrently download an archive.

        :param filename: The filename to download the archive to
        :type filename: str

        z2An error occurred while downloading an archive: %sNzDownload completed.)
rj   Zarchive_sizer   r   r'   Ú_start_download_threadsÚ_wait_for_download_threadsr	   r   r   )r   r7   r   r   r   r%   r9   r<   r   r   r   Údownload$  s    zConcurrentDownloader.downloadc          	   C   sî   dg| }t |dƒ‚}xzt|ƒD ]n}| ¡ }t|tƒrVt d|¡ |  ¡  td| ƒ‚|\}}	}
}|
||< ||	 }| 	|¡ | 
|¡ | ¡  q W W dQ R X tt|ƒƒ}t d| jj|¡ | jj|krâ|  ¡  td| jj|f ƒ‚|  ¡  dS )a  
        Waits until the result_queue is filled with all the downloaded parts
        This indicates that all part downloads have completed

        Saves downloaded parts into filename

        :param filename:
        :param result_queue:
        :param total_parts:
        NÚwbz?An error was found in the result queue, terminating threads: %sz0An error occurred while uploading an archive: %sz?Verifying final tree hash of archive, expecting: %s, actual: %szBTree hash for entire archive does not match, expected: %s, got: %s)rV   r"   r>   r?   r@   r   r   r!   r	   ra   ÚwriteÚflushr   r   rj   Zsha256_treehashr
   )r   r7   r9   r   r8   ÚfrA   rB   rC   r   Úactual_hashÚdatare   Z
final_hashr   r   r   rm   9  s6    




z/ConcurrentDownloader._wait_for_download_threadsc             C   sN   t  d¡ x>t| jƒD ]0}t| j||ƒ}t d¡ | ¡  | j	 
|¡ qW d S )NzStarting threads.gš™™™™™É?)r   r   r"   r   ÚDownloadWorkerThreadrj   rE   rF   rG   r   rH   )r   r9   r%   rA   r    r   r   r   rl   `  s    

z,ConcurrentDownloader._start_download_threads)
r(   r)   r*   rI   r   r   rn   rm   rl   rJ   r   r   )r1   r   ri     s   
'ri   c                   s4   e Zd Zddef‡ fdd„	Zdd„ Zdd„ Z‡  ZS )ru   rS   c                s.   t t| ƒ ||¡ || _|| _|| _|| _dS )a  
        Individual download thread that will download parts of the file from Glacier. Parts
        to download stored in work queue.

        Parts download to a temp dir with each part a separate file

        :param job: Glacier job object
        :param work_queue: A queue of tuples which include the part_number and
            part_size
        :param result_queue: A priority queue of tuples which include the
            part_number and the path to the temp file that holds that
            part's data.

        N)r,   ru   r   rj   rY   rZ   r[   )r   rk   r%   r9   r\   r]   r^   )r1   r   r   r   j  s
    zDownloadWorkerThread.__init__c             C   sv   d}xlt | jƒD ]^}y|  |¡}P W q | jk
rl } z(t d|d | j¡ t | j	¡ |}W dd}~X Y qX qW |S )z‹
        Attempt to download a part of the archive from Glacier
        Store the result in the result_queue

        :param work:
        Nz6Exception caught downloading part number %s for job %sr   )
r"   rY   Ú_download_chunkr[   r   r`   rj   rE   rF   rZ   )r   rQ   rB   rA   r<   r   r   r   rP   ƒ  s    
z#DownloadWorkerThread._process_chunkc       	      C   s†   |\}}|| }||| d f}t  d||¡ | j |¡}| ¡ }ttt|ƒƒƒ}|d |krttd||d |f ƒ‚||t	 
|¡|fS )z§
        Downloads a chunk of archive from Glacier. Saves the data to a temp file
        Returns the part number and temp file location

        :param work:
        rN   zDownloading chunk %s of size %sZTreeHashzBTree hash for part number %s does not match, expected: %s, got: %s)r   r   rj   Z
get_outputrb   r   r   r   r
   ÚbinasciiZ	unhexlify)	r   rQ   rC   r   re   rg   r:   rt   rs   r   r   r   rv   –  s    
z$DownloadWorkerThread._download_chunk)r(   r)   r*   r@   r   rP   rv   rJ   r   r   )r1   r   ru   i  s
   ru   )r2   r   Z	threadingrc   rE   ZloggingZboto.compatr   rw   Zboto.glacier.utilsr   r   r   r   r   Zboto.glacier.exceptionsr   r	   r
   Úobjectr$   Z	getLoggerr   r   r+   ZThreadrK   rD   ri   ru   r   r   r   r   Ú<module>   s"   
"o4]