o
    `۷i<e                     @   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mZ ddlm	Z	 ddl
mZmZmZmZmZmZ ddlZddlZddlZejdkrHddlZnddlZG dd dZzddlZdd	lmZ e  W n eyv   G d
d dZe ZY nw G dd dZe Zej dd dd Z!ddddde"dede#dee"ef dee"e$e$f defddZ%dd Z&G dd dZ'G dd  d ej(Z)e' Z*ej+d!dej,e*j-dd"d#d$d%ej+d&dej,g d'dd"d#d(d%ej+d)d*dd+d,gZ.d-ed.efd/d0Z/dS )1a/  Logger implementing the Command Line Interface.

A replacement for the standard Python `logging` API
designed for implementing a better CLI UX for the cluster launcher.

Supports color, bold text, italics, underlines, etc.
(depending on TTY features)
as well as indentation and other structured output.
    N)contextmanager)wraps)AnyCallableDictListOptionalTuplewin32c                   @   s0   e Zd Zdd Zdd Zedd Zdd Zd	S )
_ColorfulMockc                 C   s&   dd | _ | | _d | _d | _d | _d S )Nc                 S      | S N )xr   r   X/home/ubuntu/vllm_env/lib/python3.10/site-packages/ray/autoscaler/_private/cli_logger.py<lambda>"       z(_ColorfulMock.__init__.<locals>.<lambda>)identitycolorful	colormode	NO_COLORSANSI_8_COLORSselfr   r   r   __init__    s
   

z_ColorfulMock.__init__c                 C      d S r   r   r   r   r   r   disable*      z_ColorfulMock.disablec                 c   s    G dd d}| V  d S )Nc                   @   s   e Zd Zdd ZdS )z/_ColorfulMock.with_style.<locals>.IdentityClassc                 S   s   dd S )Nc                 S   r   r   r   )yr   r   r   r   1   r   zM_ColorfulMock.with_style.<locals>.IdentityClass.__getattr__.<locals>.<lambda>r   r   namer   r   r   __getattr__0   s   z;_ColorfulMock.with_style.<locals>.IdentityClass.__getattr__N)__name__
__module____qualname__r!   r   r   r   r   IdentityClass/   s    r%   r   )r   r   r%   r   r   r   
with_style-   s   z_ColorfulMock.with_stylec                 C   s   |dkr| j S | jS )Nr&   )r&   r   r   r   r   r   r!   5   s   z_ColorfulMock.__getattr__N)r"   r#   r$   r   r   r   r&   r!   r   r   r   r   r      s    

r   )ColorfulStringc                   @   s   e Zd ZdS )r'   N)r"   r#   r$   r   r   r   r   r'   F   s    r'   c                   @   s   e Zd Zg dZdd ZdS )_ColorfulProxy)r   resetbolditalic
underlineddimmed
dodgerBlue	limeGreenredorangeskyBluemagentayellowc                 C   s0   t t|}t|r|tjvrtd| d |S )NzUsage of the colorful method 'zh' is forbidden by the proxy to keep a consistent color scheme. Check `cli_logger.py` for allowed methods)getattr_cfcallabler(   _proxy_allowlist
ValueError)r   r    resr   r   r   r!   d   s   

z_ColorfulProxy.__getattr__N)r"   r#   r$   r8   r!   r   r   r   r   r(   Q   s    r(   F)stripc                  C   sN   t  } | }d}|jjtkr|j}|d7 }|jjtks|jtj	|jjdS )zGet the info from the caller frame.

    Used to override the logging function and line number with the correct
    ones. See the comment on _patched_makeRecord for more info.
    r      )linenofilename)
inspectcurrentframef_codeco_filename__file__f_backf_linenoospathbasename)framecallerlevelsr   r   r   _external_caller_infot   s   rL   )	no_format_tags	_numberedmsgargsrM   rN   rO   kwargsc             	   O   s   t | ts
t | tryd}|durCg }| D ]\}}	|	du r$||g7 }q|	du r)q||d |	 g7 }q|rCttdd|}d}
|dure|\}}}t|d t| d	 t| |d
  d }
|rm|
|  | S |
| j|i | | S |rt	d| g|}dd |D }d|S )aw  Formats a message for printing.

    Renders `msg` using the built-in `str.format` and the passed-in
    `*args` and `**kwargs`.

    Args:
        *args (Any): `.format` arguments for `msg`.
        no_format (bool):
            If `no_format` is `True`,
            `.format` will not be called on the message.

            Useful if the output is user-provided or may otherwise
            contain an unexpected formatting string (e.g. "{}").
        _tags (Dict[str, Any]):
            key-value pairs to display at the end of
            the message in square brackets.

            If a tag is set to `True`, it is printed without the value,
            the presence of the tag treated as a "flag".

            E.g. `_format_msg("hello", _tags=dict(from=mom, signed=True))`
                 `hello [from=Mom, signed]`
        _numbered (Tuple[str, int, int]):
            `(brackets, i, n)`

            The `brackets` string is composed of two "bracket" characters,
            `i` is the index, `n` is the total.

            The string `{i}/{n}` surrounded by the "brackets" is
            prepended to the message.

            This is used to number steps in a procedure, with different
            brackets specifying different major tasks.

            E.g. `_format_msg("hello", _numbered=("[]", 0, 5))`
                 `[0/5] hello`

    Returns:
        The formatted message.
     NTF=z [{}], r   /r<    z&We do not support printing kwargs yet.c                 S   s   g | ]}t |qS r   )str.0r   r   r   r   
<listcomp>   s    z_format_msg.<locals>.<listcomp>)

isinstancerX   r'   itemscfr)   r-   formatjoinr9   )rP   rM   rN   rO   rQ   rR   tags_str	tags_listkvnumbering_strcharsinr:   r   r   r   _format_msg   s2   1

.

ri   c                   C   s"   zt j W S  ty   Y dS w )z/More robust check for interactive terminal/tty.F)sys	__stdin__isatty	Exceptionr   r   r   r   _isatty   s
   rn   c                   @   s  e Zd ZU dZeed< eed< eed< dZeed< dd Z	dcd
dZ
ddddZedd Zdd Zedd Zdd Zedd Zdd Zdd Zdd Z				ded ed!ed"ed#efd$d%Zd&d' Zd ed(ed)efd*d+Zd ed(ed)efd,d-Zd.ed ed(ed)efd/d0Zd ed(ed)efd1d2Zd3d4 Zd ed(ed)efd5d6Zd ed(ed)efd7d8Zd ed(ed)efd9d:Zd	d;d ed(ed!ed)efd<d=Z d>d? Z!d	d;d ed(ed!ed)efd@dAZ"dBdC Z#dDdE Z$dd	dFd ed(ed!ed#ed)ef
dGdHZ%dfd efdIdJZ&		dcd	dKd e'e d(edLed)efdMdNZ(dOed ed(ed)efdPdQZ)e*+dRfdSe,e dTefdUdVZ-dWdWd	dXdYed ed(edZed[ed\e'e. d)efd]d^Z/d efd_d`Z0dadb Z1d	S )g
_CliLoggerav  Singleton class for CLI logging.

    Without calling 'cli_logger.configure', the CLILogger will default
    to 'record' style logging.

    Attributes:
        color_mode (str):
            Can be "true", "false", or "auto".

            Enables or disables `colorful`.

            If `color_mode` is "auto", is set to `not stdout.isatty()`
        indent_level (int):
            The current indentation level.

            All messages will be indented by prepending `"  " * indent_level`
        vebosity (int):
            Output verbosity.

            Low verbosity will disable `verbose` and `very_verbose` messages.
    
