
    ^f$                    B   d Z ddl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 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 	 ddlZn# e$ r dZY nw xY w ed          ZdZdZ G d de          Z G d dej                  Z G d dej                   Z dS )a  Consul Transport module for Kombu.

Features
========

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

It uses python-consul for talking to Consul's HTTP API

Features
========
* Type: Native
* Supports Direct: Yes
* Supports Topic: *Unreviewed*
* Supports Fanout: *Unreviewed*
* Supports Priority: *Unreviewed*
* Supports TTL: *Unreviewed*

Connection String
=================

Connection string has the following format:

.. code-block::

    consul://CONSUL_ADDRESS[:PORT]

    )annotationsN)defaultdict)contextmanager)Empty)	monotonic)ChannelError)
get_logger)dumpsloads)cached_property   )virtualzkombu.transport.consuli4!  	localhostc                      e Zd ZdZdS )	LockErrorz3An error occurred while trying to acquire the lock.N)__name__
__module____qualname____doc__     H/var/www/html/env/lib/python3.11/site-packages/kombu/transport/consul.pyr   r   9   s        ====r   r   c                       e Zd ZdZdZdZdZdZ fdZd Z	d Z
d	 Zd
 Zd Zeefd            ZefdZd Zd Zd Zd Zd ZddZd Zd Zed             Z xZS )Channelz?Consul Channel class which talks to the Consul Key/Value store.kombuN10s   c                   t           t          d           t                      j        |i | | j        j        j        p| j        j        }| j        j        j        pt          }t                              d||| j                   t          t                    | _        t          j        |t#          |                    | _        d S )NMissing python-consul libraryzHost: %s Port: %s Timeout: %shostport)consulImportErrorsuper__init__
