
    &`iz#                       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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Zd dlmZ d dlmZmZmZmZmZ d dlmZ d dlZd dlmc mZ d dlZd dlmZm Z m!Z!m"Z" d dl#m$Z$m%Z% d dl&m'Z' d dl(m)Z) d d	l*m+Z+ d d
lm,Z,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5 d dl6Z6 ej7        e8          Z9 G d d          Z:dS )    N)defaultdict)IOAnyStrDictOptionalTuple)FileLock)build_addressget_localhost_ipis_ipv6parse_address)LOGGING_ROTATE_BACKUP_COUNTLOGGING_ROTATE_BYTES)try_to_create_directory)ResourceAndLabelSpec)ResourceIsolationConfig)get_addressserialize_config)
is_in_testopen_logtry_to_symlinkvalidate_socket_filepath)	GcsClientget_session_key_from_storagec                      e Zd ZdZ	 	 	 	 	 	 dmdededededed	efd
Zd Zed             Zd Z	d Z
d Zd Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Zed              Zed!             Zed"             Zed#             Z ed$             Z!d% Z"d& Z#d' Z$d( Z%d) Z&d* Z'd+ Z(d, Z)	 dnd/e*d0e*d1e+e*         fd2Z,d3 Z-	 	 	 dod4e*d5ed6ed7ed8e.e+e*         e+e*         f         f
d9Z/	 	 	 dod4e*d5ed6ed7ed8e.e+e0e1                  e+e0e1                  f         f
d:Z2	 dpd4e*d/e*d5ed8e*fd;Z3dqd<Z4d=e*d>e*fd?Z5	 dqd@e*dAe+e6         d8e6fdBZ7drdDe6d8e*fdEZ8dF Z9dG Z:dHe+e         dIefdJZ;dK Z<	 	 dsdLe*dMe*dNe6dOedPef
dQZ=dR Z>dS Z?dT Z@dU ZAdV ZBd8e*fdWZC	 	 	 dtdXedYedZefd[ZD	 dtd\ZEdudYefd]ZFdudYefd^ZGdudYefd_ZHdudYefd`ZIdudYefdaZJdudYefdbZKdudYefdcZLdvddZMde ZNdf ZOdg ZPdh ZQdi ZRdj ZSdk ZTdl ZUd.S )wNodea  An encapsulation of the Ray processes on a single node.

    This class is responsible for starting Ray processes and killing them,
    and it also controls the temp file policy.

    Attributes:
        all_processes: A mapping from process type (str) to a list of
            ProcessInfo objects. All lists have length one except for the Redis
            server list, which has multiple.
    FTheadshutdown_at_exitspawn_reaperconnect_onlydefault_workerray_init_clusterc                    |r%|rt          d          |                                  || _        || _        t	          |o"t
          j        j                                                  | _	        |j
        | _
        i | _        t          j                    | _        || _        |r|s
J d            t           j                            d          }|j        c|a|                    d          }	t+          |	          dk    r|	                    |	d                    |	|_        t+          |	          dz
  |_        |j        r+t+          |j                  dk    r|s|st          d          |                    d	i t           j                            t           j                            t           j                            t<                              d
d          t           j                            t           j                            t           j                            t<                              d
t>          j                              d| _!        tE                      | _#        || _$        |j        pi | _%        |j&        | _'        tQ          t!          j)        dtT                              | _+        tQ          t!          j)        dtX                              | _-        | j+        dk    sJ | j-        dk    sJ |j.        | _/        |r|                    d           |j0        | _1        d| _2        | j        s.| 3                    | j4                   | 5                                 |j6        | _7        | j7        |r| 8                                }
|
Ptr          j9        :                                ;                    d          }d| dt!          j<                     | _7        nt
          j=        j        >                    |
          | _7        n| j        rJ t
          j        j        ?                    | @                                dt>          jA        t>          jB                  }t
          j=        j        >                    |          | _7        |rd| _C        nX|jD        2| j        rJ t
          j        jE        F                                | _C        nt          |jH        |jI                  | _C        | J                                 |jK        }|5|r| L                                }nt
          jM        N                                }|J |                    |           || _O        |s7t
          j        jE        P                    | Q                                |           | R                                | _S        t          U                    d| jS                    d| _V        | jS        rt          jX        | jS                  }|                    d          dk    rh|                    di                               d          }t          |t                    r|d         | _V        nt          |t                    r|| _V        |r| \                                 |r|j]        | _^        |j_        | _`        |ja        | _b        | j^        | j`        | j$        jc        | jb        ht
          j        jE        d                    | j0        | jO                  }|d         | _^        |d         | _`        |d         | j$        _c        |d         | _b        nI| e                    | j$        j]        d           | _^        | e                    | j$        j_        d!           | _`        | j$        jf        Fd"| j$        jf        v r8| j$        jf        d"         }t          U                    d#| d$           || _b        nt           j                            d"          r8t           j        d"         }t          U                    d#| d%           || _b        nTt
          jg        h                                i                                }t          U                    d#|            || _b        | j                    d&|j&        '          | _'        | j                    d(|jk        '          | _k        | j                    d)|jl        '          | _m        | j                    d*|jn        '          | _o        |                    | jk        | jm        | j'        | jo        +           |rot!          j)        t>          jp                  }|r#|                    tQ          |          ,           |jq        |jq        dk    r| j                    d-          |_q        |s|r| j	        s| r                                 |s| j$        s                                 |r| t                                 |s| u                                 t          jw        d.           t          jx                    }d/}d}	 	 t
          j        jE        y                    | j0        | jb                  }n^# t          $ r'}t          {                    d0|            Y d}~nd}~ww xY wt          jx                    |z
  |k    rt          d1          | j$        jc        dk    r|d         | j$        _c        |rJt
          j        jE        y                    | j0        | jb                  }|                    d2i           | _}        | 3                    | j4                   | 3                    | j0                   |s| ~                                 dS dS )3a*  Start a node.

        Args:
            ray_params: The RayParams to use to configure the node.
            head: True if this is the head node, which means it will
                start additional processes like the Redis servers, monitor
                processes, and web UI.
            shutdown_at_exit: If true, spawned processes will be cleaned
                up if this process exits normally.
            spawn_reaper: If true, spawns a process that will clean up
                other spawned processes if this process dies unexpectedly.
            connect_only: If true, connect to the node without starting
                new processes.
            default_worker: Whether it's running from a ray worker or not
            ray_init_cluster: Whether it's a cluster created by ray.init()
        z:'shutdown_at_exit' and 'connect_only' cannot both be true.z1ray.init() created cluster only has the head nodeRAY_REDIS_ADDRESSN,   r   z:System config parameters can only be set on the head node.Tworkerszdefault_worker.py)include_log_monitor	resourcesworker_pathsetup_worker_pathRAY_ROTATION_MAX_BYTESRAY_ROTATION_BACKUP_COUNT)num_redis_shardsz%Y-%m-%d_%H-%M-%S_%fsession__session_namenum_retries)node_ip_addressz+Starting node with object spilling config: type