color_modeindent_levelinteractive)autorecordpretty_autodetected_cf_colormodec                 C   s@   d| _ d| _d| _d| _d| _d| _d| _tjj	| _
|   d S )Nr   Frs   rt   )rq   
_verbosity_verbosity_overriden_color_mode
_log_styleru   rr   r^   r   r   rv   
set_formatr   r   r   r   r     s   
z_CliLogger.__init__Nc                 C   s$   |s
ddl m} |}t|| _d S )Nr   )LOGGER_FORMAT)!ray.autoscaler._private.constantsr|   logging	Formatter
_formatter)r   format_tmplr|   r   r   r   r{     s   z_CliLogger.set_formatc                 C   sB   |dur	|  | |dur| | |dur| | |   dS )z*Configures the logger according to values.N)_set_log_style_set_color_mode_set_verbositydetect_colors)r   	log_stylerp   	verbosityr   r   r   	configure%  s   


z_CliLogger.configurec                 C      | j S r   )rz   r   r   r   r   r   2     z_CliLogger.log_stylec                 C   s^   |  | _t | _| jdkrt | _dS | jdkr#d| _| d dS | jdkr-d| _dS dS )z(Configures interactivity and formatting.rs   rt   Ffalseru   TN)lowerrz   rn   rr   ru   r   r   r   r   r   r   r   6  s   




