
    &`iM                        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 d dl	mZ d dlmZmZ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 m!Z!m"Z"m#Z# d dl$m%Z& d dl'Z'erd d	l(m)Z) d
Z*dZ+e
j        dk    rd dl+Z+ ej,        e-          Z.da/da0da1dej2        v Z3 ed           Z4 ej5                    Z6 ej7        d          Z8 ej7        d          Z9dde:dee:         fdZ;ddee:         de:fdZ<dde:de=fdZ>	 dde:de:dee:         fdZ?	 dde:de:fdZ@dd ZAd! ZBd" ZCd# ZDd$ ZEdee:eee:                  f         fd%ZFde=fd&ZGdee:ee:         f         fd'ZHd(ee:ee:         f         ddfd)ZI G d* d+eJ          ZKdd,ZL	 	 	 	 ddeeM         fd1ZNe3d2fd3e=d4e=deMfd5ZOd6e:d7e:d8e:d9e:fd:ZPd; ZQd< ZRd= ZSd>eTd?e:d@e:dAdBddf
dCZUdD ZVdE ZWdF ZXdG ZYdH ZZdI Z[dJ Z\dK Z]dL Z^dM Z_dN Z`dO Zae
j        ejb        e
jc        jd        e
jc        je        fdfdPe:dQe:dReefeff         dSee:         de:f
dTZgejh        e
j        ejb        e
jc        ddU         fdVe:dPe:dQe:dReefeff         de:f
dWZiejh        e
j        ejb        e
jc        ddU         fdVe:dPe:dQe:dReefeff         de:f
dXZjdYe:fdZZkdeel         fd[Zmdeel         fd\Znd]Zodd_Zpdd`Zq	 ddbe:dee:eMf         fdcZr	 ddee:dee:e:f         fdfZsddgZtdh Zuddjee:ef         deffdkZv	 	 ddlZwdddmdndodpe=dqe=fdrZxdneeedof                  fdsZydte:dee:e:f         fduZzdv Z{ G dw dxe j|                  Z}dyee:         ddfdzZ~d{efd|Zd}ee:e:f         fd~Zdee:eMf         dee:eMf         fdZd Zdee:         fdZde:fdZdad ZdS )    N)defaultdict)Path)list2cmdline)TYPE_CHECKINGDictListMappingOptionalTupleUnion)json_format)$PLACEMENT_GROUP_BUNDLE_RESOURCE_NAMEget_ray_address_fileget_system_memory)RuntimeEnvInfo
RuntimeEnviwin32RAY_DISABLE_DOCKER_CPU_WARNINGc                      dS Nr    r       f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/_private/utils.py<lambda>r   D   s    1 r   z(.+)_group_(\d+)_([0-9a-zA-Z]+)z(.+)_group_([0-9a-zA-Z]+)ray_addresstemp_dirc           	         t          |          }t          j                            |          rht	          |d          5 }|                                }d d d            n# 1 swxY w Y   || k    rd S t                              d| d|  d| d           t	          |d          5 }|                    |            d d d            d S # 1 swxY w Y   d S )Nrz"Overwriting previous Ray address (zK). Running ray.init() on this node will now connect to the new instance at z*. To override this behavior, pass address=z to ray.init().zw+)	r   ospathexistsopenreadloggerinfowrite)r   r   address_filefprev_addresss        r   write_ray_addressr+   M   sq   '11L	w~~l## 
,$$ 	$6688L	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$;&&F5 5 5&5 5 $5 5 5	
 	
 	
 
lD	!	! Q	                 s#   A  A$'A$'C

CCreturnc                    t          |           }t          j                            |          sd S t	          |d          5 }|                                                                cd d d            S # 1 swxY w Y   d S )Nr   )r   r    r!   r"   r#   r$   strip)r   r(   r)   s      r   read_ray_addressr/   `   s    '11L7>>,'' t	lC	 	   Avvxx~~                                   s   &A44A8;A8Fexception_messagetask_exceptionc                     |                      d          }|r|dd         |dd         z   }	 d                    |          S )a  Improve the formatting of an exception thrown by a remote function.

    This method takes a traceback from an exception and makes it nicer by
    removing a few uninformative lines and adding some space to indent the
    remaining lines nicely.

    Args:
        exception_message: A message generated by traceback.format_exc().

    Returns:
        A string of the formatted exception message.
    
r         N)splitjoin)r0   r1   liness      r   format_error_messager9   h   sP     ##D))E  ac
U122Y&99Ur   
error_typemessagejob_idc                     |t           j                                        }t          |t           j                  sJ | j                            |||t          j                               dS )a  Push an error message to the driver to be printed in the background.

    Args:
        worker: The worker to use.
        error_type: The type of the error.
        message: The message that will be printed in the background
            on the driver.
        job_id: The ID of the driver to push the error message to. If this
            is None, then the message will be pushed to all drivers.
    N)rayJobIDnil