connectionclientr"   default_porthostnameDEFAULT_HOSTloggerdebugtimeoutr   dictqueuesConsulint)selfargskwargsr"   r!   	__class__s        r   r&   zChannel.__init__E   s    >=>>>$)&)))%*Jdo.J%.>,4dD$,OOO!$''mCII>>>r   c                    | j          d| dS )N/z.lockprefixr3   queues     r   	_lock_keyzChannel._lock_keyT   s    +,,,,,,r   c                    | j          d| S )Nr8   r9   r;   s     r   _key_prefixzChannel._key_prefixW   s    +'''''r   c                    	 | j         |         d         }n# t          $ r d}Y nw xY w||                     |          n|                                 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)r0   KeyError_renew_existing_session_create_new_session)r3   r<   rA   s      r   _get_or_create_sessionzChannel._get_or_create_sessionZ   sq    "	U+L9JJ 	 	 	JJJ	 ) ,,Z888/3/G/G/I/I	Ks    %%c                    t                               d|           | j        j                            |          }|                    d          S )Nz#Trying to renew existing session %s)rA   ID)r,   r-   r(   sessionrenewget)r3   rA   rH   s      r   rC   zChannel._renew_existing_sessionr   sD    :JGGG+%++z+BB{{4   r   c                    t                               d| j        | j                   | j        j                            | j        | j                  }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(   rH   create)r3   rA   s     r   rD   zChannel._create_new_sessionw   st    6^T%5	7 	7 	7[(//T%5 0 7 7
4^Z	1 	1 	1r   c              #     K   |                      ||           	 dV  |                     |           dS # |                     |           w xY w)aI  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)r3   r<   rS   s      r   _queue_lockzChannel._queue_lock   sc      . 	5'222	&EEEu%%%%%Du%%%%s	   6 Ac                J   |                      |          }|                     |          }t                              d||           | j        j                            ||| j                  r|| j        |         d<   d S t          	                    d|            |            )Nz/Trying to create lock object %s with session %s)keyacquirevaluerA   z Could not acquire lock on key %s)
rE   r=   r,   r-   r(   kvputrN   r0   info)r3   r<   rS   rA   lock_keys        r   rT   zChannel._acquire_lock   s    0077
>>%((Fz	+ 	+ 	+ ;>(&0$(N  4 4 	 0:DK|,F6AAAgiir   c                    t                               d|                     |                     | j        j                            |                     |                     dS )zTry 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)rX   N)r,   r-   r=   r(   r[   deleter;   s     r   rU   zChannel._release_lock   sR     	+T^^E-B-BCCC$.."7"788888r   c                    t                               d| j        |         d                    | j        j                            | j        |         d                    dS )zDestroy a previously created Consul session.

        Will release all locks it still might hold.

        Arguments:
        ---------
            queue (str): The name of the Queue.
        zDestroying session %srA   N)r,   r-   r0   r(   rH   destroyr;   s     r   _destroy_sessionzChannel._destroy_session   sP     	,dk%.@.NOOO##DK$6|$DEEEEEr   c                    dd i| j         |<   | j        j                            |                     |          d           S )NrA   )rX   rZ   )r0   r(   r[   r\   r?   )r3   r<   _s      r   
_new_queuezChannel._new_queue   s>    *D1E{~!!d&6&6u&=&=T!JJJr   c                    |                      |           | j                            |d            |                     |           d S N)rc   r0   pop_purge)r3   r<   r4   re   s       r   _deletezChannel._delete   sD    e$$$t$$$Er   c           	     R   d                     |                     |          t          t          t	                      dz                      t          j                              }| j        j        	                    |t          |          d          st          d|d          dS )zaPut `message` onto `queue`.

        This simply writes a key to the K/V store of Consul
        z{}/msg/{}_{}i  r   )rX   rZ   caszCannot add key z
 to consulN)formatr?   r2   roundr   uuiduuid4r(   r[   r\   r
   r   )r3   r<   payloadre   rX   s        r   _putzChannel._put   s    
 ##U##ikkD())**JLL
 

 {~!!cwQ!GG 	DBBBBCCC	D 	Dr   c                   |                      |t                    5  |                     |           d}t                              d|| j                   | j        j                            |d| j        | j	                  \  | _        }	 |t                      t                              d|d         d	         |d         d
                    | j        j        
                    |d         d	         |d         d
                    t          |d         d                   cddd           S # t          $ r Y nw xY w	 ddd           n# 1 swxY w Y   t                      )zGet 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
        rR   /msg/zFetching key %s with index %sTrX   recurseindexwaitNz#Removing key %s with modifyindex %sr   KeyModifyIndex)rX   rm   Value)rV   r   r?   r,   r-   rx   r(   r[   rJ   r.   r`   r   	TypeError)r3   r<   r.   rX   datas        r   _getzChannel._get   s    eU33 	 	%%e,,333CLL8#tzJJJ#{~11jt|  2    DJ
<''MB!!WU^T!W]-CE E E %%$q'%.*.q'-*@ & B B B T!WW-..%	 	 	 	 	 	 	 	&    )	 	 	 	 	 	 	 	 	 	 	 	 	 	 	, ggs1   A/EBD11
D>;E=D>>EEEc                    |                      |           | j        j                            |                     |           dd          S )Nru   T)rX   rw   )rc   r(   r[   r`   r?   r;   s     r   rj   zChannel._purge   sT    e$$${~$$##E**111 % 
 
 	
r   c                l   d}	 |                      |           d}t                              d|| j                   | j        j                            |d| j        | j                  \  | _        }t          |          }n# t          $ r Y nw xY wt                              d||| j                   |S )Nr   ru   z)Fetching key recursively %s with index %sTrv   z$Found %s keys under %s with index %s)
r?   r,   r-   rx   r(   r[   rJ   r.   lenr}   )r3   r<   sizerX   r~   s        r   _sizezChannel._size   s    
	%%e,,333CLLDdj* * *#{~11jt|  2    DJ t99DD 	 	 	D	 	;3
	, 	, 	,s   A=B 
BBc                *    t          j                     S rh   )socketgethostnamer3   s    r   rN   zChannel.lock_name  s    $&&((r   rh   )r   r   r   r   r:   rx   r.   rO   r&   r=   r?   rE   rC   rD   r   r   rV   rT   rU   rc   rf   rk   rs   r   rj   r   r   rN   __classcell__r6   s   @r   r   r   =   s}       IIFEGK? ? ? ? ?- - -( ( (K K K0! ! !
   )2 & & & ^&8 ,5    9 9 9
F 
F 
FK K K  
D D D   <
 
 
  $ ) ) _) ) ) ) )r   r   c                       e Zd ZdZeZeZdZdZe	r@e
j        j        e	j        e	j        j        fz   Ze
j        j        e	j        e	j        j        fz   Z fdZd Zd Z xZS )	Transportz'Consul K/V storage Transport for Kombu.r#   c                f    t           t          d           t                      j        |i | d S )Nr   )r#   r$   r%   r&   )r3   r4   r5   r6   s      r   r&   zTransport.__init__-  s9    >=>>>$)&)))))r   c                (   |j         j        p| j        }|j         j        pt          }t
                              d||           	 t          j        |t          |                    }|j
                                         dS # t          $ r Y nw xY wdS )Nz!Verify Consul connection to %s:%sr    TF)r(   r"   r)   r*   r+   r,   r-   r#   r1   r2   agentr3   
ValueError)r3   r'   r"   r!   r(   s        r   verify_connectionzTransport.verify_connection3  s     %:): )9\8$EEE	]3t99===FL4 	 	 	D	 us   <B 
BBc                    t           j        S rh   )r#   __version__r   s    r   driver_versionzTransport.driver_versionB  s    !!r   )r   r   r   r   r   DEFAULT_PORTr)   driver_typedriver_namer#   r   r   connection_errorsConsulExceptionbasechannel_errorsr&   r   r   r   r   s   @r   r   r     s        11GLKK 
/&(C3  	 ,&(C0  	* * * * *  " " " " " " "r   r   )!r   
__future__r   r   rp   collectionsr   
contextlibr   r<   r   timer   kombu.exceptionsr   	kombu.logr	   kombu.utils.jsonr
   r   kombu.utils.objectsr    r   r#   r$   r,   r   r+   	Exceptionr   r   r   r   r   r   <module>r      s   : # " " " " "   # # # # # # % % % % % %             ) ) ) ) ) )             ) ) ) ) ) ) ) ) / / / / / /      MMMM   FFF 
,	-	-> > > > >	 > > >W) W) W) W) W)go W) W) W)t," ," ," ," ,"! ," ," ," ," ,"s   
A AA