
    &`ioQ                        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mZm	Z	 d dl
Z
d dlmZ d dlmZmZmZmZ d dlmZmZ d dlmZ  ej        e          ZdZd	Zd
ZdZdZdZdZ dZ!dZ"dZ#dZ$ G d d          Z%dee&ef         dee&ef         fdZ'de&dee&ef         fdZ(dee&ef         fdZ)dee&ef         dee&ef         fdZ*dee&ef         de+dee&ef         fdZ,dee&ef         de+dee&e-f         fdZ.dee&ef         dee&e&f         fd Z/d!ee&e&f         d"ee&e&f         d#ee&ee&e&f         f         d$e&de-f
d%Z0d!ee&e&f         d"ee&e&f         d#ee&ee&e&f         f         de	e-         fd&Z1d!ee&e&f         d"ee&e&f         d#ee&ee&e&f         f         d$e&de	e-         f
d'Z2d!ee&e&f         d(ee&e-f         d#ee&ee&e&f         f         de	e-         fd)Z3d*e&de-fd+Z4d!ee&e&f         d"ee&ef         d$e&dee&e-f         fd,Z5dS )-    N)chain)AnyDictOptional)validate_node_label_syntax)DISABLE_LAUNCH_CONFIG_CHECK_KEYDISABLE_NODE_UPDATERS_KEYFOREGROUND_NODE_LAUNCH_KEYWORKER_LIVENESS_CHECK_KEY)node_providerutils)validate_configautoscalerOptionsidleTimeoutSecondsupscalingMode
AggressiveDefaultConservative   z!cloud.google.com/gke-tpu-topologyz$cloud.google.com/gke-tpu-accelerator	headgroupc                   :    e Zd ZdZd Zd Zdeeef         fdZ	dS )AutoscalingConfigProducera  Produces an autoscaling config by reading data from the RayCluster CR.

    Used to fetch the autoscaling config at the beginning of each autoscaler iteration.

    In the context of Ray deployment on Kubernetes, the autoscaling config is an
    internal interface.

    The autoscaling config carries the strict subset of RayCluster CR data required by
    the autoscaler to make scaling decisions; in particular, the autoscaling config does
    not carry pod configuration data.

    This class is the only public object in this file.
    c                 N    t          j        |          | _        d| | _        d S )N)	namespacezrayclusters/)r   KubernetesHttpApiClientkubernetes_api_client_ray_cr_path)selfray_cluster_nameray_cluster_namespaces      /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/autoscaler/_private/kuberay/autoscaling_config.py__init__z"AutoscalingConfigProducer.__init__9   s8    %2%J+&
 &
 &
" >+;==    c                 L    |                                  }t          |          }|S )N)#_fetch_ray_cr_from_k8s_with_retries&_derive_autoscaling_config_from_ray_cr)r   ray_crautoscaling_configs      r!   __call__z"AutoscalingConfigProducer.__call__?   s'    99;;CFKK!!r#   returnc                 D   t          dt          dz             D ]}	 | j                            | j                  c S # t
          j        $ rL}|t          k     r4t                              d           t          j
        t                     n|dY d}~zd}~ww xY wt          )zFetch the RayCluster CR by querying the K8s API server.

        Retry on HTTPError for robustness, in particular to protect autoscaler
        initialization.
           z1Failed to fetch RayCluster CR from K8s. Retrying.N)rangeMAX_RAYCLUSTER_FETCH_TRIESr   getr   requests	HTTPErrorlogger	exceptiontimesleepRAYCLUSTER_FETCH_RETRY_SAssertionError)r   ies      r!   r%   z=AutoscalingConfigProducer._fetch_ray_cr_from_k8s_with_retriesD   s     q4q899 
	& 
	&A	&155d6GHHHHH% & & &111$$K   J78888% 98888& s   =BABBN)
__name__
__module____qualname____doc__r"   r)   r   strr   r%    r#   r!   r   r   *   s_         > > >" " "
T#s(^      r#   r   r'   r*   c                    t          | d         d                   }t          | d                   }t          d |                                D                       }t	                      }| d                             t          i           }t          |v r|t                   dz  }nd}|                    t                    t          k    rd}nN|                    t                    t          k    rd}n(|                    t                    t          k    rd}nd}|| d         d	         t          ||||d
|}t          |           |S )Nmetadatar   specc              3   &   K   | ]}|d          V  dS )max_workersNr?   ).0	node_types     r!   	<genexpr>z9_derive_autoscaling_config_from_ray_cr.<locals>.<genexpr>c   s8        %.	-      r#   g      N@g      ?r,   i  name)providercluster_namehead_node_typeavailable_node_typesrD   idle_timeout_minutesupscaling_speed)_generate_provider_config/_generate_available_node_types_from_ray_cr_specsumvalues*_generate_legacy_autoscaling_config_fieldsr/   AUTOSCALER_OPTIONS_KEYIDLE_SECONDS_KEYUPSCALING_KEYUPSCALING_VALUE_CONSERVATIVEUPSCALING_VALUE_DEFAULTUPSCALING_VALUE_AGGRESSIVE_HEAD_GROUP_NAMEr   )	r'   provider_configrL   global_max_workerslegacy_autoscaling_fieldsautoscaler_optionsrM   rN   r(   s	            r!   r&   r&   Z   sw   /z0B;0OPPOJv    2F2M2M2O2O    
 !K L L  ++,BBGG---12BCdJ"m,,0LLL				.	.2I	I	I				.	.2L	L	L $z*62* 4) !5 +  $  &'''r#   r    c                 F    ddd| t           dt          dt          dt          diS )zGenerates the `provider` field of the autoscaling config, which carries data
    required to instantiate the KubeRay node provider.
    typekuberayr   TF)r	   r   r
   r   )r    s    r!   rO   rO      s-    
 		*!4'"D!5 r#   c                      i g dg g g g g g i d
S )zEGenerates legacy autoscaling config fields required for compatibiliy.F)
file_mountscluster_synced_filesfile_mounts_sync_continuouslyinitialization_commandssetup_commandshead_setup_commandsworker_setup_commandshead_start_ray_commandsworker_start_ray_commandsauthr?   r?   r#   r!   rS   rS      s1      ").#%!!##%%'  r#   ray_cr_specc                 f    | d         }t           t          |d          id | d         D             S )z[Formats autoscaler "available_node_types" field based on the Ray CR's group
    specs.
    headGroupSpecTis_headc                 >    i | ]}|d          t          |d          S )	groupNameFrp   )_node_type_from_group_spec)rE   worker_group_specs     r!   
<dictcomp>zC_generate_available_node_types_from_ray_cr_spec.<locals>.<dictcomp>   sF     
 
 
 " k*,F!5- - -
 
 
r#   workerGroupSpecs)rZ   rt   )rm   ro   s     r!   rP   rP      sT      0M4]DQQQ
 
 &11C%D	
 
 
 r#   
group_specrq   c                 :   |rdx}}n>| d         |                      dd          z  }| d         |                      dd          z  }t          | |          }t          |           }||i ||d}|                      t                    }|t	          |          |d<   |S )	z/Converts CR group spec to autoscaler node type.r   minReplicas
numOfHostsr,   maxReplicas)min_workersrD   node_config	resourceslabelsNidle_timeout_s)r/   "_get_ray_resources_from_group_spec_get_labels_from_group_specrU   float)rx   rq   r}   rD   r   r   rF   r   s           r!   rt   rt      s      R$%%kk !/*..q2Q2QQ /*..q2Q2QQ2:wGGI(44F #"  I  ^^$455N!&+N&;&;	"#r#   c                    |                      di           }|                      di           }| d         d         d         d                              di           }|rt          n| d         }t          ||||          }t          ||||          }t	          |||          }t          |||          }	t          |||          }
i }t          |t                    sJ ||d<   |||d
<   |	d|vr|	|d<   	 d| d         d         v rt          | d         d         d         v rzt          | d         d         d         v r_| d         d         d         t                   }| d         d         d         t                   }t          j        ||          }|r	d|d| d<   n+t                              dt           dt           d           |
|
|d<   |                    |           |S )z
    Infers Ray resources from group `Resources` field, rayStartCommands, or K8s limits.
    The resources extracted are used in autoscaling calculations.
    r   rayStartParamstemplaterB   
containersr   rs   CPUNGPUTPUnodeSelectorr,   zTPU-z-headzPods using TPUs require both `z` and `z` node selectors. See https://docs.ray.io/en/latest/cluster/kubernetes/user-guides/tpu.html#configuring-ray-pods-for-tpu-usage and https://cloud.google.com/kubernetes-engine/docs/how-to/tpus.memory)r/   rZ   _get_num_cpus_get_num_gpus_get_custom_resources_get_num_tpus_get_memory
isinstanceintGKE_TPU_TOPOLOGY_LABELGKE_TPU_ACCELERATOR_LABELr   tpu_node_selectors_to_typer2   errorupdate)rx   rq   group_resourcesray_start_paramsk8s_resources
group_namenum_cpusnum_gpuscustom_resource_dictnum_tpusr   r   topologyacceleratoraccelerator_types                  r!   r   r      sg    !nn["55O!~~&6;;z*62<@CGGUWXXM%,I!!*[2IJ)=* H )=* H 1):  _.BMRRH*:MJJF
 Ih$$$$$Ie#	% ,,,'Ie
	 j4V<<<&*Z*@*H*XXX)*%f-n=> > "*-f5nE&H %Z08H)K  %?+VV ><=	8!18889LLS1G S SPi S S S   $	()***r#   c                 @   i }|                      di           }|                     d          }|rt                              d| d           d| v rLt          |                      d          t                    r$|                      d          }t          |           |S )z
    Parses Ray node labels for the autoscaling config based on the following
    priority:
    1. Top-level `labels` field in the group spec.
    2. `labels` field in `rayStartParams`.
    r   r   zIgnoring labels: zi set in rayStartParams. Group labels are supported in the top-level Labels field starting in KubeRay v1.5)r/   r2   warningr   dictr   )rx   labels_dictr   
labels_strs       r!   r   r   7  s     K!~~&6;;!%%h//J 
 V
  V  V  V	
 	
 	

 :*Z^^H-E-Et"L"L nnX..";///r#   r   r   r   r   c                    d| v r=d|v r$t                               d| d          d           t          | d                   S d|v rt          |d                   S d|                    di           v r|d         d         }t          |          S d|                    di           v r|d         d         }t          |          S t          d| d	          )
z{Get CPU annotation from `resources` field, ray_start_params or k8s_resources,
    with priority for `resources` field.
    r   znum-cpuszs'CPU' specified in both the top-level 'resources' field and in 'rayStartParams'. Using the value from 'resources': .cpulimitsr0   z6Autoscaler failed to detect `CPU` resources for group zY.
Set the `--num-cpus` rayStartParam and/or the CPU resource limit for the Ray container.)r2   r   _round_up_k8s_quantityr   r/   
ValueError)r   r   r   r   cpu_quantitys        r!   r   r   P  s     )))NNO5DU5KO O O   &oe&<===%%%#J/000	-##Hb11	1	1)(3E:%l333	-##J33	3	3)*5e<%l333 <Z < < <
 
 	
r#   c                    d| v r=d|v r$t                               d| d          d           t          | d                   S d|v rt          |d                   S d|                    di           v r|d         d         }t          |          S d|                    di           v r|d         d         }t          |          S dS )zGet memory resource annotation from `resources` field, ray_start_params or k8s_resources,
    with priority for `resources` field.
    r   zv'memory' specified in both the top-level 'resources' field and in 'rayStartParams'. Using the value from 'resources': r   r   r0   N)r2   r   r   r   r/   )r   r   r   memory_quantitys       r!   r   r   q  s     ?""'''NNR5DX5NR R R   &oh&?@@@####H-...	]&&x44	4	4,X6x@%o666	]&&z266	6	6,Z8B%o6664r#   c                    d| v r=d|v r$t                               d| d          d           t          | d                   S d|v rt          |d                   S t	          |                    di                                           |                    di                                                     D ]3\  }}|                    d          rt          |          }|dk    r|c S 4d	S )
zGet GPU resource annotation from `resources` field, ray_start_params or k8s_resources,
    with priority for `resources` field.
    r   znum-gpuszs'GPU' specified in both the top-level 'resources' field and in 'rayStartParams'. Using the value from 'resources': r   r   r0   gpur   N)r2   r   r   r   r   r/   itemsendswith)r   r   r   r   keyresource_quantityr   s          r!   r   r     s#    )))NNO5DU5KO O O   &oe&<===	'	'	'#J/000&+h++1133j"--3355'
 '
 	$ 	$"C"
 ||E"" $ 22CDDa<< $OOO4r#   r   c                     d| v rt          | d                   S d|v r|d         S dD ]F}|                    |i                               d          }|t          |          }|dk    r|c S GdS )zGet TPU custom resource annotation from `resources` field, custom_resource_dict in ray_start_params,
    or k8s_resources, with priority for `resources` field.
    r   )r   r0   zgoogle.com/tpuNr   )r   r/   )r   r   r   typtpu_resource_quantityr   s         r!   r   r     s     %oe&<===	&	&	&#E**) 	$ 	$C$1$5$5c2$>$>$B$BCS$T$T!$0 22GHHa<<#OOO4r#   quantityc                     t          j        |           }|                    t          j                  }t          |          S )zRounds a Kubernetes resource quantity up to the nearest integer.

    Args:
        quantity: Resource quantity as a string in the canonical K8s form.

    Returns:
        The quantity, rounded up, as an integer.
    )rounding)r   parse_quantityto_integral_valuedecimalROUND_UPr   )r   resource_decimalroundeds      r!   r   r     s:     ).(<X(F(F00':J0KKGw<<r#   c                   
 | r|d|v rt                               d|  d           h d
	 
fd|                                 D             }n2# t          $ r%}t                               d| d           |d}~ww xY w|S d|vri S |d         }	 |d	d
                             dd          }t          j        |          }t          |t                    sJ |                                D ]3\  }}	t          |t                    sJ t          |	t                    sJ 4n2# t          $ r%}t                               d| d           |d}~ww xY w|S )ah  Format custom resources based on the group `resources` field or `resources` Ray start param.

    Currently, the value of the rayStartParam `resources` field must
    be formatted as follows:
    '"{"Custom1": 1, "Custom2": 5}"'.

    This method first converts the input to a correctly formatted
    json string and then loads that json string to a dict.
    r   zcustom resources specified in both the top-level 'resources' field and in 'rayStartParams'. Using the values from 'resources': r   >   r   r   r   r   c                 >    i | ]\  }}|v	|t          |          S r?   )r   )rE   kvstandard_keyss      r!   rv   z)_get_custom_resources.<locals>.<dictcomp>  s=          AqM)) )!,,)))r#   z#Error reading `resource` for group z. For the correct format, refer to example configuration at https://github.com/ray-project/ray/blob/master/python/ray/autoscaler/kuberay/ray-cluster.complete.yaml.Nr,   \ z1Error reading `resource` rayStartParam for group )r2   r   r   	Exceptionr   replacejsonloadsr   r   r>   r   )r   r   r   custom_resourcesr9   resources_stringresources_jsonr   r   valuer   s             @r!   r   r     s      ***NNI6EI I I   877	       +1133     
  	 	 	LLDj D D D   G	   ***	'4 *!B$/77bAAJ~..	)T*****#//++ 	* 	*JCc3'''''eS))))))	*    @
 @ @ @	
 	
 	
  s0    A 
A; A66A;BD! !
E+ EE)6r   r   loggingr4   	itertoolsr   typingr   r   r   r0   ray._private.label_utilsr   !ray.autoscaler._private.constantsr   r	   r
   r   ray.autoscaler._private.kuberayr   r   ray.autoscaler._private.utilr   	getLoggerr:   r2   rT   rU   rV   rY   rX   rW   r.   r6   r   r   rZ   r   r>   r&   rO   rS   rP   boolrt   r   r   r   r   r   r   r   r   r   r?   r#   r!   <module>r      s             & & & & & & & & & &                  A @ @ @ @ @ @ @ 8 8 8 8 8 8		8	$	$, ' ) # -   < B   - - - - - - - -`44S> 4d3PS8n 4 4 4 4nS T#s(^    DcN     c3h	#s(^   $S#X)-	#s(^   BRS#XR)-R	#s(^R R R RjDcN tCH~    2
#s(^
38n
 T#s(^+,
 	

 	
 
 
 
B#s(^38n T#s(^+, c]	   4!#s(^!38n! T#s(^+,! 	!
 c]! ! ! !H#s(^sCx. T#s(^+, c]	   2S S    :#s(^:7;CH~:SV:	#s(^: : : : : :r#   