
    &`i7              )       
   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	m
Z
mZmZmZmZmZ d dlZd dlZd dlmZ d dlmZmZ d dlmZ d dlmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- d d	l.m/Z/m0Z0  e j1        e2          Z3d
Z4ede5de5de6de7fd            Z8	 e G d de                      Z9ededfde5dee5         de:de7dee         f
d            Z;ededfde5dee5         de:de7dee          f
d            Z<ededfde5dee5         de:de7dee$         f
d            Z=ededfde5dee5         de:de7dee"         f
d            Z>ededfde5dee5         de:de7dee,         f
d            Z?ededfdee5df         dee5         de:de7dee+         f
d            Z@ededfde5dee5         de:de7dee#         f
d            ZAeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee         fd#            ZBeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee$         fd$            ZCeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee"         fd%            ZDeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee          fd&            ZEeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee,         fd'            ZFeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee+         fd(            ZGeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee#         fd)            ZHeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee&         fd*            ZIeddeedddfdee5         deeee5e%e*f                           d e:de:d!e7d"e7de7dee
         fd+            ZJ	 eddddddddd,ed-d.d/dd ddfdee5         d0ee5         d1ee5         d2ee5         d3ee5         d4ee5         d5ee:         d6e7d7e:de:d8e5d9ee5         d:ee5         d;ee5         d<e:d=ee6         d>e7dee5ddf         f$d?            ZKeddddefdee5         d0ee5         d1ee5         d@ee5         de:de
e5ee5         f         fdA            ZL	 ededdfdee5         de:d"e7de7de
f
dB            ZMededdfdee5         de:d"e7de7de
f
dC            ZNededdfdee5         de:d"e7de7de
f
dD            ZOdS )E    N)contextmanager)fields)AnyDict	GeneratorListOptionalTupleUnion)SubmissionClient)!get_address_for_submission_clientray_address_to_api_server_url)DeveloperAPI)DEFAULT_LIMITDEFAULT_RPC_TIMEOUT
ActorStateClusterEventStateGetApiOptionsGetLogOptionsJobStateListApiOptions	NodeStateObjectStatePlacementGroupStatePredicateTypeRuntimeEnvStateStateResourceSummaryApiOptionsSummaryResourceSupportedFilterType	TaskStateWorkerStatedict_to_state)RayStateApiExceptionServerUnavailable  addressendpointtimeoutexplainc              #      K   |sdV  dS dt           f fdfddD             }	 |D ]}|                                 dV  |D ]}|                                 dS # |D ]}|                                 w xY w)a9  A context manager to print warnings if the request is replied slowly.

    Warnings are printed 3 times

    Args:
        address: The address of the endpoint.
        endpoint: The name of the endpoint.
        timeout: Request timeout in seconds.
        explain: Whether ot not it will print the warning.
    Nelapsedc           
      p    t                               dt          | d           d d  d           d S )N(   z / z? seconds) Waiting for the response from the API server address .)loggerinforound)r,   r'   r(   r)   s    f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/util/state/api.pyprint_warningz/warnings_on_slow_request.<locals>.print_warningC   sd    ,gq!! , ,g , ,, (, , ,	
 	
 	
 	
 	
    c                 L    g | ] }t          j        |z  |z  g           !S ))args)	threadingTimer).0ir5   r)   s     r4   
<listcomp>z,warnings_on_slow_request.<locals>.<listcomp>J   sD        	!]'A+GGG  r6   )r/         )floatstartcancel)r'   r(   r)   r*   warning_timerstimerr5   s   ```   @r4   warnings_on_slow_requestrE   .   s        
u 
 
 
 
 
 
 
 
      N
