U
    q[                     @   s  d Z ddlmZmZ ddlZddlmZmZ ddlZddl	Z	ddl
mZmZmZ ddlZddlmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZmZmZ ddl m!Z"m#Z$m%Z& dd	l'm(Z(m)Z)m*Z* dd
l+m,Z,m-Z- ddl.m/Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl'm7Z7 eee6G dd dZ8eeG dd de9Z:eee6G dd dZ;G dd de9Z<eeeeeeG dd de9Z=e1> ree=e eee6G dd dZ?G dd dej@ZAG dd de9ZBg ZCdS )z8
Very basic functionality for a Reactor implementation.
    )divisionabsolute_importN)implementerclassImplements)heappushheappopheapify)	IReactorCoreIReactorTimeIReactorThreadsIResolverSimpleIReactorPluggableResolverIReactorPluggableNameResolver
IConnectorIDelayedCall_ISupportsExitSignalCapturing)fdescmainerrorabstractdeferthreads)GAIResolverComplexResolverSimplifierSimpleResolverComplexifier)logfailurereflect)unicode	iteritems)secondsplatform)DeferredDeferredList)	_oldStyle)
threadablec                   @   sh   e Zd ZdZdZef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d Zdd ZdS )DelayedCallFNc                 C   s\   ||||f\| _ | _| _| _|| _|| _|| _d | _| _d| _	| j
rXt dd | _dS )aR  
        @param time: Seconds from the epoch at which to call C{func}.
        @param func: The callable to call.
        @param args: The positional arguments to pass to the callable.
        @param kw: The keyword arguments to pass to the callable.
        @param cancel: A callable which will be called with this
            DelayedCall before cancellation.
        @param reset: A callable which will be called with this
            DelayedCall after changing this DelayedCall's scheduled
            execution time. The callable should adjust any necessary
            scheduling details to ensure this DelayedCall is invoked
            at the new appropriate time.
        @param seconds: If provided, a no-argument callable which will be
            used to determine the current time any time that information is
            needed.
        r   N)timefuncargskwresetter	cancellerr    	cancelledcalleddelayed_timedebug	tracebackformat_stackcreator)selfr(   r)   r*   r+   cancelresetr     r8   7/usr/lib/python3/dist-packages/twisted/internet/base.py__init__4   s    zDelayedCall.__init__c                 C   s   | j | j S )zReturn the time at which this call will fire

        @rtype: C{float}
        @return: The number of seconds after the epoch at which this call is
        scheduled to be made.
        r(   r0   r5   r8   r8   r9   getTimeO   s    zDelayedCall.getTimec                 C   sL   | j rtjn:| jrtjn,| |  d| _ | jr<t| | _| `	| `
| `dS )zUnschedule this call

        @raise AlreadyCancelled: Raised if this call has already been
        unscheduled.

        @raise AlreadyCalled: Raised if this call has already been made.
           N)r.   r   AlreadyCancelledr/   AlreadyCalledr-   r1   repr_reprr)   r*   r+   r<   r8   r8   r9   r6   X   s    

zDelayedCall.cancelc                 C   sZ   | j rtjnH| jrtjn:|  | }|| jk rJd| _|| _| |  n|| j | _dS )as  Reschedule this call for a different time

        @type secondsFromNow: C{float}
        @param secondsFromNow: The number of seconds from the time of the
        C{reset} call at which this call will be scheduled.

        @raise AlreadyCancelled: Raised if this call has been cancelled.
        @raise AlreadyCalled: Raised if this call has already been made.
        r   N)	r.   r   r?   r/   r@   r    r(   r0   r,   )r5   ZsecondsFromNowZnewTimer8   r8   r9   r7   k   s    

zDelayedCall.resetc                 C   sJ   | j rtjn8| jrtjn*|  j|7  _| jdk rF|   | |  dS )ai  Reschedule this call for a later time

        @type secondsLater: C{float}
        @param secondsLater: The number of seconds after the originally
        scheduled time for which to reschedule this call.

        @raise AlreadyCancelled: Raised if this call has been cancelled.
        @raise AlreadyCalled: Raised if this call has already been made.
        r   N)r.   r   r?   r/   r@   r0   activate_delayr,   )r5   ZsecondsLaterr8   r8   r9   delay   s    

zDelayedCall.delayc                 C   s   |  j | j7  _ d| _d S Nr   r;   r<   r8   r8   r9   rC      s    zDelayedCall.activate_delayc                 C   s   | j p
| j S )zDetermine whether this call is still pending

        @rtype: C{bool}
        @return: True if this call has not yet been made or cancelled,
        False otherwise.
        )r.   r/   r<   r8   r8   r9   active   s    zDelayedCall.activec                 C   s   | j |j kS )z
        Implement C{<=} operator between two L{DelayedCall} instances.

        Comparison is based on the C{time} attribute (unadjusted by the
        delayed time).
        r(   r5   otherr8   r8   r9   __le__   s    zDelayedCall.__le__c                 C   s   | j |j k S )z
        Implement C{<} operator between two L{DelayedCall} instances.

        Comparison is based on the C{time} attribute (unadjusted by the
        delayed time).
        rG   rH   r8   r8   r9   __lt__   s    zDelayedCall.__lt__c                 C   sN  | j dk	r| j S t| drrt| jdr0| jj}qvt| jdrd| jj}t| jdrp| jjjd | }qvt| j}nd}| 	 }dt
| | j| | j| jf g}|dk	r|d|d	f | jr|d
dd | jD  | jr|d
 | jr|d
dd | j D  |d | jr:|dd| j  |d d|S )z
        Implement C{repr()} for L{DelayedCall} instances.

        @rtype: C{str}
        @returns: String containing details of the L{DelayedCall}.
        Nr)   __qualname____name__im_class.z.<DelayedCall 0x%x [%ss] called=%s cancelled=%s (z, c                 S   s   g | ]}t |qS r8   r   	safe_repr).0er8   r8   r9   
<listcomp>   s     z(DelayedCall.__repr__.<locals>.<listcomp>c                 S   s"   g | ]\}}d |t |f qS )z%s=%srR   )rT   kvr8   r8   r9   rV      s     )z

traceback at creation: 

%sz    > )rB   hasattrr)   rL   Z	func_namerN   rM   r   rS   r    idr(   r/   r.   extendr*   appendjoinr+   itemsr1   r4   )r5   r)   nowLr8   r8   r9   __repr__   s>    


  

 

zDelayedCall.__repr__)rM   
__module__rL   r1   rB   runtimeSecondsr:   r=   r6   r7   rD   rC   rF   rJ   rK   rd   r8   r8   r8   r9   r&   +   s   
	


r&   c                   @   s:   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdS )ThreadedResolvera  
    L{ThreadedResolver} uses a reactor, a threadpool, and
    L{socket.gethostbyname} to perform name lookups without blocking the
    reactor thread.  It also supports timeouts indepedently from whatever
    timeout logic L{socket.gethostbyname} might have.

    @ivar reactor: The reactor the threadpool of which will be used to call
        L{socket.gethostbyname} and the I/O thread of which the result will be
        delivered.
    c                 C   s   || _ i | _d S N)reactor_runningQueries)r5   ri   r8   r8   r9   r:      s    zThreadedResolver.__init__c                 C   s   t d||f }t|S )Nzaddress %r not found: %s)r   DNSLookupErrorr   Failure)r5   nameerrr8   r8   r9   _fail   s    zThreadedResolver._failc                 C   s,   | j | \}}| j |= || |d d S )Nztimeout error)rj   errbackro   )r5   rm   lookupDeferreduserDeferred
cancelCallr8   r8   r9   _cleanup   s    zThreadedResolver._cleanupc                 C   sj   z| j | \}}W n tk
r&   Y n@X | j |= |  t|tjr\|| ||  n
|	| d S rh   )
rj   KeyErrorr6   
isinstancer   rl   rp   ro   ZgetErrorMessagecallback)r5   resultrm   rq   rr   rs   r8   r8   r9   _checkTimeout  s    zThreadedResolver._checkTimeoutr>         -   c                 C   sj   |rt |}nd}t }t| j| j tj|}| j	|| j
||}||f| j|< || j|| |S )a1  
        See L{twisted.internet.interfaces.IResolverSimple.getHostByName}.

        Note that the elements of C{timeout} are summed and the result is used
        as a timeout for the lookup.  Any intermediate timeout or retry logic
        is left up to the platform via L{socket.gethostbyname}.
        <   )sumr   r"   r   ZdeferToThreadPoolri   getThreadPoolsocketgethostbyname	callLaterrt   rj   ZaddBothry   )r5   rm   timeoutZtimeoutDelayrr   rq   rs   r8   r8   r9   getHostByName  s&    
     zThreadedResolver.getHostByNameN)rz   )	rM   re   rL   __doc__r:   ro   rt   ry   r   r8   r8   r8   r9   rg      s   rg   c                   @   s   e Zd ZdddZdS )BlockingResolverrz   c                 C   sR   zt |}W n4 t jk
rB   d|f }t|}t| Y S X t|S d S )Nzaddress %r not found)r   r   r   rk   r   Zfailsucceed)r5   rm   r   Zaddressmsgrn   r8   r8   r9   r   -  s    

zBlockingResolver.getHostByNameN)rz   )rM   re   rL   r   r8   r8   r8   r9   r   )  s   r   c                   @   sH   e Zd Z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 )_ThreePhaseEventa  
    Collection of callables (with arguments) which can be invoked as a group in
    a particular order.

    This provides the underlying implementation for the reactor's system event
    triggers.  An instance of this class tracks triggers for all phases of a
    single type of event.

    @ivar before: A list of the before-phase triggers containing three-tuples
        of a callable, a tuple of positional arguments, and a dict of keyword
        arguments

    @ivar finishedBefore: A list of the before-phase triggers which have
        already been executed.  This is only populated in the C{'BEFORE'} state.

    @ivar during: A list of the during-phase triggers containing three-tuples
        of a callable, a tuple of positional arguments, and a dict of keyword
        arguments

    @ivar after: A list of the after-phase triggers containing three-tuples
        of a callable, a tuple of positional arguments, and a dict of keyword
        arguments

    @ivar state: A string indicating what is currently going on with this
        object.  One of C{'BASE'} (for when nothing in particular is happening;
        this is the initial value), C{'BEFORE'} (when the before-phase triggers
        are in the process of being executed).
    c                 C   s   g | _ g | _g | _d| _d S )NBASE)beforeduringafterstater<   r8   r8   r9   r:   U  s    z_ThreePhaseEvent.__init__c                 O   s2   |dkrt dt| ||||f ||||fS )a  
        Add a trigger to the indicate phase.

        @param phase: One of C{'before'}, C{'during'}, or C{'after'}.

        @param callable: An object to be called when this event is triggered.
        @param *args: Positional arguments to pass to C{callable}.
        @param **kwargs: Keyword arguments to pass to C{callable}.

        @return: An opaque handle which may be passed to L{removeTrigger} to
            reverse the effects of calling this method.
        r   r   r   invalid phase)ru   getattrr_   )r5   phasecallabler*   kwargsr8   r8   r9   
addTrigger\  s    z_ThreePhaseEvent.addTriggerc                 C   s   t | d| j |S )aS  
        Remove a previously added trigger callable.

        @param handle: An object previously returned by L{addTrigger}.  The
            trigger added by that call will be removed.

        @raise ValueError: If the trigger associated with C{handle} has already
            been removed or if C{handle} is not a valid handle.
        ZremoveTrigger_)r   r   )r5   handler8   r8   r9   removeTriggero  s    
z_ThreePhaseEvent.removeTriggerc              	   C   s\   z|\}}}}W n  t tfk
r0   tdY n(X |dkrBtdt| ||||f dS )zN
        Just try to remove the trigger.

        @see: removeTrigger
        zinvalid trigger handler   r   N)	TypeError
ValueErrorru   r   remover5   r   r   r   r*   r   r8   r8   r9   removeTrigger_BASE|  s    z#_ThreePhaseEvent.removeTrigger_BASEc                 C   sN   |\}}}}|dkr|  |S |||f| jkr@tjdtdd n
|  | dS )z
        Remove the trigger if it has yet to be executed, otherwise emit a
        warning that in the future an exception will be raised when removing an
        already-executed trigger.

        @see: removeTrigger
        r   zdRemoving already-fired system event triggers will raise an exception in a future version of Twisted.r{   )category
stacklevelN)r   finishedBeforewarningswarnDeprecationWarningr   r8   r8   r9   removeTrigger_BEFORE  s    
z%_ThreePhaseEvent.removeTrigger_BEFOREc                 C   s   d| _ g | _g }| jrt| jd\}}}| j|||f z|||}W n   t  Y qX t|tr|| qt	|
| j dS )z8
        Call the triggers added to this event.
        ZBEFOREr   N)r   r   r   popr_   r   rn   rv   r"   r#   ZaddCallback_continueFiring)r5   ZbeforeResultsr   r*   r   rx   r8   r8   r9   	fireEvent  s    
z_ThreePhaseEvent.fireEventc                 C   s\   d| _ g | _| j| jfD ]>}|r|d\}}}z||| W q   t  Y qX qqdS )zJ
        Call the during and after phase triggers for this event.
        r   r   N)r   r   r   r   r   r   rn   )r5   Zignoredr   r   r*   r   r8   r8   r9   r     s    z _ThreePhaseEvent._continueFiringN)rM   re   rL   r   r:   r   r   r   r   r   r   r8   r8   r8   r9   r   8  s   r   c                   @   s  e Zd ZdZdZdZdZdZe Z	dZ
dZ dd ZdZdd	 Zd
d Zdd Ze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d Zd d! Zdad#d$Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Z d/d0 Z!dbd2d3Z"d4d5 Z#d6d7 Z$d8d9 Z%d:d; Z&d<d= Z'd>d? Z(e)e*Z+d@dA Z,dBdC Z-dDdE Z.dFdG Z/dHdI Z0dJdK Z1dLdM Z2dNdO Z3e45 rdZ6dZ7dZ8dPdQ Z9dRdS Z:dTdU Z;dVdW Z<dXdY Z=dZd[ Z>d\d] Z?d^d_ Z@nd`dS Z:dS )cReactorBasea  
    Default base class for Reactors.

    @type _stopped: C{bool}
    @ivar _stopped: A flag which is true between paired calls to C{reactor.run}
        and C{reactor.stop}.  This should be replaced with an explicit state
        machine.

    @type _justStopped: C{bool}
    @ivar _justStopped: A flag which is true between the time C{reactor.stop}
        is called and the time the shutdown system event is fired.  This is
        used to determine whether that event should be fired after each
        iteration through the mainloop.  This should be replaced with an
        explicit state machine.

    @type _started: C{bool}
    @ivar _started: A flag which is true from the time C{reactor.run} is called
        until the time C{reactor.run} returns.  This is used to prevent calls
        to C{reactor.run} on a running reactor.  This should be replaced with
        an explicit state machine.

    @ivar running: See L{IReactorCore.running}

    @ivar _registerAsIOThread: A flag controlling whether the reactor will
        register the thread it is running in as the I/O thread when it starts.
        If C{True}, registration will be done, otherwise it will not be.

    @ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal}
    TFNtwisted.internet.reactorc                 C   s   g | _ i | _g | _g | _d| _d| _d| _d| _d| _t	 | _
