a
    ø£BeÒ!  ã                   @   sâ   d 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 zddlZW n eyŽ   dZY n0 ejdkr¢ejZndd„ Z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é    N)Úwhich)ÚgenFÚwin32c                 C   s   ddl }d t|j| ƒ¡S )zShim for list2cmdline on posix.r   Nú )ÚshlexÚjoinÚmapÚquote)Zcmd_listr   © r
   ú\/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyterlab_server/process.pyÚlist2cmdline   s    r   c                 C   sv   |pt j}| d¡pt j}t| |d�}| dkrB|sBd} td|d�}|sj| dv rZd}t|ƒ‚tdd|   ƒ‚t j |¡S )	zËGet 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   ZnpmzÃPlease 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)ÚcommandÚenvr   Zcommand_with_pathÚmsgr
   r
   r   r   $   s    

r   c                   @   sl   e Zd ZU dZe ¡ Zejed< dZddd„Z	dd„ Z
d	d
„ Zejdd„ ƒZdd„ Zedd„ ƒZdd„ ZdS )ÚProcesszA wrapper for a child process.Ú_procsNFc           	      C   s®   t |ttfƒsd}t|ƒ‚|r2| ¡ r2d}t|ƒ‚|p<|  ¡ | _d| _|s`| j dt	|ƒ› �¡ || _
i }|rxtj|d< | jf ||dœ|¤Ž| _|pšt ¡ | _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> Ústdout)Úcwdr   N)Ú
isinstanceÚlistÚtupler   Úis_setÚget_logÚloggerZ
_last_lineÚinfor   ÚcmdÚ
subprocessÚDEVNULLÚ_create_processÚprocÚ	threadingÚEventÚ_kill_eventr   r   Úadd)	Úselfr'   r%   r   Ú
kill_eventr   Úquietr   Úkwargsr
   r
   r   Ú__init__E   s"    
zProcess.__init__c              	   C   s¶   | j }| ¡ du r"t |jtj¡ zrz|jdd� W nF tj	yz   tj
dkrVtj}ntj}| ¡ du rvt |j|¡ Y n0 W | tjv r®tj | ¡ n| tjv r¬tj | ¡ 0 | ¡ S )z/Terminate the process and return the exit code.Ng       @)ÚtimeoutÚnt)r+   Úpollr   ÚkillÚpidÚsignalÚSIGTERMÚwaitr(   ÚTimeoutExpiredÚnameZSIGBREAKÚSIGKILLr   r   Úremove)r0   r+   Úsigr
   r
   r   Ú	terminaten   s     

ÿ
zProcess.terminatec                 C   sH   | j }| j}| ¡ du r@| ¡ r4|  ¡  d}t|ƒ‚t d¡ q|  ¡ S )zhWait for the process to finish.

        Returns
        -------
        The process exit code.
        NúProcess was abortedç      ð?)r+   r.   r7   r#   rB   r   ÚtimeÚsleep©r0   r+   r1   r   r
   r
   r   r<   ˆ   s    zProcess.waitc                 c   sT   | j }| j}| ¡ du rB| ¡ r4|  ¡  d}t|ƒ‚t d¡V  qt |  ¡ ¡‚dS )z.Asynchronously wait for the process to finish.NrC   rD   )	r+   r.   r7   r#   rB   r   r   rF   ÚReturnrG   r
   r
   r   Ú
wait_async™   s    zProcess.wait_asyncc                 K   sX   t | jƒ}| dtj¡ t|d | d¡ƒ|d< tjdkrBd|d< tj	|fi |¤Ž}|S )zCreate the process.Ústderrr   r   r6   TÚshell)
r!   r'   Ú
setdefaultr(   ÚSTDOUTr   r   r   r>   ÚPopen)r0   r3   r'   r+   r
   r
   r   r*   §   s    

zProcess._create_processc                 C   s   t | jƒD ]}| ¡  q
dS )z*Clean up the started subprocesses at exit.N)r!   r   rB   )Úclsr+   r
   r
   r   Ú_cleanup´   s    zProcess._cleanupc                 C   s6   t | dƒr| jr| jS t d¡| _| j tj¡ | jS )zGet our logger.r%   Z
jupyterlab)Úhasattrr%   ÚloggingÚ	getLoggerÚsetLevelÚINFO)r0   r
   r
   r   r$   º   s
    zProcess.get_log)NNNNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚweakrefÚWeakSetr   Ú__annotations__Ú_poolr4   rB   r<   r   Ú	coroutinerI   r*   ÚclassmethodrP   r$   r
   r
   r
   r   r   ?   s   

)

r   c                       s>   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Z‡ fd	d
„Z‡  ZS )ÚWatchHelperz%A process helper for a watch process.Nc           	         s€   t ƒ j|||||d� ts$| jj| _| j ¡  d¡}|sDd}t|ƒ‚t	| 
¡ ƒ t ||¡r$q`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   r1   r   úutf-8zProcess ended improperlyT)ÚtargetÚdaemonN)Úsuperr4   Úptyr+   r   Ú_stdoutÚreadlineÚdecodeÚRuntimeErrorÚprintÚrstripÚreÚmatchr,   ÚThreadÚ_read_incomingZ_read_threadÚstart)	r0   r'   Zstartup_regexr%   r   r1   r   Úliner   ©Ú	__class__r
   r   r4   Ç   s    
zWatchHelper.__init__c              	   C   s†   | j }| ¡ du rDtjdkr4t t |j¡tj¡ nt 	|jtj¡ z"| 
¡  W | tjv r€tj | ¡ n| tjv r~tj | ¡ 0 |jS )zTerminate the process.Nr6   )r+   r7   r   r>   ÚkillpgÚgetpgidr9   r:   r;   r8   r<   r   r   r@   Ú
returncode)r0   r+   r
   r
   r   rB   ê   s    


ÿ
zWatchHelper.terminatec              
   C   sp   | j  ¡ }zt |d¡}W n4 tyN } z| j d|¡ W Y d}~dS d}~0 0 |sXdS t| d¡dd� q
dS )z(Run in a thread to read stdout and printi   zRead incoming error %sNra   r   )Úend)	rf   Úfilenor   ÚreadÚOSErrorr%   Údebugrj   rh   )r0   rx   ÚbufÚer
   r
   r   ro   þ   s    
zWatchHelper._read_incomingc                    s˜   d|d< t r@t  ¡ \}}| |d< |d< d|d< t |d¡| _nFtj|d< tjdkr†t ¡ }| j	tj
O  _	||d	< tj|d
< d|d< tƒ jf i |¤ŽS )z"Create the watcher helper process.r   ÚbufsizerJ   r   TÚstart_new_sessionÚrbr6   ÚstartupinfoÚcreationflagsrK   )re   Úopenptyr   Úfdopenrf   r(   ÚPIPEr>   ZSTARTUPINFOZdwFlagsZSTARTF_USESHOWWINDOWZCREATE_NEW_PROCESS_GROUPrd   r*   )r0   r3   ZmasterZslaver�   rr   r
   r   r*     s    


zWatchHelper._create_process)NNNN)	rV   rW   rX   rY   r4   rB   ro   r*   Ú__classcell__r
   r
   rr   r   r`   Ä   s
   #r`   )N)rY   ÚatexitrR   r   rl   r:   r(   Úsysr,   rE   rZ   Úshutilr   r   Útornador   re   ÚImportErrorÚplatformr   r   r`   ÚregisterrP   r
   r
   r
   r   Ú<module>   s0   


 `