
    &`iD                        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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Zd dl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 d dlmZm Z  d dl!m"Z" d d	l#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/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5  ej6        e7          Z8ej9        Z:dZ;ej<        =                    e;          dk    Z>e>re8?                    d           d Z@ G d d          ZAdS )    N)floor)ListSet)Version)ray_constants)build_addressparse_address)TagKeyrecord_extra_usage_tag)get_or_create_event_loop)authentication_constantsauthentication_utils)get_token_auth_middleware)get_authentication_mode)DashboardPrometheusMetrics)DashboardHeadModule)aiohttphdrs)SubprocessModuleHandle)SubprocessRouteTable#RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS1zEnabling RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS is not recommended as it allows symlinks to directories outside the dashboard build folder. You may accidentally expose files on your system outside of the build directory.c                  R   t           j                            t           j                            t           j                            t
                              dd          } t           j                            t           j                            t
                              }t           j                            |           s$t          j	        t          j        d| d|           t           j                            | d          }t                              d|t                     | S )NclientbuildzDashboard build directory not found. If installing from source, please follow the additional steps required to build the dashboard(cd python/ray/z#/client && npm ci && npm run build)static/static)follow_symlinks)ospathjoindirnameabspath__file__basenameisdirdashboard_utilsFrontendNotFoundErrorerrnoENOENTroutesr   FOLLOW_SYMLINKS_ENABLED)	build_dirmodule_name
static_dirs      r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/dashboard/http_server_head.pysetup_static_dirr1   @   s    
1122Hg I '""27??8#<#<==K7==## 

3L  *      	
 	
 		
 i22J
MM)Z9PMQQQ    c                      e Zd ZdededededededefdZe                    d	          d
e	j
        j        fd            Ze                    d          d
e	j
        j        fd            Ze                    d          d
e	j
        j        fd            Ze                    d          d
e	j
        j        fd            Ze                    d          d
e	j
        j        fd            Zd Ze	j
        j        d             Zdee         fdZe	j
        j        d             Ze	j
        j        d             Zdee         dee         fdZd ZdS )HttpServerDashboardHeadip	http_host	http_porthttp_port_retriesgcs_addresssession_namemetricsc                    || _         || _        || _        || _        t	          |          d         | _        || _        || _        d | _        	 t                      }t                              d|           nG# t          j        $ r5}	t          j        dv rt                              |	           n|	Y d }	~	nd }	~	ww xY wt"          j                            |            t)          t*          j                  t)          d          k     r(t+          j        t1                                | _        d S t+          j                    | _        d S )Nr   z"Setup static dir for dashboard: %s)win32cygwinz4.0.0)loop)r5   r6   r7   r8   r	   head_node_ipr;   _session_namerunnerr1   loggerinfor'   r(   sysplatformwarningdashboard_optional_utilsDashboardHeadRouteTablebindr   r   __version__ClientSessionr   http_session)
selfr5   r6   r7   r8   r9   r:   r;   r-   exs
             r0   __init__z HttpServerDashboardHead.__init__W   sF    ""!2)+66q9) 
	(**IKK<iHHHH4 	 	 	 |222r"""" #""""	 	!8==dCCC 7&''''*:*::: ' 5;S;U;U V V VD ' 5 7 7Ds   )A7 7B;+B66B;/returnc           	        K   	 t          t          j        d           n4# t          $ r'}t                              d|            Y d }~nd }~ww xY wt          j                            t          j
                            t          j
                            t          j
                            t                              d                    }d|j        d<   |S )NTruez`Failed to record the dashboard usage. This error message is harmless and can be ignored. Error: zclient/build/index.htmlzno-storeCache-Control)r   r
   DASHBOARD_USED	ExceptionrC   rG   r   webFileResponser   r    r!   r"   r#   r$   headers)rN   reqeresps       r0   	get_indexz!HttpServerDashboardHead.get_index   s      
	 #6#8&AAAA 	 	 	NN        	 {''GLL 9 9::<U 
 

 )3_%s    
