
    Mhb                       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	Z	ddl
Z
ddlmZ ddlmZmZmZmZmZ ddlZddlmZmZmZ ddlmZmZmZmZmZmZmZ ddlm Z m!Z! d	d
l"m#Z# d	dl$m%Z% erddl&m'Z' d	dl(m)Z) ee*ee+e*e,f         f         Z-	 	 	 	 	 	 	 	 	 	 	 d:d;d%Z.	 	 	 d<d=d+Z/	 d>d?d1Z0ej1        ej2        ej3        ej2        ej2        d2Z4d3 d4D             Z5 G d5 d6e           Z6 G d7 d8e!          Z7g d9Z8dS )@zUtilities for connecting to jupyter kernels

The :class:`ConnectionFileMixin` class in this module encapsulates the logic
related to writing and reading connections files.
    )annotationsN)getpass)TYPE_CHECKINGAnyDictUnioncast)jupyter_data_dirjupyter_runtime_dirsecure_write)BoolCaselessStrEnumInstanceIntegerTypeUnicodeobserve)LoggingConfigurableSingletonConfigurable   )	localhost)	_filefind)BlockingKernelClientSession     tcphmac-sha256fname
str | None
shell_portint
iopub_port
stdin_porthb_portcontrol_portipstrkeybytes	transportsignature_schemekernel_namekwargsr   return tuple[str, KernelConnectionInfo]c                l   |st                      }| s+t          j        d          \  }} t          j        |           g }g }t          |dk              t          |dk              z   t          |dk              z   t          |dk              z   t          |dk              z   }|dk    rt          |          D ]l}t          j                    }|                    t          j	        t          j
        d           |                    |df           |                    |           m|D ]E}|                                d         }|                                 |                    |           Fn{d}t          |          D ]i}t          j                            | d|          r)|dz  }t          j                            | d|          )|                    |           |dz  }j|dk    r|                    d          }|dk    r|                    d          }|dk    r|                    d          }|dk    r|                    d          }|dk    r|                    d          }|||||d}||d<   |                                |d	<   ||d
<   |	|d<   |
|d<   |                    |           t'          |           5 }|                    t+          j        |d                     ddd           n# 1 swxY w Y   t/          t0          d          rt          j                            |           }|rrt          j        |          j        }|t0          j        z  }||k    rD	 t          j        ||           n-# t:          $ r }|j        t<          j        k    r	 Y d}~nd}~ww xY w| |fS )a  Generates a JSON config file, including the selection of random ports.

    Parameters
    ----------

    fname : unicode
        The path to the file to write

    shell_port : int, optional
        The port to use for ROUTER (shell) channel.

    iopub_port : int, optional
        The port to use for the SUB channel.

    stdin_port : int, optional
        The port to use for the ROUTER (raw input) channel.

    control_port : int, optional
        The port to use for the ROUTER (control) channel.

    hb_port : int, optional
        The port to use for the heartbeat REP channel.

    ip  : str, optional
        The ip address the kernel will bind to.

    key : str, optional
        The Session key used for message authentication.

    signature_scheme : str, optional
        The scheme used for message authentication.
        This has the form 'digest-hash', where 'digest'
        is the scheme used for digests, and 'hash' is the name of the hash function
        used by the digest scheme.
        Currently, 'hmac' is the only supported digest scheme,
        and 'sha256' is the default hash function.

    kernel_name : str, optional
        The name of the kernel currently connected to.
    z.jsonr   r              r   -)r"   r$   r%   r'   r&   r(   r*   r,   r-   r.      )indentNS_ISVTX) r   tempfilemkstemposcloser#   rangesocket
setsockopt
SOL_SOCKET	SO_LINGERbindappendgetsocknamepathexistspopdecodeupdater   writejsondumpshasattrstatdirnamest_moder7   chmodOSErrorerrnoEPERM)r    r"   r$   r%   r&   r'   r(   r*   r,   r-   r.   r/   fdportssocketsports_needed_sockportNcfgfruntime_dirpermissionsnew_permissionses                             V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_client/connect.pywrite_connection_filerc   &   s   l  [[ $W--	E
 E#%GJ!O
