o
    ciw)                     @   s   d dl Z d dlZd dlZd dlmZmZmZmZmZ d dl	m
  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 e eZG dd	 d	Ze ae ae aeG d
d dZ e  Z!edd Z"dS )    N)AnyDictListOptionalTuple)_explicitly_disable_client_mode_explicitly_enable_client_mode)setup_logger)	JobConfig)DeveloperAPI)check_version_infoc                   @   s   e Zd Zdd Z					d&dddddeded	ed
eeeef  de	dedede
d de
eeef  deeef fddZdd Zdeeef deddfddZdd Zdd ZdefddZdefd d!Zd"d# Zd'd$d%ZdS )(_ClientContextc                 C   s0   ddl m} | | _d | _d | _d| _d| _d S )Nr   
_ClientAPIF)ray.util.client.apir   apiclient_worker_server_connected_with_init_inside_client_testselfr    r   L/home/ubuntu/.local/lib/python3.10/site-packages/ray/util/client/__init__.py__init__   s   
z_ClientContext.__init__NF   )ignore_version_credentialsray_init_kwargsconn_str
job_configsecuremetadataconnection_retries	namespacer   r   zgrpc.ChannelCredentialsr   returnc                C   s  ddl m}
 | jdur| jrdS td| jst  |dur(|p"t }|| t	j
}t	j}|	du r4i }	d|	d< |	ddurC|	d }|	ddurN|	d }t|| z(|
|||||d	| _| j| j_| j||	 | j }| || |   |W S  ty   |    w )
aW  Connect the Ray Client to a server.

        Args:
            conn_str: Connection string, in the form "[host]:port"
            job_config: The job config of the server.
            secure: Whether to use a TLS secured gRPC channel
            metadata: gRPC metadata to send on connect
            connection_retries: number of connection attempts to make
            ignore_version: whether to ignore Python or Ray version mismatches.
                This should only be used for debugging purposes.

        Returns:
            Dictionary of connection info, e.g., {"num_clients": 1}.
        r   )WorkerNz6ray.init() called, but ray client is already connectedT_skip_env_hooklogging_levellogging_format)r!   r   r"   r#   )ray.util.client.workerr&   r   r   	Exceptionr   r   r
   set_ray_namespaceray_constantsLOGGER_LEVELLOGGER_FORMATgetr	   r   worker_server_initconnection_info_check_versions_register_serializers
disconnect)r   r   r    r!   r"   r#   r$   r   r   r   r&   r(   r)   	conn_infor   r   r   connect   sL   





z_ClientContext.connectc                 C   s,   ddl }ddlm} | }|jj| dS )zRegister the custom serializer addons at the client side.

        The server side should have already registered the serializers via
        regular worker's serialization_context mechanism.
        r   N)StandaloneSerializationContext)ray.util.serialization_addonsray.util.serializationr9   utilserialization_addonsapply)r   rayr9   ctxr   r   r   r5   j   s   z$_ClientContext._register_serializersr7   c                 C   s$   |pdt jv }t|d| dd d S )NRAY_IGNORE_VERSION_MISMATCHz
Ray Clientminor)raise_on_mismatchpython_version_match_level)osenvironr   )r   r7   r   r   r   r   r4   v   s   
z_ClientContext._check_versionsc                 C   s2   ddl m} | jdur| j  | | _d| _dS )zDisconnect the Ray Client.r   r   N)r   r   r   closer   r   r   r   r   r6      s
   


z_ClientContext.disconnectc                 O   s   | j j|i |S )a	  remote is the hook stub passed on to replace `ray.remote`.

        This sets up remote functions or actors, as the decorator,
        but does not execute them.

        Args:
            args: opaque arguments
            kwargs: opaque keyword arguments
        )r   remoter   argskwargsr   r   r   rH      s   
z_ClientContext.remotekeyc                 C   s,   |   r
t| j|S |dv rdd S td)N)is_initialized_internal_kv_initializedc                   S   s   dS NFr   r   r   r   r   <lambda>   s    z,_ClientContext.__getattr__.<locals>.<lambda>zBRay Client is not connected. Please connect by calling `ray.init`.)is_connectedgetattrr   r+   )r   rL   r   r   r   __getattr__   s   z_ClientContext.__getattr__c                 C   s   | j d u rdS | j  S rO   )r   rQ   r   r   r   r   rQ      s   

