
    fIX                    *   d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlZddlmZmZmZmZ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m Z  d	dl!m"Z" d	dl#m$Z$m%Z%m&Z&  G d de'      Z(ddZ) G d de      Z* G d de*      Z+y)z%A kernel manager for multiple kernels    )annotationsNwraps)Path)AnyBoolDictDottedObjectNameInstanceUnicodedefaultobserve)LoggingConfigurable)import_item   )KernelConnectionInfo)NATIVE_KERNEL_NAMEKernelSpecManager)KernelManager)ensure_asyncrun_syncutcnowc                      e Zd Zy)DuplicateKernelErrorN)__name__
__module____qualname__     \/var/www/cvtools/html/venv/lib/python3.12/site-packages/jupyter_client/multikernelmanager.pyr   r      s    r   r   c                D     t               	 	 	 	 	 	 	 	 	 	 d fd       }|S )zDdecorator for proxying MKM.method(kernel_id) to individual KMs by IDc                    | j                  |      }t        |j                        } ||i |} | |g|i | |S N)
get_kernelgetattrr   )self	kernel_idargskwargskmmethodrfs          r    wrappedzkernel_method.<locals>.wrapped!   sM    
 __Y'QZZ(D#F# 	
$	+D+F+r   )
r&   t.Anyr'   strr(   r/   r)   r/   returnzt.Callable | t.Awaitabler   )r-   r.   s   ` r    kernel_methodr2      sJ     1X #,1=B	!  Nr   c                  @    e Zd ZdZ eed      j                  d      Z ee	d      Z
 edd      j                  d      Z ed	      d8d
       Z ed      Z ed      d9d       Zd9dZ edd      j                  d      Z ed      Z ed      Z e       Zed:d       Z ed      d;d       Z ed      Z edd      Z e       Zd< fdZ d= fdZ!d>dZ"d?dZ#d@dZ$	 	 	 	 	 	 dAdZ%dBdZ&	 	 	 	 	 	 	 	 dCdZ'	 	 	 	 	 	 dDdZ(dEd Z)dd!dFd"Z* e+e*      Z,	 	 dG	 	 	 	 	 	 	 dHd#Z- e+e-      Z.e/dIdJd$       Z0e/	 	 dK	 	 	 	 	 	 	 dLd%       Z1e/dIdMd&       Z2dNd'Z3dIdOd(Z4 e+e4      Z5dPd)Z6e/dQd*       Z7dIdRd+Z8 e+e8      Z9e/d@d,       Z:dPd-Z;dNd.Z<e/	 dS	 	 	 	 	 	 	 dTd/       Z=e/	 dS	 	 	 	 	 	 	 dTd0       Z>e/dUd1       Z?e/	 dV	 	 	 	 	 dWd2       Z@e/	 dV	 	 	 	 	 dWd3       ZAe/	 dV	 	 	 	 	 dWd4       ZBe/	 dV	 	 	 	 	 dWd5       ZCe/	 dV	 	 	 	 	 dWd6       ZDdXd7ZE xZFS )YMultiKernelManagerz&A class for managing multiple kernels.z'The name of the default kernel to starthelpTconfig)
allow_nonez)jupyter_client.ioloop.IOLoopKernelManagerzThe kernel manager class.  This is configurable to allow
        subclassing of the KernelManager for customized behavior.
        kernel_manager_classc                .    | j                         | _        y r#   )_create_kernel_manager_factorykernel_manager_factory)r&   changes     r    _kernel_manager_class_changedz0MultiKernelManager._kernel_manager_class_changedC   s    &*&I&I&K#r   z)this is kernel_manager_class after importr=   c                "    | j                         S r#   )r<   r&   s    r    _kernel_manager_factory_defaultz2MultiKernelManager._kernel_manager_factory_defaultI   s    2244r   c                B     t         j                        d fd}|S )Nc                     j                   rGj                  j                  rj                         _        |j	                  dj                          | i |}|S )Ncontext)shared_contextrE   closed_context_default
