a
    &ñ»j»=  ã                   @   s  d dl m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	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 e e¡Zd
d„ ZG dd„ dƒZG dd„ dƒZeeef dœdd„Zeeef dœdd„Zeeef dœdd„ZdS )é    )ÚcontextmanagerN)ÚPath)ÚCallable)ÚOptional)ÚUnion)Ú_utils)Ú_interprocess_mechanism)Ú%_interprocess_reader_writer_mechanismc              
   C   s„   zt  | ¡ W nl tyz } zT|jtjkrJt j | ¡s:‚ qfW Y d}~dS n|jtjkrdW Y d}~dS ‚ W Y d}~nd}~0 0 dS dS )zfCreate a directory (and any ancestor directories required).

    :param path: Directory to create
    NFT)ÚosÚmakedirsÚOSErrorÚerrnoÚEEXISTÚpathÚisdirZEISDIR)r   Úe© r   ú<E:\soccer\ml_env\Lib\site-packages\fasteners/process_lock.pyÚ_ensure_tree%   s    r   c                   @   s®   e Zd ZdZdZdZejdfee	e
f eegdf eej dœdd„Zdd	„ Zd
d„ Zdeeeee edœdd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚInterProcessLockzAn interprocess lock.çš™™™™™¹?ç{®Gáz„?N©r   Ú
sleep_funcÚloggerc                 C   s0   d| _ t |¡| _d| _|| _t |t¡| _dS )a   
        args:
            path:
                Path to the file that will be used for locking.
            sleep_func:
                Optional function to use for sleeping.
            logger:
                Optional logger to use for logging.
        NF)	Úlockfiler   Úcanonicalize_pathr   Úacquiredr   Úpick_first_not_noneÚLOGr   ©Úselfr   r   r   r   r   r   Ú__init__@   s
    zInterProcessLock.__init__c              
   C   sŠ   z|   ¡  W nt ttfy€ } zX|jtjtjfv rV|r>| ¡ rLW Y d }~dS t ¡ ‚nt	 
d| j|dœ ¡‚W Y d }~nd }~0 0 dS d S )NFz9Unable to acquire lock on `%(path)s` due to %(exception)s)r   Ú	exceptionT)ÚtrylockÚIOErrorr   r   ÚEACCESÚEAGAINÚexpiredr   Ú
RetryAgainÚ	threadingÚThreadErrorr   )r!   ÚblockingÚwatchr   r   r   r   Ú_try_acquireS   s    
þýzInterProcessLock._try_acquirec                 C   sT   t j | j¡}|r0t|ƒ}|r0| j tjd|¡ | jd u sB| jj	rPt
| jdƒ| _d S )NúCreated lock base path `%s`Úa)r
   r   Údirnamer   r   Úlogr   ÚBLATHERr   ÚclosedÚopen©r!   ZbasedirZmade_basedirr   r   r   Ú_do_openg   s    
ÿzInterProcessLock._do_openT©r,   ÚdelayÚ	max_delayÚtimeoutÚreturnc                 C   sÂ   |dk rt dƒ‚|dur(|dk r(t dƒ‚||kr4|}|  ¡  tj|d�}tj||| j|d�}|� || j||ƒ}W d  ƒ n1 s„0    Y  |s–dS d| _| j 	tj
d	| j| ¡ |j¡ dS dS )
a,  Attempt to acquire the lock.

        Args:
            blocking:
                Whether to wait to try to acquire the lock.
            delay:
                When `blocking`, starting delay as well as the delay increment
                (in seconds).
            max_delay:
                When `blocking` the maximum delay in between attempts to
                acquire (in seconds).
            timeout:
                When `blocking`, maximal waiting time (in seconds).

        Returns:
            whether or not the acquisition succeeded
        r   ú+Delay must be greater than or equal to zeroNú-Timeout must be greater than or equal to zero©Úduration©r   r-   FTúHAcquired file lock `%s` after waiting %0.3fs [%s attempts were required])Ú
ValueErrorr7   r   Ú	StopWatchÚRetryr   r.   r   r   r2   r3   r   ÚelapsedÚattempts)r!   r,   r9   r:   r;   r-   ÚrÚgottenr   r   r   Úacquiret   s,    ÿ,

ýzInterProcessLock.acquirec                 C   s   | j d ur| j  ¡  d | _ d S ©N)r   Úclose©r!   r   r   r   Ú	_do_close    s    

zInterProcessLock._do_closec                 C   s    |   ¡ }|st d| j ¡‚| S )NúFUnable to acquire a file lock on `%s` (when used as a context manager))rJ   r*   r+   r   )r!   rI   r   r   r   Ú	__enter__¥   s    þzInterProcessLock.__enter__c              
   C   s²   | j st d¡‚z|  ¡  W nF tyb } z.d| jf}| j |¡ t |¡|‚W Y d}~nTd}~0 0 d| _ z|  ¡  W n" t	y˜   | j d| j¡ Y n0 | j 
