
    Vhe>                       d Z ddlmZ ddlmZmZmZmZ ddlZddl	Z	ddl
mZ ddlmZmZmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ  ej<                  dd       G d d             Z G d d      Z  e        Z! G d dejD                        Z# G d dejH                        Z% G d dejL                        Z'y)zA
Support for starting, monitoring, and restarting child process.
    )annotations)AnyDictListOptionalN)service)errorprotocolreactor)IDelayedCallIProcessTransportIReactorProcessIReactorTime)Logger)basic)	deprecate)FailureT)frozenauto_attribsc                      e Zd ZU dZded<   dZded<   dZded<    ej                   ej                  e
            Zd	ed
<   dZded<    ej                   ej                   dddd            dd       Zy)_Processa"  
    The parameters of a process to be restarted.

    @ivar args: command-line arguments (including name of command as first one)
    @type args: C{list}

    @ivar uid: user-id to run process as, or None (which means inherit uid)
    @type uid: C{int}

    @ivar gid: group-id to run process as, or None (which means inherit gid)
    @type gid: C{int}

    @ivar env: environment for process
    @type env: C{dict}

    @ivar cwd: initial working directory for process or None
               (which means inherit cwd)
    @type cwd: C{str}
    z	List[str]argsNzOptional[int]uidgid)defaultzDict[str, str]envzOptional[str]cwdTwisted      r   c                ^    | j                   | j                  | j                  | j                  fS )a^  
        Convert process to tuple.

        Convert process to tuple that looks like the legacy structure
        of processes, for potential users who inspected processes
        directly.

        This was only an accidental feature, and will be removed. If
        you need to remember what processes were added to a process monitor,
        keep track of that when they are added. The process list
        inside the process monitor is no longer a public API.

        This allows changing the internal structure of the process list,
        when warranted by bug fixes or additional features.
        )r   r   r   r   selfs    F/home/dcms/DCMS/lib/python3.12/site-packages/twisted/runner/procmon.pytoTuplez_Process.toTuple9   s#    " 		488TXXtxx88    )returnz8tuple[list[str], int | None, int | None, dict[str, str]])__name__
__module____qualname____doc____annotations__r   r   attribFactorydictr   r   r   
deprecatedincrementalVersionr%    r&   r$   r   r      s    ( OCC!$'',$,,t*<=C=CY-+--iQBC9 D9r&   r   c                      e Zd ZdZy)DummyTransportr   N)r(   r)   r*   disconnectingr4   r&   r$   r6   r6   M   s    Mr&   r6   c                  N    e Zd ZU ded<   ded<   ded<   ded<   dZdZd	ZdZdd
Zy)
LineLoggerstrtagstreamProcessMonitorr   bytes	delimiterN   
c                    	 |j                  d      }| j                  j                  j                  d| j                  || j                         y # t        $ r t        |      }Y Tw xY w)Nzutf-8z[{tag}] {line})r;   liner<   )decodeUnicodeDecodeErrorreprr   loginfor;   r<   )r#   rB   slines      r$   lineReceivedzLineLogger.lineReceiveda   s_    	KK(E 	$((t{{ 	 	
 " 	JE	s   A A('A()rB   r>   r'   None)	r(   r)   r*   r,   r;   r<   r?   r   rI   r4   r&   r$   r9   r9   T   s3    	HK CFIG
r&   r9   c                  n    e Zd ZU ded<   ded<   dZdZddZddZddZdd	Z	e
dd
       Ze
