o
    `۷i?                     @   s  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 d dlmZ d dlZd dlm  mZ d dlm  mZ d dlm  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.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4 e5e6Z7ej8Z9dZ:ej;<e:dkZ=e=re7>d dd Z?G dd dZ@dS )    N)floor)List)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                  C   sz   t jt jt jtdd} t jt jt}t j| s,t	t
jd| d| t j| d}tjd|td | 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_dir r-   T/home/ubuntu/vllm_env/lib/python3.10/site-packages/ray/dashboard/http_server_head.pysetup_static_dir@   s   r/   c                   @   s  e Zd Zdededededededefdd	Zed
de	j
jfddZedde	j
jfddZedde	j
jfddZedde	j
jfddZedde	j
jfddZdd Ze	j
jdd Ze	j
jdd Ze	j
jd d! Zd"ee d#ee fd$d%Zd&d' Zd(S ))HttpServerDashboardHeadip	http_host	http_porthttp_port_retriesgcs_addresssession_namemetricsc           
   
   C   s   || _ || _|| _|| _t|d | _|| _|| _d | _zt	 }t
d| W n  tjyG }	 ztjdv r;t
|	 n|	W Y d }	~	nd }	~	ww tj|  ttjtdk ratjt d| _d S t | _d S )Nr   z"Setup static dir for dashboard: %s)win32cygwinz4.0.0)loop)r1   r2   r3   r4   r   head_node_ipr7   _session_namerunnerr/   loggerinfor$   r%   sysplatformwarningdashboard_optional_utilsDashboardHeadRouteTablebindr   r   __version__ClientSessionr
   http_session)
selfr1   r2   r3   r4   r5   r6   r7   r*   exr-   r-   r.   __init__W   s,   

z HttpServerDashboardHead.__init__/returnc              
      s|   zt tjd W n ty# } ztd|  W Y d }~nd }~w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	Exceptionr>   rB   r   webFileResponser   r   r   r   r    r!   headers)rI   reqerespr-   r-   r.   	get_index   s$   
z!HttpServerDashboardHead.get_index/favicon.icoc              	      s(   t jtjtjtjtdS )Nzclient/build/favicon.ico)	r   rR   rS   r   r   r   r   r    r!   )rI   rU   r-   r-   r.   get_favicon   s   z#HttpServerDashboardHead.get_faviconz	/timezonec              
      sf   zt  }tj|W S  ty2 } ztd|  tjjddt	| dW  Y d }~S d }~ww )NzError getting timezone:   zInternal Server Error:statustext)
timezone_utilsget_current_timezone_infor   rR   json_responserQ   r>   errorResponsestr)rI   rU   current_timezonerV   r-   r-   r.   get_timezone   s   z$HttpServerDashboardHead.get_timezone/api/authentication_modec              
      s   z!t  }t|}tjd|i}|dkr |jtjdddd |W S  t	yH } zt
d|  tjjdd	t| d
W  Y d }~S d }~ww )Nauthentication_modedisabled r   rL   )max_ager   z#Error getting authentication mode: r[   Internal Server Error: r\   )r   
auth_utilsget_authentication_mode_namer   rR   ra   
set_cookier    AUTHENTICATION_TOKEN_COOKIE_NAMErQ   r>   rb   rc   rd   )rI   rU   modemode_strresponserV   r-   r-   r.   r      s(   
z/HttpServerDashboardHead.get_authentication_mode/api/authenticatec              
      s  zbt  stjjdddW S |jtjd}|s"tjjdddW S t 	|s0tjjdddW S |}|
 tj
 rE|ttjd }tjd	d
d}|jdk}|jtj|tjddd|d |W S  ty } ztd|  tjjddt| dW  Y d}~S d}~w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 enabledr\   rj   z*Unauthorized: Missing authentication tokeni  z'Forbidden: Invalid authentication tokenNauthenticatedzToken is valid)r]   messagehttpsrL   TStrict)rk   r   httponlysamesitesecurezError during authentication: r[   rl   )rm   is_token_auth_enabledr   rR   rc   rT   getr   AUTHORIZATION_HEADER_NAMEvalidate_request_tokenlower
startswithAUTHORIZATION_BEARER_PREFIXlenra   schemero   rp   #AUTHENTICATION_TOKEN_COOKIE_MAX_AGErQ   r>   rb   rd   )rI   rU   auth_headertokenrs   	is_securerV   r-   r-   r.   authenticate   s`   


