
    &`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 d dlm	Z	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mZ d dlmZmZ d dlmZ d d	lmZ d d
lmZmZ d dlm Z m!Z!m"Z"m#Z#m$Z$m%Z% d dl&m'Z' d dl(m)Z)m*Z*m+Z+m,Z, d dl-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z>m?Z?m@Z@mAZA d dlBmCZC d dlDmEZEmFZFmGZG d dlHmIZI d dlJmKZLmMZNmOZPmQZQmRZSmTZU d dlVmWZWmMZMmXZXmYZYmZZZm[Z[m\Z\ d dl]m^Z^  ej_        e,          Z`dZa G d de          Zbe
 G d d                       Zc e
d!"           G d# d$                      ZO e
d!"           G d% d&                      ZTe
 G d' d(                      Zd G d) d*          Ze G d+ d,          Zf ejg        d d-.          d/ehd0ehd1ehd2ed3e[d4eeh         d5eehehf         d6eehehf         d7eeei         eee                  eeh         f         fd8            Zj	 	 d>d9eehe2f         d:ee\         d;eeeheif                  d<eeeheif                  d7eehe2f         f
d=ZkdS )?    N)deepcopy)asdict	dataclassfield)Enum)DictListOptionalTuple)cloudpickle)import_attrimport_module_and_attr)RuntimeEnvSetupError)AutoscalingStateManager)BuiltApplication	build_app)DeploymentIDDeploymentStatusDeploymentStatusInfoDeploymentStatusTriggerEndpointInfoTargetCapacityDirection)DeploymentConfig)DEFAULT_AUTOSCALING_POLICY_NAMEDEFAULT_REQUEST_ROUTER_PATHRAY_SERVE_ENABLE_TASK_EVENTSSERVE_LOGGER_NAME)deploy_args_to_deployment_infoget_app_code_versionget_deploy_args)DeploymentInfo)DeploymentStateManager)EndpointState)configure_component_logger)KVStoreBase)ServeUsageTag)DEFAULTcheck_obj_ref_ready_nowait%override_runtime_envs_except_env_varsvalidate_route_prefix)ASGIAppReplicaWrapper)AutoscalingConfigAutoscalingPolicyRequestRouterConfig)RayServeException)ApplicationArgsApplicationStatusApplicationStatusInfoDeploymentLanguageDeploymentStatusInfoListStatusOverview)APITyper1   DeploymentDetailsDeploymentNodeDeploymentTopologyLoggingConfigServeApplicationSchema)	ObjectRefz"serve-application-state-checkpointc                   "    e Zd ZdZdZdZdZdZdS )BuildAppStatusz%Status of the build application task.            N)__name__
__module____qualname____doc__NO_TASK_IN_PROGRESSIN_PROGRESS	SUCCEEDEDFAILED     x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/serve/_private/application_state.pyr>   r>   M   s)        //KIFFFrL   r>   c                   h    e Zd ZU dZeed<   eed<   eed<   ee	         ed<   ee
         ed<   eed<   dS )	BuildAppTaskInfoa8  Stores info on the current in-progress build app task.

    We use a class instead of only storing the task object ref because
    when a new config is deployed, there can be an outdated in-progress
    build app task. We attach the code version to the task info to
    distinguish outdated build app tasks.
    obj_refcode_versionconfigtarget_capacitytarget_capacity_directionfinishedN)rC   rD   rE   rF   r<   __annotations__strr;   r
   floatr   boolrK   rL   rM   rO   rO   V   sk           """"e_$$$'(?@@@@NNNNNrL   rO   T)eqc                   ^    e Zd ZU eed<   dZeed<   dZeed<   d Z	d Z
edefd	            Zd
S )r2   status messager   deployment_timestampc                 H    t          j        t          |           d          S NrB   )indentjsondumpsr   selfs    rM   debug_stringz"ApplicationStatusInfo.debug_stringn       z&,,q1111rL   c                 T    t          d| j        j         | j        | j                  S NAPPLICATION_STATUS_)r\   r^   r_   )ApplicationStatusInfoProtor\   namer^   r_   rf   s    rM   to_protozApplicationStatusInfo.to_protoq   s4    );)9;;L!%!:
 
 
 	
rL   protoc                     t          j        |j                  t          d          d          } | t	          |          |j        |j                  S rk   )ApplicationStatusProtoNamer\   lenr1   r^   r_   )clsrp   r\   s      rM   
from_protoz ApplicationStatusInfo.from_protox   sW    ',U\::3?T;U;U;W;WXs$V,,M!&!;
 
 
 	
rL   N)rC   rD   rE   r1   rV   r^   rW   r_   rX   rh   ro   classmethodrm   rv   rK   rL   rM   r2   r2   h   s         GS"#%###2 2 2
 
 
 
9 
 
 
 [
 
 
rL   r2   c                       e Zd ZU eed<   dZeed<    ee          Z	e
e         ed<   d Zdedee         fdZd	 Zed
edd fd            ZdS )r5   
app_statusr]   rn   )default_factorydeployment_statusesc                 H    t          j        t          |           d          S ra   rc   rf   s    rM   rh   zStatusOverview.debug_string   ri   rL   returnc                 8    | j         D ]}||j        k    r|c S dS )zGet a deployment's status by name.

        Args:
            name: Deployment's name.

        Returns:
            Optional[DeploymentStatusInfo]: The status of the deployment if it exists,
                otherwise None.
        N)r{   rn   )rg   rn   deployment_statuss      rM   get_deployment_statusz$StatusOverview.get_deployment_status   s>     "&!9 	) 	)(---(((( . trL   c                     | j                                         }t          d | j                  }t	                      }|j                            |           t          | j        ||          S )Nc                 *    |                                  S N)ro   )r\   s    rM   <lambda>z)StatusOverview.to_proto.<locals>.<lambda>   s    6??,, rL   )rn   ry   r{   )	ry   ro   mapr{   DeploymentStatusInfoListProtodeployment_status_infosextendStatusOverviewProtorn   )rg   app_status_protodeployment_status_protosdeployment_status_proto_lists       rM   ro   zStatusOverview.to_proto   s    ?3355 $',,d.F$
 $
 
 (E'F'F$$<CC$	
 	
 	

 #' <
 
 
 	
rL   rp   c                     t                               |j                  }g }|j        j        D ])}|                    t          j        |                     * | |||j                  S )N)ry   r{   rn   )r2   rv   ry   r{   r   appendr   rn   )ru   rp   ry   r{   
info_protos        rM   rv   zStatusOverview.from_proto   s     +55e6FGG
 !3K 	T 	TJ&&';'Fz'R'RSSSS s! 3
 
 
 	
rL   N)rC   rD   rE   r2   rV   rn   rW   r   listr{   r	   r   rh   r
   r   ro   rw   r   rv   rK   rL   rM   r5   r5      s         %%%%D#NNN6;eD6Q6Q6Q23QQQ2 2 2# (;O2P    "
 
 
, 
2 
7G 
 
 
 [
 
 
rL   r5   c                       e Zd ZU dZeeeef                  ed<   ee         ed<   ee	         ed<   ee
         ed<   ee         ed<   eed<   eed<   ee         ed	<   eed
<   dS )ApplicationTargetStatea:  Defines target state of application.

    Target state can become inconsistent if the code version doesn't
    match that of the config. When that happens, a new build app task
    should be kicked off to reconcile the inconsistency.

    deployment_infos: map of deployment name to deployment info. This is
      - None if a config was deployed but the app hasn't finished
        building yet,
      - An empty dict if the app is deleting.
    code_version: Code version of all deployments in target state. None
        if application was deployed through serve.run.
    config: application config deployed by user. None if application was
        deployed through serve.run.
    target_capacity: the target_capacity to use when adjusting num_replicas.
    target_capacity_direction: the scale direction to use when
        running the Serve autoscaler.
    deleting: whether the application is being deleted.
    external_scaler_enabled: whether external autoscaling is enabled for
        this application.
    serialized_application_autoscaling_policy_def: Optional[bytes]
    deployment_infosrQ   rR   rS   rT   deletingapi_type-serialized_application_autoscaling_policy_defexternal_scaler_enabledN)rC   rD   rE   rF   r
   r   rW   r!   rV   r;   rX   r   rY   r6   bytesrK   rL   rM   r   r      s          . tC$7899993-+,,,,e_$$$'(?@@@@NNN3;E?BBB!!!!!!rL   r   c                      e Zd ZdZdededededede	fdZ
ed	ee         fd
            Zed	e	fd            Zed	ee         fd            Zed	efd            Zed	efd            Zed	ee         fd            Zed	ee         fd            Zed	efd            ZdefdZdddddddeeeef                  dedee         dee         dee         dee         de	de	dee         fdZ d  Z!dee         fd!Z"ded	e	fd"Z#d# Z$d	e	fd$Z%d	e	fd%Z&d	e	fd&Z'd'ed(ed	e	fd)Z(deeef         de	fd*Z)d+edee         dee         d,ed	df
d-Z*d	ee         fd.Z+d	e,eef         fd/Z-d	e,ee         ee         e.ef         fd0Z/deeef         d	e,eef         fd1Z0d=d2Z1d	ee2         fd3Z3d	e,e	e	f         fd4Z4d	efd5Z5d	ee6         fd6Z7d	e8fd7Z9d	eee:f         fd8Z;d>d:ed;ed	dfd<Z<dS )?ApplicationStatez4Manage single application states with all operationsrn   deployment_state_managerautoscaling_state_managerendpoint_statelogging_configr   c                 $   || _         d| _        || _        || _        || _        d| _        d| _        t          j        | _	        t          j
                    | _        d| _        t          ddddddt          j        |d	  	        | _        || _        dS )a  
        Initialize an ApplicationState instance.

        Args:
            name: Application name.
            deployment_state_manager: Manages the state of all deployments in the cluster.
            autoscaling_state_manager: Manages autoscaling decisions in the cluster.
            endpoint_state: Manages endpoints in the system.
            logging_config: Logging configuration schema.
            external_scaler_enabled: Whether external autoscaling is enabled for
                this application.
        r]   NF)	r   rQ   rR   rS   rT   r   r   r   r   )_name_status_msg_deployment_state_manager_autoscaling_state_manager_endpoint_state_route_prefix_ingress_deployment_namer1   	DEPLOYING_statustime_deployment_timestamp_build_app_task_infor   r6   UNKNOWN_target_state_logging_config)rg   rn   r   r   r   r   r   s          rM   __init__zApplicationState.__init__   s    , 
)A&*C'-,07;%*;*E%)Y[["@D! 6L! &*_$;:>
6
 
6
 
6
  .rL   r}   c                     | j         S r   )r   rf   s    rM   route_prefixzApplicationState.route_prefix  s    !!rL   c                     | j         j        S r   )r   r   rf   s    rM   r   z(ApplicationState.external_scaler_enabled   s    !99rL   c                 j    t          | j        | j                  }| j                            |          S r   )r   r   r   r   get_deployment_docs_path)rg   ingress_deployments     rM   	docs_pathzApplicationState.docs_path$  s7    
 *$*GTT-FF
 
 	
rL   c                     | j         S )a  Status of the application.

        DEPLOYING: The build task is still running, or the deployments
            have started deploying but aren't healthy yet.
        RUNNING: All deployments are healthy.
        DEPLOY_FAILED: The build task failed or one or more deployments
            became unhealthy in the process of deploying
        UNHEALTHY: While the application was running, one or more
            deployments transition from healthy to unhealthy.
        DELETING: Application and its deployments are being deleted.
        )r   rf   s    rM   r\   zApplicationState.status.  s     |rL   c                     | j         S r   )r   rf   s    rM   r_   z%ApplicationState.deployment_timestamp=  s    ))rL   c                 t    | j         j        g S t          | j         j                                                  S )z/List of target deployment names in application.)r   r   r   keysrf   s    rM   target_deploymentsz#ApplicationState.target_deploymentsA  s5     .6ID&7<<>>???rL   c                     | j         S r   )r   rf   s    rM   r   z#ApplicationState.ingress_deploymentH  s    ,,rL   c                     | j         j        S r   )r   r   rf   s    rM   r   zApplicationState.api_typeL  s    !**rL   checkpoint_datac           
         t                               d| j         d           |                     |j        |j        |j        |j        |j        |j	        |j
        |j                   |j        |                     |j                  | _        |j        rI|j        j        ?| j                            | j        t#          dd|j        i|j        j                   d S d S d S )Nz)Recovering target state for application 'z' from checkpoint.)r   rQ   target_configrS   rT   r   r   _serialized_policy_defrK   )loggerinfor   _set_target_stater   r   rQ   rR   rS   rT   r   r   _check_routesr   autoscaling_policyr   register_applicationr-   r   )rg   r   s     rM   $recover_target_state_from_checkpointz5ApplicationState.recover_target_state_from_checkpointP  s    	V
VVV	
 	
 	
 	,$-(5)0+;&5&O$-$3$K 	 		
 		
 		
 +7!%!3!3O4T!U!UD "
	&9E+@@
!  +:+h%,?     	
	 
	EErL   NF)rS   rT   r   r   r   r   r   rQ   r   rS   rT   r   r   c                *   |r |                      t          j                   n|                      t          j                   |d| _        n(|                                D ]\  }
}|j        r|
| _        t          |||||||||		  	        }|| _        dS )ac  Set application target state.

        While waiting for build task to finish, this should be
            (None, False)
        When build task has finished and during normal operation, this should be
            (target_deployments, False)
        When a request to delete the application has been received, this should be
            ({}, True)
        N)r   r   r   )	_update_statusr1   DELETINGr   r   itemsingressr   r   )rg   r   r   rQ   r   rS   rT   r   r   r   rn   r   target_states                rM   r   z"ApplicationState._set_target_states  s    ,  	= 1 :;;;; 1 ;<<<#,0D)).4466 9 9
d< 948D1-%$;:g

 

 

 *rL   c                 Z    |                      i | j        j        ddd| j                   dS )zlSet target state to deleting.

        Wipes the target deployment infos, code version, and config.
        NTr   r   rQ   r   r   r   )r   r   r   r   rf   s    rM   _set_target_state_deletingz+ApplicationState._set_target_state_deleting  sF    
 	'0$($@ 	 	
 	
 	
 	
 	
rL   c                 b    |                      dt          j        d|d|r|j        nd           dS )zClears the target state and stores the config.

        NOTE: this currently assumes that this method is *only* called when managing
        apps deployed with the declarative API.
        NFr   )r   r6   DECLARATIVEr   )rg   r   s     rM   $_clear_target_state_and_store_configz5ApplicationState._clear_target_state_and_store_config  sP     	!('%M$I$I 	 		
 		
 		
 		
 		
rL   c                     t          || j                  }| j                            |           | j                            |          S )zDelete a deployment in the application.

        Args:
            name: The name of the deployment to delete.

        Returns:
            Whether the target state has changed.
        rn   app_name)r   r   r   delete_endpointr   delete_deployment)rg   rn   ids      rM   _delete_deploymentz#ApplicationState._delete_deployment  sF     tdj999,,R000-??CCCrL   c                     | j         t          j        k    r't                              d| j         dddi           |                                  dS )zDelete the applicationzDeleting app ''.log_to_stderrF)extraN)r   r1   r   r   r   r   r   rf   s    rM   deletezApplicationState.delete  s`    <,555KK////&.     	'')))))rL   c                 d    | j         j        o$t          |                                           dk    S )zCheck whether the application is already deleted.

        For an application to be considered deleted, the target state has to be set to
        deleting and all deployments have to be deleted.
        r   )r   r   rt   _get_live_deploymentsrf   s    rM   
is_deletedzApplicationState.is_deleted  s/     !*Us43M3M3O3O/P/PTU/UUrL   c                 @    | j                             | j                  S )zDetermine if autoscaling is enabled for the application.

        Returns:
            Autoscaling is enabled for the application if any of the deployments have autoscaling enabled.
        )r   should_autoscale_applicationr   rf   s    rM   should_autoscalez!ApplicationState.should_autoscale  s     .KKDJWWWrL   c                    | j         }t          |          dk    rdS i }|D ]:}t          || j                  }| j                            |          }|5|||<   ;t          |          dk    rdS | j                            | j        |          }d}|                                D ]"\  }}| j        	                    ||          p|}#|S )a3  
        Apply the autoscaling decisions for the application.
        If the application has deployment-level autoscaling, it will apply the autoscaling decisions for each deployment.

        Returns:
            True if there is a change to number of replicas for any deployment. False otherwise.
        r   Fr   )
r   rt   r   r   r   "get_deployment_target_num_replicasr   get_decision_num_replicasr   	autoscale)	rg   r   !deployment_to_target_num_replicasdeployment_namedeployment_idtarget_num_replicas	decisionstarget_state_changeddecision_num_replicass	            rM   r   zApplicationState.autoscale  s#    "4!""a''5EG)1 		S 		SO(o
SSSM.QQ!   
 #*?R-m<<011Q665 +EEJ9
 
 	  %4=OO4E4E 	 	0M0.88!#8  ( (	 !  $#rL   r   deployment_infoc                    |j         }|(|                    d          st          d| d          t          || j                  }| j                            ||          }|j         e|j        }| j                            |          }| j	        
                    |t          |j         |j        t          j        k    |                     n| j	                            |           |S )a  Deploys a deployment in the application.

        Args:
            deployment_name: The name of the deployment to apply.
            deployment_info: The deployment info to apply.

        Returns:
            Whether the target state has changed.
        N/zInvalid route prefix "z", it must start with "/"r   )routeapp_is_cross_languageroute_patterns)r   
startswithr/   r   r   r   deploydeployment_configget_deployment_route_patternsr   update_endpointr   deployment_languager3   PYTHONr   )rg   r   r   r   r   r   rR   r   s           rM   apply_deployment_infoz&ApplicationState.apply_deployment_info  s    '3#L,C,CC,H,H##PPPP   %/DJOOO#=DD? 
  
 '3$6F .LL!  
  00 )6*0*D)0+1#1	        00???##rL   c           	          |                      |          | _        |                     |t          j        dddd|           dS )a%  (Re-)deploy the application from list of deployment infos.

        This function should only be called to deploy an app from an
        imperative API (i.e., `serve.run` or Java API).

        Raises: RayServeException if there is more than one route prefix
            or docs path.
        N)r   r   rQ   r   rS   rT   r   )r   r   r   r6   
IMPERATIVE)rg   r   r   s      rM   
deploy_appzApplicationState.deploy_appM  sZ     "//0@AA-' &*$; 	 	
 	
 	
 	
 	
rL   rR   deployment_timec           
      "   || _         t          |          }|| j        j        k    r-	 t	          | j        j        |          }|                     |          | _        |                     | j        j        t          j
        |||||j                   d
S # t          t          t          f$ rJ |                     |           |                     t"          j        t'          j                               Y d
S t*          $ rU |                     |           |                     t"          j        d| j         dt'          j                                Y d
S w xY w| j        rM| j        j        sAt2                              d| j         d           t7          j        | j        j                   |                     |           | j        j        j                             d          s$| j        j        j                             d          rtB          j"        #                    d           tI          |j%        tL                    r|j%                             d	          }nd
}d |j'        D             }d |j'        D             }	t2                              d| j         d           tP          )                    |j        tT                    +                    |j,        ||j-        |j.        | j/        |||	          }
ta          |
||||d          | _        d
S )a  Apply the config to the application.

        If the code version matches that of the current live deployments
        then it only applies the updated config to the deployment state
        manager. If the code version doesn't match, this will re-build
        the application.

        This function should only be called to (re-)deploy an app from
        the declarative API (i.e., through the REST API).
        )rQ   r   r   r   rS   rT   r   AUnexpected error occurred while applying config for application '': 
z%Received new config for application 'z'. Cancelling previous request.	container	image_uri1policy_functionNc                     i | ]V}t          |j        t                    |j        |j                            d i                               dt
                    WS )policyr
  )
isinstanceautoscaling_configdictrn   getr   .0
deployments     rM   
<dictcomp>z5ApplicationState.apply_app_config.<locals>.<dictcomp>  sj     9 9 9 j;TBB9!>!B!B8R!P!P!T!T%'F" "9 9 9rL   c                     i | ]B}t          |j        t                    |j        |j                            d t
                    CS )request_router_class)r  request_router_configr  rn   r  r   r  s     rM   r  z5ApplicationState.apply_app_config.<locals>.<dictcomp>  sZ     0 0 0 j>EE0!A!E!E*,G" "0 0 0rL   zImporting and building app 'r   )runtime_envenable_task_eventsF)rP   rQ   rR   rS   rT   rU   )1r   r   r   rQ   override_deployment_infor   r   r   r   r6   r   r   	TypeError
ValueErrorr/   r   r   r1   DEPLOY_FAILED	traceback
format_exc	Exceptionr   r   rU   r   r   raycancelrP   rR   r  r  r&   APP_CONTAINER_RUNTIME_ENV_USEDrecordr  r   r  deploymentsbuild_serve_applicationoptionsr   remoteimport_pathrn   argsr   rO   )rg   rR   rS   rT   r  config_versionoverrided_infos'application_autoscaling_policy_function)deployment_to_autoscaling_policy_function deployment_to_request_router_clsbuild_app_obj_refs              rM   apply_app_configz!ApplicationState.apply_app_configh  s   $ &5"-f55T/<<<":&7# # &*%7%7%H%H"&&!%!3!@$0%4"($3.G,2,J ' 
 
 
 
 
 z+<=   99&AAA##%3Y5I5K5K         99&AAA##%3R(,
R R9B9M9O9OR R      ( >1J1S >3DJ 3 3 3   
44<=== 55f=== !(488  I#*6::;GGI <CCCHHH&3T:: ?:@:S:W:W%; ;77 ;?79 9 #)"4	9 9 950 0 #)"4	0 0 0, KKEtzEEEFFF 7 ? ?".#? !@ ! ! f"$790	 	  )9)+ /*C) ) )D%%%s   A)B AE4AEEc                 @    | j                             | j                  S r   )r   get_deployments_in_applicationr   rf   s    rM   r   z&ApplicationState._get_live_deployments  s    -LLTZXXXrL   c                 4   | j         j        rt          j        dfS |                                 }t          |d           }|j        t          j        k    rd |D             }t          j        d| dfS |j        t          j	        k    rd |D             }t          j	        d| d	fS |j        t          j
        k    rt          j        dfS |j        t          j        t          j        fv r#|j        t          j        k    rt          j        dfS t          j        dfS )
a  Check deployment statuses and target state, and determine the
        corresponding application status.

        Returns:
            Status (ApplicationStatus):
                RUNNING: all deployments are healthy or autoscaling.
                DEPLOYING: there is one or more updating deployments,
                    and there are no unhealthy deployments.
                DEPLOY_FAILED: one or more deployments became unhealthy
                    while the application was deploying.
                UNHEALTHY: one or more deployments became unhealthy
                    while the application was running.
                DELETING: the application is being deleted.
            Error message (str):
                Non-empty string if status is DEPLOY_FAILED or UNHEALTHY
        r]   c                     | j         S r   )rank)r   s    rM   r   z8ApplicationState._determine_app_status.<locals>.<lambda>  s    ty rL   )keyc                 F    g | ]}|j         t          j        k    |j        S rK   )r\   r   r  rn   r  ss     rM   
<listcomp>z:ApplicationState._determine_app_status.<locals>.<listcomp>  s5     " " "8/=== ===rL   z!Failed to update the deployments .c                 F    g | ]}|j         t          j        k    |j        S rK   )r\   r   	UNHEALTHYrn   r9  s     rM   r;  z:ApplicationState._determine_app_status.<locals>.<listcomp>  s5     * * *8/999 999rL   zThe deployments z are UNHEALTHY.)r   r   r1   r   get_deployments_statusesminr\   r   r  r>  UPDATINGr   	UPSCALINGDOWNSCALINGstatus_triggerr   CONFIG_UPDATE_STARTEDRUNNING)rg   r{   lowest_rank_statusfailed_deploymentsunhealthy_deployment_namess        rM   _determine_app_statusz&ApplicationState._determine_app_status  si   $ & 	2$-r11
 #;;== !4:P:PQQQ$(8(FFF" "," " " "/I4FIII   &*:*DDD* *,* * *& "+N#=NNN   &*:*CCC$.22% *,<,HIJ J"1&<= = %.22$,b00rL   c                 6     j          j         j        rddt          j        dfS t	           j         j                  sddt          j        dfS d j         _        	 t          j         j         j                  \  }}}|$t          
                    d j         d           nddt          j        d j         d| fS nx# t          $ r2 d j         d	t          j                    z   }ddt          j        |fcY S t           $ r1 d
 j         dt          j                     }ddt          j        |fcY S w xY w	  fd|D             }d |D             }d |D             }t#          | j         j        ||          }                     |           _        ||t          j        dfS # t,          t.          t0          f$ r$ ddt          j        t          j                    fcY S t           $ r1 d j         dt          j                     }ddt          j        |fcY S w xY w)an  If necessary, reconcile the in-progress build task.

        Returns:
            Serialized application autoscaling policy def (bytes):
                The serialized application autoscaling policy def returned from the build app task
                if it was built successfully, otherwise None.
            Deploy arguments (Dict[str, DeploymentInfo]):
                The deploy arguments returned from the build app task
                and their code version.
            Status (BuildAppStatus):
                NO_TASK_IN_PROGRESS: There is no build task to reconcile.
                SUCCEEDED: Task finished successfully.
                FAILED: An error occurred during execution of build app task
                IN_PROGRESS: Task hasn't finished yet.
            Error message (str):
                Non-empty string if status is DEPLOY_FAILED or UNHEALTHY
        Nr]   TzImported and built app 'z' successfully.zDeploying app 'z' failed with exception:
zRuntime env setup for app 'z
' failed:
z7Unexpected error occurred while deploying application 'r  c           	      H    i | ]}|d          t          di |dj        iS r   r   rK   )r   r   )r  paramsrg   s     rM   r  z>ApplicationState._reconcile_build_app_task.<locals>.<dictcomp>T  s_            ()+I , ,, ,'+z, , ,     rL   c                 <    i | ]}|d          
|d         |d          S )!serialized_autoscaling_policy_defNr   rK   r  rN  s     rM   r  z>ApplicationState._reconcile_build_app_task.<locals>.<dictcomp>Z  s<     ? ? ?=>J ()62U+VJJJrL   c                 <    i | ]}|d          
|d         |d          S )serialized_request_router_clsNr   rK   rQ  s     rM   r  z>ApplicationState._reconcile_build_app_task.<locals>.<dictcomp>_  s<     ; ; ;9:F ()62Q+RFFFrL   r  )r   rU   r>   rG   r(   rP   rH   r!  r  r   r   r   rJ   r   r  r  r   r  rR   r   r   rI   r  r  r/   )	rg   r   r*  err	error_msgr   /deployment_to_serialized_autoscaling_policy_def+deployment_to_serialized_request_router_clsr,  s	   `        rM   _reconcile_build_app_taskz*ApplicationState._reconcile_build_app_task  s   ( $,0I0R,~A2EE)$*C*KLL 	>~92== .2!*	@GJw)1H HD94 {RtzRRRSSSS ")QdjQQCQQ	  T $ 	@ 	@ 	@EdjEEE&(()  ~4i???? 	@ 	@ 	@>J> >%.%9%;%;> >  ~4i????	@%	@        #	     ? ?"? ? ?;
; ;"; ; ;7
 7 )0?;	 O "&!3!3O!D!DD=(	  :'89 	M 	M 	M~4i6J6L6LLLLL 	@ 	@ 	@>J> >%.%9%;%;> >  ~4i????	@s2   A"B? ?9D4:7D43D48A+F$ $8H7HHc                     d}d}|                                 D ]}|j        |j        }|dz  }|dk    rt          d| j         d          |S )a  Check route prefixes of deployments in app.

        There should only be one non-null route prefix. If there is one,
        set it as the application route prefix. This function must be
        run every control loop iteration because the target config could
        be updated without kicking off a new task.

        Returns: route prefix.
        Raises: RayServeException if more than one route prefix is found among deployments.
        r   Nr?   z0Found multiple route prefixes from application "zP", Please specify only one route prefix for the application to avoid this issue.)valuesr   r/   r   )rg   r   num_route_prefixesr   r   s        rM   r   zApplicationState._check_routesz  s     $++-- 	( 	(D  ,#0"a'"!!#'4: ' ' '   rL   c                    d}| j         j                                        D ]\  }}t          |          }|                    | j         j        | j         j                   | j         j        r8| j         j        j        r'|j	        j        | j         j        j        |j	        _        | 
                    ||          p|}|                                 D ]"}|| j        vr|                     |          p|}#|S )zReconcile target deployments in application target state.

        Ensure each deployment is running on up-to-date info, and
        remove outdated deployments from the application.
        F)new_target_capacitynew_target_capacity_direction)r   r   r   r   set_target_capacityrS   rT   rR   r   r   r   r   r   r   )rg   r   r   r   deploy_infos        rM   _reconcile_target_deploymentsz.ApplicationState._reconcile_target_deployments  s+     % &*%7%H%N%N%P%P 	 	!OT"4..K ++$($6$F&@ ,    ")&-<  1@H &-< -< **?KHH (' !   $99;; 	 	Od&===++O<<T@T % $#rL   c                 (   | j         sdS i }| j         D ]d}t          || j                  }| j                            |          pg }t          || j        d |D             || j        k              }|||<   et          | j        | j        |          S )zGet the deployment topology for this application.

        Returns:
            The deployment topology, or None if not yet built.
        Nr   c                 ,    g | ]}|j         |j        d S r   r   )r  deps     rM   r;  z<ApplicationState.get_deployment_topology.<locals>.<listcomp>  s4     & & & !X3<@@& & &rL   )rn   r   outbound_deployments
is_ingress)r   r   nodes)r   r   r   r   #get_deployment_outbound_deploymentsr8   r   r9   )rg   rh  r   r   outbound_deploymentnodes         rM   get_deployment_topologyz(ApplicationState.get_deployment_topology  s     & 	4  $6 	* 	*O(o
SSSM .RR! # 	   "$& &2& & & ,t/LL  D &*E/""!Z#<
 
 
 	
rL   c           
      d   d}| j         j        s-|                                 \  }}}}|t          j        k    rd}|                     || j        j        | j         j        | j        j	        | j        j
        | j        j        | j         j        |           | j         j	        M| j         j	        j        <| j                            | j        t#          dd|i| j         j	        j                   nP| j                            | j                   n0|t          j        k    r |                     t*          j        |           | j         j        C|                                 p|}|                                 \  }}|                     ||           | j         j        r|                                 |fS d|fS )zAttempts to reconcile this application to match its target state.

        Updates the application status and status message based on the
        current state of the system.

        Returns:
            Whether the target state has changed.
        FT)r   rQ   r   r   rS   rT   r   r   Nr   rK   )r   r   rX  r>   rI   r   r   rQ   r   rR   rS   rT   r   r   r   r   r   r-   deregister_applicationrJ   r   r1   r  r   ra  rJ  r   )rg   r   r   infostask_statusmsgr\   
status_msgs           rM   updatezApplicationState.update  s     % !* %	J ..00=n666'+$&&%*!%!:!G!/8"&";"B$($=$M1K,0,>,VBo '    &-9*1DP3HH
)  3`"07J     3JJ4:VVVV 555##$5$CSIII
 .:2244L8L ! "&!;!;!=!=FJ
333 & 	;??$$&:::***rL   c                     | j         S r   )r   rf   s    rM   get_checkpoint_dataz$ApplicationState.get_checkpoint_data0  s    !!rL   c                 ^      fd j         D             } j                            |          S )z(Return all deployment status informationc                 <    g | ]}t          |j                   S rd  )r   r   )r  r  rg   s     rM   r;  z=ApplicationState.get_deployments_statuses.<locals>.<listcomp>5  s8     
 
 
 j4:>>>
 
 
rL   )r   r   get_deployment_statuses)rg   r%  s   ` rM   r?  z)ApplicationState.get_deployments_statuses3  sG    
 
 
 
"5
 
 
 -EEkRRRrL   c                 D    t          | j        | j        | j                  S )z)Return the application status informationr^   r_   )r2   r   r   r   rf   s    rM   get_application_status_infoz,ApplicationState.get_application_status_info;  s*    $L$!%!;
 
 
 	
rL   c                 f      fd j         D             }d |                                D             S )a  Gets detailed info on all live deployments in this application.
        (Does not include deleted deployments.)

        Returns:
            A dictionary of deployment infos. The set of deployment info returned
            may not be the full list of deployments that are part of the application.
            This can happen when the application is still deploying and bringing up
            deployments, or when the application is deleting and some deployments have
            been deleted.
        c           	      n    i | ]1}|j                             t          |j                             2S rd  )r   get_deployment_detailsr   r   )r  r   rg   s     rM   r  z<ApplicationState.list_deployment_details.<locals>.<dictcomp>N  sR     
 
 
   T;RR/DJGGG 
 
 
rL   c                     i | ]
\  }}|||S r   rK   )r  kvs      rM   r  z<ApplicationState.list_deployment_details.<locals>.<dictcomp>T  s    BBBAAM1MMMrL   )r   r   )rg   detailss   ` rM   list_deployment_detailsz(ApplicationState.list_deployment_detailsC  sO    
 
 
 
 $(#:	
 
 
 CBBBBBrL   r]   r\   rr  c                     |r?|t           j        t           j        fv r%|| j        k    rt                              |           || _        || _        d S r   )r1   r  r>  r   r   errorr   )rg   r\   rr  s      rM   r   zApplicationState._update_statusV  s_    		%!/!+ 
 d...LL$$$%rL   r}   N)r]   )=rC   rD   rE   rF   rW   r"   r   r#   r:   rY   r   propertyr
   r   r   r   r1   r\   rX   r_   r	   r   r   r6   r   r   r   r   r!   r;   r   r   r   r   r   r   r   r   r   r   r   r  r1  r   r   rJ  r>   rX  r   ra  r9   rl  rs  ru  r   r?  r2   r{  r7   r  r   rK   rL   rM   r   r      s       >>/./. #9/. $;	/.
 &/. &/. "&/. /. /. /.b "hsm " " " X" : : : : X: 
8C= 
 
 
 X
 )    X *e * * * X* @DI @ @ @ X@ -HSM - - - X- +' + + + X+!5! ! ! !T ,0GK(-IM.* .* .*"4^(;#<=.* 	.*
 sm.*   67.* "%.* $,,C#D.* .* "&.* 8@.* .* .* .*`
 
 

 67
 
 
 
(Ds Dt D D D D* * *VD V V V VX$ X X X X($4 ($ ($ ($ ($T5$5$ (5$ 
	5$ 5$ 5$ 5$n
sN23
 "&
 
 
 
6t&t "%t $,,C#D	t
 t 
t t t tlYtCy Y Y Y Y81u->-C'D 81 81 81 81t]@	xC	D]@ ]@ ]@ ]@~ $S.%8 9	sCx   >*$ *$ *$ *$X&
2D)E &
 &
 &
 &
PA+dDj) A+ A+ A+ A+F"%; " " " "S$/C*D S S S S
-B 
 
 
 
Cc3D.D)E C C C C&& &%6 &C &QU & & & & & &rL   r   c            
       T   e Zd Zdededededef
dZd Z	de
d	d
fdZdee
ee         f         dee
ef         d	d
fdZde
dee         ded	d
fdZdd
d
ddee         dedee         dee         fdZde
d	ee
         fdZde
d	ee         fdZde
d	efdZde
d	efdZde
d	efdZde
d	ee
         fdZde
d	ee
         fd Z de
d	ee
         fd!Z!de
d	e"fd"Z#de
d	efd#Z$	 d,d$ee"         d	ee
ef         fd%Z%de
d	ee
e&f         fd&Z'de
d	ee(         fd'Z)d( Z*d-d)Z+d	efd*Z,d-d+Z-d
S ).ApplicationStateManagerr   r   r   kv_storer   c                     || _         || _        || _        || _        || _        d| _        i | _        |                                  d S )NF)r   r   r   	_kv_storer   _shutting_down_application_states_recover_from_checkpoint)rg   r   r   r   r  r   s         rM   r   z ApplicationStateManager.__init__g  sT     *B&*C'-!-#@B %%'''''rL   c           	      @   | j                             t                    }|zt          j        |          }|                                D ]S\  }}t          || j        | j        | j	        | j
        |j                  }|                    |           || j        |<   Rd S d S r   )r  r  CHECKPOINT_KEYr   loadsr   r   r   r   r   r   r   r   r  )rg   
checkpointapplication_state_infor   r   	app_states         rM   r  z0ApplicationStateManager._recover_from_checkpointz  s    ^''77
!%0%6z%B%B"-C-I-I-K-K 
? 
?)/,23((#; 	 >>OOO5>(22 "!
? 
?rL   rn   r}   Nc                 Z    || j         vrdS | j         |                                          dS )zDelete application by nameN)r  r   rg   rn   s     rM   
delete_appz"ApplicationStateManager.delete_app  s5    t///F &--/////rL   name_to_deployment_argsname_to_application_argsc                    d | j                                         D             }|                                D ] \  }|D ]U}|                    d          }||                    |          }||k    rt          d| d| d d          ||<   V|                              }|j        }	| j         vr0t          | j        | j        | j        | j	        |	          | j         <   t          j                            t          t          | j                                        fd|D             }
| j                                      |
|	           "d S )Nc                 \    i | ])\  }}|j         |j        t          j        k    !|j         |*S r   )r   r\   r1   r   r  r   r  s      rM   r  z7ApplicationStateManager.deploy_apps.<locals>.<dictcomp>  sI     /
 /
 /
#)%1$(9(BBB "H CBBrL   r   zPrefix z is being used by application "z!". Failed to deploy application "z".c           	      >    i | ]}|d          t          di |diS rM  )r   )r  rN  rn   s     rM   r  z7ApplicationStateManager.deploy_apps.<locals>.<dictcomp>  s]            ()+I , ,, ,'+, , ,     rL   )r  r   r  r/   r   r   r   r   r   r   r&   NUM_APPSr$  rW   rt   r  )rg   r  r  live_route_prefixesdeployment_argsdeploy_paramdeploy_app_prefixexisting_app_nameapplication_argsr   r   rn   s              @rM   deploy_appsz#ApplicationStateManager.deploy_apps  s   
/
 /
'+'?'E'E'G'G/
 /
 /
 &=%B%B%D%D ,	 ,	!D/ / > >$0$4$4^$D$D!$,$7$;$;<M$N$N! %05F$5N5N+Y"3 Y Y-Y YPTY Y Y   :>#$5667;;DAA&6&N#43331A23((+2 2(. "))#c$2J.K.K*L*LMMM        .	      $T*55 "9   U,	 ,	rL   r  r  c                 :    |                      ||i||i           dS )a|  Deploy the specified app to the list of deployment arguments.

        This function should only be called if the app is being deployed
        through serve.run instead of from a config.

        Args:
            name: application name
            deployment_args_list: arguments for deploying a list of deployments.
            application_args: application arguments.
        N)r  )rg   rn   r  r  s       rM   r  z"ApplicationStateManager.deploy_app  s+      	$049I2JKKKKKrL   r   )r  rS   rT   app_configsr  rS   rT   c          	      X   |D ]}|j         | j        vrct                              d|j          d           t	          |j         | j        | j        | j        | j        |j	                  | j        |j         <   | j        |j                  
                    ||||           d | j                                        D             }d |D             }||z
  D ]}|                     |           t          j                            t!          t#          | j                                       dS )a  Declaratively apply the list of application configs.

        The applications will be reconciled to match the target state of the config.

        Any applications previously deployed declaratively that are *not* present in
        the list will be deleted.
        zDeploying new app 'r   )r   r   r   )r  c                 B    h | ]\  }}|j         t          j        k    |S rK   )r   r6   r   )r  rn   r  s      rM   	<setcomp>z<ApplicationStateManager.apply_app_configs.<locals>.<setcomp>  s7     
 
 
i!W%888 888rL   c                     h | ]	}|j         
S rK   )rn   )r  
app_configs     rM   r  z<ApplicationStateManager.apply_app_configs.<locals>.<setcomp>  s    HHHj*/HHHrL   N)rn   r  r   r   r   r   r   r   r   r   r1  r   r  r&   r  r$  rW   rt   )	rg   r  r  rS   rT   r  existing_appsapps_in_configapp_to_deletes	            rM   apply_app_configsz)ApplicationStateManager.apply_app_configs  s[    & 	 	Jd&>>>E*/EEEFFF<LO23#'#7#'#7,6,N= = =(9 $Z_5FF) /	 G    
 
#'#;#A#A#C#C
 
 

 IHKHHH*^; 	+ 	+MOOM****%%c#d.F*G*G&H&HIIIIIrL   r   c                 <    || j         vrg S | j         |         j        S )z'Return all deployment names by app name)r  r   rg   r   s     rM   get_deploymentsz'ApplicationStateManager.get_deployments  s&    4333I'1DDrL   c                 V    || j         vrg S | j         |                                         S )z*Return all deployment statuses by app name)r  r?  r  s     rM   r?  z0ApplicationStateManager.get_deployments_statuses  s/    4333I'1JJLLLrL   c                 P    || j         vrt          j        S | j         |         j        S r   )r  r1   NOT_STARTEDr\   r  s     rM   get_app_statusz&ApplicationStateManager.get_app_status  s*    t///$00'-44rL   c                     || j         v S r   r  r  s     rM   does_app_existz&ApplicationStateManager.does_app_exist  s    t///rL   c                     || j         vr t          t          j        d| dd          S | j         |                                         S )NzApplication z doesn't existr   rz  )r  r2   r1   r  r{  r  s     rM   get_app_status_infoz+ApplicationStateManager.get_app_status_info!  sZ    t///(!-;t;;;%&   
 '-IIKKKrL   c                 &    | j         |         j        S r   )r  r   r  s     rM   get_docs_pathz%ApplicationStateManager.get_docs_path*  s    '1;;rL   c                 &    | j         |         j        S r   )r  r   r  s     rM   get_route_prefixz(ApplicationStateManager.get_route_prefix-  s    '-::rL   c                 <    || j         vrd S | j         |         j        S r   )r  r   r  s     rM   get_ingress_deployment_namez3ApplicationStateManager.get_ingress_deployment_name0  s&    t///4'-@@rL   c                 &    | j         |         j        S r   )r  r   r  s     rM   get_app_sourcez&ApplicationStateManager.get_app_source6  s    '-66rL   c                 P    |                      |          o| j        |         j        S )zCheck if external scaler is enabled for the application.

        Args:
            app_name: Name of the application.

        Returns:
            True if external_scaler_enabled is set for the application, False otherwise.
        )r  r  r   r  s     rM   get_external_scaler_enabledz3ApplicationStateManager.get_external_scaler_enabled9  s.     )) K(2J	
rL   sourcec                 X      fd j         D             S  fd j         D             S )at  Return a dictionary with {app name: application info}

        Args:
            source: Optional API type filter. If provided, only returns apps
                   deployed via the specified API type.

        Returns:
            Dict[str, ApplicationStatusInfo]: A dictionary mapping application names
                to their corresponding status information.
        Nc                 P    i | ]"}|j         |                                         #S rK   )r  r{  )r  rn   rg   s     rM   r  z=ApplicationStateManager.list_app_statuses.<locals>.<dictcomp>U  s?        d.t4PPRR  rL   c                 ~    i | ]9}                     |          u |j        |                                         :S rK   )r  r  r{  )r  rn   rg   r  s     rM   r  z=ApplicationStateManager.list_app_statuses.<locals>.<dictcomp>Z  sR       &&t,,66 d.t4PPRR666rL   r  )rg   r  s   ``rM   list_app_statusesz)ApplicationStateManager.list_app_statusesG  sl     >    4   
     4   rL   c                 V    || j         vri S | j         |                                         S )z?Gets detailed info on all deployments in specified application.)r  r  r  s     rM   r  z/ApplicationStateManager.list_deployment_details`  s/    t///I'-EEGGGrL   c                 V    || j         vrdS | j         |                                         S )a  Get the deployment topology for an application.

        Args:
            app_name: Name of the application.

        Returns:
            The deployment topology for the application, or None if the application
            doesn't exist or the topology hasn't been built yet.
        N)r  rl  r  s     rM   rl  z/ApplicationStateManager.get_deployment_topologyf  s1     43334'1IIKKKrL   c                    g }d}| j                                         D ]\  }}|                                r|                                p|}|                                \  }}|p|}|r3|                    |           t                              d| d           t          |          dk    re|D ]$}| j	        
                    |           | j         |= %t          j                            t          t          | j                                        |r/|                                  | j                                         dS dS )zUpdate each application state.FzApplication 'z' deleted successfully.r   N)r  r   r   r   rs  r   r   debugrt   r   rn  r&   r  r$  rW   save_checkpointr   )rg   apps_to_be_deletedany_target_state_changedrn   appready_to_be_deletedapp_target_state_changedr   s           rM   rs  zApplicationStateManager.updatet  sl   #( 17799 		L 		LID###%% W+.==??+V>V(<?JJLL9!9(D,D % # L"))$///JTJJJKKK!""Q&&. 7 7/FFxPPP,X66"))#c$2J.K.K*L*LMMM# 	=  """*::<<<<<	= 	=rL   c                     d| _         | j                                        D ]}|                                 | j                            t
                     d S )NT)r  r  rZ  r   r  r  )rg   r  s     rM   shutdownz ApplicationStateManager.shutdown  sY    "188:: 	 	In-----rL   c                 p    | j         o/t          d | j                                        D                       S )zReturn whether all applications have shut down.

        Iterate through all application states and check if all their applications
        are deleted.
        c              3   >   K   | ]}|                                 V  d S r   )r   )r  r  s     rM   	<genexpr>z@ApplicationStateManager.is_ready_for_shutdown.<locals>.<genexpr>  s?       +
 +