dd       Zy)LoggingProtocolr=   r   r:   nameNc                   t               | _        | j                  | j                  _        d| j                  _        | j
                  | j                  _        d| _        t               | _        | j                  | j                  _        d| j                  _        | j
                  | j                  _        d| _        | j                  j                  t               | j                  j                  t               y )NstdoutTstderr)r9   _outputrM   r;   r<   r   _outputEmpty_error_errorEmptymakeConnection	transportr"   s    r$   connectionMadezLoggingProtocol.connectionMadeu   s    !|99&#||  l))%"ll##I.""9-r&   c                T    | j                   j                  |       |d   dk(  | _        y Nr@   )rQ   dataReceivedrR   r#   datas     r$   outReceivedzLoggingProtocol.outReceived   s%    !!$' H-r&   c                T    | j                   j                  |       |d   dk(  | _        y rY   )rS   r[   rT   r\   s     r$   errReceivedzLoggingProtocol.errReceived   s%      &8u,r&   c                    | j                   s| j                  j                  d       | j                  s| j                  j                  d       | j
                  j                  | j                  |       y )Nr@   )rR   rQ   r[   rT   rS   r   _monitoredProcessExitedrM   )r#   reasons     r$   processEndedzLoggingProtocol.processEnded   sP      LL%%e,KK$$U+,,TYY?r&   c                    | j                   S N)rQ   r"   s    r$   outputzLoggingProtocol.output   s    ||r&   c                    | j                   S rf   )rR   r"   s    r$   emptyzLoggingProtocol.empty   s       r&   r'   rJ   )r]   r>   r'   rJ   )rc   r   r'   rJ   )r'   r9   )r'   bool)r(   r)   r*   r,   r   rM   rW   r^   r`   rd   propertyrg   ri   r4   r&   r$   rL   rL   l   sV    
I GD. .-@   ! !r&   rL   c                     e Zd ZdZdZdZdZdZ e       Z	e
f	 	 	 ddZ ej                   ej                  dddd	            	 	 dd
       Z ej"                   ej                  dddd	            dd       Zddi df	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZddZddZ ej                   ej                  dddd	            dd       Zdd dZddZd!dZddZddZd"dZy)#r=   a
  
    ProcessMonitor runs processes, monitors their progress, and restarts them
    when they die.

    The ProcessMonitor will not attempt to restart a process that appears to
    die instantly -- with each "instant" death (less than 1 second, by
    default), it will delay approximately twice as long before restarting it.
    A successful run will reset the counter.

    The primary interface is L{addProcess} and L{removeProcess}.  When the
    service is running (that is, when the application it is attached to is
    running), adding a process automatically starts it.

    Each process has a name.  This name string must uniquely identify the
    process.  In particular, attempting to add two processes with the same name
    will result in a C{KeyError}.

    @type threshold: C{float}
    @ivar threshold: How long a process has to live before the death is
        considered instant, in seconds.  The default value is 1 second.

    @type killTime: C{float}
    @ivar killTime: How long a process being killed has to get its affairs in
        order before it gets killed with an unmaskable signal.  The default
        value is 5 seconds.

    @type minRestartDelay: C{float}
    @ivar minRestartDelay: The minimum time (in seconds) to wait before
        attempting to restart a process.  Default 1s.

    @type maxRestartDelay: C{float}
    @ivar maxRestartDelay: The maximum time (in seconds) to wait before
        attempting to restart a process.  Default 3600s (1h).

    @type _reactor: L{IReactorProcess} provider
    @ivar _reactor: A provider of L{IReactorProcess} and L{IReactorTime} which
        will be used to spawn processes and register delayed calls.

    @type log: L{Logger}
    @ivar log: The logger used to propagate log messages from spawned
        processes.
          i  c                    || _         t        |      | _        i | _        i | _        i | _        i | _        i | _        i | _        y rf   )	_reactorr   _clock
_processes	protocolsdelaytimeStartedmurderrestart)r#   r   s     r$   __init__zProcessMonitor.__init__   sB      "7+/157')
-//102r&   r   r   r    r   c                    | j                   j                         D ci c]  \  }}||j                          c}}S c c}}w )zu
        Processes as dict of tuples

        @return: Dict of process name to monitored processes as tuples
        )rs   itemsr%   )r#   rM   processs      r$   	processeszProcessMonitor.processes   s6     >B__=R=R=TUMD'goo''UUUs   =c                    t         j                  j                  |       }|d= i |d<   i |d<   i |d<   i |d<   i |d<   |d= | j                  |d<   |S )	Nrq   rt   ru   rv   rw   rx   rs   r}   )r   Service__getstate__r}   )r#   dcts     r$   r   zProcessMonitor.__getstate__   sg    oo**40
