???<!-- GIF89;a -->
123123123123
.....................................................................................................................................???<!-- GIF89;a -->
123123123123
.....................................................................................................................................3

  \                 @   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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
lmZ dgZdZdZeeefZ e!e	dZ"d)Z#dd Z$dd Z%dd Z&dd Z'dd Z(dd Z)de	j*dddddZ+e!e	d rRd!d" Z,nd#d" Z,d$d% Z-G d&d' d'ej.Z/G d(d dej0Z1d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   )compat)
coroutines)events)futures)tasks)	coroutine)loggerBaseEventLoopd   g      ?AF_INET6   i  c             C   s0   | j }tt|dd tjr$t|jS t| S d S )N__self__)Z	_callback
isinstancegetattrr   Taskreprr   str)handlecb r   +/usr/lib64/python3.6/asyncio/base_events.py_format_handle?   s    
r   c             C   s(   | t jkrdS | t jkrdS t| S d S )Nz<pipe>z<stdout>)
subprocessPIPESTDOUTr   )fdr   r   r   _format_pipeH   s
    

r   c             C   sL   t tdstdn4y| jtjtjd W n tk
rF   tdY nX d S )NSO_REUSEPORTz)reuse_port not supported by socket moduler   zTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)hasattrsocket
ValueError
setsockopt
SOL_SOCKETr   OSError)sockr   r   r   _set_reuseportQ   s    

r&   c             C   s&   t tdr| d@ tjkS | tjkS d S )NSOCK_NONBLOCK   )r   r    SOCK_STREAM)	sock_typer   r   r   _is_stream_socket\   s    
r+   c             C   s&   t tdr| d@ tjkS | tjkS d S )Nr'   r(   )r   r    
SOCK_DGRAM)r*   r   r   r   _is_dgram_socketh   s    
r-   c             C   sv  t tdsd S |dtjtjhks(| d kr,d S t|r<tj}nt|rLtj}nd S |d kr^d}nVt|trv|dkrvd}n>t|tr|dkrd}n&yt	|}W n t
tfk
r   d S X |tjkrtjg}tr|jtj n|g}t| tr| jd} d| kr d S xp|D ]h}yJtj||  tr@|tjkr@|||d| |ddffS |||d| |ffS W n tk
rj   Y nX qW d S )N	inet_ptonr        Zidna%)r   r    IPPROTO_TCPZIPPROTO_UDPr+   r-   r   bytesr   int	TypeErrorr!   	AF_UNSPECAF_INET	_HAS_IPv6appendr   decoder.   r$   )hostportfamilytypeprotoZafsafr   r   r   _ipaddr_infop   sL    





rA   )r=   r>   r?   flagsc      
      C   sZ   | d d \}}t |||||}|d k	r@|j }	|	j|g |	S |j||||||dS d S )N   )r=   r>   r?   rB   )rA   create_future
set_resultgetaddrinfo)
addressr=   r>   r?   rB   loopr;   r<   infofutr   r   r   _ensure_resolved   s    rK   TCP_NODELAYc             C   s>   | j tjtjhkr:t| jr:| jtjkr:| jtjtj	d d S )Nr   )
r=   r    r7   r   r+   r>   r?   r2   r"   rL   )r%   r   r   r   _set_nodelay   s    
rM   c             C   s   d S )Nr   )r%   r   r   r   rM      s    c             C   s.   | j }t|tr t|t r d S | jj  d S )N)Z
_exceptionr   BaseException	Exception_loopstop)rJ   excr   r   r   _run_until_complete_cb   s
    
rS   c               @   sH   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 )Serverc             C   s   || _ || _d| _g | _d S )Nr   )rP   sockets_active_count_waiters)selfrH   rU   r   r   r   __init__   s    zServer.__init__c             C   s   d| j j| jf S )Nz<%s sockets=%r>)	__class____name__rU   )rX   r   r   r   __repr__   s    zServer.__repr__c             C   s    | j d k	st|  jd7  _d S )Nr   )rU   AssertionErrorrV   )rX   r   r   r   _attach   s    zServer._attachc             C   s<   | j dkst|  j d8  _ | j dkr8| jd kr8| j  d S )Nr   r   )rV   r]   rU   _wakeup)rX   r   r   r   _detach   s    zServer._detachc             C   sH   | j }|d krd S d | _ x|D ]}| jj| qW | jdkrD| j  d S )Nr   )rU   rP   Z_stop_servingrV   r_   )rX   rU   r%   r   r   r   close   s    