d | _d | _| dd| j | dd| j | dd| j t r|   |   d S )Nr   Fr   startupshutdown)threadCallQueue_eventTriggers_pendingTimedCalls_newTimedCalls_cancellationsrunning_started_justStopped_startedBeforesetZ_internalReaders_nameResolverwakeraddSystemEventTrigger_reallyStartRunningcrashdisconnectAllr!   supportsThreads_initThreadsinstallWakerr<   r8   r8   r9   r:     s,      zReactorBase.__init__c                 C   s   t t| jd d S )Nz did not implement installWakerNotImplementedErrorr   qual	__class__r<   r8   r8   r9   r     s    zReactorBase.installWakerc                 C   s(   t |st| j}|| _t|| _|S )z
        See L{IReactorPluggableResolver}.

        @param resolver: see L{IReactorPluggableResolver}.

        @return: see L{IReactorPluggableResolver}.
        )r   Z
providedByAssertionErrorresolver_SimpleResolverComplexifierr   )r5   r   ZoldResolverr8   r8   r9   installResolver  s
    
zReactorBase.installResolverc                 C   s   | j }|| _ t|| _|S )z
        See L{IReactorPluggableNameResolver}.

        @param resolver: See L{IReactorPluggableNameResolver}.

        @return: see L{IReactorPluggableNameResolver}.
        )r   _ComplexResolverSimplifierr   )r5   r   ZpreviousNameResolverr8   r8   r9   installNameResolver#  s    