# 	 	EKKMMMM $ 	 	ELLNNNN	 	^ 	 	ELLNNNN	s   A& &Bc                       e Zd ZdZ	 	 	 ddee         deeeef                  deeeef                  f fdZe	de
eef         defd	            Z	 d dededededef
dZ	 d dededee         dedee
eeeeeee         ef                  f
dZ	 	 	 	 d!dedededededefdZdedefdZ	 d dededededee
eeeeeeeeef	                  f
dZ d
dde!de"dededef
dZ# xZ$S )"StateApiClientzLState API Client issues REST GET requests to the server for resource states.Nr'   cookiesheadersc                     t           t          d          |sddi}t          |          }t                                          |d||           dS )a  Initialize a StateApiClient and check the connection to the cluster.

        Args:
            address: Ray bootstrap address (e.g. `127.0.0.0:6379`, `auto`), or Ray
                Client address (e.g. `ray://<head-node-ip>:10001`), or Ray dashboard
                address (e.g. `http://<head-node-ip>:8265`).
                If not provided, it will be detected automatically from any running
                local Ray cluster.
            cookies: Cookies to use when sending requests to the HTTP job server.
            headers: Headers to use when sending requests to the HTTP job server, used
                for cases like authentication to a remote cluster.
        Nz\The Ray state CLI & SDK require the ray[default] installation: `pip install 'ray[default']``Content-Typeapplication/jsonF)r'   create_cluster_if_neededrI   rH   )requestsRuntimeErrorr   super__init__)selfr'   rH   rI   api_server_url	__class__s        r4   rQ   zStateApiClient.__init__r   s}    $ >    	;%'9:G ;7CC"%*	 	 	
 	
 	
 	
 	
r6   optionsreturnc                    i }t          |          D ]}|j        dk    rg |d<   g |d<   g |d<   |j        D ]}t          |          dk    rt	          d| d          |\  }}}|d                             |           |d                             |           |d                             |           t          ||j                  }|
|||j        <   |S )Nfiltersfilter_keysfilter_predicatesfilter_values   z+The given filter has incorrect input type, z). Provide (key, predicate, value) tuples.)r   namerX   len
ValueErrorappendgetattr)	clsrU   options_dictfieldfilterfilter_kfilter_predicate
filter_val
option_vals	            r4   _make_paramzStateApiClient._make_param   s'   G__ 	6 	6E zY&&.0]+460102_-%o 	E 	EF6{{a''(F& F F F   >D:H.
 /66x@@@ !45<<=MNNN 188DDDD %*55J%+5UZ(r6   Fr(   paramsr)   _explainc                    t          | j        |||          5  d }	 |                     d|||          }|j        dk    r1d|j                            dd          vr|                                 ne# t          j        j	        $ rN}d| j         | d	}|d
z  }|t          |          |d|j         d|j         dz  }t          |          |d }~ww xY wd d d            n# 1 swxY w Y   	 |                                }nR# t          j        j        $ r;}t          d|j         d|j         d|j        d t                     d          |d }~ww xY w|d         du rt          d|d                    |d         d         S )N)r'   r(   r)   r*   GET)r)   rk   r&   rL   rK    zFailed to make request to z. a  Failed to connect to API server. Please check the API server log for details. Make sure dependencies are installed with `pip install ray[default]`. Please also check dashboard is available, and included when starting ray cluster, i.e. `ray start --include-dashboard=True --head`. zResponse(url=z,status=)zFailed to parse Response(url=z	, status=z, text='z')resultFKAPI server internal error. See dashboard.log file for more details. Error: msgdata)rE   _address_do_requeststatus_coderI   getraise_for_statusrN   
exceptionsRequestExceptionr%   urlr$   jsonJSONDecodeErrortext!_MAX_HTTP_RESPONSE_EXCEPTION_TEXT)rR   r(   rk   r)   rl   responseeerr_strs           r4   _make_http_get_requestz%StateApiClient._make_http_get_request   st    &MHgx
 
 
 $	; $	; H;++#!	 ,   (C//*#+//CCD D --///&7 ; ; ;Rt}RhRRR I #+G444X8<XXAUXXXX*733:!;)$	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	; $	;L	}}HH"2 	 	 	&n n n".n n8@FhGhFh8in n n  	
 H&&&,"5/, ,   ))sN   C$AA32C$3CA	CCC$$C(+C(0D E6EEresourceidc                    |                      |          }t          j        dt          j        dt          j        dt          j        dt          j        dt          j        dt          j        di}|vrt          dj
         d	          |         g|d
<   dg|d<   |g|d<   d|d<   dj         }|                     |||j        |          }|d         }	t          |	          dk    rdS fd|	D             }	t          j        k    r|	S t          j        k    rt          |	          dk    r|	d         S |	S t          |	          dk    sJ |	d         S )a  Get resources states by id

        Args:
            resource_name: Resource names, i.e. 'workers', 'actors', 'nodes',
                'placement_groups', 'tasks', 'objects'.
                'jobs' and 'runtime-envs' are not supported yet.
            id: ID for the resource, i.e. 'node_id' for nodes.
            options: Get options. See `GetApiOptions` for details.
            _explain: Print the API information such as API
                latency or failed query information.

        Returns:
            None if not found, and if found:
            - ActorState for actors
            - PlacementGroupState for placement groups
            - NodeState for nodes
            - WorkerState for workers
            - TaskState for tasks
            - JobState for jobs

            Empty list for objects if not found, or list of ObjectState for objects

        Raises:
            Exception: This doesn't catch any exceptions raised when the underlying request
                call raises exceptions. For example, it could raise `requests.Timeout`
                when timeout occurs.
            ValueError:
                if the resource could not be GET by id, i.e. jobs and runtime-envs.

        node_idactor_idplacement_group_id	worker_idtask_id	object_idsubmission_idz
Can't get z by id.rY   =rZ   r[   Tdetail/api/v0/r(   rk   r)   rl   rq   r   Nc                 0    g | ]}t          |          S  r#   r;   dr   s     r4   r=   z&StateApiClient.get.<locals>.<listcomp>C  s#    ===-8,,===r6      )rj   r   NODESACTORSPLACEMENT_GROUPSWORKERSTASKSOBJECTSJOBSr_   r]   valuer   r)   r^   )
rR   r   r   rU   rl   rk   RESOURCE_ID_KEY_NAMEr(   list_api_responserq   s
    `        r4   rx   zStateApiClient.get   s   ` !!'**  **,@!;!; 
 ///@(-@@@AAA!5h!? @}'*e"##%$x.hn.. 77O	 8 
 
 #8, v;;!4====f===},,,
 M}*** 6{{aay M 6{{aayr6   Tapi_responsewarn_data_source_not_availablewarn_data_truncation
warn_limitwarn_server_side_warningsc                    |r,|                     dd          }|rt          j        |           |rB|d         }|d         }	|	|k    r,t          j        d| d|	 d|j         d|	|z
   d	| d
           |rK|d         }
|d         }|
t	          |          k    r(t          j        dt	          |           d|
 d           |r1|                     dg           }|r|D ]}t          j        |           dS dS dS )a  Print the API warnings.

        Args:
            resource: Resource names, i.e. 'jobs', 'actors', 'nodes',
                see `StateResource` for details.
            api_response: The dictionarified `ListApiResponse` or `SummaryApiResponse`.
            warn_data_source_not_available: Warn when some data sources
                are not available.
            warn_data_truncation: Warn when results were truncated at
                the data source.
            warn_limit: Warn when results were limited.
            warn_server_side_warnings: Warn when the server side generates warnings
                (E.g., when callsites not enabled for listing objects)
        partial_failure_warningNnum_after_truncationtotalz1The returned data may contain incomplete result. z (z total from the cluster) z% are retrieved from the data source. z% entries have been truncated. Max of zG entries are retrieved from data source to prevent over-sized payloads.num_filteredrq   zLimit last z entries (Total zs). Use `--filter` to reduce the amount of data to return or setting a higher limit with `--limit` to see all data. warnings)rx   r   warnr   r^   )rR   r   r   r   r   r   r   warning_msgsr   r   r   rt   warnings_to_printwarning_to_prints                 r4   _print_api_warningz!StateApiClient._print_api_warningW  s   0 * 	,'++,EtLLL ,l+++ 	#/0F#G  )E+++ K/K K38K K#>K K !#77K K #7	K K K	 	 	  	 (7L)Dc$ii''Rc$ii R R".R R R   % 	4 , 0 0R @ @  4(9 4 4$M"23333	4 	44 44 4r6   c           	          |                     dd          }|rt          d|j         d          |d         }|d         }||k    rt          d| d|j         d| d	          dS )
aZ  Raise an exception when the API resopnse contains a missing output.

        Output can be missing if (1) Failures on some of data source queries (e.g.,
        `ray list tasks` queries all raylets, and if some of queries fail, it will
        contain missing output. If all queries fail, it will just fail). (2) Data
        is truncated because the output is too large.

        Args:
            resource: Resource names, i.e. 'jobs', 'actors', 'nodes',
                see `StateResource` for details.
            api_response: The dictionarified `ListApiResponse` or `SummaryApiResponse`.
        r   NzFailed to retrieve all z from the cluster becausethey are not reachable due to query failures to the data sources. To avoid raising an exception and allow having missing output, set `raise_on_missing_output=False`. r   r    z{ from the cluster because they are not reachable due to data truncation. It happens when the returned data is too large (> zf) To avoid raising an exception and allow having missing output, set `raise_on_missing_output=False`. )rx   r$   r   )rR   r   r   r   r   r   s         r4   _raise_on_missing_outputz'StateApiClient._raise_on_missing_output  s     $''(A4HH 	&8(. 8 8 8   W%+,BC(((&8% 8 8(. 8 8 +8 8 8
 
 
 )(r6   raise_on_missing_outputc                 2   |                                 rg S dj         }|                     |          }|                     |||j        |          }|r|                     |           |r|                     |           fd|d         D             S )a  List resources states

        Args:
            resource: Resource names, i.e. 'jobs', 'actors', 'nodes',
                see `StateResource` for details.
            options: List options. See `ListApiOptions` for details.
            raise_on_missing_output: When True, raise an exception if the output
                is incomplete. Output can be incomplete if
                (1) there's a partial network failure when the source is distributed.
                (2) data is truncated because it is too large.
                Set it to False to avoid throwing an exception on missing data.
            _explain: Print the API information such as API
                latency or failed query information.

        Returns:
            A list of queried result from `ListApiResponse`,

        Raises:
            Exception: This doesn't catch any exceptions raised when the
                underlying request call raises exceptions. For example, it could
                raise `requests.Timeout` when timeout occurs.

        r   r   c                 0    g | ]}t          |          S r   r   r   s     r4   r=   z'StateApiClient.list.<locals>.<listcomp>   s#    PPPqa**PPPr6   rq   )has_conflicting_filtersr   rj   r   r)   r   r   )rR   r   rU   r   rl   r(   rk   r   s    `      r4   listzStateApiClient.list  s    T **,, 	I.hn..!!'** 77O	 8 
 
 # 	G))(4EFFF 	A##H.?@@@PPPP4Eh4OPPPPr6   rl   c                    d|j         i}d|j         d}|                     |||j         |          }|r|                     ||           |r|                     ||d           |d         d         S )	a  Summarize resources states

        Args:
            resource_name: Resource names,
                see `SummaryResource` for details.
            options: summary options. See `SummaryApiOptions` for details.
            raise_on_missing_output: Raise an exception if the output has missing data.
                Output can have missing data if (1) there's a partial network failure
                when the source is distributed. (2) data is truncated
                because it is too large.
            _explain: Print the API information such as API
                latency or failed query information.

        Returns:
            A dictionary of queried result from `SummaryApiResponse`.

        Raises:
            Exception: This doesn't catch any exceptions raised when the
                underlying request call raises exceptions. For example, it could
                raise `requests.Timeout` when timeout occurs.
        r)   r   z