zServer.closec             C   s0   | j }d | _ x|D ]}|j s|j| qW d S )N)rW   donerE   )rX   waiterswaiterr   r   r   r_      s
    
zServer._wakeupc             c   s<   | j d ks| jd krd S | jj }| jj| |E d H  d S )N)rU   rW   rP   rD   r9   )rX   rd   r   r   r   wait_closed   s
    
zServer.wait_closedN)r[   
__module____qualname__rY   r\   r^   r`   ra   r_   r   re   r   r   r   r   rT      s   
rT   c            
   @   s  e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZddddddZ	ddddddddZ
dddZdddZdddZedddZdd Zd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/d0 Zd1d2 Zej rd3d4 Zd5d6 Zd7d8 Zd9d: Z d;d< Z!d=d> Z"d?d@ Z#dAdB Z$dCdD Z%dEdF Z&dGdH Z'dIdJ Z(dKdL Z)dMdMdMdMdNdOdPZ*ddQdRZ+edddMdMdMddddSdTdUZ,eddVdWZ-eddMdMdMdddddXdYdZZ.ed[d\ Z/ede0j1e0j2dd]dddd^d_d`Z3eddadbdcZ4eddde Z5edfdg Z6dhdi Z7ee8j9e8j9e8j9ddjdMdkdldmZ:ee8j9e8j9e8j9dddMdkdndoZ;dpdq Z<drds Z=dtdu Z>dvdw Z?dxdy Z@dzd{ ZAd|d} ZBd~d ZCdd ZDdd ZEdd ZFdS )r
   c             C   s   d| _ d| _d| _tj | _g | _d | _d| _d | _	t
jdj| _d | _| jtjj odttjjd d| _d | _d | _d| _ttdrtj | _nd | _d| _d S )Nr   F	monotonicZPYTHONASYNCIODEBUGg?get_asyncgen_hooks) _timer_cancelled_count_closed	_stoppingcollectionsdeque_ready
_scheduled_default_executorZ_internal_fds
_thread_idtimeZget_clock_infoZ
resolution_clock_resolution_exception_handler	set_debugsysrB   ignore_environmentboolosenvirongetslow_callback_duration_current_handle_task_factory_coroutine_wrapper_setr   weakrefWeakSet
_asyncgens_asyncgens_shutdown_called)rX   r   r   r   rY      s(    

zBaseEventLoop.__init__c             C   s    d| j j| j | j | j f S )Nz"<%s running=%s closed=%s debug=%s>)rZ   r[   
is_running	is_closed	get_debug)rX   r   r   r   r\      s    zBaseEventLoop.__repr__c             C   s   t j| dS )z,Create a Future object attached to the loop.)rH   )r   ZFuture)rX   r   r   r   rD   %  s    zBaseEventLoop.create_futurec             C   s@   | j   | jdkr0tj|| d}|jr<|jd= n| j| |}|S )zDSchedule a coroutine object.

        Return a task object.
        N)rH   r   )_check_closedr   r   r   _source_traceback)rX   coroZtaskr   r   r   create_task)  s    

zBaseEventLoop.create_taskc             C   s$   |dk	rt | rtd|| _dS )aw  Set a task factory that will be used by loop.create_task().

        If factory is None the default task factory will be set.

        If factory is a callable, it should have a signature matching
        '(loop, coro)', where 'loop' will be a reference to the active
        event loop, 'coro' will be a coroutine object.  The callable
        must return a Future.
        Nz'task factory must be a callable or None)callabler5   r   )rX   factoryr   r   r   set_task_factory7  s    
