
    :jQ                         d Z ddlZddlmZmZ ddlmZ ddlmZ  ed      Z	 G d de      Z
 G d	 d
e
      Z G d de      Z G d de      Zy)zE
Base classes for thread lifecycle management in manager components.
    N)ABCabstractmethod)Optional)
get_loggermanagerc                   ~    e Zd ZdZdefdZddZddee   ddfdZ	de
fd	Zdd
Zede
fd       ZddZddZddZy)LifecycleManagerz0Base class for components that manage lifecycle.namec                 `    || _         d| _        d| _        t        j                         | _        y)zk
        Initialize lifecycle manager.

        Args:
            name: Component name for logging
        FN)r
   running_externally_finished	threadingLock_lock)selfr
   s     3/root/.openclaw/workspace/harvester/manager/base.py__init__zLifecycleManager.__init__   s,     	 %*! ^^%
    returnNc                 (   | j                   5  | j                  r,t        j                  | j                   d       	 ddd       yd| _        | j                          t        j                  d| j                          ddd       y# 1 sw Y   yxY w)zStart the component.z already runningNTStarted )r   r   loggerwarningr
   	_on_startinfor   s    r   startzLifecycleManager.start#   sv    ZZ 
	0||$)),<=>
	0 
	0
  DL NNKK(499+./
	0 
	0 
	0s   0B9BBtimeoutc                     | j                   sy| j                  5  d| _         | j                          ddd       | j                          t        j                  d| j                          y# 1 sw Y   <xY w)zStop the component.NFStopped )r   r   _on_stop_on_stoppedr   r   r
   )r   r   s     r   stopzLifecycleManager.stop1   s_    ||ZZ 	 DL MMO		 	htyyk*+	 	s   A--A6c                 8    | j                    xs | j                  S )zCheck if component is finished.)r   r   r   s    r   is_finishedzLifecycleManager.is_finishedA   s    <<<4#<#<<r   c                 V    d| _         t        j                  | j                   d       y)z.Mark component as finished by external signal.Tz marked as finished externallyN)r   r   r   r
   r   s    r   mark_finishedzLifecycleManager.mark_finishedE   s"    $(!tyyk!?@Ar   c                     | j                   S )z(Check if component is currently running.)r   r   s    r   
is_runningzLifecycleManager.is_runningJ   s     ||r   c                      y)zHook called during start.N r   s    r   r   zLifecycleManager._on_startO       r   c                      y)zHook called during stop.Nr+   r   s    r   r!   zLifecycleManager._on_stopS   r,   r   c                      y)z(Hook called after component has stopped.Nr+   r   s    r   r"   zLifecycleManager._on_stoppedW   r,   r   r   NN)__name__
__module____qualname____doc__strr   r   r   floatr#   boolr%   r'   propertyr)   r   r!   r"   r+   r   r   r	   r	      si    :&S & 0,HUO ,t , =T =B
 D  r   r	   c                   l     e Zd ZdZddededef fdZddZdd	e	e   ddfd
Z
ddZedd       Z xZS )ThreadManagerz9Base class for components that manage background threads.r
   shutdown_timeoutdaemonc                     t         |   |       t        dt        |            | _        || _        d| _        t        j                         | _	        y)z
        Initialize thread manager.

        Args:
            name: Component name for logging
            shutdown_timeout: Maximum time to wait for graceful shutdown
            daemon: Whether the thread should be daemon
              ?N)
superr   maxr6   r;   r<   _threadr   Event_stop_event)r   r
   r;   r<   	__class__s       r   r   zThreadManager.__init___   sH     	 !$C/?)@ A 48$??,r   r   Nc                 6   | j                   5  | j                  r,t        j                  | j                   d       	 ddd       yd| _        d| _        | j                  j                          | j                          t        j                  | j                  | j                  j                          d| j                        | _        | j                  j                          t        j!                  d| j                          ddd       y# 1 sw Y   yxY w)z3Start the background thread if not already running.z is already runningNTFz-thread)targetr
   r<   r   )r   r   r   r   r
   r   rC   clearr   r   Thread_thread_wrapperlowerr<   rA   r   r   r   s    r   r   zThreadManager.starts   s    ZZ 	0||$)),?@A	0 	0
  DL(-D%""$ NN %++++TYY__5F4Gw2OX\XcXcDL LL KK(499+./%	0 	0 	0s   0DC DDr   c                 B   | j                   sy|xs | j                  }| j                  5  d| _         | j                  j	                          | j                          ddd       | j                  rr| j                  j                         rX| j                  j                  |       | j                  j                         r"t        j                  | j                   d       | j                          t        j                  d| j                          y# 1 sw Y   xY w)z&Stop the background thread gracefully.NFr   z thread did not stop gracefullyr    )r   r;   r   rC   setr!   rA   is_alivejoinr   r   r
   r"   r   )r   r   stop_timeouts      r   r#   zThreadManager.stop   s    ||7$"7"7ZZ 	 DL  " MMO	 <<DLL113LLl3||$$&$)),KLM 	htyyk*+!	 	s   2DDc                 .   	 | j                          t        j                  | j                   d       y# t        $ r/}t        j                  d| j                   d|        Y d}~Vd}~ww xY w# t        j                  | j                   d       w xY w)z1Wrapper for main thread loop with error handling.	Error in z	 thread: Nz thread finished)
_main_loop	Exceptionr   errorr
   debugr   es     r   rI   zThreadManager._thread_wrapper   sx    	9OO LLDII;&678  	>LL9TYYKy<==	> LLDII;&678s&   5 	A-%A(#A0 (A--A0 0$Bc                      y)z Main thread loop implementation.Nr+   r   s    r   rS   zThreadManager._main_loop        	r   )      @Tr/   r0   )r1   r2   r3   r4   r5   r6   r7   r   r   r   r#   rI   r   rS   __classcell__rD   s   @r   r:   r:   \   sU    C-S -E - -(0,,HUO ,t ,29  r   r:   c                   L     e Zd ZdZddededef fdZd	dZed	d       Z	 xZ
S )
PeriodicTaskManagerz6Base class for components that perform periodic tasks.r
   intervalr;   c                 Z    t         |   ||       t        dt        |            | _        y)z
        Initialize periodic task manager.

        Args:
            name: Component name for logging
            interval: Interval between task executions in seconds
            shutdown_timeout: Maximum time to wait for graceful shutdown
        皙?N)r?   r   r@   r6   r`   )r   r
   r`   r;   rD   s       r   r   zPeriodicTaskManager.__init__   s'     	/0Cx1r   c                    | j                   rQ	 | j                          | j                   r&| j                  j                  | j                         | j                   rPyy# t
        $ rk}t        j                  d| j                   d|        | j                   r0| j                  j                  t        d| j                               Y d}~~d}~ww xY w)z'Main loop that executes periodic tasks.rL   rR   z periodic task: r>   N)
r   _execute_periodic_taskrC   waitr`   rT   r   rU   r
   minrW   s     r   rS   zPeriodicTaskManager._main_loop   s    llK++- <<$$))$--)@ ll  Ky3CA3GH<<$$))#c4==2I)J	Ks   AA 	C(A!CCc                      y)zExecute the periodic task.Nr+   r   s    r   rd   z*PeriodicTaskManager._execute_periodic_task   rZ   r   )r[   r/   )r1   r2   r3   r4   r5   r6   r   rS   r   rd   r\   r]   s   @r   r_   r_      s:    @
