
    %`i                     h   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m	Z	m
Z
 ddlmZ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Zddlmc mc mZ ddlmc mZ ddl m!Z! ddl"m#Z#m$Z$ dd	l%m&Z&m'Z'  ej(        e)          Z*e$j+        Z+ e
d
           G d d                      Z, e
d
           G d d                      Z- e
d
           G d d                      Z. e
d
           G d d                      Z/ G d de          Z0 e1            a2 ej3                    Z4 e5            a6 ej3                    Z7de8de8fdZ9de8dee8         fdZ:de8fdZ;de8fdZ<	 dPde+de8d ee!         fd!Z=dPde8de8d ee!         fd"Z>de8fd#Z?de8fd$Z@d% ZAd& ZBd' ZCd( ZDej        jE        jF        G                    eC           d) ZHd* ZId+ ZJde0fd,ZKdeLfd-ZMdeLfd.ZNd/ ZOd0eLfd1ZPd2eLddfd3ZQdQd4ZRdQd5ZSd e!d0eLde5fd6ZTdeeU         fd7ZVdPdeeU         fd8ZWdee8         fd9ZXdee8         fd:ZYd e!dee8e8f         fd;ZZd e!de-fd<Z[d e!de-fd=Z\de8fd>Z]d?e8de,fd@Z^d e!de5fdAZ_d ej`        j!        deLfdBZade.fdCZbdDe,dEeUdFeUdGeUdHe8dIe8de.fdJZcdKe.dLe8de/fdMZd G dN dO          ZedS )Ra  This is the module that is in charge of Ray usage report (telemetry) APIs.

NOTE: Ray's usage report is currently "on by default".
      One could opt-out, see details at https://docs.ray.io/en/master/cluster/usage-stats.html. # noqa

Ray usage report follows the specification from
https://docs.ray.io/en/master/cluster/usage-stats.html#usage-stats-collection  # noqa

# Module

The module consists of 2 parts.

## Public API
It contains public APIs to obtain usage report information.
APIs will be added before the usage report becomes opt-in by default.

## Internal APIs for usage processing/report
The telemetry report consists of 5 components. This module is in charge of the top 2 layers.

Report                -> usage_lib
---------------------
Usage data processing -> usage_lib
---------------------
Data storage          -> Ray API server
---------------------
Aggregation           -> Ray API server (currently a dashboard server)
---------------------
Usage data collection -> Various components (Ray agent, GCS, etc.) + usage_lib (cluster metadata).

Usage report is currently "off by default". You can enable the report by setting an environment variable
RAY_USAGE_STATS_ENABLED=1. For example, `RAY_USAGE_STATS_ENABLED=1 ray start --head`.
Or `RAY_USAGE_STATS_ENABLED=1 python [drivers with ray.init()]`.

"Ray API server (currently a dashboard server)" reports the usage data to https://usage-stats.ray.io/.

Data is reported every hour by default.

Note that it is also possible to configure the interval using the environment variable,
`RAY_USAGE_STATS_REPORT_INTERVAL_S`.

