
\[\                 @   s  d  Z  d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l 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 m Z d d l m Z d d l m Z d d l m Z d d	 l m Z d
 d g Z d Z d Z d Z d d   Z d d   Z Gd d   d e  Z d d   Z d d   Z Gd d   d e j  Z  Gd d
   d
 e j!  Z" d S)a  Base implementation of event loop.

The event loop can be broken up into a multiplexer (the part
responsible for notifying us of I/O events) and the event loop proper,
which wraps a multiplexer with functionality for scheduling callbacks,
immediately or at a given time in the future.

Whenever a public API takes a callback, subsequent positional
arguments will be passed to the callback if/when it is called.  This
avoids the proliferation of trivial lambdas implementing closures.
Keyword arguments for the callback are not supported; this is a
conscious design decision, leaving the door open for keyword arguments
to modify the meaning of the API call itself.
    N   )
coroutines)events)futures)tasks)	coroutine)loggerBaseEventLoopServer   d   g      ?c             C   sH   |  j  } t j |  r: t | j t j  r: t | j  St |   Sd  S)N)		_callbackinspectZismethod
isinstance__self__r   Taskreprstr)handlecb r   )/usr/lib/python3.4/asyncio/base_events.py_format_handle3   s    	$r   c             C   s4   |  t  j k r d S|  t  j k r& d St |   Sd  S)Nz<pipe>z<stdout>)
subprocessPIPESTDOUTr   )fdr   r   r   _format_pipe<   s
    r   c               @   s   e  Z d  Z d Z d S)
_StopErrorzRaised to stop the event loop.N)__name__
__module____qualname____doc__r   r   r   r   r   E   s   r   c             C   s  |  j  } | t j k r' | \ } } n, | t j k rO | d  d  \ } } n d  Sd } t t d  rx | t j O} n  t t d  r | t j O} n  y: t j | | d | d |  j | @d |  j	 d t j
 Wn> t j k
 r} z t d	 | | f   WYd  d  } ~ Xn Xd  S)
N   r   SOCK_NONBLOCKSOCK_CLOEXECfamilytypeprotoflagsz1address must be resolved (IP address), got %r: %s)r&   socketZAF_INETAF_INET6hasattrr$   r%   getaddrinfor'   r(   ZAI_NUMERICHOSTZgaierror
ValueError)sockaddressr&   hostportZ	type_maskerrr   r   r   _check_resolved_addressI   s(    		r4   c              G   s
   t   d  S)N)r   )argsr   r   r   _raise_stop_errore   s    r6   c               @   sj   e  Z d  Z d d   Z d d   Z d d   Z d d   Z d	 d
   Z d d   Z e	 d d    Z
 d S)r
   c             C   s(   | |  _  | |  _ d |  _ g  |  _ d  S)Nr   )_loopsockets_active_count_waiters)selfloopr8   r   r   r   __init__k   s    			zServer.__init__c             C   s   d |  j  j |  j f S)Nz<%s sockets=%r>)	__class__r   r8   )r;   r   r   r   __repr__q   s    zServer.__repr__c             C   s(   |  j  d  k	 s t  |  j d 7_ d  S)Nr   )r8   AssertionErrorr9   )r;   r   r   r   _attacht   s    zServer._attachc             C   sS   |  j  d k s t  |  j  d 8_  |  j  d k rO |  j d  k rO |  j   n  d  S)Nr   r   )r9   r@   r8   _wakeup)r;   r   r   r   _detachx   s    zServer._detachc             C   sc   |  j  } | d  k r d  Sd  |  _  x | D] } |  j j |  q) W|  j d k r_ |  j   n  d  S)Nr   )r8   r7   Z_stop_servingr9   rB   )r;   r8   r/   r   r   r   close~   s    		zServer.closec             C   sC   |  j  } d  |  _  x* | D]" } | j   s | j |  q q Wd  S)N)r:   done
