
    &`i6                     n   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	 d dl
Z
d dlmc mc mc mZ d dlmc mc mc mZ d dlmc mZ d dlmc mZ d dlmZ d dlmZmZ  ej        e          Zej         Z!dZ"dZ# edd	
          Z$	 d dej%        de&de'de'fdZ(dej%        de'fdZ)dej%        de'de'de'fdZ*e"fdej%        de'de'de'de'f
dZ+dde"fde
j,        j-        dej%        de'de'de'de'fdZ. G d dej/                  Z0ej1        2                    e$          Z3 G d dej/                  Z4dS )!    N)Path)Optional)env_integer)reporter_pb2reporter_pb2_grpci      2RAY_DASHBOARD_LOG_TASK_LOG_SEARCH_MAX_WORKER_COUNT   )defaultfilecontentstart_offsetreturnc                 .   t                               d| d           |                     |t          j                   |}	 |                     t                    }|dk    rdS |                    |          }|dk    r||z   S |t          |          z  }U)a  Find the offset of the first occurrence of content in a file.

    Args:
        file: File object
        content: Content to find
        start_offset: Start offset to read from, inclusive.

    Returns:
        Offset of the first occurrence of content in a file.
    zFinding offset of content z in fileT    )	loggerdebugseekioSEEK_SETread
BLOCK_SIZEfindlen)r   r   r   offset
block_datablock_offsets         w/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/dashboard/modules/log/log_agent.pyfind_offset_of_content_in_filer        s     LL?g???@@@IIlBK(((F"YYz**
2!w//2L((#j//!"r   c                     |                                  }|                     dt          j                   |                                  }|                     |t          j                   |S )z
    Find the offset of the end of a file without changing the file pointer.

    Args:
        file: File object

    Returns:
        Offset of the end of a file.
    r   )tellr   r   SEEK_ENDr   )r   old_posends      r   find_end_offset_filer&   ?   sO     iikkGIIa
))++CIIgr{###Jr   nc                 6   |                      |           d}t          |          D ].}|                                 }|s n|                                 }/t                              d| d| d           ||n|                      dt          j                  S )a  
    Find the offsets of next n lines from a start offset.

    Args:
        file: File object
        start_offset: Start offset to read from, inclusive.
        n: Number of lines to find.

    Returns:
        Offset of the end of the next n line (exclusive)
    NzFound next  lines from  offsetr   )r   rangereadliner"   r   r   r   r#   )r   r   r'   
end_offset_lines         r   (find_end_offset_next_n_lines_from_offsetr0   P   s     	IIlJ1XX ! !}} 	EYY[[


LLCqCClCCCDDD ,

$))Ar{2K2Kr   r   
block_sizec                    t                               d| d| d           |dk    r!|                     dt          j                  }n |                     |t          j                   |dk    r|S d}|                     t          d|dz
            t          j                   |                     d          dk    r|dz  }|}t          d||z
            }|}|dk    r|dk    r|                     |d           |                     t          |||z
                      }|
                    d          }	|	|k    r2|                    d|	|z
            }
|t          |
d                   z  }n?||	z  }|t          |          z  }|dk    rn!|}t          d||z
            }|dk    r|dk    ||z
  }|dk    sJ d| d	            |S )
a  
    Find the offset of the beginning of the line of the last X lines from an offset.

    Args:
        file: File object
        offset: Start offset from which to find last X lines, -1 means end of file.
            The offset is exclusive, i.e. data at the offset is not included
            in the result.
        n: Number of lines to find
        block_size: Block size to read from file

    Returns:
        Offset of the beginning of the line of the last X lines from a start offset.
    zFinding last r)   r*   r   r   r      
zRead start offset(z) should be non-negative)r   r   r   r   r#   r   maxosr   mincountsplitr   )r   r   r'   r1   nbytes_from_end
lines_moreread_offsetprev_offsetr   	num_lineslinesoffset_read_starts               r   *find_start_offset_last_n_lines_from_offsetr@   l   s   " LL??????@@@||1bk**		&"+&&&Avv	 
 	IIc!VaZ  "+...yy||u	Q Ja*,--KK
//kQ..		+q!!!YYs:{[/HIIJJ
$$U++	z!! $$UI
,BCCEs59~~-O 	i
3z??*!!![:5665 //kQ..8 0QG-GGG 	r   r   contextr-   keep_alive_interval_secc                ^  K   d|j         v s
J d            |dk    r|dk    r
J d            |                    |d           |}|                                 s|dk    rt          ||z
  |          }n|}|                    |          }|dk    r#|dk    rt          j        |           d{V  ldS t                              dt          |           d	|            t          j        |
          W V  |t          |          z  }|dk    r||k    rdS |                                 dS dS )a}  Streaming log in chunk from start to end offset.

    Stream binary file content in chunks from start offset to an end
    offset if provided, else to the end of the file.

    Args:
        context: gRPC server side context
        file: Binary file to stream
        start_offset: File offset where streaming starts
        end_offset: If -1, implying streaming til the EOF.
        keep_alive_interval_sec: Duration for which streaming will be
            retried when reaching the file end, -1 means no retry.
        block_size: Number of bytes per chunk, exposed for testing

    Return:
        Async generator of StreamReply
    bzOnly binary file is supported.r   r   z7Keep-alive is not allowed when specifying an end offsetr   NzSending z
 bytes at )data)moder   doner6   r   asynciosleepr   r   r   r   StreamLogReply)	rA   r   r   r-   rB   r1   
cur_offsetto_readbytess	            r   _stream_log_in_chunkrN      s     2 $)=1$$r)9)9)9@ *:)9 	IIlAJ llnn *z1:>>GG G		'""C<<&!++m$;<<<<<<<<< EBE

BBjBBCCC)u5555555 	c%jj 

j 8 8E1 llnn     r   c                   :     e Zd Z fdZd Zed             Z xZS )LogAgentc                     t                                          |           t          j                     t                              d| j        j        d           d S )Nz/logsT)
show_index)super__init__	log_utilsregister_mimetypesroutesstatic_dashboard_agentlog_dirselfdashboard_agent	__class__s     r   rT   zLogAgent.__init__   sN    )))$&&&gt4<NNNNNr   c                 
   K   d S N r\   servers     r   runzLogAgent.run   s      r   c                      dS NFra   ra   r   r   is_minimal_modulezLogAgent.is_minimal_module   s    ur   )__name__
__module____qualname__rT   rd   staticmethodrg   __classcell__r^   s   @r   rP   rP      sg        O O O O O
     \    r   rP   )max_workersc                        e Zd Z fdZd Zedee         fd            Ze	d             Z
d Zedededefd	            Zd
 Z xZS )LogAgentV1Grpcc                 J    t                                          |           d S r`   )rS   rT   r[   s     r   rT   zLogAgentV1Grpc.__init__  s!    )))))r   c                 <   K   |rt          j        | |           d S d S r`   )r    add_LogServiceServicer_to_serverrb   s     r   rd   zLogAgentV1Grpc.run  s4       	M>tVLLLLL	M 	Mr   r   c                 4    | j                                         S r`   )rY   get_node_id)r\   s    r   node_idzLogAgentV1Grpc.node_id  s    $00222r   c                      dS rf   ra   ra   r   r   rg   z LogAgentV1Grpc.is_minimal_module  s	     ur   c                   K   t          | j        j                  }|                                st	          d| j        j         d          g }|                    |j                  D ]P}|                    t          |	                    |                    |
                                rdndz              Qt          j        |          S )z
        Lists all files in the active Ray logs directory.

        Part of `LogService` gRPC.

        NOTE: These RPCs are used by state_head.py, not log_head.py
        z Could not find log dir at path: z7It is unexpected. Please report an issue to Ray Github./ )	log_files)r   rY   rZ   existsFileNotFoundErrorglobglob_filterappendstrrelative_tois_dirr   ListLogsReply)r\   requestrA   pathr{   ps         r   ListLogszLogAgentV1Grpc.ListLogs  s       D)122{{}} 	#J43H3P J J J   	7.// 	U 	UASt!4!455