filesystemparamsdirectory_pathobject_store_socket_nameraylet_socket_namenode_manager_portnode_idplasma_store)default_prefixraylet RAY_OVERRIDE_NODE_ID_FOR_TESTINGzSetting node ID to z& based on ray_params.env_vars overridez based on env overridedashboard_agent_listen_port)default_portmetrics_agent_portmetrics_export_portruntime_env_agent_port)rC   rD   rA   rE   )gcs_server_portrF   皙?   zFailed to get node info zThe current node timed out during startup. This could happen because some of the raylet failed to startup or the GCS has become overloaded.labels)
ValueError_register_shutdown_hooks_default_workerr   boolray_privateutilsdetect_fate_sharing_supportkernel_fate_shareresource_isolation_configall_processes	threadingLockremoval_lockr"   osenvirongetexternal_addressessplitlenappendr.   _system_configupdate_if_absentpathjoindirnameabspath__file__ray_constantsSETUP_WORKER_FILENAME_resource_and_label_specr   
_localhost_ray_params_configrA   _dashboard_agent_listen_portintgetenvr   	max_bytesr   backup_countredis_address_redis_addressgcs_address_gcs_address_gcs_clientvalidate_ip_portaddress_init_gcs_clientr1   _session_namecheck_persisted_session_namedatetimetodaystrftimegetpid_commondecodeinternal_kv_get_with_retryget_gcs_clientKV_NAMESPACE_SESSIONNUM_REDIS_GET_RETRIES
_webui_urlwebuiservicesget_webui_url_from_internal_kvr
   dashboard_hostdashboard_port
