
    Mh!                       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	m
Z
 ddlmZmZ ddlmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddl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(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z;m<Z<m=Z=  G d de          Z> G d de>e          Z?d#d$d Z@ G d! d"e          ZAdS )%zbA MultiKernelManager for use in the Jupyter server

- raises HTTPErrors
- creates REST API models
    )annotationsNdefaultdict)datetime	timedelta)partialwraps)AsyncIOLoopKernelManager)AsyncMultiKernelManagerMultiKernelManager)Session)exists)ensure_async)EventLogger)SchemaRegistryException)	overrides)web)Future)IOLoopPeriodicCallback)AnyBoolDictFloatInstanceIntegerList
TraitErrorUnicodedefaultvalidateDEFAULT_EVENTS_SCHEMA_PATH)	isoformatutcnow)KERNEL_CURRENTLY_RUNNING_TOTAL)ApiPathimport_item
to_os_pathc                  P    e Zd ZU dZ ed          d             Z e e                      Z ed          Z	 e
            Z e
            Zded<   dZd	Z ed
          d             Z ed
          d             Z eddd          ZdZ eedd          Z ed	dd          Z ed	dd          Z eddd          Z eddd          Z e            Z ed          d             Z e e!d          Z"d Z# e e            dd          Z$ eddd          Z% eddd           Z&d! Z'd" Z( fd#Z)ddd$dCd,Z*e*Z+d- Z,d. Z-d/ Z.d0 Z/d1 Z0d2 Z1dDd3Z2e2Z3dEd4Z4e4Z5d5 Z6d6 Z7d7 Z8d8 Z9d9 Z: e e            dg d:d;<          Z;d= Z<d> Z=d? Z>d@ Z?dA Z@dB ZA xZBS )FMappingKernelManagerzmA KernelManager that handles
    - File mapping
    - HTTP error handling
    - Kernel message filtering
    kernel_manager_classc                    dS )Nz)jupyter_client.ioloop.IOLoopKernelManager selfs    m/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/services/kernels/kernelmanager.py_default_kernel_manager_classz2MappingKernelManager._default_kernel_manager_class:   s    ::    Tconfigzdict[str, list[int]]_kernel_portsNFroot_dirc                N    | j         st          j                    S | j         j        S N)parentosgetcwdr7   r/   s    r1   _default_root_dirz&MappingKernelManager._default_root_dirJ   s#    { 	9;;{##r3   c                   |d         }t           j                            |          st           j                            |          }t	          |          rt           j                            |          st          d|z            |S )z'Do a bit of validation of the root dir.valuez%kernel root dir %r is not a directory)r;   pathisabsabspathr   isdirr   )r0   proposalr?   s      r1   _update_root_dirz%MappingKernelManager._update_root_dirP   su     !w}}U## 	+GOOE**Ee}} 	NBGMM%$8$8 	NDuLMMMr3   r   zTimeout (in seconds) after which a kernel is considered idle and ready to be culled.
        Values of 0 or lower disable culling. Very short timeouts may result in kernels being culled
        for users with poor network connections.)r5   helpi,  z^The interval (in seconds) on which to check for idle kernels exceeding the cull timeout value.zxWhether to consider culling kernels which have one or more connections.
        Only effective if cull_idle_timeout > 0.zdWhether to consider culling kernels which are busy.
        Only effective if cull_idle_timeout > 0.ae  Whether messages from kernels whose frontends have disconnected should be buffered in-memory.

        When True (default), messages are buffered and replayed on reconnect,
        avoiding lost messages due to interrupted connectivity.

        Disable if long-running kernels will produce too much output while
        no frontends are connected.
        <   a  Timeout for giving up on a kernel (in seconds).

        On starting and restarting kernels, we check whether the
        kernel is running and responsive by sending kernel_info_requests.
        This sets the timeout in seconds for how long the kernel can take
        before being presumed dead.
        This affects the MappingKernelManager (which handles kernel restarts)
        and the ZMQChannelsHandler (which handles the startup).
        _kernel_buffersc                "    t          d           S )Nc                     g di dS )N )buffersession_keychannelsr.   r.   r3   r1   <lambda>z>MappingKernelManager._default_kernel_buffers.<locals>.<lambda>   s    bQS#T#T r3   r   r/   s    r1   _default_kernel_buffersz,MappingKernelManager._default_kernel_buffers   s    TTUUUr3   zAThe last activity on any kernel, including shutting down a kernelrF   c                x    t           | _        i | _         | j        j        | fi | t	                      | _        dS )zInitialize a kernel manager.Nr   pinned_superclass_pending_kernel_tasks__init__r%   last_kernel_activityr0   kwargss     r1   rV   zMappingKernelManager.__init__   B    !3%'"''77777$*HH!!!r3   zsWhite list of allowed kernel message types.
        When the list is empty, all message types are allowed.
        )traitr5   rF   z4Whether to send tracebacks to clients on exceptions.zMAn exception occurred at runtime, which is not shown due to security reasons.zHMessage to print when allow_tracebacks is False, and an exception occursc                f    | j                             d|           |                     |           dS )znotice that a kernel diedz"Kernel %s died, removing from map.N)logwarningremove_kernelr0   	kernel_ids     r1   _handle_kernel_diedz(MappingKernelManager._handle_kernel_died   s5    =yIII9%%%%%r3   c                   t          || j                  }t          j                            |          sT|| j        k    rIt          j                            |          }t          j                            |          s|| j        k    I|S )z$Turn API path into absolute OS path.)r)   r7   r;   r@   rC   dirname)r0   r@   rY   os_paths       r1   cwd_for_pathz!MappingKernelManager.cwd_for_path   ss    T4=11 '--(( 	/W-E-Egoog..G '--(( 	/W-E-Er3   c                   K   t                                          ||           d{V  | j                            |d           | j                            |d           dS )z!Remove a kernel when it is ready.N)super_remove_kernel_when_ready_kernel_connectionspopr6   )r0   ra   kernel_awaitable	__class__s      r1   ri   z.MappingKernelManager._remove_kernel_when_ready   sl      gg//	;KLLLLLLLLL $$Y555y$/////r3   )ra   r@   ra   