zReactorBase.installNameResolverc                 C   s   | j S )zd
        Implementation of read-only
        L{IReactorPluggableNameResolver.nameResolver}.
        )r   r<   r8   r8   r9   nameResolver1  s    zReactorBase.nameResolverc                 C   s   | j r| j   dS )z)
        Wake up the event loop.
        N)r   wakeUpr<   r8   r8   r9   r   :  s    zReactorBase.wakeUpc                 C   s   t t| jd dS )zV
        Do one iteration over the readers and writers which have been added.
        z did not implement doIterationNr   r5   rD   r8   r8   r9   doIterationC  s    zReactorBase.doIterationc                 C   s   t t| jd d S )Nz did not implement addReaderr   r5   readerr8   r8   r9   	addReaderJ  s    zReactorBase.addReaderc                 C   s   t t| jd d S )Nz did not implement addWriterr   r5   writerr8   r8   r9   	addWriterN  s    zReactorBase.addWriterc                 C   s   t t| jd d S )Nz did not implement removeReaderr   r   r8   r8   r9   removeReaderR  s    zReactorBase.removeReaderc                 C   s   t t| jd d S )Nz did not implement removeWriterr   r   r8   r8   r9   removeWriterV  s    zReactorBase.removeWriterc                 C   s   t t| jd d S )Nz did not implement removeAllr   r<   r8   r8   r9   	removeAllZ  s    zReactorBase.removeAllc                 C   s   t t| jd d S )Nz did not implement getReadersr   r<   r8   r8   r9   