_init_tempr4   _wait_and_get_for_node_addressutilget_node_ip_address_node_ip_addresswrite_node_ip_addressget_session_dir_path_get_object_spilling_config_object_spilling_configloggerdebug_fallback_directoryjsonloads
isinstanceliststrvalidate_external_storageplasma_store_socket_name_plasma_store_socket_namer:   _raylet_socket_namer<   _node_idr;   get_node_to_connect_for_driver_prepare_socket_fileenv_varsNodeIDfrom_randomhex_get_cached_portrC   rD   _metrics_export_portrE   _runtime_env_agent_portGCS_PORT_ENVIRONMENT_VARIABLErF   start_reaper_processupdate_pre_selected_portstart_head_processesstart_ray_processestimesleep	monotonicget_nodeRuntimeErrorinfo	Exception_node_labels_record_stats)self
ray_paramsr   r   r   r    r!   r"   redis_address_envexternal_redis	maybe_keydate_strr1   r4   configr8   	node_infor<   rF   
start_timeraylet_start_wait_time_ses                         e/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/node.py__init__zNode.__init__@   s   4  	,  P   ))+++-	!%MS\/KKMM"
 "
 0 	& $&%N,, 0 	MLLLLL4 JNN+>??(05F5R.44S99N >""a''%%nQ&7888,:J)*-n*=*=*AJ' %	J-..22 3". 3 L   	## $ 9 9::# 
 !gll 9 9::3  	$ 	
 	
 	
 )-%*,,%!06B,6,R) RY'?AUVVWWI13NOO
 
 ~"""" A%%%%(6 	<''';;;&2y 	$!!$,///!!### (4% L !==??	$'06688AA.   H *MH)L)Lry{{)L)LD&&),):)A)A))L)LD&&////"|1LL''))"!6 - C	  M     &)[%6%=%=l%K%K"  		"DOO'////"%,"7"V"V"X"X"/-z/H# #
 	$4" A"&"E"E"G"G"%(">">"@"@***##O#DDD / 	L!77))++_   (,'G'G'I'I$X$:VXX	
 	
 	
 $( ' 	>Z <==Fzz&!!\11!'Hb!9!9!=!=>N!O!Ond33 >/=a/@D,,44 >/=D,  	-**,,, 0	(-7-PD*'1'DD$&.DM .6+3#5==(  L1PP$) 	 2;;U1V.+45I+J(5>?R5S 2 )) 4 .2-F-F 9. .G . .D* (,'@'@ 3H (A ( (D$  )56$:J:SSS*34VW<' < < <   !( BCC (*%GHR7RRRSSS '*00226688<7<<=== ' -1,A,A)#? -B -
 -
)
 #'"7"7 z/L #8 #
 #
 %)$9$9!
0N %: %
 %
! (,'<'<$#: (= (
 (
$
 	###6 $ 9(,(I#'#?	 	$ 	
 	
 	
  	V i(STTO R++C<P<P+QQQ)1Z5OST5T5T-1-B-BCT-U-U
* 	( 	(T5K 	(%%''' 	855777  	(%%''' 	T$$&&& JsOOO))J')$I@ # 5 > >(! !I # @ @ @KK >1 > >????????@>##j03KKK#D  " 1Q665>?R5S 2 	<-66  I
 !*h ; ;D 	dl+++d./// 	!     	! 	!s   </i, ,
j6jjc           
      X   | j         j        d S | j         j        d         | _        t          | j                  \  }}}t	          |          dk     rt          d| d          t          |t	          |          | j         j        | j         j        |t          | j
                  d          S )Nr   zInvalid Redis port provided: z).The port must be a non-negative integer.   session_name)rj   r[   rr   r   rm   rJ   r   redis_usernameredis_passwordr   rk   )r   redis_ip_address
redis_portenable_redis_ssls       r   rz   z!Node.check_persisted_session_name  s    .64".A!D9D:
 :
6*&6 z??Q;
 ; ; ;  
 ,
OO++T\**
 
 	
    c                     t          |           }|t          d|            	 t          |d                   }dS # t          $ r t          d|d          d|  d          w xY w)z.Validates the address is in the ip:port formatNz"Port is not specified for address r&   z!Unable to parse port number from z (full address = ))r   rJ   rm   )ip_portpartsr0   s      r   rv   zNode.validate_ip_port  s     g&&=K'KKLLL	E!HAAA 	 	 	YE!HYYwYYY  	s	   < 'A#c                 \   ddl mc mc m} |                    |                                           }|'|                    |                                           }|sdS t          j        j        	                                }t          j        j
                            |d|            dS )a+  Check if the Python and Ray version of this process matches that in GCS.

        This will be used to detect if workers or drivers are started using
        different versions of Python, or Ray.

        Raises:
            Exception: An exception is raised if there is a version mismatch.
        r   Nznode )ray._common.usage.usage_libr   usage	usage_libget_cluster_metadatar   rN   rO   r   r   rP   check_version_info)r   ray_usage_libcluster_metadatar4   s       r   r   zNode.check_version_info  s     	<;;;;;;;;;;;(==d>Q>Q>S>STT#,AA$BUBUBWBWXX 	F,/CCEE--7o77	
 	
 	
 	
 	
r   c                       fd}t          j        |            fd}t          j        j                            |           d S )Nc                  6                         dd           d S )NFTcheck_aliveallow_graceful)kill_all_processes)argsr   s    r   atexit_handlerz5Node._register_shutdown_hooks.<locals>.atexit_handler  s"    ##d#KKKKKr   c                 ^                         dd           t          j        d           d S )NFTr   r&   )r   sysexit)signumframer   s     r   sigterm_handlerz6Node._register_shutdown_hooks.<locals>.sigterm_handler  s-    ##d#KKKHQKKKKKr   )atexitregisterrN   rO   rP   set_sigterm_handler)r   r   r   s   `  r   rK   zNode._register_shutdown_hooks  sm    	L 	L 	L 	L 	L 	'''
	 	 	 	 	 	..?????r   c                    t          j        d           | _        | j        rN| j                            t          j        j        	                                           | j        j
        | _        n| j        j
        | j        rJ t          j        j                            |                                 dt           j        t           j                  }t          j        j                            |          | _        n| j        j
        | _        t)          | j                   | j        r0t*          j                            | j        | j                  | _        n| j        | j        | j        rJ t          j        j                            |                                 dt           j        t           j                  }t          j        j                            |          | _        n/t*          j                            | j        | j                  | _        t*          j                            | j        t           j                  }t)          | j                   t7          || j                   t*          j                            | j        d          | _        t)          | j                   t*          j                            | j        d          | _        t)          | j                   t*          j                            | j        d          }t)          |           t*          j                            | j        | j        j                  | _        t)          | j                   t          j        j                                         }| d	}t*          j        !                    |          r7t*          j                            | j        d
          }t7          ||           d S d S )Nc                      dS )Nr    r   r   r   <lambda>z!Node._init_temp.<locals>.<lambda>  s     r   )temp_dirr   r2   session_dirsocketslogsoldz	/tpu_logstpu_logs)"collectionsr   _incremental_dictr   rj   r`   rN   r   rP   get_ray_temp_dirr   	_temp_dirrL   rO   r   r   rf   r   r   r   r   rX   ra   rb   ry   _session_dirSESSION_LATESTr   _sockets_dir	_logs_dirruntime_env_dir_name_runtime_env_dirget_user_temp_dirisdir)r   r   r   session_symlinkold_logs_diruser_temp_dirtpu_log_dirtpu_logs_symlinks           r   r   zNode._init_temp  s&   !,!8!C!C9 	;--*;;== .    "-6DNN(0////<-HH''))!6 - C	 I   "%!2!9!9(!C!C!%!1!:///9 	U "T^T=O P PD~%);)C////!l0KK''))!!6 - C	 L   %(K$5$<$<[$I$I!!$&GLLAS$T$T!',,t~}7STT 	  1222(9:::GLL):IFF 1222d&7@@///w||DNE::--- "t/D!
 !
 	  5666);;==&1117==%% 	:!w||DNJGG+[99999	: 	:r   c                    | j         stt          | j        j        | j        j        | j        j        | j        j        | j        j        | j        j                  	                    | j
        | j                  | _         | j         S )zAResolve and return the current ResourceAndLabelSpec for the node.)is_headr4   )rh   r   rj   num_cpusnum_gpusmemoryobject_store_memoryr)   rI   resolver   r4   r   s    r   get_resource_and_label_specz Node.get_resource_and_label_spec  s|    , 	O,@ ) ) ' 4 * '- - gdi9MgNN ) ,,r   c                     | j         S )zGet the node ID.)r   r  s    r   r<   zNode.node_id  s     }r   c                     | j         S )z!Get the current Ray session name.)ry   r  s    r   r1   zNode.session_name"  s     !!r   c                     | j         S )z Get the IP address of this node.)r   r  s    r   r4   zNode.node_ip_address'  s     $$r   c                     | j         S )zGet the address for bootstrapping, e.g. the address to pass to
        `ray start` or `ray.init()` to start worker nodes, that has been
        converted to ip:port format.
        rt   r  s    r   rw   zNode.address,  s       r   c                 2    | j         
J d            | j         S )zGet the gcs address.NzGcs address is not setr  r  s    r   rs   zNode.gcs_address4  s%      ,,.F,,,  r   c                     | j         S )zGet the cluster Redis address.)rr   r  s    r   rq   zNode.redis_address:  s     ""r   c                     | j         j        S )zGet the cluster Redis username.)rj   r   r  s    r   r   zNode.redis_username?       ..r   c                     | j         j        S )zGet the cluster Redis password.)rj   r   r  s    r   r   zNode.redis_passwordD  r  r   c                     | j         S )z(Get the node's plasma store socket name.)r   r  s    r   r   zNode.plasma_store_socket_nameI  s     --r   c                 $    | j          d| j         S )z&Get a unique identifier for this node.:)r4   r   r  s    r   	unique_idzNode.unique_idN  s     &II)GIIIr   c                     | j         S )zGet the cluster's web UI url.)r   r  s    r   	webui_urlzNode.webui_urlS  s     r   c                     | j         S )z"Get the node's raylet socket name.)r   r  s    r   r:   zNode.raylet_socket_nameX  s     ''r   c                     | j         j        S )zGet the node manager's port.)rj   r;   r  s    r   r;   zNode.node_manager_port]  s     11r   c                     | j         S )z!Get the port that exposes metrics)r   r  s    r   rD   zNode.metrics_export_portb  s     ((r   c                     | j         S )z3Get the port that exposes runtime env agent as http)r   r  s    r   rE   zNode.runtime_env_agent_portg  s     ++r   c                 <    dt          | j        | j                   S )z6Get the address that exposes runtime env agent as httpzhttp://)r
   r   r   r  s    r   runtime_env_agent_addresszNode.runtime_env_agent_addressl  s#     ^t'<d>Z[[]]]r   c                     | j         S )z%Get the dashboard agent's listen port)rl   r  s    r   rA   z Node.dashboard_agent_listen_portq  s     00r   c                      | j         | j        dS )z+Get the logging config of the current node.)log_rotation_max_byteslog_rotation_backup_count)ro   rp   r  s    r   logging_configzNode.logging_configv  s     '+n)-):
 
 	
r   c                     | j         | j        | j        | j        | j        | j        | j        | j        | j        | j	        d
S )zGet a dictionary of addresses.)
r4   rq   object_store_addressr:   r  r   rD   rs   rw   rA   )
r   rq   r   r   r   r   r   rs   rw   rA   r  s    r   address_infozNode.address_info~  sM      $4!/$($B"&":,#'#<+|+/+K
 
 	
r   c                     | j         S )zGet the node labels.)r   r  s    r   node_labelszNode.node_labels  s       r   c                     | j         S N)r   r  s    r   r  zNode.is_head  s
    yr   c                 F    | j         |                                  | j         S r/  )ru   rx   r  s    r   r   zNode.get_gcs_client  s&    #!!###r   c                    | j         r#| j        t          j                 d         j        }nd }t          t          j                  D ]}d }d }	 | j        }t          || j	        j
                  }|j
        | _
        | j         r|                    dd            || _         nm# t          $ r` ||                                Y  nJt          j                    }t"                              d|            t'          j        d           Y w xY w| j        t+          | d          rt-          t.          j                            | j        d                    5 }d |                                D             d	d          }d d d            n# 1 swxY w Y   d
d                    |          z   d
z   }t9          d| j         rdnd dt;          |           d| dt.          j                            | j        d           d| 
          t9          d| j         rdnd d|           t<          j        j         !                    | j                   d S )Nr   )rw   
cluster_ids   dummyzConnecting to GCS: r&   r   zgcs_server.errc                 "    g | ]}d |v sd|v 
|S )z C z E r   ).0r   s     r   
<listcomp>z)Node._init_gcs_client.<locals>.<listcomp>  s&    UUUAEQJJ%ST**a***r   i
 z
Failed to startz
connect toz GCS.  Last z lines of error files:z.Please check zgcs_server.outz% for details. Last connection error: z GCS. Last connection error: )"r   rT   rf   PROCESS_TYPE_GCS_SERVERprocessranger   rs   r   rj   r2  internal_kv_getru   r   poll	traceback
format_excr   r   r   r   hasattropenrX   ra   rb   r   	readlinesr   r]   rN   experimentalinternal_kv_initialize_internal_kv)	r   gcs_processr0   rs   last_exclienterrerrors	error_msgs	            r   rx   zNode._init_gcs_client  s   9 	,]-RS K K }:;; 	 	AKG"."'#/:   #)"39 ; **8T:::#)    *{/?/?/A/A/MEE#.00<7<<===
1 #t[)) "',,t~7GHHII S VUUUUF	               !2776??2T9	"FDI!G< F F [[F F F F %'GLLAQ$R$RF F =D	F F   #3DI!G< 3 3)03 3  
 	$<<T=MNNNNNs,   AB!! DAD
D'FFFc                     | j         S )z(Get the path of the temporary directory.)r   r  s    r   get_temp_dir_pathzNode.get_temp_dir_path  
    ~r   c                     | j         S )z Get the path of the runtime env.)r   r  s    r   get_runtime_env_dir_pathzNode.get_runtime_env_dir_path  s    $$r   c                     | j         S )z&Get the path of the session directory.)r   r  s    r   r   zNode.get_session_dir_path        r   c                     | j         S )z(Get the path of the log files directory.)r   r  s    r   get_logs_dir_pathzNode.get_logs_dir_path  rN  r   c                     | j         S )z&Get the path of the sockets directory.)r   r  s    r   get_sockets_dir_pathzNode.get_sockets_dir_path  rR  r   r7  Nsuffixprefixdirectory_namec                 D   |#t           j        j                                        }t          j                            |          }| j        |||f         }|t          j	        k     r|dk    r$t          j        
                    |||z             }n6t          j        
                    ||dz   t          |          z   |z             }|dz  }t          j                            |          s|| j        |||f<   |S |t          j	        k     t          t          j        d          )a  Return an incremental temporary file name. The file is not created.

        Args:
            suffix: The suffix of the temp file.
            prefix: The prefix of the temp file.
            directory_name (str) : The base directory of the temp file.

        Returns:
            A string of file name. If there existing a file having
                the same name, the returned name will look like
                "{directory_name}/{prefix}.{unique_index}{suffix}"
        Nr   .r&   z"No usable temporary filename found)rN   r   rP   r   rX   ra   
expanduserr   tempfileTMP_MAXrb   r   existsFileExistsErrorerrnoEEXIST)r   rW  rX  rY  indexfilenames         r   _make_inc_tempzNode._make_inc_temp  s
    ! [.??AAN++N;;&vv~'EF h&&&zz7<<HH7<<"FSL3u::$=$F  QJE7>>(++  IN&vv~'EF h&&& el,PQQQr   c                 |    | j         j        }|-t          j                            t
          j                  dk    }|S )N1)rj   redirect_outputrX   rY   rZ   rf   ,LOGGING_REDIRECT_STDERR_ENVIRONMENT_VARIABLE)r   rh  s     r   should_redirect_logszNode.should_redirect_logs  sE    *:" 
!N    r   nameunique
create_out
create_errreturnc                     |                                  sdS d}d}|r|                     |d|          }|r|                     |d|          }||fS )a  Get filename to dump logs for stdout and stderr, with no files opened.
        If output redirection has been disabled, no files will
        be opened and `(None, None)` will be returned.

        Args:
            name: descriptive string for this log file.
            unique: if true, a counter will be attached to `name` to
                ensure the returned filename is not already used.
            create_out: if True, create a .out file.
            create_err: if True, create a .err file.

        Returns:
            A tuple of two file handles for redirecting optional (stdout, stderr),
            or `(None, None)` if output redirection is disabled.
        )NNNoutrl  rI  )rj  _get_log_file_name)r   rk  rl  rm  rn  
log_stdout
log_stderrs          r   get_log_file_nameszNode.get_log_file_names  sx    , ((** 	:

 	M00uV0LLJ 	M00uV0LLJ:%%r   c                     |                      ||||          \  }}|dnt          |          }|dnt          |          }||fS )a  Open log files with partially randomized filenames, returning the
        file handles. If output redirection has been disabled, no files will
        be opened and `(None, None)` will be returned.

        Args:
            name: descriptive string for this log file.
            unique: if true, a counter will be attached to `name` to
                ensure the returned filename is not already used.
            create_out: if True, create a .out file.
            create_err: if True, create a .err file.

        Returns:
            A tuple of two file handles for redirecting optional (stdout, stderr),
            or `(None, None)` if output redirection is disabled.
        rl  rm  rn  N)rv  r   )	r   rk  rl  rm  rn  log_stdout_fnamelog_stderr_fnamert  ru  s	            r   get_log_file_handleszNode.get_log_file_handles=  sj    , .2-D-DJ: .E .
 .
** .5TT8DT;U;U
-5TT8DT;U;U
:%%r   c                     |                     d          }|r!|                     d| || j                  }n*t          j                            | j        | d|           }|S )a  Generate partially randomized filenames for log files.

        Args:
            name: descriptive string for this log file.
            suffix: suffix of the file. Usually it is .out of .err.
            unique: if true, a counter will be attached to `name` to
                ensure the returned filename is not already used.

        Returns:
            A tuple of two file names for redirecting (stdout, stderr).
        r[  )rW  rX  rY  )stripre  r   rX   ra   rb   )r   rk  rW  rl  rd  s        r   rs  zNode._get_log_file_nameZ  su    $ c"" 	H**#6||D +  HH w||DNt4F4Ff4F4FGGHr   c                 @   |t                      }t          j        t          | j                  rt          j        nt          j        t          j                  }|                    d           |                                d         }t          t          j                  D ]}t          j        |d          }||v rt          j        t          | j                  rt          j        nt          j        t          j                  }	 |                    d|f           n$# t          $ r |                                 Y w xY w|                                 |                                 |c S t                               d           |                                 |S )N)r7  r   r&   i  r7  z-Unable to succeed in selecting a random port.)setsocketr   r   AF_INET6AF_INETSOCK_STREAMbindgetsocknamer;  rf   NUM_PORT_RETRIESrandomrandintOSErrorcloser   error)r   allocated_portssportr0   new_portnew_ss          r   _get_unused_portzNode._get_unused_portv  sj   "!eeOM&t'<==QFOO6>
 
 	
w}}q!
 }566 	 	A~dE22H?** M#*4+@#A#AUv~" E

B>****    GGIIIKKMMMOOODEEE				s   D  E Esocket_pathr>   c                 l   |}t           j        dk    r-|*dt          | j        |                                            }nt||                     || j                  }n,t          t          j	        
                    |                     t          |                    dd          d                    |S )ae  Prepare the socket file for raylet and plasma.

        This method helps to prepare a socket file.
        1. Make the directory if the directory does not exist.
        2. If the socket file exists, do nothing (this just means we aren't the
           first worker on the node).

        Args:
            socket_path: the socket file to prepare.
        win32Nztcp://)rX  rY  z://r&   )r   platformr
   ri   r  re  r   r   rX   ra   rc   r   r\   )r   r  r>   results       r   r   zNode._prepare_socket_file  s     <7"""V]4?D<Q<Q<S<STTVV  ",,)$:K -   ((D(DEEE$V\\%%;%;B%?@@@r   	port_namerB   c                    t           j                            |                                 d          }|t          j        v sJ t          t                    }t          |dz             5  t           j        	                    |          s=t          |d          5 }t          j        i |           ddd           n# 1 swxY w Y   t          |d          5 }|                    t          j        |                     ddd           n# 1 swxY w Y   | j        |v r0||| j                 v r!t!          || j                 |                   }nt#          || j                                                           }|||v rd}|p|                     |          }||| j                 |<   t          |d          5 }t          j        ||           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |S )a  Get a port number from a cache on this node.

        Different driver processes on a node should use the same ports for
        some purposes, e.g. exporting metrics.  This method returns a port
        number for the given port name and caches it in a file.  If the
        port isn't already cached, an unused port is generated and cached.

        Args:
            port_name: The name of the port, e.g. metrics_export_port.
            default_port: The port to return and cache if no port has already been
                cached for the given port_name. If None, an unused port is generated
                and cached.

        Returns:
            int: The port number.
        zports_by_node.jsonz.lockwNr)rX   ra   rb   r   rf   RAY_ALLOWED_CACHED_PORTSr   dictr	   r_  rA  r   dumpupdateloadr  rm   r  valuesr  )r   r  rB   	file_pathports_by_nodefr  r  s           r   r   zNode._get_cached_port  s   & GLL!:!:!<!<>RSS	 MBBBBB 4?t3D3Di')** 	0 	07>>),, %)S)) %QIb!$$$% % % % % % % % % % % % % % % i%% 3$$TYq\\2223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 -//t~!>>> =8CDD #&mDN&C&J&J&L&L"M"M+0O0O#'L#Mt'<'<_'M'M;?dn-i8)S)) 0QImQ///0 0 0 0 0 0 0 0 0 0 0 0 0 0 03	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	08 s   )0G2B;/G2;B?	?G2B?	G2(D
