
    MhIX                    >   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+dS )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dS )DuplicateKernelErrorN)__name__
__module____qualname__     a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_client/multikernelmanager.pyr   r      s        Dr   r   f
t.Callablereturnc                >     t                     d
 fd	            }|S )zDdecorator for proxying MKM.method(kernel_id) to individual KMs by IDselft.Any	kernel_idstrargskwargsr#   t.Callable | t.Awaitablec                    |                      |          }t          |j                  } ||i |} | |g|R i | |S N)
get_kernelgetattrr   )r%   r'   r)   r*   kmmethodrr!   s          r    wrappedzkernel_method.<locals>.wrapped!   sd    
 __Y''QZ((FD#F## 	
$	+D+++F+++r   )
r%   r&   r'   r(   r)   r&   r*   r&   r#   r+   r   )r!   r3   s   ` r    kernel_methodr4      s:     1XX     X Nr   c                      e Zd ZdZ eed                              d          Z ee	d          Z
 edd                              d          Z ed	          d\d            Z ed          Z ed          d]d            Zd]dZ edd                              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 da fd Z!dbd"Z"dcd$Z#ddd(Z$ded,Z%dfd/Z&dgd4Z'dhd5Z(did6Z)dd7djd8Z* e+e*          Z,	 	 dkdld<Z- e+e-          Z.e/dmdnd=            Z0e/	 	 dodpdB            Z1e/dmdqdC            Z2drdDZ3dmdsdEZ4 e+e4          Z5dtdFZ6e/dudH            Z7dmdvdIZ8 e+e8          Z9e/dddJ            Z:dtdKZ;drdLZ<e/	 dwdxdO            Z=e/	 dwdxdP            Z>e/dydR            Z?e/	 dzd{dV            Z@e/	 dzd{dW            ZAe/	 dzd{dX            ZBe/	 dzd{dY            ZCe/	 dzd{dZ            ZDd|d[ZE xZFS )}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_classchanger&   r#   Nonec                8    |                                  | _        d S r-   )_create_kernel_manager_factorykernel_manager_factory)r%   r=   s     r    _kernel_manager_class_changedz0MultiKernelManager._kernel_manager_class_changedC   s    &*&I&I&K&K###r   z)this is kernel_manager_class after importrA   r"   c                *    |                                  S r-   )r@   r%   s    r    _kernel_manager_factory_defaultz2MultiKernelManager._kernel_manager_factory_defaultI   s    22444r   c                @     t           j                  d fd}|S )Nr)   r&   r*   r#   r   c                     j         r@j        j        r                                _        |                    dj                    | i |}|S )Ncontext)shared_contextrH   closed_context_default
setdefault)r)   r*   r0   kernel_manager_ctorr%   s      r    create_kernel_managerzPMultiKernelManager._create_kernel_manager_factory.<locals>.create_kernel_managerP   s`    " ;<& ;#'#8#8#:#:DL!!)T\:::$$d5f55BIr   )r)   r&   r*   r&   r#   r   )r   r<   )r%   rN   rM   s   ` @r    r@   z1MultiKernelManager._create_kernel_manager_factoryM   s@    )$*CDD	 	 	 	 	 	 	 %$r   z4Share a single zmq.Context to talk to all my kernelszmq.ContextFdictc                    | j         S )z#A shim for backwards compatibility.)_pending_kernelsrD   s    r    _starting_kernelsz$MultiKernelManager._starting_kernelsf   s     $$r   rH   c                6    d| _         t          j                    S NT)_created_contextzmqContextrD   s    r    rK   z#MultiKernelManager._context_defaultk   s     ${}}r    Nr)   r*   c                H     t                      j        |i | i | _        d S r-   )super__init__kernel_id_to_connection_file)r%   r)   r*   	__class__s      r    r\   zMultiKernelManager.__init__u   s-    $)&)))=?)))r   c                   | j         rN| j        rG| j        j        s;| j        r| j                            d|            | j                                         	 t                      j        } |             dS # t          $ r Y dS w xY w)z:Handle garbage collection.  Destroy context if applicable.zDestroying zmq context for %sN)	rV   rH   rJ   logdebugdestroyr[   __del__AttributeError)r%   	super_delr^   s     r    rc   zMultiKernelManager.__del__y   s      	#T\ 	#$,:M 	#x F>EEEL  """	I IKKKKK  	 	 	DD	s   A7 7
BB	list[str]c                   | j         t          | j                   }|                                rd |                                D             }t	          | j                                                  }t	          | j                                                  }t	          | j                                                  D ]1}||vr+||                    |                   }| j        |= | j	        |= 2|D ]$}|| j                                        v r	 t          j        |                                          }n# t          $ r Y Sw xY w| j                            d|           d|v rd|v s{|                                 }|| j        |<   |                     | | j        d          }|                    |           t'                      |_        d|_        d	|_        ||_        |d         |_        |j                            d           || j	        |<   &t	          | j	                                                  S )
z6Return a list of the kernel ids of the active kernels.Nc                :    g | ]}|                                 |S r   )is_file).0ps     r    
<listcomp>z6MultiKernelManager.list_kernel_ids.<locals>.<listcomp>   s*    #`#`#`!TUT]T]T_T_#`A#`#`#`r   zLoading connection file %skernel_namekeyF)parentr`   owns_kernelidler   )external_connection_dirr   is_diriterdirlistr]   keysvaluesindex_kernelsjsonloads	read_text	Exceptionr`   ra   new_kernel_idrA   load_connection_infor   last_activityexecution_stateconnectionsr'   rm   ready
set_result)	r%   rr   connection_fileskvconnection_filer'   connection_infor0   s	            r    list_kernel_idsz"MultiKernelManager.list_kernel_ids   s[   '3&*4+G&H&H#&--// )2#`#`/F/N/N/P/P#`#`#`  :??AABB:AACCDD'+D,M,T,T,V,V'W'W 5 5O&.>>>$%aggo&>&>$?	 =iH M)4 (8 2 2O&$*K*R*R*T*TTT !@D
+5577A A % ! ! ! !HNN#?QQQ)_<</AYAY  $ 2 2 4 4ICRD5i@44# H$) 5  B
 ++O<<<'-xxB$)/B&%&BN#,BL%4]%CBNH''---/1DM),, DM&&(()))s   &D==