z_CliLogger._set_log_stylec                 C   r   r   )ry   r   r   r   r   rp   C  r   z_CliLogger.color_modec                 C   s   |  | _|   d S r   )r   ry   r   r   r   r   r   r   G  s   
z_CliLogger._set_color_modec                 C   s   | j r| jS | jsdS | jS )Ni  )rx   rw   ru   r   r   r   r   r   K  s
   z_CliLogger.verbosityc                 C   s   || _ d| _d S )NT)rw   rx   r   r   r   r   r   S  s   
z_CliLogger._set_verbosityc                 C   s`   | j dkr| jtjkr| jt_dS tjt_dS | j dkr"t  dS | j dkr)dS td| j  )zUpdate color output settings.

        Parse the `color_mode` string and optionally disable or force-enable
        color output
        (8-color ANSI if no terminal detected to be safe) in colorful.
        trueNr   rs   zInvalid log color setting: )rp   rv   r^   r   r   r   r   r9   r   r   r   r   r   W  s   


z_CliLogger.detect_colorsc                 C   s   |  d dS )zPrint a line feed.rS   Nprintr   r   r   r   newlinem  s   z_CliLogger.newlineINFOTrP   
_level_str	_linefeedendc           
   	   C   s   | j rd| j | }n$| dkrdS t }tjdd|d |d |i dd}||_| j|}|d	v r7t	j
}nt	j}|sG|| |  dS d
|i}	t|fd|i|	 dS )zProxy for printing messages.

        Args:
            msg: Message to print.
            linefeed (bool):
                If `linefeed` is `False` no linefeed is printed at the
                end of the message.
        z  rS   Nclir   r>   r=   )r    levelpathnamer=   rP   rQ   exc_info)WARNINGERRORPANICr   file)ru   rq   r;   rL   r~   	LogRecord	levelnamer   r_   rj   stderrstdoutwriteflushr   )
r   rP   r   r   r   rendered_messagecaller_infort   streamrR   r   r   r   _printq  s2   
z_CliLogger._printc                    s   |  G  fddd}| S )z8Context manager that starts an indented block of output.c                       s$   e Zd Z fddZ fddZdS )z3_CliLogger.indented.<locals>.IndentedContextManagerc                    s     j d7  _ d S Nr<   rq   r   
cli_loggerr   r   	__enter__     z=_CliLogger.indented.<locals>.IndentedContextManager.__enter__c                    s     j d8  _ d S r   r   r   typevaluetbr   r   r   __exit__  r   z<_CliLogger.indented.<locals>.IndentedContextManager.__exit__Nr"   r#   r$   r   r   r   r   r   r   IndentedContextManager  s    r   r   )r   r   r   r   r   indented  s   z_CliLogger.indentedrQ   rR   c                 O   s&   | j t|g|R i | |  S )zwPrint a group title in a special color and start an indented block.

        For arguments, see `_format_msg`.
        )r   r^   r.   r   r   rP   rQ   rR   r   r   r   group  s   z_CliLogger.groupc                    s"   | G  fddd}| S )a  Context manager for printing multi-line error messages.

        Displays a start sequence "!!! {optional message}"
        and a matching end sequence "!!!".

        The string "!!!" can be used as a "tombstone" for searching.

        For arguments, see `_format_msg`.
        c                       s*   e Zd Z fddZfddZdS )zA_CliLogger.verbatim_error_ctx.<locals>.VerbatimErorContextManagerc                    s(   j tdd g R i  d S )Nz!!! z{}errorr^   r*   r   rQ   r   rR   rP   r   r   r     s   (zK_CliLogger.verbatim_error_ctx.<locals>.VerbatimErorContextManager.__enter__c                    s     td d S )Nz!!!r   r   r   r   r   r        zJ_CliLogger.verbatim_error_ctx.<locals>.VerbatimErorContextManager.__exit__Nr   r   r   r   r   VerbatimErorContextManager  s    r   r   )r   rP   rQ   rR   r   r   r   r   verbatim_error_ctx  s   
z_CliLogger.verbatim_error_ctxkeyc                 O   s4   |  t|d tt|g|R i |  dS )zDisplays a key-value pair with special formatting.

        Args:
            key: Label that is prepended to the message.

        For other arguments, see `_format_msg`.
        z: N)r   r^   r2   ri   r*   )r   r   rP   rQ   rR   r   r   r   labeled_value  s   4z_CliLogger.labeled_valuec                 O   .   | j dkr| j|g|R ddi| dS dS )z[Prints a message if verbosity is not 0.

        For arguments, see `_format_msg`.
        r   r   VINFONr   r   r   r   r   r   verbose     
 z_CliLogger.verbosec                 O   r   )zePrints a formatted warning if verbosity is not 0.

        For arguments, see `_format_msg`.
        r   r   VWARNN)r   _warningr   r   r   r   verbose_warning  r   z_CliLogger.verbose_warningc                 O   r   )zXLogs an error if verbosity is not 0.

        For arguments, see `_format_msg`.
        r   r   VERRN)r   _errorr   r   r   r   verbose_error  r   z_CliLogger.verbose_errorc                 O   r   )zOPrints if verbosity is > 1.

        For arguments, see `_format_msg`.
        r<   r   VVINFONr   r   r   r   r   very_verbose  r   z_CliLogger.very_verbosec                 O   s&   | j t|g|R ddi| dS )zWPrints a formatted success message.

        For arguments, see `_format_msg`.
        r   SUCCN)r   r^   r/   r   r   r   r   success  s   &z_CliLogger.success)r   c                O   6   |du rt d| jt|g|R d|i| dS )zWPrints a formatted warning message.

        For arguments, see `_format_msg`.
        NLog level not set.r   )r9   r   r^   r1   r   rP   r   rQ   rR   r   r   r   r        &z_CliLogger._warningc                 O      | j |ddi| d S )Nr   WARN)r   r   rQ   rR   r   r   r   warning     z_CliLogger.warningc                O   r   )zUPrints a formatted error message.

        For arguments, see `_format_msg`.
        Nr   r   )r9   r   r^   r0   r   r   r   r   r     r   z_CliLogger._errorc                 O   r   )Nr   ERRr   r   r   r   r   r     r   z_CliLogger.errorc                 O   r   )Nr   r   r   r   r   r   r   panic  r   z_CliLogger.panicr   r   c                O   s&   | j t|g|R i |||d dS )zEPrints a message.

        For arguments, see `_format_msg`.
        r   N)r   ri   )r   rP   r   r   rQ   rR   r   r   r   r      s   &z_CliLogger.printc                 O   s    | j |g|R d|i| d S )NrM   r   )r   rP   rM   rQ   rR   r   r   r   info.  s    z_CliLogger.info)excr   c                O   sT   |dur| j |g|R ddi| |dur|tj}| jr t}|du r&d}||)zPrints an error and aborts execution.

        Print an error and throw an exception to terminate the program
        (the exception will not print a message).
        Nr   r   z!Exiting due to cli_logger.abort())r   clickClickExceptionru   SilentClickException)r   rP   r   rQ   rR   exc_clsr   r   r   abort1  s   z_CliLogger.abortvalc                 O   s8   |sd}| j s
t }| j|g|R d|i| dS dS )zHandle assertion without throwing a scary exception.

        Args:
            val: Value to check.

        For other arguments, see `_format_msg`.
        Nr   )ru   AssertionErrorr   )r   r   rP   rQ   rR   r   r   r   r   doassertG  s    z_CliLogger.doassertrU   xs	separatorc                 C   s   | dd |D S )z<Render a list of bolded values using a non-bolded separator.c                 S   s   g | ]	}t t|qS r   )rX   r^   r*   rY   r   r   r   r[   \  s    z*_CliLogger.render_list.<locals>.<listcomp>)r`   )r   r   r   r   r   r   render_listZ  s   z_CliLogger.render_listF)_abort_default
