
    &`iL                     d   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mZmZmZ d dlZd dlZd dlmZ d dlmZ d dlmZmZmZ d dlZdZd	Zd
dgZ G d de          Z G d de          Z  G d de          Z! G d d          Z" G d d          Z# G d d          Z$	 	 d;de$deee%                  de%de$fdZ&	 d<de$de%de$fdZ'de$fd Z(	 	 d=de$d"eeee%e)f                           d#e)fd$Z*de$d%e"fd&Z+d>d(ee%         fd)Z,	 d?d+e#d%e"d,e%dee%         fd-Z-de$d+e#d%e"fd.Z.de$d%e"fd/Z/de$d0ee#         d%e"fd1Z0de$d0ee#         d%e"fd2Z1d3e%deee%         e%e%ee%         ee%         f         fd4Z2	 	 	 	 	 d@d5ee%         d6ee%         d7ee%         d8ee%         d9ee%         f
d:Z3dS )A    N)ThreadPoolExecutor)contextmanager)ListOptionalSequenceTuple)
cli_logger)_get_node_provider)NODE_KIND_HEADNODE_KIND_WORKERTAG_RAY_NODE_KIND   ubuntu~/ray_bootstrap_key.pemz%~/.ssh/ray-autoscaler_2_us-west-2.pemc                       e Zd ZdS )CommandFailedN__name__
__module____qualname__     x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/autoscaler/_private/cluster_dump.pyr   r              Dr   r   c                       e Zd ZdS )LocalCommandFailedNr   r   r   r   r   r      r   r   r   c                       e Zd ZdS )RemoteCommandFailedNr   r   r   r   r   r   #   r   r   r   c                   d    e Zd Z	 	 	 	 	 	 d
dedededededeeeeef                           fd	ZdS )GetParametersTNlogsdebug_statepip	processesprocesses_verboseprocesses_listc                 Z    || _         || _        || _        || _        || _        || _        d S N)r!   r"   r#   r$   r%   r&   )selfr!   r"   r#   r$   r%   r&   s          r   __init__zGetParameters.__init__(   s7     	&"!2,r   )TTTTTN)	r   r   r   boolr   r   r   strr*   r   r   r   r    r    '   s          "&;?- -- - 	-
 -  - !eCI&6!78- - - - - -r   r    c                   D    e Zd ZdZ	 	 	 	 ddededed	ee         d
ef
dZdS )NodezNode (as in "machine")r   r   NFhostssh_userssh_keydocker_containeris_headc                 L    || _         || _        || _        || _        || _        d S r(   )r/   r0   r1   r2   r3   )r)   r/   r0   r1   r2   r3   s         r   r*   zNode.__init__<   s,     	  0r   )r   r   NF)r   r   r   __doc__r,   r   r+   r*   r   r   r   r.   r.   9   su          
 !0*.   	
 #3-      r   r.   c                       e Zd ZdZddee         fdZed             Zd Z	d Z
d Zd	 Zeddedee         fd            ZdS )Archivea  Archive object to collect and compress files into a single file.

    Objects of this class can be passed around to different data collection
    functions. These functions can use the :meth:`subdir` method to add
    files to a sub directory of the archive.

    Nfilec                     |pt          j        dd          d         | _        d | _        t	          j                    | _        d S )N	ray_logs_.tar.gzprefixsuffix   )tempfilemkstempr8   tar	threadingLock_lock)r)   r8   s     r   r*   zArchive.__init__T   s>    UH,K	RRRSTU	^%%


r   c                 *    t          | j                  S r(   )r+   rB   r)   s    r   is_openzArchive.is_openY   s    DH~~r   c                 D    t          j        | j        d          | _        d S )Nzw:gz)tarfileopenr8   rB   rG   s    r   rK   zArchive.open]   s    <	622r   c                 F    | j                                          d | _         d S r(   )rB   closerG   s    r   rM   zArchive.close`   s    r   c                 .    |                                   | S r(   )rK   rG   s    r   	__enter__zArchive.__enter__d   s    		r   c                 .    |                                   d S r(   )rM   )r)   exc_typeexc_valexc_tbs       r   __exit__zArchive.__exit__h   s    

