o ?Oge"@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZzddlZWn eySdZYnwddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddl m!Z!dZ"dZ#dZ$e%e dZ&dZ'e(Z)ddZ*ddZ+ddZ,d-ddZ-d.ddZ.dd Z/e%e d!rd"d#Z0nd$d#Z0d%d&Z1Gd'd(d(ej2Z3Gd)d*d*ej4Z5Gd+d,d,ej6Z7dS)/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) constants) coroutines)events) exceptions)futures) protocols)sslproto) staggered)tasks) transports)trsock)logger) BaseEventLoopServerdg?AF_INET6iQcCs,|j}tt|ddtjrt|jSt|S)N__self__)Z _callback isinstancegetattrr Taskreprrstr)handlecbr:/opt/alt/python310/lib64/python3.10/asyncio/base_events.py_format_handleJs rcCs$|tjkrdS|tjkrdSt|S)Nzz) subprocessPIPESTDOUTr)fdrrr _format_pipeSs  r"cCsBttds tdz |tjtjdWdSty tdw)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_SOCKETr#OSErrorsockrrr_set_reuseport\s  r,c CspttdsdS|dtjtjhvs|durdS|tjkrtj}n |tjkr(tj}ndS|dur1d}n+t|tr=|dkr=d}nt|trI|dkrId}nzt |}Wn t t fy[YdSw|tj krntj g}trm|tjn|g}t|tr{|d}d|vrdS|D]2}z't||tr|tjkr|||d||||ffWS|||d||ffWStyYqwdS)N inet_ptonrZidna%)r$r% IPPROTO_TCPZ IPPROTO_UDP SOCK_STREAM SOCK_DGRAMrbytesrint TypeErrorr& AF_UNSPECAF_INET _HAS_IPv6appendrdecoder-r)) hostportfamilytypeprotoZflowinfoZscopeidZafsafrrr _ipaddr_infogsR          rBcCst}|D]}|d}||vrg||<|||qt|}g}|dkr>||dd|d|dd|d=|ddtjtj |D|S)z-Interleave list of addrinfo tuples by family.rrNcss|] }|dur|VqdSNr).0arrr sz(_interleave_addrinfos..) collections OrderedDictr:listvaluesextend itertoolschain from_iterable zip_longest)Z addrinfosZfirst_address_family_countZaddrinfos_by_familyaddrr>Zaddrinfos_listsZ reorderedrrr_interleave_addrinfoss"  rQcCs4|s|}t|ttfrdSt|dSrC) cancelled exceptionr SystemExitKeyboardInterruptrZ _get_loopstop)futexcrrr_run_until_complete_cbs rY TCP_NODELAYcCsL|jtjtjhvr |jtjkr"|jtjkr$|tjtj ddSdSdSdSNr) r>r%r8rr?r2r@r1r'rZr*rrr _set_nodelays  r\cCsdSrCrr*rrrr\scCs$tdurt|tjrtddSdS)Nz"Socket cannot be of type SSLSocket)sslrZ SSLSocketr6r*rrr_check_ssl_socketsr^c@sTeZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ dS)_SendfileFallbackProtocolcCsjt|tjs td||_||_||_|j |_ | | ||j r0|jj |_dSd|_dS)Nz.transport should be _FlowControlMixin instance)rr Z_FlowControlMixinr6 _transportZ get_protocol_protoZ is_reading_should_resume_readingZ_protocol_paused_should_resume_writing pause_reading set_protocol_loop create_future_write_ready_fut)selftransprrr__init__s     z"_SendfileFallbackProtocol.__init__cs4|jr td|j}|durdS|IdHdS)NzConnection closed by peer)r` is_closingConnectionErrorrh)rirWrrrdrains z_SendfileFallbackProtocol.draincCtd)Nz?Invalid state: connection should have been established already. RuntimeError)ri transportrrrconnection_madez)_SendfileFallbackProtocol.connection_madecCs@|jdur|dur|jtdn|j||j|dS)NzConnection is closed by peer)rh set_exceptionrmraconnection_lost)rirXrrrrvs  z)_SendfileFallbackProtocol.connection_lostcCs |jdurdS|jj|_dSrC)rhr`rfrgrirrr pause_writings z'_SendfileFallbackProtocol.pause_writingcCs$|jdurdS|jdd|_dS)NF)rh set_resultrwrrrresume_writings   z(_SendfileFallbackProtocol.resume_writingcCroNz'Invalid state: reading should be pausedrp)ridatarrr data_receivedrtz'_SendfileFallbackProtocol.data_receivedcCror{rprwrrr eof_receivedrtz&_SendfileFallbackProtocol.eof_receivedcsL|j|j|jr|j|jdur|j|jr$|jdSdSrC) r`rerarbresume_readingrhcancelrcrzrwrrrrestore s   z!_SendfileFallbackProtocol.restoreN) __name__ __module__ __qualname__rkrnrsrvrxrzr}r~rrrrrr_s  r_c@sxeZdZddZddZddZddZd d Zd d Zd dZ ddZ e ddZ ddZ ddZddZddZdS)rcCs@||_||_d|_g|_||_||_||_||_d|_d|_ dS)NrF) rf_sockets _active_count_waiters_protocol_factory_backlog _ssl_context_ssl_handshake_timeout_serving_serving_forever_fut)riloopsocketsprotocol_factoryZ ssl_contextbacklogssl_handshake_timeoutrrrrks zServer.__init__cCsd|jjd|jdS)N) __class__rrrwrrr__repr__%szServer.__repr__cCs |jdusJ|jd7_dSr[)rrrwrrr_attach(szServer._attachcCsD|jdksJ|jd8_|jdkr|jdur |dSdSdS)Nrr)rr_wakeuprwrrr_detach,s  zServer._detachcCs,|j}d|_|D] }|s||qdSrC)rdonery)riwaiterswaiterrrrr2s zServer._wakeupc CsJ|jrdSd|_|jD]}||j|j|j||j||j|jq dS)NT) rrZlistenrrf_start_servingrrr)rir+rrrr9s    zServer._start_servingcC|jSrC)rfrwrrrget_loopCzServer.get_loopcCrrC)rrwrrr is_servingFrzServer.is_servingcCs"|jdurdStdd|jDS)Nrcss|]}t|VqdSrC)r ZTransportSocket)rDsrrrrFMsz!Server.sockets..)rtuplerwrrrrIs zServer.socketscCsr|j}|dur dSd|_|D]}|j|qd|_|jdur,|js,|jd|_|jdkr7|dSdS)NFr) rrfZ _stop_servingrrrrrr)rirr+rrrcloseOs    z Server.closecs|tdIdHdS)Nr)rr sleeprwrrr start_servingbszServer.start_servingc s|jdurtd|d|jdurtd|d||j|_z&z|jIdHWntjyEz || IdHWwWd|_dSd|_w)Nzserver z, is already being awaited on serve_forever()z is closed) rrqrrrfrgrZCancelledErrorr wait_closedrwrrr serve_foreverhs&    zServer.serve_forevercs>|jdus |jdur dS|j}|j||IdHdSrC)rrrfrgr:)rirrrrr}s   zServer.wait_closedN)rrrrkrrrrrrrpropertyrrrrrrrrrrs    rc @seZdZddZddZddZddd d Zd d Zd dZddddddZ ddddddddddZ dddZ  dddZ  dddZ dddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Zd;d<Zejfd=d>Z d?d@Z!dAdBZ"ddCdDdEZ#ddCdFdGZ$ddCdHdIZ%dJdKZ&dLdMZ'dNdOZ(ddCdPdQZ)dRdSZ*dTdUZ+dVdWZ,dXdXdXdXdYdZd[Z-dd\d]Z.ddd^d_d`Z/dadbZ0dcddZ1dedfZ2ddgdhZ3 dddXdXdXdddddddi djdkZ4  ddldmZ5ddd^dndoZ6dpdqZ7drdsZ8ddddtdudvZ9 ddXdXdXe:ddddwdxdyZ;dXed|d}Z? de$sz4BaseEventLoop.shutdown_asyncgens..Zreturn_exceptionsz;an error occurred during closing of asynchronous generator )messagerSZasyncgen) rlenrrIclearr gatherzipr Exceptioncall_exception_handler)riZ closing_agensZresultsresultrrrrshutdown_asyncgenss,      z BaseEventLoop.shutdown_asyncgenscs\d|_|jdur dS|}tj|j|fd}|z |IdHW|dS|w)z.Schedule the shutdown of the default executor.TN)targetr)rrrg threadingZThread _do_shutdownstartjoin)rifuturethreadrrrshutdown_default_executor0s  z'BaseEventLoop.shutdown_default_executorc Cs|z|jjdd|s||jdWdSWdSty=}z|s2||j|WYd}~dSWYd}~dSd}~ww)NTwait)rshutdownrrryrru)rirZexrrrr =szBaseEventLoop._do_shutdowncCs(|rtdtdurtddS)Nz"This event loop is already runningz7Cannot run the event loop while another loop is running)rrqrZ_get_running_looprwrrr_check_runningFs zBaseEventLoop._check_runningc Cs||||jt}z5t|_tj |j |j dt | ||jr/nq'Wd|_d|_t d|dtj |dSd|_d|_t d|dtj |w)zRun until stop() is called.) firstiter finalizerTFN)rr_set_coroutine_origin_tracking_debugsysget_asyncgen_hooksr  get_identrset_asyncgen_hooksrrrZ_set_running_loop _run_oncer)riZold_agen_hooksrrr run_foreverMs4        zBaseEventLoop.run_foreverc Cs||t| }tj||d}|rd|_|tz z| Wn|r8| r8| s8| W| tn| tw| sNtd|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. rFz+Event loop stopped before Future completed.)rrrZisfuturer Z ensure_futureZ_log_destroy_pendingZadd_done_callbackrYrrrRrSZremove_done_callbackrqr)rirZnew_taskrrrrun_until_completees$     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)rrwrrrrVs zBaseEventLoop.stopcCst|rtd|jr dS|jrtd|d|_|j|jd|_ |j }|dur8d|_ |j dddSdS)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 %rTFr) rrqrrrdebugrrrrrrriexecutorrrrrs   zBaseEventLoop.closecCr)z*Returns True if the event loop was closed.)rrwrrrrrzBaseEventLoop.is_closedcCs8|s|d|t|d|s|dSdSdS)Nzunclosed event loop r)rrrr)riZ_warnrrr__del__s  zBaseEventLoop.__del__cCs |jduS)z*Returns True if the event loop is running.N)rrwrrrrs zBaseEventLoop.is_runningcCstS)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. )rrrwrrrrszBaseEventLoop.time)contextcGs4|j|||g|Rd|i}|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. r$r)call_atrr)riZdelaycallbackr$rtimerrrr call_laters zBaseEventLoop.call_latercGsZ||jr|||dt|||||}|jr!|jd=t|j |d|_ |S)z|Like call_later(), but uses an absolute time. Absolute time corresponds to the event loop's time() method. r%rT) rr _check_thread_check_callbackrZ TimerHandlerheapqZheappushr)riwhenr&r$rr'rrrr%s zBaseEventLoop.call_atcGsB||jr|||d||||}|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_soonr)rrr)r* _call_soonrrir&r$rrrrrr-s  zBaseEventLoop.call_sooncCsDt|s t|rtd|dt|s td|d|dS)Nzcoroutines cannot be used with z()z"a callable object was expected by z(), got )rZ iscoroutineZiscoroutinefunctionr6r)rir&methodrrrr*s  zBaseEventLoop._check_callbackcCs.t||||}|jr|jd=|j||S)Nr)rZHandlerrr:)rir&rr$rrrrr.s  zBaseEventLoop._call_sooncCs,|jdurdSt}||jkrtddS)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)rr rrq)riZ thread_idrrrr) s  zBaseEventLoop._check_threadcGsB||jr ||d||||}|jr|jd=||S)z"Like call_soon(), but thread-safe.rr)rrr*r.rrr/rrrrs z"BaseEventLoop.call_soon_threadsafecGsh||jr ||d|dur&|j}||dur&tjjdd}||_tj|j |g|R|dS)Nrun_in_executorZasyncio)Zthread_name_prefixr) rrr*rr concurrentrThreadPoolExecutorZ wrap_futureZsubmit)rir"funcrrrrr1's zBaseEventLoop.run_in_executorcCs&t|tjjstdtd||_dS)Nz{Using the default executor that is not an instance of ThreadPoolExecutor is deprecated and will be prohibited in Python 3.9)rr2rr3rrDeprecationWarningrr!rrrset_default_executor7s  z"BaseEventLoop.set_default_executorc Cs|d|g}|r|d||r|d||r&|d||r0|d|d|}td||}t||||||} ||} d|d | d d d | }| |jkrit|| St|| S) N:zfamily=ztype=zproto=zflags=, zGet address info %szGetting address info z took g@@z.3fzms: ) r:r rr rr% getaddrinforinfo) rir<r=r>r?r@flagsmsgt0addrinfodtrrr_getaddrinfo_debug@s(      z BaseEventLoop._getaddrinfo_debugrr>r?r@r<c s4|jr|j}ntj}|d|||||||IdHSrC)rrAr%r:r1)rir<r=r>r?r@r<Z getaddr_funcrrrr:Xs zBaseEventLoop.getaddrinfocs|dtj||IdHSrC)r1r% getnameinfo)riZsockaddrr<rrrrCbs  zBaseEventLoop.getnameinfo)fallbackc s|jr|dkrtdt||||||z |||||IdHWStjy<}z |s2WYd}~nd}~ww|||||IdHS)Nrzthe socket must be non-blocking) rZ gettimeoutr&r^_check_sendfile_params_sock_sendfile_nativerSendfileNotAvailableError_sock_sendfile_fallback)rir+fileoffsetcountrDrXrrr sock_sendfilefs$   zBaseEventLoop.sock_sendfilecstd|d|d)Nz-syscall sendfile is not available for socket z and file z combinationrrGrir+rIrJrKrrrrFus z#BaseEventLoop._sock_sendfile_nativec s|r|||rt|tjntj}t|}d}zL |r)t|||}|dkr)n(t|d|}|d|j|IdH} | s?n|||d| IdH|| 7}q|W|dkrdt |dre|||SSS|dkrwt |drx|||www)NrTseek) rOminrZ!SENDFILE_FALLBACK_READBUFFER_SIZE bytearray memoryviewr1readintoZ sock_sendallr$) rir+rIrJrK blocksizebuf total_sentviewreadrrrrH|s8  z%BaseEventLoop._sock_sendfile_fallbackcCsdt|ddvr td|jtjkstd|dur1t|ts&td||dkr1td|t|ts=td||dkrHtd|dS)Nbmodez$file should be opened in binary modez+only SOCK_STREAM type sockets are supportedz+count must be a positive integer (got {!r})rz0offset must be a non-negative integer (got {!r})) rr&r?r%r2rr5r6formatrNrrrrEs4   z$BaseEventLoop._check_sendfile_paramsc sXg}|||\}}}}} d} zzotj|||d} | d|durq|D]<\} }}}} | |kr2q&z| | Wn6tyb} zd| d| j}t| j|} || WYd} ~ q&d} ~ ww|ri|td|d| | | IdH| WWd}}Sty} z|| | dur| d} ~ w| dur| d}}w)z$Create, bind and connect one socket.Nr>r?r@Fz*error while attempting to bind on address : z&no matching local address with family=z found) r:r% setblockingbindr)strerrorlowererrnopop sock_connectr)rirZ addr_infoZlocal_addr_infosZ my_exceptionsr>Ztype_r@_rr+ZlfamilyZladdrrXr=rrr _connect_socksV        zBaseEventLoop._connect_sock) r]r>r@r<r+ local_addrrrhappy_eyeballs_delay interleavec  sd| dur |s td| dur|r|std|} | dur#|s#td|dur+t|| dur5| dur5d} |dus=|dur|durEtdj||f|tj||dIdH}|s\td| durvj| |tj||dIdHsutdnd| rt|| }g| dur|D]}z |IdH}Wn tyYqwntj fd d |D| d IdH\}}}|durd d Dz.t dkrΈdt dt fdd Drdtd ddd Ddwn|durtd|jtjkr td|j|||| | dIdH\}}jr.|d}td|||||||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 host1ssl_handshake_timeout is only meaningful with sslr8host/port and sock can not be specified at the same timer>r?r@r<r!getaddrinfo() returned empty listc3s"|] }tj|VqdSrC) functoolspartialrf)rDr?)r laddr_infosrirrrF+s  z2BaseEventLoop.create_connection..rcSsg|] }|D]}|qqSrr)rDsubrXrrrr1sz3BaseEventLoop.create_connection..rc3s|] }t|kVqdSrCrrDrX)modelrrrF8szMultiple exceptions: {}r9css|]}t|VqdSrCrrrsrrrrF=sz5host and port was not specified and no sock specified"A Stream Socket was expected, got )rr%z%r connected to %s:%r: (%r, %r))r&r^_ensure_resolvedr%r2r)rQrfr Zstaggered_racerrallr[r r?_create_connection_transportrget_extra_inforr )rirr<r=r]r>r@r<r+rgrrrhriinfosr?rerrrr)rrprtrircreate_connections              zBaseEventLoop.create_connectionc s~|d|}|}|r%t|trdn|} |j||| ||||d} n||||} z |IdHW| |fS| )NFrrr)r^rgrboolrrr) rir+rr]rrrrrrrrrrrrxZs$  z*BaseEventLoop._create_connection_transportc s|r tdt|dtjj}|tjjurtd||tjjurGz |||||IdHWStj yF}z |s<WYd}~nd}~ww|sPtd|| ||||IdHS)aSend a file to transport. Return the total number of bytes which were sent. The method uses high-performance os.sendfile if available. file must be a regular file object opened in binary mode. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. fallback set to True makes asyncio to manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix). Raise SendfileNotAvailableError if the system does not support sendfile syscall and fallback is False. zTransport is closingZ_sendfile_compatiblez(sendfile is not supported for transport NzHfallback is disabled and native sendfile is not supported for transport ) rlrqrrZ _SendfileModeZ UNSUPPORTEDZ TRY_NATIVE_sendfile_nativerrG_sendfile_fallback)rirrrIrJrKrDrZrXrrrsendfilets<     zBaseEventLoop.sendfilecs td)Nz!sendfile syscall is not supportedrM)rirjrIrJrKrrrr~szBaseEventLoop._sendfile_nativec s@|r|||rt|dnd}t|}d}t|}zl |rDt|||}|dkrD|W|dkrr@r< reuse_address reuse_portallow_broadcastr+c s| durI| jtjkrtd| s s |s |s |s |s | r@t|||||| d} ddd| D} td| d| d d} nus]s]|d krUtd ||fd ff}nttd r|tj krfD]}|durzt |t szt dqkrd dvrzt t jrtWn!tyYnty}z td|WYd}~nd}~ww||ffff}nji}d fdffD]L\}}|durt |trt|dksJd|j||tj|||dIdH}|std|D]\}}}}}||f}||vrddg||<||||<qqɇfdd|D}|s)tdg}|tur?|r7tdtjdtdd|D]x\\}}\}}d} d} zr@r<rrrr9css&|]\}}|r|d|VqdS)=Nr)rDkvrrrrFs$z9BaseEventLoop.create_datagram_endpoint..zKsocket modifier keyword arguments can not be used when sock is specified. ()Frzunexpected address familyNNAF_UNIXzstring is expected)rz2Unable to check or remove stale UNIX socket %r: %rrr5z2-tuple is expectedrlrmcs8g|]\}}r|ddusr|ddus||fqS)rNrr)rDkeyZ addr_pairrgrrrr3s  z:BaseEventLoop.create_datagram_endpoint..zcan not get address informationz~Passing `reuse_address=True` is no longer supported, as the usage of SO_REUSEPORT in UDP poses a significant security concern.zdThe *reuse_address* parameter has been deprecated as of 3.5.10 and is scheduled for removal in 3.11.) stacklevelr\z@Datagram endpoint local_addr=%r remote_addr=%r created: (%r, %r)z2Datagram endpoint remote_addr=%r created: (%r, %r))*r?r%r3r&dictr itemsr^r$rrrr6statS_ISSOCKosst_moderemoveFileNotFoundErrorr)rerrorrrrv_unsetrrr6r,r'r(Z SO_BROADCASTr_rdrr:rgrrr;r ) rirrgrr>r@r<rrrr+ZoptsZproblemsZr_addrZaddr_pairs_inforPerrZ addr_infosidxrzZfamreZprorrrZ local_addressZremote_addressrXrrrrrrrcreate_datagram_endpoints                  z&BaseEventLoop.create_datagram_endpointc s\|dd\}}t|||||g|ddR} | dur | gS|j||||||dIdHS)Nr5rB)rBr:) rirr>r?r@r<rr<r=r;rrrrvs   zBaseEventLoop._ensure_resolvedcs:|j||f|tj||dIdH}|std|d|S)N)r>r?r<rz getaddrinfo(z) returned empty list)rvr%r2r))rir<r=r>r<rzrrr_create_server_getaddrinfos  z(BaseEventLoop._create_server_getaddrinfor) r>r<r+rr]rrrrc  st|tr td| dur|durtd|durt||dus'dur|dur/td| dur=tjdkor<)r)rDr<r>r<r=rirrrs   z/BaseEventLoop.create_server..Fz:create_server() failed to create socket.socket(%r, %r, %r)Texc_info IPPROTO_IPV6z0error while attempting to bind on address %r: %sz)Neither host/port nor sock were specifiedrurz %r is serving)/rr}r6r&r^rrrplatformrrGabcIterabler rsetrLrMrNr%rrrwarningr:r'r(Z SO_REUSEADDRr,r9rr$rZ IPV6_V6ONLYr_r)rbr`rarr?r2r^rrrr;)rirr<r=r>r<r+rr]rrrrrZhostsZfsrzZ completedresrAZsocktyper@Z canonnameZsarrrrr create_servers           zBaseEventLoop.create_server)r]rcs|jtjkrtd||dur|std|dur t||j|||dd|dIdH\}}|jr@|d}t d|||||fS)Nrurjr/T)rrr%z%r handled: (%r, %r)) r?r%r2r&r^rxrryrr )rirr+r]rrrrrrrconnect_accepted_socket s"    z%BaseEventLoop.connect_accepted_socketc`|}|}||||}z|IdHWn||jr,td|||||fS)Nz Read pipe %r connected: (%r, %r))rgrrrrr filenorirrrrrrrrrconnect_read_pipe% zBaseEventLoop.connect_read_pipecr)Nz!Write pipe %r connected: (%r, %r))rgrrrrr rrrrrconnect_write_pipe5rz BaseEventLoop.connect_write_pipecCs|g}|dur|dt||dur%|tjkr%|dt|n|dur3|dt||durA|dt|td|dS)Nzstdin=zstdout=stderr=zstdout=zstderr= )r:r"rr rr r )rir=rrrr;rrr_log_subprocessEszBaseEventLoop._log_subprocess) rrruniversal_newlinesrrencodingerrorstextc st|ttfs td|rtd|std|dkr td| r&td| dur.td| dur6td|} d}|jrJd |}||||||j| |d ||||fi| IdH}|jrj|durjtd |||| fS) Nzcmd must be a string universal_newlines must be Falsezshell must be Truerbufsize must be 0text must be Falseencoding must be Noneerrors must be Nonezrun shell command %rT%s: %r) rr4rr&rrrrr;)rircmdrrrrrrrrrrr debug_logrrrrrsubprocess_shellRs8 zBaseEventLoop.subprocess_shellc s|rtd|r td|dkrtd| rtd| dur#td| dur+td|f| }|}d}|jrEd|}||||||j||d ||||fi| IdH}|jre|duretd ||||fS) Nrzshell must be Falserrrrrzexecute program Fr)r&rrrrr;)rirZprogramrrrrrrrrrrrZ popen_argsrrrrrrrsubprocess_execvs8    zBaseEventLoop.subprocess_execcCr)zKReturn an exception handler, or None if the default one is in use. )rrwrrrget_exception_handlersz#BaseEventLoop.get_exception_handlercCs(|durt|std|||_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 )rr6r)riZhandlerrrrset_exception_handlers   z#BaseEventLoop.set_exception_handlerc Cs|d}|s d}|d}|durt|||jf}nd}d|vr0|jdur0|jjr0|jj|d<|g}t|D]C}|dvr>q7||}|dkrWd t|}d }|| 7}n|dkrld t|}d }|| 7}nt |}| |d |q7t j d ||ddS)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 looprSNFZsource_tracebackZhandle_traceback>rrSr/z+Object created at (most recent call last): z+Handle created at (most recent call last): r] r)getr? __traceback__rrsortedr  traceback format_listrstriprr:rr) rir$rrSrZ log_linesrvaluetbrrrdefault_exception_handlers:    z'BaseEventLoop.default_exception_handlerc Cs|jdur(z||WdSttfyty'tjdddYdSwz |||WdSttfy;tyy}z3z |d||dWnttfyWtyftjdddYnwWYd}~dSWYd}~dSd}~ww)aDCall 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; - 'task' (optional): Task 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 handlerTrz$Unhandled error in exception handler)rrSr$zeException in default exception handler while handling an unexpected error in custom exception handler)rrrTrUrrr)rir$rXrrrrs@       z$BaseEventLoop.call_exception_handlercCs|js |j|dSdS)zAdd a Handle to _ready.N) _cancelledrr:rirrrr _add_callbackszBaseEventLoop._add_callbackcCs|||dS)z6Like _add_callback() but called from a signal handler.N)rrrrrr_add_callback_signalsafes  z&BaseEventLoop._add_callback_signalsafecCs|jr |jd7_dSdS)z3Notification that a TimerHandle has been cancelled.rN)rrrrrr_timer_handle_cancelled#sz%BaseEventLoop._timer_handle_cancelledc Cst|j}|tkr0|j|tkr0g}|jD]}|jrd|_q||qt|||_d|_n"|jrR|jdjrR|jd8_t |j}d|_|jrR|jdjs9d}|j sZ|j r]d}n|jrr|jdj }t td||t}|j|}||d}||j}|jr|jd}|j |krnt |j}d|_|j ||jst|j }t|D];} |j }|jrq|jrz$||_|} ||| } | |jkrtdt|| Wd|_qd|_w|qd}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. FrrNzExecuting %s took %.3f seconds)rr_MIN_SCHEDULED_TIMER_HANDLESr%_MIN_CANCELLED_TIMER_HANDLES_FRACTIONrr:r+ZheapifyZheappoprrZ_whenrPmaxrMAXIMUM_SELECT_TIMEOUTZ _selectorZselectrrrangepopleftrrZ_runrrrr) riZ sched_countZ new_scheduledrZtimeoutr,rZend_timeZntodoir>r@rrrr(sn                   zBaseEventLoop._run_oncecCsHt|t|jkr dS|rt|_ttjnt|j||_dSrC)r}rr#get_coroutine_origin_tracking_depthr#set_coroutine_origin_tracking_depthrZDEBUG_STACK_DEPTHriZenabledrrrrxs z,BaseEventLoop._set_coroutine_origin_trackingcCrrC)rrwrrrrrzBaseEventLoop.get_debugcCs$||_|r||j|dSdSrC)rrrrrrrrrszBaseEventLoop.set_debugrC)NNNr)r)rN)FN)Vrrrrkrrgrrrrrrrrrrrrrrrrrr rrrrVrrrrr#rrr(r%r-r*r.r)rr1r7rAr:rCrLrFrHrErfr{rxrr~rrrrr%r2rvrr7Z AI_PASSIVErrrrrrrrrrrrrrrrrrrrrrrrrs          &       -   / /     z  % "29P r)rr)r)8__doc__rGZcollections.abcZconcurrent.futuresr2rnr+rLrr%rrr rrrrrr] ImportErrorr/rrrrrrr r r r r logr__all__rrr$r9robjectrrr"r,rBrQrYr\r^ZProtocolr_ZAbstractServerrZAbstractEventLooprrrrrsj                 ; Do