U
    3dYC                     @   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   ;/tmp/pip-unpacked-wheel-d7dsrkjd/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mathceilfloat)r   
total_sizeZmin_part_size_requiredr   total_partsr   r   r   _calculate_required_part_size0   s    
 z2ConcurrentTransferer._calculate_required_part_sizec                 C   s>   t d | jD ]
}d|_q| jD ]}|  q"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   sD   t d t|D ]}|||f qt| jD ]}|t q0d 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 }
| ||| | 	||
|| z| 
||| W n@ tk
r } z"td | j| j|
 |W 5 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_uploadr0   r)   _start_upload_threads_wait_for_upload_threadsr   r   r   Zabort_multipart_uploadZcomplete_multipart_uploadr   r   )r   filenamedescriptionr   r   r   hash_chunksr'   result_queueresponse	upload_ider   r   r   uploadn   s@    

 

  

zConcurrentUploader.uploadc                 C   s\   t |D ]F}| }t|tr>td| |   td| |\}}|||< q|   d S )N?An error was found in the result queue, terminating threads: %s0An error occurred while uploading an archive: %s)r$   get
isinstance	Exceptionr   r   r#   r   )r   r<   r=   r   _resultpart_numberZtree_sha256r   r   r   r9      s    

z+ConcurrentUploader._wait_for_upload_threadsc                 C   sR   t d t| jD ]8}t| j| j||||}td |	  | j
| qd S NzStarting threads.g?)r   r   r$   r   UploadWorkerThreadr/   r0   timesleepstartr   append)r   r=   r?   r'   r:   rG   r"   r   r   r   r8      s    
  
z(ConcurrentUploader._start_upload_threads)N)
r*   r+   r,   __doc__r   r   rA   r9   r8   __classcell__r   r   r3   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.   rR   r   _worker_queue_result_queuer    )r   r'   r=   r3   r   r   r      s    zTransferThread.__init__c                 C   sj   | j r^z| jjdd}W n tk
r0   Y q Y nX |tkrF|   d S | |}| j| q |   d S )N   )timeout)	r    rS   rD   Emptyr&   _cleanup_process_chunkrT   r%   )r   workrH   r   r   r   run   s    

zTransferThread.runc                 C   s   d S r   r   )r   rZ   r   r   r   rY      s    zTransferThread._process_chunkc                 C   s   d S r   r   r   r   r   r   rX      s    zTransferThread._cleanup)r*   r+   r,   r   r[   rY   rX   rQ   r   r   r3   r   rR      s   rR   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 )
rK      c
           
         sL   t t| || || _|| _|| _t|d| _|| _|| _	|| _
|	| _d S )Nrb)r.   rK   r   r/   r0   	_filenameopen_fileobj
_upload_id_num_retries_time_between_retries_retry_exceptions)
r   r1   r2   r:   r?   r'   r=   num_retriestime_between_retriesretry_exceptionsr3   r   r   r      s    zUploadWorkerThread.__init__c                 C   s   d }t | jd D ]z}z| |}W  qW q | jk
r } z@td|d | j|d | jd | j|j| t	
| j |}W 5 d }~X Y qX q|S )NrU   zpException caught uploading part number %s for vault %s, attempt: (%s / %s), filename: %s, exception: %s, msg: %sr   )r$   rc   _upload_chunkre   r   errorr0   r_   r4   rL   rM   rd   )r   rZ   rH   r(   r@   r   r   r   rY      s$    

     z!UploadWorkerThread._process_chunkc           
      C   s   |\}}|| }| j | | j |}t| }tt|}||t| d f}t	
d|| | j| j| j|t|||}	|	  ||fS )NrU   zUploading chunk %s of size %s)ra   seekreadhashlibsha256	hexdigestr   r   lenr   r   r/   Zupload_partr0   rb   r   )
r   rZ   rI   r   
start_bytecontentsZlinear_hashZtree_hash_bytes
byte_ranger>   r   r   r   ri      s      z UploadWorkerThread._upload_chunkc                 C   s   | j   d S r   )ra   closer\   r   r   r   rX     s    zUploadWorkerThread._cleanup)	r*   r+   r,   rF   r   rY   ri   rX   rQ   r   r   r3   r   rK      s   rK   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.   ru   r   _job)r   jobr   r   r3   r   r   r     s    
zConcurrentDownloader.__init__c              
   C   s   | j j}| |\}}t }t }| ||| | || z| ||| W n2 tk
r } zt	d| |W 5 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.)
rv   Zarchive_sizer   r   r)   _start_download_threads_wait_for_download_threadsr	   r   r   )r   r:   r   r   r   r'   r=   r@   r   r   r   download$  s    zConcurrentDownloader.downloadc              	   C   s   dg| }t |d~}t|D ]n}| }t|trTtd| |   td| |\}}	}
}|
||< ||	 }|	| |
| |  qW 5 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wbrB   rC   z?Verifying final tree hash of archive, expecting: %s, actual: %szBTree hash for entire archive does not match, expected: %s, got: %s)r`   r$   rD   rE   rF   r   r   r#   r	   rk   writeflushr   r   rv   Zsha256_treehashr
   )r   r:   r=   r   r<   frG   rH   rI   r   actual_hashdatarq   Z
final_hashr   r   r   ry   9  sF    



 z/ConcurrentDownloader._wait_for_download_threadsc                 C   sJ   t d t| jD ]0}t| j||}td |  | j	
| qd S rJ   )r   r   r$   r   DownloadWorkerThreadrv   rL   rM   rN   r   rO   )r   r=   r'   rG   r"   r   r   r   rx   `  s    

z,ConcurrentDownloader._start_download_threads)
r*   r+   r,   rP   r   r   rz   ry   rx   rQ   r   r   r3   r   ru     s   
'ru   c                       s4   e Zd Zddef fdd	Zdd Zdd Z  ZS )r   r]   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.   r   r   rv   rc   rd   re   )r   rw   r'   r=   rf   rg   rh   r3   r   r   r   j  s
    zDownloadWorkerThread.__init__c                 C   sv   d}t | jD ]b}z| |}W  qrW q | jk
rn } z(td|d | j t| j	 |}W 5 d}~X Y qX q|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$   rc   _download_chunkre   r   rj   rv   rL   rM   rd   )r   rZ   rH   rG   r@   r   r   r   rY     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:
        rU   zDownloading chunk %s of size %sZTreeHashzBTree hash for part number %s does not match, expected: %s, got: %s)r   r   rv   Z
get_outputrl   r   r   r   r
   binascii	unhexlify)	r   rZ   rI   r   rq   rs   r>   r   r   r   r   r   r     s     z$DownloadWorkerThread._download_chunk)r*   r+   r,   rF   r   rY   r   rQ   r   r   r3   r   r   i  s   r   )r5   r   	threadingrm   rL   loggingZboto.compatr   r   Zboto.glacier.utilsr   r   r   r   r   Zboto.glacier.exceptionsr   r	   r
   objectr&   	getLoggerr   r   r-   ThreadrR   rK   ru   r   r   r   r   r   <module>   s"   
"o4]