set_result)r;   waiterswaiterr   r   r   rB      s
    		zServer._wakeupc             c   sT   |  j  d  k s |  j d  k r" d  St j d |  j  } |  j j |  | Dd  Hd  S)Nr<   )r8   r:   r   Futurer7   append)r;   rH   r   r   r   wait_closed   s
    zServer.wait_closedN)r   r    r!   r=   r?   rA   rC   rD   rB   r   rK   r   r   r   r   r
   i   s   
c               @   s  e  Z d  Z d d   Z d d   Z d d   Z d d d d	 d d
 d Z d d d d d d d	 d d d  Z d d d d d  Z d d d d  Z	 d d d d  Z
 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' d(   Z d) d*   Z d+ d,   Z d- d.   Z d/ d0   Z d1 d2   Z d3 d4   Z d5 d6   Z d7 d8   Z d9 d:   Z d; d<   Z d= d>   Z d? d@ dA d@ dB d@ dC d@ dD dE  Z  d@ dF dG  Z! e d d dH d d? d@ dB d@ dC d@ dI d dJ d d d dK dL  Z" e dM dN    Z# e d d d? d@ dB d@ dC d@ dO dP  Z$ e d d d? e% j& dC e% j' dI d dQ dR dH d dS d dT dU  Z( e dV dW    Z) e dX dY    Z* dZ d[   Z+ e d\ e, j- d] e, j- d^ e, j- d_ d d` da db d@ dc dd   Z. e d\ e, j- d] e, j- d^ e, j- d_ d d` d db d@ de df   Z/ dg dh   Z0 di dj   Z1 dk dl   Z2 dm dn   Z3 do dp   Z4 dq dr   Z5 ds dt   Z6 du dv   Z7 dw dx   Z8 d S)yr	   c             C   s   d |  _  d |  _ t j   |  _ g  |  _ d  |  _ d |  _ d |  _ t	 j
 d  j |  _ d  |  _ t j j o t t j j d   |  _ d |  _ d  S)Nr   F	monotonicZPYTHONASYNCIODEBUGg?)_timer_cancelled_count_closedcollectionsdeque_ready
_scheduled_default_executorZ_internal_fds_runningtimeZget_clock_infoZ
resolution_clock_resolution_exception_handlersysr)   ignore_environmentboolosenvironget_debugslow_callback_duration)r;   r   r   r   r=      s    							zBaseEventLoop.__init__c             C   s,   d |  j  j |  j   |  j   |  j   f S)Nz"<%s running=%s closed=%s debug=%s>)r>   r   
is_running	is_closed	get_debug)r;   r   r   r   r?      s    zBaseEventLoop.__repr__c             C   s/   t  j | d |  } | j r+ | j d =n  | S)zDSchedule a coroutine object.

        Return a task object.
        r<   r   )r   r   _source_traceback)r;   ZcoroZtaskr   r   r   create_task   s    	zBaseEventLoop.create_taskNextraserverc            C   s
   t   d S)zCreate socket transport.N)NotImplementedError)r;   r/   protocolrH   rf   rg   r   r   r   _make_socket_transport   s    z$BaseEventLoop._make_socket_transportserver_sideFserver_hostnamec      	      C   s
   t   d S)zCreate SSL transport.N)rh   )	r;   Zrawsockri   
sslcontextrH   rk   rl   rf   rg   r   r   r   _make_ssl_transport   s    z!BaseEventLoop._make_ssl_transportc             C   s
   t   d S)zCreate datagram transport.N)rh   )r;   r/   ri   r0   rH   rf   r   r   r   _make_datagram_transport   s    z&BaseEventLoop._make_datagram_transportc             C   s
   t   d S)zCreate read pipe transport.N)rh   )r;   piperi   rH   rf   r   r   r   _make_read_pipe_transport   s    z'BaseEventLoop._make_read_pipe_transportc             C   s
   t   d S)zCreate write pipe transport.N)rh   )r;   rp   ri   rH   rf   r   r   r   _make_write_pipe_transport   s    z(BaseEventLoop._make_write_pipe_transportc	       
      K   s
   t   d S)zCreate subprocess transport.N)rh   )