'0I  ""+
 +
 +
 +
 +
 +
rL   )r  allr  rZ  rf   s    rM   is_ready_for_shutdownz-ApplicationStateManager.is_ready_for_shutdown  sK     " 
s +
 +
484L4S4S4U4U+
 +
 +
 (
 (
 	
rL   c                     | j         rdS d | j                                        D             }| j                            t
          t          j        |                     dS )z-Write a checkpoint of all application states.Nc                 >    i | ]\  }}||                                 S rK   )ru  r  s      rM   r  z;ApplicationStateManager.save_checkpoint.<locals>.<dictcomp>  s:     "
 "
 "
#) i3355"
 "
 "
rL   )r  r  r   r  putr  r   re   )rg   r  s     rM   r  z'ApplicationStateManager.save_checkpoint  sz     	 F"
 "
'+'?'E'E'G'G"
 "
 "

 	455	
 	
 	
 	
 	
rL   r   r  ).rC   rD   rE   r"   r   r#   r%   r:   r   r  rW   r  r   r	   ApplicationArgsProtor  r  r;   rX   r
   r   r  r  r   r?  r1   r  rY   r  r2   r  r  r  r  r6   r  r  r  r7   r  r9   rl  rs  r  r  r  rK   rL   rM   r  r  f  s       ("8( $;( &	(
 ( &( ( ( (&? ? ?"0s 0t 0 0 0 08!%c4:o!68 #'s,@'@"A8 
	8 8 8 8tLL dL /	L
 
L L L L, "#+/GK-J -J -J01-J 	-J
 "%-J $,,C#D-J -J -J -J^E ES	 E E E EM M>R9S M M M M53 5+< 5 5 5 503 04 0 0 0 0L L0E L L L L<c <hsm < < < <;S ;Xc] ; ; ; ;A A A A A A73 77 7 7 7 7
C 
D 
 
 
 
 +/ w'	c((	)   2HC HD>O9O4P H H H HL LAS8T L L L L= = =2. . . .
t 
 
 
 

 
 
 
 
 
rL   r  r?   )num_cpus	max_callsr)  rQ   rn   r*  r   r-  r.  r/  r}   c                 P   t          dd| dt          j                     |           	 ddlm} |rd| nd}	t
                              d	| d
|	 d            |t          |           |          }
g }t          |
|t          j
                    j                  }d}dt          dt          fd}d}| ||          }|j        D ]}t          j        |j                  rt%          |j        t&                    r|dz  }|j        |j        k    }d}d}|j        |v r |||j                           }|j        |v r |||j                           }|                    t/          |j        |j        ||j        ||rdnd||                     |dk    rddd|j         dfS ||dfS # t6          $ r t
                              d           Y dS t8          $ rJ t
                              d| dt=          j                                ddt=          j                    fcY S w xY w)a  Import and build a Serve application.

    Args:
        import_path: import path to top-level bound deployment.
        code_version: code version inferred from app config. All
            deployment versions are set to this code version.
        name: application name. If specified, application will be deployed
            without removing existing applications.
        args: Arguments to be passed to the application builder.
        logging_config: the logging config for the build app task.
        application_autoscaling_policy_function: the application autoscaling policy function name
        deployment_to_autoscaling_policy_function: a dictionary mapping deployment names to autoscaling policy function names
        deployment_to_request_router_cls: a dictionary mapping deployment names to request router class names

    Returns:
        Serialized application autoscaling policy def: a serialized autoscaling
            policy def for the application if it was built successfully, otherwise None.
        Deploy arguments: a list of deployment arguments if application
            was built successfully, otherwise None.
        Error message: a string if an error was raised, otherwise None.
    
