o
    wvXjc#  ã                   @   sø   d Z ddlmZmZ ddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ zddlZW n eyW   dZY nw edƒZdZdZG dd„ deƒZG dd„ dejƒZG dd„ dej ƒZ dS )z�Consul Transport.

It uses Consul.io's Key/Value store to transport messages in Queues

It uses python-consul for talking to Consul's HTTP API
é    )Úabsolute_importÚunicode_literalsN)Údefaultdict)Úcontextmanager)ÚChannelError)ÚEmptyÚ	monotonic)Ú
get_logger)ÚloadsÚdumps)Úcached_propertyé   )Úvirtualzkombu.transport.consuli4!  Ú	localhostc                   @   s   e Zd ZdZdS )Ú	LockErrorz3An error occurred while trying to acquire the lock.N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   úS/var/www/html/myproject/venv/lib/python3.10/site-packages/kombu/transport/consul.pyr   "   s    r   c                       sÂ   e Zd ZdZdZdZdZdZ‡ fdd„Zdd	„ Z	d
d„ Z
dd„ Zdd„ Zdd„ Zeefdd„ƒZefdd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd(d d!„Zd"d#„ Zd$d%„ Zed&d'„ ƒZ‡  ZS ))ÚChannelz?Consul Channel class which talks to the Consul Key/Value store.ÚkombuNÚ10sé   c                    sz   t d u rtdƒ‚tt| ƒj|i |¤Ž | jjjp| jj}| jjj	p"t
}t d||| j¡ ttƒ| _t j|t|ƒd�| _d S )NúMissing python-consul libraryzHost: %s Port: %s Timeout: %s©ÚhostÚport)ÚconsulÚImportErrorÚsuperr   Ú__init__Ú
connectionÚclientr   Údefault_portÚhostnameÚDEFAULT_HOSTÚloggerÚdebugÚtimeoutr   ÚdictÚqueuesÚConsulÚint)ÚselfÚargsÚkwargsr   r   ©Ú	__class__r   r   r"   .   s   
zChannel.__init__c                 C   ó   d  | j|¡S )Nz{0}/{1}.lock©ÚformatÚprefix©r/   Úqueuer   r   r   Ú	_lock_key=   ó   zChannel._lock_keyc                 C   r4   )Nz{0}/{1}r5   r8   r   r   r   Ú_key_prefix@   r;   zChannel._key_prefixc                 C   sD   z	| j | d }W n ty   d}Y nw |dur|  |¡S |  ¡ S )aƒ  Get or create consul session.

        Try to renew the session if it exists, otherwise create a new
        session in Consul.

        This session is used to acquire a lock inside Consul so that we achieve
        read-consistency between the nodes.

        Arguments:
            queue (str): The name of the Queue.

        Returns:
            str: The ID of the session.
        Ú
session_idN)r,   ÚKeyErrorÚ_renew_existing_sessionÚ_create_new_session)r/   r9   r=   r   r   r   Ú_get_or_create_sessionC   s   ÿ
ÿÿzChannel._get_or_create_sessionc                 C   s&   t  d|¡ | jjj|d�}| d¡S )Nz#Trying to renew existing session %s)r=   ÚID)r(   r)   r$   ÚsessionÚrenewÚget)r/   r=   rC   r   r   r   r?   Y   s   
zChannel._renew_existing_sessionc                 C   s<   t  d| j| j¡ | jjj| j| jd�}t  d| j|¡ |S )NzCreating session %s with TTL %s)ÚnameÚttlzCreated session %s with id %s)r(   r)   Ú	lock_nameÚsession_ttlr$   rC   Úcreate)r/   r=   r   r   r   r@   ^   s   ÿÿÿzChannel._create_new_sessionc              	   c   s4   � | j ||d� zdV  W |  |¡ dS |  |¡ w )a  Try to acquire a lock on the Queue.

        It does so by creating a object called 'lock' which is locked by the
        current session..

        This way other nodes are not able to write to the lock object which
        means that they have to wait before the lock is released.

        Arguments:
            queue (str): The name of the Queue.
            raising (Exception): Set custom lock error class.

        Raises:
            LockError: if the lock cannot be acquired.

        Returns:
            bool: success?
        ©ÚraisingN)Ú_acquire_lockÚ_release_lock)r/   r9   rL   r   r   r   Ú_queue_lockg   s
   €zChannel._queue_lockc                 C   s\   |   |¡}|  |¡}t d||¡ | jjj||| jd�r%|| j| d< d S t 	d|¡ |ƒ ‚)Nz/Trying to create lock object %s with session %s)ÚkeyÚacquireÚvaluer=   z Could not acquire lock on key %s)
rA   r:   r(   r)   r$   ÚkvÚputrH   r,   Úinfo)r/   r9   rL   r=   Úlock_keyr   r   r   rM   �   s   

