o
    $i1                  	   @   s"  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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 d dlZddded	ed
eeef fddZddde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*dEde(fddZ+d d! Z,d"d# Z-d$ee fd%d&Z.dFd$ee fd'd(Z/d)d* Z0	+	,dGd-ed.efd/d0Z1d1d2 Z2d3d4 Z3d5d6 Z4d7d8 Z5d9d: Z6dHd<ed=ed>efd?d@Z7G dAdB dBeZ8G dCdD dDe8Z9dS )I    N)ABCabstractmethod)	signature)
ModuleType)Any	CoroutineDictOptionalTupleFreload_module	full_pathr   returnc                C   s   d| v r|  ddkrtd|  d| d\}}n| d}| d| }| |d d }t|}|r:t| |t||fS )ai  Given a full import path to a module attr, return the imported module and attr.

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

    Args:
        full_path: The full import path to the module and attr.
        reload_module: Whether to reload the module.

    Returns:
        A tuple of the imported module and attr.
    :   zGot invalid import path "z-". An import path may have at most one colon..N)count
ValueErrorsplitrfind	importlibimport_modulereloadgetattr)r   r   module_name	attr_namelast_period_idxmodule r   N/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/_common/utils.pyimport_module_and_attr   s   



r    c                C   s   t | |dd 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
    r   r   )r    )r   r   r   r   r   import_attr3   s   r!   c               
   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_loopC   s   r1   	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
    )r1   create_task_BACKGROUND_TASKSaddadd_done_callbackdiscard)r2   taskr   r   r   run_background_taskg   s   
r9   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)r;   r<   rA   rB   r?   r@   rC   r   r   r   resources_from_ray_options   s>   	




rI   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)rJ   r   r   r   get_random_alphanumeric_string   s   rQ   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)rR   rU   framer   r   r   get_call_location   s   rZ   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pathrM   septempfile
gettempdir)tempdirr   r   r   get_user_temp_dir   s   


ri   c                   C   s   t jt dS )Nray)r`   rd   rM   ri   r   r   r   r   get_ray_temp_dir   s   rk   temp_dirc                 C   s   | d u rt  } tj| dS )Nray_current_cluster)rk   r`   rd   rM   )rl   r   r   r   get_ray_address_file   s   rn   c                 C   s>   t | }tj|rzt| W d S  ty   Y d S w d S N)rn   r`   rd   existsremoveOSError)rl   address_filer   r   r   reset_ray_address   s   rt   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   rM   r   r   r   )rd   
class_datamodule_path	class_strr   r   r   r   
load_class   s   


r{   +/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`   rd   rp   openrG   readstrip	isnumericpsutilvirtual_memorytotalmin)r~   r   docker_limitfmax_filepsutil_memory_in_bytesr   r   r   get_system_memory
  s$   



r   c                 C   s   t | }| }|S ro   )binasciihexlifydecode)
identifierhex_identifierr   r   r   binary_to_hex9  s   
r   c                 C   s
   t | S ro   )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`   chmodrr   errnoEACCESEPERM)directory_pathr0   r   r   r   try_make_directory_sharedC  s   r   c                 C   s&   t j| } t j| dd t|  d S )NT)exist_ok)r`   rd   
expandusermakedirsr   )r   r   r   r   try_to_create_directoryR  s   r   c                 C   s   t t| j}t|S ro   )	frozensetr   
parameterslist)callableall_parametersr   r   r   get_function_args[  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.
    NrK   zThe argument z must be a bytes object.)
isinstancebytesr   r   )r   r   r   r   r   r   r   `  s
   

r   c                   @   s   e Zd ZedefddZdS )	TimerBaser   c                 C   s   t )zReturn the current time.)NotImplementedErrorselfr   r   r   timev  s   zTimerBase.timeN)__name__
__module____qualname__r   floatr   r   r   r   r   r   u  s    r   c                   @   s   e Zd ZdefddZdS )Timerr   c                 C   s   t   S ro   )r   r   r   r   r   r   }  s   z
Timer.timeN)r   r   r   r   r   r   r   r   r   r   |  s    r   )r   ro   )r|   r}   )Fr   ):r(   r   r   r   rT   r`   rN   stringr$   rf   r   abcr   r   r   typesr   typingr   r   r   r	   r
   r   r+   boolr    r!   AbstractEventLoopr1   setr4   Taskr9   rH   rF   rI   ascii_lowercasedigitsrP   rG   rQ   _PRINTED_WARNINGrZ   ri   rk   rn   rt   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sn    

!"/	
/	