/summarizer   F)r   rq   node_id_to_summary)r)   r   r   r   r   )rR   r   rU   r   rl   rk   r(   summary_api_responses           r4   summaryzStateApiClient.summary  s    : W_-8hn888#::O	  ;  
  
 # 	J))(4HIII 	V##H.Bu#UUU#H-.BCCr6   )NNN)F)TTTT)%__name__
__module____qualname____doc__r	   strr   r   rQ   classmethodr   r   r   rj   r@   boolr   r   r   r   r   r"   r!   r   r   r   rx   dictr   r   r   r   r   r   r   r   __classcell__)rT   s   @r4   rG   rG   n   s       VV "&,0,0	"
 "
#"
 $sCx.)"
 $sCx.)	"
 "
 "
 "
 "
 "
H %(E"F 4    [F <* <*<* <* 	<*
 <* 
<* <* <* <*F b bb b -(	b
 b 
	


b b b bP 04%)*.F4 F4F4 F4 )-	F4
 #F4 F4 $(F4 F4 F4 F4P% %d % % % %X :Q :Q:Q  :Q "&	:Q
 :Q 

	

:Q :Q :Q :QD *D *D *D!*D #	*D
 "&*D *D 
*D *D *D *D *D *D *D *Dr6   rG   Fr   rl   rV   c                     t          |                              t          j        | t	          |          |          S )aI  Get an actor by id.

    Args:
        id: Id of the actor
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state API requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if actor not found, or
        :class:`ActorState <ray.util.state.common.ActorState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r'   r)   r   )rG   rx   r   r   r   r   r'   r)   rl   s       r4   	get_actorr   /  sC    0 '***..b-"@"@"@8 /   r6   c                     t          |                              t          j        | t	          |          |          S )ag  Get a submission job detail by id.

    Args:
        id: Submission ID obtained from job API.
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state API requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if job not found, or
        :class:`JobState <ray.util.state.common.JobState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   rx   r   r   r   r   s       r4   get_jobr   L  sF    0 '***..