setdefault)r(   r)   r*   kernel_manager_ctorr&   s      r    create_kernel_managerzPMultiKernelManager._create_kernel_manager_factory.<locals>.create_kernel_managerP   sQ    ""<<&&#'#8#8#:DL!!)T\\:$d5f5BIr   )r(   r/   r)   r/   r1   r   )r   r:   )r&   rK   rJ   s   ` @r    r<   z1MultiKernelManager._create_kernel_manager_factoryM   s!    )$*C*CD	 %$r   z4Share a single zmq.Context to talk to all my kernelszmq.ContextFc                    | j                   S )z#A shim for backwards compatibility.)_pending_kernelsrA   s    r    _starting_kernelsz$MultiKernelManager._starting_kernelsf   s     $$$r   rE   c                8    d| _         t        j                         S NT)_created_contextzmqContextrA   s    r    rH   z#MultiKernelManager._context_defaultk   s     ${{}r    Nc                2    t        |   |i | i | _        y r#   )super__init__kernel_id_to_connection_file)r&   r(   r)   	__class__s      r    rX   zMultiKernelManager.__init__u   s    $)&)=?)r   c                (   | j                   rd| j                  rX| j                  j                  sB| j                  r| j                  j	                  d|        | j                  j                          	 t        |   } |        y# t        $ r Y yw xY w)z:Handle garbage collection.  Destroy context if applicable.zDestroying zmq context for %sN)	rR   rE   rG   logdebugdestroyrW   __del__AttributeError)r&   	super_delrZ   s     r    r_   zMultiKernelManager.__del__y   sq      T\\$,,:M:Mxx>ELL  "	I K  		s   3
B 	BBc                   | j                   
t        | j                         }|j                         r|j                         D cg c]  }|j	                         s| }}t        | j                  j                               }t        | j                  j                               }t        | j                  j                               D ]5  }||vs||j                  |         }| j                  |= | j                  |= 7 |D ]  }|| j                  j                         v r!	 t        j                  |j                               }| j                  j!                  d|       d|v rd|v sj| j#                         }|| j                  |<   | j%                  | | j                  d      }	|	j'                  |       t)               |	_        d|	_        d|	_        ||	_        |d   |	_        |	j4                  j7                  d       |	| j                  |<    t        | j                  j                               S c c}w # t        $ r Y Gw xY w)	z6Return a list of the kernel ids of the active kernels.NzLoading connection file %skernel_namekeyF)parentr\   owns_kernelidler   )external_connection_dirr   is_diriterdiris_filelistrY   keysvaluesindex_kernelsjsonloads	read_text	Exceptionr\   r]   new_kernel_idr=   load_connection_infor   last_activityexecution_stateconnectionsr'   rc   ready
set_result)
r&   rh   pconnection_fileskvconnection_filer'   connection_infor*   s
             r    list_kernel_idsz"MultiKernelManager.list_kernel_ids   s%   ''3&*4+G+G&H#&--//F/N/N/P#`!TUT]T]T_A#` #` ::??AB::AACD'+D,M,M,T,T,V'W 5O&.>>$%aggo&>$?	 ==iH MM)4	5 (8 2O&$*K*K*R*R*TT !@D

+557A
 HHNN#?Q)_</AY  $ 2 2 4ICRD55i@44# HH$) 5 B
 ++O<'-xB$)/B&%&BN#,BL%4]%CBNHH''-/1DMM),92@ DMM&&())Y $a& % ! !s   H;H;'#I  	IIc                4    t        | j                               S )z%Return the number of running kernels.)lenr   rA   s    r    __len__zMultiKernelManager.__len__   s    4'')**r   c                    || j                   v S r#   )rp   r&   r'   s     r    __contains__zMultiKernelManager.__contains__   s    DMM))r   c                b   |j                  d | j                  di |      }|| v rt        d|z        || j                  }i }| j                  r| j                  |d<    | j
                  dt        j                  j                  | j                  d|z        | | j                  |d|}|||fS )Nr'   zKernel already exists: %skernel_spec_managerzkernel-%s.json)r   re   r\   rc   r   )popru   r   default_kernel_namer   r=   ospathjoinconnection_dirr\   )r&   rc   r)   r'   constructor_kwargsr*   s         r    pre_start_kernelz#MultiKernelManager.pre_start_kernel   s     JJ{,>D,>,>,H,HI	&'BY'NOO22K  ##8<8P8P45(T(( 
GGLL)<)<>NQZ>Z[#	

 !
 ;	))r   c               L    || v r | j                   |   j                  |       yy)z
        Allow to update the environment of the given kernel.

        Forward the update env request to the corresponding kernel.

        .. version-added: 8.5
        )envN)rp   
