
    &`i_0                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZmZ d dlmZmZmZmZ d dlmZmZmZ d dlmZ 	 d dlZd d	l m!Z!m"Z" n# e#$ r	 dZdZ!dZ"Y nw xY w ej$        e%          Z&d
Z'dZ(dedee)         fdZ*de
e)ef         de
e)ef         fdZ+de)de)fdZ,de)de	eee)                           fdZ-de!dedeee"f         fdZ.	 	 d$dedee)         dee/         dee
e)ef         e
e)ef         f         fdZ0dedede)dee         fdZ1dededee)         de
e)ef         fdZ2	 d%de)d e/d!e/d"e/de)f
d#Z3dS )&    N)	dataclass)AnyAsyncIteratorDictListOptionalTupleUnion)ray_constants)RAY_INTERNAL_NAMESPACE_PREFIX	GcsClient)JOB_ID_METADATA_KEYJobInfoStorageClient	JobStatusvalidate_request_type)
DriverInfo
JobDetailsJobType)
RuntimeEnv)RequestResponse
   i N  
gcs_clientreturnc                    K   |                      t          j        t          j        d           d{V }|dS |                                S )z%Fetches Head node id persisted in GCS   )	namespacetimeoutN)async_internal_kv_getr   KV_HEAD_NODE_ID_KEYKV_NAMESPACE_JOBdecode)r   head_node_id_hex_bytess     s/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/dashboard/modules/job/utils.pyget_head_node_idr%   %   sn      #-#C#C)0 $D $ $      
 %t!((***    dc                 >    d |                                  D             S )z-Strip keys with value None from a dictionary.c                     i | ]
\  }}|||S N ).0kvs      r$   
<dictcomp>z.strip_keys_with_value_none.<locals>.<dictcomp>3   s    888TQ!-Aq---r&   )items)r'   s    r$   strip_keys_with_value_noner1   1   s    88QWWYY8888r&   urlc                     t          j        d|           }t          |          dk    r |                     d|d          dd          } | S )zRedact any passwords in a URL.zhttps?:\/\/.*:(.*)@.*r   :@z:<redacted>@)refindalllenreplace)r2   secrets     r$   redact_url_passwordr;   6   sK    Z0#66F
6{{Qkk*fQi***N;;Jr&   pathc                  K   t          | t                    s t          dt          |            d          t          j                            |           sBt                              d|  d           dW V  t          j                            |           Bd}t          | d          5 }g }d}d}	 t          |          d
k    s|t          k    s||k    r|pdW V  g }d}|                                }||k    r(|                    |           |t          |          z  }nt          j        d           d{V  # 1 swxY w Y   dS )aw  Yield lines from a file as it's written.

    Returns lines in batches of up to 10 lines or 20000 characters,
    whichever comes first. If it's a chunk of 20000 characters, then
    the last line that is yielded could be an incomplete line.
    New line characters are kept in the line string.

    Returns None until the file exists or if no new line has been written.
    zpath must be a string, got .zPath z doesn't exist yet.N rr   Tr      )
isinstancestr	TypeErrortypeosr<   existsloggerdebugopenr8   MAX_CHUNK_CHAR_LENGTHreadlineappendasynciosleep)r<   EOFflineschunk_char_count	curr_lines         r$   file_tail_iteratorrU   ?   s      dC   ECd4jjCCCDDDgnnT"" 6T666777



 gnnT""  C	dC #'A		' E

b  #&;;;## mt#####$  

I
 CY''' C	NN2   mA&&&&&&&&&;	'#' #' #' #' #' #' #' #' #' #'s   +BD??EEreqrequest_typec                 H  K   ddl }t          |                                  d{V           }	 t          ||          S # t          $ rX}t
                              d|            t          t          j	                    |j
        j        j                  cY d}~S d}~ww xY w)a  Parse request and cast to request type.

    Remove keys with value None to allow newer client versions with new optional fields
    to work with older servers.

    If parsing failed, return a Response object with status 400 and stacktrace instead.

    Args:
        req: aiohttp request object.
        request_type: dataclass type to cast request to.

    Returns:
        Parsed request object or Response object with status 400 and stacktrace.
    r   NzGot invalid request type: )textstatus)aiohttpr1   jsonr   	ExceptionrH   infor   	traceback
format_excwebHTTPBadRequeststatus_code)rV   rW   r[   	json_dataes        r$   parse_and_validate_requestrf   x   s      " NNN*+;+;+;+;+;+;<<I
$Y=== 
 
 
444555%'';-9
 
 
 	
 	
 	
 	
 	
 	

s   ? 
B!	ABB!B!job_or_submission_idr   c                 b  K   |                      |dd|           d{V }t          |                                d           }i }i }|D ]_}|j        j                            t                    r(|j                                        }t          |j        j
                  }	|	                    t                    }
|
st          ||j        j        t!          |j                            }t%          |t&          j        |j        rt,          j        nt,          j        |j        |j        |j        |	t9          j        |j        j        j                                                   |	  	        }|||<   ,t          ||j        j        t!          |j                            }|||
<   a||fS )a  Returns a tuple of dictionaries related to drivers.

    The first dictionary contains all driver jobs and is keyed by the job's id.
    The second dictionary contains drivers that belong to submission jobs.
    It's keyed by the submission job's submission id.
    Only the last driver of a submission job is returned.

    An optional job_or_submission_id filter can be provided to only return
    jobs with the job id or submission id.
    T)rg   skip_submission_job_info_fieldskip_is_running_tasks_fieldr   Nc                 4    | j                                         S r*   )job_idhex)job_table_entrys    r$   <lambda>z!get_driver_jobs.<locals>.<lambda>   s    8N8R8R8T8T r&   )key)idnode_ip_addresspid)	rl   rE   rZ   
entrypoint
start_timeend_timemetadataruntime_envdriver_info)!async_get_all_job_infosortedvaluesconfigray_namespace
startswithr   rl   rm   dictrw   getr   r   driver_address
ip_addressrC   
driver_pidr   r   DRIVERis_deadr   	SUCCEEDEDRUNNINGrt   ru   rv   r   deserializeruntime_env_infoserialized_runtime_envto_dict)r   rg   r   	job_infossorted_job_infosjobssubmission_job_driversrn   rl   rw   job_submission_iddriverjobs                r$   get_driver_jobsr      s      !771'+$(	 8        I  T T   D+ %? %?!/::)
 
 	  '++--.788$LL)<==  	? / > I233  F
 ^"*'y**&*5*5(1!&2#*;R '))"  C DLL / > I233  F
 9?"#455'''r&   job_info_clientc           	        K   t          |            d{V \  }}|                              }|r|S t          fd|                                D             d          }|s}|                    |           d{V }|rO|                    |          }t          di t          j        |          ||r|j        nd|t          j
        d}|S dS )zH
    Attempts to find the job with a given submission_id or job id.
    )rg   Nc              3   8   K   | ]\  }}|j         k    |V  d S r*   rq   )r,   rq   r   rg   s      r$   	<genexpr>z"find_job_by_ids.<locals>.<genexpr>   sA       	
 	
Fy000 0000	
 	
r&   submission_idrl   ry   rE   r+   )r   r   nextr0   get_infor   dataclassesasdictrq   r   
SUBMISSION)	r   r   rg   driver_jobsr   r   r   job_infor   s	     `      r$   find_job_by_idsr      s\      1@)=1 1 1 + + + + + +'K' //.
/
/C
 
	
 	
 	
 	