>G2
D	G2D	B'G29GG2G	G2"G	#G22G69G6<   	timeout_sc           	         t          |          D ]}t          j        j                            |                                           }||c S t          j        d           |dz  dk    r=t          	                    dt          j         d|                                  d           t          dt          j         d|                                  d| d	          )
a  Wait until the RAY_NODE_IP_FILENAME file is avialable.

        RAY_NODE_IP_FILENAME is created when a ray instance is started.

        Args:
            timeout_s: If the ip address is not found within this
                timeout, it will raise ValueError.
        Returns:
            The node_ip_address of the current session if it finds it
            within timeout_s.
        Nr&   
   r   zCan't find a `z` file from z@. Have you started Ray instance using `ray start` or `ray.init`?z. for z[ seconds. A ray instance hasn't started. Did you do `ray start` or `ray.init` on this host?)r;  rN   rO   r   get_cached_node_ip_addressr   r   r   r   r   rf   RAY_NODE_IP_FILENAMErJ   )r   r  ir4   s       r   r   z#Node._wait_and_get_for_node_address  s    y!! 	 	A!l3NN))++ O *&&&&JqMMM2v{{1]%G 1 1!%!:!:!<!<1 1 1   A]? A A2244A AA A A
 
 	
r   c                     | j         r
J d            t          j        j                            d          }t
          j        | j        vsJ ||g| j        t
          j        <   dS dS )z
        Start the reaper process.

        This must be the first process spawned and should only be called when
        ray processes should be cleaned up if this process dies.
        z4a reaper should not be used with kernel fate-sharingF)