update_env)r&   r'   r   s      r    r   zMultiKernelManager.update_env   s+     MM)$//C/8 r   c                   K   	 | d {    || j                   |<   | j                  j                  |d        y 7 0# t        $ r%}| j                  j                  |       Y d }~y d }~ww xY wwr#   )rp   rN   r   rt   r\   	exception)r&   r'   r*   kernel_awaitablees        r    _add_kernel_when_readyz)MultiKernelManager._add_kernel_when_ready   sc     	""""')DMM)$!!%%i6 #  	"HHq!!	"s7   A-< :/< A-< 	A*A% A-%A**A-c                   K   	 | d {    | j                  |       | j                  j                  |d        y 7 2# t        $ r%}| j                  j                  |       Y d }~y d }~ww xY wwr#   )remove_kernelrN   r   rt   r\   r   )r&   r'   r   r   s       r    _remove_kernel_when_readyz,MultiKernelManager._remove_kernel_when_ready   sc     	""""y)!!%%i6 #  	"HHq!!	"s7   A/> <1> A/> 	A,A'"A/'A,,A/c                    t        | dd      S )zReturns a boolean; a clearer method for determining if
        this multikernelmanager is using pending kernels or not
        use_pending_kernelsF)r%   rA   s    r    _using_pending_kernelsz)MultiKernelManager._using_pending_kernels   s     t2E::r   )rc   c               D  K   | j                  ||      \  }}}t        |t              s?| j                  j	                  dj                  | j                  j                               ||d<   t         |j                  di |      }t        j                  | j                  |||            }|| j                  |<   | j                         r|| j                  |<   |S | d{    |j                   j#                         r|j                   j#                         |S 7 :w)zStart a new kernel.

        The caller can pick a kernel_id by passing one in as a keyword arg,
        otherwise one will be generated using new_kernel_id().

        The kernel ID for the newly started kernel is returned.
        zHKernel manager class ({km_class}) is not an instance of 'KernelManager'!)km_classr'   Nr   )r   
isinstancer   r\   warningformatr:   rZ   r   start_kernelasynciocreate_taskr   rN   r   rp   rz   r   )r&   rc   r)   r*   r'   startertasks          r    _async_start_kernelz&MultiKernelManager._async_start_kernel   s     &*%:%:;%O"K"m,HHZaa!66@@ b 
 ({r889""4#>#>y"g#VW+/i(&&( (*DMM)$  JJxx!!#hh((** s   C!D #D$;D c                  K   | j                   j                  d|       || j                  v ra| j                  |   }	 | d{    | j                  |      }t	        j
                  t        j                  |j                         d{    | j                  |      }|j                  j                         s,|j                  j                         r| j                  |       yt        |j                  ||            }t        j                   | j#                  ||            }|| j                  |<   | j%                         s?| d{    |j                  j                         r|j                  j                         yy7 B7 # t        j                  $ r Y t        $ r | j                  |       Y yw xY w7 tw)a3  Shutdown a kernel by its kernel uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to shutdown.
        now : bool
            Should the kernel be shutdown forcibly using a signal.
        restart : bool
            Will the kernel be restarted?
        Kernel shutdown: %sN)r\   inforN   r$   tcastr   Futurerz   CancelledErrorrt   r   	cancelledr   r   shutdown_kernelensure_futurer   r   )r&   r'   nowrestartr   r*   stopperfuts           r    _async_shutdown_kernelz)MultiKernelManager._async_shutdown_kernel!  sr    " 	+Y7---((3D

__Y/ffW^^RXX666 __Y'xx!!#(:(:(<y)r11#w?@##D$B$B9g$VW+.i(**,IIxx!!#hh((** $ -# 6))  ""9- sf   :G F	 FAF	 	F
F	 B;G 	F>
:G F	 F	 	F;G F;8G :F;;G c                     y)z,Ask a kernel to shut down by its kernel uuidNr   r&   r'   r   s      r    request_shutdownz#MultiKernelManager.request_shutdownP      r   c                <    | j                   j                  d|       y)zDWait for a kernel to finish shutting down, and kill it if it doesn'tr   Nr\   r   )r&   r'   waittimepollintervals       r    finish_shutdownz"MultiKernelManager.finish_shutdownT  s     	+Y7r   c                     y)zClean up a kernel's resourcesNr   r   s      r    cleanup_resourcesz$MultiKernelManager.cleanup_resources^  r   r   c                :    | j                   j                  |d      S )zremove a kernel from our mapping.

        Mainly so that a kernel can be removed if it is already dead,
        without having to call shutdown_kernel.

        The kernel object is returned, or `None` if not found.
        N)rp   r   r   s     r    r   z MultiKernelManager.remove_kernelb  s     }}  D11r   c                (  K   | j                         }|t        | j                        z  }t        | j                  j	                               }t        |      D cg c]  }| j                  ||       }}t        j                  |  d{    | j                         r|D ]  }	 |j                   d{     yyc c}w 7 77 # t        j                  $ r* | j                  |j                     j                          Y at        $ r Y kw xY ww)zShutdown all kernels.r   N)r   rl   rN   rp   rn   setr   r   gatherr   rz   r   r'   cancelrt   )r&   r   kidskmskidfutsr*   s          r    _async_shutdown_allz&MultiKernelManager._async_shutdown_alll  s     ##%T**++4=='')*EHYOc++CS+9OOnnd###&&( ((NN ) P#
 #-- A))",,7>>@  s`   ADB?5DCD'C6C7C;
