
    &`i:                     :   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 dZ	da
dad ZdefdZd	 Zdefd
Z G d de          Z ej        d           ej        d           ej        d           ej        d          dZddZeddfdZeddfdZd ZdS )    N)cf
cli_logger   FTc                      t           S N_redirect_output     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/autoscaler/_private/subprocess_output_util.pyis_output_redirectedr      s    r   valc                 
    | a dS )zChoose between logging to a temporary file and to `sys.stdout`.

    The default is to log to a file.

    Args:
        val: If true, subprocess output will be redirected to
                    a temporary file.
    Nr   r   s    r   set_output_redirectedr      s     r   c                      t           S r   _allow_interactiver
   r   r   does_allow_interactiver   !   s    r   c                 
    | a dS )zChoose whether to pass on stdin to running commands.

    The default is to pipe stdin and close it immediately.

    Args:
        val: If true, stdin will be passed to commands.
    Nr   r   s    r   set_allow_interactiver   %   s     r   c                         e Zd Zd fd	Z xZS )ProcessRunnerErrorNc           	          t          t          |                               d                    |||||                     || _        || _        || _        || _        d S )Nz0{} (discovered={}): type={}, code={}, command={})superr   __init__formatmsg_typecodecommandspecial_case)selfmsgr   r   r    r!   	__class__s         r   r   zProcessRunnerError.__init__2   si     $''00>EE\8T7 	
 	
 	
 !	(r   )NNN)__name__
__module____qualname__r   __classcell__)r$   s   @r   r   r   1   s=        ) ) ) ) ) ) ) ) ) )r   r   zH\s*Warning: Permanently added '.+' \(.+\) to the list of known hosts.\s*z%\s*Shared connection to .+ closed.\s*z:\s*ssh: connect to host .+ port .+: Operation timed out\s*z9\s*ssh: connect to host .+ port .+: Connection refused\s*)known_host_updateconnection_closedtimeoutconn_refusedc                 X   d}	 |                                  }||dk    rn|d         dk    r
|dd         }|st          d                             |          Xt          d                             |          |t          d|z             d	}t          d
                             |          |t          d|z             d}t          d                             |          t	          j        |           |(|t          j        k    r|                    |dz              &|S )a  Read and process a subprocess output stream.

    The goal is to find error messages and respond to them in a clever way.
    Currently just used for SSH messages (CONN_REFUSED, TIMEOUT, etc.), so
    the user does not get confused by these.

    Ran in a thread each for both `stdout` and `stderr` to
    allow for cross-platform asynchronous IO.

    Note: `select`-based IO is another option, but Windows has
    no support for `select`ing pipes, and Linux support varies somewhat.
    Spefically, Older *nix systems might also have quirks in how they
    handle `select` on pipes.

    Args:
        f: File object for the stream.
        output_file: File object to which filtered output is written.
        is_stdout (bool):
            When `is_stdout` is `False`, the stream is assumed to
            be `stderr`. Different error message detectors are used,
            and the output is displayed to the user unless it matches
            a special case (e.g. SSH timeout), in which case this is
            left up to the caller.
    NT 
r*   r+   z:Bug: ssh_timeout conflicts with another special codition: ssh_timeoutr,   z?Bug: ssh_conn_refused conflicts with another special codition: ssh_conn_refusedr)   )	readline_ssh_output_regexes	fullmatch
ValueErrorr   error
subprocessDEVNULLwrite)foutput_file	is_stdoutdetected_special_caselines        r   _read_subprocess_streamr@   O   ss   4 !<+ zz||<42::8t9D ,	#"#67AA$GGS "9-77==I
 )4$-/DE  
 )6%">2<<TBBN )4$-/DE  
 );%"#67AA$GGS T""""{j6H'H'HdTk***y<+| ! r   c           	      J   t           j        }t                      rt                      r
J d            |t           k    st                      rt                      sd}|s|t           k    r|                    | |||          S t          j        | |t           j        t           j        dd          5 }ddlm} |j        	                                  |d	
          5 }|
                    t          |j        |d          }	|
                    t          |j        |d          }
|                                 |                                 |	                                }|
                                %|t#          d          |
                                }|j        dk    rt'          dd|j        | |          |j        dk     rt'          dd|j        | d          |j        cddd           cddd           S # 1 swxY w Y   	 ddd           dS # 1 swxY w Y   dS )aU  Run a command and process its output for special cases.

    Calls a standard 'check_call' if process_runner is not subprocess.

    Specifically, run all command output through regex to detect
    error conditions and filter out non-error messages that went to stderr
    anyway (SSH writes ALL of its "system" messages to stderr even if they
    are not actually errors).

    Args:
        cmd (List[str]): Command to run.
        process_runner: Used for command execution. Assumed to have
            'check_call' and 'check_output' inplemented.
        stdout_file: File to redirect stdout to.
        stderr_file: File to redirect stderr to.

    Implementation notes:
    1. `use_login_shells` disables special processing
    If we run interactive apps, output processing will likely get
    overwhelmed with the interactive output elements.
    Thus, we disable output processing for login shells. This makes
    the logging experience considerably worse, but it only degrades
    to old-style logging.

    For example, `pip install` outputs HUNDREDS of progress-bar lines
    when downloading a package, and we have to
    read + regex + write all of them.

    After all, even just printing output to console can often slow
    down a fast-printing app, and we do more than just print, and
    all that from Python, which is much slower than C regarding
    stream processing.

    2. `stdin=PIPE` for subprocesses
    Do not inherit stdin as it messes with bash signals
    (ctrl-C for SIGINT) and these commands aren't supposed to
    take input anyway.

    3. `ThreadPoolExecutor` without the `Pool`
    We use `ThreadPoolExecutor` to create futures from threads.
    Threads are never reused.

    This approach allows us to have no custom synchronization by
    off-loading the return value and exception passing to the
    standard library (`ThreadPoolExecutor` internals).

    This instance will be `shutdown()` ASAP so it's fine to
    create one in such a weird place.

    The code is thus 100% thread-safe as long as the stream readers
    are read-only except for return values and possible exceptions.
    z1Cannot redirect output while in interactive mode.N)stdinstdoutstderr   T)rB   rC   rD   bufsizeuniversal_newlinesr   )ThreadPoolExecutor   )max_workers)r=   FzqBug: found a special case in both stdout and stderr. This is not valid behavior at the time of writing this code.zCommand failedssh_command_failed)r   r    r!   died_to_signal)r8   PIPEr   r   
check_callPopenconcurrent.futuresrH   rB   closesubmitr@   rC   rD   shutdownpollresultr6   
returncoder   )cmdstdout_fileprocess_runnerstderr_fileuse_login_shellsstdin_overwriteprH   executorstdout_futurestderr_futurer>   s               r   _run_and_process_outputra      sO   v !oO 	  ;%9%;%;; ;:; ;  ##   $)=)?)? $   
>Z77((! ) 
 
 	
 
	
 
 
 @  
999999 	
  A... 0	 ($OO';$ ,  M %OO';% ,  M  FFHHH$1$8$8$:$:!##%%1(4
 %0  
 )6(<(<(>(>%|a )$(!6    !! )$(!1    <a0	  0	  0	  0	  0	  0	  0	 !@  @  @  @  @  @  @  @  0	  0	  0	  0	  0	  0	  0	  0	  0	 !@  @  @  @  @  @  @  @  @  @  @  @  @  @  @  @  @  @ s7   0,HD
G?&H?H	HH	HHHc                 ^   |r.t           j        dk     rt          | ||j        |j        |          S t	                      s(t          | |t
          j        t
          j        |          S t          j	        
                    t          j                    d                    | d         t          j                                        }t          |dd          5 }t          j        dt#          j        |j                             t          | ||||          cddd           S # 1 swxY w Y   dS )	a  Run a command and optionally redirect output to a file.

    Args:
        cmd (List[str]): Command to run.
        process_runner: Process runner used for executing commands.
        silent: If true, the command output will be silenced completely
                       (redirected to /dev/null), unless verbose logging
                       is enabled. Use this for running utility commands like
                       rsync.
    rE   )rY   rX   rZ   r[   zray-up-{}-{}.txtr   w)mode	bufferingz"Command stdout is redirected to {}N)r   	verbosityra   r9   r   sysrC   rD   ospathjointempfile
gettempdirr   timeopenverboser   boldname)rW   rY   silentr[   tmpfile_pathtmps         r   run_cmd_redirectedru   >  s     
*&**&)&.&.-
 
 
 	
  !! &)

-
 
 
 	
 w||!!#5#<#<SVTY[[#Q#Q
 
 	
 
 
 	
 CRWSXEVEVWWW*-!1  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   A D""D&)D&c                    | j         dk    rdS | j        dk    r|lt          j                    |z
  t          k    rMt	          j        dt          j        t          t                                         t	          j	        d           t	          j
        d           t	          j
        d           t          j                    S | j        dv r5t	          j        d	t          j        t          |                               n| |S )
a   Handle SSH system failures coming from a subprocess.

    Args:
        e: The `ProcessRunnerException` to handle.
        first_conn_refused_time:
            The time (as reported by this function) or None,
            indicating the last time a CONN_REFUSED error was caught.

            After exceeding a patience value, the program will be aborted
            since SSH will likely never recover.
        retry_interval: The interval after which the command will be retried,
                        used here just to inform the user.
    rK   Nr2   zOSSH connection was being refused for {} seconds. Head node assumed unreachable.zGCheck the node's firewall settings and the cloud network configuration.zSSH connection was refused.zsThis might mean that the SSH daemon is still setting up, or that the host is inaccessable (e.g. due to a firewall).)r1   r2   z0SSH still not available, retrying in {} seconds.)r   r!   rm   CONN_REFUSED_PATIENCEr   r7   r   rp   strabortwarningprint)efirst_conn_refused_timeretry_intervals      r   handle_ssh_failsr   q  s    	z)))~+++#/	558MMM 12233	   7  
 	8999	
 	
 	
 y{{~<<<>GC''((	
 	
 	
 	

 ""r   )F)rh   rer8   rg   rk   rm   "ray.autoscaler._private.cli_loggerr   r   rw   r	   r   r   boolr   r   r   	Exceptionr   compiler4   r@   ra   ru   r   r
   r   r   <module>r      s   				 				     



   = = = = = = = =     
t 
 
 
 
  	t 	 	 	 	) ) ) ) ) ) ) )  $W  $$LMMrzI  BJD   Y! Y! Y! Y!~ P  P  P  P h #550 0 0 0f3# 3# 3# 3# 3#r   