r   /subdirrootc              #       K   t           j                                       G  fdd          } |            V  dS )a  Open a context to add files to the archive.

        Example:

            .. code-block:: python

                with Archive("file.tar.gz") as archive:
                    with archive.subdir("logfiles", root="/tmp/logs") as sd:
                        # Will be added as `logfiles/nested/file.txt`
                        sd.add("/tmp/logs/nested/file.txt")

        Args:
            subdir: Subdir to which to add files to. Calling the
                ``add(path)`` command will place files into the ``subdir``
                directory of the archive.
            root: Root path. Files without an explicit ``arcname``
                will be named relatively to this path.

        Yields:
            A context object that can be used to add files to the archive.
        c                   F    e Zd Zeddedee         f fd            ZdS ) Archive.subdir.<locals>._ContextNpatharcnamec                 b   t           j                            |           } |p=t           j                            t           j                            |                     }j                                         j                            | |           j        	                                 d S )Nr\   )
osr[   abspathjoinrelpathrE   acquirerB   addrelease)r[   r\   rW   r)   rV   s     r   rd   z$Archive.subdir.<locals>._Context.add   s    wt,,!VRW\\&"'//$PT:U:U%V%V
""$$$T7333
""$$$$$r   r(   )r   r   r   staticmethodr,   r   rd   )rW   r)   rV   s   r   _ContextrZ      s^        % %# % % % % % % % % \% % %r   rg   N)r_   r[   r`   )r)   rV   rW   rg   s   ``` r   rV   zArchive.subdirk   st      . wt$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% hjjr   r(   )rU   )r   r   r   r5   r   r,   r*   propertyrH   rK   rM   rO   rT   r   rV   r   r   r   r7   r7   K   s         & &Xc] & & & &
   X3 3 3       " "S " " " " ^" " "r   r7   /tmp/ray/session_latestarchiveexcludesession_log_dirreturnc                 D  	 | j         s|                                  |pg }t          j                            t          j                            |          d          }|                     d|          5 }t          j        |          D ]}\  }}}|D ]t}t          j                            ||          }t          j                            ||          	t          	fd|D                       r_|
                    |           u~	 ddd           n# 1 swxY w Y   | S )a  Copy local log files into an archive.

    Args:
        archive: Archive object to add log files to.
        exclude (Sequence[str]): Sequence of regex patterns. Files that match
            any of these patterns will not be included in the archive.
        session_dir: Path to the Ray session files. Defaults to
            ``/tmp/ray/session_latest``

    Returns:
        Open archive object.

    r!   rW   )startc              3   B   K   | ]}t          j        |          V  d S r(   )rematch).0patternrel_paths     r   	<genexpr>z%get_local_ray_logs.<locals>.<genexpr>   s/      JJwrx22JJJJJJr   N)rH   rK   r_   r[   ra   
expanduserrV   walkrb   anyrd   )
rj   rk   rl   sdrW   dirsfilesr8   	file_pathrv   s
            @r   get_local_ray_logsr      s[   $ ? mGgll27#5#5o#F#FOOO	_	5	5 "!#!9!9 	" 	"D$ " "GLLt44	7??9O?LLJJJJ'JJJJJ y!!!!"	"" " " " " " " " " " " " " " " Ns   5BDDDsession_dirc                    | j         s|                                  t          j                            |          }t          j                            |d          }t          j                            |          st          d          |                     d|          5 }|	                    |           ddd           n# 1 swxY w Y   | S )zCopy local log files into an archive.

    Args:
        archive: Archive object to add log files to.
        session_dir: Path to the Ray session files. Defaults to
            ``/tmp/ray/session_latest``

    Returns:
        Open archive object.

    zlogs/debug_state.txtz No `debug_state.txt` file found. ro   N)
rH   rK   r_   r[   rx   ra   existsr   rV   rd   )rj   r   debug_state_filer{   s       r   get_local_debug_stater      s     ? '$$[11Kw||K1GHH7>>*++ E !CDDD		-	- !
   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Ns    CC	Cc                    | j         s|                                  	 ddlm} n# t          $ r	 ddlm} Y nw xY wt          j        d          5 }|                                D ]}|                    |dg           |	                                 | 
                    d          5 }|                    |j        d           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   | S )zGet currently installed pip packages and write into an archive.

    Args:
        archive: Archive object to add meta files to.

    Returns:
        Open archive object.
    r   )freezewt