OKGMHI>>K
r&   Nc                    || j                   v rt        d| d      t        |||||      | j                   |<   | j                  | j                  |<   | j
                  r| j                  |       yy)a  
        Add a new monitored process and start it immediately if the
        L{ProcessMonitor} service is running.

        Note that args are passed to the system call, not to the shell.  If
        running the shell is desired, the common idiom is to use
        C{ProcessMonitor.addProcess("name", ['/bin/sh', '-c', shell_script])}

        @param name: A name for this process.  This value must be unique across
            all processes added to this monitor.

        @param args: The argv sequence for the process to launch.

        @param uid: The user ID to use to run the process.  If L{None}, the
            current UID is used.

        @param gid: The group ID to use to run the process.  If L{None}, the
            current GID is used.

        @param env: The environment to give to the launched process.  See
            L{IReactorProcess.spawnProcess}'s C{env} parameter.

        @param cwd: The initial working directory of the launched process.  The
            default of C{None} means inheriting the laucnhing process's working
            directory.

        @raise KeyError: If a process with the given name already exists.
        zremove z firstN)rs   KeyErrorr   minRestartDelayru   runningstartProcess)r#   rM   r   r   r   r   r   s          r$   
addProcesszProcessMonitor.addProcess   sn    J 4??"WTF&122 (sCc B//

4<<d# r&   c                @    | j                  |       | j                  |= y)z
        Stop the named process and remove it from the list of monitored
        processes.

        @param name: A string that uniquely identifies the process.
        N)stopProcessrs   r#   rM   s     r$   removeProcesszProcessMonitor.removeProcess!  s     	OOD!r&   c                    t         j                  j                  |        t        | j                        D ]  }| j                  |        y)z0
        Start all monitored processes.
        N)r   r   startServicelistrs   r   r   s     r$   r   zProcessMonitor.startService+  s<     	$$T*) 	$Dd#	$r&   c                0   t         j                  j                  |        t        | j                  j                               D ]&  \  }}|j                         s|j                          ( t        | j                        D ]  }| j                  |        y)zY
        Stop all monitored processes and cancel all scheduled process restarts.
        N)
r   r   stopServicer   rx   r{   activecancelrs   r   )r#   rM   delayedCalls      r$   r   zProcessMonitor.stopService3  s~     	##D) "&dll&8&8&:!; 	%D+!!#""$	% ) 	#DT"	#r&      c                $    | j                  |      S )a  
        Called when a monitored processes exits.  If
        L{service.IService.running} is L{True} (ie the service is started), the
        process will be restarted.  If the process had been running for more
        than L{ProcessMonitor.threshold} seconds it will be restarted
        immediately.  If the process had been running for less than
        L{ProcessMonitor.threshold} seconds, the restart will be delayed and
        each time the process dies before the configured threshold, the restart
        delay will be doubled - up to a maximum delay of maxRestartDelay sec.

        @param name: A string that uniquely identifies the process which
            exited.
        )rb   r   s     r$   connectionLostzProcessMonitor.connectionLostA  s     ++D11r&   c                .   |L|j                  t        j                  t        j                        s| j                  j                  d||       || j                  v rG| j                  |   j                         r| j                  |   j                          | j                  |= | j                  |= | j                  j                         | j                  |   z
  | j                  k  rC| j                  |   }t        | j                  |   dz  | j                         | j                  |<   nd}| j"                  | j                  |<   | j$                  rD|| j&                  v r5| j                  j)                  || j*                  |      | j,                  |<   yyy)a  
        Called when a monitored processes exits.  If
        L{service.IService.running} is L{True} (ie the service is started), the
        process will be restarted.  If the process had been running for more
        than L{ProcessMonitor.threshold} seconds it will be restarted
        immediately.  If the process had been running for less than
        L{ProcessMonitor.threshold} seconds, the restart will be delayed and
        each time the process dies before the configured threshold, the restart
        delay will be doubled - up to a maximum delay of maxRestartDelay sec.

        @param name: A string that uniquely identifies the process which
            exited.

        @param reason: The reason why the connection was lost.
        Nz(Process '{name}' has exited: {failure!r})failurerM      r   )checkr	   ProcessDoneProcessTerminatedrF   r   rw   r   r   rt   rr   secondsrv   	thresholdru   minmaxRestartDelayr   r   rs   	callLaterr   rx   )r#   rM   rc   	nextDelays       r$   rb   z&ProcessMonitor._monitoredProcessExitedR  sY   " fll##'
 HH:   4;;{{4 '')D!((*D!NN4 ;; 4#3#3D#99DNNJ

4(I"4::d#3a#79M9MNDJJt
 I#33DJJt <<DDOO3!%!6!64,,d"DLL 4<r&   c           	        || j                   v ry| j                  |   }t               }| |_        ||_        || j                   |<   | j
                  j                         | j                  |<   	 | j                  j                  ||j                  d   |j                  |j                  |j                  |j                  |j                         y# t        $ r | j!                  |t#                      Y yw xY w)zD
        @param name: The name of the process to be started
        Nr   )r   r   r   path)rt   rs   rL   r   rM   rr   r   rv   rq   spawnProcessr   r   r   r   r   OSErrorrb   r   )r#   rM   r|   protos       r$   r   zProcessMonitor.startProcess  s     4>>!//$'!
$t!%!4!4!6	:MM&&QKKKKKK[[ '   	:((wy9	:s   .A!C #C65C6c                Z    	 |j                  d       y # t        j                  $ r Y y w xY w)NKILL)signalProcessr	   ProcessExitedAlready)r#   procs     r$   _forceStopProcessz ProcessMonitor._forceStopProcess  s-    	v&)) 		s    **c                l   || j                   vrt        d|       | j                  j                  |d      }|a|j                  }|J 	 |j                  d       | j                  j                  | j                  | j                  |      | j                  |<   yy# t        j                  $ r Y yw xY w)zD
        @param name: The name of the process to be stopped
        zUnrecognized process name: NTERM)rs   r   rt   getrV   r   rr   r   killTimer   rw   r	   r   )r#   rM   r   r   s       r$   r   zProcessMonitor.stopProcess  s     t&8?@@""4.??D###""6* %)KK$9$9MM4#9#94%D! 
 -- s   B B32B3c                H    | j                   D ]  }| j                  |        y)z
        Restart all processes. This is useful for third party management
        services to allow a user to restart servers because of an outside change
        in circumstances -- for example, a new version of a library is
        installed.
        N)rs   r   r   s     r$   
