U
    /ej                     @  s   d dl mZ d dl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mZ d dlmZ eeZG d	d
 d
ZG dd dZdS )    )annotationsN)defaultdict)Hashable)parse_timedelta)Client)TimeoutError
log_errors)
get_workerc                   @  sP   e Zd ZdZdd Zdddddd	d
Zdd ZedddZedddZ	dS )MultiLockExtensiona  An extension for the scheduler to manage MultiLocks

    This adds the following routes to the scheduler

    *  multi_lock_acquire
    *  multi_lock_release

    The approach is to maintain `self.locks` that maps a lock (unique name given to
    `MultiLock(names=, ...)` at creation) to a list of users (instances of `MultiLock`)
    that "requests" the lock. Additionally, `self.requests` maps a user to its requested
    locks and `self.requests_left` maps a user to the number of locks still need.

    Every time a user `x` gets to the front in `self.locks[name] = [x, ...]` it means
    that `x` now holds the lock `name` and when it holds all the requested locks
    `acquire()` can return.

    Finally, `self.events` contains all the events users are waiting on to finish.
    c                 C  s>   || _ tt| _i | _i | _i | _| j j| j	| j
d d S )N)multi_lock_acquiremulti_lock_release)	schedulerr   listlocksrequestsrequests_lefteventshandlersupdateacquirerelease)selfr    r   :/tmp/pip-unpacked-wheel-g426oqom/distributed/multi_lock.py__init__&   s    
zMultiLockExtension.__init__z	list[str]r   intbool)r   id	num_locksreturnc                   s   | j kstt| j |< t||kr0|dks4t| j|< t| fddd}t|D ]r\}} j| | t j| dkrZ j|  d8  <  j| dkrZ j |  t||d d 8  <  dS qZdS )	a  Request locks

        Parameters
        ----------
        locks: List[str]
            Names of the locks to request.
        id: Hashable
            Identifier of the `MultiLock` instance requesting the locks.
        num_locks: int
            Number of locks in `locks` requesting

        Return
        ------
        result: bool
            Whether `num_locks` requested locks are free immediately or not.
        r   c                   s   t  j|  S N)lenr   )xr   r   r   <lambda>G       z3MultiLockExtension._request_locks.<locals>.<lambda>)key   NTF)	r   AssertionErrorsetr!   r   sorted	enumerater   append)r   r   r   r   ilockr   r#   r   _request_locks1   s    
"z!MultiLockExtension._request_locksc                 C  s   t  }|D ]}| j| d |kr~| j| d | j| r| j| d }| j|  d8  < | j| dkrd| j|< || n| j| | || j| ks
tq
| j|= | j|= |D ]}| jj	
| j| j  qdS )a  Cancel/release previously requested/acquired locks

        Parameters
        ----------
        locks: List[str]
            Names of the locks to refain.
        id: Hashable
            Identifier of the `MultiLock` instance refraining the locks.
        r   r'   N)r)   r   popr   addremover(   r   r   ZloopZadd_callbackr   )r   r   r   Zwaiters_readyr.   Z	new_firstwaiterr   r   r   _refain_locksR   s     


z MultiLockExtension._refain_locksNc                   s   |  |||s|| jkstt }|| j|< | }|d k	rJt||}z:z|I d H  W n& tk
r   | || Y W 
dS X W 5 | j|= X | j	| dkstdS )NFr   T)
r/   r   r(   asyncioEventwaitwait_forr   r4   r   )r   r   r   timeoutr   eventfuturer   r   r   r   q   s    

zMultiLockExtension.acquirec                 C  s   |  | j| | d S r    )r4   r   )r   r   r   r   r   r      s    zMultiLockExtension.release)NNNN)N)
__name__
__module____qualname____doc__r   r/   r4   r   r   r   r   r   r   r   r
      s   !r
   c                   @  sd   e Zd ZdZddddddZ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 )	MultiLocka3  Distributed Centralized Lock

    Parameters
    ----------
    names
        Names of the locks to acquire. Choosing the same name allows two
        disconnected processes to coordinate a lock.
    client
        Client to use for communication with the scheduler.  If not given, the
        default global client will be used.

    Examples
    --------
    >>> lock = MultiLock(['x', 'y'])  # doctest: +SKIP
    >>> lock.acquire(timeout=1)  # doctest: +SKIP
    >>> # do things with protected resource 'x' and 'y'
    >>> lock.release()  # doctest: +SKIP
    Nzlist[str] | NonezClient | None)namesclientc                 C  sR   z|pt  | _W n tk
r0   t j| _Y nX |p8g | _t j| _	d| _
d S )NF)r   currentrB   
ValueErrorr	   rA   uuidZuuid4hexr   _locked)r   rA   rB   r   r   r   r      s    
zMultiLock.__init__Tc                 C  sT   t |}|s |dk	rtdd}| jj| jjj| j| j||pDt| jd}d| _	|S )a  Acquire the lock

        Parameters
        ----------
        blocking : bool, optional
            If false, don't wait on the lock in the scheduler at all.
        timeout : string or number or timedelta, optional
            Seconds to wait on the lock in the scheduler.  This does not
            include local coroutine time, network transfer time, etc..
            It is forbidden to specify a timeout when blocking is false.
            Instead of number of seconds, it is also possible to specify
            a timedelta in string format, e.g. "200ms".
        num_locks : int, optional
            Number of locks needed. If None, all locks are needed

        Examples
        --------
        >>> lock = MultiLock(['x', 'y'])  # doctest: +SKIP
        >>> lock.acquire(timeout="1s")  # doctest: +SKIP

        Returns
        -------
        True or False whether or not it successfully acquired the lock
        Nz/can't specify a timeout for a non-blocking callr   )r   r   r9   r   T)
r   rD   rB   syncr   r   rA   r   r!   rG   )r   blockingr9   r   resultr   r   r   r      s    zMultiLock.acquirec                 C  s2   |   std| jj| jjj| jd}d| _|S )z$Release the lock if already acquiredzLock is not yet acquired)r   F)lockedrD   rB   rH   r   r   r   rG   )r   retr   r   r   r      s
    zMultiLock.releasec                 C  s   | j S r    )rG   r#   r   r   r   rK      s    zMultiLock.lockedc                 C  s   |    | S r    r   r#   r   r   r   	__enter__   s    zMultiLock.__enter__c                 C  s   |    d S r    r   r   exc_type	exc_value	tracebackr   r   r   __exit__   s    zMultiLock.__exit__c                   s   |   I d H  | S r    rM   r#   r   r   r   
__aenter__   s    zMultiLock.__aenter__c                   s   |   I d H  d S r    rO   rP   r   r   r   	__aexit__   s    zMultiLock.__aexit__c                 C  s   t | | jffS r    )typerA   r#   r   r   r   
__reduce__   s    zMultiLock.__reduce__)NN)TNN)r<   r=   r>   r?   r   r   r   rK   rN   rT   rU   rV   rX   r   r   r   r   r@      s   
*r@   )
__future__r   r5   loggingrE   collectionsr   collections.abcr   Z
dask.utilsr   Zdistributed.clientr   Zdistributed.utilsr   r   Zdistributed.workerr	   	getLoggerr<   loggerr
   r@   r   r   r   r   <module>   s   
x