jAo

	
jAo

	 la
 
 	! gl

		  E|$$ 	! 	!A=??DOOF-v/?KKKIIr1gNN4     	 	D##%%a(DJJLLLLL	
 |$$ 	 	A'..B// Q '..B// LLOOOFAAQYYq\\
QYYq\\
QYYq\\
qyy||!||))A,, !  $! !C CICJ C.C$CJJv
 
e		 +	
3q)))***+ + + + + + + + + + + + + + + tY  gooe,, 
	'+..6K)DL8O+--H[/::::   w%+-- 	
 #:s*   	*K??LL/N 
N/N**N/kernel-*.jsonfilenamerD   str | list[str] | Noneprofilec           	     .   |t          j        d|z  d           |dt                      g}t          |t                    r|g}	 t          | |          S # t          $ r Y nw xY wd| v r| }nd| z  }g }|D ]G}|                    t          j        t          j
                            ||                               Hd |D             }|sd	| d
|}t          |          t          |          dk    r|d         S t          |d           d         S )a  find a connection file, and return its absolute path.

    The current working directory and optional search path
    will be searched for the file if it is not given by absolute path.

    If the argument does not match an existing file, it will be interpreted as a
    fileglob, and the matching file in the profile's security dir with
    the latest access time will be used.

    Parameters
    ----------
    filename : str
        The connection file or fileglob to search for.
    path : str or list of strs[optional]
        Paths in which to search for connection files.

    Returns
    -------
    str : The absolute path of the connection file.
    Nz5Jupyter has no profiles. profile=%s has been ignored.r5   )
stacklevel.*z*%s*c                L    g | ]!}t           j                            |          "S  )r:   rD   abspath).0ms     rb   
<listcomp>z(find_connection_file.<locals>.<listcomp>   s&    333arwq!!333r   zCould not find z in r   r   c                4    t          j        |           j        S N)r:   rM   st_atime)r]   s    rb   <lambda>z&find_connection_file.<locals>.<lambda>   s    RWQZZ-@ r   )r*   )warningswarnr   
isinstancer)   r   rQ   extendglobr:   rD   joinlensorted)re   rD   rg   patmatchespmsgs          rb   find_connection_filer      sk   2 CgMZ[	
 	
 	
 	
 |(**+$ v4(((   
 h xG 8 8tya!5!5667777337333G F88888cll	W		qz g#@#@AAA"EEs   A 
A$#A$connection_infostr | KernelConnectionInfo	sshserversshkeytuple[Any, ...]c           	     x   ddl m} t          | t                    rMt	          |           5 }t          j        |                                          } ddd           n# 1 swxY w Y   t          t          t          t          f         |           }|                    d          }|d         |d         |d         |d         |d	         f}|d
         }|                    ||          rd}	nt          d|z            }	t          ||          D ]\  }
}|                    |
|||||	            t!          |          S )a  tunnel connections to a kernel via ssh

    This will open five SSH tunnels from localhost on this machine to the
    ports associated with the kernel.  They can be either direct
    localhost-localhost tunnels, or if an intermediate server is necessary,
    the kernel must be listening on a public IP.

    Parameters
    ----------
    connection_info : dict or str (path)
        Either a connection dict, or the path to a JSON connection file
    sshserver : str
        The ssh sever to use to tunnel to the kernel. Can be a full
        `user@server:port` string. ssh config aliases are respected.
    sshkey : str [optional]
        Path to file containing ssh key to use for authentication.
        Only necessary if your ssh config does not already associate
        a keyfile with the host.

    Returns
    -------

    (shell, iopub, stdin, hb, control) : ints
        The five ports on localhost that have been forwarded to the kernel.
    r   )tunnelN   r"   r$   r%   r&   r'   r(   FzSSH Password for %s: )sshr   ry   r)   openrJ   loadsreadr	   r   r   select_random_portstry_passwordless_sshr   zip