E
	E
intc                D    t          |                                           S )z%Return the number of running kernels.)lenr   rD   s    r    __len__zMultiKernelManager.__len__   s    4''))***r   r'   r(   boolc                    || j         v S r-   )ry   r%   r'   s     r    __contains__zMultiKernelManager.__contains__   s    DM))r   rm   
str | Nonetuple[KernelManager, str, str]c                ,   |                     d | j        di |          }|| v rt          d|z            || j        }i }| j        r
| j        |d<    | j        dt          j                            | j	        d|z            | | j
        |d|}|||fS )Nr'   zKernel already exists: %skernel_spec_managerzkernel-%s.json)r   ro   r`   rm   r   )popr~   r   default_kernel_namer   rA   ospathjoinconnection_dirr`   )r%   rm   r*   r'   constructor_kwargsr0   s         r    pre_start_kernelz#MultiKernelManager.pre_start_kernel   s     JJ{,>D,>,H,H,H,HII	&'BY'NOOO2K  # 	Q8<8P45(T( 
GLL)<>NQZ>Z[[#	
 

 !
 
 ;	))r   envt.Dict[str, str]c               T    || v r#| j         |                             |           dS dS )z
        Allow to update the environment of the given kernel.

        Forward the update env request to the corresponding kernel.

        .. version-added: 8.5
        )r   N)ry   