AAA/favicon.icoc           	         K   t           j                            t          j                            t          j                            t          j                            t                              d                    S )Nzclient/build/favicon.ico)	r   rX   rY   r   r    r!   r"   r#   r$   )rN   r[   s     r0   get_faviconz#HttpServerDashboardHead.get_favicon   sU      {''GLL 9 9::<V 
 
 	
r2   z	/timezonec                 6  K   	 t          j                    }t          j                            |          S # t
          $ rX}t                              d|            t          j                            ddt          |          z             cY d }~S d }~ww xY w)NzError getting timezone:   zInternal Server Error:statustext)
timezone_utilsget_current_timezone_infor   rX   json_responserW   rC   errorResponsestr)rN   r[   current_timezoner\   s       r0   get_timezonez$HttpServerDashboardHead.get_timezone   s      	-GII;,,-=>>> 	 	 	LL7A77888;''!9CFF!B (        	s   16 
B ABBB/api/authentication_modec                   K   	 t                      }t          j        |          }t          j                            d|i          }|dk    r#|                    t          j        ddd           |S # t          $ rX}t                              d|            t          j                            dd	t          |          z   
          cY d }~S d }~ww xY w)Nauthentication_modedisabled r   rQ   )max_ager    z#Error getting authentication mode: rc   Internal Server Error: rd   )r   
auth_utilsget_authentication_mode_namer   rX   ri   
set_cookier    AUTHENTICATION_TOKEN_COOKIE_NAMErW   rC   rj   rk   rl   )rN   r[   modemode_strresponser\   s         r0   r   z/HttpServerDashboardHead.get_authentication_mode   s     	*,,D!>tDDH{002G1RSSH :%%##,M	 $    O 	 	 	LLBqBBCCC;''!:SVV!C (        	s   A-A2 2
C<AC	CC/api/authenticatec           	        K   	 t          j                    s!t          j                            dd          S |j                            t          j        d          }|s!t          j                            dd          S t          j	        |          s!t          j                            dd          S |}|
                                                    t          j        
                                          r!|t          t          j                  d         }t          j                            d	d
d          }|j        dk    }|                    t          j        |t          j        ddd|           |S # t&          $ rX}t(                              d|            t          j                            ddt-          |          z             cY d}~S d}~ww xY w)a  
        Authenticate a user by validating their token and setting a secure HttpOnly cookie.

        This endpoint accepts a token via the Authorization header, validates it,
        and if valid, sets an HttpOnly cookie for subsequent requests from the web dashboard.
        i  z1Unauthorized: Token authentication is not enabledrd   rs   z*Unauthorized: Missing authentication tokeni  z'Forbidden: Invalid authentication tokenNauthenticatedzToken is valid)re   messagehttpsrQ   TStrict)rt   r    httponlysamesitesecurezError during authentication: rc   ru   )rv   is_token_auth_enabledr   rX   rk   rZ   getr   AUTHORIZATION_HEADER_NAMEvalidate_request_tokenlower
startswithAUTHORIZATION_BEARER_PREFIXlenri   schemerx   ry   #AUTHENTICATION_TOKEN_COOKIE_MAX_AGErW   rC   rj   rl   )rN   r[   auth_headertokenr|   	is_securer\   s          r0   authenticatez$HttpServerDashboardHead.authenticate   s     <	355 {++L ,    +//(BB K  {++E ,    4[AA {++B ,     E  ""--(DJJLL   $0LMMOO
 {00*7GHH H 
g-I(I0T!       O 	 	 	LL<<<===;''!:SVV!C (        	s1   3E: AE:  4E: 5CE: :
GAGGGc                 >    | j         r| j        sJ | j         | j        fS N)r6   r7   rN   s    r0   get_addressz#HttpServerDashboardHead.get_address  s&    ~0$.000~t~--r2   c                   K   |j                             d          s|j                             d          rt          j        |j                             d          rdnd          }t          j        t	          j        |j                             }||k    rG||j        vr>t                              d|d|           t          j
                                         ||           d {V S )Nr   z/logszRejecting request_path=z& because it is not relative to parent=)r    r   pathlibPurePosixPath	posixpathrealpathparentsrC   rD   r   rX   HTTPForbidden)rN   requesthandlerparentrequest_paths        r0   path_clean_middlewarez-HttpServerDashboardHead.path_clean_middleware  s      <""9-- 	21H1H1Q1Q 	2*"<227;;J F #01CGL1Q1QRRLv%%&8L*L*LXXXvXX   k//111WW%%%%%%%%%r2   whitelisted_pathsc                 @    t           j        j        fd            }|S )a-  Create middleware that blocks POST/PUT requests from browsers.

        Args:
            whitelisted_paths: Set of paths that are allowed to accept POST/PUT
                              from browsers (e.g., {"/api/authenticate"})

        Returns:
            An aiohttp middleware function
        c                   K   | j         v r ||            d {V S t          j        |           r@| j        t          j        t          j        fv r!t          j        	                    dd          S  ||            d {V S )Ni  z'Method Not Allowed for browser traffic.rd   )
r    rH   is_browser_requestmethodr   	METH_POSTMETH_PUTr   rX   rk   )r   r   r   s     r0   browsers_no_post_put_middlewarezdHttpServerDashboardHead.get_browsers_no_post_put_middleware.<locals>.browsers_no_post_put_middleware(  s       |000$WW---------
 );GDD Nt~t}&EEE{++%N ,    !)))))))))r2   )r   rX   