controllerbuild__)component_namecomponent_idr   r   ),call_user_app_builder_with_args_if_necessaryz with arguments r]   zImporting application ''r<  )rn   default_runtime_env	attr_pathr}   c                     t          |           \  }}t          j        |           t          j        |          }t          j        |           |S r   )r   r   register_pickle_by_valuere   unregister_pickle_by_value)r  moduleattr
serializeds       rM   _get_serialized_defz4build_serve_application.<locals>._get_serialized_def  sK    1)<<LFD0888$*400J26:::rL   Nr?   r   )rn   replica_configr   r   versionr   rP  rS  z3Found multiple FastAPI deployments in application "zb". Please only include one deployment with @serve.ingress in your application to avoid this issue.zLExisting config deployment request terminated because of keyboard interrupt.)NNNz!Exception importing application 'z'.
) r$   osgetpidray.serve._private.apir  r   r   r   r   r!  get_runtime_contextr  rW   r   r%  inspectisclassfunc_or_class
issubclassr+   rn   ingress_deployment_namer   r    r   _replica_config_deployment_configKeyboardInterruptr   r  r  r  )r)  rQ   rn   r*  r   r-  r.  r/  r  args_info_strr  deploy_args_list	built_appnum_ingress_deploymentsr  -application_serialized_autoscaling_policy_defr  rg  rV  rW  s                       rM   r&  r&    s<   @ #2d22RY[[22%   R2WWWWWW 6:A14111rEdEE]EEEFFF::$$d
 
 &/ # 7 9 9 E'
 '
 '
	
 #$	3 	5 	 	 	 	 9=52><O<O7= =9 $/ 	 	Jz788 -Z(*?> > - (1,'#I,MMJ>B;:>7"KKKBUBU=joNC C? "BBB>Q>Q4Z_E? ?; ###)#-#=&&0&C((2!<6e2]	 	 	    #Q&&?). ? ? ?	  =>NPTTT       		
 	
 	
   2 2 2RRR):N:P:PRR	
 	
 	
 T9/111111	2s   E:F+ &F+ +$H%AH%$H%r   override_configrV  rW  c           
         t          |           } || S |                    d          }|                    dg           }|D ]}d|v r|                    d          |d<   |d         }|| vr4t          d| dt	          |                                                      | |         }|j                                        }	|	d	                             t          |                     |                    d
          dk    rd|d