getReaders_  s    zReactorBase.getReadersc                 C   s   t t| jd d S )Nz did not implement getWritersr   r<   r8   r8   r9   
getWritersd  s    zReactorBase.getWritersrz   c                 C   s0   |st dS t|r"t |S | j||S )z8Return a Deferred that will resolve a hostname.
        z0.0.0.0)r   r   r   ZisIPAddressr   r   )r5   rm   r   r8   r8   r9   resolvei  s
    


zReactorBase.resolvec                 C   s&   | j rtdd| _ d| _d| _dS )zD
        See twisted.internet.interfaces.IReactorCore.stop.
        z&Can't stop reactor that isn't running.TN)_stoppedr   ZReactorNotRunningr   r   r<   r8   r8   r9   stopv  s    zReactorBase.stopc                 C   s    d| _ d| _| dd| j dS )z
        See twisted.internet.interfaces.IReactorCore.crash.

        Reset reactor state tracking attributes and re-initialize certain
        state-transition helpers which were set up in C{__init__} but later
        destroyed (through use).
        Fr   r   N)r   r   r   r   r<   r8   r8   r9   r     s      zReactorBase.crashc                 G   s$   t d | | j |d | _dS )zp
        Handle a SIGINT interrupt.

        @param args: See handler specification in L{signal.signal}
        zReceived SIGINT, shutting down.r   Nr   r   callFromThreadr   _exitSignalr5   r*   r8   r8   r9   sigInt  s    