zBaseEventLoop.set_task_factoryc             C   s   | j S )z<Return a task factory, or None if the default one is in use.)r   )rX   r   r   r   get_task_factoryE  s    zBaseEventLoop.get_task_factoryN)extraserverc            C   s   t dS )zCreate socket transport.N)NotImplementedError)rX   r%   protocolrd   r   r   r   r   r   _make_socket_transportI  s    z$BaseEventLoop._make_socket_transportF)server_sideserver_hostnamer   r   c      	      C   s   t dS )zCreate SSL transport.N)r   )	rX   Zrawsockr   
sslcontextrd   r   r   r   r   r   r   r   _make_ssl_transportN  s    z!BaseEventLoop._make_ssl_transportc             C   s   t dS )zCreate datagram transport.N)r   )rX   r%   r   rG   rd   r   r   r   r   _make_datagram_transportT  s    z&BaseEventLoop._make_datagram_transportc             C   s   t dS )zCreate read pipe transport.N)r   )rX   piper   rd   r   r   r   r   _make_read_pipe_transportY  s    z'BaseEventLoop._make_read_pipe_transportc             C   s   t dS )zCreate write pipe transport.N)r   )rX   r   r   rd   r   r   r   r   _make_write_pipe_transport^  s    z(BaseEventLoop._make_write_pipe_transportc	       
      K   s   t dS )zCreate subprocess transport.N)r   )
rX   r   argsshellstdinstdoutstderrbufsizer   kwargsr   r   r   _make_subprocess_transportc  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)r   )rX   r   r   r   _write_to_selfj  s    zBaseEventLoop._write_to_selfc             C   s   t dS )zProcess selector events.N)r   )rX   
event_listr   r   r   _process_eventss  s    zBaseEventLoop._process_eventsc             C   s   | j rtdd S )NzEvent loop is closed)rk   RuntimeError)rX   r   r   r   r   w  s    zBaseEventLoop._check_closedc             C   s*   | j j| | j s&| j| j|j  d S )N)r   discardr   call_soon_threadsafer   aclose)rX   agenr   r   r   _asyncgen_finalizer_hook{  s    z&BaseEventLoop._asyncgen_finalizer_hookc             C   s,   | j rtjdj|t| d | jj| d S )NzNasynchronous generator {!r} was scheduled after loop.shutdown_asyncgens() call)source)r   warningswarnformatResourceWarningr   add)rX   r   r   r   r   _asyncgen_firstiter_hook  s    
z&BaseEventLoop._asyncgen_firstiter_hookc             c   s   d| _ | jdkst| j r dS t| j}| jj  tjdd |D d| d}|E dH }x8t||D ]*\}}t|t	rf| j
dj|||d qfW dS )z,Shutdown all active asynchronous generators.TNc             S   s   g | ]}|j  qS r   )r   ).0Zagr   r   r   
<listcomp>  s    z4BaseEventLoop.shutdown_asyncgens.<locals>.<listcomp>)Zreturn_exceptionsrH   z?an error occurred during closing of asynchronous generator {!r})message	exceptionZasyncgen)r   r   lenlistclearr   gatherzipr   rO   call_exception_handlerr   )rX   Zclosing_agensZshutdown_coroZresultsresultr   r   r   r   shutdown_asyncgens  s"    




z BaseEventLoop.shutdown_asyncgensc             C   s   | j   | j rtdtj dk	r,td| j| j tj | _	| j
dk	rftj }tj| j| jd z$tj|  x| j  | jrtP qtW W dd| _d| _	tjd | jd | j
dk	rtj|  X dS )zRun until stop() is called.z"This event loop is already runningNz7Cannot run the event loop while another loop is running)	firstiter	finalizerF)r   r   r   r   Z_get_running_loop_set_coroutine_wrapper_debug	threading	get_identrr   r   rw   ri   set_asyncgen_hooksr   r   Z_set_running_loop	_run_oncerl   )rX   Zold_agen_hooksr   r   r   run_forever  s0    







zBaseEventLoop.run_foreverc             C   s   | j   tj| }tj|| d}|r,d|_|jt z>y| j  W n,   |rj|j	 rj|j
  rj|j   Y nX W d|jt X |j	 std|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.
        )rH   FNz+Event loop stopped before Future completed.)r   r   Zisfuturer   Zensure_futureZ_log_destroy_pendingZadd_done_callbackrS   r   rb   Z	cancelledr   Zremove_done_callbackr   r   )rX   ZfutureZnew_taskr   r   r   run_until_complete  s     
