3 \@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZd gZd Zd ZeeefZ e!e dZ"d)Z#ddZ$ddZ%ddZ&ddZ'ddZ(ddZ)de j*dddddZ+e!e d rRd!d"Z,nd#d"Z,d$d%Z-Gd&d'd'ej.Z/Gd(d d ej0Z1dS)*aBase 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 BaseEventLoopdg?AF_INET6icCs0|j}tt|ddtjr$t|jSt|SdS)N__self__)Z _callback isinstancegetattrrTaskreprrstr)handlecbr#/usr/lib64/python3.6/base_events.py_format_handle?s rcCs(|tjkrdS|tjkrdSt|SdS)Nzz) subprocessPIPESTDOUTr)fdrrr _format_pipeHs   rc CsLttdstdn4y|jtjtjdWntk rFtdYnXdS)N SO_REUSEPORTz)reuse_port not supported by socket modulerzTreuse_port not supported by socket module, SO_REUSEPORT defined but not implemented.)hasattrsocket ValueError setsockopt SOL_SOCKETrOSError)sockrrr_set_reuseportQs   r&cCs&ttdr|d@tjkS|tjkSdS)N SOCK_NONBLOCK)rr SOCK_STREAM) sock_typerrr_is_stream_socket\s r+cCs&ttdr|d@tjkS|tjkSdS)Nr'r()rr SOCK_DGRAM)r*rrr_is_dgram_sockeths r-cCsvttdsdS|dtjtjhks(|dkr,dSt|rt|tr|dkrd}n&y t |}Wnt t fk rdSX|tj krtj g}tr|jtjn|g}t|tr|jd}d|krdSxp|D]h}yJtj||tr@|tjkr@|||d||ddffS|||d||ffSWntk rjYnXqWdS)N inet_ptonrZidna%)rr IPPROTO_TCPZ IPPROTO_UDPr+r-rbytesrint TypeErrorr! AF_UNSPECAF_INET _HAS_IPv6appendr decoder.r$)hostportfamilytypeprotoZafsafrrr _ipaddr_infopsL         rA)r=r>r?flagsc CsZ|dd\}}t|||||}|dk r@|j} | j|g| S|j||||||dSdS)N)r=r>r?rB)rA create_future set_result getaddrinfo) addressr=r>r?rBloopr;r<infofutrrr_ensure_resolveds  rK TCP_NODELAYcCs>|jtjtjhkr:t|jr:|jtjkr:|jtjtj ddS)Nr) r=r r7r r+r>r?r2r"rL)r%rrr _set_nodelays  rMcCsdS)Nr)r%rrrrMscCs.|j}t|tr t|t r dS|jjdS)N)Z _exceptionr BaseException Exception_loopstop)rJexcrrr_run_until_complete_cbs   rSc@sHeZdZddZddZddZddZd d Zd d Ze d dZ dS)ServercCs||_||_d|_g|_dS)Nr)rPsockets _active_count_waiters)selfrHrUrrr__init__szServer.__init__cCsd|jj|jfS)Nz<%s sockets=%r>) __class____name__rU)rXrrr__repr__szServer.__repr__cCs |jdk st|jd7_dS)Nr)rUAssertionErrorrV)rXrrr_attachszServer._attachcCs<|jdkst|jd8_|jdkr8|jdkr8|jdS)Nrr)rVr]rU_wakeup)rXrrr_detachszServer._detachcCsH|j}|dkrdSd|_x|D]}|jj|qW|jdkrD|jdS)Nr)rUrPZ _stop_servingrVr_)rXrUr%rrrcloses  z Server.closecCs0|j}d|_x|D]}|js|j|qWdS)N)rWdonerE)rXwaiterswaiterrrrr_s  zServer._wakeupccs<|jdks|jdkrdS|jj}|jj||EdHdS)N)rUrWrPrDr9)rXrdrrr wait_closeds   zServer.wait_closedN) r[ __module__ __qualname__rYr\r^r`rar_rrerrrrrTs rTc @seZdZddZddZddZddZd d Zd d Zdd d dddZ ddd d d dddZ dddZ dddZ dddZ edddZddZdd Zd!d"Zd#d$Zd%d&Zed'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zejrd3d4Zd5d6Zd7d8Zd9d:Z d;d<Z!d=d>Z"d?d@Z#dAdBZ$dCdDZ%dEdFZ&dGdHZ'dIdJZ(dKdLZ)dMdMdMdMdNdOdPZ*ddQdRZ+edd dMdMdMd d d dSdTdUZ,eddVdWZ-eddMdMdMd d d d dXdYdZZ.ed[d\Z/ede0j1e0j2d d]d d d d^d_d`Z3ed dadbdcZ4edddeZ5edfdgZ6dhdiZ7ee8j9e8j9e8j9ddjdMdkdldmZ:ee8j9e8j9e8j9dddMdkdndoZ;dpdqZdvdwZ?dxdyZ@dzd{ZAd|d}ZBd~dZCddZDddZEddZFd S)r cCsd|_d|_d|_tj|_g|_d|_d|_d|_ t j dj |_ d|_|jtjj odttjjdd|_d|_d|_d|_ttdrtj|_nd|_d|_dS)NrF monotonicZPYTHONASYNCIODEBUGg?get_asyncgen_hooks) _timer_cancelled_count_closed _stopping collectionsdeque_ready _scheduled_default_executorZ _internal_fds _thread_idtimeZget_clock_infoZ resolution_clock_resolution_exception_handler set_debugsysrBignore_environmentboolosenvirongetslow_callback_duration_current_handle _task_factory_coroutine_wrapper_setrweakrefWeakSet _asyncgens_asyncgens_shutdown_called)rXrrrrYs(   zBaseEventLoop.__init__cCs d|jj|j|j|jfS)Nz"<%s running=%s closed=%s debug=%s>)rZr[ is_running is_closed get_debug)rXrrrr\ s zBaseEventLoop.__repr__cCs tj|dS)z,Create a Future object attached to the loop.)rH)rZFuture)rXrrrrD%szBaseEventLoop.create_futurecCs@|j|jdkr0tj||d}|jr<|jd=n |j||}|S)zDSchedule a coroutine object. Return a task object. N)rHr) _check_closedrrr_source_traceback)rXcoroZtaskrrr create_task)s   zBaseEventLoop.create_taskcCs$|dk rt| rtd||_dS)awSet 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)callabler5r)rXfactoryrrrset_task_factory7s zBaseEventLoop.set_task_factorycCs|jS)zsz4BaseEventLoop.shutdown_asyncgens..)Zreturn_exceptionsrHz?an error occurred during closing of asynchronous generator {!r})message exceptionZasyncgen) rrlenlistclearrgatherziprrOcall_exception_handlerr)rXZ closing_agensZ shutdown_cororesultsresultrrrrshutdown_asyncgenss"      z BaseEventLoop.shutdown_asyncgensc Cs|j|jrtdtjdk r,td|j|jtj|_ |j dk rft j }t j |j|jdz$tj|x|j|jrtPqtWWdd|_d|_ tjd|jd|j dk rt j |XdS)zRun until stop() is called.z"This event loop is already runningNz7Cannot run the event loop while another loop is running) firstiter finalizerF)rrrrZ_get_running_loop_set_coroutine_wrapper_debug threading get_identrrrrwriset_asyncgen_hooksrrZ_set_running_loop _run_oncerl)rXZold_agen_hooksrrr run_forevers0          zBaseEventLoop.run_forevercCs|jtj| }tj||d}|r,d|_|jtz>y |jWn,|rj|j rj|j rj|j YnXWd|j tX|j st d|jS)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. )rHFNz+Event loop stopped before Future completed.)rrZisfuturerZ ensure_futureZ_log_destroy_pendingZadd_done_callbackrSrrbZ cancelledrZremove_done_callbackrr)rXZfutureZnew_taskrrrrun_until_completes      z BaseEventLoop.run_until_completecCs d|_dS)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)rXrrrrQszBaseEventLoop.stopcCsj|jrtd|jrdS|jr,tjd|d|_|jj|jj|j }|dk rfd|_ |j dddS)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 loopNzClose %rTF)wait) rrrkrr debugrorrprqZshutdown)rXexecutorrrrras   zBaseEventLoop.closecCs|jS)z*Returns True if the event loop was closed.)rk)rXrrrrszBaseEventLoop.is_closedcCs0|js,tjd|t|d|js,|jdS)Nzunclosed event loop %r)r)rrrrrra)rXrrr__del__ s  zBaseEventLoop.__del__cCs |jdk S)z*Returns True if the event loop is running.N)rr)rXrrrrszBaseEventLoop.is_runningcCstjS)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. )rsrh)rXrrrrsszBaseEventLoop.timecGs,|j|j||f|}|jr(|jd=|S)a8Arrange 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. rr)call_atrsr)rXZdelaycallbackrtimerrrr call_later szBaseEventLoop.call_latercGsX|j|jr"|j|j|dtj||||}|jr@|jd=tj|j |d|_ |S)z|Like call_later(), but uses an absolute time. Absolute time corresponds to the event loop's time() method. rrTr) rr _check_thread_check_callbackr TimerHandlerheapqheappushrp)rXwhenrrrrrrr5s zBaseEventLoop.call_atcGs@|j|jr"|j|j|d|j||}|jr<|jd=|S)aTArrange 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_soonrr)rrrr _call_soonr)rXrrrrrrrEs   zBaseEventLoop.call_sooncCs>tj|stj|r"tdj|t|s:tdj||dS)Nz#coroutines cannot be used with {}()z0a callable object was expected by {}(), got {!r})rZ iscoroutineZiscoroutinefunctionr5rr)rXrmethodrrrrXs   zBaseEventLoop._check_callbackcCs,tj|||}|jr|jd=|jj||S)Nrr)rHandlerror9)rXrrrrrrrcs  zBaseEventLoop._call_sooncCs,|jdkrdStj}||jkr(tddS)aoCheck 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)rrrrr)rXZ thread_idrrrrjs  zBaseEventLoop._check_threadcGs@|j|jr|j|d|j||}|jr4|jd=|j|S)z"Like call_soon(), but thread-safe.rrr)rrrrrr)rXrrrrrrr{s  z"BaseEventLoop.call_soon_threadsafecGsZ|j|jr|j|d|dkr@|j}|dkr@tjj}||_tj|j|f||dS)Nrun_in_executor)rH) rrrrq concurrentrZThreadPoolExecutorZ wrap_futureZsubmit)rXrfuncrrrrrs  zBaseEventLoop.run_in_executorcCs ||_dS)N)rq)rXrrrrset_default_executorsz"BaseEventLoop.set_default_executorc Csd||fg}|r |jd||r2|jd||rD|jd||rV|jd|dj|}tjd||j}tj||||||} |j|} d|| d | f}| |jkrtj|n tj|| S) Nz%s:%rz family=%rztype=%rzproto=%rzflags=%rz, zGet address info %sz(Getting address info %s took %.3f ms: %rg@@) r9joinr rrsr rFr}rI) rXr;r<r=r>r?rBmsgt0Zaddrinfodtrrr_getaddrinfo_debugs(      z BaseEventLoop._getaddrinfo_debugr)r=r>r?rBc Cs>|jr |jd|j||||||S|jdtj||||||SdS)N)rrrr rF)rXr;r<r=r>r?rBrrrrFs   zBaseEventLoop.getaddrinfocCs|jdtj||S)N)rr getnameinfo)rXZsockaddrrBrrrrszBaseEventLoop.getnameinfo)sslr=r?rBr% local_addrrc#s| dk r| rtd| dkr2|r2|s.td|} |dk sD|dk r|dk rTtdt||f|tj|||d} | g} | dk rt| |tj|||d} | j| nd} tj| |dEdH| j}|std| dk r| j}|stdg}x|D]B\}}}}}ytj|||d}|j d | dk rx|D]j\}}}}}y|j |PWnHtk r}z*t|j d j ||j j}|j|WYdd}~XnXq.W|jd}w|jrtjd |||j||EdHWn^tk r}z"|dk r|j|j|WYdd}~Xq|dk r,|jYqXPqWt|d krR|d nJt|d tfdd|Dr~|d tdj djdd|Dn,|dkrtdt|jstdj ||j|||| EdH\}}|jr |jd}tjd|||||||fS)aConnect 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?rBrH)rHz!getaddrinfo() returned empty list)r=r>r?Fz2error while attempting to bind on address {!r}: {}zconnect %r to %rrrc3s|]}t|kVqdS)N)r)rrR)modelrr sz2BaseEventLoop.create_connection..zMultiple exceptions: {}z, css|]}t|VqdS)N)r)rrRrrrr#sz5host 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!rKr r)r9rrrr$ setblockingbinderrnorstrerrorlowerrarr r sock_connectrrallrr+r>_create_connection_transportget_extra_info)rXprotocol_factoryr;r<rr=r?rBr%rrf1fsf2infosZ laddr_infos exceptionsr>ZcnamerG_ZladdrrR transportrr)rrcreate_connections        "        zBaseEventLoop.create_connectionc cs|jd|}|j}|rFt|tr*dn|}|j||||||d} n|j|||} y|EdHWn| jYnX| |fS)NF)rr)rrDrryrrra) rXr%rrrrrrdrrrrrr=s  z*BaseEventLoop._create_connection_transport)r=r?rB reuse_address reuse_portallow_broadcastr%c#sZ| dk rt| js tdj| s@s@|s@|s@|s@|s@|s@| r~t|||||| d} djdd| jD} tdj| | jdd} nLps|d krtd ||fdff}ntj }xd fd ffD]\}}|dk rt |t rt |d kst d t||tj|||dEdH}|s.tdxB|D]:\}}}}}||f}||kr`ddg||<||||<q4WqWfdd|jD}|stdg}|dkrtjdkotjdk}x|D]\\}}\}}d} d} ytj|tj|d} |r| jtjtjd |rt| | r4| jtjtjd | jdrN| j|rj|j| |EdH|} Wn^tk r}z"| dk r| j|j|WYdd}~Xn"| dk r| jYnXPqW|d |}|j}|j | || |}|j!r,rt"j#d||nt"j$d||y|EdHWn|jYnX||fS)zCreate datagram connection.Nz#A UDP Socket was expected, got {!r})r remote_addrr=r?rBrrrz, css"|]\}}|rdj||VqdS)z{}={}N)r)rkvrrrrisz9BaseEventLoop.create_datagram_endpoint..zNsocket modifier keyword arguments can not be used when sock is specified. ({})Frzunexpected address familyrrCz2-tuple is expected)r=r>r?rBrHz!getaddrinfo() returned empty listcs8g|]0\}}r|ddkp*o*|ddks||fqS)rNrr)rkeyZ addr_pair)rrrrrsz:BaseEventLoop.create_datagram_endpoint..zcan not get address informationposixcygwin)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!rdictritemsrrm OrderedDictrtuplerr]rKr r,r$rznamerwplatformr"r# SO_REUSEADDRr&Z SO_BROADCASTrrrar9rDrrr rIr)rXrrrr=r?rBrrrr%ZoptsZproblemsZr_addrZaddr_pairs_infoZ addr_infosidxZaddrrZfamrZprorGrrZ local_addressZremote_addressrRrrdrr)rrrcreate_datagram_endpointUs              z&BaseEventLoop.create_datagram_endpointccs4t||f|tj||dEdH}|s0tdj||S)N)r=r>rBrHz%getaddrinfo({!r}) returned empty list)rKr r)r$r)rXr;r<r=rBrrrr_create_server_getaddrinfos  z(BaseEventLoop._create_server_getaddrinfor )r=rBr%backlogrrrc #st|trtd|dk s$dk r|dk r4td| dkrPtjdkoNtjdk} g} |dkrddg} n$t|ts|t|t j  r|g} n|} fdd| D} t j | d iEdH}t tjj|}d }z x|D] }|\}}}}}ytj|||}Wn6tjk r2jr,tjd |||d d wYnX| j|| rV|jtjtjd | rdt|tr|tjkrttdr|jtjtjd y|j |Wqt!k r}z t!|j"d||j#j$fWYdd}~XqXqWd }Wd|s x| D]}|j%qWXn2|dkr"tdt&|j's.rHFz: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).rryr5r!rzr rwr rrmIterablerrset itertoolschain from_iterabler errorrr warningr9r"r#rr&r8r rrZ IPV6_V6ONLYrr$rrrrar+r>rrTZlistenrZ_start_servingrI)rXrr;r<r=rBr%rrrrrUZhostsrrZ completedresr@Zsocktyper?Z canonnameZsaerrrr)r=rBr<rXr create_servers     (         zBaseEventLoop.create_server)rccs^t|jstdj||j|||dddEdH\}}|jrV|jd}tjd|||||fS)aHandle 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}r0T)rNr z%r handled: (%r, %r)) r+r>r!rrrrr r)rXrr%rrrrrrconnect_accepted_socketAs   z%BaseEventLoop.connect_accepted_socketc csd|}|j}|j|||}y|EdHWn|jYnX|jr\tjd|j||||fS)Nz Read pipe %r connected: (%r, %r))rDrrarr rfileno)rXrrrrdrrrrconnect_read_pipeXszBaseEventLoop.connect_read_pipec csd|}|j}|j|||}y|EdHWn|jYnX|jr\tjd|j||||fS)Nz!Write pipe %r connected: (%r, %r))rDrrarr rr )rXrrrrdrrrrconnect_write_pipeisz BaseEventLoop.connect_write_pipecCs|g}|dk r |jdt||dk rF|tjkrF|jdt|n4|dk r`|jdt||dk rz|jdt|tjdj|dS)Nzstdin=%szstdout=stderr=%sz stdout=%sz stderr=%s )r9rrrr rr)rXrrrrrIrrr_log_subprocesszszBaseEventLoop._log_subprocessT)rrruniversal_newlinesrrc kst|ttfstd|r"td|s.td|dkr>td|} d} |jrfd|} |j| ||||j| |d||||f| EdH} |jr| dk rtjd| | | | fS) Nzcmd must be a stringz universal_newlines must be Falsezshell must be Truerzbufsize must be 0zrun shell command %rTz%s: %r) rr3rr!rr$rr rI) rXrcmdrrrr%rrrr debug_logrrrrsubprocess_shells$zBaseEventLoop.subprocess_shellcos|r td|rtd|dkr(td|f| } x,| D]$} t| ttfs8tdt| jq8W|} d}|jrd|}|j|||||j | | d||||f| EdH}|jr|dk rt j d|||| fS) Nz universal_newlines must be Falsezshell must be Falserzbufsize must be 0z8program arguments must be a bytes or text string, not %szexecute program %rFz%s: %r) r!rrr3r5r>r[rr$rr rI)rXrZprogramrrrr%rrrrZ popen_argsargrr'rrrrsubprocess_execs,   zBaseEventLoop.subprocess_execcCs|jS)zKReturn an exception handler, or None if the default one is in use. )ru)rXrrrget_exception_handlersz#BaseEventLoop.get_exception_handlercCs*|dk r t| r tdj|||_dS)aSet 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})rr5rru)rXZhandlerrrrset_exception_handlers z#BaseEventLoop.set_exception_handlerc Cs|jd}|sd}|jd}|dk r6t|||jf}nd}d|kr`|jdk r`|jjr`|jj|d<|g}xt|D]}|dkr~qp||}|dkrdjtj|}d }||j 7}n2|dkrdjtj|}d }||j 7}nt |}|j d j ||qpWt jd j||d dS)aEDefault 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()`. rz!Unhandled exception in event looprNFZsource_tracebackZhandle_tracebackr0z+Object created at (most recent call last): z+Handle created at (most recent call last): z{}: {} )r>rr)r|r> __traceback__r~rsortedr traceback format_listrstriprr9rr r) rXcontextrrrZ log_linesrvaluetbrrrdefault_exception_handlers6    z'BaseEventLoop.default_exception_handlercCs|jdkr>y|j|Wqtk r:tjdddYqXnny|j||Wn\tk r}z@y|jd||dWn"tk rtjdddYnXWYdd}~XnXdS)aCall 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)rz$Unhandled error in exception handler)rrr3zeException in default exception handler while handling an unexpected error in custom exception handler)rur6rOr r)rXr3rRrrrrs" z$BaseEventLoop.call_exception_handlercCs@t|tjstd|jrdSt|tj s0t|jj|dS)z3Add a Handle to _scheduled (TimerHandle) or _ready.zA Handle is required hereN)rrrr] _cancelledrror9)rXrrrr _add_callback9s zBaseEventLoop._add_callbackcCs|j||jdS)z6Like _add_callback() but called from a signal handler.N)r8r)rXrrrr_add_callback_signalsafeAs z&BaseEventLoop._add_callback_signalsafecCs|jr|jd7_dS)z3Notification that a TimerHandle has been cancelled.rN)rprj)rXrrrr_timer_handle_cancelledFsz%BaseEventLoop._timer_handle_cancelledc Cst|j}|tkrd|j|tkrdg}x&|jD]}|jr>d|_q,|j|q,Wtj|||_d|_n8x6|jr|jdjr|jd8_tj |j}d|_qfWd}|j s|j rd}n*|jr|jdj }t td||jt}|jo|dkr|j}|jj|}|j|}|dkrtj} ntj} t|} |dkrLtj| d|d| nD| rntj| d|d|d| n"|dkrtj| d |d|dn |jj|}|j||j|j} xD|jr|jd}|j | krPtj |j}d|_|j j|qWt|j } xt| D]|} |j j}|jr*q|jrzD||_|j}|j|j|}||jkrttj d t!||Wdd|_Xn|jqWd}dS) 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. FrrNg?zpoll took %.3f ms: %s eventsg@@z$poll %.3f ms took %.3f ms: %s eventsz"poll %.3f ms took %.3f ms: timeoutzExecuting %s took %.3f seconds)"rrp_MIN_SCHEDULED_TIMER_HANDLESrj%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONr7r9rheapifyheappoprorlZ_whenminmaxrsMAXIMUM_SELECT_TIMEOUTrZ _selectorZselectloggingINFODEBUGr logrrtrangepopleftr~Z_runr}rr)rXZ sched_countZ new_scheduledrZtimeoutrrrrlevelZneventZend_timeZntodoirrrrKs                       zBaseEventLoop._run_oncec Csytj}tj}Wntk r$dSXt|}|j|krsV            ;   /