zReactorBase.sigIntc                 G   s$   t d | | j |d | _dS )zr
        Handle a SIGBREAK interrupt.

        @param args: See handler specification in L{signal.signal}
        z!Received SIGBREAK, shutting down.r   Nr   r   r8   r8   r9   sigBreak  s    
zReactorBase.sigBreakc                 G   s$   t d | | j |d | _dS )zq
        Handle a SIGTERM interrupt.

        @param args: See handler specification in L{signal.signal}
        z Received SIGTERM, shutting down.r   Nr   r   r8   r8   r9   sigTerm  s    
zReactorBase.sigTermc                 C   s.   |   }|D ]}t||jttj qdS )z;Disconnect every reader, and writer in the system.
        N)r   r   ZcallWithLoggerconnectionLostr   rl   r   ZCONNECTION_LOST)r5   Zselectablesr   r8   r8   r9   r     s    
zReactorBase.disconnectAllr   c                 C   s   |    | | dS )z>See twisted.internet.interfaces.IReactorCore.iterate.
        N)runUntilCurrentr   r   r8   r8   r9   iterate  s    zReactorBase.iteratec                 C   s    | j |}|dk	r|  dS )zFSee twisted.internet.interfaces.IReactorCore.fireSystemEvent.
        N)r   getr   )r5   	eventTypeZeventr8   r8   r9   fireSystemEvent  s    zReactorBase.fireSystemEventc                 O   sH   t |std| || jkr*t | j|< || j| j||f||fS )zLSee twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.
        %s is not callable)r   r   r   r   r   )r5   Z_phaseZ
_eventType_fr*   r+   r8   r8   r9   r     s    
 z!ReactorBase.addSystemEventTriggerc                 C   s   |\}}| j | | dS )zOSee twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger.
        N)r   r   )r5   Z	triggerIDr   r   r8   r8   r9   removeSystemEventTrigger  s    z$ReactorBase.removeSystemEventTriggerc                 O   s,   | j r||| n| jdd|f||S dS )zFSee twisted.internet.interfaces.IReactorCore.callWhenRunning.
        r   r   N)r   r   )r5   	_callabler*   r+   r8   r8   r9   callWhenRunning  s    zReactorBase.callWhenRunningc                 C   sD   | j rt | jrt d| _ d| _| jr6t  | 	d dS )a  
        Method called when reactor starts: do some initialization and fire
        startup events.

        Don't call this directly, call reactor.run() instead: it should take
        care of calling this.

        This method is somewhat misnamed.  The reactor will not necessarily be
        in the running state by the time this method returns.  The only
        guarantee is that it will be on its way to the running state.
        TFr   N)
r   r   ZReactorAlreadyRunningr   ZReactorNotRestartabler   _registerAsIOThreadr%   ZregisterAsIOThreadr   r<   r8   r8   r9   startRunning  s    zReactorBase.startRunningc                 C   s
   d| _ dS )z
        Method called to transition to the running state.  This should happen
        in the I{during startup} event trigger phase.
        TN)r   r<   r8   r8   r9   r     s    zReactorBase._reallyStartRunningc              	   O   s^   t |std| |dks*td|f t|  | |||| j| j| jd}| j| |S )z@See twisted.internet.interfaces.IReactorTime.callLater.
        r   r   z,%s is not greater than or equal to 0 seconds)r    )r   r   r&   r    _cancelCallLater_moveCallLaterSoonerr   r_   )r5   Z_secondsr   r*   r+   tpler8   r8   r9   r     s    