z BaseEventLoop.run_until_completec             C   s
   d| _ dS )zStop running the event loop.

        Every callback already scheduled will still run.  This simply informs
        run_forever to stop looping after a complete iteration.
        TN)rl   )rX   r   r   r   rQ     s    zBaseEventLoop.stopc             C   sj   | j  rtd| jrdS | jr,tjd|  d| _| jj  | jj  | j	}|dk	rfd| _	|j
dd 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 %rTF)wait)r   r   rk   r   r	   debugro   r   rp   rq   Zshutdown)rX   executorr   r   r   ra     s    

zBaseEventLoop.closec             C   s   | j S )z*Returns True if the event loop was closed.)rk   )rX   r   r   r   r     s    zBaseEventLoop.is_closedc             C   s0   | j  s,tjd|  t| d | j s,| j  d S )Nzunclosed event loop %r)r   )r   r   r   r   r   ra   )rX   r   r   r   __del__  s
    zBaseEventLoop.__del__c             C   s
   | j dk	S )z*Returns True if the event loop is running.N)rr   )rX   r   r   r   r     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.
        )rs   rh   )rX   r   r   r   rs     s    zBaseEventLoop.timec             G   s,   | j | j | |f| }|jr(|jd= |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   r   )call_atrs   r   )rX   Zdelaycallbackr   timerr   r   r   
call_later   s    zBaseEventLoop.call_laterc             G   sX   | j   | jr"| j  | j|d tj|||| }|jr@|jd= tj| j	| d|_	|S )z|Like call_later(), but uses an absolute time.

        Absolute time corresponds to the event loop's time() method.
        r   r   Tr   )
r   r   _check_thread_check_callbackr   TimerHandler   heapqheappushrp   )rX   whenr   r   r   r   r   r   r   5  s    zBaseEventLoop.call_atc             G   s@   | j   | jr"| j  | j|d | j||}|jr<|jd= |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.
        	call_soonr   r   )r   r   r   r   
_call_soonr   )rX   r   r   r   r   r   r   r   E  s    
zBaseEventLoop.call_soonc             C   s>   t j|st j|r"tdj|t|s:tdj||d S )Nz#coroutines cannot be used with {}()z0a callable object was expected by {}(), got {!r})r   ZiscoroutineZiscoroutinefunctionr5   r   r   )rX   r   methodr   r   r   r   X  s    

zBaseEventLoop._check_callbackc             C   s,   t j||| }|jr|jd= | jj| |S )Nr   r   )r   Handler   ro   r9   )rX   r   r   r   r   r   r   r   c  s
    zBaseEventLoop._call_soonc             C   s,   | j dkrdS tj }|| j kr(tddS )ao  Check that the current thread is the thread running the 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)rr   r   r   r   )rX   Z	thread_idr   r   r   r   j  s    	

zBaseEventLoop._check_threadc             G   s@   | j   | jr| j|d | j||}|jr4|jd= | j  |S )z"Like call_soon(), but thread-safe.r   r   r   )r   r   r   r   r   r   )rX   r   r   r   r   r   r   r   {  s    z"BaseEventLoop.call_soon_threadsafec             G   sZ   | j   | jr| j|d |d kr@| j}|d kr@tjj }|| _tj|j|f| | dS )Nrun_in_executor)rH   )	r   r   r   rq   
concurrentr   ZThreadPoolExecutorZwrap_futureZsubmit)rX   r   funcr   r   r   r   r     s    
zBaseEventLoop.run_in_executorc             C   s
   || _ d S )N)rq   )rX   r   r   r   r   set_default_executor  s    z"BaseEventLoop.set_default_executorc             C   s   d||f g}|r |j d|  |r2|j d|  |rD|j d|  |rV|j d|  dj|}tjd| | j }tj||||||}	| j | }
d||
d	 |	f }|
| jkrt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     @@)	r9   joinr	   r   rs   r    rF   r}   rI   )rX   r;   r<   r=   r>   r?   rB   msgt0Zaddrinfodtr   r   r   _getaddrinfo_debug  s(    


z BaseEventLoop._getaddrinfo_debugr   )r=   r>   r?   rB   c         	   C   s>   | j r | jd | j||||||S | jd tj||||||S d S )N)r   r   r   r    rF   )rX   r;   r<   r=   r>   r?   rB   r   r   r   rF     s
    