<   t          j
                                                    }
|                    d          p|j        j        }|r|
                    |           |r*||v r&t          j        |
d         ||                   }||
d<   t          di |
|d<   t          j                            d           i }|j        }|j        }d|v r|                    di           }n	|j        pi }|                    d|j                  }|                    d|j                  }|                    d|j                  }|                    d          rU|d                             d          s|d                             d          rt          j                            d           t3          ||                    di                     }|                    d|i           |                    ||||           ||d<   d|v rK|                    d          }|r4|r#||v rt5          j        |||                   |d<   nt5          di ||d<   |                    dd           |	                    |           t9          di |	|d<    |j        di || |<   | |         j        }|j        <|j        |j                                        k     rt>                               d           |                    dtB          j"                  }tG          |           t	          | $                                          D ]}|tB          j"        ur|j%        ||_%        | S )a  Override deployment infos with options from app config.

    Args:
        app_name: application name
        deployment_infos: deployment info loaded from code
        override_config: application config deployed by user with
            options to override those loaded from code.
        deployment_to_serialized_autoscaling_policy_def: serialized autoscaling policy def for each deployment
        deployment_to_serialized_request_router_cls: serialized request router cls for each deployment

    Returns: the updated deployment infos.

    Raises:
        ValueError: If config options have invalid values.
        TypeError: If config options have invalid types.
    NT)exclude_unsetr%  max_ongoing_requestsrn   zDeployment 'z' does not exist. Available: user_configured_option_namesnum_replicasautor  r  r	  ray_actor_optionsplacement_group_bundlesplacement_group_strategymax_replicas_per_noder  r  r  )r  r  r  r  r  r  r   ziAutoscaling will never happen, because 'max_ongoing_requests' is less than 'target_ongoing_requests' now.r   rK   )&r   r  r  r  r   r   r   rs  setr,   defaultr  r-   from_serialized_policy_defr&   AUTO_NUM_REPLICAS_USEDr$  r  r  popr  r  r  r  %DEPLOYMENT_CONTAINER_RUNTIME_ENV_USEDr)   r.   "from_serialized_request_router_clsr   r  get_target_ongoing_requestsr   warningr'   VALUEr*   rZ  r   )r   r  rV  rW  config_dictdeployment_override_optionsr'  r   r   original_options