_timeout_syesr   r   r   c             
   O   s  |}|}	| j s|s| d td|	rd}
nd}
td|
 d d }t|g|R i |}|r:|ds:|d7 }t|dd	 }|| }|rW| 	|d
 t
d  dS | j	|dd d}g d}g d}z	 |du rttj }nrtjdkrt }d}	 t | |kr|   d}n;t rt }|dv r|   |d }n&|dkr|r|dd	 }tdddd n|| }t|ddd ntd qnttjgg g |\}}}|s|   d}ntj }| }|dkr|	}n7| }||v rd}n,||v rd}n$d| }| d|t| | |d| |d | j	|| dd qjW n ty9   |   |	}Y nw |sI|rI| 	d td|S )a  Display a confirmation dialog.

        Valid answers are "y/yes/true/1" and "n/no/false/0".

        Args:
            yes: If `yes` is `True` the dialog will default to "yes"
                        and continue without waiting for user input.
            _abort (bool):
                If `_abort` is `True`,
                "no" means aborting the program.
            _default (bool):
                The default action to take if the user just presses enter
                with no input.
            _timeout_s (float):
                If user has no input within _timeout_s seconds, the default
                action is taken. None means no timeout.
        z^This command requires user confirmation. When running non-interactively, supply --yes to skip.z&Non-interactive confirm without --yes.zY/nzy/Nz	Confirm [z]:rW   