DC:DDDDDDc                    | j                  |      }|j                  j                         sd}t        |      |j	                         }| j
                  j                  d|       |S )zInterrupt (SIGINT) the kernel by its uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to interrupt.
        z/Kernel is in a pending state. Cannot interrupt.zKernel interrupted: %s)r$   rz   doneRuntimeErrorinterrupt_kernelr\   r   )r&   r'   kernelmsgouts        r    r   z#MultiKernelManager.interrupt_kernel  sX     +||  "CCs##%%'.	:
r   c                >    | j                   j                  d||       y)aR  Sends a signal to the kernel by its uuid.

        Note that since only SIGTERM is supported on Windows, this function
        is only useful on Unix systems.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to signal.
        signum : int
            Signal number to send kernel.
        zSignaled Kernel %s with %sNr   )r&   r'   signums      r    signal_kernelz MultiKernelManager.signal_kernel  s     	2IvFr   c                  K   | j                  |      }| j                         r'|j                  j                         sd}t	        |      t        |j                  |             d{    | j                  j                  d|       y7 !w)aE  Restart a kernel by its uuid, keeping the same ports.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to interrupt.
        now : bool, optional
            If True, the kernel is forcefully restarted *immediately*, without
            having a chance to do any cleanup action.  Otherwise the kernel is
            given 1s to clean up before a forceful restart is issued.

            In all cases the kernel is restarted, the only difference is whether
            it is given a chance to perform a clean shutdown or not.
        z-Kernel is in a pending state. Cannot restart.r   NzKernel restarted: %s)	r$   r   rz   r   r   r   restart_kernelr\   r   )r&   r'   r   r   r   s        r    _async_restart_kernelz(MultiKernelManager._async_restart_kernel  su      +&&(1B1B1DACs##600S09:::,i8 	;s   A'B)B*"Bc                     y)zIs the kernel alive.

        This calls KernelManager.is_alive() which calls Popen.poll on the
        actual kernel subprocess.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.
        Nr   r   s     r    is_alivezMultiKernelManager.is_alive  r   r   c                (    || vrt        d|z        y)zcheck that a kernel id is validzKernel with id not found: %sN)KeyErrorr   s     r    _check_kernel_idz#MultiKernelManager._check_kernel_id  s     D 9IEFF !r   c                B    | j                  |       | j                  |   S )zGet the single KernelManager object for a kernel by its uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.
        )r   rp   r   s     r    r$   zMultiKernelManager.get_kernel  s!     	i(}}Y''r   c                     y)z&add a callback for the KernelRestarterNr   r&   r'   callbackevents       r    add_restart_callbackz'MultiKernelManager.add_restart_callback  r   r   c                     y)z)remove a callback for the KernelRestarterNr   r   s       r    remove_restart_callbackz*MultiKernelManager.remove_restart_callback  r   r   c                     y)a  Return a dictionary of connection data for a kernel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.

        Returns
        =======
        connection_dict : dict
            A dict of the information needed to connect to a kernel.
            This includes the ip address and the integer port
            numbers of the different channels (stdin_port, iopub_port,
            shell_port, hb_port).
        Nr   r   s     r    get_connection_infoz&MultiKernelManager.get_connection_info  r   r   c                     y)a6  Return a zmq Socket connected to the iopub channel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel
        identity : bytes (optional)
            The zmq identity of the socket

        Returns
        =======
        stream : zmq Socket or ZMQStream
        Nr   r&   r'   identitys      r    connect_iopubz MultiKernelManager.connect_iopub  r   r   c                     y)a6  Return a zmq Socket connected to the shell channel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel
        identity : bytes (optional)
            The zmq identity of the socket

        Returns
        =======
        stream : zmq Socket or ZMQStream
        Nr   r   s      r    connect_shellz MultiKernelManager.connect_shell  r   r   c                     y)a8  Return a zmq Socket connected to the control channel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel
        identity : bytes (optional)
            The zmq identity of the socket

        Returns
        =======
        stream : zmq Socket or ZMQStream
        Nr   r   s      r    connect_controlz"MultiKernelManager.connect_control  r   r   c                     y)a6  Return a zmq Socket connected to the stdin channel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel
        identity : bytes (optional)
            The zmq identity of the socket

        Returns
        =======
        stream : zmq Socket or ZMQStream
        Nr   r   s      r    connect_stdinz MultiKernelManager.connect_stdin)  r   r   c                     y)a3  Return a zmq Socket connected to the hb channel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel
        identity : bytes (optional)
            The zmq identity of the socket

        Returns
        =======
        stream : zmq Socket or ZMQStream
        Nr   r   s      r    