isinstancecore_worker
push_errortime)workerr:   r;   r<   s       r   push_error_to_driverrF   ~   sY     ~fci(((((
!!&*gty{{KKKKKr   c                 ^   |t           j                                        }t          |t           j                  sJ 	 |                    |                                                                | ||d           dS # t          $ r% t          	                    d| d|  d           Y dS w xY w)a  Push an error message to the driver to be printed in the background.

    Normally the push_error_to_driver function should be used. However, in some
    instances, the raylet client is not available, e.g., because the
    error happens in Python before the driver or worker has connected to the
    backend processes.

    Args:
        error_type: The type of the error.
        message: The message that will be printed in the background
            on the driver.
        gcs_client: The GCS client to use.
        job_id: The ID of the driver to push the error message to. If this
            is None, then the message will be pushed to all drivers.
    N<   zFailed to publish error: z [type ])
r>   r?   r@   rA   publish_errorhexencode	Exceptionr%   	exception)r:   r;   
gcs_clientr<   s       r   publish_error_to_driverrP      s    * ~fci(((((T  !4!4!6!6
GVUWXXXXX T T TRWRRZRRRSSSSSSTs   =A= =+B,+B,utf-8strictc                     t          | t                    r| S t          | t                    sJ dt          |                        |                     ||          S )zQCoerce *s* to `str`.

    - `str` -> `str`
    - `bytes` -> decoded to `str`
    zExpected str or bytes, got )rA   strbytestypedecode)sencodingerrorss      r   
ensure_strr[      s\     !S *!U##LL%L477%L%LLL#xx&)))r   c                 *    t          j        |           S N)r>   	ObjectRef)binary_object_refs    r   binary_to_object_refr`      s    =*+++r   c                 *    t          j        |           S r]   )r>   TaskID)binary_task_ids    r   binary_to_task_idrd      s    :n%%%r   c                     t          | t          j                  sJ t          j        |                                 dt          j                                                           S r   )rA   r>   WorkerIDr?   binarysize)	driver_ids    r   compute_job_id_from_driverrj      sL    i.....9Y%%''CINN,<,<(<=>>>r   c                     t          | t          j                  sJ t          j        |                                 z
  }|                                 |dz  z   }t          j        |          S )N   )rA   r>   r?   ray_constantsID_SIZErh   rg   rf   )r<   rest_lengthdriver_id_strs      r   compute_driver_id_from_jobrq      sV    fci((((('&++--7KMMOO{W'<=M<&&&r   c                  @    ddl mm}  fd |             D             S )zFGet the mapping from accelerator resource name
    to the visible ids.r   )$get_accelerator_manager_for_resource"get_all_accelerator_resource_namesc                 L    i | ] }| |                                           !S r   )+get_current_process_visible_accelerator_ids).0accelerator_resource_namers   s     r   
<dictcomp>z/get_visible_accelerator_ids.<locals>.<dictcomp>   sJ        & 	"#G#G%$
 $

5
5
7
7  r   )ray._private.acceleratorsrs   rt   )rt   rs   s    @r   get_visible_accelerator_idsr{      sb           
    *L)K)M)M	   r   c                     t           j                            d          } | dS t          j                    }|j        j        t          j        j        j        k    rdS |	                                                    d          }|t                              d           d}ddl}t          |                    |          d          }t          |          t           j        d<   dS )	a)  Set the OMP_NUM_THREADS to default to num cpus assigned to the worker

    This function sets the environment variable OMP_NUM_THREADS for the worker,
    if the env is not previously set and it's running in worker (WORKER_MODE).

    Returns True if OMP_NUM_THREADS is set in this function.

    OMP_NUM_THREADSNFCPUz[ray] Forcing OMP_NUM_THREADS=1 to avoid performance degradation with many workers (issue #6998). You can override this by explicitly setting OMP_NUM_THREADS, or changing num_cpus.r4   r   T)r    environgetr>   get_runtime_contextrE   mode_privateWORKER_MODEget_assigned_resourcesr%   debugmathmaxfloorrT   )num_threads_from_envruntime_ctxnum_assigned_cpusr   omp_num_threadss        r   set_omp_num_threads_if_unsetr      s     :>>*;<<'u )++K#,"5"AAAu#::<<@@GG K	
 	
 	

 KKK $**%677;;O$'$8$8BJ !4r   c                     ddl m}  i } | t          j        j        j        d          }t          j                                                                                    D ]\  }}|st          |          dk    rt          j        j        
                    |                                          }t          j                            |d          ||<   t          j        j        
                    |                              |           |S )a  Set (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, HIP_VISIBLE_DEVICES,
    NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS , HABANA_VISIBLE_MODULES ,...)
    environment variables based on the accelerator runtime. Return the original
    environment variables.
    r   )env_boolTN)ray._private.ray_constantsr   r>   r   accelerators*RAY_ACCEL_ENV_VAR_OVERRIDE_ON_ZERO_ENV_VARr   get_accelerator_idsitemslenrs   #get_visible_accelerator_ids_env_varr    r   r   +set_current_process_visible_accelerator_ids)r   %original_visible_accelerator_env_varsoverride_on_zeroresource_nameaccelerator_idsenv_vars         r   set_visible_accelerator_idsr     s    433333,.)x!L 
 	!!5577==??G G&   	C$8$8A$=$=,+PP
 

-
-
/
/ 	 :<QU9V9V-g6!FF	
 	

5
5o
F
F
F
F00r   r   c                     |                                  D ]7\  }}|!t          j                            |d           (|t          j        |<   8dS )z>Reset the visible accelerator env vars to the original values.N)r   r    r   pop)r   r   	env_values      r   "reset_visible_accelerator_env_varsr   )  s]     DIIKK , ,JNN7D))))"+BJw	, ,r   c                   4     e Zd ZdZd Zd Zd Z fdZ xZS )
UnbufferedaL  There's no "built-in" solution to programatically disabling buffering of
    text files. Ray expects stdout/err to be text files, so creating an
    unbuffered binary file is unacceptable.

    See
    https://mail.python.org/pipermail/tutor/2003-November/026645.html.
    https://docs.python.org/3/library/functions.html#open

    c                     || _         d S r]   )stream)selfr   s     r   __init__zUnbuffered.__init__?  s    r   c                 l    | j                             |           | j                                          d S r]   )r   r'   flush)r   datas     r   r'   zUnbuffered.writeB  s2    $r   c                 l    | j                             |           | j                                          d S r]   )r   
writelinesr   )r   datass     r   r   zUnbuffered.writelinesF  s2    u%%%r   c                 |    |dk    r!t                                          d          S t          | j        |          S )Nr   )super__getattribute__getattrr   )r   attr	__class__s     r   __getattr__zUnbuffered.__getattr__J  s8    877++H555t{D)))r   )	__name__
__module____qualname____doc__r   r'   r   r   __classcell__)r   s   @r   r   r   4  so               * * * * * * * * *r   r   c                     |                     dd           |                     dd           |                     dd           t          | fi |}|rt          |          S |S )z[
    Opens the log file at `path`, with the provided kwargs being given to
    `open`.
    	bufferingr4   r   arY   rQ   )