fate_shareN)rR   rN   rO   r   start_reaperrf   PROCESS_TYPE_REAPERrT   )r   process_infos     r   r   zNode.start_reaper_process  s     &	B 	BA	B 	B&|,99U9KK08JJJJJ#ED}@AAA $#r   c           
      @   |                      dddd          \  }}t          j        j                            |                                 | j        | j        | j        | j	        | j
        ||          }t          j        | j        vsJ |g| j        t          j        <   dS )zStart the log monitor.log_monitorTrx  )r  ro   rp   stdout_filepathstderr_filepathN)rv  rN   rO   r   start_log_monitorr   r   rs   rR   ro   rp   rf   PROCESS_TYPE_LOG_MONITORrT   )r   stdout_log_fnamestderr_log_fnamer  s       r   r  zNode.start_log_monitor%  s    -1-D-D$4D .E .
 .
** |,>>%%''N-n*,, ? 	
 	
 5T=OOOOOF
=ABBBr   include_dashboardraise_on_failurec                L   |                      dddd          \  }}t          j        j                            ||| j        j        | j        | j        	                                | j
        | j        | j        | j        | j        j        | j        | j        | j        ||          \  | _        }t&          j        | j        vsJ |b|g| j        t&          j        <   |                                                     d| j                                        dt&          j                   dS dS )a  Start the dashboard.

        Args:
            include_dashboard: If true, this will load all dashboard-related modules
                when starting the API server. Otherwise, it will only
                start the modules that are not relevant to the dashboard.
            raise_on_failure: If true, this will raise an exception
                if we fail to start the API server. Otherwise it will print
                a warning if we fail to start the API server.
        	dashboardTrx  )r  r  ro   rp   r  r  Ns	   webui:url)rv  rN   rO   r   start_api_serverrj   r   rs   r2  r   r   r   r   r   r   rR   ro   rp   r   rf   PROCESS_TYPE_DASHBOARDrT   r   internal_kv_putencodeKV_NAMESPACE_DASHBOARD)r   r  r  r  r  r  s         r   r  zNode.start_api_server9  s>    .2-D-D$ .E .
 .
** ),(=(N(N+O!!!NN!0-n*,, )O )
 )
%" 34;MMMMM#HD}CD !!11&&((4	    	 $#r   c                 
   | j         j        }|dk    sJ | j        
J d            | j        
J d            |                     dddd          \  }}t
          j        j                            | j	        | j
        ||| j        | j         j        | j         j        | j        | j        || j         j        | j                  }t$          j        | j        vsJ |g| j        t$          j        <   t+          | j        |          | _        dS )	zStart the gcs server.r   NzGCS server is already running.z GCS client is already connected.