To see collected/reported data, see `usage_stats.json` inside a temp
folder (e.g., /tmp/ray/session_[id]/*).
    N)asdict	dataclass)Enumauto)Path)DictListOptionalSet)	GcsClient)gcs_pb2	usage_pb2)_internal_kv_initialized_internal_kv_putT)initc                       e Zd ZU dZee         ed<   dZee         ed<   dZ	ee         ed<   dZ
ee         ed<   dZeee                  ed<   dS )ClusterConfigToReportNcloud_providermin_workersmax_workershead_node_instance_typeworker_node_instance_types)__name__
__module____qualname__r   r
   str__annotations__r   intr   r   r   r	        o/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_common/usage/usage_lib.pyr   r   M   s}         $(NHSM(((!%K#%%%!%K#%%%-1Xc]1116:c 3:::::r    r   c                   x    e Zd ZU dZee         ed<   dZee         ed<   dZee	         ed<   dZ
ee	         ed<   dS )ClusterStatusToReportNtotal_num_cpustotal_num_gpustotal_memory_gbtotal_object_store_memory_gb)r   r   r   r$   r
   r   r   r%   r&   floatr'   r   r    r!   r#   r#   V   sc         $(NHSM((($(NHSM((('+OXe_+++48 (5/88888r    r#   c                      e Zd ZU dZeed<   eed<   eed<   dZee         ed<   dZ	ee         ed<   dZ
ee         ed<   dZee         ed	<   dZee         ed
<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZeee                  ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZee         ed<   dZeee                  ed<   dZeeeef                  ed<   dZee         ed<   dZ ee         ed<   dZ!ee         ed<   dZ"eee                  ed<   dS )UsageStatsToReportzUsage stats to reportschema_versionsourcecollect_timestamp_msNtotal_successtotal_failed
seq_numberray_versionpython_version
session_id
git_commitossession_start_timestamp_msr   r   r   r   r   r$   r%   r&   r'   library_usagesextra_usage_tagstotal_num_nodestotal_num_running_jobslibc_versionhardware_usages)#r   r   r   __doc__r   r   r   r.   r
   r/   r0   r1   r2   r3   r4   r5   r6   r   r   r   r   r   r	   r$   r%   r&   r(   r'   r7   r8   r   r9   r:   r;   r<   r   r    r!   r*   r*   ^   s=         KKK#'M8C='''"&L(3-&&& $J$$$!%K#%%%$(NHSM((( $J$$$ $J$$$B04444$(NHSM(((!%K#%%%!%K#%%%-1Xc]1116:c 3:::$(NHSM((($(NHSM((('+OXe_+++48 (5/888*.NHT#Y'... 26htCH~.555%)OXc]))) -1HSM000"&L(3-&&&+/OXd3i(/////r    r*   c                   2    e Zd ZU dZeed<   eed<   eed<   dS )UsageStatsToWritezUsage stats to write to `USAGE_STATS_FILE`

    We are writing extra metadata such as the status of report
    to this file.
    usage_statssuccesserrorN)r   r   r   r=   r*   r   boolr   r   r    r!   r?   r?      s:           $###MMMJJJJJr    r?   c                   J    e Zd Z e            Z e            Z e            ZdS )UsageStatsEnablednessN)r   r   r   r   ENABLED_EXPLICITLYDISABLED_EXPLICITLYENABLED_BY_DEFAULTr   r    r!   rE   rE      s4        $&&r    rE   set_namevaluec           	      &   t                      sJ 	 t          |  |                                 dt          j                                                   d S # t
          $ r.}t                              d| d|  d|            Y d }~d S d }~ww xY w)Nr    	namespacezFailed to add z to usage set , )r   r   encodeusage_constantUSAGE_STATS_NAMESPACE	Exceptionloggerdebug)rI   rJ   es      r!   _add_to_usage_setrV      s    #%%%%%L   ''))$:AACC	
 	
 	
 	
 	
 	

  L L LJeJJ8JJqJJKKKKKKKKKLs   AA 
B"#BBreturnc                    	 t                      }|                     |                                t          j                                                  }|D ]A}|                    d          }|                    |t          |          d                     B|S # t          $ r8}t          
                    d| d|            t                      cY d }~S d }~ww xY w)NrL   utf-8zFailed to get usage set rN   )setinternal_kv_keysrO   rP   rQ   decodeaddlenrR   rS   rT   )
gcs_clientrI   resultusagesusagerU   s         r!   _get_usage_setrc      s    ,,OO$:AACC - 
 
  	/ 	/ELL))EJJuS]]__-....   ???A??@@@uus   BB 
C%-CCClibrary_usagec                 :    t          t          j        |            d S N)rV   rP   LIBRARY_USAGE_SET_NAMErd   s    r!   _put_library_usageri      s    n;]KKKKKr    hardware_usagec                 :    t          t          j        |            d S rf   )rV   rP   HARDWARE_USAGE_SET_NAMErj   s    r!   _put_hardware_usagern      s    n<nMMMMMr    keyr_   c                 N   t                               |                                           } t          5  t                              |           |k    r	 ddd           dS |t          | <   ddd           n# 1 swxY w Y   t                      s|dS t          | ||           dS )a%  Record extra kv usage tag.

    If the key already exists, the value will be overwritten.

    To record an extra tag, first add the key to the TagKey enum and
    then call this function.
    It will make a synchronous call to the internal kv store if the tag is updated.

    Args:
        key: The key of the tag.
        value: The value of the tag.
        gcs_client: The GCS client to perform KV operation PUT. Defaults to None.
            When None, it will try to get the global client from the internal_kv.

    Returns:
        None
    N)TagKeyNamelower_recorded_extra_usage_tags_lock_recorded_extra_usage_tagsgetr   _put_extra_usage_tag)ro   rJ   r_   s      r!   record_extra_usage_tagrx      s   ( ++c


 
 
"
"C	( 0 0%))#..%770 0 0 0 0 0 0 0 +0"3'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 $%% **< 	eZ00000s    A7!
A77A;>A;c                    	 t           j         |                                  } |                                }t           j                                        }||                    | ||           d S t                      sJ t          | ||           d S # t          $ r(}t          	                    d|            Y d }~d S d }~ww xY w)NrL   zFailed to put extra usage tag, )
rP   EXTRA_USAGE_TAG_PREFIXrO   rQ   internal_kv_putr   r   rR   rS   rT   )ro   rJ   r_   valrM   rU   s         r!   rw   rw      s    <6===DDFFllnn"8??AA	!&&sC9&EEEEE ,-----S#;;;;;; < < <:q::;;;;;;;;;<s   A.B 2"B 
C CCc                 D    t                      sJ t          |            dS )z4Record hardware usage (e.g. which CPU model is used)N)r   rn   rm   s    r!   record_hardware_usager~     s(    #%%%%%'''''r    c                    t           5  | t          v r	 ddd           dS t                              |            ddd           n# 1 swxY w Y   t                      sdS t          j        j        j        j        t          j	        k    sQt          j        j        j        j        t          j
        k    s(t          j        j        j                                        rt          |            dS dS )z1Record library usage (e.g. which library is used)N)_recorded_library_usages_lock_recorded_library_usagesr]   r   ray_privateworkerglobal_workermodeSCRIPT_MODEWORKER_MODEutilclientis_connectedri   rh   s    r!   record_library_usager     s,   	& 4 44444 4 4 4 4 4 4 4 	!$$]3334 4 4 4 4 4 4 4 4 4 4 4 4 4 4
 $%%  	).#/AA<,1S_DD8?++-- E 	=))))) EDs   AAA
A
c                      t                      sJ t          j        j        j        j        t          j        k    s*t          j        j        j        	                                sd S t          D ]} t          |            d S rf   )r   r   r   r   r   r   r   r   r   r   r   ri   rh   s    r!   _put_pre_init_library_usagesr   *  s{    #%%%%%
 	).#/AA8?++-- 	B 	1 * *=))))* *r    c                      t                      sJ t                                          D ]\  } }t          | |           d S rf   )r   ru   itemsrw   )kvs     r!   _put_pre_init_extra_usage_tagsr   9  sP    #%%%%%*0022 # #1Q""""# #r    c                  >    t                       t                       d S rf   )r   r   r   r    r!   put_pre_init_usage_statsr   ?  s      """"$$$$$r    c                      t           5  t                      ad d d            n# 1 swxY w Y   t          5  t	                      ad d d            d S # 1 swxY w Y   d S rf   )r   rZ   r   rt   dictru   r   r    r!   reset_global_stater   D  s     
' ) )#&55 ) ) ) ) ) ) ) ) ) ) ) ) ) ) )	( , ,%)VV", , , , , , , , , , , , , , , , , ,s   #''AAAc                  ,    t          j        dd          S )NRAY_USAGE_STATS_REPORT_URLzhttps://usage-stats.ray.io/)r5   getenvr   r    r!   _usage_stats_report_urlr   P  s     913PQQQr    c                  F    t          t          j        dd                    S )N!RAY_USAGE_STATS_REPORT_INTERVAL_Si  r   r5   r   r   r    r!   _usage_stats_report_interval_sr   V  s    ry<dCCDDDr    c                  f    t          j        dt           j                            d                    S )NRAY_USAGE_STATS_CONFIG_PATHz~/.ray/config.json)r5   r   path
expanduserr   r    r!   _usage_stats_config_pathr   Z  s,    9%rw'9'9:N'O'O  r    c                     t          j        t          j                  } | dk    rt          j        S | dk    rt          j        S | t          dt          j         d|            d }	 t          t                                5 }t          j        |          }|                    d          }d d d            n# 1 swxY w Y   n?# t          $ r Y n3t          $ r'}t                              d|            Y d }~nd }~ww xY w|du rt          j        S |du rt          j        S |!t          d	t                       d
|           t          j        S )N01zValid value for z env var is 0 or 1, but got r@   z"Failed to load usage stats config FTz!Valid value for 'usage_stats' in z is true or false, but got )r5   r   rP   USAGE_STATS_ENABLED_ENV_VARrE   rG   rF   
ValueErroropenr   jsonloadrv   FileNotFoundErrorrR   rS   rT   rH   )usage_stats_enabled_env_varusage_stats_enabled_config_varfconfigrU   s        r!   _usage_stats_enablednessr   `  s   "$)N,V"W"W"c))$88	$	+	+$77	$	0H~I H H*EH H
 
 	

 &*"?*,,-- 	GYq\\F-3ZZ-F-F*	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G 	G     ? ? ?=!==>>>>>>>>? &..$88	'4	/	/$77	'	3K0H0J0J K K*HK K
 
 	
 !33sB   'C *B8,C 8B<<C ?B< C 
D 	D C;;D c                  >    t           j        dk    odt           j        v S )Nz{{RAY_COMMIT_SHA}}dev)r   
__commit____version__r   r    r!   is_nightly_wheelr     s    >11Nes6NNr    c                  6    t                      t          j        uS rf   )r   rE   rG   r   r    r!   usage_stats_enabledr     s    #%%-B-VVVr    c                  N    t          t          j        dd                    dk    S )NRAY_USAGE_STATS_PROMPT_ENABLEDr      r   r   r    r!   usage_stats_prompt_enabledr     s"    ry93??@@AEEr    ray_init_clusterc                    t           j        j                                        \  }}||| d}t	                      r|                    t           j        t          j        t          t          j
                    dz            d           t          j        dk    rLt          j                    \  }}|s|                    ddi           n|                    d| d| i           |S )zReturn a dictionary of cluster metadata.

    Params:
        ray_init_cluster: Whether the cluster is started by ray.init()

    Returns:
        A dictionary of cluster metadata.
    )r1   r2   r     )r4   r5   r6   linuxr;   NA:)r   r   utilscompute_version_infor   updater   sysplatformr   timelibc_ver)r   r1   r2   metadatalibvers         r!   _generate_cluster_metadatar     s     #&,"4"I"I"K"KK #(, H  B!nl.1$)++2D.E.E 	
 	
 	
 <7""!*,,JS# B 67777C# @AAAOr    clic                    t                      sd S ddlm} | r|j        nt          }t	                      }|t
          j        u r |t          j                   d S |t
          j	        u r| s |t          j
                   d S |j        r|                    dt          j        dd          }t          |           	 t          |           n4# t           $ r'}t"                              d|            Y d }~nd }~ww xY w|r |t          j                   d S  |t          j                   d S  |t          j                   d S |t
          j        u sJ  || rt          j        nt          j                   d S )Nr   )
cli_loggerFT
   )_default
_timeout_sz:Failed to persist usage stats choice for future clusters: )r   "ray.autoscaler._private.cli_loggerr   printr   rE   rG   rP   USAGE_STATS_DISABLED_MESSAGErH   3USAGE_STATS_ENABLED_BY_DEFAULT_FOR_RAY_INIT_MESSAGEinteractiveconfirm USAGE_STATS_CONFIRMATION_MESSAGE#set_usage_stats_enabled_via_env_var"set_usage_stats_enabled_via_configrR   rS   rT   #USAGE_STATS_ENABLED_FOR_CLI_MESSAGE.USAGE_STATS_ENABLED_BY_DEFAULT_FOR_CLI_MESSAGErF   (USAGE_STATS_ENABLED_FOR_RAY_INIT_MESSAGE)r   r   prompt_printusage_stats_enablednessenabledrU   s         r!   show_usage_stats_promptr     s   %'' ======'*5:##L688"7"KKK^@AAAAA	 $9$L	L	L 	LR     # 	 ((?	 )  G 088827;;;;   TQRTT         J^OPPPPP^HIIIIILM     '*?*RRRRRIN>>H	
 	
 	
 	
 	
s   ;C 
C<C77C<c           
      8   i }	 t          t                                5 }t          j        |          }d d d            n# 1 swxY w Y   t	          |t
                    s,t                              dt          |                      i }n?# t          $ r Y n3t          $ r'}t                              d|            Y d }~nd }~ww xY w| |d<   	 t          j        t          j                            t                                d           t          t                      d          5 }t          j        ||           d d d            d S # 1 swxY w Y   d S # t          $ r2}t          d| rdnd	 d
| rdnd dt                                 |d }~ww xY w)Nz7Invalid ray config file, should be a json dict but got zFailed to load ray config file r@   T)exist_okwz
Failed to enabledisablez( usage stats by writing {"usage_stats": truefalsez} to )r   r   r   r   
isinstancer   rS   rT   typer   rR   r5   makedirsr   dirnamedump)r   r   r   rU   s       r!   r   r     sd   F<*,,-- 	"Yq\\F	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"&$'' 	LLX$v,,XX   F    < < <:q::;;;;;;;;< $F=
BGOO$<$>$>??$OOOO*,,c22 	!aIfa   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!   ,"1xx	, , !-vvg, ,
 ()), ,
 
 	s}   B A B  AB AAB 
C		C	"CC	AE -EE EE EE 
F'-FFc                 @    | rdndt           j        t          j        <   d S )Nr   r   )r5   environrP   r   )r   s    r!   r   r     s!    DK=TSSQTBJ~9:::r    c                    t          |          }|                     t          j        t	          j        |                                          dt          j                   |S )aF  Generate the cluster metadata and store it to GCS.

    It is a blocking API.

    Params:
        gcs_client: The GCS client to perform KV operation PUT.
        ray_init_cluster: Whether the cluster is started by ray.init()

    Raises:
        gRPC exceptions: If PUT fails.

    Returns:
        The cluster metadata.
    )r   T)	overwriterM   )	r   r{   rP   CLUSTER_METADATA_KEYr   dumpsrO   ray_constantsKV_NAMESPACE_CLUSTER)r_   r   r   s      r!   put_cluster_metadatar   	  sa     *;KLLLH+
8##%%4	     Or    c                 (   	 |                      dd          }d}|                                D ]-}|j        s$|j        j                            d          s|dz  }.|S # t          $ r(}t                              d|            Y d}~dS d}~ww xY w)zNReturn the total number of running jobs in the cluster excluding internal onesT)skip_submission_job_info_fieldskip_is_running_tasks_fieldr   _ray_internalr   z7Failed to query number of running jobs in the cluster: N)	get_all_job_infovaluesis_deadr   ray_namespace
startswithrR   rS   info)r_   r`   r:   job_inforU   s        r!   $get_total_num_running_jobs_to_reportr  "  s    ,,+/T - 
 
 "# 	, 	,H# ,HO,I,T,T- - , '!+&%%   QaQQRRRttttts   AA 
B)BBc                    	 |                      |t          j        j        j                  }t          |                                          S # t          $ r(}t          	                    d|            Y d}~dS d}~ww xY w)z5Return the total number of alive nodes in the cluster)timeoutstate_filterz0Failed to query number of nodes in the cluster: N)
get_all_node_infor   GcsNodeInfoGcsNodeStateALIVEr^   r   rR   rS   r  )r_   r  r`   rU   s       r!   #get_total_num_alive_nodes_to_reportr  4  s    --'*=*J*P . 
 
 6<<>>"""   JqJJKKKttttts   AA 
B A;;B c                 P    t          t          | t          j                            S rf   )listrc   rP   rg   r_   s    r!   get_library_usages_to_reportr  @  s    z>+PQQRRRr    c                 P    t          t          | t          j                            S rf   )r  rc   rP   rl   r  s    r!   get_hardware_usages_to_reportr  D  s    z>+QRRSSSr    c                    t                      }t          j        dd          }|r	 |                    d                              d          }|D ]}|                    d          \  }}|||<    n4# t
          $ r'}t                              d|            Y d}~nd}~ww xY wd t          	                                D             }	 | 
                    t          j                                        t          j                                                  }	|                     |	t          j                                                  }|                                D ]Y\  }
}|
                    d          }
|
t%          t          j                  d         }
|
|v sJ |                    d          ||
<   Zn4# t
          $ r'}t                              d	|            Y d}~nd}~ww xY w|S )
a  Get the extra usage tags from env var and gcs kv store.

    The env var should be given this way; key=value;key=value.
    If parsing is failed, it will return the empty data.

    Params:
        gcs_client: The GCS client.

    Returns:
        Extra usage tags as kv pairs.
    RAY_USAGE_STATS_EXTRA_TAGSN;=z*Failed to parse extra usage tags env var: c                 6    g | ]}|                                 S r   )rs   ).0tag_keys     r!   
<listcomp>z2get_extra_usage_tags_to_report.<locals>.<listcomp>`  s     CCC'gmmooCCCr    rL   rY   z.Failed to get extra usage tags from kv store: )r   r5   r   stripsplitrR   rS   r  rq   keysr[   rP   rz   rO   rQ   internal_kv_multi_getr   r\   r^   )r_   r8   extra_usage_tags_env_varkvskvr   r   rU   valid_tag_keysr  ro   rJ   s               r!   get_extra_usage_tags_to_reportr%  H  s5    vv!y)EtLL J	J*0055;;C@@C ( (xx}}1&' ##(  	J 	J 	JKKHQHHIIIIIIII	J DCV[[]]CCCNJ**188::$:AACC + 
 
 --N@GGII . 
 
 ((** 	: 	:JC**W%%Cc.?@@BBCC.(((($)LL$9$9S!!		:
  J J JHQHHIIIIIIIIJs1   A
A2 2
B#<BB#
C0F; ;
G,G''G,c                    ddl m} t                      }	  || j                  }|                                }t          |                    dd                    |_        t          |                    dd                    |_        d}|                    dd          |z  |_	        |                    dd          |z  |_
        n4# t          $ r'}t                              d|            Y d	}~nd	}~ww xY w|S # |c cY S xY w)
a+  
    Get the current status of this cluster. A temporary proxy for the
    autoscaler v2 API.

    It is a blocking API.

    Params:
        gcs_client: The GCS client.

    Returns:
        The current cluster status or empty ClusterStatusToReport
        if it fails to get that information.
    r   )get_cluster_statusCPUGPU      >memoryobject_store_memory'Failed to get cluster status to report N)ray.autoscaler.v2.sdkr'  r#   addresstotal_resourcesr   rv   r$   r%   r&   r'   rR   rS   r  )r_   r'  r`   cluster_statusr0  to_GiBrU   s          r!    _get_cluster_status_to_report_v2r3  s  s9    988888"$$F++J,>??(88:: #O$7$7q$A$A B B #O$7$7q$A$A B B!0!4!4Xq!A!AF!J 5q99FB 	++  C C CAaAABBBBBBBBC vs0   B2C	 C? 	
C:C50C? 5C::C? ?Dc                    	 ddl m}  |            rt          |           S |                     t          j        j        j                                        d          }|st                      S t                      }d}t          j        |                    d                    }d|vs
d|d         vrt                      S |d         d         }d	|v r t          |d	         d
                   |_        d|v r t          |d         d
                   |_        d|v r|d         d
         |z  |_        d|v r|d         d
         |z  |_        |S # t$          $ r5}t&                              d|            t                      cY d}~S d}~ww xY w)zGet the current status of this cluster.

    It is a blocking API.

    Params:
        gcs_client: The GCS client to perform KV operation GET.

    Returns:
        The current cluster status or empty if it fails to get that information.
    r   )is_autoscaler_v2NrL   r*  rY   load_metrics_reportrb   r(  r   r)  r+  r,  r-  )ray.autoscaler.v2.utilsr5  r3  internal_kv_getr   r   r   DEBUG_AUTOSCALING_STATUSrO   r#   r   loadsr\   r   r$   r%   r&   r'   rR   rS   r  )r_   r5  r1  r`   r2  rb   rU   s          r!   get_cluster_status_to_reportr;    s   &'<<<<<< 	@3J???#33L&?FFHH 4 
 
  	+(***&((N$9$9'$B$BCC!77n-BCCC(***45g>E>>$'eQ$8$8F!E>>$'eQ$8$8F!u%*8_Q%7&%@F" E))+,Q/&8 /  ' ' 'AaAABBB$&&&&&&&&'s1   E AE .AE BE 
F*FFFc                      dt           dt          t          t           t           f                  dt          fd} d}ddi}d}d	d
i}d}d } | ||          rdS  | ||          rdS  | ||          rdS dS )NurlheadersrW   c                     	 t          j        | |d          }|j        dk    rdS nI# t           j        j        $ r Y n3t
          $ r'}t                              d|            Y d }~nd }~ww xY wdS )Nr   )r>  r     TzBUnexpected exception when making cloud provider metadata request: F)requestsrv   status_code
exceptionsConnectionErrorrR   rS   r  )r=  r>  resrU   s       r!   cloud_metadata_requestz@get_cloud_from_metadata_requests.<locals>.cloud_metadata_request  s    	,sGQ???C #%%t & "2 	 	 	D 	 	 	KKXUVXX       	 us   "' A-	A-A((A-z?http://169.254.169.254/metadata/instance?api-version=2021-12-13Metadatar   z2http://metadata.google.internal/computeMetadata/v1zMetadata-FlavorGooglez(http://169.254.169.254/latest/meta-data/azuregcpawsunknown)r   r
   r   rC   )rF  AZURE_METADATA_URLAZURE_METADATA_HEADERSGCP_METADATA_URLGCP_METADATA_HEADERSAWS_METADATA_URLAWS_METADATA_HEADERSs          r!    get_cloud_from_metadata_requestsrS    s    C (4S>2J t    " 	J  )&1K-x8A02HII w		 02F	G	G u		 02F	G	G uyr    cluster_config_file_pathc                    d }	 t          |           5 }t          j        |          }t                      }d|v r|d         |_        d|v r|d         |_        d|v rd|d         v r|d         d         |_        d|vr|cddd           S d|vr|cddd           S |d         }|d         }|D ]}||k    r. |||                             d	                    }|r||_        6 |||                             d	                    }	|	r4|j	        pt                      |_	        |j	                            |	           |j	        rt          |j	                  |_	        |cddd           S # 1 swxY w Y   dS # t          $ r t                      }t          j        t           j        v r;t          j        t           j        v rt          j        |_        nt          j        |_        |j        t+                      |_        n|xj        d
t+                       z  c_        |cY S t,          $ r5}
t.                              d|
            t                      cY d}
~
S d}
~
ww xY w)a	  Get the static cluster (autoscaler) config used to launch this cluster.

    Params:
        cluster_config_file_path: The file path to the cluster config file.

    Returns:
        The cluster (autoscaler) config or empty if it fails to get that information.
    c                 v    | sd S d| v r| d         S d| v r| d         S d| v rd| d         v r| d         d         S d S )NInstanceTypemachineTypeazure_arm_parametersvmSizer   )node_configs    r!   get_instance_typez7get_cluster_config_to_report.<locals>.get_instance_type  sm     	4[((~..K''}--"k11K(>???56x@@tr    r   r   providerr   head_node_typeNavailable_node_typesr[  z_$z'Failed to get cluster config to report )r   yaml	safe_loadr   r   r   r   rv   r   r   rZ   r]   r  r   rP   KUBERNETES_SERVICE_HOST_ENVr5   r   KUBERAY_ENVPROVIDER_KUBERAYPROVIDER_KUBERNETES_GENERICrS  rR   rS   r  )rT  r\  r   r   r`   r^  r_  available_node_typer   worker_node_instance_typerU   s              r!   get_cluster_config_to_reportrh    si      ='*++ %	q^A&&F*,,F&&%+M%:"&&%+M%:"V##&2D(D(D(.z(:6(B%v--%	 %	 %	 %	 %	 %	 %	 %	 &V33%	 %	 %	 %	 %	 %	 %	 %	 $$45N#)*@#A '; Y Y#&.88.?.?,-@AEEmTT/ /+ / Q9P60A0A,-@AEEmTT1 1- 1 Y"=F 9 9==>WXXX0 4855 51 K%	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	 %	L    &(( 5CC)RZ77(6(G%% )7(R%  ($D$F$FF!!!!%N*J*L*L%N%NN!! ' ' 'AaAABBB$&&&&&&&&'sa   E< A+E/?E< E/E< CE/"E< /E33E< 6E37E< <B'I#%	I#.*II#I#c                     t          j        |                     t          j        t
          j                                      d                    S )af  Get the cluster metadata from GCS.

    It is a blocking API.

    This will return None if `put_cluster_metadata` was never called.

    Params:
        gcs_client: The GCS client to perform KV operation GET.

    Returns:
        The cluster metadata in a dictionary.

    Raises:
        RuntimeError: If it fails to obtain cluster metadata from GCS.
    rL   rY   )r   r:  r8  rP   r   r   r   r\   r  s    r!   get_cluster_metadatarj  I  sI      :""/#8 	# 	
 	
 &//	  r    c                 0    t          |           }|d         S )z3Return whether the cluster is started by ray.init()r   )rj  )r_   cluster_metadatas     r!   is_ray_init_clusterrm  a  s    +J77.//r    c                      t          t          j        t          j        t          j        t          j                  t          t          j                    dz                      } | S )z;Generate the report data indicating usage stats is disabledr   )r+   r,   r-   )	r*   rP   SCHEMA_VERSIONr5   r   USAGE_STATS_SOURCE_ENV_VARUSAGE_STATS_SOURCE_OSSr   r   )datas    r!   generate_disabled_report_datars  g  sV    %4y51
 
 !t!344  D Kr    cluster_config_to_reportr.   r/   r0   gcs_address
cluster_idc           	      $   |sJ t           j                            ||          }t          |          }t	          |          }t          di dt          j        dt          j	        t          j
        t          j                  dt          t          j                    dz            d|d|d|d	|d	         d
|d
         d|d|d         d|d         d|d         d| j        d| j        d| j        d| j        d| j        d|j        d|j        d|j        d|j        dt/          |          dt1          |          dt3          |          dt5          |          d|                    d          dt9          |          }	|	S )af  Generate the report data.

    Params:
        cluster_config_to_report: The cluster (autoscaler)
            config generated by `get_cluster_config_to_report`.
        total_success: The total number of successful report
            for the lifetime of the cluster.
        total_failed: The total number of failed report
            for the lifetime of the cluster.
        seq_number: The sequence number that's incremented whenever
            a new report is sent.
        gcs_address: the address of gcs to get data to report.
        cluster_id: hex id of the cluster.

    Returns:
        UsageStats
    )r/  rv  r+   r,   r-   r   r.   r/   r0   r1   r2   r3   r4   r5   r6   r   r   r   r   r   r$   r%   r&   r'   r7   r8   r9   r:   r;   r<   r   )r   _rayletr   rj  r;  r*   rP   ro  r5   r   rp  rq  r   r   r   r   r   r   r   r$   r%   r&   r'   r  r%  r  r  rv   r  )
rt  r.   r/   r0   ru  rv  r_   rl  cluster_status_to_reportrr  s
             r!   generate_report_datarz  t  sU   2 :&&{z&RRJ+J77;JGG   %44y51
 
 
 !t!3444 $m "\ : %]33 ((899 : $L11 D!! $44P#Q#Q  0>>!" -88#$ -88%& !9 P P'( $<#V#V)* 0>>+, 0>>-. 1@@/0 &>%Z%Z12 4J???34 8
CCC56 <JGGG78  DJOOO9: &)).999;< 6jAAA=D@ Kr    r@   rB   c                 .    t          | |du |          }|S )zGenerate the report data.

    Params:
        usage_stats: The usage stats that were reported.
        error: The error message of failed reports.

    Returns:
        UsageStatsToWrite
    N)r@   rA   rB   )r?   )r@   rB   rr  s      r!   generate_write_datar|    s,       D
 Kr    c                   :    e Zd ZdZdededdfdZdededdfdZdS )	UsageReportClientzThe client implementation for usage report.

    It is in charge of writing usage stats to the directory
    and report usage stats.
    rr  dir_pathrW   Nc                    t          |          }|t          j        z  }|t          j         dz  }|                    d          5 }|                    t          j        t          |                               ddd           n# 1 swxY w Y   t          j	        dk    r|
                    d           |                    |           dS )zWrite the usage data to the directory.

        Params:
            data: Data to report
            dir_path: The path to the directory to write usage data.
        z.tmpr   )r   Nwin32T)
missing_ok)r   rP   USAGE_STATS_FILEr   writer   r   r   r   r   unlinkrename)selfrr  r  destinationtemp	json_files         r!   write_usage_dataz"UsageReportClient.write_usage_data  s     >>!@@^<BBBBYYCY   	6IOODJvd||44555	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6<7"" $///K     s   5BBBr=  c                 ~    t          j        d|ddit          |          d          }|                                 |S )zReport the usage data to the usage server.

        Params:
            url: The URL to update resource usage.
            data: Data to report.

        Raises:
            requests.HTTPError: If requests fails.
        POSTzContent-Typezapplication/jsonr   )r>  r   r  )rA  requestr   raise_for_status)r  r=  rr  rs       r!   report_usage_dataz#UsageReportClient.report_usage_data  sO     #%78
 
 
 	
r    )	r   r   r   r=   r?   r   r  r*   r  r   r    r!   r~  r~    sr         !%6 !# !$ ! ! ! !&S 0B t      r    r~  rf   )rW   N)fr=   r   loggingr5   r   r   	threadingr   dataclassesr   r   enumr   r   pathlibr   typingr   r	   r
   r   rA  r`  r   !ray._common.usage.usage_constants_commonrb   usage_constantsrP   ray._private.ray_constantsr   r   ray._rayletr   ray.core.generatedr   r   ray.experimental.internal_kvr   r   	getLoggerr   rS   rq   r   r#   r*   r?   rE   rZ   r   Lockr   r   ru   rt   r   rV   rc   ri   rn   rx   rw   r~   r   r   r   r   r   r   _post_init_hooksappendr   r   r   r   rC   r   r   r   r   r   r   r   r   r   r  r  r  r  r%  r3  r;  rS  rh  rj  rx  rm  rs  rz  r|  r~  r   r    r!   <module>r     s"  * *V   				  



      ) ) ) ) ) ) ) )               , , , , , , , , , , , ,   



 : : : : : : : : : : : : 2 2 2 2 2 2 2 2 2 ! ! ! ! ! ! 1 1 1 1 1 1 1 1       
 
	8	$	$		 ; ; ; ; ; ; ; ; 9 9 9 9 9 9 9 9 :0 :0 :0 :0 :0 :0 :0 :0z                 D       355  .	 0 0 !TVV "0)."2"2 	L 	LC 	L 	L 	L 	L S    "Lc L L L LN N N N N
 @D1 1	11)1))<1 1 1 1D< <c <# <8I;N < < < < (# ( ( ( (* * * * *,* * *# # #% % %
, , ,   $ + +,D E E ER R RE E E  "4"7 "4 "4 "4 "4JO$ O O O OWT W W W WF F F!D ! ! ! !H-
 -
$ -
 -
 -
 -
`   @U U U UY T d    2    $	 	Xc] 	 	 	 	SS	 S S S STc T T T T(y (T#s(^ ( ( ( (V ?T    D1'Y 1';P 1' 1' 1' 1'h!# ! ! ! !HY'!Y'Y' Y' Y' Y'xY 4    00CK$9 0d 0 0 0 0
'9 
 
 
 
@3@@ @ 	@
 @ @ @ @ @ @F#    *, , , , , , , , , ,r    