zBaseEventLoop.getaddrinfoc             C   s   | j d tj||S )N)r   r    getnameinfo)rX   ZsockaddrrB   r   r   r   r     s    zBaseEventLoop.getnameinfo)sslr=   r?   rB   r%   
local_addrr   c            #   s  |
dk	r| rt d|
dkr2|r2|s.t d|}
|dk	sD|dk	r|dk	rTt dt||f|tj||| d}|g}|	dk	rt|	|tj||| d}|j| nd}tj|| dE dH  |j }|std|dk	r|j }|stdg }x|D ]B\}}}}}ytj|||d}|j	d	 |dk	rx|D ]j\}}}}}y|j
| P W nH tk
r } z*t|jd
j||jj }|j| W Y dd}~X nX q.W |j  d}w| jrtjd|| | j||E dH  W n^ tk
r } z"|dk	r|j  |j| W Y dd}~X q   |dk	r,|j   Y qX P qW t|dkrR|d nJt|d  t fdd|D r~|d tdjdjdd |D n,|dkrt dt|jst dj|| j||||
E dH \}}| jr
|jd}tjd||||| ||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 time)r=   r>   r?   rB   rH   )rH   z!getaddrinfo() returned empty list)r=   r>   r?   Fz2error while attempting to bind on address {!r}: {}zconnect %r to %rr   r   c             3   s   | ]}t | kV  qd S )N)r   )r   rR   )modelr   r   	<genexpr>  s    z2BaseEventLoop.create_connection.<locals>.<genexpr>zMultiple exceptions: {}z, c             s   s   | ]}t |V  qd S )N)r   )r   rR   r   r   r   r   #  s    z5host and port was not specified and no sock specifiedz&A Stream Socket was expected, got {!r}r    z%r connected to %s:%r: (%r, %r))r!   rK   r    r)   r9   r   r   r   r$   setblockingbinderrnor   strerrorlowerra   r   r	   r   sock_connectr   r   allr   r+   r>   _create_connection_transportget_extra_info)rX   protocol_factoryr;   r<   r   r=   r?   rB   r%   r   r   f1fsf2infosZladdr_infos
exceptionsr>   ZcnamerG   _ZladdrrR   	transportr   r   )r   r   create_connection  s    





"




zBaseEventLoop.create_connectionc       
   	   c   s   |j d | }| j }|rFt|tr*d n|}| j||||||d}	n| j|||}	y|E d H  W n   |	j   Y nX |	|fS )NF)r   r   )r   rD   r   ry   r   r   ra   )
rX   r%   r   r   r   r   r   rd   r   r   r   r   r   r   =  s    
z*BaseEventLoop._create_connection_transport)r=   r?   rB   reuse_address
reuse_portallow_broadcastr%   c            #   sZ  |
dk	rt |
js tdj|
 s@s@|s@|s@|s@|s@|s@|	r~t ||||||	d}djdd |j D }tdj||
