o
    ci;                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZ erJddlmZ ddlmZ dd	lmZ dd
lmZmZmZ eeZdd ZG dd dZdS )z^This file defines the interface between the ray client worker
and the overall ray module API.
    N)Future)TYPE_CHECKINGAnyCallableListOptionalUnion)ray_option_utils)_ClientWorkerPropertyAPI)
ActorClass)DataResponse)RemoteFunction)ClientActorHandleClientObjectRef
ClientStubc                 C   s   t | tr
| dS | S )Nzutf-8)
isinstancestrencode)value r   G/home/ubuntu/.local/lib/python3.10/site-packages/ray/util/client/api.py	_as_bytes   s   

r   c                   @   s  e Zd ZdZdiddZddddZdd	 Zd
d Zdd Zddde	e
 fddZdeddfddZdeddfddZdjddZ	didedee ddfddZdkd ede	e fd!d"Zd#d$dld&d'Zdd#d(dmd+d,Zdefd-d.Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zdefd9d:Zdid;ee dee	e  fd<d=Z defd>d?Z!dd@dAe"eef dee"eef  defdBdCZ#dd@dAe"eef dee"eef  defdDdEZ$	#dndd@dAe"eef dFe"eef dGedee"eef  def
dHdIZ%dddJdAe"eef dKedee"eef  de&fdLdMZ'dd@dNe"eef dee"eef  de	e fdOdPZ(dQedRe&ddfdSdTZ)d%dUdefdVdWZ*dXdYdefdZd[Z+dAeddfd\d]Z,dAedefd^d_Z-dAefd`daZ.dbd*dce/ddgdf ddfdedfZ0defdgdhZ1dS )o
_ClientAPIzThe Client-side methods corresponding to the ray API. Delegates
    to the Client Worker that contains the connection to the ClientServer.
    Nc                 C   s
   || _ d S N)worker)selfr   r   r   r   __init__    s   
z_ClientAPI.__init__timeoutc                C   s   | j j||dS )zget is the hook stub passed on to replace `ray.get`

        Args:
            vals: [Client]ObjectRef or list of these refs to retrieve.
            timeout: Optional timeout in milliseconds
        r   )r   get)r   valsr   r   r   r   r   #   s   z_ClientAPI.getc                 O      | j j|i |S )zput is the hook stub passed on to replace `ray.put`

        Args:
            val: The value to `put`.
            args: opaque arguments
            kwargs: opaque keyword arguments
        )r   putr   argskwargsr   r   r   r"   ,   s   z_ClientAPI.putc                 O   r!   )zwait is the hook stub passed on to replace `ray.wait`

        Args:
            args: opaque arguments
            kwargs: opaque keyword arguments
        )r   waitr#   r   r   r   r&   6   s   z_ClientAPI.waitc                 O   sn   ddl m} t|dkr!t|dkr!t|d r!|dd|d S t|dkr-t|dks2J tj||d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_decorator   N)options)ray.util.client.commonr'   lencallabler	   remote_args_error_string)r   r$   r%   r'   r   r   r   remote?   s   $
z_ClientAPI.remoteinstancer   returnc                 O   s   | j j|g|R i |S )a2  call_remote is called by stub objects to execute them remotely.

        This is used by stub objects in situations where they're called
        with .remote, eg, `f.remote()` or `actor_cls.remote()`.
        This allows the client stub objects to delegate execution to be
        implemented in the most effective way whether it's in the client,
        clientserver, or raylet worker.

        Args:
            instance: The Client-side stub reference to a remote object
            args: opaque arguments
            kwargs: opaque keyword arguments
        )r   call_remote)r   r/   r$   r%   r   r   r   r1   V   s   z_ClientAPI.call_remoteidc                 C      | j |S )ap  Attempts to release an object reference.

        When client references are destructed, they release their reference,
        which can opportunistically send a notification through the datachannel
        to release the reference being held for that object on the server.

        Args:
            id: The id of the reference to release on the server side.
        )r   call_releaser   r2   r   r   r   r4   f   s   
z_ClientAPI.call_releasec                 C   r3   )a  Attempts to retain a client object reference.

        Increments the reference count on the client side, to prevent
        the client worker from attempting to release the server reference.

        Args:
            id: The id of the reference to retain on the client side.
        )r   call_retainr5   r   r   r   r6   r   s   	z_ClientAPI.call_retainc                 C   
   | j  S )zsclose cleans up an API connection by closing any channels or
        shutting down any servers gracefully.
        )r   closer   r   r   r   r8   }   s   