str | Noner@   ApiPath | NonerY   strreturnc               <  K   ||| vr|.|                      ||                    di                     |d<   ||
J d            ||d<    | j        j        | fi | d{V }d| j        |<   |                     |          }d|_        d	|_        t                      |_	        | j
                            d
|           | j
                            dd |                                D                        |                    dd          }|rOt          |t                    r:| j
                            dt!          |                                                     t%          j        |                     |                    }t+          | dd          s	| d{V  n
|| j        |<   t/          j        | j        |         j                                                   n| j
                            d|           | j        s|                                  |J |S )ay  Start a kernel for a session and return its kernel_id.

        Parameters
        ----------
        kernel_id : uuid (str)
            The uuid to associate the new kernel with. If this
            is not None, this kernel will be persistent whenever it is
            requested.
        path : API path
            The API path (unicode, '/' delimited) for the cwd.
            Will be transformed to an OS path relative to root_dir.
        kernel_name : str
            The name identifying which kernel spec to launch. This is ignored if
            an existing kernel is returned, but it may be checked in the future.
        Nenvrs   cwdz#Never Fail, but necessary for mypy ra   r   startingrK   zKernel started: %szKernel args (excluding env): %rc                &    i | ]\  }}|d k    ||S rt   r.   ).0kvs      r1   
