o
    ^i%                     @  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	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mZ ddlmZ zddlZW n eyY   dZY nw e	jdkrcejZndddZddddZG dd dZG dd deZeej dS )z!JupyterLab Server process handler    )annotationsN)Logger)which)Any)genwin32cmd_list	list[str]returnstrc                 C  s   ddl }dt|j| S )zShim for list2cmdline on posix.r   N )shlexjoinmapquote)r   r    r   T/home/ubuntu/hpml_nyu/venv/lib/python3.10/site-packages/jupyterlab_server/process.pylist2cmdline    s   r   commandenvdict[str, str] | Nonec                 C  sv   |pt j}|dpt j}t| |d}| dkr!|s!d} td|d}|s5| dv r-d}t|tdd|   t j|S )	zGet the full path to a command.

    Parameters
    ----------
    command: str
        The command name or path.
    env: dict, optional
        The environment variables, defaults to `os.environ`.
    PATH)pathnodenodejs)r   r   npmzPlease install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org).z%The command was not found or was not zexecutable: %s.)osenvirongetdefpath_which
ValueErrorr   abspath)r   r   r   command_with_pathmsgr   r   r   r   '   s   

r   c                   @  s   e Zd ZU dZe Zded< dZ					d)d*ddZ	d+ddZ
d+ddZejd,ddZd-d d!Zed.d$d%Zd/d'd(ZdS )0ProcesszA wrapper for a child process.zweakref.WeakSet_procsNFcmdr	   loggerLogger | Nonecwd
str | None
kill_eventthreading.Event | Noner   r   quietboolr
   Nonec           	      C  s   t |ttfsd}t||r| rd}t||p|  | _d| _|s.| jdt	| || _
i }|r:tj|d< | jd||d|| _|pKt | _tj|  dS )	a)  Start a subprocess that can be run asynchronously.

        Parameters
        ----------
        cmd: list
            The command to run.
        logger: :class:`~logger.Logger`, optional
            The logger instance.
        cwd: string, optional
            The cwd of the process.
        env: dict, optional
            The environment for the process.
        kill_event: :class:`~threading.Event`, optional
            An event used to kill the process operation.
        quiet: bool, optional
            Whether to suppress output.
        zCommand must be given as a listzProcess aborted z> %sstdout)r*   r   Nr   )
isinstancelisttupler!   is_setget_logr(   
_last_lineinfor   r'   
subprocessDEVNULL_create_processproc	threadingEvent_kill_eventr%   r&   add)	selfr'   r(   r*   r,   r   r.   r$   kwargsr   r   r   __init__H   s"   
zProcess.__init__intc              	   C  s   | j }| du rt|jtj z<z|jdd W n# tj	y=   tj
dkr+tj}ntj}| du r;t|j| Y nw W | tjv rJtj|  | S | tjv rZtj|  w w )z/Terminate the process and return the exit code.Ng       @)timeoutnt)r=   pollr   killpidsignalSIGTERMwaitr:   TimeoutExpirednameSIGBREAKSIGKILLr%   r&   remove)rB   r=   sigr   r   r   	terminatey   s(   



zProcess.terminatec                 C  sR   | j }| j}| du r%| r|   d}t|td | du s|  S )zhWait for the process to finish.

        Returns
        -------
        The process exit code.
        NProcess was aborted      ?)r=   r@   rH   r6   rT   r!   timesleeprB   r=   r,   r$   r   r   r   rM      s   
zProcess.waitr   c                 c  s\    | j }| j}| du r'| r|   d}t|tdV  | du st|  )z.Asynchronously wait for the process to finish.NrU   rV   )	r=   r@   rH   r6   rT   r!   r   rX   ReturnrY   r   r   r   
wait_async   s   zProcess.wait_asyncrC   subprocess.Popen[str]c                 K  sT   t | j}|dtj t|d |d|d< tjdkr!d|d< tj	|fi |S )zCreate the process.stderrr   r   rG   Tshell)
r4   r'   
setdefaultr:   STDOUTr   r   r   rO   Popen)rB   rC   r'   r   r   r   r<      s   