restartAllzProcessMonitor.restartAll  s%     OO 	#DT"	#r&   c                   g }| j                   j                         D ]{  \  }}d}|j                  t        |j                        }|j                  |dt        |j                        z   z  }|rd|z   dz   }|j                  || d|j                         } d| j                  j                  z   dz   dj                  |      z   dz   S )	N :()z: < >)
rs   r{   r   r:   r   appendr   	__class__r(   join)r#   lstrM   r   uidgids        r$   __repr__zProcessMonitor.__repr__  s    ////1 		;JD$Fxx#TXXxx##DHH--v+JJ$&DII=9:		; T^^,,,s2SXXc]BSHHr&   )r   r   r'   rJ   )r'   zCdict[str, tuple[list[str], int | None, int | None, dict[str, str]]])r'   r   )rM   r:   r   z	list[str]r   
int | Noner   r   r   zdict[str, str]r   z
str | Noner'   rJ   )rM   r:   r'   rJ   rj   rf   )rM   r:   rc   zFailure | Noner'   rJ   )r   r   r'   rJ   )r'   r:   )r(   r)   r*   r+   r   r   r   r   r   rF   rq   ry   r   deprecatedPropertyr2   r3   r}   r1   r   r   r   r   r   r   rb   r   r   r   r   r   r4   r&   r$   r=   r=      su   )V IHOO
(C $,3 3 
3 "Y!!"5+"5"5iQ"JKV	LV LV Y-+--iQBC
 D
   *$*$ *$ 	*$
 *$ *$ *$ 
*$X"$# "Y!!"5+"5"5iQ"JK2 L2 2h::(#Ir&   r=   )(r+   
__future__r   typingr   r   r   r   r-   r2   twisted.applicationr   twisted.internetr	   r
   r   rq   twisted.internet.interfacesr   r   r   r   twisted.loggerr   twisted.protocolsr   twisted.pythonr   twisted.python.failurer   sr   r6   rV   LineReceiverr9   ProcessProtocolrL   r   r=   r4   r&   r$   <module>r      s   
 # , ,   ' A A  " # $ * t$',9 ,9 (,9^  	
## 
0.!h.. .!bvIW__ vIr&   