<dictcomp>z<MappingKernelManager._async_start_kernel.<locals>.<dictcomp>   s*    3b3b3bTQWX\aWaWaAqWaWaWar3   z%Kernel argument 'env' passed with: %ruse_pending_kernelstypezUsing existing kernel: %s)rf   getrT   _async_start_kernelrj   
get_kernelexecution_statereasonr%   last_activityr]   infodebugitems
isinstancedictlistkeysasynciocreate_task_finish_kernel_startgetattrrU   r&   labels_kernelskernel_nameinc_initialized_cullerinitialize_culler)r0   ra   r@   rY   kernelrs   tasks          r1   r   z(MappingKernelManager._async_start_kernel   sF     $ 	 5 5 $ 1 1$FJJub<Q<Q 1 R Ru$ ,,.S,,,&/{#Hd4HXXQWXXXXXXXXI23D$Y/ __Y//F%/F"FM#)88F HMM.	:::HNN13b3bV\\^^3b3b3b   **UD))C Zz#t,, ZFSXXZZHXHXYYY&t'@'@'K'KLLD4!6== =







8<*95 +1t}Y7O7[\\\``bbbb HMM5yAAA ' 	%""$$$$$$r3   c                   K                                   }t          |d          rj|j        }t          |t          j                  st	          j        |          }	 | d{V  n+# t          $ r  j        	                    d           Y dS w xY w|j
         j        <                                                         fdd           dS )z'Handle a kernel that finishes starting.readyNz&Error waiting for kernel manager readyc                 .                                    S r9   )rb   )ra   r0   s   r1   rO   z;MappingKernelManager._finish_kernel_start.<locals>.<lambda>#  s    D,,Y77 r3   dead)r   hasattrr   r   r   r   wrap_future	Exceptionr]   	exceptionportsr6   start_watching_activityadd_restart_callback)r0   ra   kmr   s   ``  r1   r   z)MappingKernelManager._finish_kernel_start  s     __Y''2w 	HEeW^44 3+E22   ""#KLLL )+9%$$Y///!!77777	
 	
 	
 	
 	
s    A) )$BBc                    |                      |          }|r'| j                            d|           || j        |<   dS dS )a}  Used by ZMQChannelsHandler to determine how to coordinate nudge and replays.

        Ports are captured when starting a kernel (via MappingKernelManager).  Ports
        are considered changed (following restarts) if the referenced KernelManager
        is using a set of ports different from those captured at startup.  If changes
        are detected, the captured set is updated and a value of True is returned.

        NOTE: Use is exclusive to ZMQChannelsHandler because this object is a singleton
        instance while ZMQChannelsHandler instances are per WebSocket connection that
        can vary per kernel lifetime.
        z#Port change detected for kernel: %sTF)_get_changed_portsr]   r   r6   )r0   ra   changed_portss      r1   ports_changedz"MappingKernelManager.ports_changed'  sM     //	:: 	HNN@)LLL,9Dy)4ur3   c                    |                      |          }t          |j        t                    sJ t          | j        |         t                    sJ |j        | j        |         k    r|j        S dS )a  Internal method to test if a kernel's ports have changed and, if so, return their values.

        This method does NOT update the captured ports for the kernel as that can only be done
        by ZMQChannelsHandler, but instead returns the new list of ports if they are different
        than those captured at startup.  This enables the ability to conditionally restart
        activity monitoring immediately following a kernel's restart (if ports have changed).
        N)r   r   r   r   r6   )r0   ra   r   s      r1   r   z'MappingKernelManager._get_changed_ports;  sl     __Y''"(D)))))$,Y7>>>>>8t))4448Otr3   c                     j         s-|                                D ]}|                                 dS  j                            d|                                                                            j                 |d<   g d<   |d<    fd}|                                D ](\  }}|	                    t          ||                     )dS )a  Start buffering messages for a kernel

        Parameters
        ----------
        kernel_id : str
            The id of the kernel to stop buffering.
        session_key : str
            The session_key, if any, that should get the buffer.
            If the session_key matches the current buffered session_key,
            the buffer will be returned.
        channels : dict({'channel': ZMQStream})
            The zmq channels whose messages should be buffered.
        NzStarting buffering for %srM   rL   rN   c                z    j                             d|            d                             | |f           d S )NzBuffering msg on %s:%srL   )r]   r   append)channel	msg_partsbuffer_infora   r0   s     r1   
buffer_msgz8MappingKernelManager.start_buffering.<locals>.buffer_msgk  s@    HNN3YHHH!(('9)=>>>>>r3   )buffer_offline_messagesvaluescloser]   r   _check_kernel_idstop_bufferingrH   r   on_recvr   )r0   ra   rM   rN   streamr   r   r   s   ``     @r1   start_bufferingz$MappingKernelManager.start_bufferingK  s    + 	"//++  F1;???i(((I&&&*95%0M" "H"*J	? 	? 	? 	? 	? 	? 	?  (~~// 	9 	9OGVNN7:w778888	9 	9r3   c                    | j                             d|           || j        vrdS | j        |         }|d         |k    r| j                            |           |S |                     |           dS )at  Get the buffer for a given kernel

        Parameters
        ----------
        kernel_id : str
            The id of the kernel to stop buffering.
        session_key : str, optional
            The session_key, if any, that should get the buffer.
            If the session_key matches the current buffered session_key,
            the buffer will be returned.
        zGetting buffer for %sNrM   )r]   r   rH   rk   r   )r0   ra   rM   r   s       r1   
