a
    ø£Be}X  ã                   @  s   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„ de'ƒZ(dddœdd„Z)G dd„ deƒZ*G d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                   @  s   e Zd ZdS )ÚDuplicateKernelErrorN)Ú__name__Ú
__module__Ú__qualname__© r   r   úd/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_client/multikernelmanager.pyr      s   r   ú
t.Callable)ÚfÚreturnc                   s&   t ˆ ƒddddddœ‡ fdd„ƒ}|S )zDdecorator for proxying MKM.method(kernel_id) to individual KMs by IDút.AnyÚstrzt.Callable | t.Awaitable)ÚselfÚ	kernel_idÚargsÚkwargsr    c                   s@   |   |¡}t|ˆ jƒ}||i |¤Ž}ˆ | |g|¢R i |¤Ž |S ©N)Ú
get_kernelÚgetattrr   )r#   r$   r%   r&   ÚkmÚmethodÚr©r   r   r   Úwrapped!   s
    
zkernel_method.<locals>.wrappedr   )r   r.   r   r-   r   Úkernel_method   s    r/   c                      sž  e Zd ZdZeedd�jdd�Zee	dd�Z
eddd�jdd�Zed	ƒd
ddœdd„ƒZedd�Zedƒddœdd„ƒZddœdd„Zeddd�jdd�ZedƒZedƒZeƒ Zeddœdd„ƒZedƒddœdd„ƒZed ƒZed!dd�Zeƒ Zd
d
dd"œ‡ fd#d$„Z ddœ‡ fd%d&„Z!d'dœd(d)„Z"d*dœd+d,„Z#d-d.d/œd0d1„Z$d2d
d3d4œd5d6„Z%d-d7dd8œd9d:„Z&d-d;d<dd=œd>d?„Z'd-d<dd@œdAdB„Z(d.dœdCdD„Z)d!dEœd2d
d-d4œdFdG„Z*e+e*ƒZ,d‚d-dHdHddIœdJdK„Z-e+e-ƒZ.e/dƒd-dHddLœdMdN„ƒZ0e/d„d-dPdPddQœdRdS„ƒZ1e/d…d-d.ddLœdTdU„ƒZ2d-d;d/œdVdW„Z3d†d.ddXœdYdZ„Z4e+e4ƒZ5d-dd/œd[d\„Z6e/d-d*dd]œd^d_„ƒZ7d‡d-d.dd`œdadb„Z8e+e8ƒZ9e/d-d.d/œdcdd„ƒZ:d-dd/œdedf„Z;d-d;d/œdgdh„Z<e/dˆd-dd-ddjœdkdl„ƒZ=e/d‰d-dd-ddjœdmdn„ƒZ>e/d-dod/œdpdq„ƒZ?e/dŠd-drdsdtœdudv„ƒZ@e/d‹d-drdsdtœdwdx„ƒZAe/dŒd-drdsdtœdydz„ƒZBe/d�d-drdsdtœd{d|„ƒZCe/dŽd-drdsdtœd}d~„ƒZDd
d-dœd€d�„ZE‡  ZFS )�ÚMultiKernelManagerz&A class for managing multiple kernels.z'The name of the default kernel to start©ÚhelpT©Úconfig)Ú
allow_nonez)jupyter_client.ioloop.IOLoopKernelManagerzƒThe kernel manager class.  This is configurable to allow
        subclassing of the KernelManager for customized behavior.
        Úkernel_manager_classr!   ÚNone)Úchanger    c                 C  s   |   ¡ | _d S r'   )Ú_create_kernel_manager_factoryÚkernel_manager_factory)r#   r8   r   r   r   Ú_kernel_manager_class_changedC   s    z0MultiKernelManager._kernel_manager_class_changedz)this is kernel_manager_class after importr:   r   ©r    c                 C  s   |   ¡ S r'   )r9   ©r#   r   r   r   Ú_kernel_manager_factory_defaultI   s    z2MultiKernelManager._kernel_manager_factory_defaultc                   s&   t ˆjƒ‰ ddddœ‡ ‡fdd„}|S )Nr!   r   ©r%   r&   r    c                    s8   ˆj r&ˆjjrˆ ¡ ˆ_| dˆj¡ ˆ | i |¤Ž}|S )NÚcontext)Úshared_contextr@   ÚclosedÚ_context_defaultÚ
setdefault)r%   r&   r*   ©Zkernel_manager_ctorr#   r   r   Úcreate_kernel_managerP   s    
zPMultiKernelManager._create_kernel_manager_factory.<locals>.create_kernel_manager)r   r6   )r#   rF   r   rE   r   r9   M   s    
	z1MultiKernelManager._create_kernel_manager_factoryz4Share a single zmq.Context to talk to all my kernelszzmq.ContextFÚdictc                 C  s   | j S )z#A shim for backwards compatibility.)Ú_pending_kernelsr=   r   r   r   Ú_starting_kernelsf   s    z$MultiKernelManager._starting_kernelsr@   c                 C  s   d| _ t ¡ S ©NT)Ú_created_contextÚzmqÚContextr=   r   r   r   rC   k   s    z#MultiKernelManager._context_defaultÚ Nr?   c                   s   t ƒ j|i |¤Ž i | _d S r'   )ÚsuperÚ__init__Úkernel_id_to_connection_file)r#   r%   r&   ©Ú	__class__r   r   rP   u   s    zMultiKernelManager.__init__c                   s\   | j r2| jr2| jjs2| jr(| j d| ¡ | j ¡  ztƒ j}W n tyP   Y n0 |ƒ  dS )z:Handle garbage collection.  Destroy context if applicable.zDestroying zmq context for %sN)	rK   r@   rB   ÚlogÚdebugÚdestroyrO   Ú__del__ÚAttributeError)r#   Z	super_delrR   r   r   rW   y   s    
zMultiKernelManager.__del__z	list[str]c           	   	   C  sb  | j du�rTt| j ƒ}| ¡ �rTdd„ | ¡ D ƒ}t| j ¡ ƒ}t| j ¡ ƒ}t| j ¡ ƒD ]*}||vr\|| |¡ }| j|= | j	|= q\|D ]Æ}|| j ¡ v r qŒzt
 | ¡ ¡}W n tyÈ   Y qŒY n0 | j d|¡ d|v rŒd|v sêqŒ|  ¡ }|| j|< | j| | jdd�}| |¡ tƒ |_d	|_d
|_||_|d |_|j d¡ || j	|< qŒt| j	 ¡ ƒS )z6Return a list of the kernel ids of the active kernels.Nc                 S  s   g | ]}|  ¡ r|‘qS r   )Úis_file)Ú.0Úpr   r   r   Ú
<listcomp>‹   ó    z6MultiKernelManager.list_kernel_ids.<locals>.<listcomp>zLoading connection file %sÚkernel_nameÚkeyF)ÚparentrT   Zowns_kernelÚidler   )Úexternal_connection_dirr   Úis_dirÚiterdirÚlistrQ   ÚkeysÚvaluesÚindexÚ_kernelsÚjsonÚloadsÚ	read_textÚ	ExceptionrT   rU   Únew_kernel_idr:   Zload_connection_infor   Zlast_activityZexecution_stateÚconnectionsr$   r^   ÚreadyÚ
set_result)	r#   rb   Zconnection_filesÚkÚvÚconnection_filer$   Zconnection_infor*   r   r   r   Úlist_kernel_ids†   sN    


ÿ

ý

z"MultiKernelManager.list_kernel_idsÚintc                 C  s   t |  ¡ ƒS )z%Return the number of running kernels.)Úlenru   r=   r   r   r   Ú__len__¹   s    zMultiKernelManager.__len__r"   Úbool)r$   r    c                 C  s
   || j v S r'   )ri   ©r#   r$   r   r   r   Ú__contains__½   s    zMultiKernelManager.__contains__z
str | Noneztuple[KernelManager, str, str])r^   r&   r    c                 C  s„   |  d| jf i |¤Ž¡}|| v r,td| ƒ‚|d u r:| j}i }| jrN| j|d< | jf tj | j	d| ¡| | j
|dœ|¤Ž}|||fS )Nr$   zKernel already exists: %sÚkernel_spec_managerzkernel-%s.json)rt   r`   rT   r^   )Úpoprn   r   Údefault_kernel_namer|   r:   ÚosÚpathÚjoinÚconnection_dirrT   )r#   r^   r&   r$   Zconstructor_kwargsr*   r   r   r   Úpre_start_kernelÀ   s"    
üûz#MultiKernelManager.pre_start_kernelzt.Dict[str, str])r$   Úenvr    c                C  s   || v r| j |  |¡ 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
        N)ri   Ú