zReactorBase.callLaterc                 C   sr   | j }zR||}|| }|dkrN|d d }|| |kr<qN|| ||< |}q|||< W n tk
rl   Y nX d S )Nr   r>      )r   indexr   )r5   r   heapposZeltparentr8   r8   r9   r     s    
z ReactorBase._moveCallLaterSoonerc                 C   s   |  j d7  _ d S Nr>   )r   )r5   r   r8   r8   r9   r   &  s    zReactorBase._cancelCallLaterc                 C   s   dd | j | j D S )a3  
        Return all the outstanding delayed calls in the system.
        They are returned in no particular order.
        This method is not efficient -- it is really only meant for
        test cases.

        @return: A list of outstanding delayed calls.
        @type: L{list} of L{DelayedCall}
        c                 S   s   g | ]}|j s|qS r8   r.   rT   xr8   r8   r9   rV   4  s      z/ReactorBase.getDelayedCalls.<locals>.<listcomp>)r   r   r<   r8   r8   r9   getDelayedCalls*  s    
zReactorBase.getDelayedCallsc                 C   s@   | j D ].}|jr |  jd8  _q|  t| j| qg | _ d S r   )r   r.   r   rC   r   r   )r5   callr8   r8   r9   _insertNewDelayedCalls7  s    
z"ReactorBase._insertNewDelayedCallsc                 C   s:   |    | jsdS | jd j|   }d}tdt||S )a  
        Determine the longest time the reactor may sleep (waiting on I/O
        notification, perhaps) before it must wake up to service a time-related
        event.

        @return: The maximum number of seconds the reactor may sleep.
        @rtype: L{float}
        Nr   i  )r   r   r(   r    maxmin)r5   rD   Zlongestr8   r8   r9   r   A  s    
zReactorBase.timeoutc           	      C   s  | j rxd}t| j }| j D ]B\}}}z||| W n   t  Y nX |d7 }||kr q^q| j d|= | j rx|   |   |  }| jrb| jd j|krbt	| j}|j
r|  jd8  _q|jdkr|  t| j| qzd|_|j|j|j W q   t  t|drZd}|d7 }|d7 }|d|j dd	7 }|d7 }t| Y qX q| jd
kr| jt| jd? krd| _dd | jD | _t| j | jrd| _| d dS )z.
        Run all pending timed calls.
        r   r>   Nr4   
z? C: previous exception occurred in a DelayedCall created here:
z C:r[   z
 C:2   c                 S   s   g | ]}|j s|qS r8   r   r   r8   r8   r9   rV     s    z/ReactorBase.runUntilCurrent.<locals>.<listcomp>Fr   )r   lenr   rn   r   r   r    r   r(   r   r.   r   r0   rC   r   r/   r)   r*   r+   Zdeferrr\   r`   r4   rstripreplacer   r   r   r   )	r5   countZtotalfar+   rb   r   rU   r8   r8   r9   r   _  s\    



zReactorBase.runUntilCurrentc           	         s   t    fdd}t|ttfs*tdg }|D ](}||}|dkrPtdq2|| q2d}|dk	ri }t|D ]@\}}||}|dkrtd||}|dkrtd|||< qt||fS )a  
        Check for valid arguments and environment to spawnProcess.

        @return: A two element tuple giving values to use when creating the
        process.  The first element of the tuple is a C{list} of C{bytes}
        giving the values for argv of the child process.  The second element
        of the tuple is either L{None} if C{env} was L{None} or a C{dict}
        mapping C{bytes} environment keys to C{bytes} environment values.
        c                    sJ   t | tr0z|  } W n tk
r.   Y dS X t | trFd| krF| S dS )a\  
            Return either L{bytes} or L{None}.  If the given value is not
            allowable for some reason, L{None} is returned.  Otherwise, a
            possibly different object which should be used in place of arg is
            returned.  This forces unicode encoding to happen now, rather than
            implicitly later.
            N    )rv   r   encodeUnicodeEncodeErrorbytes)argZdefaultEncodingr8   r9   
argChecker  s    
z1ReactorBase._checkProcessArgs.<locals>.argCheckerz!Arguments must be a tuple or listNz$Arguments contain a non-string valuez%Environment contains a non-string keyz'Environment contains a non-string value)sysgetfilesystemencodingrv   tuplelistr   r_   r   )	r5   r*   envr  Z
outputArgsr  Z	outputEnvkeyvalr8   r  r9   _checkProcessArgs  s,    

zReactorBase._checkProcessArgsc                 C   s   |  t| | j d| _d S )NT)r   _GAIResolverr   usingThreadsr<   r8   r8   r9   r     s    zReactorBase._initThreadsc                 O   s4   t |std|f | j|||f |   dS )zl
            See
            L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}.
            r   N)r   r   r   r_   r   r5   r  r*   r+   r8   r8   r9   r     s    zReactorBase.callFromThreadc                 C   sB   ddl m} |ddd| _| | jj| _| dd| j| _dS )zO
            Create the threadpool accessible with callFromThread.
            r   )
threadpool
   r   r   r   N)	twisted.pythonr  Z
ThreadPoolr   start_threadpoolStartupIDr   _stopThreadPoolthreadpoolShutdownID)r5   r  r8   r8   r9   _initThreadPool  s        zReactorBase._initThreadPoolc                 C   s   d S rh   r8   r<   r8   r8   r9   _uninstallHandler  s    zReactorBase._uninstallHandlerc              	   C   s`   | j | jg}td|D ](}z| | W q tk
r<   Y qX qd| _ d| _| j  d| _dS )a4  
            Stop the reactor threadpool.  This method is only valid if there
            is currently a threadpool (created by L{_initThreadPool}).  It
            is not intended to be called directly; instead, it will be
            called by a shutdown trigger created in L{_initThreadPool}.
            N)r  r   filterr   r   r  r   )r5   ZtriggersZtriggerr8   r8   r9   r    s    