get_bufferzMappingKernelManager.get_bufferr  s     	.	:::D0004*95}%44 $$Y///	*****r3   c                   | j                             d|           |                     |           || j        vrdS | j                            |          }|d                                         D ]7}|j        j        s)|                    d           |	                                 8|d         }|r1| j         
                    dt          |          |d                    dS dS )zStop buffering kernel messages

        Parameters
        ----------
        kernel_id : str
            The id of the kernel to stop buffering.
        zClearing buffer for %sNrN   rL   z&Discarding %s buffered messages for %srM   )r]   r   r   rH   rk   r   socketclosedr   r   r   len)r0   ra   r   r   
msg_buffers        r1   r   z#MappingKernelManager.stop_buffering  s     	/;;;i(((D000F*..y99!*-4466 	 	F=' t$$$ *
 	HMM8JM*    	 	r3   c                  K   |                      |           t          j        | j        |         j                                                   || j        v r.| j                            |          }|                                 | 	                    |           | 
                    |           | j                            | |||           d{V S )zShutdown a kernel by kernel_idr}   )nowrestartN)r   r&   r   r   r   decrU   rk   cancelstop_watching_activityr   rT   _async_shutdown_kernel)r0   ra   r   r   r   s        r1   r   z+MappingKernelManager._async_shutdown_kernel  s      i((( 	'-4=3K3WXXX\\^^^222-11)<<DKKMMM##I...I&&&+BB)g C 
 
 
 
 
 
 
 
 	
r3   c                   	
K                                     j                             |           d{V                                                                 t                      	
fd fd} fd} fd
                    
d           _        j        	                    d           
                    |           t          j                    		                    	                                 j        z   |                                         *                                                                S )	zRestart a kernel by kernel_id)r   Nc                                                       s                                                                                     d           d_        dS )z:Common cleanup when restart finishes/fails for any reason.r   N)r   r   remove_timeoutremove_restart_callback_pending_restart_cleanup)r   r   loopon_restart_failedtimeouts   r1   finishz:MappingKernelManager._async_restart_kernel.<locals>.finish  s[    >>##  (((**+<fEEE.2F+++r3   c                    j                             d                                                         s                    |            d S d S )NzKernel info reply received: %s)r]   r   done
set_result)msgr   futurera   r0   s    r1   on_replyz<MappingKernelManager._async_restart_kernel.<locals>.on_reply  sY    HNN;YGGGFHHH;;== '!!#&&&&&' 'r3   c                     j                             d                                                          s$                    t	          d                     d S d S )Nz)Timeout waiting for kernel_info_reply: %szTimeout waiting for restart)r]   r^   r   set_exceptionTimeoutErrorr   r   ra   r0   s   r1   
on_timeoutz>MappingKernelManager._async_restart_kernel.<locals>.on_timeout  sg    HH)TTTFHHH;;== R$$\2O%P%PQQQQQR Rr3   c                     j                             d                                                          s$                    t	          d                     d S d S )NzRestarting kernel failed: %szRestart failed)r]   r^   r   r   RuntimeErrorr   s   r1   r   zEMappingKernelManager._async_restart_kernel.<locals>.on_restart_failed  sg    H;YGGGFHHH;;== E$$\2B%C%CDDDDDE Er3   r   kernel_info_request)r   rT   _async_restart_kernelr   connect_shellr   r   r   sessionsendr   r   currentadd_timeouttimekernel_info_timeoutr   r   r   )r0   ra   r   r   r   r   r   r   r   r   r   r   s   ``   @@@@@@@r1   r   z*MappingKernelManager._async_restart_kernel  s     i((($::4PS:TTTTTTTTT++&&(($hh	3 	3 	3 	3 	3 	3 	3 	3 	3	' 	' 	' 	' 	' 	' 	' 	'	R 	R 	R 	R 	R 	R 	R 	R	E 	E 	E 	E 	E 	E 	E 	E 	##$5v>>>*0'G%:;;;!!!~""499;;1I#I:VV""9--9''	222((333r3   c                F    || j         v r| j         |xx         dz  cc<   dS dS )z#Notice a new connection to a kernel   Nrj   r`   s     r1   notify_connectz#MappingKernelManager.notify_connect  =    000$Y///14///// 10r3   c                F    || j         v r| j         |xx         dz  cc<   dS dS )z$Notice a disconnection from a kernelr   Nr   r`   s     r1   notify_disconnectz&MappingKernelManager.notify_disconnect  r   r3   c                    |                      |           | j        |         }||j        t          |j                  |j        | j                            |d          d}t          |dd          r
|j	        |d<   |S )zqReturn a JSON-safe dict representing a kernel

        For use in representing kernels in the JSON APIs.
        r   )idnamer   r   connectionsr   N)
r   r   r   r$   r   r   rj   r   r   r   )r0   ra   r   models       r1   kernel_modelz!MappingKernelManager.kernel_model  s    
 	i(((y) &&v';<<%5377	1EE
 
 68T** 	,$mE(Or3   c                    g }| j                             |           }|D ]I}	 |                     |          }|                    |           .# t          j        t          f$ r Y Fw xY w|S )z1Returns a list of kernel_id's of kernels running.)rT   list_kernel_idsr   r   r   	HTTPErrorKeyError)r0   kernels