tjd| j¡ dS )z%Release the previously acquired lock.z#Unable to release an unaquired lockú1Could not unlock the acquired lock opened on `%s`NFú.Could not close the file handle opened on `%s`ú*Unlocked and closed file lock open on `%s`)r   r*   r+   ÚunlockÚ	Exceptionr   r   r#   rN   r%   r2   r   r3   )r!   r   Úmsgr   r   r   Úrelease®   s&    

"ÿ

þzInterProcessLock.releasec                 C   s   |   ¡  d S rK   )rW   )r!   Úexc_typeÚexc_valÚexc_tbr   r   r   Ú__exit__Ä   s    zInterProcessLock.__exit__c                 C   s   t j | j¡S rK   )r
   r   ÚexistsrM   r   r   r   r\   Ç   s    zInterProcessLock.existsc                 C   s   t  | j¡ d S rK   )r   r$   r   rM   r   r   r   r$   Ê   s    zInterProcessLock.trylockc                 C   s   t  | j¡ d S rK   )r   rT   r   rM   r   r   r   rT   Í   s    zInterProcessLock.unlock)Tr   r   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	MAX_DELAYÚDELAY_INCREMENTÚtimeÚsleepr   r   Ústrr   Úfloatr   ÚloggingÚLoggerr"   r.   r7   ÚboolrJ   rN   rP   rW   r[   r\   r$   rT   r   r   r   r   r   :   s:   ý
ý    üü,	r   c                   @   sÈ   e Zd ZdZdZdZejdfee	e
f eegdf eej dœdd„Zeddd	„ƒZedd
d„ƒZdd„ Zdd„ Zd eeeeedœdd„Zd!eeeeedœdd„Zd"dd„Zdd„ Zdd„ Zdd„ ZdS )#ÚInterProcessReaderWriterLockz$An interprocess readers writer lock.r   r   Nr   c                 C   s*   d| _ t |¡| _|| _t |t¡| _dS )a   
        Args:
            path:
                Path to the file that will be used for locking.
            sleep_func:
                Optional function to use for sleeping.
            logger:
                Optional logger to use for logging.
        N)r   r   r   r   r   r   r   r   r    r   r   r   r"   ×   s    z%InterProcessReaderWriterLock.__init__c                 c   s4   | j d||dd� zdV  W |  ¡  n
|  ¡  0 dS )z&Context manager that grans a read lockTN©r,   r9   r:   r;   )Úacquire_read_lockÚrelease_read_lock)r!   r9   r:   r   r   r   Ú	read_locké   s    ÿz&InterProcessReaderWriterLock.read_lockc                 c   sH   | j d||dd�}|s&t d| j ¡‚zdV  W |  ¡  n
|  ¡  0 dS )z'Context manager that grans a write lockTNrk   rO   )Úacquire_write_lockr*   r+   r   Úrelease_write_lock)r!   r9   r:   rI   r   r   r   Ú
write_lockô   s    ÿþz'InterProcessReaderWriterLock.write_lockc              
   C   sp   zt  | j|¡}W n8 tyJ } z t d | j|¡¡‚W Y d }~n