zReactorBase._stopThreadPoolc                 C   s   | j dkr|   | j S )z[
            See L{twisted.internet.interfaces.IReactorThreads.getThreadPool}.
            N)r  r!  r<   r8   r8   r9   r   !  s    
zReactorBase.getThreadPoolc                 O   s   |   j|f|| dS )z\
            See L{twisted.internet.interfaces.IReactorInThreads.callInThread}.
            N)r   callInThread)r5   r   r*   r   r8   r8   r9   r$  *  s    zReactorBase.callInThreadc                 C   s   |   j|d dS )zc
            See L{twisted.internet.interfaces.IReactorThreads.suggestThreadPoolSize}.
            )Z
maxthreadsN)r   ZadjustPoolsize)r5   sizer8   r8   r9   suggestThreadPoolSize1  s    z!ReactorBase.suggestThreadPoolSizec                 O   s,   t |std|f | j|||f d S )Nr   )r   r   r   r_   r  r8   r8   r9   r   8  s    )rz   )r   )ArM   re   rL   r   r   r   Z	installedr  r   r   r   r:   _lockr   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   staticmethodrf   r    r   r   r   r   r   r   r   r  r!   r   r  r  r   r   r   r!  r"  r  r   r$  r&  r8   r8   r8   r9   r     sx   
	



		
AG
	
r   c                   @   s`   e Zd ZdZdZdZ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d ZdS )BaseConnectorzdBasic implementation of connector.

    State can be: "connecting", "connected", "disconnected"
    Nr   c                 C   s   d| _ || _|| _|| _d S )Ndisconnected)r   ri   factoryr   )r5   r,  r   ri   r8   r8   r9   r:   K  s    zBaseConnector.__init__c                 C   s,   | j dkr|   n| j dkr(| j  dS )z!Disconnect whatever our state is.
connecting	connectedN)r   stopConnecting	transportZloseConnectionr<   r8   r8   r9   
disconnectQ  s    


zBaseConnector.disconnectc                 C   sp   | j dkrtdd| _ | js.| j  d| _|   | _}| jdk	r`| j	| j|j
t | _| j|  dS )z"Start connection to remote server.r+  zcan't connect in this stater-  r>   N)r   RuntimeErrorfactoryStartedr,  ZdoStartZ_makeTransportr0  r   ri   r   failIfNotConnectedr   TimeoutError	timeoutIDZstartedConnecting)r5   r0  r8   r8   r9   connectX  s    


zBaseConnector.connectc                 C   s2   | j dkrtdd| _ | jt  | `dS )zStop attempting to connect.r-  zwe're not trying to connectr+  N)r   r   ZNotConnectingErrorr0  r4  Z	UserErrorr<   r8   r8   r9   r/  f  s
    

zBaseConnector.stopConnectingc                 C   s6   | j d k	r2z| j   W n tk
r,   Y nX | ` d S rh   )r6  r6   r   r<   r8   r8   r9   cancelTimeouto  s    
zBaseConnector.cancelTimeoutc                 C   s   d| _ |   | j|S )Nr.  )r   r8  r,  buildProtocol)r5   Zaddrr8   r8   r9   r9  w  s    zBaseConnector.buildProtocolc                 C   s@   |    d | _d| _| j| | | jdkr<| j  d| _d S Nr+  r   )r8  r0  r   r,  ZclientConnectionFaileddoStopr3  r5   reasonr8   r8   r9   connectionFailed|  s    