gcs_serverTrx  )log_dirr  r  r1   r   r   r   r  rF   rC   r4   )rj   rF   rt   ru   rv  rN   rO   r   start_gcs_serverrq   r   r1   r   r   rk   rR   rC   r   rf   r9  rT   r
   )r   rF   r  r  r  s        r   r  zNode.start_gcs_serverf  s,   *:"""" ((*J((('')K'''-1-D-D$4 .E .
 .
** |,==N,,*+:+:<-+#/B 1 > 
 
 4D<NNNNNE
=@A *$*?QQr   plasma_directoryfallback_directoryr
  use_valgrinduse_profilerc                    |                      t          j        ddd          \  }}|                      t          j        ddd          \  }}	|                      t          j        ddd          \  }
}| j                            |                                            t          j	        j
        j        | j        | j        | j        | j        | j        j        | j        | j        | j                                        | j        j        | j        j        | j        | j        | j        | j        |                                 |||| j        fi d|                                 d| j        j        d| j        j         d| j        j!        d| j        j"        d| j        j#        d	| j        j$        d
| j        j%        d| j        j&        d| j'        d| j        j(        d|d|d|d|d|d|	d|
d|d| j        j)        d| j*        ddd| j+        d| j,        d| j        j-        d| j        j.        d| j        j/        d| j0        d | j        }t          j        | j1        vsJ |g| j1        t          j        <   dS )!zStart the raylet.

        Args:
            use_valgrind: True if we should start the process in
                valgrind.
            use_profiler: True if we should start the process in the
                valgrind profiler.
        Trx  is_head_nodemin_worker_portmax_worker_portworker_port_listobject_manager_portr   r   rC   rE   rD   rA   r  r  raylet_stdout_filepathraylet_stderr_filepathdashboard_agent_stdout_filepathdashboard_agent_stderr_filepath!runtime_env_agent_stdout_filepath!runtime_env_agent_stderr_filepath
huge_pagesr  socket_to_useNro   rp   ray_debugger_externalenv_updates	node_namer   rS   )2rv  rf   PROCESS_TYPE_RAYLETPROCESS_TYPE_DASHBOARD_AGENTPROCESS_TYPE_RUNTIME_ENV_AGENTrS   add_system_pids,_get_system_processes_for_resource_isolationrN   rO   r   start_rayletrq   rs   r   r   rj   r;   r   r   r2  r   r*   r+   r   r   r   r   r  r1   r  r  r  r  r  r   r   rC   rE   r   rA   r  rR   ro   rp   r  r   r  r   rT   )r   r  r  r
  r  r  r  r  r  r  r  r  r  s                r   r  zNode.start_raylet  s     :>9P9P-	 :Q :
 :
6 6 ##6	 $ 
 
	
++ ##8	 $ 
 
	
-- 	&66==??	
 	
 	
 |,9M!.$*O!!(.N!N,,..'1
 1
 1
( )1
* !,<<+1
, !,<<-1
. "->>/1
0 !% 0 D D11
2  +::31
4  +::51
6  $/BB71
8 $(#3#J#J91
: !% 9 9;1
< )-(8(T(T=1
> &?1
@ &A1
B $:#9C1
D $:#9E1
F -L,KG1
H -L,KI1
J /P.OK1
L /P.OM1
N '22O1
P --Q1
R $S1
T nnU1
V **W1
X #'"2"H"HY1
Z (11[1
\ &00]1
^ //_1
` '+&D&Da1
d 08JJJJJAM=<===r   c                 ^   ddl m} |                     dddd          \  }}t          j        j                            | j        | j        ||| j	        j
        | j        | j        | j        | j         |d          
  
        }t          j        | j        vsJ |g| j        t          j        <   dS )	zStart the monitor.

        Autoscaling output goes to these monitor.err/out files, and
        any modification to these files may break existing
        cluster launching commands.
        r   )is_autoscaler_v2monitorTrx  )fetch_from_server)r  r  autoscaling_configr  ro   rp   
monitor_ipautoscaler_v2N)ray.autoscaler.v2.utilsr  rv  rN   rO   r   start_monitorrs   r   rj   r  rR   ro   rp   r   rf   PROCESS_TYPE_MONITORrT   )r   r  r  r  r  s        r   r  zNode.start_monitor  s     	=<<<<<-1-D-Ddt .E .
 .
** |,::N,,#/B-n*,**TBBB ; 
 
 19KKKKKBN==>>>r   c                 L   |                      dd          \  }}t          j        j                            | j        | j        | j        j        ||| j        j	        | j        j
        | j        | j        	  	        }t          j        | j        vsJ |g| j        t          j        <   dS )z$Start the ray client server process.ray_client_serverTrr  )stdout_filestderr_filer   r   r  r#  N)r{  rN   rO   r   start_ray_client_serverrw   r   rj   ray_client_server_portr   r   rR   r#  rf   PROCESS_TYPE_RAY_CLIENT_SERVERrT   )r   r  r  r  s       r   r  zNode.start_ray_client_server  s    #'#<#< $= $
 $
 [ |,DDL!3##+:+:-&*&D E 

 

 ;4CUUUUUL
=GHHHr   c                    ddl mc mc m} |                    |                                 | j                   |                                                     d| j        	                                dt          j                  }|sf|                                                     dt          j                  }|| j        	                    d          k    sJ d| j         d| d	            |                                                     d
| j        	                                dt          j                   |                                                     d| j        	                                dt          j                   | j        j        rR|                                                     d| j        j        	                                dt          j                   dS dS )zWrite the cluster metadata to GCS.
        Cluster metadata is always recorded, but they are
        not reported unless usage report is enabled.
        Check `usage_stats_head.py` for more details.
        r   N)r"   r   Fzutf-8zSession name z  does not match persisted value z1. Perhaps there was an error connecting to Redis.s   session_dirTs   temp_dirs   tracing_startup_hook)r   r   r   r   put_cluster_metadatar   r"   r  ry   r  rf   r   r<  r   r   rj   tracing_startup_hookKV_NAMESPACE_TRACING)r   r   addedcurr_vals       r   _write_cluster_info_to_kvzNode._write_cluster_info_to_kv  s    	<;;;;;;;;;;;**!!D4I 	+ 	
 	
 	
 ##%%55%%''.	
 
  	**,,<<!C H t188AAAAA. 2 . .#+. . . BAA 	--$$&&.		
 	
 	
 	--N!!##.		
 	
 	
 0 	!!11' 5<<>>2	    	 	r   c                    t                               d| j         d           | j        J | j        J |                                  |                                 J |                                  | j        j	        s| 
                                 | j        j        r|                                  | j        j        d}n| j        j        }|                     | j        j        |           dS )z!Start head processes on the node.1Process STDOUT and STDERR is being redirected to r[  NF)r  r  )r   r   r   rt   ru   r  r   r  rj   
no_monitorr  r  r  r  r  )r   raise_on_api_server_failures     r   r   zNode.start_head_processesM  s   UDNUUU	
 	
 	
  ((('''""$$000&&(((* 	!   2 	+((***-5*/''*.*:*L'".@8 	 	
 	
 	
 	
 	
r   c                    t                               d| j         d           | j        st          j        j                            | j        | j	        
                                dd          }t          j        j                                        }|                    |           |                                }| j                                        |                                k    sJ d| j         d|             || _        |                                 }|j                            t          j        j                  rBddlm} |                    |j                            t          j        j                             t          j        j                            |j        | j        | j        j        | j        | j        j         	          \  }}}| j!        "                                r| j!        #                    |           | j        j$        r| %                                 | &                    |||           d
S )z'Start all of the processes on the node.r  r[  F)allow_cluster_id_nilfetch_cluster_id_if_nilzThe system config from GCS is not a superset of the local system config. There might be a configuration inconsistency issue between the head node and non-head nodes. Local system config: z, GCS system config: r   )r   )r  r  r  N)'r   r   r   r   rN   _rayletGcsClientOptionscreaters   r2  r   rO   stateGlobalState_initialize_global_stateget_system_configrk   itemsr  rI   rZ   RAY_NODE_ACCELERATOR_TYPE_KEYray._common.usager   record_hardware_usager   determine_plasma_store_configr
  r   rj   r  r   r  rS   
is_enabledadd_object_store_memoryr(   r  r  )	r   gcs_optionsglobal_state
new_configresource_and_label_specr   r  r  r
  s	            r   r   zNode.start_ray_processesj  sS   UDNUUU	
 	
 	
 y 	&+6== ##%%%*(-	 >  K <-99;;L11+>>>%7799J<%%'':+;+;+=+====4 *.4 4 (2	4 4 >== &DL #'"B"B"D"D")--K5
 
 		 433333++'.22K=    L!??#7N!->#7'2 @ 
 
		
 )4466 	X*BBCVWWW/ 	%""$$$*,>@STTTTTr   c                 P   d | j                                         D             }t          j        | j         v r\| j         t          j                 d         j        j        }t          j        |          }|d |                                D             z  }d	                    |          S )a  Returns a list of system processes that will be isolated by raylet.

        NOTE: If a new system process is started before the raylet starts up, it needs to be
        added to self.all_processes so it can be moved into the raylet's managed cgroup
        hierarchy.
        c                 L    g | ]!}t          |d          j        j                  "S )r   )r   r:  pidr4  ps     r   r5  zENode._get_system_processes_for_resource_isolation.<locals>.<listcomp>  s6     
 
 
&'C! !!
 
 
r   r   c                 6    g | ]}t          |j                  S r   )r   r  r  s     r   r5  zENode._get_system_processes_for_resource_isolation.<locals>.<listcomp>  s     #U#U#U1CJJ#U#U#Ur   r%   )
rT   r  rf   r  r:  r  psutilProcesschildrenrb   )r   system_process_pidsdashboard_piddashboard_processs       r   r  z1Node._get_system_processes_for_resource_isolation  s    
 
+/+=+D+D+F+F
 
 
 /43EEE .}/STc  !'} = =#U#U8I8R8R8T8T#U#U#UUxx+,,,r   r   r   waitc                 x    | j         5  |                     ||||           ddd           dS # 1 swxY w Y   dS )aN  Kill a process of a given type.

        If the process type is PROCESS_TYPE_REDIS_SERVER, then we will kill all
        of the Redis servers.

        If the process was started in valgrind, then we will raise an exception
        if the process has a non-zero exit code.

        Args:
            process_type: The type of the process to kill.
            allow_graceful: Send a SIGTERM first and give the process
                time to exit gracefully. If that doesn't work, then use
                SIGKILL. We usually want to do this outside of tests.
            check_alive: If true, then we expect the process to be alive
                and will raise an exception if the process is already dead.
            wait: If true, then this method will not return until the
                process in question has exited.

        Raises:
            This process raises an exception in the following cases:
                1. The process had already died and check_alive is true.
                2. The process had been started in valgrind and had a non-zero
                   exit code.
        )r   r   r  N)rW   _kill_process_impl)r   process_typer   r   r  s        r   _kill_process_typezNode._kill_process_type  s    B  	 	##-'	 $   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   /33c                 l   || j         vrdS | j         |         }|t          j        k    rt          |          dk    sJ |D ]}|j        }|                                |rt          d| d          4|j        r|                                 |	                                 |j
        dk    rd| d|j
         d}|j        Gt          |j        d	          5 }	|d
|	                                z   z  }ddd           n# 1 swxY w Y   |j        Gt          |j        d	          5 }	|d|	                                z   z  }ddd           n# 1 swxY w Y   t          |          )|j        r8t!          j        |j        t&          j                   t+          j        d           |rB|                                 d}
	 |	                    |
           n# t.          j        $ r Y nw xY w|                                *|                                 |r|	                                 | j         |= dS )zSee `_kill_process_type`.Nr&   z&Attempting to kill a process of type 'z$', but this process is already dead.r   z1Valgrind detected some errors in process of type z. Error code r[  r  z
PROCESS STDOUT:
z
PROCESS STDERR:
rG   )rT   rf   PROCESS_TYPE_REDIS_SERVERr]   r:  r=  r   r  	terminater  
returncoder  rA  readr  use_valgrind_profilerrX   killr  signalSIGINTr   r   
subprocessTimeoutExpired)r   r!  r   r   r  process_infosr  r:  messager  timeout_secondss              r   r   zNode._kill_process_impl  s#    t111F*<8=BBB}%%****) 2	# 2	#L"*G||~~) &O(O O O  
 ( !!###%**Q ,Q Q;B;MQ Q Q  $/;!,":C@@ HA#'<qvvxx'GGGH H H H H H H H H H H H H H H#/;!,":C@@ HA#'<qvvxx'GGGH H H H H H H H H H H H H H H&w///1  V]333
3 !!###"#LL1111!0   D ||~~%  #LLNNN|,,,s6   C??D	D	&EE	E	GG)(G)c                 H    |                      t          j        |           dS )zKill the Redis servers.

        Args:
            check_alive: Raise an exception if any of the processes
                were already dead.
        r   N)r"  rf   r$  r   r   s     r   
kill_rediszNode.kill_redis%  s3     	3 	  	
 	
 	
 	
 	
r   c                 H    |                      t          j        |           dS )zKill the raylet.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        r2  N)r"  rf   r  r3  s     r   kill_rayletzNode.kill_raylet0  3     	-; 	  	
 	
 	
 	
 	
r   c                 H    |                      t          j        |           dS )zKill the log monitor.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        r2  N)r"  rf   r  r3  s     r   kill_log_monitorzNode.kill_log_monitor;  s3     	2 	  	
 	
 	
 	
 	
r   c                 H    |                      t          j        |           dS )zKill the dashboard.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        r2  N)r"  rf   r  r3  s     r   kill_dashboardzNode.kill_dashboardF  s3     	0k 	  	
 	
 	
 	
 	
r   c                 H    |                      t          j        |           dS )zKill the monitor.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        r2  N)r"  rf   r  r3  s     r   kill_monitorzNode.kill_monitorQ  s3     	.K 	  	
 	
 	
 	
 	
r   c                 f    |                      t          j        |d           d| _        d| _        dS )zKill the gcs server.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        T)r   r  N)r"  rf   r9  rt   ru   r3  s     r   kill_gcs_serverzNode.kill_gcs_server\  sD     	1{QU 	  	
 	
 	
 !r   c                 H    |                      t          j        |           dS )zKill the reaper process.

        Args:
            check_alive: Raise an exception if the process was already
                dead.
        r2  N)r"  rf   r  r3  s     r   kill_reaperzNode.kill_reaperj  r7  r   c                    t           j        | j        v r#|                     t           j        |||           t           j        | j        v r#|                     t           j        |||           t          | j                                                  D ]+}|t           j        k    r|                     ||||           ,t           j        | j        v r%|                     t           j        |||           dS dS )a  Kill all of the processes.

        Note that This is slower than necessary because it calls kill, wait,
        kill, wait, ... instead of kill, kill, ..., wait, wait, ...

        Args:
            check_alive: Raise an exception if any of the processes were
                already dead.
            wait: If true, then this method will not return until the
                process in question has exited.
        )r   r   r  N)rf   r  rT   r"  r9  r   keysr  )r   r   r   r  r!  s        r   r   zNode.kill_all_processesu  s4   " ,0BBB##1'-	 $    0D4FFF##5'-	 $    !!3!8!8!:!:;; 		 		L }@@@''  +#1	 (    ,0BBB##1'-	 $      CBr   c                     g }| j                                         D ]?\  }}|D ]7}|j                                        |                    ||j        f           8@|S )ziReturn a list of the live processes.

        Returns:
            A list of the live processes.
        rT   r  r:  r=  r^   r   r  r!  r.  r  s        r   live_processeszNode.live_processes  s|     +/+=+C+C+E+E 	H 	H'L- - H H',,..6MM<1E"FGGGH r   c                     g }| j                                         D ]?\  }}|D ]7}|j                                        |                    ||j        f           8@|S )a-  Return a list of the dead processes.

        Note that this ignores processes that have been explicitly killed,
        e.g., via a command like node.kill_raylet().

        Returns:
            A list of the dead processes ignoring the ones that have been
                explicitly killed.
        rE  rF  s        r   dead_processeszNode.dead_processes  s|     +/+=+C+C+E+E 	H 	H'L- - H H',,..:MM<1E"FGGGH r   c                 D    t          |                                           S )zxReturn true if any processes are still alive.

        Returns:
            True if any process is still alive.
        )anyrG  r  s    r   any_processes_alivezNode.any_processes_alive  s     4&&(()))r   c                 F    t          |                                            S )a!  Return true if all remaining processes are still alive.

        Note that this ignores processes that have been explicitly killed,
        e.g., via a command like node.kill_raylet().

        Returns:
            True if any process that wasn't explicitly killed is still alive.
        )rK  rI  r  s    r   remaining_processes_alivezNode.remaining_processes_alive  s!     t**,,----r   c                     | j                             di           }|rQt          j        |          }ddlm} |                    || j        | j                  }|	                                 d S d S )Nobject_spilling_configr   external_storage)
rk   rZ   r   r   ray._privaterR  setup_external_storager   ry   destroy_external_storage)r   rP  rR  storages       r   rU  zNode.destroy_external_storage  s    !%!1!12JB!O!O! 	/%)Z0F%G%G"555555&==&t7I G ,,.....	/ 	/r   c                    | j                             dd          }|sdS | j        }t          j        |          }|| j        j        d<   || j         d<   |d         dk    }|| j        j        d<   || j         d<   dd	lm} t          j
                                                                        }|                    ||| j                  }|                                 |                                 dS )
z<Make sure we can setup the object spilling external storage.!automatic_object_spilling_enabledTNrP  r5   r6   is_external_storage_type_fsr   rQ  )rk   rZ   r   r   r   rj   r_   rS  rR  rN   r   r   r   rT  ry   rU  reset_external_storage)r   automatic_spilling_enabledrP  deserialized_configrY  rR  dummy_node_idrV  s           r   r   zNode.validate_external_storage  s,    &*\%5%5/&
 &
" * 	F!%!=
 #j)?@@ # 	'$	
 2H-.&9&&A\&Q# ( 	')	
 7R23 	211111 
..004466"990B
 
 	((***//11111r   c                    | j         j        }|s| j                            dd          }|s t          j                            dd          }|rt          j        dd|id          S | j                            di           }|s t          j                            dd          }|st          j        dd| j        id          }n(t                      st                              d	           |S )
a  Consolidate the object spilling config from the ray params, environment
        variable, and system config. The object spilling directory specified through
        ray params will override the one specified through environment variable and
        system config.object_spilling_directoryr7  RAY_object_spilling_directoryr6   r8   )r5   r7   rP  RAY_object_spilling_configa  The object spilling config is specified from an unstable API - system config or environment variable. This is subject to change in the future. You can use the stable API - --object-spilling-directory in ray start or object_spilling_directory in ray.init() to specify the object spilling directory instead. If you need more advanced settings, please open a github issue with the Ray team.)rj   r_  rk   rZ   rX   rY   r   dumpsr   r   r   warning)r   r_  rP  s      r   r   z Node._get_object_spilling_config  s.    %)$4$N!( 	(,(8(8+R) )% ) 	(*
/) )% % 	:(/1JK    "&!1!12JB!O!O% 	V%'Z^^4PRT%U%U" & 	%)Z%2BDDU1VWW& &"" << 
 	 	 	 &%r   c                     ddl m}m}m} t          j        j                                        s6t          j        j                            | 	                                           t          j        j                                        sJ | j
        r4t          j                            d          dnd} ||j        |           t          j        j                                        }|r ||d d                    d S d S )Nr   )TagKeyrecord_extra_usage_tagr
  r$   redisr	  2   )r   re  rf  r
  rN   rC  rD  _internal_kv_initializedrE  r   r   rX   rY   rZ   GCS_STORAGErO   rP   get_current_node_cpu_model_name)r   re  rf  r
  gcs_storage_typecpu_model_names         r   r   zNode._record_statsC  s&   	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 +DDFF 	X(@@ATATAVAVWWW+DDFFFFF9 	I :>>*=>>JPX  #"6#57GHHH+KKMM 	7 "!.""566666		7 	7r   )FTTFFF)r7  r7  N)FTT)Fr/  )r  )FF)FTF)T)TFF)V__name__
__module____qualname____doc__rM   r   rz   staticmethodrv   r   rK   r   r  propertyr<   r1   r4   rw   rs   rq   r   r   r   r  r  r:   r;   rD   rE   r#  rA   r(  r+  r-  r  r   rx   rM  rP  r   rT  rV  r   r   re  rj  r   rv  r   r   r{  rs  r  r   rm   r   r   r   r  r  r  r  r  r  r  r   r   r  r"  r   r4  r6  r9  r;  r=  r?  rA  r   rG  rI  rL  rN  rU  r   r   r   r   r   r   r   r   4   s       	 	 !%!"$!&C! C! C! 	C!
 C! C! C! C! C! C! C!J

 
 
0 
 
 \

 
 
,@ @ @"=: =: =:~- - -   X " " X" % % X% ! ! X! ! ! X!
 # # X# / / X/ / / X/ . . X. J J XJ   X ( ( X( 2 2 X2 ) ) X) , , X, ^ ^ X^ 1 1 X1 
 
 X
 
 
 X
 ! ! X!       
9O 9O 9Ov  % % %! ! !  ! ! !
 SW"R "R"R(+"RBJ3-"R "R "R "RH
 
 
   &  & &  & 	 &
  & 
x}hsm+	, &  &  &  &J & && & 	&
 & 
x6
#Xbj%99	:& & & &B 	   	
 
   8" " " "H S    : =A7 77,4SM7	7 7 7 7r#
 #
 #
S #
 #
 #
 #
J  "
 
 
(+$,TN+FJ+ + + +Z R  R  RN #"`O `O`O  `O !	`O
 `O `O `O `O `ODP P P6
 
 
*1 1 1f
 
 
:;U ;U ;Uz-c - - - -2  % ' ' ' 	'
 ' ' ' 'T JO=- =- =- =-~	
 	
d 	
 	
 	
 	
	
 	
t 	
 	
 	
 	
	
 	
D 	
 	
 	
 	
	
 	
$ 	
 	
 	
 	
	
 	
 	
 	
 	
 	
   4        	
 	
t 	
 	
 	
 	
4 4 4 4l    "* * *	. 	. 	.	/ 	/ 	/(2 (2 (2T0& 0& 0&d7 7 7 7 7r   r   );r   r   r{   ra  r   loggingrX   r  r*  r  r,  r   r]  rU   r   r>  r   typingr   r   r   r   r   filelockr	   rN   ray._private.ray_constantsrO   rf   ray._private.servicesray._common.network_utilsr
   r   r   r   ray._common.ray_constantsr   r   ray._common.utilsr   $ray._private.resource_and_label_specr   &ray._private.resource_isolation_configr   r   r   ray._private.utilsr   r   r   r   ray._rayletr   r   r  	getLoggerrn  r   r   r   r   r   <module>r     st            				        



           # # # # # # 4 4 4 4 4 4 4 4 4 4 4 4 4 4       



 2 2 2 2 2 2 2 2 2                X W W W W W W W 5 5 5 5 5 5 E E E E E E J J J J J J ? ? ? ? ? ? ? ?            @ ? ? ? ? ? ? ? 
 
	8	$	$f7 f7 f7 f7 f7 f7 f7 f7 f7 f7r   