o [d@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddl mZddl mZddl mZddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddlmZdZe jdkredddZddZGdddejZ Gdddej!Z"Gdddej#ej$Z%Gdddej&Z'GdddZ(Gd d!d!e(Z)Gd"d#d#e(Z*Gd$d%d%e*Z+Gd&d'd'e*Z,Gd(d)d)e(Z-Gd*d+d+e(Z.Gd,d-d-ej/Z0e Z1e0Z2dS).z2Selector event loop for Unix with signal handling.N) base_events)base_subprocess) constants) coroutines)events) exceptions)futures)selector_events)tasks) transports)logger)SelectorEventLoopAbstractChildWatcherSafeChildWatcherFastChildWatcherPidfdChildWatcherMultiLoopChildWatcherThreadedChildWatcherDefaultEventLoopPolicywin32z+Signals are not really supported on WindowscCdS)zDummy signal handler.N)signumframerr*/usr/lib/python3.10/asyncio/unix_events.py_sighandler_noop*srcCs$zt|WSty|YSwN)oswaitstatus_to_exitcode ValueError)statusrrrr/s   rcseZdZdZd)fdd ZfddZddZd d Zd d Zd dZ ddZ  d*ddZ  d*ddZ d)ddZ ddZ d)dddddddZ d)dddddddd Zd!d"Zd#d$Zd%d&Zd'd(ZZS)+_UnixSelectorEventLoopzdUnix event loop. Adds signal handling and UNIX Domain Socket support to SelectorEventLoop. Ncst|i|_dSr)super__init___signal_handlers)selfselector __class__rrr$?  z_UnixSelectorEventLoop.__init__cs`ttst|jD]}||qdS|jr.tjd|dt |d|j dSdS)NzClosing the loop z@ on interpreter shutdown stage, skipping signal handlers removalsource) r#closesys is_finalizinglistr%remove_signal_handlerwarningswarnResourceWarningclearr&sigr(rrr-Cs  z_UnixSelectorEventLoop.closecCs|D] }|sq||qdSr)_handle_signal)r&datarrrr_process_self_dataQs  z)_UnixSelectorEventLoop._process_self_datac Gs.t|s t|rtd|||z t|j Wnt t fy5}zt t |d}~wwt|||d}||j|<zt|tt|dWdSt y}z8|j|=|jsztdWnt t fy}z td|WYd}~nd}~ww|jtjkrt d|dd}~ww)zAdd a handler for a signal. UNIX only. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. z3coroutines cannot be used with add_signal_handler()NFset_wakeup_fd(-1) failed: %ssig  cannot be caught)r iscoroutineiscoroutinefunction TypeError _check_signal _check_closedsignal set_wakeup_fd_csockfilenor OSError RuntimeErrorstrrHandler%r siginterruptr infoerrnoEINVAL)r&r7callbackargsexchandlenexcrrradd_signal_handlerXs>      z)_UnixSelectorEventLoop.add_signal_handlercCs:|j|}|dur dS|jr||dS||dS)z2Internal helper that is the actual signal handler.N)r%get _cancelledr1_add_callback_signalsafe)r&r7rSrrrr8s z%_UnixSelectorEventLoop._handle_signalc Cs||z|j|=Wn tyYdSw|tjkrtj}ntj}zt||WntyE}z|jtj kr@t d|dd}~ww|jsmzt dWdSt tfyl}z t d|WYd}~dSd}~wwdS)zwRemove a handler for a signal. UNIX only. Return True if a signal handler was removed, False if not. Fr=r>Nr;r<T)rBr%KeyErrorrDSIGINTdefault_int_handlerSIG_DFLrHrNrOrIrEr r rM)r&r7handlerrRrrrr1s6      z,_UnixSelectorEventLoop.remove_signal_handlercCs6t|ts td||tvrtd|dS)zInternal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. zsig must be an int, not zinvalid signal number N) isinstanceintrArD valid_signalsr r6rrrrBs  z$_UnixSelectorEventLoop._check_signalcCt|||||Sr)_UnixReadPipeTransportr&pipeprotocolwaiterextrarrr_make_read_pipe_transportz0_UnixSelectorEventLoop._make_read_pipe_transportcCrar)_UnixWritePipeTransportrcrrr_make_write_pipe_transportriz1_UnixSelectorEventLoop._make_write_pipe_transportc stU} | std|} t||||||||f| |d| } | | |j| z| IdHWnt t fy?t yQ| | IdHwWd| S1s]wY| S)NzRasyncio.get_child_watcher() is not activated, subprocess support is not installed.)rfrg)rget_child_watcher is_activerI create_future_UnixSubprocessTransportadd_child_handlerget_pid_child_watcher_callback SystemExitKeyboardInterrupt BaseExceptionr-_wait) r&rerQshellstdinstdoutstderrbufsizergkwargswatcherrftransprrr_make_subprocess_transports:     z1_UnixSelectorEventLoop._make_subprocess_transportcCs||j|j|dSr)call_soon_threadsafe call_soon_process_exited)r&pid returncoder~rrrrrsz._UnixSelectorEventLoop._child_watcher_callback)sslsockserver_hostnamessl_handshake_timeoutc s|dus t|ts J|r|durtdn|durtd|dur'td|durZ|dur3tdt|}ttjtjd}z|d| ||IdHWn(| |durbtd|j tjksn|j tjkrutd||d|j |||||d IdH\}}||fS) Nz/you have to pass server_hostname when using sslz+server_hostname is only meaningful with ssl1ssl_handshake_timeout is only meaningful with ssl3path and sock can not be specified at the same timerFzno path and sock were specified.A UNIX Domain Stream Socket was expected, got )r)r^rJr rfspathsocketAF_UNIX SOCK_STREAM setblocking sock_connectr-familytype_create_connection_transport) r&protocol_factorypathrrrr transportrerrrcreate_unix_connectionsP     z-_UnixSelectorEventLoop.create_unix_connectiondT)rbacklogrr start_servingc st|tr td|dur|std|dur|dur tdt|}ttjtj}|ddvrezt t |j rBt |Wn!t yLYntyd}z td||WYd}~nd}~wwz||WnFty} z|| jtjkrd|d} ttj| dd} ~ w||durtd |jtjks|jtjkrtd ||d t||g||||} |r| tdIdH| S) Nz*ssl argument must be an SSLContext or Nonerrr)rz2Unable to check or remove stale UNIX socket %r: %rzAddress z is already in usez-path was not specified, and no sock specifiedrF)r^boolrAr rrrrrstatS_ISSOCKst_moderemoveFileNotFoundErrorrHr errorbindr-rN EADDRINUSErrrrServer_start_servingr sleep) r&rrrrrrrerrrRmsgserverrrrcreate_unix_serversp            z)_UnixSelectorEventLoop.create_unix_serverc sztjWn tytdwz|}Wnttjfy-}ztdd}~wwzt|j }Wn t yBtdw|rG|n|}|sMdS| } | | d|||||d| IdHS)Nzos.sendfile() is not availableznot a regular filer) rsendfileAttributeErrorrSendfileNotAvailableErrorrGioUnsupportedOperationfstatst_sizerHrn_sock_sendfile_native_impl) r&rfileoffsetcountrGrfsize blocksizefutrrr_sock_sendfile_nativeUs6         z,_UnixSelectorEventLoop._sock_sendfile_nativec Cs*|} |dur |||r||||dS|r2||}|dkr2||||||dSz t| |||} Wnttfya|durO| ||| | |j || |||||| YdSt y} zK|dur| j t jkrt| turtdt j} | | _| } |dkrtd} |||||| n|||||| WYd} ~ dSWYd} ~ dSd} ~ wttfyty} z|||||| WYd} ~ dSd} ~ ww| dkr||||||dS|| 7}|| 7}|dur| ||| | |j || |||||| dS)Nrzsocket is not connectedzos.sendfile call failed)rG remove_writer cancelled_sock_sendfile_update_filepos set_resultrrBlockingIOErrorInterruptedError_sock_add_cancellation_callback add_writerrrHrNENOTCONNrConnectionError __cause__rr set_exceptionrsrtru)r&r registered_fdrrGrrr total_sentfdsentrRnew_excrrrrrlst           z1_UnixSelectorEventLoop._sock_sendfile_native_implcCs |dkrt||tjdSdSNr)rlseekSEEK_SET)r&rGrrrrrrsz4_UnixSelectorEventLoop._sock_sendfile_update_fileposcsfdd}||dS)Ncs.|r}|dkr|dSdSdS)Nr;)rrGr)rrr&rrrcbs zB_UnixSelectorEventLoop._sock_add_cancellation_callback..cb)add_done_callback)r&rrrrrrrsz6_UnixSelectorEventLoop._sock_add_cancellation_callbackrNN)__name__ __module__ __qualname____doc__r$r-r:rUr8r1rBrhrkrrrrrrrrr __classcell__rrr(rr"9sD -       . CFr"cseZdZdZdfdd ZddZddZd d Zd d Zd dZ ddZ ddZ ddZ e jfddZdddZddZddZZS) rbiNcst|||jd<||_||_||_||_d|_d|_ t |jj }t |sBt |sBt |sBd|_d|_d|_tdt |jd|j|jj||j|jj|j|j|durm|jtj|ddSdS)NrdFz)Pipe transport is for pipes/sockets only.)r#r$_extra_loop_piperG_fileno _protocol_closing_pausedrrrrS_ISFIFOrS_ISCHRr set_blockingrconnection_made _add_reader _read_readyr _set_result_unless_cancelled)r&looprdrerfrgmoder(rrr$s8      z_UnixReadPipeTransport.__init__cCs|jjg}|jdur|dn|jr|d|d|jt|jdd}|jdurH|durHt ||jt j }|rB|dn|dn|jdurS|dn|dd d |S) Nclosedclosingfd= _selectorpollingidleopen<{}> )r)rrappendrrgetattrrr _test_selector_event selectors EVENT_READformatjoin)r&rMr'rrrr__repr__s$          z_UnixReadPipeTransport.__repr__c Csz t|j|j}Wn$ttfyYdSty.}z ||dWYd}~dSd}~ww|r9|j |dS|j rDt d|d|_|j |j|j |jj|j |jddS)Nz"Fatal read error on pipe transport%r was closed by peerT)rreadrmax_sizerrrH _fatal_errorr data_receivedr get_debugr rMr_remove_readerr eof_received_call_connection_lost)r&r9rRrrrrs   z"_UnixReadPipeTransport._read_readycCsB|js|jrdSd|_|j|j|jrtd|dSdS)NTz%r pauses reading)rrrrrrr debugr&rrr pause_readings  z$_UnixReadPipeTransport.pause_readingcCsF|js|jsdSd|_|j|j|j|jr!td|dSdS)NFz%r resumes reading) rrrrrrrr rrrrrresume_readings  z%_UnixReadPipeTransport.resume_readingcC ||_dSrrr&rerrr set_protocol z#_UnixReadPipeTransport.set_protocolcC|jSrrrrrr get_protocolz#_UnixReadPipeTransport.get_protocolcCr rrrrrr is_closingrz!_UnixReadPipeTransport.is_closingcCs|js |ddSdSr)r_closerrrrr-!sz_UnixReadPipeTransport.closecC0|jdur|d|t|d|jdSdSNzunclosed transport r+rr4r-r&_warnrrr__del__% z_UnixReadPipeTransport.__del__Fatal error on pipe transportcCsZt|tr|jtjkr|jrtjd||ddn |j||||j d| |dSNz%r: %sTexc_info)message exceptionrre) r^rHrNEIOrrr rcall_exception_handlerrrr&rRrrrrr*s z#_UnixReadPipeTransport._fatal_errorcCs(d|_|j|j|j|j|dSNT)rrrrrrr&rRrrrr8sz_UnixReadPipeTransport._closecCNz|j|W|jd|_d|_d|_dS|jd|_d|_d|_wrrconnection_lostrr-rr#rrrr=   z,_UnixReadPipeTransport._call_connection_lostrr)rrrrr$rrrrr r rr-r2r3rrrrrrrr(rrbs rbcseZdZd%fdd ZddZddZdd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZejfddZddZd&dd Zd'd!d"Zd#d$ZZS)(rjNc st||||jd<||_||_||_t|_d|_ d|_ t |jj }t|}t|}t|} |sJ|sJ| sJd|_d|_d|_tdt |jd|j|jj|| sd|rptjdsp|j|jj|j|j|dur|jtj|ddSdS)NrdrFz?Pipe transport is only for pipes, sockets and character devicesaix)r#r$rrrGrr bytearray_buffer _conn_lostrrrrrrrrr rrrrr.platform startswithrrr r) r&rrdrerfrgris_charis_fifo is_socketr(rrr$Js8        z _UnixWritePipeTransport.__init__cCs|jjg}|jdur|dn|jr|d|d|jt|jdd}|jdurT|durTt ||jt j }|rB|dn|d| }|d|n|jdur_|dn|dd d |S) Nrrrrrrzbufsize=rrr)r)rrrrrrrr rr EVENT_WRITEget_write_buffer_sizerr)r&rMr'rr{rrrros(          z _UnixWritePipeTransport.__repr__cCs t|jSr)lenr+rrrrr3r z-_UnixWritePipeTransport.get_write_buffer_sizecCs8|jr td||jr|tdS|dS)Nr)rrr rMr+rBrokenPipeErrorrrrrrs   z#_UnixWritePipeTransport._read_readyc CsBt|tttfsJt|t|trt|}|sdS|js!|jr5|jtjkr,t d|jd7_dS|j sz t |j|}Wn5ttfyNd}Yn)ttfyWtyv}z|jd7_||dWYd}~dSd}~ww|t|krdS|dkrt||d}|j|j|j|j |7_ |dS)Nz=pipe closed by peer or os.write(pipe, data) raised exception.rr#Fatal write error on pipe transport)r^bytesr* memoryviewreprr,rr!LOG_THRESHOLD_FOR_CONNLOST_WRITESr warningr+rwriterrrrsrtrurr4r _add_writer _write_ready_maybe_pause_protocol)r&r9nrRrrrr<s<       z_UnixWritePipeTransport.writec Cs|jsJdz t|j|j}Wn@ttfyYdSttfy&tyQ}z |j |j d7_ |j |j| |dWYd}~dSd}~ww|t|jkrz|j |j |j||jrx|j |j|ddS|dkr|jd|=dSdS)NzData should not be emptyrr6r)r+rr<rrrrsrtrur5r,r_remove_writerrr4_maybe_resume_protocolrrr)r&r@rRrrrr>s2   z$_UnixWritePipeTransport._write_readycCrr"rrrrr can_write_eofz%_UnixWritePipeTransport.can_write_eofcCsF|jrdS|js Jd|_|js!|j|j|j|jddSdSr")rrr+rrrrrrrrr write_eofs z!_UnixWritePipeTransport.write_eofcCrrrr rrrr r z$_UnixWritePipeTransport.set_protocolcCr rrrrrrr rz$_UnixWritePipeTransport.get_protocolcCr rrrrrrrrz"_UnixWritePipeTransport.is_closingcCs$|jdur|js|dSdSdSr)rrrErrrrr-s z_UnixWritePipeTransport.closecCrrrrrrrrrz_UnixWritePipeTransport.__del__cC|ddSr)rrrrrabortz_UnixWritePipeTransport.abortrcCsNt|tr|jrtjd||ddn |j||||jd||dSr) r^rHrrr rr rrr!rrrrs  z$_UnixWritePipeTransport._fatal_errorcCsFd|_|jr |j|j|j|j|j|j|j|dSr") rr+rrArr5rrrr#rrrrs  z_UnixWritePipeTransport._closecCr$rr%r#rrrr r'z-_UnixWritePipeTransport._call_connection_lostrr(r)rrrr$rr3rr<r>rCrEr r rr-r2r3rrGrrrrrrr(rrjGs$% #   rjc@seZdZddZdS)roc Ksd}|tjkrtjdrt\}}z7tj|f||||d|d||_|dur:| t | d|d|j_ d}W|durI| | dSdS|durX| | ww)Nr)F)rwrxryrzuniversal_newlinesr{wb) buffering) subprocessPIPEr.r-r.r socketpairPopen_procr-rdetachrx) r&rQrwrxryrzr{r|stdin_wrrr_starts0    z_UnixSubprocessTransport._startN)rrrrSrrrrros roc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS)raHAbstract base class for monitoring child processes. Objects derived from this class monitor a collection of subprocesses and report their termination or interruption by a signal. New callbacks are registered with .add_child_handler(). Starting a new process must be done within a 'with' block to allow the watcher to suspend its activity until the new process if fully registered (this is needed to prevent a race condition in some implementations). Example: with watcher: proc = subprocess.Popen("sleep 1") watcher.add_child_handler(proc.pid, callback) Notes: Implementations of this class must be thread-safe. Since child watcher objects may catch the SIGCHLD signal and call waitpid(-1), there should be only one active object per process. cGt)aRegister a new child handler. Arrange for callback(pid, returncode, *args) to be called when process 'pid' terminates. Specifying another callback for the same process replaces the previous handler. Note: callback() must be thread-safe. NotImplementedErrorr&rrPrQrrrrpCs z&AbstractChildWatcher.add_child_handlercCrT)zRemoves the handler for process 'pid'. The function returns True if the handler was successfully removed, False if there was nothing to remove.rUr&rrrrremove_child_handlerNsz)AbstractChildWatcher.remove_child_handlercCrT)zAttach the watcher to an event loop. If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop. Note: loop may be None. rUr&rrrr attach_loopVsz AbstractChildWatcher.attach_loopcCrT)zlClose the watcher. This must be called to make sure that any underlying resource is freed. rUrrrrr-`szAbstractChildWatcher.closecCrT)zReturn ``True`` if the watcher is active and is used by the event loop. Return True if the watcher is installed and ready to handle process exit notifications. rUrrrrrmgszAbstractChildWatcher.is_activecCrT)zdEnter the watcher's context and allow starting new processes This function must return selfrUrrrr __enter__pszAbstractChildWatcher.__enter__cCrT)zExit the watcher's contextrUr&abcrrr__exit__vszAbstractChildWatcher.__exit__N) rrrrrprYr[r-rmr\rarrrrr,s   rc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS)ra6Child watcher implementation using Linux's pid file descriptors. This child watcher polls process file descriptors (pidfds) to await child process termination. In some respects, PidfdChildWatcher is a "Goldilocks" child watcher implementation. It doesn't require signals or threads, doesn't interfere with any processes launched outside the event loop, and scales linearly with the number of subprocesses launched by the event loop. The main disadvantage is that pidfds are specific to Linux, and only work on recent (5.3+) kernels. cCd|_i|_dSrr _callbacksrrrrr$ zPidfdChildWatcher.__init__cC|Srrrrrrr\rDzPidfdChildWatcher.__enter__cCdSrr)r&exc_type exc_value exc_tracebackrrrrarDzPidfdChildWatcher.__exit__cC|jduo |jSrr is_runningrrrrrmzPidfdChildWatcher.is_activecCrFrr[rrrrr-rHzPidfdChildWatcher.closecCsd|jdur|dur|jrtdt|jD]\}}}|j|t|q|j ||_dSNzCA loop is being detached from a child watcher with pending handlers) rrdr2r3RuntimeWarningvaluesrrr-r5)r&rpidfd_rrrr[s    zPidfdChildWatcher.attach_loopcGs\|j|}|dur|d||f|j|<dSt|}|j||j||||f|j|<dSr)rdrVr pidfd_openrr_do_wait)r&rrPrQexistingrsrrrrps  z#PidfdChildWatcher.add_child_handlercCs~|j|\}}}|j|z t|d\}}Wnty*d}td|Ynwt |}t ||||g|RdS)NrzJchild process pid %d exit status already read: will report returncode 255) rdpoprrrwaitpidChildProcessErrorr r;rr-)r&rrsrPrQrtr!rrrrrvs   zPidfdChildWatcher._do_waitcCsFz |j|\}}}Wn tyYdSw|j|t|dS)NFT)rdryrYrrrr-)r&rrsrtrrrrYs   z&PidfdChildWatcher.remove_child_handlerN) rrrrr$r\rarmr-r[rprvrYrrrrr{s   rc@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)BaseChildWatchercCrbrrcrrrrr$rezBaseChildWatcher.__init__cCrFrrorrrrr-rHzBaseChildWatcher.closecCrkrrlrrrrrmrnzBaseChildWatcher.is_activecCrTrrU)r& expected_pidrrr _do_waitpidrzBaseChildWatcher._do_waitpidcCrTrrUrrrr_do_waitpid_allrz BaseChildWatcher._do_waitpid_allcCs|dus t|tjs J|jdur|dur|jrtdt|jdur*|jt j ||_|dur?| t j |j | dSdSrp)r^rAbstractEventLooprrdr2r3rqr1rDSIGCHLDrU _sig_chldrrZrrrr[s  zBaseChildWatcher.attach_loopc CsZz|WdSttfyty,}z|jd|dWYd}~dSd}~ww)N$Unknown exception in SIGCHLD handler)rr)rrsrtrurr r#rrrrszBaseChildWatcher._sig_chldN) rrrr$r-rmr~rr[rrrrrr|s r|csPeZdZdZfddZddZddZdd Zd d Zd d Z ddZ Z S)rad'Safe' child watcher implementation. This implementation avoids disrupting other code spawning processes by polling explicitly each process in the SIGCHLD handler instead of calling os.waitpid(-1). This is a safe solution but it has a significant overhead when handling a big number of children (O(n) each time SIGCHLD is raised) cs|jtdSr)rdr5r#r-rr(rrr- s zSafeChildWatcher.closecCrfrrrrrrr\ rDzSafeChildWatcher.__enter__cCrgrrr]rrrrarDzSafeChildWatcher.__exit__cGs||f|j|<||dSr)rdr~rWrrrrpsz"SafeChildWatcher.add_child_handlercC$z|j|=WdStyYdSwNTFrdrYrXrrrrY  z%SafeChildWatcher.remove_child_handlercCt|jD]}||qdSrr0rdr~rXrrrr s z SafeChildWatcher._do_waitpid_allcCs|dksJz t|tj\}}Wnty$|}d}td|Ynw|dkr+dSt|}|jr;t d||z |j |\}}Wnt y_|jr\tjd|ddYdSYdSw|||g|RdS)Nrrx8Unknown child process pid %d, will report returncode 255$process %s exited with returncode %s'Child watcher got an unexpected pid: %rTr) rrzWNOHANGr{r r;rrrrrdryrY)r&r}rr!rrPrQrrrr~%s8       zSafeChildWatcher._do_waitpid) rrrrr-r\rarprYrr~rrrr(rrs rcsTeZdZdZfddZfddZddZdd Zd d Zd d Z ddZ Z S)raW'Fast' child watcher implementation. This implementation reaps every terminated processes by calling os.waitpid(-1) directly, possibly breaking other code spawning processes and waiting for their termination. There is no noticeable overhead when handling a big number of children (O(1) each time a child terminates). cs$tt|_i|_d|_dSr)r#r$ threadingLock_lock_zombies_forksrr(rrr$Rs   zFastChildWatcher.__init__cs"|j|jtdSr)rdr5rr#r-rr(rrr-Xs  zFastChildWatcher.closecCs<|j|jd7_|WdS1swYdS)Nr)rrrrrrr\]s$zFastChildWatcher.__enter__cCsv|j(|jd8_|js|js WddSt|j}|jWdn1s.wYtd|dS)Nrz5Caught subprocesses termination from unknown pids: %s)rrrrJr5r r;)r&r^r_r`collateral_victimsrrrracs    zFastChildWatcher.__exit__c Gs|jsJd|j(z|j|}Wnty*||f|j|<YWddSwWdn1s5wY|||g|RdS)NzMust use the context manager)rrrryrYrd)r&rrPrQrrrrrpqs  z"FastChildWatcher.add_child_handlercCrrrrXrrrrYrz%FastChildWatcher.remove_child_handlerc Cs z tdtj\}}Wn tyYdSw|dkrdSt|}|jFz |j|\}}Wn'tyV|j rR||j |<|j rJt d||YWdqd}Yn w|j rct d||Wdn1smwY|dur~t d||n |||g|Rq)NTr;rz,unknown process %s exited with returncode %srz8Caught subprocess termination from unknown pid: %d -> %d)rrzrr{rrrdryrYrrrrr rr;)r&rr!rrPrQrrrrsH      z FastChildWatcher._do_waitpid_all) rrrrr$r-r\rarprYrrrrr(rrHs rc@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)ra~A watcher that doesn't require running loop in the main thread. This implementation registers a SIGCHLD signal handler on instantiation (which may conflict with other code that install own handler for this signal). The solution is safe but it has a significant overhead when handling a big number of processes (*O(n)* each time a SIGCHLD is received). cCsi|_d|_dSr)rd_saved_sighandlerrrrrr$rezMultiLoopChildWatcher.__init__cCs |jduSr)rrrrrrmr zMultiLoopChildWatcher.is_activecCsT|j|jdur dSttj}||jkrtdnttj|jd|_dS)Nz+SIGCHLD handler was changed by outside code) rdr5rrD getsignalrrr r;)r&r]rrrr-s      zMultiLoopChildWatcher.closecCrfrrrrrrr\rDzMultiLoopChildWatcher.__enter__cCrgrrr&rhexc_valexc_tbrrrrarDzMultiLoopChildWatcher.__exit__cGs&t}|||f|j|<||dSr)rget_running_looprdr~)r&rrPrQrrrrrpsz'MultiLoopChildWatcher.add_child_handlercCrrrrXrrrrYrz*MultiLoopChildWatcher.remove_child_handlercCsN|jdurdSttj|j|_|jdurtdtj|_ttjddS)NzaPrevious SIGCHLD handler was set by non-Python code, restore to default handler on watcher close.F)rrDrrr r;r\rLrZrrrr[s   z!MultiLoopChildWatcher.attach_loopcCrrrrXrrrrs z%MultiLoopChildWatcher._do_waitpid_allc Cs|dksJz t|tj\}}Wnty&|}d}td|d}Yn w|dkr-dSt|}d}z |j|\}}}Wnt yPtjd|ddYdSw| r^td||dS|rk| rkt d |||j |||g|RdS) NrrxrFTrr%Loop %r that handles pid %r is closedr)rrzrr{r r;rrdryrY is_closedrrr) r&r}rr!r debug_logrrPrQrrrr~s<      z!MultiLoopChildWatcher._do_waitpidc CsDz|WdSttfyty!tjdddYdSw)NrTr)rrsrtrur r;)r&rrrrrr%s zMultiLoopChildWatcher._sig_chldN)rrrrr$rmr-r\rarprYr[rr~rrrrrrs  %rc@sneZdZdZddZddZddZdd Zd d Zd d Z e j fddZ ddZ ddZddZddZdS)raAThreaded child watcher implementation. The watcher uses a thread per process for waiting for the process finish. It doesn't require subscription on POSIX signal but a thread creation is not free. The watcher has O(1) complexity, its performance doesn't depend on amount of spawn processes. cCstd|_i|_dSr) itertoolsr _pid_counter_threadsrrrrr$;r*zThreadedChildWatcher.__init__cCrr"rrrrrrm?rDzThreadedChildWatcher.is_activecCs |dSr) _join_threadsrrrrr-Bs zThreadedChildWatcher.closecCs.ddt|jD}|D]}|qdS)z%Internal: Join all non-daemon threadscSsg|] }|r|js|qSr)is_alivedaemon.0threadrrr Gs  z6ThreadedChildWatcher._join_threads..N)r0rrrr)r&threadsrrrrrEs z"ThreadedChildWatcher._join_threadscCrfrrrrrrr\LrDzThreadedChildWatcher.__enter__cCrgrrrrrrraOrDzThreadedChildWatcher.__exit__cCs:ddt|jD}|r||jdt|ddSdS)NcSsg|]}|r|qSr)rrrrrrSs z0ThreadedChildWatcher.__del__..z0 has registered but not finished child processesr+)r0rrrr)r4)r&rrrrrrRs  zThreadedChildWatcher.__del__cGsFt}tj|jdt|j||||fdd}||j|<|dS)Nzwaitpid-T)targetnamerQr) rrrThreadr~nextrrstart)r&rrPrQrrrrrrpZs   z&ThreadedChildWatcher.add_child_handlercCrr"rrXrrrrYcsz)ThreadedChildWatcher.remove_child_handlercCrgrrrZrrrr[irDz ThreadedChildWatcher.attach_loopcCs|dksJz t|d\}}Wnty#|}d}td|Ynwt|}|r3td|||r?td||n |j |||g|R|j |dS)Nrrxrrr) rrzr{r r;rrrrrrry)r&rr}rPrQrr!rrrrr~ls(   z ThreadedChildWatcher._do_waitpidN)rrrrr$rmr-rr\rar2r3rrprYr[r~rrrrr.s   rcsHeZdZdZeZfddZddZfddZdd Z d d Z Z S) _UnixDefaultEventLoopPolicyz:UNIX event loop policy with a watcher for child processes.cstd|_dSr)r#r$_watcherrr(rrr$s  z$_UnixDefaultEventLoopPolicy.__init__cCs~tj2|jdur%t|_ttur-|j|jj WddSWddSWddS1s8wYdSr) rrrrrcurrent_thread main_threadr[_localrrrrr _init_watchers "z)_UnixDefaultEventLoopPolicy._init_watchercs>t||jdurttur|j|dSdSdS)zSet the event loop. As a side effect, if a child watcher was set before, then calling .set_event_loop() from the main thread will call .attach_loop(loop) on the child watcher. N)r#set_event_looprrrrr[rZr(rrrs  z*_UnixDefaultEventLoopPolicy.set_event_loopcCs|jdur ||jS)z~Get the watcher for child processes. If not yet set, a ThreadedChildWatcher object is automatically created. N)rrrrrrrls z-_UnixDefaultEventLoopPolicy.get_child_watchercCs4|dus t|ts J|jdur|j||_dS)z$Set the watcher for child processes.N)r^rrr-)r&r}rrrset_child_watchers   z-_UnixDefaultEventLoopPolicy.set_child_watcher) rrrrr" _loop_factoryr$rrrlrrrrr(rrs   r)3rrNrrrrrDrrrLr.rr2rrrrrrr r r r logr __all__r- ImportErrorrrBaseSelectorEventLoopr" ReadTransportrb_FlowControlMixinWriteTransportrjBaseSubprocessTransportrorrr|rrrrBaseDefaultEventLoopPolicyrrrrrrrsd               NON5Ji}Y2