new_configr  
policy_objoverride_optionsr  app_runtime_envoverride_actor_options override_placement_group_bundles!override_placement_group_strategyoverride_max_replicas_per_node
merged_envr  r   app_route_prefixr  s                            rM   r  r  ,  sR   .   011!&&T&::K"-//-"D"D / ~ ~!W,,.5kk:P.Q.QG*+!&/"222> > >"#3#8#8#:#:;;> >  
  01668878??GMMM ;;~&&&00&*GN#*24499;;J 011 =)<  " 6!!"4555 @
2#'VVV /Ix(COT 
 (2
8$,=,K,K
,K,KG()077<<<  ,)5'))%,[[1Db%I%I"" &4%E%K"+2;;%~'M,
 ,
( -4KK&(O-
 -
) *1#^%I*
 *
&
 "%%m44 	L"=155kBB	L%m488EE	L ?FFsKKK:377rJJ
 

 	%%}j&ABBB4$D%F"@	 	 	
 	
 	
 .<)*"g--$+KK0G$H$H!$ ?'+VVV ,N-COT  /  8K 8 8/8 8G34
 	FD!!!(((0@0T0TCS0T0T,-,7DK,K,K:J,K,K),_=O0<!62NNPPQ Q NN1   #~w}EE*++++224455 7 7
GM11'3&6J#rL   )NN)lr  rd   loggingr  r   r  copyr   dataclassesr   r   r   enumr   typingr   r	   r
   r   r!  r   ray._common.utilsr   r   ray.exceptionsr   $ray.serve._private.autoscaling_stater   ray.serve._private.build_appr   r   ray.serve._private.commonr   r   r   r   r   r   ray.serve._private.configr   ray.serve._private.constantsr   r   r   r   ray.serve._private.deploy_utilsr   r   r    "ray.serve._private.deployment_infor!   #ray.serve._private.deployment_stater"   !ray.serve._private.endpoint_stater#    ray.serve._private.logging_utilsr$   #ray.serve._private.storage.kv_storer%   ray.serve._private.usager&   ray.serve._private.utilsr'   r(   r)   r*   ray.serve.apir+   ray.serve.configr,   r-   r.   ray.serve.exceptionsr/   ray.serve.generated.serve_pb2r0   r  r1   rr   r2   rm   r3   r4   r   r5   r   ray.serve.schemar6   r7   r8   r9   r:   r;   	ray.typesr<   	getLoggerr   r  r>   rO   r   r   r  r(  rW   r   r&  r  rK   rL   rM   <module>rE     s      				            0 0 0 0 0 0 0 0 0 0       . . . . . . . . . . . . 



       A A A A A A A A / / / / / / H H H H H H D D D D D D D D                7 6 6 6 6 6                    
 > = = = = = F F F F F F ; ; ; ; ; ; G G G G G G ; ; ; ; ; ; 2 2 2 2 2 2            0 / / / / / V V V V V V V V V V 2 2 2 2 2 2                                       		,	-	-5    T           " d
 
 
 
 
 
 
 
2 d>
 >
 >
 >
 >
 >
 >
 >
B  "  "  "  "  "  "  "  "F{& {& {& {& {& {& {& {&|H
 H
 H
 H
 H
 H
 H
 H
V
 Q!$$$w2w2w2 w2 	w2
 "w2 .6c]w2 04CH~w2 '+38nw2 8E?HT$Z0(3-?@w2 w2 w2 %$w2z SWNR	i i3./i45i 6>d3:>N5Oi 2:$sEz:J1K	i
 
#~
i i i i i irL   