setdefaultr#   r   )r!   
unbufferedkwargsr   s       r   open_logr   Q  sv     k1%%%
fc"""
j'***$!!&!!F &!!!r   #/sys/fs/cgroup/cpu/cpu.cfs_quota_us$/sys/fs/cgroup/cpu/cpu.cfs_period_us!/sys/fs/cgroup/cpuset/cpuset.cpus/sys/fs/cgroup/cpu.maxc                 p   d }t           j                            |           rt           j                            |          r	 t          | d          5 }t          |d          5 }t	          |                                          t	          |                                          z  }d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   n# t          $ r t                              d           Y nw xY wt           j                            |          r	 t          |                                          }|	                                \  }}	|
                                r4|	
                                r t	          |          t	          |	          z  }nd }n*# t          $ r t                              d           Y nw xY w|	|dk     rd }n|dk    rd}d }
t           j                            |          r	 t          |          5 }|                                }|	                    d          }g }|D ]}d|v rf|	                    d          \  }}|                    t          t          t          |          t          |          dz                                  l|                    t          |                     t!          |          }
d d d            n# 1 swxY w Y   n*# t          $ r t                              d           Y nw xY w|r|
rt#          ||
          S |p|
S )Nr   z.Unexpected error calculating docker cpu quota.r   r4   ,-z/Unexpected error calculating docker cpuset ids.)r    r!   r"   r#   floatr$   rM   r%   rN   r6   	isnumericextendlistrangeintappendr   min)cpu_quota_file_namecpu_period_file_namecpuset_file_namecpu_max_file_name	cpu_quota
quota_fileperiod_filemax_file	quota_str
period_str
cpuset_numcpuset_fileranges_as_stringrangescpu_idsnum_or_rangestartends                     r   _get_docker_cpusr   a  s0    I	w~~)** Orw~~>R/S/S O	O(#..Q2<)3//Q3>!*//"3"344u[=M=M=O=O7P7PP		Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q
  	O 	O 	OMNNNNN	O 
)	*	* 
O		O-..3355H$,NN$4$4!Iz""$$ !)=)=)?)? !!),,uZ/@/@@		 !	 	O 	O 	OMNNNNN	OIMM			a	J	w~~&'' P	P&'' 
*;#.#3#3#5#5 )//44$* : :Ll**%1%7%7%<%<
stE#e**c#hhl,K,K'L'LMMMMs<'8'89999 \\

* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
* 
*  	P 	P 	PNOOOOO	P
  *Z *9j)))"
"s   C C
#AB3'C
3B7	7C
:B7	;C
>C 
CC CC $C=<C= BF# #$G
	G
K6 CK*K6 *K..K6 1K.2K6 6$LLToverride_docker_cpu_warningtruncatec                    t          j                    }t          j                            d          rt
                              d           |S 	 t                      }|||k    rdt          j        vr#t          s| st
          	                    d           t          |          t          |          k    r.t
          	                    d| dt          |           d           |rt          |          }|}n# t          $ r Y nw xY w|S )	a4  
    Get the number of CPUs available on this node.
    Depending on the situation, use multiprocessing.cpu_count() or cgroups.

    Args:
        override_docker_cpu_warning: An extra flag to explicitly turn off the Docker
            warning. Setting this flag True has the same effect as setting the env
            RAY_DISABLE_DOCKER_CPU_WARNING. By default, whether or not to log
            the warning is determined by the env variable
            RAY_DISABLE_DOCKER_CPU_WARNING.
        truncate: truncates the return value and drops the decimal part.
    !RAY_USE_MULTIPROCESSING_CPU_COUNTzDetected RAY_USE_MULTIPROCESSING_CPU_COUNT=1: Using multiprocessing.cpu_count() to detect the number of CPUs. This may be inconsistent when used inside docker. To correctly detect CPUs, unset the env var: `RAY_USE_MULTIPROCESSING_CPU_COUNT`.NKUBERNETES_SERVICE_HOSTal  Detecting docker specified CPUs. In previous versions of Ray, CPU detection in containers was incorrect. Please ensure that Ray has enough CPUs allocated. As a temporary workaround to revert to the prior behavior, set `RAY_USE_MULTIPROCESSING_CPU_COUNT=1` as an env var before starting Ray. Set the env var: `RAY_DISABLE_DOCKER_CPU_WARNING=1` to mute this warning.zkRay currently does not support initializing Ray with fractional cpus. Your num_cpus will be truncated from z to .)multiprocessing	cpu_countr    r   r   r%   r&   r   ENV_DISABLE_DOCKER_CPU_WARNINGwarningr   r   rM   )r   r   r   docker_counts       r   get_num_cpusr     sS      )++I	z~~9:: 3	
 	
 	
 % ())#	(A(A *;;6 <3 < O	 	 	 <  E,$7$777,&2, , <((, , ,    1"<00$I    	
 s   B(C9 9
DDmemory_stat_filenamememory_usage_filenameinactive_file_keyactive_file_keyc                 F   d}d}t          | d          5 }|                                }|D ]_}| d|v r(t          |                                d                   }1| d|v r't          |                                d                   }`	 ddd           n# 1 swxY w Y   t          |d          5 }|                                }t          |d                                                   }	ddd           n# 1 swxY w Y   |dk    s|	dk    s|dk    rdS |	|z
  |z
  S )zl
    The calculation logic is the same with `GetCGroupMemoryUsedBytes`
    in `memory_monitor.cc` file.
    r    r4   Nr   )r#   	readlinesr   r6   r.   )
r   r   r   r   inactive_file_bytesactive_file_bytesr)   r8   linecgroup_usage_in_bytess
             r   get_cgroup_used_memoryr     s    	"C	(	( 9A 	9 	9D#&&&$..&)$**,,q/&:&:###&&&$..$'

Q$8$8!		99 9 9 9 9 9 9 9 9 9 9 9 9 9 9 
#S	)	) 6Q #E!HNN$4$4 5 56 6 6 6 6 6 6 6 6 6 6 6 6 6 6
 	r!! B&&""t #669JJJs$   A7BB B4<C<<D D c                     d} d}d}d}d}t           j                            |          r2t           j                            |          rt          ||dd          } nPt           j                            |          r1t           j                            |          rt          ||dd	          } | | S t	          j                    j        S )
zkReturn the currently used system memory in bytes

    Returns:
        The total amount of used memory
    Nz+/sys/fs/cgroup/memory/memory.usage_in_bytesz!/sys/fs/cgroup/memory/memory.statz/sys/fs/cgroup/memory.currentz/sys/fs/cgroup/memory.stattotal_inactive_filetotal_active_fileinactive_fileactive_file)r    r!   r"   r   psutilvirtual_memoryused)docker_usagememory_usage_filename_v1memory_stat_filename_v1memory_usage_filename_v2memory_stat_filename_v2s        r   get_used_memoryr
    s     LLA>:	w~~.// 
BGNN5 5 
 .#$!	
 
 
0	1	1 
bgnn7 7 
 .#$	
 
  ""''r   c                  <    t                      t                      z
  S )zReturn the currently available amount of system memory in bytes.

    Returns:
        The total amount of available memory in bytes. Based on the used
        and total memory.

    )r   r
  r   r   r   estimate_available_memoryr  2  s     !2!222r   c                  ,   t           j        dk    st           j        dk    sJ t          j        dt          j                  } 	 t          j        |           }|j        |j        z  }t          j        |            n# t          j        |            w xY w|S )z}Get the size of the shared memory file system.

    Returns:
        The size of the shared memory file system in bytes.
    linuxlinux2z/dev/shm)	sysplatformr    r#   O_RDONLYfstatvfsf_bsizef_bavailclose)shm_fdshm_fs_stats	shm_avails      r   get_shared_memory_bytesr  =  s     <7""clh&>&>&>>WZ--F{6** !(<+@@	
s   #A; ;Bpicklednameobj_typerE   z
ray.Workerc                 \   t          |           }|t          j        k    rdS |t          j        k     rEd                    |||dz            }|r't          |t          j        d|z   |j                   dS dS d                    |||dz  t          j        dz            }t          |          )av  Send a warning message if the pickled function is too large.

    Args:
        pickled: the pickled function.
        name: name of the pickled object.
        obj_type: type of the pickled object, can be 'function',
            'remote function', or 'actor'.
        worker: the worker used to send warning message. message will be logged
            locally if None.
    NzThe {} {} is very large ({} MiB). Check that its definition is not implicitly capturing a large array or other object in scope. Tip: use ray.put() to put large objects in the Ray object store.i   z	Warning: )r<   zThe {} {} is too large ({} MiB > FUNCTION_SIZE_ERROR_THRESHOLD={} MiB). Check that its definition is not implicitly capturing a large array or other object in scope. Tip: use ray.put() to put large objects in the Ray object store.)	r   rm   FUNCTION_SIZE_WARN_THRESHOLDFUNCTION_SIZE_ERROR_THRESHOLDformatrF    PICKLING_LARGE_OBJECT_PUSH_ERRORcurrent_job_id
ValueError)r  r  r  rE   lengthwarning_messageerrors          r   check_oversized_functionr(  S  s     \\F;;;	-=	=	=/ &4K!8
9
9 	  	 >o-,	     	 	9 &{#7KH	
 
 	 r   c                  T    t          j                                                    dk    S )N
MainThread)	threadingcurrent_threadgetNamer   r   r   is_main_threadr.    s"    #%%--//<??r   c                     t           t          j        dk    rdd l	 ddlm} mm}m}m	} 
                    d          }||f|j        _        ||j        _        |j        |f}||j        _        | |j        _        ||f|j        _        | |j        _        d|j        _        | |j        _        n# t$          t&          t(          f$ r d }Y nw xY w|r|                    d d           nd }|rt+          j        |          n|}|rddlmmm  G fddj                   G fd	d
j                   G fddj                  }|                                }d}	d}
d}d} |            }|rdn||z  |
z  |j        _        |	}|                    ||                    |                              |                    sd }||j        nda|r|nda t?          t                     S )Nr   r   )BOOLDWORDHANDLELPCWSTRLPVOIDkernel32r   )r1  LARGE_INTEGERULARGE_INTEGERc            
       h    e Zd Zdfdfd fdj        fdj        fd fdj        fd fd	 fg	Zd
S )Ldetect_fate_sharing_support_win32.<locals>.JOBOBJECT_BASIC_LIMIT_INFORMATIONPerProcessUserTimeLimitPerJobUserTimeLimit
LimitFlagsMinimumWorkingSetSizeMaximumWorkingSetSizeActiveProcessLimitAffinityPriorityClassSchedulingClassNr   r   r   c_size_t_fields_)r1  r6  ctypess   r   !JOBOBJECT_BASIC_LIMIT_INFORMATIONr9    sd        .>*M:!5),fo>,fo>)511$e,&.
r   rG  c                   8    e Zd Zd fd fd fd fd fd fgZdS )6detect_fate_sharing_support_win32.<locals>.IO_COUNTERSReadOperationCountWriteOperationCountOtherOperationCountReadTransferCountWriteTransferCountOtherTransferCountN)r   r   r   rE  )r7  s   r   IO_COUNTERSrI    sF        )>:*N;*N;(.9)>:)>:r   rP  c                   `    e Zd Zdfd fdj        fdj        fdj        fdj        fgZdS )Odetect_fate_sharing_support_win32.<locals>.JOBOBJECT_EXTENDED_LIMIT_INFORMATIONBasicLimitInformationIoInfoProcessMemoryLimitJobMemoryLimitPeakProcessMemoryUsedPeakJobMemoryUsedNrC  )rP  rG  rF  s   r   $JOBOBJECT_EXTENDED_LIMIT_INFORMATIONrR    sO        ,.OP{+)6?;%v7,fo>(&/:r   rY  	   i   i   i    F) 	win32_jobr  r  rF  ctypes.wintypesr0  r1  r2  r3  r4  WinDLLCreateJobObjectWargtypesrestypec_intSetInformationJobObjectAssignProcessToJobObjectIsDebuggerPresentAttributeError	TypeErrorImportError
subprocessHandler6  r7  	StructurerS  r<  byrefsizeofwin32_AssignProcessToJobObjectbool)r0  r2  r3  r4  r5  sijo_argtypesjobrY  r   !JobObjectExtendedLimitInformationJOB_OBJECT_LIMIT_BREAKAWAY_OK+JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION"JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSEbuf	infoclassr1  rP  rG  r6  r7  rF  s                  @@@@@@r   !detect_fate_sharing_support_win32rw    s   S\W44	LLLLLLLLLLLLLL}}Z00H28'1BH%.06H%-#V\65AM8EH,57;H,4:@&9IH-68<H-524H&/15H&..	;7 	 	 	HHH	7?Ih''d333T(+4j$$$ 6	LLLLLLLLLL        F4D         f.           v7G    ..00E 12-,6):D71;.6688CC!C=>/0 %0
 :I33YS 1 16==3E3E   191EH--5 	' )CCE		??s   BB8 8CCc                     t           mt          j                            d          rN	 ddlm} m}m}  | d           j        }||_	        |||||g|_
        n# t          t          f$ r d }Y nw xY w|r|nda t          t                     S )Nr  r   )CDLLra  c_ulongF)linux_prctlr  r  
startswithrF  ry  ra  rz  prctlr`  r_  re  rf  rn  )ry  ra  rz  r}  s       r   !detect_fate_sharing_support_linuxr~    s    s|66w??	3333333333DJJ$E!EM#WgwHENN	* 	 	 	EEE	$/ee%s   -A A,+A,c                      d } t           j        dk    rt                      } n-t           j                            d          rt	                      } | S )Nr   r  )r  r  rw  r|  r~  )results    r   detect_fate_sharing_supportr    sI    F
|w244		 	 	)	) 5244Mr   c                      t                      rJddl} d}t          || j        ddd          dk    r&ddl}t          |                                d          dS J d            )zEnsures this process dies if its parent dies (fate-sharing).

    Linux-only. Must be called in preexec_fn (i.e. by the child).
    r   Nr4   zprctl(PR_SET_PDEATHSIG) failedFz/PR_SET_PDEATHSIG used despite being unavailable)r~  signalr{  SIGKILLrF  OSError	get_errno)r  PR_SET_PDEATHSIGrF  s      r   set_kill_on_parent_death_linuxr    s    
 )** 	H'AqAAQFFMMM&**,,.NOOO GF
 	HGGGur   c                 @   t          | t          j                  r| j        } t          | t          j                  sJ t                      rJt          t          t          |                     s&ddl	}t          |                                d          dS J d            )zEnsures the child process dies if this process dies (fate-sharing).

    Windows-only. Must be called by the parent, after spawning the child.

    Args:
        child_proc: The subprocess.Popen or subprocess.Handle object.
    r   Nz!AssignProcessToJobObject() failedFz7AssignProcessToJobObject used despite being unavailable)rA   rh  Popen_handleri  rw  rm  r[  r   rF  r  get_last_error)
child_procrF  s     r   set_kill_child_on_death_win32r    s     *j.// ('
j*"344444(** P-iZII 	XMMM&//113VWWW	X 	X
 	POOOur   c                     t           j        dk    r!t          j        t          j        |            dS t          j        t          j        |            dS )z@Registers a handler for SIGTERM in a platform-compatible manner.r   N)r  r  r  SIGBREAKSIGTERM)sigterm_handlers    r   set_sigterm_handlerr    sE    
|w 	fo77777fno66666r   c                    t           j                            |           } t           j                            |          }t           j                            |           rHt           j                            |           r'	 t          j        |            n# t          $ r Y dS w xY wdS 	 t          j        ||            dS # t          $ r Y dS w xY w)aV  Attempt to create a symlink.

    If the symlink path exists and isn't a symlink, the symlink will not be
    created. If a symlink exists in the path, it will be attempted to be
    removed and replaced.

    Args:
        symlink_path: The path at which to create the symlink.
        target_path: The path the symlink should point to.
    N)r    r!   
expanduserr"   islinkremover  symlink)symlink_pathtarget_paths     r   try_to_symlinkr  "  s     7%%l33L'$$[11K	w~~l## 	7>>,'' 		,''''    F

;-----   s$   >B 
B! B!'B> >
CCc                      t           dS 	 t          j        t          j                              j        S # t
          $ r Y dS w xY w)N )pwdgetpwuidr    getuidpw_namerM   r   r   r   get_userr  A  sL    
{r|BIKK((00   rrs   )5 
AAc                     dt           j        v rOt           j                            t           j        d                   }t           j                            ||           S | S )z
    Return path to the specified executable, assumed to be discoverable within
    the 'bin' subdirectory of a conda installation.  Adapted from
    https://github.com/mlflow/mlflow.
    	CONDA_EXE)r    r   r!   dirnamer7   )executable_nameconda_bin_dirs     r   get_conda_bin_executabler  J  sG     bj  
;(?@@w||M?;;;r   c                    t           j                            d          }|Vt           j                            d          }|t          d          t	          t          |          j        j                  }t           j                            d          dk    r+| dk    r|}ngt           j                            |d|           }nEt           j        	                    |          d         }t           j                            ||           }t           j        
                    |          st          d	| z   d
z   dz             |S )a  Find and validate the conda directory for a given conda environment.

    For example, given the environment name `tf1`, this function checks
    the existence of the corresponding conda directory, e.g.
    `/Users/scaly/anaconda3/envs/tf1`, and returns it.
    CONDA_PREFIXNr  zQCannot find environment variables set by conda. Please verify conda is installed.CONDA_DEFAULT_ENVbaseenvsr   z
conda env z< not found in conda envs directory. Run `conda env list` to zverify the name is correct.)r    r   r   r$  rT   r   parentr!   r7   r6   isdir)env_nameconda_prefix	conda_exeenv_dirconda_envs_dirs        r   get_conda_env_dirr  X  s1    :>>.11L JNN;//	4   4	??1899 
z~~)**f44 v"GG gll<BBGG
 |44Q7',,~x887==!! 
LM ,,
 
 	
 Nr   c                  b    t          j        dt          j                  dS dt          j         S )zAGet the docs.ray.io version corresponding to the ray.__version__.z^\d+\.\d+\.\d+$Nmasterz	releases-)rematchr>   __version__r   r   r   get_ray_doc_versionr    s0    
 
x"CO44<x )s(((r   sys_platformray_version
py_versionarchitecturec           
      ^   |t           j        v s
J |            d                    t          t          |                    }|pt          j                    }| dv s
J |             | dk    r|dk    rd}n#d}n | dk    r|dk    s|d	k    rd
}nd}n| dk    rd}d| d| d| |dv rdnd d| d
}|S )a  Returns the filename used for the nightly Ray wheel.

    Args:
        sys_platform: The platform as returned by sys.platform. Examples:
            "darwin", "linux", "win32"
        ray_version: The Ray version as returned by ray.__version__ or
            `ray --version`.  Examples: "3.0.0.dev0"
        py_version: The Python version as returned by sys.version_info. A
            tuple of (major, minor). Examples: (3, 8)
        architecture: Architecture, e.g. ``x86_64`` or ``aarch64``. If None, will
            be determined by calling ``platform.processor()``.

    Returns:
        The wheel file name.  Examples:
            ray-3.0.0.dev0-cp38-cp38-manylinux2014_x86_64.whl
    r  )darwinr  r   r  x86_64macosx_12_0_x86_64macosx_12_0_arm64r  aarch64arm64manylinux2014_aarch64manylinux2014_x86_64r   	win_amd64zray-z-cp)37mr   z.whl)rm   RUNTIME_ENV_CONDA_PY_VERSIONSr7   maprT   r  	processor)r  r  r  r  py_version_str	os_stringwheel_filenames          r   get_wheel_filenamer    s)   , DDDDjDDDWWSj1122N78#5#7#7L7777777x8##,II+II		 	 9$$(?(?/II.II		 	 		{ 	 	~ 	 		$2f$<$<SS"	 		 	 	  r      
ray_commitc                 6    t          |||          }d|  d| S )z4Return the URL for the wheel from a specific commit.r  r  r  z5https://s3-us-west-2.amazonaws.com/ray-wheels/master//r  r  r  r  r  filenames        r   get_master_wheel_urlr    sC     "!{z  H	#	# 	# 	# 	#r   c                 <    t          |||          }d| d|  d| S )z4Return the URL for the wheel for a specific release.r  z7https://ray-wheels.s3-us-west-2.amazonaws.com/releases/r  r  r  s        r   get_release_wheel_urlr    sP     "!{z  H	1	1 	1#	1 	1&.	1 	1r   	namespacec                 x    t          | t                    st          d          | dk    rt          d          d S )Nz#namespace must be None or a string.r  zB"" is not a valid namespace. Pass None to not specify a namespace.)rA   rT   rf  r$  )r  s    r   validate_namespacer    sH    i%% 
=>>>	bS
 
 	
 
r   c                  B    	 ddl } dS # t          $ r}|cY d}~S d}~ww xY w)a  Returns the exception error if Ray Dashboard dependencies are not installed.
    None if they are installed.

    Checks to see if we should start the dashboard agent or not based on the
    Ray installation version the user has installed (ray vs. ray[default]).
    Unfortunately there doesn't seem to be a cleaner way to detect this other
    than just blindly importing the relevant packages.
    r   N)ray.dashboard.optional_depsrg  )r>   es     r   get_dashboard_dependency_errorr    sF    ****t       
c                  B    	 ddl } dS # t          $ r}|cY d}~S d}~ww xY w)znReturns the exception error if Ray Client dependencies are not installed.
    None if they are installed.
    r   N)grpcrg  )r  r  s     r   get_ray_client_dependency_errorr    sC    t   r  zUnable to connect to GCS (ray head) at {}. Check that (1) Ray with matching version started successfully at the specified address, (2) this node can reach the specified address, and (3) there is no firewall setting preventing access.   c                    d }t          |t                    r|                                }t          |t                    r|                                }t          |          D ]}	 |                     ||          }n# t
          $ r}t          |t          j        j                  ra|j	        t          j
        j        t          j
        j        fv r8t                              t                              | j                             nt                              d           d }Y d }~nd }~ww xY w| n4t                              d| d           t)          j        d           |t-          d| d          |S )NzInternal KV List failedFetched =None from KV. Retrying.r  zCould not list ''' from GCS. Did GCS start successfully?)rA   rT   rL   r   internal_kv_keysrM   r>   
exceptionsRpcErrorrpc_code_rayletGRPC_STATUS_CODE_UNAVAILABLEGRPC_STATUS_CODE_UNKNOWNr%   r   connect_errorr!  addressrN   r   rD   sleepConnectionError)rO   prefixr  num_retriesr  _r  s          r   internal_kv_list_with_retryr  !  s   F&# !)S!! '$$&&	;  
	00CCFF 	 	 	!S^455 <!*84I ; ; }33J4FGGHHHH  !:;;;FFFFFF	 ELLDFDDDEEEJqMMMM~NvNNN
 
 	
 Ms   (A??
D/	BD**D/c                    d }t          |t                    r|                                }t          |          D ]}	 |                     ||          }n# t
          $ r}t          |t          j        j                  ra|j	        t          j
        j        t          j
        j        fv r8t                              t                              | j                             nt                              d           d }Y d }~nd }~ww xY w| n4t                              d| d           t)          j        d           |s%t-          d|                                 d          |S )NzInternal KV Get failedr  r  r  zCould not read 'r  )rA   rT   rL   r   internal_kv_getrM   r>   r  r  r  r  r  r  r%   r   r  r!  r  rN   r   rD   r  r  rW   )rO   keyr  r  r  r  r  s          r   internal_kv_get_with_retryr   @  sp   F#s jjll;  
	//Y??FF 	 	 	!S^455 ;!*84I ; ; }33J4FGGHHHH  !9:::FFFFFF	 ELLACAAABBBJqMMMM 
Tszz||TTT
 
 	
 Ms   A
D BDD--resources	resourcesc           	      x   	 t          j        |           } t          | t                    st	          d          n# t
          $ rr}|                    d|                    | d|            t          |                     |	                    d|                    | d                     Y d }~nd }~ww xY w| S )N.The format after deserialization is not a dict0`{}` is not a valid JSON string, detail error:{}=!Valid values look like this: `{}`z/='{"CustomResource3": 1, "CustomResource2": 2}'
jsonloadsrA   dictr$  rM   r'  boldrT   abort)r  
cli_loggercfcommand_argr  s        r   parse_resources_jsonr  ]  s    
Jy))	)T** 	OMNNN	O 
 
 
>GG{00Y0011FF	
 	
 	

 	/GGSSS 	
 	
 	
 	
 	
 	
 	
 	

    8; 
B7A(B22B7--metadata-jsonmetadatac           	      x   	 t          j        |           } t          | t                    st	          d          n# t
          $ rr}|                    d|                    | d|            t          |                     |	                    d|                    | d                     Y d }~nd }~ww xY w| S )Nr  r  r  r  z'='{"key1": "value1", "key2": "value2"}'r  )r  r  r  r  r  s        r   parse_metadata_jsonr  s  s    
:h''(D)) 	OMNNN	O 	
 	
 	
>GG{//X//00FF	
 	
 	

 	/GG{OOOPP	
 	
 	
 	
 	
 	
 	
 	
	
 Or  c                    t          |t                    r|                                }t          |t                    r|                                }t          |t                    r|                                }d }t          |          D ]}	 |                     ||d|          c S # t
          j        j        $ r}|j        t
          j	        j
        t
          j	        j        fv r8t                              t                              | j                             nt                              d           t%          j        d           |}Y d }~d }~ww xY w|)NT)	overwriter  zInternal KV Put failedr  )rA   rT   rL   r   internal_kv_putr>   r  r  r  r  r  r  r%   r   r  r!  r  rN   rD   r  )rO   r  valuer  r  r'  r  r  s           r   internal_kv_put_with_retryr    s^   #s jjll% )S!! '$$&&	E;  	--Udi .      ~& 		 		 		z84   }33J4FGGHHHH  !9:::JqMMMEEEEEE		 Ks   B++E?BEEc                      t           j        } d                    t          t          t
          j        dd                             }| |fS )zoCompute the versions of Python, and Ray.

    Returns:
        A tuple containing the version information.
    r   Nr5   )r>   r  r7   r  rT   r  version_info)r  python_versions     r   compute_version_infor    s=     /KXXc#s'7';<<==N&&r   r   r!   c                 6   d}t          j        |           D ]\  }}}|D ]x}t           j                            ||          }t           j                            |          s7|                    d          s"|t           j                            |          z  }y|S )zEGet the total size of a directory in bytes, including subdirectories.r   z.pyc)r    walkr!   r7   r  endswithgetsize)r!   total_size_bytesdirpathdirnames	filenamesr)   fps          r   get_directory_size_bytesr)    s    (* 8 8$9 	8 	8Agq))B7>>"%% 8ajj.@.@ 8 BGOOB$7$77 		8 r   c                    | t           j                            dd          }| d         | d         f}t                      }|d         |d         k    }|d         |d         k    }|dk    r|d         |d         k    }nf|dk    rM|d                             d	          }	|d                             d	          }
|	dd
         |
dd
         k    }nt          d| d          d|d          d|d          d| d|d          d|d          d}|r%|r#|st                              d|            dS dS d| }|rt          |          t                              |           dS )aR  Check if the Python and Ray versions stored in GCS matches this process.
    Args:
        cluster_metadata: Ray cluster metadata from GCS.
        this_process_address: Informational only. The address of this process.
            e.g. "node address:port" or "Ray Client".
        raise_on_mismatch: Raise an exception on True, log a warning otherwise.
        python_version_match_level: "minor" or "patch". To which python version level we
            try to match. Note if "minor" and the patch is different, we will still log
            a warning. Default value is `RAY_DEFAULT_PYTHON_VERSION_MATCH_LEVEL` if it
            exists, otherwise "patch"

    Behavior:
        - We raise or log a warning, based on raise_on_mismatch, if:
            - Ray versions do not match; OR
            - Python (major, minor) versions do not match,
                if python_version_match_level == 'minor'; OR
            - Python (major, minor, patch) versions do not match,
                if python_version_match_level == 'patch'.
        - We also log a warning if:
            - Python (major, minor) versions match, AND
            - Python patch versions do not match, AND
            - python_version_match_level == 'minor' AND
            - raise_on_mismatch == False.

    Raises:
        Exception: An exception is raised if there is a version mismatch.
    N&RAY_DEFAULT_PYTHON_VERSION_MATCH_LEVELpatchr  r  r   r4   minorr   r  z$Invalid python_version_match_level: z, want: 'minor' or 'patch'z'The cluster was started with:
    Ray: z
    Python: z
This process on z was started with:
    Ray: r3   zPython patch version mismatch: zVersion mismatch: )	r    r   r   r  r6   r$  r%   r   RuntimeError)cluster_metadatathis_process_addressraise_on_mismatchpython_version_match_levelcluster_version_infomy_version_inforay_matchespython_full_matchespython_matchesmy_python_versionscluster_python_versionsmismatch_msgerror_messages                r   check_version_infor<    s   B ")%'Z^^4g&
 &
"
 	')* +,,O 'q)_Q-??K.q1_Q5GG!W,,-a0OA4FF	#w	.	.,Q/55c::"6q"9"?"?"D"D+BQB/3J2A23NN'3M ' ' '
 
 	
	.(+	. 	.+A.	. 	. 0	. 	. $A&		. 	.
 'q)	. 	. 	.   *~ *" 	MNNK\KKLLLLL	M 	M <\;; 	*}---NN=)))))r   )is_job_runtime_env	serializeruntime_envr   r=  r>  c                   ddl m} t                      }|                                 r|                                 |j        _        t          |                                           dk    r#|                                 |j        j        dd<   |                     d          }||                                }n|	                    |          }|j
                            |                                           ||                    d          nd}|s|E|d}n4t          |t                    st          dt!          |                     ||j
        _        |                                 |_        |s|S t)          j        |          S )ao  Create runtime env info from runtime env.

    In the user interface, the argument `runtime_env` contains some fields
    which not contained in `ProtoRuntimeEnv` but in `ProtoRuntimeEnvInfo`,
    such as `eager_install`. This function will extract those fields from
    `RuntimeEnv` and create a new `ProtoRuntimeEnvInfo`, and serialize it
    into json format.
    r   )RuntimeEnvConfigNconfigeager_installTz%eager_install must be a boolean. got )ray.runtime_envrA  ProtoRuntimeEnvInfoworking_dir_uriurisr   py_modules_urisr   default_config%parse_and_validate_runtime_env_configruntime_env_configCopyFrombuild_proto_runtime_env_configrA   rn  rf  rV   rC  r>  serialized_runtime_envr   MessageToJson)r?  r=  r>  rA  proto_runtime_env_inforK  rC  s          r   get_runtime_env_inforQ  	  s    100000022""$$ T6A6Q6Q6S6S#3
;&&(())A--9D9T9T9V9V#3AAA6
 %22!-<<>>-SS
 
 -6699;;   ) 	/// 
  P]6  MMM400 	M]8K8KMM   CP1?4?4I4I4K4K1 &%%$%;<<<r   c                     ddl m} ddlm} | rLt	          | t
                    r |di | pi }  ||            | S t          ddt          |                      d S )Nr   r   )_validate_no_local_pathsz(runtime_env must be dict or RuntimeEnv, z	but got: r   )rD  r   ray.runtime_env.runtime_envrS  rA   r  rf  rV   )r?  r   rS  s      r   #parse_runtime_env_for_task_or_actorrU  H  s     +*****DDDDDD
  k4(( 	$*;;(9r;;K$$[1116+[))++
 
 	
 tr   r  c                 d    d| vrt          d          |                     dd          \  }}||fS )a  Splits address into a module string (scheme) and an inner_address.

    We use a custom splitting function instead of urllib because
    PEP allows "underscores" in a module names, while URL schemes do not
    allow them.

    Args:
        address: The address to split.

    Returns:
        A tuple of (scheme, inner_address).

    Raises:
        ValueError: If the address does not contain '://'.

    Examples:
        >>> split_address("ray://my_cluster")
        ('ray', 'my_cluster')
    z://zAddress must contain '://'r4   )maxsplit)r$  r6   )r  module_stringinner_addresss      r   split_addressrZ  a  sC    ( G5666#*===#C#C M==))r   c                      d} 	 t          j                    }t          t          d          rd} | t	          |                                          z   S # t          $ r Y dS w xY w)z)Get the entrypoint of the current script.r  ps1z(interactive_shell) unknown)r  Processhasattrr  r   cmdlinerM   )r  currs     r   get_entrypoint_namerb  |  so    F	~ 3 	,+FT\\^^4444   yys   AA 
A A c                   V    e Zd ZdZd Zedej        fd            Zd Z	d Z
d Zd Zd	S )
DeferSigintzEContext manager that defers SIGINT signals until the context is left.c                 0    d| _         d | _        d | _        d S NF)signal_receivedoverridden_sigint_handlerorig_signalr   s    r   r   zDeferSigint.__init__  s     $)-&r   r,   c                     t          j                    t          j                    k    r
 |             S t          j                    S )zCreates a DeferSigint context manager if running on the main thread,
        returns a no-op context manager otherwise.
        )r+  r,  main_thread
contextlibnullcontext)clss    r   create_if_main_threadz!DeferSigint.create_if_main_thread  s;    
 #%%)>)@)@@@355L)+++r   c                     d| _         dS )z&SIGINT handler that defers the signal.TN)rg  )r   signumframes      r   _set_signal_receivedz DeferSigint._set_signal_received  s    #r   c                     t          j                    t          j                    k    r |t          j        k    r| j        }|| _        |S |                     ||          S )zyMonkey patch for signal.signal that defers the setting of new signal
        handler after the DeferSigint context exits.)r+  r,  rl  r  SIGINTrh  ri  )r   rr  handlerorig_sigint_handlers       r   _signal_monkey_patchz DeferSigint._signal_monkey_patch  s[     $&&)*?*A*AAA&-''"&"@-4D*&&000r   c                     t          j        t           j                  | _        t          j         t           j        | j                   t           j         | _        | j        t           _         | S r]   )r  	getsignalrv  rh  rt  ri  ry  rj  s    r   	__enter__zDeferSigint.__enter__  sI    )/)9&-)H)H&fmT%>??? "=1r   c                     | j         J | j        J | j        t          _        t          j        t          j        | j                    |)| j        r"|                      t          j        d            d S dS rf  )rh  ri  r  rv  rg  )r   exc_typeexcexc_tbs       r   __exit__zDeferSigint.__exit__  sv    -999+++(fmT%CDDD 4 **6=$????? 5r   N)r   r   r   r   r   classmethodrm  AbstractContextManagerrp  rt  ry  r|  r  r   r   r   rd  rd    s        OO      ,j&G , , , [,$ $ $1 1 1	 	 	    r   rd  module_names_to_importc                     | D ]E}	 t          j        |           # t          $ r! t                              d| d           Y Bw xY wdS )z
    Make a best-effort attempt to import each named Python module.
    This is used by the Python default_worker.py to preload modules.
    zFailed to preload the module ""N)	importlibimport_modulerg  r%   rN   )r  module_to_preloads     r   try_import_each_moduler    s    
 4 T T	T#$56666 	T 	T 	TR>ORRRSSSSS	TT Ts   (AAenvc                 P    t           j        D ]}|                     |d           dS )za
    Remove Ray internal flags from `env`.
    Defined in ray/common/ray_internal_flag_def.h
    N)rm   RAY_INTERNAL_FLAGSr   )r  flags     r   "remove_ray_internal_flags_from_envr    s7    
 0  d r   env_varsc                     | sdS |                                  D ]I\  }}t          j                            |          }t	          j        dd|          }|t          j        |<   JdS )z
    When updating the environment variable, if there is ${X},
    it will be replaced with the current environment variable.
    Nz\$\{[A-Z0-9_]+\}r  )r   r    r!   
expandvarsr  subr   )r  r  r  expandedr  s        r   update_envsr    sn    
  nn&& ! !
U7%%e,,+R:: 
3	! !r   pg_formatted_resourcesc                 "   i }|                                  D ]\  }}t                              |          }|r]t          |                                          dk    r8|                    d          t          k    re|||                    d          <   ~t                              |          }|rXt          |                                          dk    r3|                    d          dk    r|||                    d          <   |||<   |S )Nr5   r4   r  bundle)r   0PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERNr  r   groupsgroupr   )PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN)r  original_resourcesr  r  r  s        r   (parse_pg_formatted_resources_to_originalr    s
    ,2244 ( (
UAGGLL 		c&--//**a//
 ||A"FFF27v||A/:@@EE 	c&--//**a//||A(**27v||A/"'3r   c                 D    | d S g d}| |vrt          d|  d          d S )N)DEPENDENCIES_UNREADYPENDING_CREATIONALIVE
RESTARTINGDEADr  z" is not a valid actor state name, it must be one of the following: "DEPENDENCIES_UNREADY", "PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD")r$  )actor_state_nameactor_state_namess     r   validate_actor_state_namer    sb       000C  C C C
 
 	
 10r   c                     t           j                            d          sd S 	 	 t          dd          5 } | D ]R}|                    d          r;|                    d          d                                         c cd d d            S S	 d d d            n# 1 swxY w Y   d S # t          $ r  t                              dd	           Y d S w xY w)
Nr  z/proc/cpuinfor   z
model name:r4   zFailed to get CPU model nameT)exc_info)	r  r  r|  r#   r6   r.   rM   r%   r   )r)   r   s     r   get_current_node_cpu_model_namer  $  sF   <""7++ t		 /3'' 	61 6 6??<00 6::c??1-335555	6 	6 	6 	6 	6 	6 	6 	666	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 t   3dCCCttsA   B$ AB<B$ 	BB$ BB$ BB$ $&CCfilepathc                     t           j        dk    rdS t           j                            d          }|rdnddz
  }t          |                     d                    |k    rt          d| d	|            dS )
zI
    Validate the provided filename is a valid Unix socket filename.
    r   Nr  h   l   r4   rQ   zCvalidate_socket_filename failed: AF_UNIX path length cannot exceed z bytes: )r  r  r|  r   rL   r  )r  is_macmaxlens      r   validate_socket_filepathr  =  s    
 |w\$$X..F$cc)F
8??7##$$v--lRXllbjll
 
 	
 .-r   c                  P    t           t          d dD                       a t           S )Nc              3   2   K   | ]}|t           j        v V  d S r]   )r    r   )rw   r   s     r   	<genexpr>zis_in_test.<locals>.<genexpr>T  s?       
 
  rz!
 
 
 
 
 
r   )PYTEST_CURRENT_TEST	BUILDKITE)in_testanyr   r   r   
is_in_testr  P  s>      
 
 @	
 
 
 
 
 Nr   r]   )F)rQ   rR   )r   r   r   r   )r  )r  )r  )r   )TN)rm  r  r	  loggingr   r    r  r  r  rh  r  r+  rD   collectionsr   pathlibr   r   typingr   r   r   r	   r
   r   r   google.protobufr   r>   r   r   rm   ray._common.utilsr   r   r   *ray.core.generated.runtime_environment_pb2r   rE  r  rD  r   	INT32_MAXr  	getLoggerr   r%   r{  r[  rm  r   r   _CALLED_FREQLock_CALLED_FREQ_LOCKcompiler  r  rT   r+   r/   rn  r9   rF   rP   r[   r`   rd   rj   rq   r{   r   r   r   objectr   r   r   r   r   r   r
  r  r  rU   r(  r.  rw  r~  r  r  r  r  r  r  r  r  r  r  r  majorr-  r   r  
__commit__r  r  r  rg  r  r  r  r  r   r  r  r  r  r)  r<  rQ  rU  rZ  rb  r  rd  r  r  r  r  r  r  r  r  r  r  r   r   r   <module>r     s.                 				  				      



      # # # # # #       # # # # # #                  ( ' ' ' ' ' 



 2 2 2 2 2 2 2 2 2         
     
  +****** 	 <7JJJ		8	$	$  	!% !ARZ!O  {99%%"IN$$ 3=2:&4 4 0 -7BJ7S,T,T ) 3 (3-    &   x}           C     . DHL LL&)L3;C=L L L L. 	T TTT T T T<
* 
* 
* 
*, , ,& & &? ? ?
' ' 'WS(492E-E%F    "%d % % % %P1WS(3--?%@ 1 1 1 1<,+233E+F,	, , , ,* * * * * * * *:   " >?8.	@# @#
 e_@# @# @# @#H )GA A!%AA A A A AJKKK K 	K K K KD$( $( $(N3 3 3  ,* * * ),* 6B* 	*  *  *  * Z@ @ @Q Q Qh    H H H"P P P,7 7 7  >    2 2 2j	) 	) 	) #&#3#93;K;Q"R"&	1 111 c3h1 3-	1
 	1 1 1 1j n"%"22A2"6	   c3h	
 	   " n"%"22A2"6	   c3h	
 	   &
# 
 
 
 
(=    "	+)> 	 	 	 	-    >   < 1> 	#u*   . 0A 	#s(^   (   6' ' '
 
5d#3 
c 
 
 
 
  #	L* L* L* L*d  %	<= <= <=<= <= 	<= <= <= <=~%l 234   2*3 *5c? * * * *6  B B B B B*3 B B BJ	T49 	T 	T 	T 	T 	TD    !$sCx. ! ! ! ! e,	#u*   <
 
 
$#    2
s 
 
 
 
  
 
 
 
 
r   