z_ClientAPI.closename	namespacer   c                 C      | j ||S )zReturns a handle to an actor by name.

        Args:
            name: The name passed to this actor by
              Actor.options(name="name").remote()
        )r   	get_actor)r   r:   r;   r   r   r   r=      s   	z_ClientAPI.get_actorFall_namespacesc                 C   r3   )a  List all named actors in the system.

        Actors must have been created with Actor.options(name="name").remote().
        This works for both detached & non-detached actors.

        By default, only actors in the current namespace will be returned
        and the returned entries will simply be their name.

        If `all_namespaces` is set to True, all actors in the cluster will be
        returned regardless of namespace, and the retunred entries will be of
        the form '<namespace>/<name>'.
        )r   list_named_actors)r   r>   r   r   r   r?      s   z_ClientAPI.list_named_actorsT)
no_restartactorc                C   r<   )zkill forcibly stops an actor running in the cluster

        Args:
            no_restart: Whether this actor should be restarted if it's a
              restartable actor.
        )r   terminate_actor)r   rA   r@   r   r   r   kill   s   z_ClientAPI.kill)force	recursiveobjr   c                C   s   | j |||S )a  Cancels a task on the cluster.

        If the specified task is pending execution, it will not be executed. If
        the task is currently executing, the behavior depends on the ``force``
        flag, as per `ray.cancel()`

        Only non-actor tasks can be canceled. Canceled tasks will not be
        retried (max_retries will not be respected).

        Args:
            object_ref: ObjectRef returned by the task
                that should be canceled.
            force: Whether to force-kill a running task by killing
                the worker that is running the task.
            recursive: Whether to try to cancel tasks submitted by
                the task specified.
        )r   terminate_task)r   rF   rD   rE   r   r   r   cancel   s   z_ClientAPI.cancelc                 C   r7   )zTrue if our client is connected, and if the server is initialized.
        Returns:
            A boolean determining if the client is connected and
            server initialized.
        )r   is_initializedr9   r   r   r   rI      s   
z_ClientAPI.is_initializedc                 C   (   ddl m  m  m} | j|jjS )zGet a list of the nodes in the cluster (for debugging only).

        Returns:
            Information about the Ray clients in the cluster.
        r   N)!ray.core.generated.ray_client_pb2core	generatedray_client_pb2r   get_cluster_infoClusterInfoTypeNODESr   rN   r   r   r   nodes   s   z_ClientAPI.nodesc                    sn   ddg}d| d}t |dkrt  dksJ | D ]}d| d| }||v s.J |q fdd	}|S )
zAnnotate an actor method

        Args:
            num_returns: The number of object refs that should be returned by
                invocations of this actor method.
        num_returnsconcurrency_groupzZThe @ray.method decorator must be applied using at least one of the arguments in the list z+, for example '@ray.method(num_returns=2)'.r   z-Unexpected keyword argument to @ray.method: "z'". The supported keyword arguments are c                    s(   d v r	 d | _ d v r d | _| S )NrT   rU   )__ray_num_returns____ray_concurrency_group__)methodr%   r   r   annotate_method   s
   

z*_ClientAPI.method.<locals>.annotate_method)r+   )r   r$   r%   valid_kwargserror_stringkeykey_error_stringrZ   r   rY   r   rX      s    z_ClientAPI.methodc                 C   rJ   )a'  Get the current total cluster resources.

        Note that this information can grow stale as nodes are added to or
        removed from the cluster.

        Returns:
            A dictionary mapping resource name to the total quantity of that
                resource in the cluster.
        r   N)rK   rL   rM   rN   r   rO   rP   CLUSTER_RESOURCESrR   r   r   r   cluster_resources   s   z_ClientAPI.cluster_resourcesc                 C   rJ   )a  Get the current available cluster resources.

        This is different from `cluster_resources` in that this will return
        idle (available) resources rather than total resources.

        Note that this information can grow stale as tasks start and finish.

        Returns:
            A dictionary mapping resource name to the total quantity of that
                resource in the cluster.
        r   N)rK   rL   rM   rN   r   rO   rP   AVAILABLE_RESOURCESrR   r   r   r   available_resources  s   z_ClientAPI.available_resourcesc                 C   s   t | j S )zReturn a Ray RuntimeContext describing the state on the server

        Returns:
            A RuntimeContext wrapping a client making get_cluster_info calls.
        )r
   r   build_runtime_contextr9   r   r   r   get_runtime_context  s   z_ClientAPI.get_runtime_contextc                 C   s   g S r   r   r9   r   r   r   get_gpu_ids!  s   z_ClientAPI.get_gpu_idsfilenamec                 C   sz   t d dd lm  m  m} | j|jj	}|d ur;t