middleware)rN   r   r   s    ` r0   #get_browsers_no_post_put_middlewarez;HttpServerDashboardHead.get_browsers_no_post_put_middleware  s6     
		* 	* 	* 	* 
 		*" /.r2   c           
      d  K   t          j                    }	  ||           d {V }t          |j        dz             d}|t          j                    |z
  }	 | j        j                            |j        |t          j	        | j
        d                              |           | j        j                            |j        |j        |t          j	        | j
        d                                           S # t          $ r'}t                               d|            Y d }~S d }~ww xY w# t          t$          j        f$ r d} w xY w# t          j                    |z
  }	 | j        j                            |j        |t          j	        | j
        d                              |           | j        j                            |j        |j        |t          j	        | j
        d                                           w # t          $ r'}t                               d|            Y d }~w d }~ww xY wxY w)Nd   xx	dashboard)endpointhttp_statusr   SessionName	Component)r   r   r   r   r   r   zError emitting api metrics: 5xx)time	monotonicr   re   r;   metrics_request_durationlabels__name__rayrK   rA   observemetrics_request_countr   incrW   rC   	exceptionasyncioCancelledError)rN   r   r   
start_timer|   
status_tag	resp_timer\   s           r0   metrics_middlewarez*HttpServerDashboardHead.metrics_middleware<  sy     ^%%
	E$WW--------H!(/C"788<<<J
 ((:5IE5<<$- *O $ 2) =   ')$$$299">$- *O $ 2) :   #%%%% E E E  !C!C!CDDDDDDDDE+ 712 	 	 	J	 ((:5IE5<<$- *O $ 2) =   ')$$$299">$- *O $ 2) :   #%%%% E E E  !C!C!CDDDDDDDDEs[   ,D* BC66
D' D""D'*EE H/BG;:H/;
H,H'"H/'H,,H/c                    K   |j                             d          r ||           d {V }d|j        d<   |S  ||           d {V S )Nr   zmax-age=31536000rU   )r    r   rZ   )rN   r   r   r|   s       r0   cache_control_static_middlewarez7HttpServerDashboardHead.cache_control_static_middleware\  ss      <""9-- 	$WW--------H0BH_-OWW%%%%%%%%%r2   dashboard_head_modulessubprocess_module_handlesc           	      *  K   |D ]!}t           j                            |           "|D ]}t          j        |           h d}d}dh}t          j                            t          j        | j	        t          t          ||          | j        |                     |          | j        g          }|                    t                                                     |                    t          j                               t          j                            |d          | _        | j                                         d {V  d }	t)          d| j        z             D ]}
	 t          j                            | j        | j        | j                  }|                                 d {V   nd# t4          $ r=}|}	| xj        dz  c_        t6                              d	| j        |           Y d }~d }~ww xY wt;          d
| j         d|	           |j        j        d                                          ^| _        | _        }tC          j"        | j                  j#        r| j$        n| j        | _        t6          %                    dtM          | j        | j                             d |j'                                        D             }|D ]}t6          %                    |           t6          %                    dtQ          |                     d S )N>   
/-/healthz/api/healthz/api/gcs_healthz/api/local_raylet_healthzrQ   r_   r}   ro   )z/static/r}   )client_max_sizemiddlewares)r+   z;%a %t '%r' %s %b bytes %D us '%{Referer}i' '%{User-Agent}i')access_log_format   zTry to use port %s: %sz0Failed to find a valid port for dashboard after z
 retries: r   zDashboard head http address: %sc                 <    g | ]}|j         t          j        k    |S  )r   r   	METH_HEAD).0rs     r0   
<listcomp>z/HttpServerDashboardHead.run.<locals>.<listcomp>  s&    TTTQT^9S9Sq9S9S9Sr2   zRegistered %s routes.))rH   rI   rJ   r   r   rX   Applicationr   DASHBOARD_CLIENT_MAX_SIZEr   r   r   r   r   
add_routesr+   bound_routes	AppRunnerrB   setupranger8   TCPSiter6   r7   startOSErrorrC   rG   rW   _serversocketsgetsockname	ipaddress
ip_addressis_unspecifiedr5   rD   r   routerr   )rN   r   r   mhpublic_exact_pathspublic_path_prefixesbrowser_post_put_allowed_pathsapplast_exisiter\   _dump_routesr   s                   r0   runzHttpServerDashboardHead.rund  s_      ( 	E 	EA$<AA!DDDD* 	) 	)A %a((((	
 	
 	
  -  *
& k%%)C')/1E  *882  4
 & 
 
 	f11334442?AABBBk++M , 
 
 k!!!!!!!!!q41122 	 	AL{**4;WWjjll""""""" L L L!#7KKKKKKKKL
 ?)? ?5<? ?   .2\-A!-D-P-P-R-R* #DN33B DGG 	
 	-$.$.99	
 	
 	

 UT#*"3"3"5"5TTT 	 	AKKNNNN+S-=-=>>>>>s   $A
F00
G7:3G22G7c                 H   K   | j                                          d {V  d S r   )rB   cleanupr   s    r0   r   zHttpServerDashboardHead.cleanup  s2      k!!###########r2   N)r   
__module____qualname__rl   intr   rP   r+   r   r   rX   rY   r^   ra   rk   rn   r   postr   r   r   r   r   r   r   r   r   r   r   r   r   r   r2   r0   r4   r4   V   sk       (8(8 (8 	(8
 (8 (8 (8 ,(8 (8 (8 (8T ZZ__gk&>    _( ZZ
(@ 
 
 
  
 ZZ	)= 	 	 	 	 ZZ*++GK4H    ,+. [[$%%C)= C C C &%CJ. . . [& & & /SX / / / /> [E E E> [& & &W? $%8 9W? $((>#?W? W? W? W?r$ $ $ $ $r2   r4   )Br   r)   r   loggingr   r   r   rE   r   mathr   typingr   r   packaging.versionr   r   ray.dashboard.optional_utilsr   optional_utilsrH   ray.dashboard.timezone_utilsrg   ray.dashboard.utilsutilsr'   r   ray._common.network_utilsr   r	   ray._common.usage.usage_libr
   r   ray._common.utilsr   ray._private.authenticationr   r   rv   5ray._private.authentication.http_token_authenticationr   ray._rayletr   ray.dashboard.dashboard_metricsr   ray.dashboard.headr   ray.dashboard.optional_depsr   r   !ray.dashboard.subprocesses.handler   !ray.dashboard.subprocesses.routesr   	getLoggerr   rC   rI   r+   ENV_VAR_FOLLOW_SYMLINKSenvironr   r,   rG   r1   r4   r   r2   r0   <module>r     s          				      



                % % % % % % 



 ? ? ? ? ? ? ? ? ? 5 5 5 5 5 5 5 5 5 - - - - - - - - -       B B B B B B B B F F F F F F F F 6 6 6 6 6 6             0 / / / / / F F F F F F 2 2 2 2 2 2
 6 5 5 5 5 5 5 5 D D D D D D B B B B B B
 
	8	$	$	!	9 @ *..)@AASH  
NN	    ,i$ i$ i$ i$ i$ i$ i$ i$ i$ i$r2   