r;   ri   r5   shellstdinstdoutstderrbufsizerf   kwargsr   r   r   _make_subprocess_transport   s    z(BaseEventLoop._make_subprocess_transportc             C   s
   t   d S)zWrite a byte to self-pipe, to wake up the event loop.

        This may be called from a different thread.

        The subclass is responsible for implementing the self-pipe.
        N)rh   )r;   r   r   r   _write_to_self   s    zBaseEventLoop._write_to_selfc             C   s
   t   d S)zProcess selector events.N)rh   )r;   
event_listr   r   r   _process_events   s    zBaseEventLoop._process_eventsc             C   s   |  j  r t d   n  d  S)NzEvent loop is closed)rN   RuntimeError)r;   r   r   r   _check_closed   s    	zBaseEventLoop._check_closedc             C   sj   |  j    |  j r" t d   n  d |  _ z. x' y |  j   Wq1 t k
 rT PYq1 Xq1 Wd d |  _ Xd S)zRun until stop() is called.zEvent loop is running.TNF)r~   rT   r}   	_run_oncer   )r;   r   r   r   run_forever   s    
		zBaseEventLoop.run_foreverc             C   s   |  j    t | t j  } t j | d |  } | rD d | _ n  | j t  |  j	   | j
 t  | j   s t d   n  | j   S)a\  Run until the Future is done.

        If the argument is a coroutine, it is wrapped in a Task.

        WARNING: It would be disastrous to call run_until_complete()
        with the same coroutine twice -- it would wrap it in two
        different Tasks and that can't be good.

        Return the Future's result, or raise its exception.
        r<   Fz+Event loop stopped before Future completed.)r~   r   r   rI   r   ZasyncZ_log_destroy_pendingZadd_done_callbackr6   r   Zremove_done_callbackrE   r}   result)r;   ZfutureZnew_taskr   r   r   run_until_complete   s    