update_env)r#   r$   r„   r   r   r   r…   Ù   s    zMultiKernelManager.update_envr   zt.Awaitable)r$   r*   Úkernel_awaitabler    c              
   Ã  s\   z&|I d H  || j |< | j |d ¡ W n0 tyV } z| j |¡ W Y d }~n
d }~0 0 d S r'   )ri   rH   r}   rm   rT   Ú	exception)r#   r$   r*   r†   Úer   r   r   Ú_add_kernel_when_readyä   s    

z)MultiKernelManager._add_kernel_when_ready)r$   r†   r    c              
   Ã  s\   z&|I d H  |   |¡ | j |d ¡ W n0 tyV } z| j |¡ W Y d }~n
d }~0 0 d S r'   )Úremove_kernelrH   r}   rm   rT   r‡   )r#   r$   r†   rˆ   r   r   r   Ú_remove_kernel_when_readyî   s    

z,MultiKernelManager._remove_kernel_when_readyc                 C  s   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)   r=   r   r   r   Ú_using_pending_kernelsø   s    z)MultiKernelManager._using_pending_kernels)r^   c                Ë  s¤   |   ||¡\}}}t|tƒs4| j dj| jjd�¡ ||d< t|j	f i |¤Žƒ}t
 |  |||¡¡}|| j|< |  ¡ r‚|| j|< n|I dH  |j ¡ r |j ¡ ‚|S )zéStart 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'!)Zkm_classr$   N)rƒ   Ú