ÿ
þzChannel._acquire_lockc                 C   s,   t  d|  |¡¡ | jjj|  |¡d� dS )zÓTry to release a lock.

        It does so by simply removing the lock key in Consul.

        Arguments:
            queue (str): The name of the queue we want to release
                the lock from.
        zRemoving lock key %s)rP   N)r(   r)   r:   r$   rS   Údeleter8   r   r   r   rN   �   s   	zChannel._release_lockc                 C   s2   t  d| j| d ¡ | jj | j| d ¡ dS )z®Destroy a previously created Consul session.

        Will release all locks it still might hold.

        Arguments:
            queue (str): The name of the Queue.
        zDestroying session %sr=   N)r(   r)   r,   r$   rC   Údestroyr8   r   r   r   Ú_destroy_sessionœ   s   zChannel._destroy_sessionc                 K   s&   dd i| j |< | jjj|  |¡d d�S )Nr=   )rP   rR   )r,   r$   rS   rT   r<   )r/   r9   Ú_r   r   r   Ú
_new_queue§   s   zChannel._new_queuec                 O   s&   |   |¡ | j |d ¡ |  |¡ d S ©N)rY   r,   ÚpopÚ_purge)r/   r9   r0   rZ   r   r   r   Ú_delete«   s   
zChannel._deletec                 K   sP   d  |  |¡tttƒ d ƒƒt ¡ ¡}| jjj	|t
|ƒdd�s&td  |¡ƒ‚dS )zaPut `message` onto `queue`.

        This simply writes a key to the K/V store of Consul
        z{0}/msg/{1}_{2}iè  r   )rP   rR   ÚcaszCannot add key {0!r} to consulN)r6   r<   r.   Úroundr   ÚuuidÚuuid4r$   rS   rT   r   r   )r/   r9   ÚpayloadrZ   rP   r   r   r   Ú_put°   s   ýÿzChannel._putc              	   C   sú   | j |td��k d |  |¡¡}t d|| j¡ | jjj	|d| j| j
d�\| _}z7|du r0tƒ ‚t d|d d	 |d d
 ¡ | jjj|d d	 |d d
 d� t|d d ƒW W  d  ƒ S  tyh   Y nw W d  ƒ tƒ ‚1 suw   Y  tƒ ‚)zËGet the first available message from the queue.

        Before it does so it acquires a lock on the Key/Value store so
        only one node reads at the same time. This is for read consistency
        rK   ú{0}/msg/zFetching key %s with index %sT©rP   ÚrecurseÚindexÚwaitNz#Removing key %s with modifyindex %sr   ÚKeyÚModifyIndex)rP   r`   ÚValue)rO   r   r6   r<   r(   r)   ri   r$   rS   rE   r*   rW   r
   Ú	TypeError)r/   r9   r*   rP   Údatar   r   r   Ú_get½   s4   þÿ
ÿîÿ
ìêzChannel._getc                 C   s(   |   |¡ | jjjd |  |¡¡dd�S )Nrf   T)rP   rh   )rY   r$   rS   rW   r6   r<   r8   r   r   r   r^   Û   s
   
þzChannel._purgec                 C   sz   d}z&d  |  |¡¡}t d|| j¡ | jjj|d| j| jd�\| _}t	|ƒ}W n	 t
y1   Y nw t d||| j¡ |S )Nr   rf   z)Fetching key recursively %s with index %sTrg   z$Found %s keys under %s with index %s)r6   r<   r(   r)   ri   r$   rS   rE   r*   Úlenrn   )r/   r9   ÚsizerP   ro   r   r   r   Ú_sizeâ   s$   ÿþÿÿzChannel._sizec                 C   s   d  t ¡ ¡S )Nz{0})r6   ÚsocketÚgethostname©r/   r   r   r   rH   ô   s   zChannel.lock_namer\   )r   r   r   r   r7   ri   r*   rI   r"   r:   r<   rA   r?   r@   r   r   rO   rM   rN   rY   r[   r_   re   rp   r^   rs   r   rH   Ú__classcell__r   r   r2   r   r   &   s2    	
r   c                       s@   e Zd ZdZeZeZdZdZ‡ fdd„Z	dd„ Z
dd„ Z‡  ZS )	Ú	Transportz'Consul K/V storage Transport for Kombu.r   c                    sZ   t d u rtdƒ‚tt| ƒj|i |¤Ž tjjt jt jjf | _tjj	t jt jjf | _	d S )Nr   )
r   r    r!   rx   r"   r   Úconnection_errorsÚConsulExceptionÚbaseÚchannel_errors)r/   r0   r1   r2   r   r   r"     s   
ÿÿ
ÿÿzTransport.__init__c                 C   s`   |j jp| j}|j jpt}t d||¡ ztj|t	|ƒd�}|j
 ¡  W dS  ty/   Y dS w )Nz!Verify Consul connection to %s:%sr   TF)r$   r   r%   r&   r'   r(   r)   r   r-   r.   Úagentr/   Ú
ValueError)r/   r#   r   r   r$   r   r   r   Úverify_connection  s   
ýzTransport.verify_connectionc                 C   s   t jS r\   )r   Ú__version__rv   r   r   r   Údriver_version#  s   zTransport.driver_version)r   r   r   r   r   ÚDEFAULT_PORTr%   Údriver_typeÚdriver_namer"   r   r�   rw   r   r   r2   r   rx   ù   s    rx   )!r   Ú
__future__r   r   rb   rt   Úcollectionsr   Ú
contextlibr   Úkombu.exceptionsr   Ú
kombu.fiver   r   Ú	kombu.logr	   Úkombu.utils.jsonr
   r   Úkombu.utils.objectsr   Ú r   r   r    r(   r‚   r'   Ú	Exceptionr   r   rx   r   r   r   r   Ú<module>   s0    ÿ T