
    &`ivS                     \   d dl Z d dlZd dl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mZmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lm Z  	 d dl!Z!d dl"Z"n# e#$ r dZ!dZ"Y nw xY w ej$        e%          Z&e&'                    ej(                    G d de          Z)dS )    N)AnyAsyncIteratorDictListOptionalUnion)SubmissionClient)JobDeleteResponseJobLogsResponse	JobStatusJobStopResponseJobSubmitRequestJobSubmitResponse
JobDetails)strip_keys_with_value_none)!get_address_for_submission_client)
RuntimeEnv)_validate_no_local_paths)	PublicAPIc                   ^    e Zd ZdZ	 	 	 	 	 	 d dee         dedeeeef                  deeeef                  d	eeeef                  d
ee	eef                  f fdZ
 ed          ddddddddddedee         deeeef                  deeeef                  dee         dee	eef                  dee	eef                  dee         deeeef                  defd            Z ed          dedefd            Z ed          dedefd            Z ed          dedefd            Z ed          dee         fd            Z ed          dedefd            Z ed          dedefd            Z ed          dedee         fd            Z xZS )!JobSubmissionClienta,  A local client for submitting and interacting with jobs on a remote cluster.

    Submits requests over HTTP to the job server on the cluster using the REST API.


    Args:
        address: Either (1) the address of the Ray cluster, or (2) the HTTP address
            of the dashboard server on the head node, e.g. "http://<head-node-ip>:8265".
            In case (1) it must be specified as an address that can be passed to
            ray.init(), e.g. a Ray Client address (ray://<head_node_host>:10001),
            or "auto", or "localhost:<port>". If unspecified, will try to connect to
            a running local Ray cluster. This argument is always overridden by the
            RAY_API_SERVER_ADDRESS or RAY_ADDRESS environment variable.
        create_cluster_if_needed: Indicates whether the cluster at the specified
            address needs to already be running. Ray doesn't start a cluster
            before interacting with jobs, but third-party job managers may do so.
        cookies: Cookies to use when sending requests to the HTTP job server.
        metadata: Arbitrary metadata to store along with all jobs.  New metadata
            specified per job will be merged with the global metadata provided here
            via a simple dict update.
        headers: Headers to use when sending requests to the HTTP job server, used
            for cases like authentication to a remote cluster.
        verify: Boolean indication to verify the server's TLS certificate or a path to
            a file or directory of trusted certificates. Default: True.
    NFTaddresscreate_cluster_if_neededcookiesmetadataheadersverifyc                 j   t           j        | _        	 t          t	          d          |4t          |t                    st          dt          |                     t          |t                    st          dt          |                     |4t          |t                    st          dt          |                     |4t          |t                    st          dt          |                     |4t          |t                    st          dt          |                     t          |t                    s4t          |t                    st          dt          |                     t          |          }t                                          ||||||           |                     d	d
           t          j                            | j                  t          j                            d          k    r"|                     dd| j         d           d S d S )NZThe Ray jobs CLI & SDK require the ray[default] installation: `pip install 'ray[default]'`zaddress must be a string, got z-create_cluster_if_needed must be a bool, got zcookies must be a dict, got zmetadata must be a dict, got zheaders must be a dict, got z"verify must be a str or bool, got )r   r   r   r   r   r   z1.9zeJobs API is not supported on the Ray cluster. Please ensure the cluster is running Ray 1.9 or higher.min_versionversion_error_messagez2.0zClient Ray version z is not compatible with the Ray cluster. Please ensure the cluster is running Ray 2.0 or higher or downgrade the client Ray version.)ray__version___client_ray_versionrequestsRuntimeError
isinstancestr	TypeErrortypebooldictr   super__init___check_connection_and_version	packagingversionparse)	selfr   r   r   r   r   r   api_server_url	__class__s	           q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/dashboard/modules/job/sdk.pyr0   zJobSubmissionClient.__init__?   st    $'? W=  
 z'3'?'?LT']]LLMMM2D99 	51225 5   z'4'@'@J4==JJKKK
8T(B(BLDNNLLMMMz'4'@'@J4==JJKKK63'' 	Q:fd+C+C 	QOfOOPPP:7CC"%= 	 	
 	
 	
 	**#) 	+ 	
 	
 	
 ""4#;<<y?P?V?V@
 @
 
 
 ..!'QD<T 'Q 'Q 'Q /     
 
    stable)	stability)job_idruntime_envr   submission_identrypoint_num_cpusentrypoint_num_gpusentrypoint_memoryentrypoint_resources
entrypointr<   r=   r>   r?   r@   rA   rB   returnc       	   
         |rt                               d           |s|s|	r|                     dd           |r|                     dd           |pi }|pi }|                    | j                   |                     |           |                     |           |                    d          }
|
r5t          |
t                    s t          dt          |
           d	          t          di |}t          |           |                                }|p|}t          ||||||||	
          }t!          t#          j        |                    }t                               d| d           |                     dd|          }|j        dk    r#t-          di |                                j        S |                     |           dS )aM	  Submit and execute a job asynchronously.

        When a job is submitted, it runs once to completion or failure. Retries or
        different runs with different parameters should be handled by the
        submitter. Jobs are bound to the lifetime of a Ray cluster, so if the
        cluster goes down, all running jobs on that cluster will be terminated.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> client.submit_job( # doctest: +SKIP
            ...     entrypoint="python script.py",
            ...     runtime_env={
            ...         "working_dir": "./",
            ...         "pip": ["requests==2.26.0"]
            ...     }
            ... )  # doctest: +SKIP
            'raysubmit_4LamXRuQpYdSMg7J'

        Args:
            entrypoint: The shell command to run for this job.
            submission_id: A unique ID for this job.
            runtime_env: The runtime environment to install and run this job in.
            metadata: Arbitrary data to store along with this job.
            job_id: DEPRECATED. This has been renamed to submission_id
            entrypoint_num_cpus: The quantity of CPU cores to reserve for the execution
                of the entrypoint command, separately from any tasks or actors launched
                by it. Defaults to 0.
            entrypoint_num_gpus: The quantity of GPUs to reserve for the execution
                of the entrypoint command, separately from any tasks or actors launched
                by it. Defaults to 0.
            entrypoint_memory: The quantity of memory to reserve for the
                execution of the entrypoint command, separately from any tasks or
                actors launched by it. Defaults to 0.
            entrypoint_resources: The quantity of custom resources to reserve for the
                execution of the entrypoint command, separately from any tasks or
                actors launched by it.

        Returns:
            The submission ID of the submitted job.  If not specified,
            this is a randomly generated unique ID.

        Raises:
            RuntimeError: If the request to the job server fails, or if the specified
                submission_id has already been used by a job on this cluster.
        z=job_id kwarg is deprecated. Please use submission_id instead.z2.2z`entrypoint_num_cpus`, `entrypoint_num_gpus`, and `entrypoint_resources` kwargs are not supported on the Ray cluster. Please ensure the cluster is running Ray 2.2 or higher.r!   z2.8zv`entrypoint_memory` kwarg is not supported on the Ray cluster. Please ensure the cluster is running Ray 2.8 or higher.worker_process_setup_hookzInvalid type z for `worker_process_setup_hook`. When a job submission API is used, `worker_process_setup_hook` only allows a string type (module name). Specify `worker_process_setup_hook` via ray.init within a driver to use a `Callable` type. )rC   r>   r=   r   r?   r@   rA   rB   z"Submitting job with submission_id=.POST
/api/jobs/)	json_data   N )loggerwarningr1   update_default_metadata_upload_working_dir_if_needed_upload_py_modules_if_neededgetr)   r*   
ValueErrorr,   r   r   to_dictr   r   dataclassesasdictdebug_do_requeststatus_coder   jsonr>   _raise_error)r5   rC   r<   r=   r   r>   r?   r@   rA   rB   
setup_hookreqrJ   rs                 r8   
submit_jobzJobSubmissionClient.submit_job}   sI   x  	NNO    	"5 	9M 	..!'- /     	..!'- /    "'R>r.///**;777))+666 !__%@AA
 	jS99 	FZ 0 0 F F F   !//;// ---!))++%/!'# 3 3/!5	
 	
 	
 /{/A#/F/FGG	J-JJJKKKV\YGG=C$00qvvxx00>>a     r9   c                     t                               d| d           |                     dd| d          }|j        dk    r#t	          di |                                j        S |                     |           dS )	a  Request a job to exit asynchronously.

        Attempts to terminate process first, then kills process after timeout.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> sub_id = client.submit_job(entrypoint="sleep 10") # doctest: +SKIP
            >>> client.stop_job(sub_id) # doctest: +SKIP
            True

        Args:
            job_id: The job ID or submission ID for the job to be stopped.

        Returns:
            True if the job was running, otherwise False.

        Raises:
            RuntimeError: If the job does not exist or if the request to the
                job server fails.
        zStopping job with job_id=rG   rH   rI   z/stoprK   NrL   )rM   rX   rY   rZ   r   r[   stoppedr\   r5   r<   r_   s      r8   stop_jobzJobSubmissionClient.stop_job   s    4 	::::;;;V%?&%?%?%?@@=C"..QVVXX..66a     r9   c                     t                               d| d           |                     dd|           }|j        dk    r#t	          di |                                j        S |                     |           dS )a  Delete a job in a terminal state and all of its associated data.

        If the job is not already in a terminal state, raises an error.
        This does not delete the job logs from disk.
        Submitting a job with the same submission ID as a previously
        deleted job is not supported and may lead to unexpected behavior.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient() # doctest: +SKIP
            >>> job_id = client.submit_job(entrypoint="echo hello") # doctest: +SKIP
            >>> client.delete_job(job_id) # doctest: +SKIP
            True

        Args:
            job_id: submission ID for the job to be deleted.

        Returns:
            True if the job was deleted, otherwise False.

        Raises:
            RuntimeError: If the job does not exist, if the request to the
                job server fails, or if the job is not in a terminal state.
        zDeleting job with job_id=rG   DELETErI   rK   NrL   )rM   rX   rY   rZ   r
   r[   deletedr\   rc   s      r8   
delete_jobzJobSubmissionClient.delete_job!  s    : 	::::;;;X'<F'<'<===C$00qvvxx0088a     r9   c                     |                      dd|           }|j        dk    r4t          t          d          t          di |                                S |                     |           dS )a  Get the latest status and other information associated with a job.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> submission_id = client.submit_job(entrypoint="sleep 1") # doctest: +SKIP
            >>> client.get_job_info(submission_id) # doctest: +SKIP
            JobDetails(status='SUCCEEDED',
            job_id='03000000', type='submission',
            submission_id='raysubmit_4LamXRuQpYdSMg7J',
            message='Job finished successfully.', error_type=None,
            start_time=1647388711, end_time=1647388712, metadata={}, runtime_env={})

        Args:
            job_id: The job ID or submission ID of the job whose information
                is being requested.

        Returns:
            The JobDetails for the job.

        Raises:
            RuntimeError: If the job does not exist or if the request to the
                job server fails.
        GETrI   rK   Nr    rL   )rY   rZ   r   r(   r[   r\   rc   s      r8   get_job_infoz JobSubmissionClient.get_job_infoF  s    : U$9$9$9::=C!"A  
 "--AFFHH---a     r9   c                     |                      dd          }|j        dk    r"|                                }d |D             }|S |                     |           dS )aW  List all jobs along with their status and other information.

        Lists all jobs that have ever run on the cluster, including jobs that are
        currently running and jobs that are no longer running.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> client.submit_job(entrypoint="echo hello") # doctest: +SKIP
            >>> client.submit_job(entrypoint="sleep 2") # doctest: +SKIP
            >>> client.list_jobs() # doctest: +SKIP
            [JobDetails(status='SUCCEEDED',
            job_id='03000000', type='submission',
            submission_id='raysubmit_4LamXRuQpYdSMg7J',
            message='Job finished successfully.', error_type=None,
            start_time=1647388711, end_time=1647388712, metadata={}, runtime_env={}),
            JobDetails(status='RUNNING',
            job_id='04000000', type='submission',
            submission_id='raysubmit_1dxCeNvG1fCMVNHG',
            message='Job is currently running.', error_type=None,
            start_time=1647454832, end_time=None, metadata={}, runtime_env={})]

        Returns:
            A list of JobDetails containing the job status and other information.

        Raises:
            RuntimeError: If the request to the job server fails.
        rj   rI   rK   c                 &    g | ]}t          d i |S )rL   r   ).0job_info_jsons     r8   
<listcomp>z1JobSubmissionClient.list_jobs.<locals>.<listcomp>  s3       0=
++]++  r9   N)rY   rZ   r[   r\   )r5   r_   jobs_info_json	jobs_infos       r8   	list_jobszJobSubmissionClient.list_jobsp  ss    < UL11=CVVXXN AO  I a     r9   c                 6    |                      |          j        S )a  Get the most recent status of a job.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> client.submit_job(entrypoint="echo hello") # doctest: +SKIP
            >>> client.get_job_status("raysubmit_4LamXRuQpYdSMg7J") # doctest: +SKIP
            'SUCCEEDED'

        Args:
            job_id: The job ID or submission ID of the job whose status is being
                requested.

        Returns:
            The JobStatus of the job.

        Raises:
            RuntimeError: If the job does not exist or if the request to the
                job server fails.
        )rk   status)r5   r<   s     r8   get_job_statusz"JobSubmissionClient.get_job_status  s    ,   ((//r9   c                     |                      dd| d          }|j        dk    r#t          di |                                j        S |                     |           dS )a  Get all logs produced by a job.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> sub_id = client.submit_job(entrypoint="echo hello") # doctest: +SKIP
            >>> client.get_job_logs(sub_id) # doctest: +SKIP
            'hello\n'

        Args:
            job_id: The job ID or submission ID of the job whose logs are being
                requested.

        Returns:
            A string containing the full logs of the job.

        Raises:
            RuntimeError: If the job does not exist or if the request to the
                job server fails.
        rj   rI   z/logsrK   NrL   )rY   rZ   r   r[   logsr\   rc   s      r8   get_job_logsz JobSubmissionClient.get_job_logs  sk    , U$>$>$>$>??=C"..QVVXX..33a     r9   c                  K   t          j        | j        | j                  4 d{V 	 }|                    | j         d| d| j                   d{V }	 |                                 d{V }|j        t           j	        j
        k    r|j        W V  n|j        t           j	        j        k    rWt                              d| d|j                    |j        t           j        j        k    rt%          d	|j                   nN|j        t           j	        j        k    r3t                              d
| d|                                            n	 ddd          d{V  dS # 1 d{V swxY w Y   dS )a  Get an iterator that follows the logs of a job.

        Example:
            >>> from ray.job_submission import JobSubmissionClient
            >>> client = JobSubmissionClient("http://127.0.0.1:8265") # doctest: +SKIP
            >>> submission_id = client.submit_job( # doctest: +SKIP
            ...     entrypoint="echo hi && sleep 5 && echo hi2")
            >>> async for lines in client.tail_job_logs( # doctest: +SKIP
            ...           'raysubmit_Xe7cvjyGJCyuCvm2'):
            ...     print(lines, end="") # doctest: +SKIP
            hi
            hi2

        Args:
            job_id: The job ID or submission ID of the job whose logs are being
                requested.

        Returns:
            The iterator.

        Raises:
            RuntimeError: If the job does not exist, if the request to the
                job server fails, or if the connection closes unexpectedly
                before the job reaches a terminal state.
        )r   r   NrI   z
/logs/tail)sslTzWebSocket closed for job z with close code z9WebSocket connection closed unexpectedly with close code zWebSocket error for job z!, treating as normal close. Err: )aiohttpClientSession_cookies_headers
ws_connect_address_ssl_contextreceiver,   	WSMsgTypeTEXTdataCLOSEDrM   rX   
close_codeWSCloseCodeABNORMAL_CLOSUREr(   ERROR	exception)r5   r<   sessionwsmsgs        r8   tail_job_logsz!JobSubmissionClient.tail_job_logs  sT     6 (M4=
 
 
 	 	 	 	 	 	 	 	))=>>F>>>DDU *        BJJLL((((((8w0555(NNNNNX!2!999LL\F\\R]\\   }(;(LLL*gXZXegg   X!2!888LLl6ll\^\h\h\j\jll   ' 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   D-E++
E58E5)NFNNNT)__name__
__module____qualname____doc__r   r*   r-   r   r   r   r0   r   intfloatr`   rd   rh   r   rk   r   rs   r   rv   ry   r   r   __classcell__)r7   s   @r8   r   r   $   s        8 "&).,0-1,0-1< <#< #'< $sCx.)	<
 4S>*< $sCx.)< sDy)*< < < < < <| Y"""
 !%04-1'+;?;?+/;?! ! ! ! 	!
 d38n-! 4S>*!  }! &eCJ&78! &eCJ&78! $C=! 'tCJ'78! 
! ! ! #"!B Y"""!! 
! ! ! #"!B Y""""!"! 
"! "! "! #""!H Y"""'!'! 
'! '! '! #"'!R Y"""&!4
+ &! &! &! #"&!P Y"""0S 0Y 0 0 0 #"0. Y"""!3 !3 ! ! ! #"!8 Y"""4# 4-2D 4 4 4 #"4 4 4 4 4r9   r   )*rV   loggingtypingr   r   r   r   r   r   packaging.versionr2   r$   #ray.dashboard.modules.dashboard_sdkr	    ray.dashboard.modules.job.commonr
   r   r   r   r   r   )ray.dashboard.modules.job.pydantic_modelsr   ray.dashboard.modules.job.utilsr   ray.dashboard.utilsr   ray.runtime_envr   ray.runtime_env.runtime_envr   ray.util.annotationsr   r|   r'   ImportError	getLoggerr   rM   setLevelINFOr   rL   r9   r8   <module>r      s        B B B B B B B B B B B B B B B B     



 @ @ @ @ @ @                A @ @ @ @ @ F F F F F F A A A A A A & & & & & & @ @ @ @ @ @ * * * * * *NNNOOOO   GHHH
 
	8	$	$    _ _ _ _ _* _ _ _ _ _s   A% %	A10A1