B
    ‹æ@\¼S  ã               @   s  d Z ddlmZmZmZmZ ddlZe e¡Z	ddl
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 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 ddlmZ ddlm Z m!Z! ddl"m#Z# ddl$m%Z% dZ&dZ'dZ(dZ)dZ*dZ+dZ,G dd„ deƒZ-dS )z1 Provides the Bokeh Server Tornado application.

é    )Úabsolute_importÚdivisionÚprint_functionÚunicode_literalsN)Úpformat)Úgen)ÚPeriodicCallback)ÚApplication)ÚStaticFileHandleré   )Ú	Resources)Úsettings)Úimport_optionalé   )ÚApplicationContext)ÚServerConnection)Úper_app_patternsÚtoplevel_patterns)ÚRootHandler)ÚStaticHandlerihB  iˆ  i˜:  i  @)ÚBokehTornadoc                   s  e Zd ZdZddde ¡ e ¡ deee	e
eddef‡ fdd„	Zdd„ Zedd	„ ƒZed
d„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZd,dd„Zdd„ Zd-dd„Zdd„ Zdd„ Zd d!„ Zd"d#„ Zejd$d%„ ƒZd&d'„ Z d(d)„ Z!d*d+„ Z"‡  Z#S ).r   am   A Tornado Application used to implement the Bokeh Server.

    Args:
        applications (dict[str,Application] or Application) :
            A map from paths to ``Application`` instances.

            If the value is a single Application, then the following mapping
            is generated:

            .. code-block:: python

                applications = { '/' : applications }

            When a connection comes in to a given path, the associate
            Application is used to generate a new document for the session.

        prefix (str, optional) :
            A URL prefix to use for all Bokeh server paths. (default: None)

        extra_websocket_origins (list[str], optional) :
            A list of hosts that can connect to the websocket.

            This is typically required when embedding a Bokeh server app in an
            external web site using :func:`~bokeh.embed.server_document` or
            similar.

            If None, ``["localhost"]`` will be assumed (default: None)

        extra_patterns (seq[tuple], optional) :
            A list of tuples of (str, http or websocket handler)

            Use this argument to add additional endpoints to custom deployments
            of the Bokeh Server.

            If None, then ``[]`` will be used. (default: None)

        secret_key (str, optional) :
            A secret key for signing session IDs.

            Defaults to the current value of the environment variable
            ``BOKEH_SECRET_KEY``

        sign_sessions (bool, optional) :
            Whether to cryptographically sign session IDs

            Defaults to the current value of the environment variable
            ``BOKEH_SIGN_SESSIONS``. If ``True``, then ``secret_key`` must
            also be provided (either via environment setting or passed as
            a parameter value)

        generate_session_ids (bool, optional) :
            Whether to generate a session ID if one is not provided
            (default: True)

        keep_alive_milliseconds (int, optional) :
            Number of milliseconds between keep-alive pings (default: 37000)

            Pings normally required to keep the websocket open. Set to 0 to
            disable pings.

        check_unused_sessions_milliseconds (int, optional) :
            Number of milliseconds between checking for unused sessions
            (default: 17000)

        unused_session_lifetime_milliseconds (int, optional) :
            Number of milliseconds for unused session lifetime (default: 15000)

        stats_log_frequency_milliseconds (int, optional) :
            Number of milliseconds between logging stats (default: 15000)

        mem_log_frequency_milliseconds (int, optional) :
            Number of milliseconds between logging memory information (default: 0)

            Enabling this feature requires the optional dependency ``psutil`` to be
            installed.

        use_index (bool, optional) :
            Whether to generate an index of running apps in the ``RootHandler``
            (default: True)

        redirect_root (bool, optional) :
            When there is only a single running application, whether to
            redirect requests to ``"/"`` to that application automatically
            (default: True)

            If there are multiple Bokeh applications configured, this option
            has no effect.

        websocket_max_message_size_bytes (int, optional):
            Set the Tornado ``websocket_max_message_size`` value.
            (default: 20*1024*1024)

            NOTE: This setting has effect ONLY for Tornado>=4.5

    Any additional keyword arguments are passed to ``tornado.web.Application``.
    NTc          	      s  d | _ t|tƒrd|i}|d kr$d}| d¡}|r:d| }|| _|dk rRtdƒ‚n(|dkrft d¡ n|tkrzt d|¡ || _	|	dkr’tdƒ‚n|	t
kr¦t d|	¡ |	| _|
dkr¾tdƒ‚n|
tkrÒt d	|
¡ |
| _|dkrêtd
ƒ‚n|tkrþt d|¡ || _|dk rtdƒ‚n>|dkrVtdƒd kr@t d¡ d}n|tkrVt d|¡ || _|dkrptdƒ‚n|tkrŒt d||d ¡ |d kr tƒ | _n
t|ƒ| _|| _|| _|| _t dt| jƒ¡ tƒ | _x(| ¡ D ]\}}t||d| j|< qàW |pg }g }x| ¡ D ]
\}}g }xVt D ]N}|dkrF|d }n||d  }| j| }| !||d d| j| if¡ q.W d }x&|D ]}|d  "d¡rŠ|d }qŠW |sºt#dƒ‚x|D ]}||d d< qÀW | $|¡ |j%d k	r|dkrüd}n|d }| j| }| !|t&d|j%if¡ qW xŠ|t' D ]~}|d t(krŠ|r°| j| j|dœ}| j|d  f|dd …  |f }| !|¡ n&| j|d  f|dd …  }| !|¡ q4W t d¡ x*t)|dd  *d!¡D ]}t d"| ¡ qÔW t+t,| ƒj-|fd#|i|—Ž d S )$Nú/Ú r   z$keep_alive_milliseconds must be >= 0zKeep-alive ping disabledz0Keep-alive ping configured every %d millisecondsz.check_unused_sessions_milliseconds must be > 0z/Check for unused sessions every %d millisecondsz(Unused sessions last for %d millisecondsz,stats_log_frequency_milliseconds must be > 0z$Log statistics every %d millisecondsz+mem_log_frequency_milliseconds must be >= 0Úpsutilz†Memory logging requested, but is disabled. Optional dependency 'psutil' is missing. Try 'pip install psutil' or 'conda install psutil'z&Log memory usage every %d millisecondsz2websocket_max_message_size_bytes must be postitivez>Torndado websocket_max_message_size set to %d bytes (%0.2f MB)g      0Az3These host origins can connect to the websocket: %r)Zurlr   Úapplication_contextz/wszCouldn't find websocket pathr   Zbokeh_websocket_pathz/static/(.*)Úpath)ÚapplicationsÚprefixZuse_redirectzPatterns are:é<   )ÚwidthÚ
z  Zwebsocket_max_message_size).Ú_loopÚ
isinstancer	   ÚstripÚ_prefixÚ
ValueErrorÚlogÚinfoÚDEFAULT_KEEP_ALIVE_MSÚ_keep_alive_millisecondsÚDEFAULT_CHECK_UNUSED_MSÚ#_check_unused_sessions_millisecondsÚDEFAULT_UNUSED_LIFETIME_MSÚ%_unused_session_lifetime_millisecondsÚDEFAULT_STATS_LOG_FREQ_MSÚ!_stats_log_frequency_millisecondsr   ZwarningÚDEFAULT_MEM_LOG_FREQ_MSÚ_mem_log_frequency_millisecondsÚ(DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTESÚsetÚ_websocket_originsÚ_secret_keyÚ_sign_sessionsÚ_generate_session_idsÚdebugÚlistÚdictÚ_applicationsÚitemsr   r   ÚappendÚendswithÚRuntimeErrorÚextendZstatic_pathr
   r   r   r   ÚsplitÚsuperr   Ú__init__)Úselfr   r   Zextra_websocket_originsZextra_patternsÚ