update_env)r%   r'   r   s      r    r   zMultiKernelManager.update_env   s;     M)$//C/88888 r   r0   r   kernel_awaitablet.Awaitablec                   K   	 | d {V  || j         |<   | j                            |d            d S # t          $ r%}| j                            |           Y d }~d S d }~ww xY wr-   )ry   rR   r   r}   r`   	exception)r%   r'   r0   r   es        r    _add_kernel_when_readyz)MultiKernelManager._add_kernel_when_ready   s      	"""""""""')DM)$!%%i66666 	" 	" 	"Hq!!!!!!!!!	"s   -3 
A"AA"c                   K   	 | d {V  |                      |           | j                            |d            d S # t          $ r%}| j                            |           Y d }~d S d }~ww xY wr-   )remove_kernelrR   r   r}   r`   r   )r%   r'   r   r   s       r    _remove_kernel_when_readyz,MultiKernelManager._remove_kernel_when_ready   s      	"""""""""y)))!%%i66666 	" 	" 	"Hq!!!!!!!!!	"s   8> 
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/   rD   s    r    _using_pending_kernelsz)MultiKernelManager._using_pending_kernels   s     t2E:::r   )rm   c               .  K   |                      ||          \  }}}t          |t                    s8| j                            d                    | j        j                             ||d<   t           |j	        di |          }t          j        |                     |||                    }|| j        |<   |                                 r|| j        |<   n:| d{V  |j                                        r|j                                        |S )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<   r^   r   start_kernelasynciocreate_taskr   rR   r   ry   r   r   )r%   rm   r*   r0   r'   startertasks          r    _async_start_kernelz&MultiKernelManager._async_start_kernel   s2      &*%:%:;%O%O"K"m,, 	HZaa!6@ b    
 ({r888899"4#>#>y"g#V#VWW+/i(&&(( 	+ (*DM)$$JJJJJJJx!!## +h((***r   nowbool | Nonerestartc                p  K   | j                             d|           || j        v r| j        |         }	 | d{V  |                     |          }t	          j        t          j        |j                   d{V  n6# t          j	        $ r Y n%t          $ r |                     |           Y dS w xY w|                     |          }|j                                        s0|j                                        r|                     |           dS t          |                    ||                    }t          j        |                     ||                    }|| j        |<   |                                 s:| d{V  |j                                        r|j                                        dS dS )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`   inforR   r.   tcastr   Futurer   CancelledErrorr}   r   	cancelledr   r   shutdown_kernelensure_futurer   r   )r%   r'   r   r   r   r0   stopperfuts           r    _async_shutdown_kernelz)MultiKernelManager._async_shutdown_kernel!  s     " 	+Y777---(3D






__Y//fW^RX6666666666)      ""9--- __Y''x!!## 	(:(:(<(< 	y)))Fr11#w??@@#D$B$B9g$V$VWW+.i(**,, 	+IIIIIIIx!!## +h((***		+ 	++ +s   AA= =B0B0/B0c                    dS )z,Ask a kernel to shut down by its kernel uuidNr   r%   r'   r   s      r    request_shutdownz#MultiKernelManager.request_shutdownP        r   皙?waittimefloat | Nonepollintervalc                <    | j                             d|           dS )zDWait for a kernel to finish shutting down, and kill it if it doesn'tr   Nr`   r   )r%   r'   r   r   s       r    finish_shutdownz"MultiKernelManager.finish_shutdownT  s!     	+Y77777r   c                    dS )zClean up a kernel's resourcesNr   r   s      r    cleanup_resourcesz$MultiKernelManager.cleanup_resources^  r   r   c                8    | 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)ry   r   r   s     r    r   z MultiKernelManager.remove_kernelb  s     }  D111r   c                   K                                     }|t           j                  z  }t           j                                                  } fdt          |          D             }t          j        |  d{V                                   rW|D ]V}	 |j	         d{V  # t          j
        $ r'  j        |j                                                  Y Ft          $ r Y Qw xY wdS dS )zShutdown all kernels.c                >    g | ]}                     |           S )r   )r   )rj   kidr   r%   s     r    rl   z:MultiKernelManager._async_shutdown_all.<locals>.<listcomp>q  s,    OOOc++CS+99OOOr   N)r   ru   rR   ry   rw   setr   gatherr   r   r   r'   cancelr}   )r%   r   kidskmsfutsr0   s   ``    r    _async_shutdown_allz&MultiKernelManager._async_shutdown_alll  s5     ##%%T*+++4=''))**OOOOOSYYOOOnd########&&(( 	  (NNNNNNNN- A A A)",7>>@@@@@    D	 	 s   B--3C."	C.-C.c                    |                      |          }|j                                        sd}t          |          |                                }| 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.   r   doneRuntimeErrorinterrupt_kernelr`   r   )r%   r'   kernelmsgouts        r    r   z#MultiKernelManager.interrupt_kernel  sk     ++|  "" 	$CCs###%%''.	:::