|d}t|| W d    d S 1 s4w   Y  d S |S )NzBTimeline will include events from other clients using this server.r   w)loggerwarningrK   rL   rM   rN   r   rO   rP   TIMELINEopenjsondump)r   rf   rN   
all_eventsoutfiler   r   r   timeline$  s   "z_ClientAPI.timelinec                 C   s   dS )z.Hook for internal_kv._internal_kv_initialized.Tr   r9   r   r   r   _internal_kv_initialized4  s   z#_ClientAPI._internal_kv_initializedr;   r]   c                C      | j jt|t|dS )z)Hook for internal_kv._internal_kv_exists.rr   )r   internal_kv_existsr   r   r]   r;   r   r   r   _internal_kv_exists;     z_ClientAPI._internal_kv_existsc                C   rs   )z&Hook for internal_kv._internal_kv_get.rr   )r   internal_kv_getr   ru   r   r   r   _internal_kv_getC  rw   z_ClientAPI._internal_kv_getr   	overwritec                C   s    | j jt|t||t|dS )z&Hook for internal_kv._internal_kv_put.rr   )r   internal_kv_putr   )r   r]   r   rz   r;   r   r   r   _internal_kv_putK  s   	z_ClientAPI._internal_kv_putdel_by_prefixr;   r~   c                C   s   | j jt||t|dS )z&Hook for internal_kv._internal_kv_del.r}   )r   internal_kv_delr   )r   r]   r~   r;   r   r   r   _internal_kv_delX  s   z_ClientAPI._internal_kv_delprefixc                C   rs   )z'Hook for internal_kv._internal_kv_list.rr   )r   internal_kv_listr   )r   r   r;   r   r   r   _internal_kv_listd  s   z_ClientAPI._internal_kv_listuriexpiration_sc                 C   r<   )z*Hook for internal_kv._pin_runtime_env_uri.)r   pin_runtime_env_uri)r   r   r   r   r   r   _pin_runtime_env_urio  s   z_ClientAPI._pin_runtime_env_urir   c                 C   r3   )z@Register a ClientActorClass for the ActorClass and return a UUID)r   _convert_actor)r   rA   r   r   r   r   s     z_ClientAPI._convert_actorfuncr   c                 C   r3   )z@Register a ClientRemoteFunc for the ActorClass and return a UUID)r   _convert_function)r   r   r   r   r   r   w  r   z_ClientAPI._convert_functionc                 C   r3   )z)Given a UUID, return the converted object)r   _get_convertedr   r]   r   r   r   r   {  r   z_ClientAPI._get_convertedc                 C   r3   )zACheck if a key UUID is present in the store of converted objects.)r   _converted_key_existsr   r   r   r   r     r   z _ClientAPI._converted_key_existsc                 C   s"   | dstd|| |S )N_zNot available in Ray client: `ray.{}`. This method is only available within Ray remote functions and is not yet implemented in the client API.)
startswithNotImplementedErrorformat__getattribute__r   r   r   r   __getattr__  s   

z_ClientAPI.__getattr__refcallbackr   c                 C   s   | j || d S r   )r   register_callback)r   r   r   r   r   r   _register_callback  s   z_ClientAPI._register_callbackc                 C   s0   dd l m  m  m} | j|jjddS )Nr   dashboard_url )	rK   rL   rM   rN   r   rO   rP   DASHBOARD_URLr   rR   r   r   r   _get_dashboard_url  s   z_ClientAPI._get_dashboard_urlr   )r0   N)F)rA   r   )rF   r   )T)2__name__
__module____qualname____doc__r   r   r"   r&   r.   r   r   r1   bytesr4   r6   r8   r   r   r=   boolr?   rC   rH   rI   rS   rX   r`   rb   rd   listre   r   rp   rq   r   rv   ry   r|   intr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s    
	
	

	&	 

	








	
r   )r   rl   loggingconcurrent.futuresr   typingr   r   r   r   r   r   ray._privater	   ray.util.client.runtime_contextr
   	ray.actorr   rK   r   ray.remote_functionr   r*   r   r   r   	getLoggerr   rh   r   r   r   r   r   r   <module>   s     