secret_keyÚsign_sessionsÚgenerate_session_idsZkeep_alive_millisecondsZ"check_unused_sessions_millisecondsZ$unused_session_lifetime_millisecondsZ stats_log_frequency_millisecondsZmem_log_frequency_millisecondsZ	use_indexZredirect_rootZ websocket_max_message_size_bytesÚkwargsÚkÚvZall_patternsÚkeyÚappZapp_patternsÚpZrouteZwebsocket_pathÚrÚdataZprefixed_patÚline)Ú	__class__© ú3lib/python3.7/site-packages/bokeh/server/tornado.pyrC   ¥   sÂ    






















$




"
zBokehTornado.__init__c             C   s’   || _ x| j ¡ D ]}| j |_ qW tƒ | _t| j| jƒ| _| j	dkrVt| j
| j	ƒ| _nd| _t| j| jƒ| _| jdkrˆt| j| jƒ| _nd| _dS )zN Start a Bokeh Server Tornado Application on a given Tornado IOLoop.

        r   N)r!   r;   Úvaluesr3   Ú_clientsr   Ú
_log_statsr/   Ú
_stats_jobr1   Ú_log_memÚ_mem_jobÚ_cleanup_sessionsr+   Ú_cleanup_jobr)   Ú_keep_aliveÚ	_ping_job)rD   Úio_loopZapp_contextrR   rR   rS   Ú
initialize6  s    