9RPRSTTTT)I>>>>r   root_log_dirfilenamec                    t          |                                          s||z  }nt          |          }t          t          j                            |                    }|                                st          d|           	 |                    |           n)# t          $ r}t          | d| d|           d}~ww xY w|	                                S )au  
        Resolves the file path relative to the root log directory.

        Args:
            root_log_dir: Root log directory.
            filename: File path relative to the root log directory.

        Raises:
            FileNotFoundError: If the file path is invalid.

        Returns:
            The absolute file path resolved from the root log directory.
        zA file is not found at: z not in z: N)
r   is_absoluter5   r   abspathis_filer}   r   
ValueErrorresolve)clsr   r   filepathes        r   _resolve_filenamez LogAgentV1Grpc._resolve_filename+  s     H~~))++ 	&#h.HHH~~H
 1122!! 	K#$Ix$I$IJJJ	N  .... 	N 	N 	N#x$L$L$L$L$L$LMMM	N !!!s   
B   
C*CCc                b  K   |j         r|j         nd}	 |                     t          | j        j                  |j                  }t          |d          5 }|                    g            d{V  |                    d          r|j	        nd}|                    d          r|j
        nt          |          }|dk    r t          t          |||          |          }d}|j        r|j        r|j        nt           }d}t"                              d	| d