z$HttpServerDashboardHead.authenticatec                 C   s   | j r| jsJ | j | jfS N)r2   r3   rI   r-   r-   r.   get_address  s   z#HttpServerDashboardHead.get_addressc                    s   |j ds|j dr<t|j drdnd}tt|j }||kr<||jvr<td|d| t	j
 ||I d H S )Nr   z/logszRejecting request_path=z& because it is not relative to parent=)r   r   pathlibPurePosixPath	posixpathrealpathparentsr>   r?   r   rR   HTTPForbidden)rI   requesthandlerparentrequest_pathr-   r-   r.   path_clean_middleware  s   
z-HttpServerDashboardHead.path_clean_middlewarec                    sp  t  }zjz\||I d H }t|jd  d}|W W t  | }z'| jjj|j|tj	| j
dd| | jjj|j|j|tj	| j
dd  W S  tyb } ztd|  W Y d }~S d }~ww  ttjfyo   d} w t  | }z'| jjj|j|tj	| j
dd| | jjj|j|j|tj	| j
dd  W w  ty } ztd|  W Y d }~w d }~ww )Nd   xx	dashboard)endpointhttp_statusr   SessionName	Component)methodr   r   r   r   r   zError emitting api metrics: 5xx)time	monotonicr   r]   r7   metrics_request_durationlabels__name__rayrF   r<   observemetrics_request_countr   incrQ   r>   	exceptionasyncioCancelledError)rI   r   r   
start_timers   
status_tag	resp_timerV   r-   r-   r.   metrics_middleware  sp   

z*HttpServerDashboardHead.metrics_middlewarec                    s8   |j dr||I d H }d|jd< |S ||I d H S )Nr   zmax-age=31536000rO   )r   r   rT   )rI   r   r   rs   r-   r-   r.   cache_control_static_middleware=  s   
z7HttpServerDashboardHead.cache_control_static_middlewaredashboard_head_modulessubprocess_module_handlesc                    s  |D ]}t j| q|D ]}t| qh d}d}tjjtj| j	t
t||| jt jth ddgd| jgd}|jt d |jt d tjj|dd	| _| j I d H  d }td
| j D ]:}	ztj| j| j| j}
|
 I d H  W  n. ty } z|}|  jd
7  _td| j| W Y d }~qdd }~ww td| j d| |
jjd   ^| _| _}t!"| jj#r| j$n| j| _t%dt&| j| j dd |j' D }|D ]}t%| qt%dt(| d S )N>   
/-/healthz/api/healthz/api/gcs_healthz/api/local_raylet_healthzrL   rY   rt   rg   )z/static/>   GETHEADOPTIONSrt   )allowed_methodsallowed_paths)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                 S   s   g | ]
}|j tjkr|qS r-   )r   r   	METH_HEAD).0rr-   r-   r.   
<listcomp>  s    z/HttpServerDashboardHead.run.<locals>.<listcomp>zRegistered %s routes.))rC   rD   rE   r   r   rR   Applicationr   DASHBOARD_CLIENT_MAX_SIZEr   r   r   get_browser_request_middlewarer   
add_routesr(   bound_routes	AppRunnerr=   setupranger4   TCPSiter2   r3   startOSErrorr>   rB   rQ   _serversocketsgetsockname	ipaddress
ip_addressis_unspecifiedr1   r?   r   routerr   )rI   r   r   mhpublic_exact_pathspublic_path_prefixesapplast_exisiterV   _dump_routesr   r-   r-   r.   runE  sz   
zHttpServerDashboardHead.runc                    s   | j  I d H  d S r   )r=   cleanupr   r-   r-   r.   r     s   zHttpServerDashboardHead.cleanupN)r   
__module____qualname__rd   intr   rK   r(   r}   r   rR   rS   rX   rZ   rc   rf   r   postr   r   
middlewarer   r   r   r   r   r   r   r   r-   r-   r-   r.   r0   V   sN    
*E



Vr0   )Ar   r&   r   loggingr   r   r   r@   r   mathr   typingr   packaging.versionr   r   ray.dashboard.optional_utilsr   optional_utilsrC   ray.dashboard.timezone_utilsr_   ray.dashboard.utilsutilsr$   r   ray._common.network_utilsr   r   ray._common.usage.usage_libr   r	   ray._common.utilsr
   ray._private.authenticationr   r   rm   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   r>   rD   r(   ENV_VAR_FOLLOW_SYMLINKSenvironr}   r)   rB   r/   r0   r-   r-   r-   r.   <module>   sL    