connect_hbzMultiKernelManager.connect_hb;  r   r   c                <    t        t        j                               S )z
        Returns the id to associate with the kernel for this request. Subclasses may override
        this method to substitute other sources of kernel ids.
        :param kwargs:
        :return: string-ized version 4 uuid
        )r0   uuiduuid4)r&   r)   s     r    ru   z MultiKernelManager.new_kernel_idM  s     4::<  r   )r>   r/   r1   None)r1   
t.Callable)r1   dict)r1   rL   )r(   r/   r)   r/   r1   r   )r1   r   )r1   z	list[str])r1   int)r'   r0   r1   bool)rc   
str | Noner)   r/   r1   ztuple[KernelManager, str, str])r'   r0   r   zt.Dict[str, str]r1   r   )r'   r0   r*   r   r   t.Awaitabler1   r   )r'   r0   r   r  r1   r   )r1   r   )rc   r  r)   r/   r1   r0   )FF)r'   r0   r   bool | Noner   r  r1   r   )F)r'   r0   r   r  r1   r   )Ng?)r'   r0   r   float | Noner   r  r1   r   )r'   r0   r   r   r1   r   )r'   r0   r1   r   )r   r   r1   r   )r'   r0   r1   r   )r'   r0   r   r   r1   r   )r'   r0   r   r   r1   r   )r   )r'   r0   r   r   r   r0   r1   r   )r'   r0   r1   zdict[str, t.Any]r#   )r'   r0   r   zbytes | Noner1   zsocket.socket)r)   r/   r1   r0   )Gr   r   r   __doc__r   r   tagr   r   r   r   r
   r:   r   r?   r   r=   r   rB   r<   r   rF   rE   rR   r	   rN   propertyrO   rH   r   rh   rp   rX   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r2   r   r   r   r   r   shutdown_allr   r   r   r   r   r   r$   r   r   r   r   r   r   r   r   ru   __classcell__)rZ   s   @r    r4   r4   3   sD   0!!J	cc  ##4F+3
 
cc  #$L %L !&QR%&5 '5% C 
cc 
 }%GE{v% % Y  R[N%dt<vH@1*f+**%*/4*	'*2	9"""/"CN"	"""0;"	"; FJ B /0L
 !$	++++ ++ 	++
 
++Z 56O; ;  "&%(	88 8 #	8
 
8 8 , ,2$ /0L  G G9, 34N
 
G
	( AJ55(25;>5	5 5
 AJ88(28;>8	8 8
  " 7;(4	 " 7;(4	 " 7;(4	 " 7;(4	 " 7;(4	 "!r   r4   c                     e Zd ZU  eddd      Z edd      j                  d      Z ed	      Z	 e
d
      dd       Zej                  Zded<   ej                   Zded<   ej$                  Zded<   ej(                  Zded<   y)AsyncMultiKernelManagerz.jupyter_client.ioloop.AsyncIOLoopKernelManagerTzThe kernel manager class.  This is configurable to allow
        subclassing of the AsyncKernelManager for customized behavior.
        )r8   r6   FzWhether to make kernels available before the process has started.  The
        kernel has a `.ready` future which can be awaited before connectingr5   r7   zmq.asyncio.ContextrE   c                L    d| _         t        j                  j                         S rQ   )rR   rS   r   rT   rA   s    r    rH   z(AsyncMultiKernelManager._context_defaulth  s     ${{""$$r   zt.Callable[..., t.Awaitable]r   r   r   r  N)r1   r  )r   r   r   r
   r:   r   r  r   r   rE   r   rH   r4   r   r   __annotations__r   r   r   r   r   r  r   r   r    r  r  W  s    +8 O 
cc	  ,-GY% % 2D1W1WL.W3E3[3[N0[4F4]4]O1]1C1W1WL.Wr   r  )r-   r   r1   r   ),r  
__future__r   r   rq   r   sockettypingr   r   	functoolsr   pathlibr   rS   	traitletsr   r   r	   r
   r   r   r   r   traitlets.config.configurabler   traitlets.utils.importstringr   connectr   
kernelspecr   r   managerr   utilsr   r   r   rt   r   r2   r4   r  r   r   r    <module>r     sv    + #   	      
 \ \ \ = 4 ) = " 1 1	9 	*a!, a!HX0 Xr   