kernel_idsra   r   s        r1   list_kernelsz!MappingKernelManager.list_kernels
  s    +;;DAA
# 	 	I)))44u%%%%M8,    s   *AA&%A&c                >    || vrt          j        dd|z            dS )z5Check a that a kernel_id exists and raise 404 if not.i  zKernel does not exist: %sN)r   r   r`   s     r1   r   z%MappingKernelManager._check_kernel_id  s-    D  -%@9%LMMM ! r3   )comm_info_requestcomm_info_replyr   kernel_info_replyshutdown_requestshutdown_replyinterrupt_requestinterrupt_replydebug_requestdebug_replyr   display_dataupdate_display_dataexecute_inputexecute_resulterrorstatusclear_outputdebug_eventinput_requestinput_replyzList of kernel message types excluded from user activity tracking.

        This should be a superset of the message types sent on any channel other
        than the shell channel.)r[   r5   default_valuerF   c                    || j         vS r9   )untracked_message_types)r0   message_types     r1   track_message_typez'MappingKernelManager.track_message_type>  s    4#???r3   c                *     j                  d_        d_        t                      _                                        _        t          j        j	        j        j
                   fd}j                            |           dS )zStart watching IOPub messages on a kernel for activity.

        - update last_activity on every message
        - record execution_state from status messages
        rv   rK   )r5   keyc                                        |           \  }}                    |d          }|d         d         }|                    d          }|dn|                    d          }
                    |          s 
                    |          sj        dk    rt                      x
_        _        |dk    r|                    |          }|d	         d
         }
                    |          r|_        nj        dk    r|dk    rd_        