4::<<	
 	
 	

 	 M  - -$--m<<<<<<<<H 	'++M:: 
 
 **
' &0699D#
 
 
 
 
4r&   job_idsc                 d  K   t          |            d{V \  }fd|                                D             }fd                                D                                             }t          j        fd|D               d{V }i |fdt          ||          D             S )z
    Returns a dictionary of submission jobs with the given job ids, keyed by the job id.

    This only accepts job ids and not submission ids.
    Nc                 $    i | ]\  }}|v 	||S r+   r+   r,   rp   r   r   s      r$   r/   z(find_jobs_by_job_ids.<locals>.<dictcomp>  s$    RRRS3'>>3>>>r&   c                 .    i | ]\  }}|j         v ||S r+   r   r   s      r$   r/   z(find_jobs_by_job_ids.<locals>.<dictcomp>  s2       S#36WCTCTSCTCTCTr&   c                 :    g | ]}                     |          S r+   )r   )r,   r   r   s     r$   
<listcomp>z(find_jobs_by_job_ids.<locals>.<listcomp>  s7     

 

 

 $$]33

 

 

r&   c                     i | ]x\  }}                     |          j        t          di t          j        |          |                     |          j                             |          t
          j        d yS )r   r+   )r   rq   r   r   r   r   r   )r,   r   r   r   s      r$   r/   z(find_jobs_by_job_ids.<locals>.<dictcomp>'  s     	
 	
 	
 (- #&&}558* ; ;$X..;+-11-@@C266}EE'; ; ; ;	
 	
 	
r&   )r   r0   keysrN   gatherzip)r   r   r   r   job_submission_idsr   r   s    ``   @r$   find_jobs_by_job_idsr   
  s<      1@