jd d}nL ps|d	krtd
||fdff}ntj	 }xd	 fdffD ]\}}|dk	rt
|t rt|dkstdt||tj||| dE dH }|s.tdxB|D ]:\}}}}}||f}||kr`ddg||< ||| |< q4W qW  fdd|j D }|stdg }|dkrtjdkotjdk}x|D ]\\}}\}}d}
d}ytj|tj|d}
|r|
jtjtjd |rt|
 |	r4|
jtjtjd |
jd  rN|
j| rj| j|
|E dH  |}W n^ tk
r } z"|
dk	r|
j  |j| W Y dd}~X n"   |
dk	r|
j   Y nX P qW |d	 | }| j }| j |
|||}| j!r, rt"j#d || nt"j$d|| y|E dH  W n   |j   Y nX ||fS )zCreate datagram connection.Nz#A UDP Socket was expected, got {!r})r   remote_addrr=   r?   rB   r   r   r   z, c             s   s"   | ]\}}|rd j ||V  qdS )z{}={}N)r   )r   kvr   r   r   r   i  s    z9BaseEventLoop.create_datagram_endpoint.<locals>.<genexpr>zNsocket modifier keyword arguments can not be used when sock is specified. ({})Fr   zunexpected address familyr   rC   z2-tuple is expected)r=   r>   r?   rB   rH   z!getaddrinfo() returned empty listc                s8   g | ]0\}} r|d  dkp*o*|d dks||fqS )r   Nr   r   )r   keyZ	addr_pair)r   r  r   r   r     s    z:BaseEventLoop.create_datagram_endpoint.<locals>.<listcomp>zcan not get address informationposixcygwin)r=   r>   r?   z@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))NN)%r-   r>   r!   r   dictr   itemsr   rm   OrderedDictr   tupler   r]   rK   r    r,   r$   rz   namerw   platformr"   r#   SO_REUSEADDRr&   ZSO_BROADCASTr   r   ra   r9   rD   r   r   r	   rI   r   )rX   r   r   r  r=   r?   rB   r   r   r   r%   ZoptsZproblemsZr_addrZaddr_pairs_infoZ
addr_infosidxZaddrr   Zfamr   ZprorG   r  r   Zlocal_addressZremote_addressrR   r   rd   r   r   )r   r  r   create_datagram_endpointU  s    








z&BaseEventLoop.create_datagram_endpointc             c   s4   t ||f|tj|| dE d H }|s0tdj||S )N)r=   r>   rB   rH   z%getaddrinfo({!r}) returned empty list)rK   r    r)   r$   r   )rX   r;   r<   r=   rB   r   r   r   r   _create_server_getaddrinfo  s    
z(BaseEventLoop._create_server_getaddrinfor   )r=   rB   r%   backlogr   r   r   c             #   s  t |trtd|dk	s$dk	r|dk	r4td|	dkrPtjdkoNtjdk}	g }|dkrddg}n$t |ts|t |t	j
 r|g}n|} fdd|D }tj|d	iE dH }ttjj|}d
}z x|D ]
}|\}}}}}ytj|||}W n6 tjk
r2   jr,tjd|||dd wY nX |j| |	rV|jtjtjd |
rdt| tr|tjkrttdr|jtjtjd y|j | W q t!k
r } z t!|j"d||j#j$ f W Y dd}~X qX qW d}W d|sx|D ]}|j%  qW X n2|dkr"tdt&|j's<tdj(||g}t)|}x4|D ],}|j*| |j+d
 j,||||| qRW jrtj-d| |S )a1  Create a TCP server.

        The host parameter can be a string, in that case the TCP server is bound
        to host and port.

        The host parameter can also be a sequence of strings and in that case
        the TCP server is bound to all hosts of the sequence. If a host
        appears multiple times (possibly indirectly e.g. when hostnames
        resolve to the same IP address), the server is only bound once to that
        host.

        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  r0   c                s   g | ]}j | d qS ))r=   rB   )r  )r   r;   )r=   rB   r<   rX   r   r   r     s   z/BaseEventLoop.create_server.<locals>.<listcomp>rH   Fz:create_server() failed to create socket.socket(%r, %r, %r)T)exc_infoIPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedz&A Stream Socket was expected, got {!r}z%r is serving).r   ry   r5   r!   rz   r  rw   r  r   rm   Iterabler   r   set	itertoolschainfrom_iterabler    errorr   r	   warningr9   r"   r#   r  r&   r8   r   r   r  ZIPV6_V6ONLYr   r$   r   r   r   ra   r+   r>   r   rT   Zlistenr   Z_start_servingrI   )rX   r   r;   r<   r=   rB   r%   r  r   r   r   rU   Zhostsr   r   Z	completedresr@   Zsocktyper?   Z	canonnameZsaerrr   r   )r=   rB   r<   rX   r   create_server  s    


(





zBaseEventLoop.create_server)r   c            c   s^   t |jstdj|| j|||dddE dH \}}| jrV|jd}tjd||| ||fS )a  Handle an accepted connection.

        This is used by servers that accept connections outside of
        asyncio but that use asyncio to handle connections.

        This method is a coroutine.  When completed, the coroutine
        returns a (transport, protocol) pair.
        z&A Stream Socket was expected, got {!r}r0   T)r   Nr    z%r handled: (%r, %r))	r+   r>   r!   r   r   r   r   r	   r   )rX   r   r%   r   r   r   r   r   r   connect_accepted_socketA  s    


z%BaseEventLoop.connect_accepted_socketc             c   sd   | }| j  }| j|||}y|E d H  W n   |j   Y nX | jr\tjd|j || ||fS )Nz Read pipe %r connected: (%r, %r))rD   r   ra   r   r	   r   fileno)rX   r   r   r   rd   r   r   r   r   connect_read_pipeX  s    zBaseEventLoop.connect_read_pipec             c   sd   | }| j  }| j|||}y|E d H  W n   |j   Y nX | jr\tjd|j || ||fS )Nz!Write pipe %r connected: (%r, %r))rD   r   ra   r   r	   r   r  )rX   r   r   r   rd   r   r   r   r   connect_write_pipei  s    z BaseEventLoop.connect_write_pipec             C   s   |g}|d k	r |j dt|  |d k	rF|tjkrF|j dt|  n4|d k	r`|j dt|  |d k	rz|j dt|  tjdj| d S )Nzstdin=%szstdout=stderr=%sz	stdout=%sz	stderr=%s )r9   r   r   r   r	   r   r   )rX   r   r   r   r   rI   r   r   r   _log_subprocessz  s    zBaseEventLoop._log_subprocessT)r   r   r   universal_newlinesr   r   c            k   s   t |ttfstd|r"td|s.td|dkr>td| }
d }| jrfd| }| j|||| | j|
|d||||f|	E d H }| jr|d k	rtjd|| ||
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   r3   r   r!   r   r#  r   r	   rI   )rX   r   cmdr   r   r   r$  r   r   r   r   	debug_logr   r   r   r   subprocess_shell  s$    zBaseEventLoop.subprocess_shellc            o   s   |rt d|rt d|dkr(t d|f|	 }x,|D ]$}t|ttfs8tdt|j q8W | }d }| jrd| }| j|||| | j	||d||||f|
E d H }| jr|d k	rt
jd|| ||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   r3   r5   r>   r[   r   r#  r   r	   rI   )rX   r   Zprogramr   r   r   r$  r   r   r   r   Z
popen_argsargr   r&  r   r   r   r   subprocess_exec  s,    

zBaseEventLoop.subprocess_execc             C   s   | j S )zKReturn an exception handler, or None if the default one is in use.
        )ru   )rX   r   r   r   get_exception_handler  s    z#BaseEventLoop.get_exception_handlerc             C   s*   |dk	r t | r tdj||| _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})r   r5   r   ru   )rX   Zhandlerr   r   r   set_exception_handler  s    z#BaseEventLoop.set_exception_handlerc       	      C   s  |j d}|sd}|j d}|dk	r6t|||jf}nd}d|kr`| jdk	r`| jjr`| jj|d< |g}xt|D ]}|dkr~qp|| }|dkrdjtj|}d	}||j	 7 }n2|dkrdjtj|}d
}||j	 7 }nt
|}|jdj|| qpW tjdj||d dS )aE  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.

        This default handler logs the error message and other
        context-dependent information.  In debug mode, a truncated
        stack trace is also appended showing where the given object
        (e.g. a handle or future or task) was created, if any.

        The context parameter has the same meaning as in
        `call_exception_handler()`.
        r   z!Unhandled exception in event loopr   NFZsource_tracebackZhandle_tracebackr0   z+Object created at (most recent call last):