j        	                    d	|j                   dS 
j        	                    d	|           dS )z.Record an IOPub message arriving from a kernelF)contentheadermsg_typeparent_headerNbusyr  r  r   rv   idlezactivity on %s: %s (%s)zactivity on %s: %s)
feed_identitiesdeserializer   r  r   r%   rW   r   r]   r   )msg_listidentsfed_msg_listr   r  r  parent_msg_typer   r   ra   r0   r   s           r1   record_activityzEMappingKernelManager.start_watching_activity.<locals>.record_activityR  s   #*#:#:8#D#D FL%%lE%BBC8}Z0HGGO44M&3&;ddARARS]A^A^O''11L**?;;L )V33CI88K)F,@8##)),77"%i.1B"C**?;; 4-<F**+z99oQ[>[>[ .4F*-*	     3YIIIIIr3   N)r   r   r   r%   r   connect_iopub_activity_streamr   r   r5   r  r   )r0   ra   r!  r   r   s   `` @@r1   r   z,MappingKernelManager.start_watching_activityA  s     y)!+%xx"("6"6"8"8>("
 
 

	J 	J 	J 	J 	J 	J 	J 	JB 	''88888r3   c                    | j         |         }t          |dd          r1|j        j        j        s|j                                         d|_        t          |dd          r|                                 dS dS )z6Stop watching IOPub messages on a kernel for activity.r#  Nr   )r   r   r#  r   r   r   r   )r0   ra   r   s      r1   r   z+MappingKernelManager.stop_watching_activityu  s    y)6-t44 	+*18 0'--///&*F#65t<< 	.++-----	. 	.r3   c                .   | j         s| j        dk    r| j        t          j                    }| j        dk    r2| j                            d| j        | j                   | j        | _        t          | j
        d| j        z            | _        | j                            d| j        | j                   | j        r| j                            d           | j        r| j                            d           | j                                         d| _         dS )	zStart idle culler if 'cull_idle_timeout' is greater than zero.

        Regardless of that value, set flag that we've been here.
        r   NzKInvalid value for 'cull_interval' detected (%s) - using default value (%s).i  zKCulling kernels with idle durations > %s seconds at %s second intervals ...zCulling kernels even if busyz+Culling kernels even with connected clientsT)r   cull_idle_timeout_culler_callbackr   r   cull_intervalr]   r^   cull_interval_defaultr   cull_kernelsr   	cull_busycull_connectedstart)r0   _s     r1   r   z&MappingKernelManager.initialize_culler  s     (	*&**%-  A!Q&&  a&.  
 &*%?"$4T5FtOaHa$b$bD!HMM]&"  
 ~ ><===" MKLLL!'')))#'   r3   c                $  K   | j                             d| j        | j                   	 t	          | j                  D ]Q}	 |                     |           d{V  # t          $ r&}| j                             d||           Y d}~Jd}~ww xY wdS )zHandle culling kernels.z9Polling every %s seconds for kernels idle > %s seconds...NzYThe following exception was encountered while checking the idle duration of kernel %s: %s)	r]   r   r(  r&  r   r   cull_kernel_if_idler   r   )r0   ra   es      r1   r*  z!MappingKernelManager.cull_kernels  s      G"	
 	
 	

 	]dm,, 	 	I..y9999999999   ""o       	 	s   A
B'BBc                t  K   | j         |         }t          |dd          dk    rQ| j                            d|j        |j        |           t          |                     |                     d{V  dS |j        j	        }|
                    d| j                  }t          |d          r| j                            d||j        |j                   t                      }||j        z
  }|t!          |          k    }| j        p
|j        d	k    }| j        
                    |d
          }	| j        p|	 }
|rz|rz|
rzt)          |                                          }| j                            d|j        |j        ||	|           t          |                     |                     d{V  dS dS dS dS dS )zCull a kernel if it is idle.r   Nr   z#Culling '%s' dead kernel '%s' (%s).r&  r   z.kernel_id=%s, kernel_name=%s, last_activity=%s)secondsr  r   zRCulling '%s' kernel '%s' (%s) with %d connections due to %s seconds of inactivity.)r   r   r]   r^   r   r   r   shutdown_kernelkernel_specmetadatar   r&  r   r   r   r%   r   r+  rj   r,  inttotal_seconds)r0   ra   r   kernel_spec_metadatar&  dt_nowdt_idleis_idle_timeis_idle_executer   is_idle_connectedidle_durations               r1   r0  z(MappingKernelManager.cull_kernel_if_idle  s*     y)6,d33v==H5&"	   t33I>>?????????F%1:0445H$J`aaO
 
 	D HNN@"$	   XXFv33G"Y7H%I%I%IIL"nR1G61QO266y!DDK $ 3 F; 
D 
D4E 
D #G$9$9$;$; < <  h*&!   #4#7#7	#B#BCCCCCCCCCCC7	D 	D"
D 
D 
D 
D 
D 
Dr3   )ra   rn   r@   ro   rY   rp   rq   rp   )FF)F)C__name__
__module____qualname____doc__r    r2   r   r   kernel_argvr7   r   rj   r6   __annotations__r'  r   r=   r!   rE   r   r&  r)  r(  r   r,  r+  r   r   r   r   rH   rP   r   r   rW   rV   allowed_message_typesallow_tracebackstraceback_replacement_messagerb   rf   ri   r   start_kernelr   r   r   r   r   r   r   r4  r   restart_kernelr   r   r   r   r   r  r  r   r   r   r*  r0  __classcell__rm   s   @r1   r+   r+   3   s          W#$$; ; %$; $wwyy//Kwd###H$&&*.$&&M0000WZ$ $ $
 Xj    	4    Gq  M T4  N 4  I #d    %
   ceeOWV V  V $8P  