zy z[automatic, due to --yes]TF)r   N)r   r   r   1)rh   nor   0r
   rS   )r   z )r   r   g?z'{}Invalid answer: {}. Expected {} or {}rV   z
Exiting...z:Exiting due to the response to confirm(should_abort=True).)rr   r   r9   r^   r,   ri   endswithlensplitr   r-   rj   stdinreadlineplatformtimer   msvcrtkbhitgetwchr   sleepselectr   r;   r*   r   KeyboardInterruptr   )r   r   rP   r   r   r   rQ   rR   should_abortdefaultyn_strconfirm_strr   msg_lencomplete_strr:   yes_answers
no_answersans
start_timechready_indentr   r   r   confirm^  s   






;
z_CliLogger.confirmc                 O   s   t |}t|g|R i |}|r|ds|d7 }| j|dd d}ztj }| }|	 }W |S  t
yB   |   Y |S w )zPrompt the user for some text input.

        Args:
            msg: The mesage to display to the user before the prompt.

        Returns:
            The string entered by the user.
        r   rW   F)linefeedrS   )r^   r,   ri   r   r   rj   r   r   r   r;   r   r   )r   rP   rQ   rR   r  r   r:   r	  r   r   r   prompt  s   
	


z_CliLogger.promptc                 C   s   t j  t j  d S r   )rj   r   r   r   r   r   r   r   r      s   
z_CliLogger.flushr   )NNN)r   TN)T)2r"   r#   r$   __doc__rX   __annotations__intboolVALID_LOG_STYLESr   r{   r   propertyr   r   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r^   r)   r   r   floatr  r  r   r   r   r   r   ro      s   
 





7	
 	 	

 	
 	ro   c                       s0   e Zd ZdZdef fddZdddZ  ZS )	r   a;  `ClickException` that does not print a message.

    Some of our tooling relies on catching ClickException in particular.

    However the default prints a message, which is undesirable since we expect
    our code to log errors manually using `cli_logger.error()` to allow for
    colors and other formatting.
    messagec                    s   t t| | d S r   )superr   r   )r   r  	__class__r   r   r     r   zSilentClickException.__init__Nc                 C   r   r   r   )r   r   r   r   r   show  r   zSilentClickException.showr   )r"   r#   r$   r  rX   r   r  __classcell__r   r   r  r   r     s    	r   z--log-style)case_sensitivers   zIf 'pretty', outputs with formatting and color. If 'record', outputs record-style without formatting. 'auto' defaults to 'pretty', and disables pretty logging if stdin is *not* a TTY.)requiredr   r  helpz--log-color)rs   r   r   zAUse color logging. Auto enables color logging if stdout is a TTY.z-vz	--verboseT)r  countfreturnc                    s8   t tD ]}|  qt d d d d fdd
}|S )N)r   	log_colorr   c                    s   t | ||  |i |S r   )r   r   )r   r%  r   rQ   rR   r#  r   r   wrapper4  s   z*add_click_logging_options.<locals>.wrapper)reversedCLICK_LOGGING_OPTIONSr   )r#  optionr'  r   r&  r   add_click_logging_options0  s
   
r+  )0r  r?   r~   rF   rj   r   
contextlibr   	functoolsr   typingr   r   r   r   r   r	   r   coloramarayr   r   r   r   r   r6   colorful.corer'   use_8_ansi_colorsModuleNotFoundErrorr(   r^   initrL   rX   r  r  ri   rn   ro   r   r   r   r*  Choicer  r)  r+  r   r   r   r   <module>   s    	 




\    