isinstancer   rT   ÚwarningÚformatr6   rS   r   Ústart_kernelÚasyncioÚcreate_taskr‰   rH   r�   ri   rp   r‡   )r#   r^   r&   r*   r$   ZstarterÚtaskr   r   r   Ú_async_start_kernelþ   s"    
ÿÿ



z&MultiKernelManager._async_start_kernelzbool | None)r$   ÚnowÚrestartr    c                 Ã  s  | j  d|¡ || jv r‚| j| }z.|I dH  |  |¡}t tj|j¡I dH  W n0 tj	yd   Y n t
y€   |  |¡ Y dS 0 |  |¡}|j ¡ s®|j ¡ r®|  |¡ dS t| ||¡ƒ}t |  ||¡¡}|| j|< |  ¡ �s|I dH  |j ¡ �r|j ¡ ‚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)rT   ÚinforH   r(   ÚtÚcastr’   ÚFuturerp   ÚCancelledErrorrm   rŠ   Ú	cancelledr‡   r   Úshutdown_kernelÚensure_futurer‹   r�   )r#   r$   r–   r—   r”   r*   ZstopperÚfutr   r   r   Ú_async_shutdown_kernel!  s.    









z)MultiKernelManager._async_shutdown_kernel)r$   r—   r    c                 C  s   dS )z,Ask a kernel to shut down by its kernel uuidNr   ©r#   r$   r—   r   r   r   Úrequest_shutdownP  s    z#MultiKernelManager.request_shutdownçš™™™™™¹?zfloat | None)r$   ÚwaittimeÚpollintervalr    c                 C  s   | j  d|¡ dS )zDWait for a kernel to finish shutting down, and kill it if it doesn'tr˜   N©rT   r™   )r#   r$   r¦   r§   r   r   r   Úfinish_shutdownT  s    z"MultiKernelManager.finish_shutdownc                 C  s   dS )zClean up a kernel's resourcesNr   r£   r   r   r   Úcleanup_resources^  s    z$MultiKernelManager.cleanup_resourcesc                 C  s   | j  |d¡S )záremove 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)ri   r}   rz   r   r   r   rŠ   b  s    z MultiKernelManager.remove_kernel)r–   r    c              	   ƒ  s¨   ˆ  ¡ }|tˆjƒ7 }tˆj ¡ ƒ}‡ ‡fdd„t|ƒD ƒ}tj|Ž I dH  ˆ ¡ r¤|D ]J}z|j	I dH  W qX tj
y�   ˆj|j  ¡  Y qX ty    Y qX0 qXdS )zShutdown all kernels.c                   s   g | ]}ˆj |ˆ d �‘qS )©r–   )r¢   )rZ   Úkid©r–   r#   r   r   r\   q  r]   z:MultiKernelManager._async_shutdown_all.<locals>.<listcomp>N)ru   re   rH   ri   rg   Úsetr’   Úgatherr�   rp   r�   r$   Úcancelrm   )r#   r–   ZkidsZkmsZfutsr*   r   r­   r   Ú_async_shutdown_alll  s    z&MultiKernelManager._async_shutdown_allc                 C  s:   |   |¡}|j ¡ s d}t|ƒ‚| ¡ }| j d|¡ |S )z¢Interrupt (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(   rp   ÚdoneÚRuntimeErrorÚinterrupt_kernelrT   r™   )r#   r$   ÚkernelÚmsgÚoutr   r   r   r´   €  s    