z BaseEventLoop.run_until_completec             C   s   |  j  t  d S)zStop running the event loop.

        Every callback scheduled before stop() is called will run. Callbacks
        scheduled after stop() is called will not run. However, those callbacks
        will run if run_forever is called again later.
        N)	call_soonr6   )r;   r   r   r   stop  s    zBaseEventLoop.stopc             C   s   |  j  r t d   n  |  j r% d S|  j rA t j d |   n  d |  _ |  j j   |  j j   |  j	 } | d k	 r d |  _	 | j
 d d  n  d S)zClose the event loop.

        This clears the queues and shuts down the executor,
        but does not wait for the executor to finish.

        The event loop must not be running.
        z!Cannot close a running event loopNzClose %rTwaitF)rT   r}   rN   r^   r   debugrQ   clearrR   rS   Zshutdown)r;   executorr   r   r   rD     s    						zBaseEventLoop.closec             C   s   |  j  S)z*Returns True if the event loop was closed.)rN   )r;   r   r   r   ra   5  s    zBaseEventLoop.is_closedc             C   s   |  j  S)z*Returns True if the event loop is running.)rT   )r;   r   r   r   r`   9  s    zBaseEventLoop.is_runningc             C   s
   t  j   S)zReturn the time according to the event loop's clock.

        This is a float expressed in seconds since an epoch, but the
        epoch, precision, accuracy and drift are unspecified and may
        differ per event loop.
        )rU   rL   )r;   r   r   r   rU   =  s    zBaseEventLoop.timec             G   s9   |  j  |  j   | | |  } | j r5 | j d =n  | S)a8  Arrange for a callback to be called at a given time.

        Return a Handle: an opaque object with a cancel() method that
        can be used to cancel the call.

        The delay can be an int or float, expressed in seconds.  It is
        always relative to the current time.

        Each callback will be called exactly once.  If two callbacks
        are scheduled for exactly the same time, it undefined which
        will be called first.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        r   rc   )call_atrU   rd   )r;   Zdelaycallbackr5   timerr   r   r   
call_laterF  s    	zBaseEventLoop.call_laterc             G   s   t  j |  r t d   n  |  j r4 |  j   n  t j | | | |   } | j rb | j d =n  t j	 |  j
 |  d | _
 | S)z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        z(coroutines cannot be used with call_at()r   Trc   )r   iscoroutinefunction	TypeErrorr^   _assert_is_current_event_loopr   TimerHandlerd   heapqheappushrR   )r;   whenr   r5   r   r   r   r   r   [  s    			zBaseEventLoop.call_atc             G   s2   |  j  | | d d } | j r. | j d =n  | S)aT  Arrange for a callback to be called as soon as possible.

        This operates as a FIFO queue: callbacks are called in the
        order in which they are registered.  Each callback will be
        called exactly once.

        Any positional arguments after the callback will be passed to
        the callback when it is called.
        
check_loopTr   rc   )
_call_soonrd   )r;   r   r5   r   r   r   r   r   k  s    
	zBaseEventLoop.call_soonc             C   sy   t  j |  r t d   n  |  j r: | r: |  j   n  t j | | |   } | j re | j d =n  |  j j	 |  | S)Nz*coroutines cannot be used with call_soon()r   rc   )
r   r   r   r^   r   r   Handlerd   rQ   rJ   )r;   r   r5   r   r   r   r   r   r   z  s    	zBaseEventLoop._call_soonc             C   sH   y t  j   } Wn t k
 r( d SYn X| |  k	 rD t d   n  d S)ac  Asserts that this event loop is the current event loop.

        Non-thread-safe methods of this class make this assumption and will
        likely behave incorrectly when the assumption is violated.

        Should only be called when (self._debug == True).  The caller is
        responsible for checking this condition for performance reasons.
        NzMNon-thread-safe operation invoked on an event loop other than the current one)r   Zget_event_loopr@   r}   )r;   Zcurrentr   r   r   r     s    		z+BaseEventLoop._assert_is_current_event_loopc             G   s<   |  j  | | d d } | j r. | j d =n  |  j   | S)z"Like call_soon(), but thread-safe.r   Fr   rc   )r   rd   rz   )r;   r   r5   r   r   r   r   call_soon_threadsafe  s
    	
z"BaseEventLoop.call_soon_threadsafec             G   s   t  j |  r t d   n  t | t j  r | s= t  t | t j  sV t  | j r t	 j
 d |   } | j d   | S| j | j } } n  | d  k r |  j } | d  k r t j	 j t  } | |  _ q n  t	 j | j | |  d |  S)Nz0Coroutines cannot be used with run_in_executor()r<   )r   r   r   r   r   r   r@   r   
_cancelledr   rI   rF   r   Z_argsrS   
concurrentZThreadPoolExecutor_MAX_WORKERSZwrap_futureZsubmit)r;   r   r   r5   fr   r   r   run_in_executor  s     		zBaseEventLoop.run_in_executorc             C   s   | |  _  d  S)N)rS   )r;   r   r   r   r   set_default_executor  s    z"BaseEventLoop.set_default_executorc             C   s  d | | f g } | r- | j  d |  n  | rG | j  d |  n  | ra | j  d |  n  | r{ | j  d |  n  d j |  } t j d |  |  j   } t j | | | | | |  }	 |  j   | }
 d | |
 d	 |	 f } |
 |  j k r
t j |  n t j |  |	 S)
Nz%s:%rz	family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg     @@)	rJ   joinr   r   rU   r*   r-   r_   info)r;   r1   r2   r&   r'   r(   r)   msgt0Zaddrinfodtr   r   r   _getaddrinfo_debug  s(    z BaseEventLoop._getaddrinfo_debugr&   r   r'   r(   r)   c         	   C   sW   |  j  r. |  j d  |  j | | | | | |  S|  j d  t j | | | | | |  Sd  S)N)r^   r   r   r*   r-   )r;   r1   r2   r&   r'   r(   r)   r   r   r   r-     s
    	zBaseEventLoop.getaddrinfoc             C   s   |  j  d  t j | |  S)N)r   r*   getnameinfo)r;   Zsockaddrr)   r   r   r   r     s    zBaseEventLoop.getnameinfosslr/   
local_addrc            #   s0  |
 d k	 r" | r" t  d   n  |
 d k rR | rR | sI t  d   n  | }
 n  | d k	 sj | d k	 r| d k	 r t  d   n  |  j | | d | d t j d | d | } | g } |	 d k	 r|  j d | d t j d | d | |	  } | j |  n d } t j | d	 |  Dd H| j   } | s@t d
   n  | d k	 rp| j   } | spt d
   qpn  g  } xF| D]\ } } } } } yt j d | d | d |  } | j	 d  | d k	 rpx | D] \ } } } } } y | j
 |  PWqt k
 rU} z9 t | j d j | | j j     } | j |  WYd d } ~ XqXqW| j   d } w}n  |  j rt j d | |  n  |  j | |  Dd HWnn t k
 r} z+ | d k	 r| j   n  | j |  WYd d } ~ Xq}| d k	 r| j   n    Yq}XPq}Wt |  d k r:| d  qt | d    t   f d d   | D  rv| d  n  t d j d j d d   | D     n | d k rt  d   n  | j	 d  |  j | | | |
  Dd H\ } } |  j r&| j d  } t j d | | | | |  n  | | f S)a  Connect to a TCP server.

        Create a streaming transport connection to a given Internet host and
        port: socket family AF_INET or socket.AF_INET6 depending on host (or
        family if specified), socket type SOCK_STREAM. protocol_factory must be
        a callable returning a protocol instance.

        This method is a coroutine which will try to establish the connection
        in the background.  When successful, the coroutine returns a
        (transport, protocol) pair.
        Nz+server_hostname is only meaningful with sslz:You must set server_hostname when using ssl without a hostz8host/port and sock can not be specified at the same timer&   r'   r(   r)   r<   z!getaddrinfo() returned empty listFz2error while attempting to bind on address {!r}: {}zconnect %r to %rr   r   c             3   s!   |  ] } t  |    k Vq d  S)N)r   ).0exc)modelr   r   	<genexpr>>  s    z2BaseEventLoop.create_connection.<locals>.<genexpr>zMultiple exceptions: {}z, c             s   s   |  ] } t  |  Vq d  S)N)r   )r   r   r   r   r   r   C  s    z5host and port was not specified and no sock specifiedr*   z%r connected to %s:%r: (%r, %r))r.   r-   r*   SOCK_STREAMrJ   r   r   r   OSErrorsetblockingbinderrnoformatstrerrorlowerrD   r^   r   r   sock_connectlenr   allr   _create_connection_transportZget_extra_info)r;   protocol_factoryr1   r2   r   r&   r(   r)   r/   r   rl   f1Zfsf2infosZladdr_infos
exceptionsr'   Zcnamer0   _Zladdrr   	transportri   r   )r   r   create_connection  s    			$
		%		zBaseEventLoop.create_connectionc       	   	   c   s   |   } t  j d |   } | rc t | t  r6 d  n | } |  j | | | | d d d | } n |  j | | |  } | Dd  H| | f S)Nr<   rk   Frl   )r   rI   r   rZ   rn   rj   )	r;   r/   r   r   rl   ri   rH   rm   r   r   r   r   r   U  s    		z*BaseEventLoop._create_connection_transportc            #   sD    p	  s? | d k r' t  d   n  | | f d f f } nEt j   } x d   f d  f f D] \ }	 }
 |
 d k	 rd t |
 t  r t |
  d k s t d   |  j d | d t j	 d	 | d
 | |
  Dd H} | s t
 d   n  xY | D]N \ } } } } } | | f } | | k r4d d g | | <n  | | | |	 <q Wqd qd W   f d d   | j   D } | st  d   n  g  } x-| D]\ \ } } \ } } d } d } y t j d | d t j	 d	 |  } | j t j t j d  | j d    r| j |  n   r9|  j | |  Dd H| } n  Wnn t
 k
 r} z+ | d k	 rh| j   n  | j |  WYd d } ~ Xq| d k	 r| j   n    YqXPqW| d  |   } t j d |   } |  j | | | |  } |  j r1  rt j d    | |  q1t j d  | |  n  | Dd H| | f S)zCreate datagram connection.r   zunexpected address familyNr   r#   z2-tuple is expectedr&   r'   r(   r)   z!getaddrinfo() returned empty listc                sN   g  |  ]D \ } }   r( | d  d k p;  o; | d d k s | | f  q S)r   Nr   r   )r   keyZ	addr_pair)r   remote_addrr   r   
<listcomp>  s   	 	z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationFr<   z@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))NN)r.   rO   OrderedDictr   tupler   r@   r-   r*   Z
SOCK_DGRAMr   items
setsockopt
SOL_SOCKETSO_REUSEADDRr   r   r   rD   rJ   r   rI   ro   r^   r   r   r   )r;   r   r   r   r&   r(   r)   Zaddr_pairs_infoZ
addr_infosidxZaddrr   Zfamr   Zpror0   r   r   Zlocal_addressZremote_addressr/   Zr_addrr   ri   rH   r   r   )r   r   r   create_datagram_endpointe  sv    %$		"	
						z&BaseEventLoop.create_datagram_endpointbacklogr   reuse_addressc             c   s  t  | t  r t d   n  | d k	 s6 | d k	 rs| d k	 rQ t d   n  t t d d  }
 |	 d k r t j d k o t j	 d k }	 n  g  } | d k r d } n  |  j
 | | d	 | d
 t j d d d | Dd H} | s t d   n  d } zPxC| D];} | \ } } } } } y t j | | |  } Wn@ t j k
 rx|  j rqt j d | | | d d n  wYn X| j |  |	 r| j t j t j d  n  | |
 k rt t d  r| j t j t j d  n  y | j |  Wqt k
 r<} z* t | j d | | j j   f   WYd d } ~ XqXqWd } Wd | sox | D] } | j   qXWn  Xn$ | d k rt d   n  | g } t |  |  } x> | D]6 } | j |  | j d  |  j  | | | |  qW|  j rt j! d |  n  | S)zCreate a TCP server bound to host and port.

        Return a Server object which can be used to stop the service.

        This method is a coroutine.
        z*ssl argument must be an SSLContext or NoneNz8host/port and sock can not be specified at the same timer+   r   posixcygwin r&   r'   r(   r)   z!getaddrinfo() returned empty listFz:create_server() failed to create socket.socket(%r, %r, %r)exc_infoTIPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedz%r is serving)"r   rZ   r   r.   getattrr*   r[   namerX   platformr-   r   r   errorr^   r   warningrJ   r   r   r   r,   r   ZIPV6_V6ONLYr   r   r   r   rD   r
   Zlistenr   Z_start_servingr   )r;   r   r1   r2   r&   r)   r/   r   r   r   r+   r8   r   Z	completedZresZafZsocktyper(   Z	canonnameZsar3   rg   r   r   r   create_server  sp    !			

0
		zBaseEventLoop.create_serverc             c   sk   |   } t  j d |   } |  j | | |  } | Dd  H|  j ra t j d | j   | |  n  | | f S)Nr<   z Read pipe %r connected: (%r, %r))r   rI   rq   r^   r   r   fileno)r;   r   rp   ri   rH   r   r   r   r   connect_read_pipe  s    				zBaseEventLoop.connect_read_pipec             c   sk   |   } t  j d |   } |  j | | |  } | Dd  H|  j ra t j d | j   | |  n  | | f S)Nr<   z!Write pipe %r connected: (%r, %r))r   rI   rr   r^   r   r   r   )r;   r   rp   ri   rH   r   r   r   r   connect_write_pipe  s    				z BaseEventLoop.connect_write_pipec             C   s   | g } | d  k	 r/ | j  d t |   n  | d  k	 rd | t j k rd | j  d t |   nL | d  k	 r | j  d t |   n  | d  k	 r | j  d t |   n  t j d j |   d  S)Nzstdin=%szstdout=stderr=%sz	stdout=%sz	stderr=%s )rJ   r   r   r   r   r   r   )r;   r   rt   ru   rv   r   r   r   r   _log_subprocess#  s    	zBaseEventLoop._log_subprocessrt   ru   rv   universal_newlinesrs   Trw   c         	   k   s   t  | t t f  s$ t d   n  | r9 t d   n  | sN t d   n  | d k ri t d   n  |   }
 |  j r d | } |  j | | | |  n  |  j |
 | d | | | | |	  Dd  H} |  j r t j d | | f  n  | |
 f S)	Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truer   zbufsize must be 0zrun shell command %rTz%s: %r)	r   bytesr   r.   r^   r   ry   r   r   )r;   r   cmdrt   ru   rv   r   rs   rw   rx   ri   	debug_logr   r   r   r   subprocess_shell0  s"    		
#	zBaseEventLoop.subprocess_shellc         	   o   s  | r t  d   n  | r* t  d   n  | d k rE t  d   n  | f |	 } x? | D]7 } t | t t f  sY t d t |  j   qY qY W|   } |  j r d | } |  j | | | |  n  |  j	 | | d | | | | |
  Dd  H} |  j rt
 j d | | f  n  | | f S)	Nz universal_newlines must be Falsezshell must be Falser   zbufsize must be 0z8program arguments must be a bytes or text string, not %szexecute program %rFz%s: %r)r.   r   r   r   r   r'   r   r^   r   ry   r   r   )r;   r   Zprogramrt   ru   rv   r   rs   rw   r5   rx   Z
popen_argsargri   r   r   r   r   r   subprocess_execI  s*    		
	zBaseEventLoop.subprocess_execc             C   s>   | d k	 r1 t  |  r1 t d j |    n  | |  _ d S)a  Set handler as the new event loop exception handler.

        If handler is None, the default exception handler will
        be set.

        If handler is a callable object, it should have a
        signature matching '(loop, context)', where 'loop'
        will be a reference to the active event loop, 'context'
        will be a dict object (see `call_exception_handler()`
        documentation for details about context).
        Nz/A callable object or None is expected, got {!r})callabler   r   rW   )r;   Zhandlerr   r   r   set_exception_handlerg  s    z#BaseEventLoop.set_exception_handlerc       	      C   s  | j  d  } | s d } n  | j  d  } | d k	 rT t |  | | j f } n d } | g } x t |  D] } | d k r qp n  | | } | d k r d j t j |   } d } | | j   7} n t |  } | j	 d	 j
 | |   qp Wt j d
 j |  d | d S)a@  Default exception handler.

        This is called when an exception occurs and no exception
        handler is set, and can be called by a custom exception
        handler that wants to defer to the default behavior.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        messagez!Unhandled exception in event loop	exceptionNFZsource_tracebackr   z+Object created at (most recent call last):
z{}: {}
r   >   message	exception)r]   r'   __traceback__sortedr   	tracebackformat_listrstripr   rJ   r   r   r   )	r;   contextr   r   r   Z	log_linesr   valuetbr   r   r   default_exception_handlerx  s&    
		
z'BaseEventLoop.default_exception_handlerc             C   s   |  j  d k rK y |  j |  Wq t k
 rG t j d d d Yq Xn y |  j  |  |  Wns t k
 r } zS y& |  j i d d 6| d 6| d 6 Wn% t k
 r t j d	 d d Yn XWYd d } ~ Xn Xd S)
a  Call the current event loop's exception handler.

        The context argument is a dict containing the following keys:

        - 'message': Error message;
        - 'exception' (optional): Exception object;
        - 'future' (optional): Future instance;
        - 'handle' (optional): Handle instance;
        - 'protocol' (optional): Protocol instance;
        - 'transport' (optional): Transport instance;
        - 'socket' (optional): Socket instance.

        New keys maybe introduced in the future.

        Note: do not overload this method in an event loop subclass.
        For custom exception handling, use the
        `set_exception_handler()` method.
        Nz&Exception in default exception handlerr   Tz$Unhandled error in exception handlerr   r   r   zeException in default exception handler while handling an unexpected error in custom exception handler)rW   r   	Exceptionr   r   )r;   r   r   r   r   r   call_exception_handler  s"    	z$BaseEventLoop.call_exception_handlerc             C   sX   t  | t j  s t d   | j r+ d St  | t j  sD t  |  j j |  d S)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)r   r   r   r@   r   r   rQ   rJ   )r;   r   r   r   r   _add_callback  s
    	zBaseEventLoop._add_callbackc             C   s   |  j  |  |  j   d S)z6Like _add_callback() but called from a signal handler.N)r   rz   )r;   r   r   r   r   _add_callback_signalsafe  s    z&BaseEventLoop._add_callback_signalsafec             C   s   | j  r |  j d 7_ n  d S)z3Notification that a TimerHandle has been cancelled.r   N)rR   rM   )r;   r   r   r   r   _timer_handle_cancelled  s    	z%BaseEventLoop._timer_handle_cancelledc             C   sX  t  |  j  } | t k r |  j | t k r g  } x3 |  j D]( } | j rY d | _ q> | j |  q> Wt j |  | |  _ d |  _ nJ xG |  j r |  j d j r |  j d 8_ t j	 |  j  } d | _ q Wd } |  j
 r d } n5 |  j r#|  j d j } t d | |  j    } n  |  j r| d k r|  j   } |  j j |  } |  j   | } | d k r~t j }	 n	 t j }	 t  |  }
 | d k rt j |	 d | d |
  q(|
 rt j |	 d | d | d |
  q(| d k r(t j |	 d	 | d | d  q(n |  j j |  } |  j |  |  j   |  j } xX |  j r|  j d } | j | k rtPn  t j	 |  j  } d | _ |  j
 j |  qKWt  |  j
  } x t |  D] } |  j
 j   } | j rqn  |  j r@|  j   } | j   |  j   | } | |  j k rJt j d
 t |  |  qJq| j   qWd } d S)zRun one full iteration of the event loop.

        This calls all currently ready callbacks, polls for I/O,
        schedules the resulting callbacks, and finally schedules
        'call_later' callbacks.
        Fr   r   Ng      ?zpoll took %.3f ms: %s eventsg     @@z$poll %.3f ms took %.3f ms: %s eventsz"poll %.3f ms took %.3f ms: timeoutzExecuting %s took %.3f seconds)r   rR   _MIN_SCHEDULED_TIMER_HANDLESrM   %_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr   rJ   r   heapifyheappoprQ   Z_whenmaxrU   r^   Z	_selectorZselectloggingINFODEBUGr   logr|   rV   rangepopleftZ_runr_   r   r   )r;   Zsched_countZnew_scheduledr   Ztimeoutr   r   r{   r   levelZneventZend_timeZntodoir   r   r   r     s    
												
	zBaseEventLoop._run_oncec             C   s   |  j  S)N)r^   )r;   r   r   r   rb   <  s    zBaseEventLoop.get_debugc             C   s   | |  _  d  S)N)r^   )r;   Zenabledr   r   r   	set_debug?  s    zBaseEventLoop.set_debug)9r   r    r!   r=   r?   re   rj   rn   ro   rq   rr   r   ry   rz   r|   r~   r   r   r   rD   ra   r`   rU   r   r   r   r   r   r   r   r   r   r-   r   r   r   r   r*   Z	AF_UNSPECZ
AI_PASSIVEr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r  r   r   r   r   r	      s   
			!	y	Q			L	#0_)#r"   rO   Zconcurrent.futuresr   r   r   r   r[   r*   r   rU   r   rX   r   r   r   r   r   r   r   r   __all__r   r   r   r   r   BaseExceptionr   r4   r6   ZAbstractServerr
   ZAbstractEventLoopr	   r   r   r   r   <module>   s8   		/