z+Handle created at (most recent call last):
z{}: {}
)r  >   r   r   )r|   r>   __traceback__r~   r   sortedr   	tracebackformat_listrstripr   r9   r   r	   r  )	rX   contextr   r   r  Z	log_linesr  valuetbr   r   r   default_exception_handler  s6    


z'BaseEventLoop.default_exception_handlerc             C   s   | j dkr>y| j| W q tk
r:   tjddd Y qX nny| j | | W n\ tk
r } z@y| jd||d W n" tk
r   tjddd Y nX W Y dd}~X nX d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;
        - 'asyncgen' (optional): Asynchronous generator that caused
                                 the exception.

        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 handlerT)r  z$Unhandled error in exception handler)r   r   r2  zeException in default exception handler while handling an unexpected error in custom exception handler)ru   r5  rO   r	   r  )rX   r2  rR   r   r   r   r     s"    
z$BaseEventLoop.call_exception_handlerc             C   s@   t |tjstd|jrdS t |tj s0t| jj| dS )z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)r   r   r   r]   
_cancelledr   ro   r9   )rX   r   r   r   r   _add_callback9  s
    zBaseEventLoop._add_callbackc             C   s   | j | | j  dS )z6Like _add_callback() but called from a signal handler.N)r7  r   )rX   r   r   r   r   _add_callback_signalsafeA  s    