zBaseConnector.connectionFailedc                 C   s2   d| _ | j| | | j dkr.| j  d| _d S r:  )r   r,  ZclientConnectionLostr;  r3  r<  r8   r8   r9   r     s
    

zBaseConnector.connectionLostc                 C   s   t t| jd d S )Nz! did not implement getDestinationr   r<   r8   r8   r9   getDestination  s    zBaseConnector.getDestination)rM   re   rL   r   r6  r3  r:   r1  r7  r/  r8  r9  r>  r   r?  r8   r8   r8   r9   r*  A  s   	
r*  c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )BasePortziBasic implementation of a ListeningPort.

    Note: This does not actually implement IListeningPort.
    Nc                 C   s,   t  | j| j}|d t|  |S rE   )r   addressFamily
socketTypeZsetblockingr   Z_setCloseOnExecfileno)r5   sr8   r8   r9   createInternetSocket  s    
zBasePort.createInternetSocketc                 C   s   t dt| j dS )zRaises a RuntimeErrorzdoWrite called on a %sN)r2  r   r   r   r<   r8   r8   r9   doWrite  s    zBasePort.doWrite)rM   re   rL   r   rA  rB  rE  rF  r8   r8   r8   r9   r@    s
   r@  c                   @   s@   e Zd ZdZdZdd ZdddZdd	 Zdd
dZdd Z	dS )_SignalReactorMixinaK  
    Private mixin to manage signals: it installs signal handlers at start time,
    and define run method.

    It can only be used mixed in with L{ReactorBase}, and has to be defined
    first in the inheritance (so that method resolution order finds
    startRunning first).

    @type _installSignalHandlers: C{bool}
    @ivar _installSignalHandlers: A flag which indicates whether any signal
        handlers will be installed during startup.  This includes handlers for
        SIGCHLD to monitor child processes, and SIGINT, SIGTERM, and SIGBREAK
        to stop the reactor.
    Fc                 C   s~   zddl }W n  tk
r,   td Y dS X ||j|jkrP| |j| j | |j| j	 t
|drz| |j| j dS )zI
        Install the signal handlers for the Twisted event loop.
        r   NzEWarning: signal module unavailable -- not installing signal handlers.SIGBREAK)signalImportErrorr   r   	getsignalSIGINTdefault_int_handlerr   SIGTERMr   r\   rH  r   )r5   rI  r8   r8   r9   _handleSignals  s    

z"_SignalReactorMixin._handleSignalsTc                 C   s   || _ t|  dS )ao  
        Extend the base implementation in order to remember whether signal
        handlers should be installed later.

        @type installSignalHandlers: C{bool}
        @param installSignalHandlers: A flag which, if set, indicates that
            handlers for a number of (implementation-defined) signals should be
            installed during startup.
        N)_installSignalHandlersr   r   r5   installSignalHandlersr8   r8   r9   r     s    
z _SignalReactorMixin.startRunningc                 C   s   t |  | jr|   dS )z
        Extend the base implementation by also installing signal handlers, if
        C{self._installSignalHandlers} is true.
        N)r   r   rP  rO  r<   r8   r8   r9   r     s    
z'_SignalReactorMixin._reallyStartRunningc                 C   s   | j |d |   d S )N)rR  )r   mainLooprQ  r8   r8   r9   run  s    z_SignalReactorMixin.runc                 C   sf   | j rbz0| j r4|   |  }| jo&|}| | qW n   td t  Y q X td q d S )NzUnexpected error in main loop.zMain loop terminated.)r   r   r   r   r   r   r   rn   )r5   t2tr8   r8   r9   rS    s    

z_SignalReactorMixin.mainLoopN)T)T)
rM   re   rL   r   rP  rO  r   r   rT  rS  r8   r8   r8   r9   rG    s   

rG  )Dr   Z
__future__r   r   r   Zzope.interfacer   r   r  r   heapqr   r   r   r2   Ztwisted.internet.interfacesr	   r
   r   r   r   r   r   r   r   Ztwisted.internetr   r   r   r   r   r   Ztwisted.internet._resolverr   r  r   r   r   r   r  r   r   r   Ztwisted.python.compatr   r   Ztwisted.python.runtimer    rf   r!   Ztwisted.internet.deferr"   r#   Ztwisted.python._oldstyler$   r%   r&   objectrg   r   r   r   r   r*  ZFileDescriptorr@  rG  __all__r8   r8   r8   r9   <module>   sX   ,  9C      z

R\