g&&&	 /   r6   c                     t          |                              t          j        | t	          |          |          S )aZ  Get a placement group by id.

    Args:
        id: Id of the placement group
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state APIs requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if actor not found, or
        :class:`~ray.util.state.common.PlacementGroupState`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   rx   r   r   r   r   s       r4   get_placement_groupr   l  sF    0 '***..&
g&&&	 /   r6   c                     t          |                              t          j        | t	          |          |          S )aI  Get a node by id.

    Args:
        id: Id of the node.
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state APIs requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if actor not found, or
        :class:`NodeState <ray.util.state.common.NodeState>`.

    Raises:
        RayStateApiException: if the CLI is failed to query the data.
    r   r   r   )rG   rx   r   r   r   r   s       r4   get_noder     sF    0 '***..
g&&&	 /   r6   c                     t          |                              t          j        | t	          |          |          S )aM  Get a worker by id.

    Args:
        id: Id of the worker
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state APIs requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if actor not found, or
        :class:`WorkerState <ray.util.state.common.WorkerState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   rx   r   r   r   r   s       r4   
get_workerr     sF    0 '***..
g&&&	 /   r6   zray.ObjectRefc                     t          | t                    r| }n&|                                                                 }t	          |                              t          j        |t          |          |          S )a  Get task attempts of a task by id.

    Args:
        id: String id of the task or ObjectRef that corresponds to task
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state APIs requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        None if task not found, or a list of
        :class:`~ray.util.state.common.TaskState`
        from the task attempts.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )	
isinstancer   r   hexrG   rx   r   r   r   )r   r'   r)   rl   str_ids        r4   get_taskr     sx    4 "c $!!##'***..g&&&	 /   r6   c                     t          |                              t          j        | t	          |          |          S )a  Get objects by id.

    There could be more than 1 entry returned since an object could be
    referenced at different places.

    Args:
        id: Id of the object
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout value for the state APIs requests made.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`~ray.util.state.common.ObjectState`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   rx   r   r   r   r   s       r4   get_objectsr     sF    6 '***..
g&&&	 /   r6   TrX   limitr   r   c           	          t          |                               t          j        t	          ||||          ||          S )aq  List actors in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("id", "=", "abcd")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `ActorState`)
            will be queried and returned. See
            :class:`ActorState <ray.util.state.common.ActorState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`ActorState <ray.util.state.common.ActorState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r)   rX   r   rU   r   rl   )rG   r   r   r   r   r'   rX   r   r)   r   r   rl   s          r4   list_actorsr     sY    F '***//	
 
 
 !8 0 
 
 
r6   c           	          t          |                               t          j        t	          ||||          ||          S )ay  List placement groups in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("state", "=", "abcd")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `PlacementGroupState`)
            will be queried and returned. See
            :class:`~ray.util.state.common.PlacementGroupState`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of :class:`~ray.util.state.common.PlacementGroupState`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   list_placement_groupsr   E  sV    D '***//&'&
 
 
 !8 0   r6   c           	          t          |                               t          j        t	          ||||          ||          S )a  List nodes in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("node_name", "=", "abcd")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `NodeState`)
            will be queried and returned. See
            :class:`NodeState <ray.util.state.common.NodeState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of dictionarified
        :class:`NodeState <ray.util.state.common.NodeState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   
list_nodesr   q  V    F '***//'&
 
 
 !8 0   r6   c           	          t          |                               t          j        t	          ||||          ||          S )a  List jobs submitted to the cluster by :ref:`ray job submission <jobs-overview>`.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("status", "=", "abcd")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `JobState`)
            will be queried and returned. See
            :class:`JobState <ray.util.state.common.JobState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of dictionarified
        :class:`JobState <ray.util.state.common.JobState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   	list_jobsr     sV    F '***//'&
 
 
 !8 0   r6   c           	          t          |                               t          j        t	          ||||          ||          S )a}  List workers in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("is_alive", "=", "True")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `WorkerState`)
            will be queried and returned. See
            :class:`WorkerState <ray.util.state.common.WorkerState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`WorkerState <ray.util.state.common.WorkerState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   list_workersr     V    F '***//'&
 
 
 !8 0   r6   c           	          t          |                               t          j        t	          ||||          ||          S )aq  List tasks in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("is_alive", "=", "True")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `TaskState`)
            will be queried and returned. See
            :class:`TaskState <ray.util.state.common.TaskState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`TaskState <ray.util.state.common.TaskState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   
list_tasksr     r   r6   c           	          t          |                               t          j        t	          ||||          ||          S )az  List objects in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("ip", "=", "0.0.0.0")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `ObjectState`)
            will be queried and returned. See
            :class:`ObjectState <ray.util.state.common.ObjectState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`ObjectState <ray.util.state.common.ObjectState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r   s          r4   list_objectsr   %  r   r6   c           	          t          |                               t          j        t	          ||||          ||          S )a  List runtime environments in the cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        filters: List of tuples of filter key, predicate (=, or !=), and
            the filter value. E.g., `("node_id", "=", "abcdef")`
            String filter values are case-insensitive.
        limit: Max number of entries returned by the state backend.
        timeout: Max timeout value for the state APIs requests made.
        detail: When True, more details info (specified in `RuntimeEnvState`)
            will be queried and returned. See
            :class:`RuntimeEnvState <ray.util.state.common.RuntimeEnvState>`.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Returns:
        List of
        :class:`RuntimeEnvState <ray.util.state.common.RuntimeEnvState>`.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   RUNTIME_ENVSr   r   s          r4   list_runtime_envsr   R  sV    F '***//"'&
 
 
 !8 0   r6   c           	          t          |                               t          j        t	          ||||          ||          S )Nr   r   r   )rG   r   r   CLUSTER_EVENTSr   r   s          r4   list_cluster_eventsr     sU     '***//$'&
 
 
 !8 0   r6   outzutf-8strictr   node_ipfilenamer   r   pidfollowtailsuffixencodingerrorsr   attempt_number	_intervalfilter_ansi_codec              #   8  K   t          |           }|rdnd}t          ||||||||||	|
||          }i }t          |          D ]#}t          ||j                  }|
|||j        <   $|||d<   t          j        | d| dt          j        	                    |           d	          5 }|j
        d
k    rt          |j                  |                    d          D ]}||                    ||          }|V   	 ddd           dS # 1 swxY w Y   dS )a  Retrieve log file based on file name or some entities ids (pid, actor id, task id).

    Examples:
        .. testcode::
            :hide:

            import ray
            import time

            ray.shutdown()
            ray.init()

            # Wait for the node to be registered to the dashboard
            time.sleep(5)

        .. testcode::

            import ray
            from ray.util.state import get_log

            # Node id could be retrieved from list_nodes() or ray.nodes()
            node_id = ray.nodes()[0]["NodeID"]
            filename = "raylet.out"
            for l in get_log(filename=filename, node_id=node_id):
               print(l)

        .. testoutput::
            :options: +MOCK

            [2023-05-19 12:35:18,347 I 4259 68399276] (raylet) io_service_pool.cc:35: IOServicePool is running with 1 io_service.
            [2023-05-19 12:35:18,348 I 4259 68399276] (raylet) store_runner.cc:32: Allowing the Plasma store to use up to 2.14748GB of memory.
            [2023-05-19 12:35:18,348 I 4259 68399276] (raylet) store_runner.cc:48: Starting object store with directory /tmp, fallback /tmp/ray, and huge page support disabled

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If not specified, it will be retrieved from the initialized ray cluster.
        node_id: Id of the node containing the logs .
        node_ip: Ip of the node containing the logs. (At least one of the node_id and
            node_ip have to be supplied when identifying a node).
        filename: Name of the file (relative to the ray log directory) to be retrieved.
        actor_id: Id of the actor if getting logs from an actor.
        task_id: Id of the task if getting logs from a non concurrent actor.
            For concurrent actor, please query the log with actor_id.
        pid: PID of the worker if getting logs generated by a worker. When querying
            with pid, either node_id or node_ip must be supplied.
        follow: When set to True, logs will be streamed and followed.
        tail: Number of lines to get from the end of the log file. Set to -1 for getting
            the entire log.
        timeout: Max timeout for requests made when getting the logs.
        suffix: The suffix of the log file if query by id of tasks/workers/actors. Default to "out".
        encoding: The encoding used to decode the content of the log file. Default is
            "utf-8". Use None to get binary data directly.
        errors: The error handling scheme to use for decoding errors. Default is
            "strict". See https://docs.python.org/3/library/codecs.html#error-handlers
        submission_id: Job submission ID if getting log from a submission job.
        attempt_number: The attempt number of the task if getting logs generated by a task.
        _interval: The interval in secs to print new logs when `follow=True`.
        filter_ansi_code: A boolean flag for determining whether to filter ANSI escape codes.
            Setting to `True` removes ANSI escape codes from the output. The default value is `False`.

    Return:
        A Generator of log line, None for SendType and ReturnType.

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    streamfile)r   r   r   r   r   r   linesinterval
media_typer)   r   r   r  Nr  z/api/v0/logs/?T)r     )
chunk_size)r   r  )r   r   r   ra   r]   rN   rx   urllibparse	urlencoderw   r$   r   iter_contentdecode)r'   r   r   r   r   r   r   r   r   r)   r   r   r  r   r  r  r  rS   r
  rU   rc   rd   ri   rchunks                            r4   get_logr    s     n 37;;N#/J#%  G L 2 2Wej11
!'1L$#+;'(	 	2 	2
 	2 	2<!!,//	2 	2
 
 
 
 
=C&qv...^^t^44 	 	E#hvFFKKKK	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   +ADDDglob_filterc                    ||
J d            t          |           }|sd}i }|r||d<   |r||d<   |r||d<   ||d<   t          j        | dt          j                            |                     }|                                 |                                }|d	         d
u rt          d|d                    |d         d	         S )a  Listing log files available.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If not specified, it will be retrieved from the initialized ray cluster.
        node_id: Id of the node containing the logs.
        node_ip: Ip of the node containing the logs.
        glob_filter: Name of the file (relative to the ray log directory) to be
            retrieved. E.g. `glob_filter="*worker*"` for all worker logs.
        actor_id: Id of the actor if getting logs from an actor.
        timeout: Max timeout for requests made when getting the logs.
        _interval: The interval in secs to print new logs when `follow=True`.

    Return:
        A dictionary where the keys are log groups (e.g. gcs, raylet, worker), and
        values are list of log filenames.

    Raises:
        RayStateApiException: if the CLI failed to query the data, or ConnectionError if
            failed to resolve the ray address.
    Nz/At least one of node ip and node id is required*r   r   globr)   z/api/v0/logs?rq   Frr   rs   rt   )	r   rN   rx   r  r  r  ry   r}   r$   )	r'   r   r   r  r)   rS   rc   r  r   s	            r4   	list_logsr    s   < 	w228  322 37;;N L *")Y *")Y +*V%LNN(>(>|(L(LNN	 	A vvxxHU"""(uo( (
 
 	
 FH%%r6   c                     t          |                               t          j        t	          |          ||          S )a  Summarize the tasks in cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout for requests made when getting the states.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Return:
        Dictionarified
        :class:`~ray.util.state.common.TaskSummaries`

    Raises:
        RayStateApiException: if the CLI is failed to query the data.
    r   r   r   )rG   r   r   r   r   r'   r)   r   rl   s       r4   summarize_tasksr  Z  sF    2 '***22!'222 7	 3   r6   c                     t          |                               t          j        t	          |          ||          S )a  Summarize the actors in cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout for requests made when getting the states.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Return:
        Dictionarified
        :class:`~ray.util.state.common.ActorSummaries`

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r  s       r4   summarize_actorsr  {  sF    2 '***22!'222 7	 3   r6   c                     t          |                               t          j        t	          |          ||          S )a  Summarize the objects in cluster.

    Args:
        address: Ray bootstrap address, could be `auto`, `localhost:6379`.
            If None, it will be resolved automatically from an initialized ray.
        timeout: Max timeout for requests made when getting the states.
        raise_on_missing_output: When True, exceptions will be raised if
            there is missing data due to truncation/data source unavailable.
        _explain: Print the API information such as API latency or
            failed query information.

    Return:
        Dictionarified :class:`~ray.util.state.common.ObjectSummaries`

    Raises:
        RayStateApiException: if the CLI failed to query the data.
    r   r   r   )rG   r   r   r   r   r  s       r4   summarize_objectsr!    sF    0 '***22!'222 7	 3   r6   )Ploggingr9   r  r   
contextlibr   dataclassesr   typingr   r   r   r   r	   r
   r   rN   ray#ray.dashboard.modules.dashboard_sdkr   ray.dashboard.utilsr   r   ray.util.annotationsr   ray.util.state.commonr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   ray.util.state.exceptionr$   r%   	getLoggerr   r1   r   r   r@   r   rE   rG   intr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r!  r   r6   r4   <module>r.     s\          % % % % % %       E E E E E E E E E E E E E E E E E E  



 @ @ @ @ @ @        . - - - - -                                           , M L L L L L L L		8	$	$$' ! ''"'-2'=A' ' ' 'T* }D }D }D }D }D% }D }D }D@  "&	 c]  	
 j   8  "&	 c]  	
 h   >  "&	 c]  	
 !"   >  "&	 c]  	
 i   >  "&	 c]  	
 k   >  "&	" "c?"#"c]" " 	"
 i" " " "J  "&	 c]  	
 
+   D !NR&$(, ,c],d5m5H!HIJK, , 	,
 , ", , 
*, , , ,^ !NR&$(( (c](d5m5H!HIJK( ( 	(
 ( "( ( 

( ( ( (V !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
)_) ) ) )X !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
(^) ) ) )X !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
+) ) ) )X !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
)_) ) ) )X !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
+) ) ) )X !NR&$() )c])d5m5H!HIJK) ) 	)
 ) ") ) 
/) ) ) )X !NR&$( c]d5m5H!HIJK  	
  "  
$Z   &
 !!!""!&%$#'!%"#{ {c]{c]{ c]{ sm	{
 sm{ c]{ 
#{ { { { { sm{ SM{ C={ {  !{" #{$ sD$%{ { { {| !!!!%&:& :&c]:&c]:& c]:& #	:&
 :& 
#tCy.:& :& :& :&z
 !&$(	 c] " 	
 
   @ !&$(	 c] " 	
 
   @ !&$(	 c] " 	
 
     r6   