- - - !Dgii   tT!W   %,GWX% % %!& & &
  0 0 0 0 0 *.d9 9 9 9 9 9| 'L
 
 
,  (   %9 %9 %9N+ + +2  8
 
 
 
& -O- - - -^ +N5 5 5
5 5 5
  &  N N N #dgii
 
 
.#5  @@ @ @29 29 29h. . .( ( (@  $,D ,D ,D ,D ,D ,D ,Dr3   r+   c                  h    e Zd ZdZ ed          d             Z ed          d             Zd ZdS )AsyncMappingKernelManagerz'An asynchronous mapping kernel manager.r,   c                    dS )NzAjupyter_server.services.kernels.kernelmanager.ServerKernelManagerr.   r/   s    r1   r2   z7AsyncMappingKernelManager._default_kernel_manager_class  s    RRr3   c                    |j         }t          |          }t          |t                    s t	          j        d| dt          d           |S )z)A validator for the kernel manager class.zKernelManager class 'z' is not a subclass of 'ServerKernelManager'.  Custom KernelManager classes should derive from 'ServerKernelManager' beginning with jupyter-server 2.0 or risk missing functionality.  Continuing...   )
stacklevel)r?   r(   
issubclassServerKernelManagerwarningswarnFutureWarning)r0   rD   km_class_valuekm_classs       r1   _validate_kernel_manager_classz8AsyncMappingKernelManager._validate_kernel_manager_class  sn     "~..($788 	M@ @ @ @     r3   c                x    t           | _        i | _         | j        j        | fi | t	                      | _        dS )z+Initialize an async mapping kernel manager.NrS   rX   s     r1   rV   z"AsyncMappingKernelManager.__init__  rZ   r3   N)	r@  rA  rB  rC  r    r2   r!   rZ  rV   r.   r3   r1   rN  rN    sx        11W#$$S S %$S X$%%  &%- - - - -r3   rN  rK   success_msgrp   rq   t.Callable[..., t.Any]c                      fd}|S )a  Decorate kernel action methods to
    begin emitting jupyter kernel action events.

    Parameters
    ----------
    success_msg: str
        A formattable string that's passed to the message field of
        the emitted event when the action succeeds. You can include
        the kernel_id, kernel_name, or action in the message using
        a formatted string argument,
        e.g. "{kernel_id} succeeded to {action}."

    error_msg: str
        A formattable string that's passed to the message field of
        the emitted event when the action fails. You can include
        the kernel_id, kernel_name, or action in the message using
        a formatted string argument,
        e.g. "{kernel_id} failed to {action}."
    c                @     t                      fd            }|S )Nc                  K   j                             dd           }	  | g|R i | d{V }| j        |d	                    | j        | j        |          d}| j        r
| j        |d<   |                     d|           |S # t          $ rz}| j        |d	t          |          d}| j        r
| j        |d<   t          |t          j
                  r|j        pd }|j        |d
