o
    $iD                     @   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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/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5 e6e7Z8ej9Z:dZ;ej<=e;dkZ>e>re8?d dd Z@G d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                  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.   [/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/dashboard/http_server_head.pysetup_static_dir@   s   r0   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dee f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)r2   r3   r4   r5   r   head_node_ipr8   _session_namerunnerr0   loggerinfor%   r&   sysplatformwarningdashboard_optional_utilsDashboardHeadRouteTablebindr   r   __version__ClientSessionr   http_session)
selfr2   r3   r4   r5   r6   r7   r8   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?   rC   r   webFileResponser   r   r   r    r!   r"   headers)rJ   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   rS   rT   r   r   r   r    r!   r"   )rJ   rV   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   rS   json_responserR   r?   errorResponsestr)rJ   rV   current_timezonerW   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   rM   )max_ager   z#Error getting authentication mode: r\   Internal Server Error: r]   )r   
auth_utilsget_authentication_mode_namer   rS   rb   
set_cookier    AUTHENTICATION_TOKEN_COOKIE_NAMErR   r?   rc   rd   re   )rJ   rV   modemode_strresponserW   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]   rk   z*Unauthorized: Missing authentication tokeni  z'Forbidden: Invalid authentication tokenNauthenticatedzToken is valid)r^   messagehttpsrM   TStrict)rl   r   httponlysamesitesecurezError during authentication: r\   rm   )rn   is_token_auth_enabledr   rS   rd   rU   getr   AUTHORIZATION_HEADER_NAMEvalidate_request_tokenlower
startswithAUTHORIZATION_BEARER_PREFIXlenrb   schemerp   rq   #AUTHENTICATION_TOKEN_COOKIE_MAX_AGErR   r?   rc   re   )rJ   rV   auth_headertokenrt   	is_securerW   r.   r.   r/   authenticate   s`   


z$HttpServerDashboardHead.authenticatec                 C   s   | j r| jsJ | j | jfS N)r3   r4   rJ   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   rS   HTTPForbidden)rJ   requesthandlerparentrequest_pathr.   r.   r/   path_clean_middleware  s   
z-HttpServerDashboardHead.path_clean_middlewarewhitelisted_pathsc                    s   t jj fd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                    sT   | j  v r|| I d H S t| r#| jtjtjfv r#tjj	dddS || I d H S )Ni  z'Method Not Allowed for browser traffic.r]   )
r   rD   is_browser_requestmethodr   	METH_POSTMETH_PUTr   rS   rd   )r   r   r   r.   r/   browsers_no_post_put_middleware(  s   
zdHttpServerDashboardHead.get_browsers_no_post_put_middleware.<locals>.browsers_no_post_put_middleware)r   rS   
middleware)rJ   r   r   r.   r   r/   #get_browsers_no_post_put_middleware  s   z;HttpServerDashboardHead.get_browsers_no_post_put_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)r   r   r   r   r   r   zError emitting api metrics: 5xx)time	monotonicr   r^   r8   metrics_request_durationlabels__name__rayrG   r=   observemetrics_request_countr   incrR   r?   	exceptionasyncioCancelledError)rJ   r   r   
start_timert   
status_tag	resp_timerW   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=31536000rP   )r   r   rU   )rJ   r   r   rt   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}dh}tjjtj| j	t
t||| j| || 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 }~qad }~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_healthzrM   rZ   ru   rh   )z/static/ru   )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.))rD   rE   rF   r   r   rS   Applicationr   DASHBOARD_CLIENT_MAX_SIZEr   r   r   r   r   
add_routesr)   bound_routes	AppRunnerr>   setupranger5   TCPSiter3   r4   startOSErrorr?   rC   rR   _serversocketsgetsockname	ipaddress
ip_addressis_unspecifiedr2   r@   r   routerr   )rJ   r   r   mhpublic_exact_pathspublic_path_prefixesbrowser_post_put_allowed_pathsapplast_exisiterW   _dump_routesr   r.   r.   r/   rund  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__re   intr   rL   r)   r~   r   rS   rT   rY   r[   rd   rg   r   postr   r   r   r   r   r   r   r   r   r   r   r   r   r.   r.   r.   r/   r1   V   sP    
*E



Yr1   )Br   r'   r   loggingr   r   r   rA   r   mathr   typingr   r   packaging.versionr   r   ray.dashboard.optional_utilsr   optional_utilsrD   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   rn   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?   rE   r)   ENV_VAR_FOLLOW_SYMLINKSenvironr~   r*   rC   r0   r1   r.   r.   r.   r/   <module>   sL    