2S 
2E 
2U 
2K"  r   r_   c                   b     e Zd ZdZd
dededef fdZddZede	fd       Z
edd	       Z xZS )ConditionalTaskManagerz5Base class for components that respond to conditions.r
   check_intervalr;   c                 Z    t         |   ||       t        dt        |            | _        y)a  
        Initialize conditional task manager.

        Args:
            name: Component name for logging
            check_interval: Interval between condition checks in seconds
            shutdown_timeout: Maximum time to wait for graceful shutdown
        rb   N)r?   r   r@   r6   rj   )r   r
   rj   r;   rD   s       r   r   zConditionalTaskManager.__init__   s)     	/0!#u^'<=r   r   c                    | j                   ra	 | j                         r| j                          | j                   r&| j                  j	                  | j
                         | j                   r`yy# t        $ rk}t        j                  d| j                   d|        | j                   r0| j                  j	                  t        d| j
                               Y d}~~d}~ww xY w)z8Main loop that checks conditions and responds to events.rL   rR   z condition handling: r>   N)r   _should_execute_handle_conditionrC   re   rj   rT   r   rU   r
   rf   rW   s     r   rS   z!ConditionalTaskManager._main_loop   s    llQ'')**, <<$$))$2E2E)F ll  Qy3HLM<<$$))#c4;N;N2O)P	Qs   AA/ /	C#8A!CC#c                      y)z%Check if condition should be handled.Nr+   r   s    r   rm   z&ConditionalTaskManager._should_execute   rZ   r   c                      y)zHandle the detected condition.Nr+   r   s    r   rn   z(ConditionalTaskManager._handle_condition   rZ   r   )r>   r[   r/   )r1   r2   r3   r4   r5   r6   r   rS   r   r7   rm   rn   r\   r]   s   @r   ri   ri      sV    ?
>S 
>% 
>QV 
>Q$     r   ri   )r4   r   abcr   r   typingr   tools.loggerr   r   r	   r:   r_   ri   r+   r   r   <module>rt      sZ     #  #	I	Is IXR$ Rj#- #L)] )r   