d }~0 0 |rTdS |r`| ¡ rddS t	 
¡ ‚d S )Nz'Unable to acquire lock on {} due to {}!TF)r	   r$   r   rU   r*   r+   Úformatr   r(   r   r)   )r!   r,   r-   Ú	exclusiverI   r   r   r   r   r.     s    ÿz)InterProcessReaderWriterLock._try_acquirec                 C   sL   t j | j¡}|r0t|ƒ}|r0| j tjd|¡ | jd u rHt	 
| j¡| _d S )Nr/   )r
   r   r1   r   r   r2   r   r3   r   r	   Z
get_handler6   r   r   r   r7     s    
ÿ
z%InterProcessReaderWriterLock._do_openTr8   c                 C   s   | j ||||dd�S )a3  Attempt to acquire a reader's lock.

        Args:
            blocking:
                Whether to wait to try to acquire the lock.
            delay:
                When `blocking`, starting delay as well as the delay increment
                (in seconds).
            max_delay:
                When `blocking` the maximum delay in between attempts to
                acquire (in seconds).
            timeout:
                When `blocking`, maximal waiting time (in seconds).

        Returns:
            whether or not the acquisition succeeded
        F©rs   ©Ú_acquire©r!   r,   r9   r:   r;   r   r   r   rl     s    z.InterProcessReaderWriterLock.acquire_read_lockc                 C   s   | j ||||dd�S )a3  Attempt to acquire a writer's lock.

        Args:
            blocking:
                Whether to wait to try to acquire the lock.
            delay:
                When `blocking`, starting delay as well as the delay increment
                (in seconds).
            max_delay:
                When `blocking` the maximum delay in between attempts to
                acquire (in seconds).
            timeout:
                When `blocking`, maximal waiting time (in seconds).

        Returns:
            whether or not the acquisition succeeded
        Trt   ru   rw   r   r   r   ro   6  s    z/InterProcessReaderWriterLock.acquire_write_lockc           	      C   s¾   |dk rt dƒ‚|d ur(|dk r(t dƒ‚||kr4|}|  ¡  tj|d�}tj||| j|d�}|�  || j|||ƒ}W d   ƒ n1 s†0    Y  |s˜dS | j tj	d| j
| ¡ |j¡ dS d S )	Nr   r=   r>   r?   rA   FrB   T)rC   r7   r   rD   rE   r   r.   r   r2   r3   r   rF   rG   )	r!   r,   r9   r:   r;   rs   r-   rH   rI   r   r   r   rv   N  s*    ÿ.

ýz%InterProcessReaderWriterLock._acquirec                 C   s    | j d urt | j ¡ d | _ d S rK   )r   r	   Úclose_handlerM   r   r   r   rN   g  s    
z&InterProcessReaderWriterLock._do_closec                 C   s|   zt  | j¡ W n" ty2   | j d| j¡ Y nF0 z|  ¡  W n" tyb   | j d| j¡ Y n0 | j t	j
d| j¡ dS )zRelease the writer's lock.rQ   rR   rS   N©r	   rT   r   r%   r   r#   r   rN   r2   r   r3   rM   r   r   r   rp   l  s     ÿ
ÿ

þz/InterProcessReaderWriterLock.release_write_lockc                 C   s|   zt  | j¡ W n" ty2   | j d| j¡ Y nF0 z|  ¡  W n" tyb   | j d| j¡ Y n0 | j t	j
d| j¡ dS )zRelease the reader's lock.rQ   rR   rS   Nry   rM   r   r   r   rm   ~  s     ÿ
ÿ

þz.InterProcessReaderWriterLock.release_read_lock)r   r   )r   r   )Tr   r   N)Tr   r   N)Tr   r   NT)r]   r^   r_   r`   ra   rb   rc   rd   r   r   re   r   rf   r   rg   rh   r"   r   rn   rq   r.   r7   ri   rl   ro   rv   rN   rp   rm   r   r   r   r   rj   Ñ   sV   ý
ý
    üü    üü   þ
rj   )r   c                    s   t | ƒ‰ ‡ fdd„}|S )z¤Acquires & releases an interprocess  **write** lock around the call into
    the decorated function

    Args:
        path: Path to the file used for locking.
    c                    s   t  ˆ ¡‡ ‡fdd„ƒ}|S )Nc                     s:   ˆ  ¡ � ˆ | i |¤ŽW  d   ƒ S 1 s,0    Y  d S rK   )rq   ©ÚargsÚkwargs©ÚfÚlockr   r   Úwrapper›  s    
z=interprocess_write_locked.<locals>.decorator.<locals>.wrapper©Ú	functoolsÚwraps©r~   r€   ©r   ©r~   r   Ú	decoratorš  s    z,interprocess_write_locked.<locals>.decorator©rj   ©r   r‡   r   r…   r   Úinterprocess_write_locked‘  s    rŠ   c                    s   t | ƒ‰ ‡ fdd„}|S )z¢Acquires & releases an interprocess **read** lock around the call into
    the decorated function

    Args:
        path: Path to the file used for locking.
    c                    s   t  ˆ ¡‡ ‡fdd„ƒ}|S )Nc                     s:   ˆ  ¡ � ˆ | i |¤ŽW  d   ƒ S 1 s,0    Y  d S rK   )rn   rz   r}   r   r   r€   ¯  s    
z<interprocess_read_locked.<locals>.decorator.<locals>.wrapperr�   r„   r…   r†   r   r‡   ®  s    z+interprocess_read_locked.<locals>.decoratorrˆ   r‰   r   r…   r   Úinterprocess_read_locked¥  s    r‹   c                    s   t | ƒ‰ ‡ fdd„}|S )z—Acquires & releases an interprocess lock around the call to the
    decorated function.

    Args:
        path: Path to the file used for locking.
   c                    s   t  ˆ ¡‡ ‡fdd„ƒ}|S )Nc                     s6   ˆ� ˆ | i |¤ŽW  d   ƒ S 1 s(0    Y  d S rK   r   rz   r}   r   r   r€   Ã  s    z7interprocess_locked.<locals>.decorator.<locals>.wrapperr�   r„   r…   r†   r   r‡   Â  s    z&interprocess_locked.<locals>.decorator)r   r‰   r   r…   r   Úinterprocess_locked¹  s    rŒ   )Ú
contextlibr   r   r‚   rg   r
   Úpathlibr   r*   rc   Útypingr   r   r   Z	fastenersr   Zfasteners.process_mechanismr   r	   Ú	getLoggerr]   r   r   r   rj   re   rŠ   r‹   rŒ   r   r   r   r   Ú<module>   s,   
  A