<   ||d<   |                     d|           |d}~ww xY w)rK   _kernelNsuccess)ra   r   action)r   rc  r  r   ra   z;https://events.jupyter.org/jupyter_server/kernel_actions/v1	schema_iddatar  status_coder   )r@  replacer   formatra   emitr   rp   r   r   r   log_messagerg  )
r0   argsrY   rc  outrf  errr   methodr\  s
           r1   wrapped_methodzEemit_kernel_action_event.<locals>.wrap_method.<locals>.wrapped_method  s      _,,Y;;F%"F49$999&99999999#'#3$'&--"&.d>NW] .  	  > 7(,D%		[     
   #'#3$%s88	  > 7(,D% c3=11 &//RC*-/D'"%DK		[     	's   A'B 
DA5DD)r	   )ro  rp  r\  s   ` r1   wrap_methodz-emit_kernel_action_event.<locals>.wrap_method  s;    	v*	 *	 *	 *	 *	 
*	X r3   r.   )r\  rq  s   ` r1   emit_kernel_action_eventrr     s%    *. . . . .` r3   c                  
    e Zd ZU dZ eddd          Z edd          Z eed	          Z	e
dd            Z eg d                              d          Zded<    ee          Z ed          d             Zd Ze ed           fd                        Ze ed           fd                        Ze ed           fd                        Ze ed           fd                        Z xZS )rT  z!A server-specific kernel manager.NTz)The current execution state of the kernel)
allow_nonerF   rK   z2The reason for the last failure against the kernelrQ   zThe last activity on the kernelrq   list[pathlib.Path]c                    t           dz  dz  gS )Nkernel_actionszv1.yamlr"   r/   s    r1   core_event_schema_pathsz+ServerKernelManager.core_event_schema_pathsV  s    *-==	IJJr3   zw
        A list of pathlib.Path objects pointing at to register with
        the kernel manager's eventlogger.
        )r  rF   r4   z	List[str]extra_event_schema_pathsevent_loggerc                   | j         8| j         j         ,t          | j         j         d          r| j         j         j        }nt                      }| j        | j        z   }|D ](}	 |                    |           # t          $ r Y %w xY w|S )zAInitialize the logger and ensure all required events are present.Nrz  )r:   r   rz  r   rx  ry  register_event_schemar   )r0   loggerschemasschema_paths       r1   _default_event_loggerz)ServerKernelManager._default_event_loggerf  s     K#".*N;; / ['4FF !]]F.1NN" 	 	K,,[9999*   s   "A88
BBc                >    | j                             ||           dS )z&Emit an event from the kernel manager.rd  N)rz  rj  )r0   re  rf  s      r1   rj  zServerKernelManager.emit}  s$    >>>>>r3   zKernel {kernel_id} was started.)r\  c                F   K    t                      j        |i | d {V S r9   )rh   rI  r0   rl  rY   rm   s      r1   rI  z ServerKernelManager.start_kernel  s7      
 *UWW)4:6:::::::::r3   z Kernel {kernel_id} was shutdown.c                F   K    t                      j        |i | d {V S r9   )rh   r4  r  s      r1   r4  z#ServerKernelManager.shutdown_kernel  s7      
 -UWW,d=f=========r3   z!Kernel {kernel_id} was restarted.c                F   K    t                      j        |i | d {V S r9   )rh   rJ  r  s      r1   rJ  z"ServerKernelManager.restart_kernel  s7      
 ,UWW+T<V<<<<<<<<<r3   z#Kernel {kernel_id} was interrupted.c                F   K    t                      j        |i | d {V S r9   )rh   interrupt_kernelr  s      r1   r  z$ServerKernelManager.interrupt_kernel  s7      
 .UWW-t>v>>>>>>>>>r3   )rq   ru  )r@  rA  rB  rC  r   r   r   r   r   r   propertyrx  r   tagry  rE  r   rz  r    r  rj  r   rr  rI  r4  rJ  r  rK  rL  s   @r1   rT  rT  H  s?        ++ g$O  O WRRSSSFHX,MNNNM
 K K K XK
 +/$+ + + 
cc      8K((LW^  ,? ? ? 5  ; ; ; ;  Y; 6  > > > >  Y> 7  = = = =  Y= 9  ? ? ? ?  Y? ? ? ? ?r3   rT  )rK   )r\  rp   rq   r]  )BrC  
__future__r   r   r;   pathlibtypingtrU  collectionsr   r   r   	functoolsr   r	   jupyter_client.ioloop.managerr
   !jupyter_client.multikernelmanagerr   r   jupyter_client.sessionr   jupyter_core.pathsr   jupyter_core.utilsr   jupyter_eventsr   jupyter_events.schema_registryr   r   tornador   tornado.concurrentr   tornado.ioloopr   r   	traitletsr   r   r   r   r   r   r   r   r   r    r!   jupyter_serverr#   jupyter_server._tzr$   r%   !jupyter_server.prometheus.metricsr&   jupyter_server.utilsr'   r(   r)   r+   rN  rr  rT  r.   r3   r1   <module>r     s    # " " " " "  				       # # # # # # ( ( ( ( ( ( ( ( $ $ $ $ $ $ $ $ B B B B B B Y Y Y Y Y Y Y Y * * * * * * % % % % % % + + + + + + & & & & & & B B B B B B             % % % % % % 3 3 3 3 3 3 3 3                          6 5 5 5 5 5 0 0 0 0 0 0 0 0 L L L L L L A A A A A A A A A Aj
D j
D j
D j
D j
D- j
D j
D j
D^- - - - - 46M - - -<E E E E EPS? S? S? S? S?2 S? S? S? S? S?r3   