z_ClientContext.is_connectedc                 O   sh   | j d ur	tddd lm  m  m  m} |jdg|R i |\}}|j| _ | d d| _	|S )Nz/Trying to start two instances of ray via clientr   z127.0.0.1:50051T)
r   r+   ray.util.client.server.serverr<   clientserverinit_and_servegrpc_serverr8   r   )r   rJ   rK   ray_client_serverserver_handleaddress_infor   r   r   init   s   


z_ClientContext.initc                 C   sL   |    dd lm  m  m  m} | jd u rd S || j| d | _d S Nr   )r6   rU   r<   rV   rW   r   shutdown_with_server)r   _exiting_interpreterrZ   r   r   r   shutdown   s   

z_ClientContext.shutdown)NFNr   N)F)__name__
__module____qualname__r   strr
   boolr   r   intr   r   r   r8   r5   r4   r6   rH   rS   rQ   r]   ra   r   r   r   r   r      sP    		


L
r   c                   @   sh   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )
RayAPIStuba  This class stands in as the replacement API for the `import ray` module.

    Much like the ray module, this mostly delegates the work to the
    _client_worker. As parts of the ray API are covered, they are piped through
    here or on the client worker API.
    c                 C   s   t  | _t| j_d| _d S rO   )	threadinglocal_cxt_default_contexthandlerr   rT   r   r   r   r      s   

zRayAPIStub.__init__c                 C   s2   z| j dW S  ty   t| j _| j j Y S w )Nrm   )rk   __getattribute__AttributeErrorrl   rm   rT   r   r   r   get_context   s   zRayAPIStub.get_contextc                 C   s*   |   }|d u rt | j_|S || j_|S N)rp   r   rk   rm   )r   cxtold_cxtr   r   r   set_context   s   
zRayAPIStub.set_contextc                 C   s   |   tkS rq   )rp   rl   rT   r   r   r   
is_default   s   zRayAPIStub.is_defaultc                 O   sX   | j |  _ |  j|i |}t t| jj W d    |S 1 s%w   Y  |S rq   )r   rp   r8   _lock_all_contextsaddrk   rm   )r   rJ   kw_argsconnr   r   r   r8      s   
zRayAPIStub.connectc                 O      t H t|  krtD ]
}|j|i | qt an
|  j|i | |  tv r1t|   ttdkrBt  W d    d S W d    d S 1 sMw   Y  d S r^   )	rv   rl   rp   rw   r6   setremovelenr   )r   rJ   ry   rr   r   r   r   r6         	"zRayAPIStub.disconnectc                 O      |   j|i |S rq   )rp   rH   rI   r   r   r   rH         zRayAPIStub.remotec                 C   s   |   |S rq   )rp   rS   )r   namer   r   r   rS      s   zRayAPIStub.__getattr__c                 O   r   rq   )rp   rQ   rI   r   r   r   rQ     r   zRayAPIStub.is_connectedc                 O   sL   |   j|i |}t t| jj W d    |S 1 sw   Y  |S rq   )rp   r]   rv   rw   rx   rk   rm   )r   rJ   rK   retr   r   r   r]     s   
zRayAPIStub.initc                 O   r{   r^   )	rv   rl   rp   rw   ra   r|   r}   r~   r   )r   rJ   rK   rr   r   r   r   ra     r   zRayAPIStub.shutdownN)rb   rc   rd   __doc__r   rp   rt   ru   r8   r6   rH   rS   rQ   r]   ra   r   r   r   r   rh      s    rh   c                   C   s0   t  ttW  d   S 1 sw   Y  dS )z/Return the number of client connections active.N)rv   r~   rw   r   r   r   r   num_connected_contexts  s   $r   )#loggingrE   ri   typingr   r   r   r   r   ray._private.ray_constants_privater-   ray._private.client_mode_hookr   r   ray._private.ray_loggingr	   ray.job_configr
   ray.util.annotationsr   ray._private.utilsr   	getLoggerrb   loggerr   r|   rw   Lockrv   rl   rh   r?   r   r   r   r   r   <module>   s*    
 -T