r   zpip_packages.txtN)rH   rK   pip._internal.operationsr   ImportErrorpip.operationsr@   NamedTemporaryFile
writelinesflushrV   rd   name)rj   r   fpliner{   s        r   get_local_pip_packagesr      s    ? *3333333 * * *))))))))* 
	$T	*	* 0bMMOO 	( 	(DMM4,''''



^^B 	02FF27.///	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NsC   $ 77AC%&CC%C	C%C	C%%C),C)Fr$   verbosec           	      Z   |sddl m} |}g }t          j        g d          D ]}	 |                                5  d                    |                                          }|                    |r|n#|                    dd          d         dd         |	                                |j
        |                                d	|                                f           ddd           n# 1 swxY w Y   # t          $ r}t          |          |d}~ww xY wi }|D ]E\  }	}|D ]=\  }
}|r	|	d
         }nt          j        |          }|
|v r|	d         |vr|	||	d         <   >Ft!          j        d          5 }|                                D ]+}|                    t)          j        |          dg           ,|                                 |                     d          5 }|                    |j	        d           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   | S )a7  Get the status of all the relevant ray processes.
    Args:
        archive: Archive object to add process info files to.
        processes: List of processes to get information on. The first
            element of the tuple is a string to filter by, and the second
            element is a boolean indicating if we should filter by command
            name (True) or command line including parameters (False)
        verbose: If True, show entire executable command line.
            If False, show just the first term.
    Returns:
        Open archive object.
    r   )RAY_PROCESSES)pidr   cmdlinestatus z--r?   N)
executabler   r   r   r   r   r   r   metazprocess_info.txt)!ray.autoscaler._private.constantsr   psutilprocess_iteroneshotra   r   appendsplitr   r   r   	Exceptionr   
subprocesslist2cmdliner@   r   valuesr   yamldumpr   rV   rd   )rj   r$   r   r   process_infosprocessr   excrelevant_processesprocess_dictkeywordfilter_by_cmdcorpusr   r   r{   s                   r   get_local_ray_processesr      s<   "  "CCCCCC!	M&'K'K'KLL 3 3	3""  ((7??#4#455$$  '+@''!(tQ!7!7!:3B3!?$+LLNN#*;&-nn&6&6   ))
                  	3 	3 	3$S))s2	3 !. G Gg&/ 	G 	G"G] :%f-#099&  \%%8@R%R%R:F"<#67	G 
	$T	*	* 0b&--// 	3 	3DMM49T??D12222



^^F## 	0rFF27.///	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Nsr   C7B%C+C7+C/	/C72C/	3C77
DDD7A*H !H	=H 	H	H H	H  H$'H$
parametersc                 t   | j         s|                                  |j        r=	 t          |            n+# t          $ r}t          j        |           Y d}~nd}~ww xY w|j        r=	 t          |            n+# t          $ r}t          j        |           Y d}~nd}~ww xY w|j	        r=	 t          |            n+# t          $ r}t          j        |           Y d}~nd}~ww xY w|j        rI	 t          | |j        |j                   n+# t          $ r}t          j        |           Y d}~nd}~ww xY w| S )a'  Get all local data.

    Gets:
        - The Ray logs of the latest session
        - The currently installed pip packages

    Args:
        archive: Archive object to add meta files to.
        parameters: Parameters (settings) for getting data.

    Returns:
        Open archive object.
    )rj   N)rj   r$   r   )rH   rK   r!   r   r   r	   errorr"   r   r#   r   r$   r   r&   r%   )rj   r   r   s      r   get_all_local_datar   6  s    ?  "	"w/////! 	" 	" 	"S!!!!!!!!	" "	"!'22222! 	" 	" 	"S!!!!!!!!	"~ "	""733333! 	" 	" 	"S!!!!!!!!	" "	"#$3"4    
 " 	" 	" 	"S!!!!!!!!	" Ns\   5 
AAA(A9 9
B!BB!,B= =
C%C  C%0D 
D5D00D5'itemsc                 8    | d                     |            | S )Nr   )ra   )r   quotess     r   _wrapr   h  s"    /chhuoo/v///r   rayremote_nodescript_pathc           	         ddddd| j         | j         d| j         g}| j        r|dd| j        gz  }|d	d
g}||j        rdgndgz  }||j        rdgndgz  }||j        rdgndgz  }||j        rdgndgz  }|j        r||j        rdgndgz  }|ddt          |d          gz  }| j
        sdnd}t          j        d| j                    t          j        d| d| j         dd          d          }t          |d!          5 }	 t!          j        ||t$          j        "           n=# t           j        $ r+}t+          d#d$                    |                     |d%}~ww xY w	 d%d%d%           n# 1 swxY w Y   |S )&a  Create an archive containing logs on a remote node and transfer.

    This will call ``ray local-dump --stream`` on the remote
    node. The resulting file will be saved locally in a temporary file and
    returned.

    Args:
        remote_node: Remote node to gather archive from.
        script_path: Path to this script on the remote node.
        parameters: Parameters (settings) for getting data.

    Returns:
        Path to a temporary file containing the node's collected data.

    sshz-o StrictHostKeyChecking=noz-o UserKnownHostsFile=/dev/nullz-o LogLevel=ERRORz-i@dockerexecz
local-dumpz--streamz--logsz	--no-logsz--debug-statez--no-debug-statez--pipz--no-pipz--processesz--no-processesz--processes-verbosez--no-proccesses-verbosez	/bin/bashz-c")r   nodeheadz"Collecting data from remote node: ray__r;   r<   r?   wb)stdoutstderrz(Gathering logs from remote node failed: r   N)r1   r0   r/   r2   r!   r"   r#   r$   r%   r   r3   r	   printr@   rA   rK   r   
check_callsysr   CalledProcessErrorr   ra   )	r   r   r   cmdcollect_cmdcattmpr   r   s	            r   'create_and_get_archive_from_remote_noder   l  sc   & 	%)44+"244C # 
(
 	
 j9KCH::{mCK
(>XO$$EWDXXK
@G99ZL@Kj&:RM??AQ@RRK 
+-"##+,	
 Ku[===>>C#+
7&&CL+:JLLMMM

"B"B"B{/?"B"B"B9
U
U
UVW
XC	c4 B	!#bDDDDD, 	 	 	%J388C==JJ 	 E               Js6   E2!D('E2(E"7&EE""E22E69E6c           	      P   t          ||          }| j        s|                                  |j        sdnd}|                     dt
          j                            |                    5 }|                    |d| d|j	         d           d	d	d	           n# 1 swxY w Y   | S )
a%  Create and get data from remote node and add to local archive.

    Args:
        archive: Archive object to add remote data to.
        remote_node: Remote node to gather archive from.
        parameters: Parameters (settings) for getting data.

    Returns:
        Open archive object.
    r   r   r   ro   r   r   r;   r^   N)
r   rH   rK   r3   rV   r_   r[   dirnamerd   r/   )rj   r   r   r   r   r{   s         r   +create_and_add_remote_data_to_local_archiver     s     2+z
J
JC? #+
7&&C	!5!5	6	6 D"
sB3BB)9BBBCCCD D D D D D D D D D D D D D D Ns   +$BB"Bc                    t                      5 }t          ||           ddd           n# 1 swxY w Y   | j        s|                                  |                     dt
          j                            |j                            5 }|	                    |j        d           ddd           n# 1 swxY w Y   t          j
        |j                   | S )zCreate and get data from this node and add to archive.

    Args:
        archive: Archive object to add remote data to.
        parameters: Parameters (settings) for getting data.

    Returns:
        Open archive object.
    Nr   ro   zlocal_node.tar.gzr^   )r7   r   rH   rK   rV   r_   r[   r   r8   rd   remove)rj   r   local_data_archiver{   s       r   *create_and_add_local_data_to_local_archiver     sK    
 ;(-z:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ? 	1C1H!I!I	J	J Eb
!&0CDDDE E E E E E E E E E E E E E E I %&&&Ns   ,00B44B8;B8remote_nodesc                     | j         s|                                  t          t                    5 }|D ] }|                    t
          | ||           !	 ddd           n# 1 swxY w Y   | S )ag  Create an archive combining data from the remote nodes.

    This will parallelize calls to get data from remote nodes.

    Args:
        archive: Archive object to add remote data to.
        remote_nodes (Sequence[Node]): Sequence of remote nodes.
        parameters: Parameters (settings) for getting data.

    Returns:
        Open archive object.

    )max_workers)rj   r   r   N)rH   rK   r   MAX_PARALLEL_SSH_WORKERSsubmitr   )rj   r   r   executorr   s        r   create_archive_for_remote_nodesr     s      ? 	(@	A	A	A X' 	 	KOO;'%	     	               Ns   $A""A&)A&c                 "   | j         s|                                  	 t          | |           n+# t          $ r}t	          j        |           Y d}~nd}~ww xY wt          | ||           t	          j        dt          |           d           | S )aj  Create an archive combining data from the local and remote nodes.

    This will parallelize calls to get data from remote nodes.

    Args:
        archive: Archive object to add data to.
        remote_nodes (Sequence[Node]): Sequence of remote nodes.
        parameters: Parameters (settings) for getting data.

    Returns:
        Open archive object.

    Nz#Collected data from local node and z remote nodes.)	rH   rK   r   r   r	   r   r   r   len)rj   r   r   r   s       r   )create_archive_for_local_and_remote_nodesr     s      ? 27JGGGG    $G\:FFFSc,.?.?SSS   Ns   . 
AAAcluster_configc                    ddl m} t          j        d|             t          j                            |           } t          j        t          |           
                                          } ||d          }t          |d         |d                                       t          t          i          }                    t          t          i          }fd||z   D             }|d	         d
         }|d	         d         }d}|                    dd          }	|	r|	                    dd          }|                    dd          }
|||||
fS )a[  Get information from Ray cluster config.

    Return list of host IPs, ssh user, ssh key file, and optional docker
    container.

    Args:
        cluster_config: Path to ray cluster config.

    Returns:
        Tuple of list of host IPs, ssh user name, ssh key file path,
            optional docker container name, optional cluster name.
    r   )_bootstrap_configz6Retrieving cluster information from ray cluster file: T)no_config_cacheprovidercluster_namec                 :    g | ]}                     |          S r   )external_ip)rt   r   r   s     r   
<listcomp>z4get_info_from_ray_cluster_config.<locals>.<listcomp>@  s'    NNNDX!!$''NNNr   authr0   ssh_private_keyNr   container_name) ray.autoscaler._private.commandsr   r	   r   r_   r[   rx   r   	safe_loadrK   readr
   non_terminated_nodesr   r   r   get)r   r   config
head_nodesworker_nodeshostsr0   r1   r   docker_configr   r   s              @r    get_info_from_ray_cluster_configr   "  sh    CBBBBBU^UU   W''77N^D00557788Fvt<<<F!&"4f^6LMMH..0A>/RSSJ002CEU1VWWLNNNNJ4MNNNEf~j)HVn./GFJJx..M ;""#3T::::nd33L(GV\99r   clusterr/   r0   r1   r   c                    |s[| sYt           j                            d          }t           j                            |          r|} t	          j        d|  d           n!| rt           j                            |           } d}| rOt          |           \  }}}	}
}|p|}|p|	}|p|
}|r|                    d          n|}|st          d|            n'|r|                    d          }nt          d          |st          }t	          j        d| d	           |sdt          D ]\}t           j                            |          }t           j                            |          r|}t	          j        d
| d            n]| |||||fS )ziParse command line arguments.

    Note: This returns a list of hosts, not a comma separated string!
    z~/ray_bootstrap_config.yamlz Detected cluster config file at z@. If this is incorrect, specify with `ray cluster-dump <config>`N,z6Invalid cluster file or cluster has no running nodes: z<You need to either specify a `<cluster_config>` or `--host`.zUsing default SSH user `z9`. If this is incorrect, specify with `--ssh-user <user>`zAuto detected SSH key file: z6. If this is incorrect, specify with `--ssh-key <key>`)r_   r[   rx   r   r	   warningr   r   r   DEFAULT_SSH_USERDEFAULT_SSH_KEYS)r   r/   r0   r1   r   bootstrap_configr   hukdr   cand_keycand_key_files                 r   _info_from_paramsr
  N  s     
. 
.7--.KLL7>>*++ 	&G/7 / / /  
 
 .'$$W--L 
#CG#L#L 1aL=q,Q1#'.

3Q 	$VWVV  	 
 


3 J
 
 	
  
#Fx F F F	
 	
 	

  	( 	 	HG..x88Mw~~m,, '"L7 L L L    E8WflBBr   )Nri   )ri   )NF)r   )r   )NNNNN)4r_   rr   r   r   rJ   r@   rC   concurrent.futuresr   
contextlibr   typingr   r   r   r   r   r   "ray.autoscaler._private.cli_loggerr	   !ray.autoscaler._private.providersr
   ray.autoscaler.tagsr   r   r   r   r   r  r  RuntimeErrorr   r   r   r    r.   r7   r,   r   r   r   r+   r   r   r   r   r   r   r   r   r   r
  r   r   r   <module>r     s   				 				     



       1 1 1 1 1 1 % % % % % % 2 2 2 2 2 2 2 2 2 2 2 2  



 9 9 9 9 9 9 @ @ @ @ @ @ S S S S S S S S S S   -/VW 	 	 	 	 	L 	 	 		 	 	 	 	 	 	 		 	 	 	 	- 	 	 	- - - - - - - -$       $C C C C C C C CZ (,4# ##hsm$# # 	# # # #N *C #&   :G    < 37> >>U39-./> > > > >B* *] * * * *d0 0c 0 0 0 0
 FK= ==#0=?B=c]= = = =@#'5B   4"/   4$,TN@M   >$,TN@M   F):):
49c3x}<=): ): ): ):Z ""! >C >Cc]>C
3->C sm>C c]	>C
 SM>C >C >C >C >C >Cr   