zProcess._create_processclstype[Process]c                 C  s   t | jD ]}|  qdS )z*Clean up the started subprocesses at exit.N)r4   r&   rT   )rb   r=   r   r   r   _cleanup   s   
zProcess._cleanupr   c                 C  s:   t | dr| jdur| jS td| _| jtj | jS )zGet our logger.r(   N
jupyterlab)hasattrr(   logging	getLoggersetLevelINFO)rB   r   r   r   r7      s
   zProcess.get_log)NNNNF)r'   r	   r(   r)   r*   r+   r,   r-   r   r   r.   r/   r
   r0   r
   rE   )r
   r   rC   r   r
   r\   )rb   rc   r
   r0   )r
   r   )__name__
__module____qualname____doc__weakrefWeakSetr&   __annotations___poolrD   rT   rM   r   	coroutiner[   r<   classmethodrd   r7   r   r   r   r   r%   B   s$   
 
1

r%   c                      sN   e Zd ZdZ				dd fddZdddZd ddZd! fddZ  ZS )"WatchHelperz%A process helper for a watch process.Nr'   r	   startup_regexr   r(   r)   r*   r+   r,   r-   r   r   r
   r0   c           	        s   t  j|||||d tdu r| jj| _	 | j d}|s%d}t|t	|
  t||r2nqtj| jdd| _| j  dS )a  Initialize the process helper.

        Parameters
        ----------
        cmd: list
            The command to run.
        startup_regex: string
            The regex to wait for at startup.
        logger: :class:`~logger.Logger`, optional
            The logger instance.
        cwd: string, optional
            The cwd of the process.
        env: dict, optional
            The environment for the process.
        kill_event: callable, optional
            A function to call to check if we should abort.
        )r(   r*   r,   r   N   utf-8zProcess ended improperlyT)targetdaemon)superrD   ptyr=   r2   _stdoutreadlinedecodeRuntimeErrorprintrstriprematchr>   Thread_read_incoming_read_threadstart)	rB   r'   rx   r(   r*   r,   r   liner$   	__class__r   r   rD      s   
	zWatchHelper.__init__rE   c              	   C  s   | j }| du r"tjdkrtt|jtj nt	|jtj z|
  W | tjv r3tj|  |jS | tjv rBtj|  w w )zTerminate the process.NrG   )r=   rH   r   rO   killpggetpgidrJ   rK   rL   rI   rM   r%   r&   rR   
returncode)rB   r=   r   r   r   rT      s   



zWatchHelper.terminatec              
   C  sn   | j  }	 zt|d}W n ty( } z| jd| W Y d}~dS d}~ww |s-dS t|ddd q)z(Run in a thread to read stdout and printry   i   zRead incoming error %sNrz   r1   )end)	r   filenor   readOSErrorr(   debugr   r   )rB   r   bufer   r   r   r     s   
zWatchHelper._read_incomingrC   r   r\   c                   s   d|d< t dur"t  \}}| |d< |d< d|d< t|d| _n#tj|d< tjd	krEt }| j	tj
O  _	||d
< tj|d< d|d< t jdi |S )z"Create the watcher helper process.r   bufsizeNr]   r2   Tstart_new_sessionrbrG   startupinfocreationflagsr^   r   )r~   openptyr   fdopenr   r:   PIPErO   STARTUPINFOdwFlagsSTARTF_USESHOWWINDOWCREATE_NEW_PROCESS_GROUPr}   r<   )rB   rC   masterslaver   r   r   r   r<     s   


zWatchHelper._create_process)NNNN)r'   r	   rx   r   r(   r)   r*   r+   r,   r-   r   r   r
   r0   rk   )r
   r0   rl   )	rm   rn   ro   rp   rD   rT   r   r<   __classcell__r   r   r   r   rw      s    
+
rw   )r   r	   r
   r   )N)r   r   r   r   r
   r   )rp   
__future__r   atexitrg   r   r   rK   r:   sysr>   rW   rq   r   shutilr   r    typingr   tornador   r~   ImportErrorplatformr   r%   rw   registerrd   r   r   r   r   <module>   s:    

 h