zBokehTornado.initializec             C   s
   t | jƒS )zw A list of all application paths for all Bokeh applications
        configured on this Bokeh server instance.

        )r3   r;   )rD   rR   rR   rS   Ú	app_pathsS  s    zBokehTornado.app_pathsc             C   s   | j S )z` The Tornado IOLoop that this  Bokeh Server Tornado Application
        is running on.

        )r!   )rD   rR   rR   rS   r^   [  s    zBokehTornado.io_loopc             C   s   | j S )z^ A URL prefix for this Bokeh Server Tornado Application to use
        for all paths

        )r$   )rD   rR   rR   rS   r   c  s    zBokehTornado.prefixc             C   s   | j S )zK A list of websocket origins permitted to connect to this server.

        )r4   )rD   rR   rR   rS   Úwebsocket_originsk  s    zBokehTornado.websocket_originsc             C   s   | j S )zy A secret key for this Bokeh Server Tornado Application to use when
        signing session IDs, if configured.

        )r5   )rD   rR   rR   rS   rE   r  s    zBokehTornado.secret_keyc             C   s   | j S )zÃ Whether this Bokeh Server Tornado Application has been configured
        to cryptographically sign session IDs

        If ``True``, then ``secret_key`` must also have been configured.
        )r6   )rD   rR   rR   rS   rF   z  s    zBokehTornado.sign_sessionsc             C   s   | j S )z{ Whether this Bokeh Server Tornado Application has been configured
        to automatically generate session IDs.

        )r7   )rD   rR   rR   rS   rG   ƒ  s    z!BokehTornado.generate_session_idsc             C   s,   |rt d|| j tjdS t d| jtjdS )aJ   Provide a :class:`~bokeh.resources.Resources` that specifies where
        Bokeh application sessions should load BokehJS resources from.

        Args:
            absolute_url (bool):
                An absolute URL prefix to use for locating resources. If None,
                relative URLs are used (default: None)

        Zserver)ÚmodeZroot_urlZpath_versioner)r   r$   r   Zappend_version)rD   Zabsolute_urlrR   rR   rS   Ú	resources‹  s    
zBokehTornado.resourcesc             C   s\   | j  ¡  | jdk	r| j ¡  | j ¡  | jdk	r<| j ¡  x| j ¡ D ]}| ¡  qHW dS )a   Start the Bokeh Server application.

        Starting the Bokeh Server Tornado application will run periodic
        callbacks for stats logging, cleanup, pinging, etc. Additionally, any
        startup hooks defined by the configured Bokeh applications will be run.

        N)rW   ÚstartrY   r[   r]   r;   rT   Zrun_load_hook)rD   ÚcontextrR   rR   rS   rd   ™  s    





zBokehTornado.startc             C   sf   x| j  ¡ D ]}| ¡  qW | j ¡  | jdk	r:| j ¡  | j ¡  | jdk	rX| j ¡  | j 	¡  dS )z¬ Stop the Bokeh Server application.

        Args:
            wait (bool): whether to wait for orderly cleanup (default: True)

        Returns:
            None

        N)
r;   rT   Zrun_unload_hookrW   ÚstoprY   r[   r]   rU   Úclear)rD   Úwaitre   rR   rR   rS   rf   «  s    





zBokehTornado.stopc             C   s   t ||||ƒ}| j |¡ |S )N)r   rU   Úadd)rD   ZprotocolZsocketr   ÚsessionÚ
connectionrR   rR   rS   Únew_connectionÃ  s    zBokehTornado.new_connectionc             C   s   | j  |¡ | ¡  d S )N)rU   ÚdiscardZdetach_session)rD   rk   rR   rR   rS   Úclient_lostÈ  s    zBokehTornado.client_lostc             C   s&   || j krtd| ƒ‚| j |  |¡S )ak   Get an active a session by name application path and session ID.

        Args:
            app_path (str) :
                The configured application path for the application to return
                a session for.

            session_id (str) :
                The session ID of the session to retrieve.

        Returns:
            ServerSession

        z,Application %s does not exist on this server)r;   r%   Úget_session)rD   Úapp_pathZ
session_idrR   rR   rS   ro   Ì  s    
zBokehTornado.get_sessionc             C   s&   || j krtd| ƒ‚t| j | jƒS )a   Gets all currently active sessions for an application.

        Args:
            app_path (str) :
                The configured application path for the application to return
                sessions for.

        Returns:
            list[ServerSession]

        z,Application %s does not exist on this server)r;   r%   r9   Úsessions)rD   rp   rR   rR   rS   Úget_sessionsß  s    
zBokehTornado.get_sessionsc             c   s:   t  d¡ x | j ¡ D ]}| | j¡V  qW t d ¡‚d S )NzRunning session cleanup job)r&   Útracer;   rT   rZ   r-   r   ZReturn)rD   rL   rR   rR   rS   rZ   ñ  s    
zBokehTornado._cleanup_sessionsc             C   s˜   t  d¡ t  ¡ tjkrd S t  dt ¡ t| j	ƒ¡ x^| j
 ¡ D ]P\}}t|jƒ}d}x|D ]}|jdkr\|d7 }q\W t  dt ¡ |t|ƒ|¡ q@W d S )NzRunning stats log jobz[pid %d] %d clients connectedr   r   z,[pid %d]   %s has %d sessions with %d unused)r&   rs   ÚgetEffectiveLevelÚloggingÚDEBUGr8   ÚosÚgetpidÚlenrU   r;   r<   r9   rq   Zconnection_count)rD   rp   rL   rq   Zunused_countÚsrR   rR   rS   rV   ø  s    



zBokehTornado._log_statsc       	         sÌ   dd l }| t ¡ ¡}t dt ¡ | ¡ jd | ¡ jd ¡ t 	¡ t
jkrPd S dd l}ddlm} ddlm} ddlm} xJd	|fd
|fd|fgD ]0\}‰ ‡ fdd„| ¡ D ƒ}t d|t|ƒ¡ q”W d S )Nr   z5[pid %d] Memory usage: %0.2f MB (RSS), %0.2f MB (VMS)i   r   )ÚDocument)ÚModelr   )ÚServerSessionZ	DocumentsZSessionsZModelsc                s   g | ]}t |ˆ ƒr|‘qS rR   )r"   )Ú.0Úx)ÚtyprR   rS   ú
<listcomp>  s    z)BokehTornado._log_mem.<locals>.<listcomp>z  uncollected %s: %d)r   ZProcessrw   rx   r&   r'   Zmemory_infoZrssZvmsrt   ru   rv   ÚgcZdocumentr{   Zmodelr|   rj   r}   Zget_objectsr8   ry   )	rD   r   Zprocessr‚   r{   r|   r}   ÚnameZobjsrR   )r€   rS   rX   	  s    ( zBokehTornado._log_memc             C   s&   t  d¡ x| jD ]}| ¡  qW d S )NzRunning keep alive job)r&   rs   rU   Z	send_ping)rD   ÚcrR   rR   rS   r\     s    
zBokehTornado._keep_alive)N)T)$Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Zsecret_key_bytesrF   r(   r*   r,   r.   r0   r2   rC   r_   Úpropertyr`   r^   r   ra   rE   rG   rc   rd   rf   rl   rn   ro   rr   r   Ú	coroutinerZ   rV   rX   r\   Ú__classcell__rR   rR   )rQ   rS   r   C   sF   ` 	

r   ).rˆ   Z
__future__r   r   r   r   ru   Z	getLoggerr…   r&   rw   Zpprintr   Ztornador   Ztornado.ioloopr   Ztornado.webr	   ZTornadoApplicationr
   Zapplicationrc   r   r   Zutil.dependenciesr   Zcontextsr   rk   r   Zurlsr   r   Zviews.root_handlerr   Zviews.static_handlerr   r*   r(   r0   r.   r,   r2   Ú__all__r   rR   rR   rR   rS   Ú<module>	   s4   
	