z&BaseEventLoop._add_callback_signalsafec             C   s   |j r|  jd7  _dS )z3Notification that a TimerHandle has been cancelled.r   N)rp   rj   )rX   r   r   r   r   _timer_handle_cancelledF  s    z%BaseEventLoop._timer_handle_cancelledc             C   s  t | j}|tkrd| j| tkrdg }x&| jD ]}|jr>d|_q,|j| q,W tj| || _d| _n8x6| jr| jd jr|  jd8  _tj	| j}d|_qfW d}| j
s| jrd}n*| jr| jd j}ttd|| j  t}| jo|dkr| j }| jj|}| j | }|dkrtj}	ntj}	t |}
|dkrLtj|	d|d |
 nD|
rntj|	d|d |d |
 n"|dkrtj|	d	|d |d  n| jj|}| j| | j | j }xD| jr| jd }|j|krP tj	| j}d|_| j
j| qW t | j
}xt|D ]|}| j
j }|jr*q| jrzD|| _| j }|j  | j | }|| jkrttj d
t!|| W dd| _X n|j  qW d}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   rp   _MIN_SCHEDULED_TIMER_HANDLESrj   %_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr6  r9   r   heapifyheappopro   rl   Z_whenminmaxrs   MAXIMUM_SELECT_TIMEOUTr   Z	_selectorZselectloggingINFODEBUGr	   logr   rt   rangepopleftr~   Z_runr}   r  r   )rX   Zsched_countZnew_scheduledr   Ztimeoutr   r   r   r   levelZneventZend_timeZntodoir   r   r   r   K  s    











zBaseEventLoop._run_oncec             C   s   yt j}t j}W n tk
r$   d S X t|}| j|kr<d S tj}| }|rz|d |fkrjtj	d| t
 q|| d| _n,|d |fkrtj	d| t
 n|d  d| _d S )Nz[loop.set_debug(True): cannot set debug coroutine wrapper; another wrapper is already set %rTzWloop.set_debug(False): cannot unset debug coroutine wrapper; another wrapper was set %rF)rw   set_coroutine_wrapperget_coroutine_wrapperAttributeErrorry   r   r   Zdebug_wrapperr   r   RuntimeWarning)rX   enabledZset_wrapperZget_wrapperwrapperZcurrent_wrapperr   r   r   r     s.    

z$BaseEventLoop._set_coroutine_wrapperc             C   s   | j S )N)r   )rX   r   r   r   r     s    zBaseEventLoop.get_debugc             C   s   || _ | j r| j| d S )N)r   r   r   )rX   rM  r   r   r   rv     s    zBaseEventLoop.set_debug)N)N)NNN)NN)NN)N)r   )NN)F)NN)NN)Gr[   rf   rg   rY   r\   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rQ   ra   r   r   ZPY34r   r   rs   r   r   r   r   r   r   r   r   r   r   rF   r   r   r   r  r  r    r6   Z
AI_PASSIVEr  r  r   r!  r#  r   r   r'  r)  r*  r+  r5  r   r7  r8  r9  r   r   r   rv   r   r   r   r   r
      s   !
 
 
		%	

 u	`12c!iQ )2__doc__rm   Zconcurrent.futuresr   r   inspectr  rA  rz   r    r   r   rs   r/  rw   r   r   r0   r   r   r   r   r   r   rD  r	   __all__r:  r;  BrokenPipeErrorConnectionResetErrorConnectionAbortedErrorZ_FATAL_ERROR_IGNOREr   r8   r@  r   r   r&   r+   r-   rA   r)   rK   rM   rS   ZAbstractServerrT   ZAbstractEventLoopr
   r   r   r   r   <module>   sV   
		;

/