Ϫf?8UdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z ddlmZmZmZddlmZmZddl mZmZdd lmZdd lmZmZmZdd lmZed k(rd dlm Z m!Z!e e"e e gdfZ#de$d<d'dZ%dZ&GddeZ'eGddZ(eGddZ)eGddZ*eGddZ+GddeZ,ee,Gdd ejZZ.eeGd!d"ejZZ/ee,Gd#d$e/Z0ed k(re0Z1ne.Z1Gd%d&e/Z2y)(a This module is used to integrate child process termination into a reactor event loop. This is a challenging feature to provide because most platforms indicate process termination via SIGCHLD and do not provide a way to wait for that signal and arbitrary I/O events at the same time. The naive implementation involves installing a Python SIGCHLD handler; unfortunately this leads to other syscalls being interrupted (whenever SIGCHLD is received) and failing with EINTR (which almost no one is prepared to handle). This interruption can be disabled via siginterrupt(2) (or one of the equivalent mechanisms); however, if the SIGCHLD is delivered by the platform to a non-main thread (not a common occurrence, but difficult to prove impossible), the main thread (waiting on select() or another event notification API) may not wake up leading to an arbitrary delay before the child termination is noticed. The basic solution to all these issues involves enabling SA_RESTART (ie, disabling system call interruption) and registering a C signal handler which writes a byte to a pipe. The other end of the pipe is registered with the event loop, allowing it to wake up shortly after SIGCHLD is received. See L{_SIGCHLDWaker} for the implementation of the event loop side of this solution. The use of a pipe this way is known as the U{self-pipe trick}. From Python version 2.6, C{signal.siginterrupt} and C{signal.set_wakeup_fd} provide the necessary C signal handler which writes to the pipe to be registered with C{SA_RESTART}. ) annotationsN) FrameType)CallableOptionalSequence) Attribute Interface implementer)definefrozen)Protocol TypeAlias)IReadDescriptor)failurelogutil) platformTypeposix)fdescprocessr SignalHandlerc2|dk(r3tjtjtjnKd}tjtj|tjtjdtj|S)a Install a signal handler which will write a byte to C{fd} when I{SIGCHLD} is received. This is implemented by installing a SIGCHLD handler that does nothing, setting the I{SIGCHLD} handler as not allowed to interrupt system calls, and using L{signal.set_wakeup_fd} to do the actual writing. @param fd: The file descriptor to which to write when I{SIGCHLD} is received. @return: The file descriptor previously configured for this use. cyN)argss ;/usr/lib/python3/dist-packages/twisted/internet/_signals.pynoopSignalHandlerz)installHandler..noopSignalHandlerMs F)signalSIGCHLDSIG_DFL siginterrupt set_wakeup_fd)fdr s rinstallHandlerr(;s` Rx fnnfnn5   fnn&78FNNE2    ##r!cjtjtjtjk(S)zI Determine whether the I{SIGCHLD} handler is the default or not. )r" getsignalr#r$rr!risDefaultHandlerr+Us"   FNN +v~~ ==r!c eZdZdZddZddZy)SignalHandlingaF The L{SignalHandling} protocol enables customizable signal-handling behaviors for reactors. A value that conforms to L{SignalHandling} has install and uninstall hooks that are called by a reactor at the correct times to have the (typically) process-global effects necessary for dealing with signals. cy)z. Install the signal handlers. Nrselfs rinstallzSignalHandling.installfr!cy)zB Restore signal handlers to their original state. Nrr/s r uninstallzSignalHandling.uninstallkr2r!NreturnNone__name__ __module__ __qualname____doc__r1r4rr!rr-r-\s  r!r-c eZdZdZddZddZy)_WithoutSignalHandlingz A L{SignalHandling} implementation that does no signal handling. This is the implementation of C{installSignalHandlers=False}. cy)z5 Do not install any signal handlers. Nrr/s rr1z_WithoutSignalHandling.installyr2r!cy)zB Do nothing because L{install} installed nothing. Nrr/s rr4z _WithoutSignalHandling.uninstall~r2r!Nr5r8rr!rr>r>qs   r!r>c@eZdZUdZded<ded<ded<d dZd dZy) _WithSignalHandlingzg A reactor core helper that can manage signals: it installs signal handlers at start time. r_sigInt _sigBreak_sigTermctjtjtjk(r.tjtj|jtjtj |j ttdd}|!tj||jyy)zI Install the signal handlers for the Twisted event loop. SIGBREAKN) r"r*SIGINTdefault_int_handlerrCSIGTERMrEgetattrrD)r0rGs rr1z_WithSignalHandling.installsz   FMM *f.H.H H MM&-- 6 fnndmm46:t4   MM(DNN 3 r!cy)zE At the moment, do nothing (for historical reasons). Nrr/s rr4z_WithSignalHandling.uninstallr2r!Nr5)r9r:r;r<__annotations__r1r4rr!rrBrBs%  4 r!rBc:eZdZUdZded<dZded<d dZd dZy ) _MultiSignalHandlinga An implementation of L{SignalHandling} which propagates protocol method calls to a number of other implementations. This supports composition of multiple signal handling implementations into a single object so the reactor doesn't have to be concerned with how those implementations are factored. @ivar _signalHandlings: The other C{SignalHandling} implementations to which to propagate calls. @ivar _installed: If L{install} has been called but L{uninstall} has not. This is used to avoid double cleanup which otherwise results (at least during test suite runs) because twisted.internet.reactormixins doesn't keep track of whether a reactor has run or not but always invokes its cleanup logic. zSequence[SignalHandling]_signalHandlingsFbool _installedcT|jD]}|jd|_y)NT)rPr1rRr0ds rr1z_MultiSignalHandling.installs'&& A IIK r!cn|jr)|jD]}|jd|_yy)NF)rRrPr4rTs rr4z_MultiSignalHandling.uninstalls3 ??**   #DO r!Nr5)r9r:r;r<rMrRr1r4rr!rrOrOs#$/.J $r!rOcDeZdZUdZded<ded<dZded<d dZd d Zy) _ChildSignalHandlinga  Signal handling behavior which supports I{SIGCHLD} for notification about changes to child process state. @ivar _childWaker: L{None} or a reference to the L{_SIGCHLDWaker} which is used to properly notice child process termination. This is L{None} when this handling behavior is not installed and non-C{None} otherwise. This is mostly an unfortunate implementation detail due to L{_SIGCHLDWaker} allocating file descriptors as a side-effect of its initializer. z#Callable[[IReadDescriptor], object]_addInternalReader_removeInternalReaderNzOptional[_SIGCHLDWaker] _childWakerc|j*t|_|j|j|jjt j y)z Extend the basic signal handling logic to also support handling SIGCHLD to know when to try to reap child processes. N)r[ _SIGCHLDWakerrYr1rreapAllProcessesr/s rr1z_ChildSignalHandling.installsN    #,D   # #D$4$4 5   "   "r!c|jJ|j|j|jj|jjt j t dd|_y)a If a child waker was created and installed, uninstall it now. Since this disables reactor functionality and is only called when the reactor is stopping, it doesn't provide any directly useful functionality, but the cleanup of reactor-related process-global state that it does helps in unit tests involving multiple reactors and is generally just a nice thing. N uninstalled)r[rZr4connectionLostrFailure Exceptionr/s rr4z_ChildSignalHandling.uninstallsj+++ ""4#3#34 ""$ '' -8P(QR r!r5)r9r:r;r<rMr[r1r4rr!rrXrXs* <;>>+/K(/#& r!rXc8eZdZdZedZddZddZddZy) _IWakeraQ Interface to wake up the event loop based on the self-pipe trick. The U{I{self-pipe trick}}, used to wake up the main loop from another thread or a signal handler. This is why we have wakeUp together with doRead This is used by threads or signals to wake up the event loop. cy)z: Called when the event should be wake up. Nrrr!rwakeUpz_IWaker.wakeUpr2r!cy)zC Read some data from my connection and discard it. Nrrr!rdoReadz_IWaker.doReadr2r!cy)zB Called when connection was closed and the pipes. Nr)reasons rraz_IWaker.connectionLostr2r!Nr5)rlzfailure.Failurer6r7) r9r:r;r<r disconnectedrhrjrarr!rreres!R=L   r!rec.eZdZdZdZddZdZdZdZy) _SocketWakerz The I{self-pipe trick}, implemented using a pair of sockets rather than pipes (due to the lack of support in select() on Windows for pipes), used to wake up the main loop from another thread. rctjtjtj}|jtjtj dt jtjtjtj5}|jd|jd|j|j|j\}}ddd|jdjd||_||_|jj |_y#1swYUxYw) Initialize.r)z 127.0.0.1rNF)socketAF_INET SOCK_STREAM setsockopt IPPROTO_TCP TCP_NODELAY contextlibclosingbindlistenconnect getsocknameaccept setblockingrwfileno)r0clientserverreader clientaddrs r__init__z_SocketWaker.__init__-sv~~v/A/AB&,,f.@.@!D    MM&..&*<*< =  1  KK( ) MM!  NN6--/ 0!' FJ  1 5!5!ffmm  1 1s 'AEEc tj|jjdy#t$r+}|j dt jk7rYd}~yd}~wwxYw)zSend a byte to my connection.xrN)runtilConcludesrsendOSErrorrerrnoWSAEWOULDBLOCKr0es rrhz_SocketWaker.wakeUp?sM     T 2 vvayE0001 s*- A!!AA!cZ |jjdy#t$rYywxYw)z4 Read some data from my connection. i N)rrecvrr/s rrjz_SocketWaker.doReadGs)  FFKK    s  **cl|jj|jjyr)rcloser)r0rls rraz_SocketWaker.connectionLostPs    r!Nr5) r9r:r;r<rmrrhrjrarr!rroro"s"L$$r!roc@eZdZUdZdZded<ded<d dZd dZdZy ) _FDWakera The I{self-pipe trick}, used to wake up the main loop from another thread or a signal handler. L{_FDWaker} is a base class for waker implementations based on writing to a pipe being monitored by the reactor. @ivar o: The file descriptor for the end of the pipe which can be written to wake up a reactor monitoring this waker. @ivar i: The file descriptor which should be monitored in order to be awoken by this waker. rintiocTtj\__t j jt j jt j jt j jfd_y)rqcjSr)rr/srz#_FDWaker.__init__..qs dffr!N)ospiperrrsetNonBlocking_setCloseOnExecrr/s`rrz_FDWaker.__init__jse TVV$ dff% TVV$ dff%$ r!cNtj|jdy)zA Read some bytes from the pipe and discard them. cyrr)datas rrz!_FDWaker.doRead..wr2r!N)r readFromFDrr/s rrjz_FDWaker.doReadss (9:r!ct|dsy|j|jfD]} tj||`|`y#t $rY+wxYw)zClose both ends of my pipe.rN)hasattrrrrrr)r0rlr's rraz_FDWaker.connectionLostysYtS! &&$&&. B    FDF  sA AANr5) r9r:r;r<rmrMrrjrarr!rrrUs' L F F%; r!rceZdZdZdZy) _UnixWakerz This class provides a simple interface to wake up the event loop. This is used by threads or signals to wake up the event loop. c|j1 tjtj|jdyy#t $r(}|j t jk7rYd}~yd}~wwxYw)z)Write one byte to the pipe, and flush it.Nr)rrrrwriterrEAGAINrs rrhz_UnixWaker.wakeUps^ 66  ##BHHdffd;  77ell*+ s/? A0A++A0N)r9r:r;r<rhrr!rrrs  r!rc4eZdZdZddZddZdfd ZxZS)r]zQ L{_SIGCHLDWaker} can wake up a reactor whenever C{SIGCHLD} is received. c.t|jy)zJ Install the handler necessary to make this waker active. N)r(rr/s rr1z_SIGCHLDWaker.installs tvvr!ctdy)zC Remove the handler which makes this waker active. rN)r(r/s rr4z_SIGCHLDWaker.uninstalls  rr!cJt|tjy)a Having woken up the reactor in response to receipt of C{SIGCHLD}, reap the process which exited. This is called whenever the reactor notices the waker pipe is writeable, which happens soon after any call to the C{wakeUp} method. N)superrjrr^)r0 __class__s rrjz_SIGCHLDWaker.doReads   "r!r5)r9r:r;r<r1r4rj __classcell__)rs@rr]r]s  # #r!r])r'rr6r)3r< __future__rrxrrr"rrtypesrtypingrrrzope.interfacerr r attrsr r r rtwisted.internet.interfacesrtwisted.pythonrrrtwisted.python.runtimerrfrrrrrMr(r+r-r>rBrOrXreLoggerrorr_Wakerr]rr!rrs} :# //<< &7--/7 #S(9*=$>$DE yE$4> X *   $   @$$$D9 9 9 x i : W/3:://d _,szz,,^ W*7 FF#H#r!