o
    bi.                     @   s  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Zd dlZd dlZd dl	Z	d dl
Z
d dlZd dlmZmZmZmZ dddedefdd	Zd
e jfddZe Zded
e jfddZdZdZdeeef d
eeef fddZe	je	j Zde fddZ!e Z"d=de fddZ#dd Z$dd Z%d ee fd!d"Z&d>d ee fd#d$Z'd%d& Z(	'	(d?d)ed*efd+d,Z)d-d. Z*d/d0 Z+d1d2 Z,d3d4 Z-d5d6 Z.d@d8ed9ed:efd;d<Z/dS )A    N)	signature)Any	CoroutineDictOptionalF)reload_module	full_pathr   c                C   s   | du rt dd| v r#| ddkrtd|  d| d\}}n| d}| d| }| |d d }t|}|rBt| t||S )a  Given a full import path to a module attr, return the imported attr.

    If `reload_module` is set, the module will be reloaded using `importlib.reload`.

    For example, the following are equivalent:
        MyClass = import_attr("module.submodule:MyClass")
        MyClass = import_attr("module.submodule.MyClass")
        from module.submodule import MyClass

    Returns:
        Imported attr
    Nzimport path cannot be None:   zGot invalid import path "z-". An import path may have at most one colon..)		TypeErrorcount
ValueErrorsplitrfind	importlibimport_modulereloadgetattr)r   r   module_name	attr_namelast_period_idxmodule r   E/home/ubuntu/.local/lib/python3.10/site-packages/ray/_common/utils.pyimport_attr   s   




r   returnc               
   C   s~   t j} | jdkr;| jdkr;zt }|dusJ |W S  ty: } zdt|v s*J t 	 W  Y d}~S d}~ww t	 S )aj  Get a running async event loop if one exists, otherwise create one.

    This function serves as a proxy for the deprecating get_event_loop().
    It tries to get the running loop first, and if no running loop
    could be retrieved:
    - For python version <3.10: it falls back to the get_event_loop
        call.
    - For python version >= 3.10: it uses the same python implementation
        of _get_event_loop() at asyncio/events.py.

    Ideally, one should use high level APIs like asyncio.run() with python
    version >= 3.7, if not possible, one should create and manage the event
    loops explicitly.
       
   Nzno running event loop)
sysversion_infomajorminorasyncioget_running_loopRuntimeErrorstrget_event_loop_policyget_event_loop)	vers_infolooper   r   r   get_or_create_event_loop2   s   r,   	coroutinec                 C   s&   t  | }t| |tj |S )a1  Schedule a task reliably to the event loop.

    This API is used when you don't want to cache the reference of `asyncio.Task`.
    For example,

    ```
    get_event_loop().create_task(coroutine(*args))
    ```

    The above code doesn't guarantee to schedule the coroutine to the event loops

    When using create_task in a  "fire and forget" way, we should keep the references
    alive for the reliable execution. This API is used to fire and forget
    asynchronous execution.

    https://docs.python.org/3/library/asyncio-task.html#creating-tasks
    )r,   create_task_BACKGROUND_TASKSaddadd_done_callbackdiscard)r-   taskr   r   r   run_background_taskV   s   
r4   zaccelerator_type:bundleoptions_dictc                 C   s   |  dpi  }d|v sd|v rtdd|v sd|v r!tdt|v r,td| |  d	}|  d
}|  d}|  d}|  d}|durM||d< |durU||d< |dur_t||d< |durg||d< |dursd|t | < |S )zDetermine a task's resource requirements.

    Args:
        options_dict: The dictionary that contains resources requirements.

    Returns:
        A dictionary of the resource requirements for the task.
    	resourcesCPUGPUz@The resources dictionary must not contain the key 'CPU' or 'GPU'memoryobject_store_memoryzSThe resources dictionary must not contain the key 'memory' or 'object_store_memory'zOThe resource should not include `bundle` which is reserved for Ray. resources: num_cpusnum_gpusaccelerator_typeNgMbP?)getcopyr   $PLACEMENT_GROUP_BUNDLE_RESOURCE_NAMEintRESOURCE_CONSTRAINT_PREFIX)r6   r7   r<   r=   r:   r;   r>   r   r   r   resources_from_ray_optionsx   s>   	




rD   lengthc                 C   s   d tjt| dS )zjGenerates random string of length consisting exclusively of
    - Lower-case ASCII chars
    - Digits
     )k)joinrandomchoicesRANDOM_STRING_ALPHABET)rE   r   r   r   get_random_alphanumeric_string   s   rL   r
   backc                 C   s>   t  }z|| d  }|j d|j W S  ty   Y dS w )aL  
    Get the location (filename and line number) of a function caller, `back`
    frames up the stack.

    Args:
        back: The number of frames to go up the stack, not including this
            function.

    Returns:
        A string with the filename and line number of the caller.
        For example, "myfile.py:123".
    r
   r	   UNKNOWN)inspectstackfilenamelineno
