o
    bi6%                     @   s  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mZm	Z	m
Z
 	 dZejdkZdedee fddZd	edefd
dZdedefddZ	d(dededeej ddfddZd(dedeej defddZdefddZdefddZdedee	eef  fddZG dd deZ	d)d ee d!edeej de
ee	eeef f fd"d#Z	$d*d ee dejd%ede	eef fd&d'ZdS )+    N)ListOptionalTupleUnionRAY_CONDA_HOMEntconda_env_namereturnc                 C   s~   t s$dtjv sttjv r$td}dtj| ddg}|dd| g7 }ntd}t s0d|| g}n	td}|d| g}|ddg S )	zQ
    Get a list of commands to run to silently activate the given conda env.
    	CONDA_EXEconda.z/../etc/profile.d/conda.shz&&activatesourcez1>&2)_WIN32osenvironr   get_conda_bin_executablepathdirname)r   
conda_pathactivate_conda_envactivate_path r   X/home/ubuntu/.local/lib/python3.10/site-packages/ray/_private/runtime_env/conda_utils.pyget_conda_activate_commands   s   
r   executable_namec                 C   s   t jt}|r6tr-t j|d|  }t j|r|S t j|d|  }t j|r,|S nt j|d|  S d}dt jv rrt jt jd }trkt j|d|  }t j|rY|S t j|d|  }t j|rj|S nt j|| S trx| d S | S )a  
    Return path to the specified executable, assumed to be discoverable within
    a conda installation.

    The conda home directory (expected to contain a 'bin' subdirectory on
    linux) is configurable via the ``RAY_CONDA_HOME`` environment variable. If
    ``RAY_CONDA_HOME`` is unspecified, try the ``CONDA_EXE`` environment
    variable set by activating conda. If neither is specified, this method
    returns `executable_name`.
    z%s.exez%s.batzbin/%sr   r
   z.bat)	r   r   getr   r   r   joinexistsr   )r   
conda_home	candidateconda_bin_dirr   r   r   r   +   s4   
r   conda_env_pathc                 C   s$   t |  }dt|d  S )Nzray-%szutf-8)openreadhashlibsha1encode	hexdigest)r"   conda_env_contentsr   r   r   _get_conda_env_nameT   s   r*   conda_yaml_fileprefixloggerc           
   	   C   s  |du r	t t}td}z
t|dgdd W n ttfy+   td| dt dw t|d	d
dg\}}}t	
||dd d }||v rT|d| d dS |d	dd| d|g}|d|  t||\}}	|dkrtj|r{t| td| d|	 dS )a  
    Given a conda YAML, creates a conda environment containing the required
    dependencies if such a conda environment doesn't already exist.
    Args:
        conda_yaml_file: The path to a conda `environment.yml` file.
        prefix: Directory to install the environment into via
            the `--prefix` option to conda create.  This also becomes the name
            of the conda env; i.e. it can be passed into `conda activate` and
            `conda remove`
    Nr   --helpFthrow_on_errorz$Could not find Conda executable at 'z'. Ensure Conda is installed as per the instructions at https://conda.io/projects/conda/en/latest/user-guide/install/index.html. You can also configure Ray to look for a specific Conda executable by setting the z: environment variable to the path of the Conda executable.envlist--json{envszConda environment z already exists.createz--filez--prefixzCreating conda environment r   z$Failed to install conda environment z
:
Output:
)logging	getLogger__name__r   exec_cmdEnvironmentErrorFileNotFoundError
ValueErrorr   jsonloadsindexinfoexec_cmd_stream_to_loggerr   r   r   shutilrmtreeRuntimeError)
r+   r,   r-   r   _stdoutr5   
create_cmd	exit_codeoutputr   r   r   create_conda_env_if_neededY   sD   


rK   c                 C   sn   |d u r	t t}|d|   td}|dd| ddg}t||\}}|dkr5|d|  d	|  d
S dS )NzDeleting conda environment r   removez-pz--allz-yr   z#Failed to delete conda environment z:
FT)r7   r8   r9   rA   r   rB   debug)r,   r-   r   
delete_cmdrI   rJ   r   r   r   delete_conda_env   s   
rO   c                  C   sd   t d} z
t| dgdd W n ty   td|  dw t| ddd	g\}}}t|d
 }|S )z+
    Get conda env list in full paths.
    r   r.   Fr/   #Could not find Conda executable at r   r1   r2   r3   r5   r   r:   r;   r=   r>   r?   )r   rF   rG   r5   r   r   r   get_conda_env_list   s   rR   c                  C   sZ   t d} z
t| dgdd W n ty   td|  dw t| ddg\}}}t|S )	aO  
    Get `conda info --json` output.

    Returns dict of conda info. See [1] for more details. We mostly care about these
    keys:

    - `conda_prefix`: str The path to the conda installation.
    - `envs`: List[str] absolute paths to conda environments.

    [1] https://github.com/conda/conda/blob/main/conda/cli/main_info.py
    r   r.   Fr/   rP   r   rA   r3   rQ   )r   rF   rG   r   r   r   get_conda_info_json   s   
rS   
conda_infoc                 C   sL   | d }g }| d D ]}||kr| d|f q
| tj||f q
|S )zH
    Gets the conda environments, as a list of (name, path) tuples.
    conda_prefixr5   base)appendr   r   basename)rT   r,   retr1   r   r   r   get_conda_envs   s   rZ   c                   @   s   e Zd ZdS )ShellCommandExceptionN)r9   
__module____qualname__r   r   r   r   r[      s    r[   Tcmdr0   c                 C   sV   t j| t jt jt jdd}| \}}| }|r&|dkr&td|||f |||fS )a  
    Runs a command as a child process.

    A convenience wrapper for running a command from a Python script.

    Note on the return value: A tuple of the exit code,
    standard output and standard error is returned.

    Args:
        cmd: the command to run, as a list of strings
        throw_on_error: if true, raises an Exception if the exit code of the
            program is nonzero
    T)rG   stdinstderruniversal_newlinesr   z-Non-zero exit code: %s

STDOUT:
%s

STDERR:%s)
subprocessPopenPIPEcommunicatewaitr[   )r^   r0   r-   childrG   r`   rI   r   r   r   r:      s    
r:   2   n_linesc                 K   s   d|v rt rddd |jD vrtdtj| fdtjtjd|}g }|j8 t|jj	dD ](}|
 }|d	ur< n| }|sCq0||  || d	 }||  q0W d	   n1 scw   Y  | }|d
|fS )zRuns a command as a child process, streaming output to the logger.

    The last n_lines lines of output are also returned (stdout and stderr).
    r1   PATHc                 S   s   g | ]}|  qS r   )upper).0xr   r   r   
<listcomp>   s    z-exec_cmd_stream_to_logger.<locals>.<listcomp>z*On windows, Popen requires 'PATH' in 'env'T)ra   rG   r`       N
)r   keysr=   rb   rc   rd   STDOUTrG   iterreadlinepollstriprW   rA   rf   r   )r^   r-   ri   kwargsrg   last_n_lineslinerI   r   r   r   rB      s6    rB   )N)TN)rh   ) r%   r>   r7   r   rC   rb   typingr   r   r   r   r   namer   strr   r   r*   LoggerrK   boolrO   r2   rR   dictrS   rZ   	Exceptionr[   intr:   rB   r   r   r   r   <module>   s`    
)
9
"