0K0K*K*K*K*K*K*K'K' SRRRK,=,=,?,?RRRK   !7!=!=!?!?  
 04466n

 

 

 

!3

 

 

      I
	
 	
 	
 	
 ,/y:L+M+M	
 	
 	
 r&       	num_lines	max_chars
block_sizec           
      $   |dk     rt          d|           |dk    rdS |dk     rt          d|           |dk    rdS |dk    rt          d|           t                              d|  d| d| d	|            t          | d
          5 }|                    dt
          j                   |                                }|dk    r	 ddd           dS g }|}d}|dk    r||dz   k     r|t          ||          }	||	z  }|                    |           |	                    |	          }
||

                    d          z  }|                    d|
           |dk    r	||dz   k     |ddd           n# 1 swxY w Y   d                    |          }|                    dd                              d          }t          |          |k    rd                    |          }nd                    || d                   }|| d         S )a  Return the last ``num_lines`` lines from a large log file efficiently.

    This function avoids scanning the entire file. It seeks to the end of
    the file and reads backwards in fixed-size blocks until enough lines are
    collected. This is much faster for large files compared to using
    ``file_tail_iterator()``, which performs a full sequential scan.

    Args:
        path: The file path to read.
        num_lines: Number of lines to return.
        max_chars: Maximum number of characters in the returned string.
        block_size: Read size for each backward block.

    Returns:
        A string containing at most ``num_lines`` of the last lines in the file,
        truncated to ``max_chars`` characters.
    r   z$num_lines must be non-negative, got r?   z$max_chars must be non-negative, got z!block_size must be positive, got zStart reading log file z with num_lines=z max_chars=z block_size=rbNrA      
r&   zutf-8r9   )errorsT)keepends)
ValueErrorrH   rI   rJ   seekrF   SEEK_ENDtellminreadcountinsertjoinr"   
splitlinesr8   )r<   r   r   r   rQ   	file_sizechunkspositionnewlines_found	read_sizechunkbufferrR   results                 r$   fast_tail_last_n_linesr   4  s   . 1}}K	KKLLLA~~r1}}K	KKLLLA~~rQIZIIJJJ
LLq$qq	qqiqqeoqq   
dD		 $Q	q"+FFHH	>>	$ $ $ $ $ $ $ $  ll~	A==J11I	!HFF8FF9%%Eekk%000NMM!U### ll~	A==$ $ $ $ $ $ $ $ $ $ $ $ $ $ $* XXfFMM')M44???NNE
5zzY	z{{+,,9*++s   <E5BE55E9<E9)NN)r   )4rN   r   loggingrF   r6   r_   r   typingr   r   r   r   r   r	   r
   ray._privater   ray._rayletr   r    ray.dashboard.modules.job.commonr   r   r   r   )ray.dashboard.modules.job.pydantic_modelsr   r   r   ray.runtime_envr   r[   aiohttp.webr   r   r]   	getLogger__name__rH   MAX_CHUNK_LINE_LENGTHrK   rC   r%   r1   r;   rU   rf   intr   r   r   r   r+   r&   r$   <module>r      s         				 				     ! ! ! ! ! ! I I I I I I I I I I I I I I I I I I & & & & & & @ @ @ @ @ @ @ @            V U U U U U U U U U & & & & & &NNN---------   GGHHH 
	8	$	$  	+y 	+Xc] 	+ 	+ 	+ 	+9$sCx. 9T#s(^ 9 9 9 9
S S    6'3 6'=$s)9L+M 6' 6' 6' 6'r
	
 )

9h
 
 
 
@ +/!D( D(D("3-D( c]D( 4Z $sJ"778	D( D( D( D(N**)* * j	* * * *Z'')' #Y' 
#z/	' ' ' '\ 	B B
BB B 	B
 	B B B B B Bs   A) )A76A7