IndexError)rM   rP   framer   r   r   get_call_location   s   rU   c                  C   sl   dt jv r
t jd S tjdrdt jv rt jd S tjds&tjdr0t jt jd} | S t	 } | S )N
RAY_TMPDIRlinuxTMPDIRdarwintmp)
osenvironr   platform
startswithpathrH   septempfile
gettempdir)tempdirr   r   r   get_user_temp_dir   s   


rd   c                   C   s   t jt dS )Nray)r[   r_   rH   rd   r   r   r   r   get_ray_temp_dir   s   rf   temp_dirc                 C   s   | d u rt  } tj| dS )Nray_current_cluster)rf   r[   r_   rH   )rg   r   r   r   get_ray_address_file   s   ri   c                 C   s>   t | }tj|rzt| W d S  ty   Y d S w d S N)ri   r[   r_   existsremoveOSError)rg   address_filer   r   r   reset_ray_address   s   ro   c                 C   sL   |  d}t|dk rtdd|dd }|d }t|}t||S )z`Load a class at runtime given a full path.

    Example of the path: mypkg.mysubpkg.myclass
    r      z:You need to pass a valid path like mymodule.provider_classN)r   lenr   rH   r   r   r   )r_   
class_datamodule_path	class_strr   r   r   r   
load_class   s   


rv   +/sys/fs/cgroup/memory/memory.limit_in_bytes/sys/fs/cgroup/memory.maxmemory_limit_filenamememory_limit_filename_v2c                 C   s   d}t j| r&t| d}t|  }W d   n1 s w   Y  n,t j|rRt|d}|  }| rAt|}nd}W d   n1 sMw   Y  t	 j
}|dur`t||S |S )a  Return the total amount of system memory in bytes.

    Args:
        memory_limit_filename: The path to the file that contains the memory
            limit for the Docker container. Defaults to
            /sys/fs/cgroup/memory/memory.limit_in_bytes.
        memory_limit_filename_v2: The path to the file that contains the memory
            limit for the Docker container in cgroups v2. Defaults to
            /sys/fs/cgroup/memory.max.

    Returns:
        The total amount of system memory in bytes.
    Nr)r[   r_   rk   openrB   readstrip	isnumericpsutilvirtual_memorytotalmin)ry   rz   docker_limitfmax_filepsutil_memory_in_bytesr   r   r   get_system_memory   s$   



r   c                 C   s   t | }| }|S rj   )binasciihexlifydecode)
identifierhex_identifierr   r   r   binary_to_hex(  s   
r   c                 C   s
   t | S rj   )r   	unhexlify)r   r   r   r   hex_to_binary.  s   
r   c              
   C   sP   z	t | d W d S  ty' } z|jtjtjfv rn W Y d }~d S d }~ww )Ni  )r[   chmodrm   errnoEACCESEPERM)directory_pathr+   r   r   r   try_make_directory_shared2  s   r   c                 C   s&   t j| } t j| dd t|  d S )NT)exist_ok)r[   r_   
expandusermakedirsr   )r   r   r   r   try_to_create_directoryA  s   r   c                 C   s   t t| j}t|S rj   )	frozensetr   
parameterslist)callableall_parametersr   r   r   get_function_argsJ  s   r   utf-8byte_str
allow_noneencode_typec                 C   s4   | du r|rdS t | tstd|  d| |S )a  Make this unicode in Python 3, otherwise leave it as bytes.

    Args:
        byte_str: The byte string to decode.
        allow_none: If true, then we will allow byte_str to be None in which
            case we will return an empty string. TODO(rkn): Remove this flag.
            This is only here to simplify upgrading to flatbuffers 1.10.0.
        encode_type: The encoding type to use for decoding. Defaults to "utf-8".

    Returns:
        A byte string in Python 2 and a unicode string in Python 3.
    NrF   zThe argument z must be a bytes object.)
isinstancebytesr   r   )r   r   r   r   r   r   r   O  s
   

r   )r
   rj   )rw   rx   )Fr   )0r#   r   r   r   rO   r   r[   r   rI   stringr   ra   typingr   r   r   r   r&   boolr   AbstractEventLoopr,   setr/   Taskr4   rC   rA   rD   ascii_lowercasedigitsrK   rB   rL   _PRINTED_WARNINGrU   rd   rf   ri   ro   rv   r   r   r   r   r   r   r   r   r   r   r   <module>   sT    "!"/	
/	