z#MultiKernelManager.interrupt_kernel)r$   Úsignumr    c                 C  s   | 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¸   r   r   r   Úsignal_kernel�  s    z MultiKernelManager.signal_kernel)r$   r–   r    c                 Ã  sP   |   |¡}|  ¡ r(|j ¡ s(d}t|ƒ‚t|j|d�ƒI dH  | 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�   rp   r²   r³   r   Úrestart_kernelrT   r™   )r#   r$   r–   rµ   r¶   r   r   r   Ú_async_restart_kernel   s    
z(MultiKernelManager._async_restart_kernelc                 C  s   dS )zìIs 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   rz   r   r   r   Úis_alive¸  s    zMultiKernelManager.is_alivec                 C  s   || vrt d| ƒ‚dS )zcheck that a kernel id is validzKernel with id not found: %sN)ÚKeyErrorrz   r   r   r   Ú_check_kernel_idÅ  s    z#MultiKernelManager._check_kernel_idc                 C  s   |   |¡ | j| S )z¨Get the single KernelManager object for a kernel by its uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.
        )r¾   ri   rz   r   r   r   r(   Ê  s    
zMultiKernelManager.get_kernelr—   )r$   ÚcallbackÚeventr    c                 C  s   dS )z&add a callback for the KernelRestarterNr   ©r#   r$   r¿   rÀ   r   r   r   Úadd_restart_callbackÕ  s    z'MultiKernelManager.add_restart_callbackc                 C  s   dS )z)remove a callback for the KernelRestarterNr   rÁ   r   r   r   Úremove_restart_callbackÛ  s    z*MultiKernelManager.remove_restart_callbackzdict[str, t.Any]c                 C  s   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   rz   r   r   r   Úget_connection_infoá  s    z&MultiKernelManager.get_connection_infozbytes | Nonezsocket.socket)r$   Úidentityr    c                 C  s   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Å   r   r   r   Úconnect_iopubó  s    z MultiKernelManager.connect_iopubc                 C  s   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Æ   r   r   r   Úconnect_shell  s    z MultiKernelManager.connect_shellc                 C  s   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Æ   r   r   r   Úconnect_control  s    z"MultiKernelManager.connect_controlc                 C  s   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Æ   r   r   r   Úconnect_stdin)  s    z MultiKernelManager.connect_stdinc                 C  s   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Æ   r   r   r   Ú
connect_hb;  s    zMultiKernelManager.connect_hb)r&   r    c                 K  s   t t ¡ ƒ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&   r   r   r   rn   M  s    z MultiKernelManager.new_kernel_id)FF)F)Nr¥   )F)F)F)r—   )r—   )N)N)N)N)N)Gr   r   r   Ú__doc__r   r   Útagr~   r
   r   r|   r	   r6   r   r;   r   r:   r   r>   r9   r   rA   r@   rK   r   rH   ÚpropertyrI   rC   r‚   rb   ri   rP   rW   ru   rx   r{   rƒ   r…   r‰   r‹   r�   r•   r   r‘   r¢   rŸ   r/   r¤   r©   rª   rŠ   r±   Úshutdown_allr´   r¹   r»   rº   r¼   r¾   r(   rÂ   rÃ   rÄ   rÇ   rÈ   rÉ   rÊ   rË   rn   Ú__classcell__r   r   rR   r   r0   3   s¾   ÿþþû
þý3

!  ü-  ü	
 ÿ ÿ ÿ ÿ ÿ ÿ ÿr0   c                   @  s†   e Zd ZU edddd�Zeddd�jdd�Zed	ƒZ	e
d
ƒd	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.AsyncIOLoopKernelManagerTzˆThe kernel manager class.  This is configurable to allow
        subclassing of the AsyncKernelManager for customized behavior.
        )r4   r2   Fz’Whether to make kernels available before the process has started.  The
        kernel has a `.ready` future which can be awaited before connectingr1   r3   zzmq.asyncio.Contextr@   r<   c                 C  s   d| _ tj ¡ S rJ   )rK   rL   r’   rM   r=   r   r   r   rC   h  s    z(AsyncMultiKernelManager._context_defaultzt.Callable[..., t.Awaitable]r‘   rº   rŸ   rÑ   N)r   r   r   r	   r6   r   rÏ   rŒ   r
   r@   r   rC   r0   r•   r‘   Ú__annotations__r»   rº   r¢   rŸ   r±   rÑ   r   r   r   r   rÓ   W  s,   
ýþüþ
þ
þ
þrÓ   ),rÎ   Ú
__future__r   r’   rj   r   ÚsocketÚtypingrš   rÌ   Ú	functoolsr   Úpathlibr   rL   Z	traitletsr   r   r   r	   r
   r   r   r   Ztraitlets.config.configurabler   Ztraitlets.utils.importstringr   Úconnectr   Z
kernelspecr   r   Úmanagerr   Úutilsr   r   r   rm   r   r/   r0   rÓ   r   r   r   r   Ú<module>   s2   (    (