| d| d|            t'          |||||          2 3 d{V }	|	W V  6 	 ddd           dS # 1 swxY w Y   dS # t(          $ r@}
|                    t*          j        t/          |
          gg           d{V  Y d}
~
dS d}
~
ww xY w)af  
        Streams the log in real time starting from `request.lines` number of lines from
        the end of the file if `request.keep_alive == True`. Else, it terminates the
        stream once there are no more bytes to read from the log file.

        Part of `LogService` gRPC.

        NOTE: These RPCs are used by state_head.py, not log_head.py
        i  rbNr   r   r-   r   )r   r'   zTailing logs from z to z for lines=z, with keep_alive=)rA   r   r   r-   rB   )r>   r   r   rY   rZ   log_file_nameopensend_initial_metadataHasFieldr   r-   r&   r4   r@   
keep_aliveintervalDEFAULT_KEEP_ALIVE_INTERVAL_SECr   inforN   r}   
log_constsLOG_GRPC_ERRORr   )r\   r   rA   r>   r   fr   r-   rB   	chunk_resr   s              r   	StreamLogzLogAgentV1Grpc.StreamLogO  s      ")8D7	$--T*233W5J H h%% 0$33B777777777 -4,<,<^,L,LSG((RS 
 ''551G&&-a00  B;; $'BjE   %	$ $L +-'% $ #+=((< , "$JP P P: P P"P P6MP P   (<#!-),C( ( ( $ $ $ $ $ $ $) $OOOOO( (S0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ 0$ ! 	W 	W 	W//*2KSQRVV1T0UVVVVVVVVVVVVVVV	Ws6   2E$ C%E;EEEE$
F..5F))F.)rh   ri   rj   rT   rd   propertyr   r   rv   rk   rg   r   classmethodr   r   r   rl   rm   s   @r   rp   rp     s        * * * * *M M M 3# 3 3 3 X3   \? ? ?& !"T !"S !"T !" !" !" [!"FE$ E$ E$ E$ E$ E$ E$r   rp   )r   )5rH   concurrent.futures
concurrentr   loggingr5   pathlibr   typingr   grpc$ray.dashboard.modules.log.log_consts	dashboardmoduleslogr   #ray.dashboard.modules.log.log_utilsrU   ray.dashboard.optional_utilsoptional_utilsdashboard_optional_utilsray.dashboard.utilsutilsdashboard_utilsray._private.ray_constantsr   ray.core.generatedr   r   	getLoggerrh   r   DashboardAgentRouteTablerW   r   r   r	   BufferedIOBaserM   intr    r&   r0   r@   aioServicerContextrN   DashboardAgentModulerP   futuresThreadPoolExecutor_task_log_search_worker_poolrp   ra   r   r   <module>r      sM        				  				              9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 ? ? ? ? ? ? ? ? ? - - - - - - - - - 2 2 2 2 2 2 > > > > > > > >		8	$	$	!	: 
 #$ 5@[8!6 6 6 2 BC" "

"&+";>"" " " ">r0 S    "

+.36   : EOH H

H%(H-0H>AHH H H H^ #% : :X%:

: : 	:
 !: : : : :z    3     *1DDB  E     
M$ M$ M$ M$ M$_9 M$ M$ M$ M$ M$r   