ssh_tunneltuple)r   r   r   r   r]   cflportsrports	remote_ippasswordlprps               rb   tunnel_to_kernelr      s   < /3'' 3/"" 	3a"j22O	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 
d38no	.	.B''**F
<
<
<
9
>F 4I""9f55 @$2Y>??ff%% J JB"b)YIIII==s   'AA"%A")hbshelliopubstdincontrolc                    g | ]}d |z  S )%s_portrm   )ro   channels     rb   rq   rq   :  s    ^^^gi'!^^^r   )r   r   r   r   r   c                     e Zd ZU dZ e            Zded<   dGdZ eddd	
          Z e	d          Z
 eddgdd          Z e            Zded<    eej                  Z edd
          ZdGdZ ed          dHd            Z eddd
          Z eddd
          Z eddd
          Z eddd
          Z eddd
          ZdZded<   edId!            Z ed"          ZdJd$Z dKdLd(Z! e"e#d)*          Z$dMd,Z%dNd-Z&dNd.Z'dNd/Z(dNd0Z)dOd2Z*dPdQd5Z+dRd7Z,dRd8Z-e.dSd;            Z/dTd=Z0	 dPdUdAZ1dPdVdBZ2dPdVdCZ3dPdVdDZ4dPdVdEZ5dPdVdFZ6dS )WConnectionFileMixinz>Mixin for configurable classes that work with connection fileszstr | Unicodedata_dirr0   r)   c                    t                      S rs   )r
   selfs    rb   _data_dir_defaultz%ConnectionFileMixin._data_dir_defaultB  s    !!!r   r   Ta:  JSON file in which to store connection info [default: kernel-<pid>.json]

    This file will contain the IP, ports, and authentication key needed to connect
    clients to this kernel. By default, this file will be created in the security dir
    of the current profile, but can be specified by absolute path.
    )confighelpFr   ipc)default_valuer   r.   zSet the kernel's IP address [default localhost].
        If the IP address is something other than localhost, then
        Consoles on other machines will be able to connect
        to the Kernel, so be careful!c                    | j         dk    r6| j        r-t          j                            | j                  d         dz   S dS t                      S )Nr   r   z-ipcz