r   signumc                >    | j                             d||           dS )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'   r   s      r    signal_kernelz MultiKernelManager.signal_kernel  s#     	2IvFFFFFr   c                8  K   |                      |          }|                                 r*|j                                        sd}t	          |          t          |                    |                     d{V  | j                            d|           dS )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   r   r   r   r   restart_kernelr`   r   )r%   r'   r   r   r   s        r    _async_restart_kernelz(MultiKernelManager._async_restart_kernel  s       ++&&(( 	$1B1B1D1D 	$ACs###600S099:::::::::,i88888r   c                    dS )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                2    || vrt          d|z            dS )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F ! r   c                F    |                      |           | j        |         S )zGet the single KernelManager object for a kernel by its uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.
        )r   ry   r   s     r    r.   zMultiKernelManager.get_kernel  s%     	i(((}Y''r   callbackeventc                    dS )z&add a callback for the KernelRestarterNr   r%   r'   r   r   s       r    add_restart_callbackz'MultiKernelManager.add_restart_callback  r   r   c                    dS )z)remove a callback for the KernelRestarterNr   r   s       r    remove_restart_callbackz*MultiKernelManager.remove_restart_callback  r   r   dict[str, t.Any]c                    dS )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   identitybytes | Nonesocket.socketc                    dS )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'   r   s      r    connect_iopubz MultiKernelManager.connect_iopub  r   r   c                    dS )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                    dS )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                    dS )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                    dS )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                B    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
        )r(   uuiduuid4)r%   r*   s     r    r~   z MultiKernelManager.new_kernel_idM  s     4:<<   r   )r=   r&   r#   r>   )r#   r"   )r#   rP   )r#   rO   )r)   r&   r*   r&   r#   r>   )r#   r>   )r#   rf   )r#   r   )r'   r(   r#   r   )rm   r   r*   r&   r#   r   )r'   r(   r   r   r#   r>   )r'   r(   r0   r   r   r   r#   r>   )r'   r(   r   r   r#   r>   )r#   r   )rm   r   r*   r&   r#   r(   )FF)r'   r(   r   r   r   r   r#   r>   )F)r'   r(   r   r   r#   r>   )Nr   )r'   r(   r   r   r   r   r#   r>   )r'   r(   r   r   r#   r>   )r'   r(   r#   r   )r   r   r#   r>   )r'   r(   r#   r>   )r'   r(   r   r   r#   r>   )r'   r(   r   r   r#   r>   )r   )r'   r(   r   r"   r   r(   r#   r>   )r'   r(   r#   r   r-   )r'   r(   r   r  r#   r  )r*   r&   r#   r(   )Gr   r   r   __doc__r   r   tagr   r   r   r   r
   r<   r   rB   r   rA   r   rE   r@   r   rI   rH   rV   r	   rR   propertyrS   rK   r   rr   ry   r\   rc   r   r   r   r   r   r   r   r   r   r   r   r   r   r4   r   r   r   r   r   shutdown_allr   r   r   r   r   r   r.   r   r   r   r  r  r	  r  r  r~   __classcell__)r^   s   @r    r6   r6   3   s       00!'!J  	cc  #(#4FFF++3  
 
cc  W#$$L L L %$L !S&QRRRW%&&5 5 5 '&5% % % % TC   
cc 
 h}%%GtE{{tvv% % % X% WY    WR[[N%gdt<<<tvvH@ @ @ @ @ @     1* 1* 1* 1*f+ + + +* * * ** * * *2	9 	9 	9 	9" " " "" " " "; ; ; ; FJ      B 8/00L
 !$	++ ++ ++ ++ ++Z h566O; ; ; ; ];  "&%(	8 8 8 8 ]8 , , , , ],2 2 2 2    $ 8/00L     G G G ]G9 9 9 9 9, X344N
 
 
 ]
G G G G
	( 	( 	( 	( AJ5 5 5 5 ]5
 AJ8 8 8 8 ]8
    ]" 7;    ]" 7;    ]" 7;    ]" 7;    ]" 7;    ]"! ! ! ! ! ! ! !r   r6   c                     e Zd ZU  eddd          Z edd                              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<   dS )AsyncMultiKernelManagerz.jupyter_client.ioloop.AsyncIOLoopKernelManagerTzThe kernel manager class.  This is configurable to allow
        subclassing of the AsyncKernelManager for customized behavior.
        )r:   r8   FzWhether to make kernels available before the process has started.  The
        kernel has a `.ready` future which can be awaited before connectingr7   r9   zmq.asyncio.ContextrH   r#   c                L    d| _         t          j                                        S rU   )rV   rW   r   rX   rD   s    r    rK   z(AsyncMultiKernelManager._context_defaulth  s     ${""$$$r   zt.Callable[..., t.Awaitable]r   r   r   r  N)r#   r  )r   r   r   r
   r<   r   r  r   r   rH   r   rK   r6   r   r   __annotations__r   r   r   r   r   r  r   r   r    r  r  W  s         ++8   $O   
cc	  h,--GWY% % % % 2D1WLWWWW3E3[N[[[[4F4]O]]]]1C1WLWWWWWWr   r  )r!   r"   r#   r"   ),r  
__future__r   r   rz   r   sockettypingr   r  	functoolsr   pathlibr   rW   	traitletsr   r   r	   r
   r   r   r   r   traitlets.config.configurabler   traitlets.utils.importstringr   connectr   
kernelspecr   r   managerr   utilsr   r   r   r}   r   r4   r6   r  r   r   r    <module>r'     s   + + # " " " " "   				                   



 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ = = = = = = 4 4 4 4 4 4 ) ) ) ) ) ) = = = = = = = = " " " " " " 1 1 1 1 1 1 1 1 1 1	 	 	 	 	9 	 	 	   *a! a! a! a! a!, a! a! a!HX X X X X0 X X X X Xr   