kernel-ipc)r,   connection_filer:   rD   splitextr   r   s    rb   _ip_defaultzConnectionFileMixin._ip_default_  sL    >U""# $w''(<==a@6II#|;;r   r(   changer   Nonec                0    |d         dk    r	d| _         d S d S )Nnewrk   z0.0.0.0)r(   )r   r   s     rb   _ip_changedzConnectionFileMixin._ip_changedh  s$    %=CDGGG  r   r   z(set the heartbeat port [default: random]z-set the shell (ROUTER) port [default: random]z*set the iopub (PUB) port [default: random]z-set the stdin (ROUTER) port [default: random]z/set the control (ROUTER) port [default: random]Nzlist[str] | None_random_port_names	list[int]c                *      fdt           D             S )Nc                0    g | ]}t          |          S rm   )getattr)ro   namer   s     rb   rq   z-ConnectionFileMixin.ports.<locals>.<listcomp>z  s#    ;;;d##;;;r   )
port_namesr   s   `rb   rU   zConnectionFileMixin.portsx  s    ;;;;
;;;;r   zjupyter_client.session.Sessionr   c                &    ddl m}  ||           S )Nr   r   parent)sessionr   )r   r   s     rb   _session_defaultz$ConnectionFileMixin._session_default  s'    $$$$$$wd####r   r   boolKernelConnectionInfoc                    | j         | j        | j        | j        | j        | j        | j        d}|r| j                                        |d<   n,|	                    | j        j
        | j        j        d           |S )a  Return the connection info as a dict

        Parameters
        ----------
        session : bool [default: False]
            If True, return our session object will be included in the connection info.
            If False (default), the configuration parameters of our session object will be included,
            rather than the session object itself.

        Returns
        -------
        connect_info : dict
            dictionary of connection information.
        )r,   r(   r"   r$   r%   r&   r'   r   )r-   r*   )r,   r(   r"   r$   r%   r&   r'   r   clonerH   r-   r*   )r   r   infos      rb   get_connection_infoz'ConnectionFileMixin.get_connection_info  s      '///| -
 
  	 #l0022DOO KK(,(E<+    r   z#jupyter_client.BlockingKernelClient)klassr   r   c                    |                                  }|                     |           }|                    |           |S )z-Make a blocking client connected to my kernelr   )r   blocking_classload_connection_info)r   r   bcs      rb   blocking_clientz#ConnectionFileMixin.blocking_client  sB    ''))   --
%%%	r   c                    | j         r;d| _         	 t          j        | j                   dS # t          t
          f$ r Y dS w xY wdS )z}Cleanup connection file *if we wrote it*

        Will not raise if the connection file was already removed somehow.
        FN)_connection_file_writtenr:   remover   rQ   AttributeErrorr   s    rb   cleanup_connection_filez+ConnectionFileMixin.cleanup_connection_file  sf    
 ( 	,1D)	$./////^,   	 	s   + A A c                    | j         dk    rdS | j        D ]3}d| j        |fz  }	 t          j        |           $# t
          $ r Y 0w xY wdS )z#Cleanup ipc files if we wrote them.r   Nz%s-%i)r,   rU   r(   r:   r   rQ   )r   rZ   ipcfiles      rb   cleanup_ipc_filesz%ConnectionFileMixin.cleanup_ipc_files  sw    >U""FJ 	 	D$/G	'""""   		 	s   9
AAc                    | j         dk    rdS | j        dS g | _        t          D ]0}t          | |          dk    r| j                            |           1dS )zRecords which of the ports are randomly assigned.

        Records on first invocation, if the transport is tcp.
        Does nothing on later invocations.r   Nr   )r,   r   r   r   rB   r   r   s     rb   _record_random_port_namesz-ConnectionFileMixin._record_random_port_names  sr     >U""F".F"$ 	5 	5DtT""a'''..t444	5 	5r   c                v    | j         sdS | j         D ]}t          | |d           |                                  dS )zForgets randomly assigned port numbers and cleans up the connection file.

        Does nothing if no port numbers have been randomly assigned.
        In particular, does nothing unless the transport is tcp.
        Nr   )r   setattrr   r   s     rb   cleanup_random_portsz(ConnectionFileMixin.cleanup_random_ports  sS     & 	F+ 	# 	#DD$""""$$&&&&&r   r/   c                   | j         r&t          j                            | j                  rdS t          | j        f| j        | j        | j        j	        | j
        | j        | j        | j        | j        | j        j        | j        d
|\  | _        }|                                  t$          D ]}t'          | |||                    d| _         dS )z;Write connection info to JSON dict in self.connection_file.N)
r,   r(   r*   r%   r$   r"   r&   r'   r-   r.   T)r   r:   rD   rE   r   rc   r,   r(   r   r*   r%   r$   r"   r&   r'   r-   r.   r   r   r   )r   r/   r\   r   s       rb   rc   z)ConnectionFileMixin.write_connection_file  s    ( 	RW^^D<P-Q-Q 	F$9 %
nw L*!\:(%
 %
 %
 %
!c 	&&((( 	+ 	+DD$D	****(,%%%r   r   r!   c                    || j         }| j                            d|           t          |          5 }t	          j        |          }ddd           n# 1 swxY w Y   |                     |           dS )zLoad connection info from JSON dict in self.connection_file.

        Parameters
        ----------
        connection_file: unicode, optional
            Path to connection file to load.
            If unspecified, use self.connection_file
        NzLoading connection file %s)r   logdebugr   rJ   loadr   )r   r   r]   r   s       rb   load_connection_filez(ConnectionFileMixin.load_connection_file	  s     ""2O3_EEE/"" 	 a9Q<<D	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 !!$'''''s   AAAr   c                   |                     d| j                  | _        |                     d|                                           | _        |                                  t
          D ]1}t          | |          dk    r||v rt          | |||                    2d|v rT|d         }t          |t                    r|
                                }t          |t                    sJ || j        _        d|v r|d         | j        _        dS dS )aQ  Load connection info from a dict containing connection info.

        Typically this data comes from a connection file
        and is called by load_connection_file.

        Parameters
        ----------
        info: dict
            Dictionary containing connection_info.
            See the connection_file spec for details.
        r,   r(   r   r*   r-   N)getr,   r   r(   r   r   r   r   ry   r)   encoder+   r   r*   r-   )r   r   r   r*   s       rb   r   z(ConnectionFileMixin.load_connection_info  s    +t~>>((4!1!1!3!344&&((( 	0 	0DtT""a''DDLLdDJ///D==u+C#s## #jjllc5)))))"DL%%,01C,DDL))) &%r   c                   d}t           j                            | j                  rt	          | j                  5 }t          j        |          }ddd           n# 1 swxY w Y   |d                                         |d<   |                     ||          s!t          j	        | j                   d| _
        nd}|sDt          D ]}t          | |d           |                     |           |                                  |                                 }|                     ||          sd}t!          |          dS )a  Reconciles the connection information returned from the Provisioner.

        Because some provisioners (like derivations of LocalProvisioner) may have already
        written the connection file, this method needs to ensure that, if the connection
        file exists, its contents match that of what was returned by the provisioner.  If
        the file does exist and its contents do not match, the file will be replaced with
        the provisioner information (which is considered the truth).

        If the file does not exist, the connection information in 'info' is loaded into the
        KernelManager and written to the file.
        FNr*   Tr   zwKernelManager's connection information already exists and does not match the expected values returned from provisioner!)r:   rD   rE   r   r   rJ   r   r   _equal_connectionsr   r   r   r   r   rc   r   
ValueError)r   r   file_existsr]   	file_infor   km_infor   s           rb   _reconcile_connection_infoz.ConnectionFileMixin._reconcile_connection_info8  s     "7>>$.// 
	#d*++ )q IaLL	) ) ) ) ) ) ) ) ) ) ) ) ) ) )  )/6688Ie**4;; #	$.///05--" 	) # ' 'dA&&&&%%d+++&&((( **,,&&tW55 	"A  S//!	" 	"s   AA #A conn1conn2c                F     g d}t           fd|D                       S )z]Compares pertinent keys of connection info data. Returns True if equivalent, False otherwise.)	r*   r(   r%   r$   r"   r'   r&   r,   r-   c              3  p   K   | ]0}                     |                               |          k    V  1d S rs   )r   )ro   r*   r   r   s     rb   	<genexpr>z9ConnectionFileMixin._equal_connections.<locals>.<genexpr>v  s<      NN599S>>UYYs^^3NNNNNNr   )all)r   r   pertinent_keyss   `` rb   r   z&ConnectionFileMixin._equal_connectionsf  s=    

 

 

 NNNNN~NNNNNNr   r   c                r    | j         }| j        }t          | d|z            }|dk    rd||fz  S | d| d| S )z&Make a ZeroMQ URL for a given channel.r   r   ztcp://%s:%iz://r4   )r,   r(   r   )r   r   r,   r(   rZ   s        rb   	_make_urlzConnectionFileMixin._make_url|  sZ    N	WtY011 B:--//B/////r   identitybytes | Nonezmq.sugar.socket.Socketc                    |                      |          }t          |         }| j                            d|           | j                            |          }d|_        |r||_        |                    |           |S )z1Create a zmq Socket and connect it to the kernel.zConnecting to: %si  )	r   channel_socket_typesr   r   contextr=   lingerr   connect)r   r   r   urlsocket_typerY   s         rb   _create_connected_socketz,ConnectionFileMixin._create_connected_socket  sx     nnW%%*73*C000|"";// 	%$DMSr   c                t    |                      d|          }|                    t          j        d           |S )z0return zmq Socket connected to the IOPub channelr   r   r   )r  r>   zmq	SUBSCRIBE)r   r   rY   s      rb   connect_iopubz!ConnectionFileMixin.connect_iopub  s5    ,,Wx,HHs+++r   c                0    |                      d|          S )z0return zmq Socket connected to the Shell channelr   r  r  r   r   s     rb   connect_shellz!ConnectionFileMixin.connect_shell      ,,Wx,HHHr   c                0    |                      d|          S )z0return zmq Socket connected to the StdIn channelr   r  r	  r
  s     rb   connect_stdinz!ConnectionFileMixin.connect_stdin  r  r   c                0    |                      d|          S )z4return zmq Socket connected to the Heartbeat channelr   r  r	  r
  s     rb   
connect_hbzConnectionFileMixin.connect_hb  s    ,,TH,EEEr   c                0    |                      d|          S )z2return zmq Socket connected to the Control channelr   r  r	  r
  s     rb   connect_controlz#ConnectionFileMixin.connect_control  s    ,,Y,JJJr   )r0   r)   )r   r   r0   r   )r0   r   )r0   r   )F)r   r   r0   r   )r0   r   )r0   r   r/   r   r0   r   rs   )r   r!   r0   r   )r   r   r0   r   )r   r   r   r   r0   r   )r   r)   r0   r)   )r   r)   r   r   r0   r   )r   r   r0   r   )7__name__
__module____qualname____doc__r   r   __annotations__r   r   r   r   r   r,   r.   r   r  Contextr   r(   r   r   r   r   r&   r"   r$   r%   r'   r   propertyrU   r   r   r   r   objectr   r   r   r   r   r   rc   r   r   r   staticmethodr   r   r  r  r  r  r  r  rm   r   rb   r   r   =  s        HH%giiH''''" " " " g
	 	 	O  $tE{{eDQQQI!(K****hs{##G	)
 
 
B    WT]]      ]  ga+UVVVG4.]^^^J4.Z[[[J4.]^^^J71T0abbbL ,0////< < < X< h788G$ $ $ $$ $ $ $ $N T6[\\\N      	 	 	 	5 5 5 5 ' ' ' '- - - -4( ( ( ( ( E E E E>," ," ," ,"\ O O O \O*	0 	0 	0 	0 6:        I I I I II I I I IF F F F FK K K K K K Kr   r   c                  4     e Zd ZdZd fdZdd
ZddZ xZS )LocalPortCachea  
    Used to keep track of local ports in order to prevent race conditions that
    can occur between port acquisition and usage by the kernel.  All locally-
    provisioned kernels should use this mechanism to limit the possibility of
    race conditions.  Note that this does not preclude other applications from
    acquiring a cached but unused port, thereby re-introducing the issue this
    class is attempting to resolve (minimize).
    See: https://github.com/jupyter/jupyter_client/issues/487
    r/   r   r0   r   c                `     t                      j        di | t                      | _        d S )Nrm   )super__init__setcurrently_used_ports)r   r/   	__class__s     rb   r!  zLocalPortCache.__init__  s2    ""6""".1ee!!!r   r(   r)   r#   c                V   	 t          j                     }|                    t           j        t           j        d           |                    |df           |                                d         }|                                 || j        vr| j                            |           |S )NTr3   r   r   )	r=   r>   r?   r@   rA   rC   r;   r#  add)r   r(   tmp_sockrZ   s       rb   find_available_portz"LocalPortCache.find_available_port  s    	}H 163CYOOOMM2q'"""''))!,DNN 4444)--d333	r   rZ   c                P    || j         v r| j                             |           d S d S rs   )r#  r   )r   rZ   s     rb   return_portzLocalPortCache.return_port  s5    4,,,%,,T22222 -,r   r  )r(   r)   r0   r#   )rZ   r#   r0   r   )r  r  r  r  r!  r(  r*  __classcell__)r$  s   @rb   r  r    so         4 4 4 4 4 4   3 3 3 3 3 3 3 3r   r  )rc   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   r0   r1   )rd   NN)re   r)   rD   rf   rg   r!   r0   r)   rs   )r   r   r   r)   r   r!   r0   r   )9r  
__future__r   rR   r{   rJ   r:   r=   rM   r8   rw   r   typingr   r   r   r   r	   r  jupyter_core.pathsr
   r   r   	traitletsr   r   r   r   r   r   r   traitlets.configr   r   localinterfacesr   utilsr   jupyter_clientr   r   r   r)   r#   r+   r   rc   r   r   REQDEALERSUBr   r   r   r  __all__rm   r   rb   <module>r8     s    # " " " " "    				           8 8 8 8 8 8 8 8 8 8 8 8 8 8 



 R R R R R R R R R R V V V V V V V V V V V V V V V V V V G G G G G G G G & & & & & &       !333333       CsC!778  )H H H H HX $#'=F =F =F =F =FF : : : : :D 'ZWZz   _^1]^^^
mK mK mK mK mK- mK mK mK`3 3 3 3 3* 3 3 3D  r   