σ
mάJ]c           @` sy  d  Z  d d l m Z m Z m Z m Z d d l Z e j 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, d e f d     YZ- d S(   u1    Provides the Bokeh Server Tornado application.

i    (   t   absolute_importt   divisiont   print_functiont   unicode_literalsN(   t   pformat(   t   gen(   t   PeriodicCallback(   t   Application(   t   StaticFileHandleri   (   t	   Resources(   t   settings(   t   import_optionali   (   t   ApplicationContext(   t   ServerConnection(   t   per_app_patternst   toplevel_patterns(   t   RootHandler(   t   StaticHandlerihB  i  i:  i   i   u   BokehTornadot   BokehTornadoc           B` sC  e  Z d  Z d d d e j   e j   e e e	 e
 e e e e e d d  Z d   Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d	    Z e d
    Z d d  Z d   Z e d  Z d   Z d   Z d   Z d   Z e j  d    Z! d   Z" d   Z# d   Z$ RS(   uH   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)

        index (str, optional) :
            Path to a Jinja2 template to serve as the index for "/" if use_index
            is True. If None, the basic built in app index template is used.
            (default: None)

        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``.
    c         K` s  d  |  _ t | t  r( i | d 6} n  | d  k r= d } n  | j d  } | r_ d | } n  | |  _ | |  _ | d k  r t d   n; | d k r¨ t j	 d  n | t
 k rΗ t j	 d |  n  | |  _ |	 d k rλ t d   n |	 t k r
t j	 d |	  n  |	 |  _ |
 d k r.t d   n |
 t k rMt j	 d	 |
  n  |
 |  _ | d k rqt d
   n | t k rt j	 d |  n  | |  _ | d k  r΄t d   nV | d k r
t d  d  k rθt j d  d } q
| t k r
t j	 d |  q
n  | |  _ | d k r.t d   n& | t k rTt j	 d | | d'  n  | d  k rot   |  _ n t |  |  _ | |  _ | |  _ | |  _ t j d t |  j   t   |  _ x3 | j    D]% \ } } t! | d | |  j | <qΛW| pύg  } g  } xc| j    D]U\ } } g  } xj t" D]b } | d k rK| d } n | | d } |  j | } | j# | | d i |  j | d 6f  q,Wd  } x. | D]& } | d j$ d  r| d } qqW| sήt% d   n  x | D] } | | d d <qεW| j& |  | j' d  k	 r| d k r.d } n
 | d } |  j | } | j# | t( i | j' d 6f  qqWx² | t) D]¦ } | d t* k rτ| ri |  j d 6|  j d 6|  j d 6| d  6} |  j | d f | d | f } | j# |  qqw|  j | d f | d } | j# |  qwWt j d!  x4 t+ | d" d# j, d$  D] } t j d% |  qJWt- t. |   j/ | d& | | d  S((   Nu   /u    i    u$   keep_alive_milliseconds must be >= 0u   Keep-alive ping disabledu0   Keep-alive ping configured every %d millisecondsu.   check_unused_sessions_milliseconds must be > 0u/   Check for unused sessions every %d millisecondsu(   Unused sessions last for %d millisecondsu,   stats_log_frequency_milliseconds must be > 0u$   Log statistics every %d millisecondsu+   mem_log_frequency_milliseconds must be >= 0u   psutilu   Memory logging requested, but is disabled. Optional dependency 'psutil' is missing. Try 'pip install psutil' or 'conda install psutil'u&   Log memory usage every %d millisecondsu2   websocket_max_message_size_bytes must be postitiveu>   Torndado websocket_max_message_size set to %d bytes (%0.2f MB)g      @i   u3   These host origins can connect to the websocket: %rt   urli   u   application_contextu   /wsu   Couldn't find websocket pathu   bokeh_websocket_pathu   /static/(.*)u   pathu   applicationsu   prefixu   indexu   use_redirectu   Patterns are:t   widthi<   u   
u     t   websocket_max_message_sizeg      0A(0   t   Nonet   _loopt
   isinstanceR   t   stript   _prefixt   _indext
   ValueErrort   logt   infot   DEFAULT_KEEP_ALIVE_MSt   _keep_alive_millisecondst   DEFAULT_CHECK_UNUSED_MSt#   _check_unused_sessions_millisecondst   DEFAULT_UNUSED_LIFETIME_MSt%   _unused_session_lifetime_millisecondst   DEFAULT_STATS_LOG_FREQ_MSt!   _stats_log_frequency_millisecondsR   t   warningt   DEFAULT_MEM_LOG_FREQ_MSt   _mem_log_frequency_millisecondst(   DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTESt   sett   _websocket_originst   _secret_keyt   _sign_sessionst   _generate_session_idst   debugt   listt   dictt   _applicationst   itemsR   R   t   appendt   endswitht   RuntimeErrort   extendt   static_pathR   R   R   R   t   splitt   superR   t   __init__(   t   selft   applicationst   prefixt   extra_websocket_originst   extra_patternst
   secret_keyt   sign_sessionst   generate_session_idst   keep_alive_millisecondst"   check_unused_sessions_millisecondst$   unused_session_lifetime_millisecondst    stats_log_frequency_millisecondst   mem_log_frequency_millisecondst	   use_indext   redirect_roott    websocket_max_message_size_bytest   indext   kwargst   kt   vt   all_patternst   keyt   appt   app_patternst   pt   routet   websocket_patht   rt   datat   prefixed_patt   line(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR<   ͺ   sΖ    														,	
'


#"c         C` sΥ   | |  _  x# |  j j   D] } |  j  | _  q Wt   |  _ t |  j |  j  |  _ |  j	 d k r} t |  j
 |  j	  |  _ n	 d |  _ t |  j |  j  |  _ |  j d k rΘ t |  j |  j  |  _ n	 d |  _ d S(   uN    Start a Bokeh Server Tornado Application on a given Tornado IOLoop.

        i    N(   R   R3   t   valuesR+   t   _clientsR   t
   _log_statsR&   t
   _stats_jobR)   t   _log_memt   _mem_jobR   t   _cleanup_sessionsR"   t   _cleanup_jobR    t   _keep_alivet	   _ping_job(   R=   t   io_loopt   app_context(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt
   initialize?  s    					c         C` s   t  |  j  S(   uw    A list of all application paths for all Bokeh applications
        configured on this Bokeh server instance.

        (   R+   R3   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt	   app_paths\  s    c         C` s   |  j  S(   u>    Path to a Jinja2 template to serve as the index "/"

        (   R   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRM   d  s    c         C` s   |  j  S(   u`    The Tornado IOLoop that this  Bokeh Server Tornado Application
        is running on.

        (   R   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRf   k  s    c         C` s   |  j  S(   u^    A URL prefix for this Bokeh Server Tornado Application to use
        for all paths

        (   R   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR?   s  s    c         C` s   |  j  S(   uK    A list of websocket origins permitted to connect to this server.

        (   R,   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt   websocket_origins{  s    c         C` s   |  j  S(   uy    A secret key for this Bokeh Server Tornado Application to use when
        signing session IDs, if configured.

        (   R-   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRB     s    c         C` s   |  j  S(   uΓ    Whether this Bokeh Server Tornado Application has been configured
        to cryptographically sign session IDs

        If ``True``, then ``secret_key`` must also have been configured.
        (   R.   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRC     s    c         C` s   |  j  S(   u{    Whether this Bokeh Server Tornado Application has been configured
        to automatically generate session IDs.

        (   R/   (   R=   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRD     s    c         C` sH   | r) t  d d d | |  j d t j  St  d d d |  j d t j  S(   uJ   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)

        t   modeu   servert   root_urlt   path_versioner(   R	   R   R   t   append_version(   R=   t   absolute_url(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt	   resources  s    
#c         C` s   |  j  j   |  j d k	 r, |  j j   n  |  j j   |  j d k	 rX |  j j   n  x! |  j j   D] } | j   qh Wd S(   u   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(	   R_   t   startRa   R   Rc   Re   R3   R\   t   run_load_hook(   R=   t   context(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRq   ©  s    c         C` s   x! |  j  j   D] } | j   q W|  j j   |  j d k	 rP |  j j   n  |  j j   |  j d k	 r| |  j j   n  |  j	 j
   d S(   u¬    Stop the Bokeh Server application.

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

        Returns:
            None

        N(   R3   R\   t   run_unload_hookR_   t   stopRa   R   Rc   Re   R]   t   clear(   R=   t   waitRs   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRu   »  s    c         C` s)   t  | | | |  } |  j j |  | S(   N(   R   R]   t   add(   R=   t   protocolt   sockett   application_contextt   sessiont
   connection(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt   new_connectionΣ  s    c         C` s   |  j  j |  | j   d  S(   N(   R]   t   discardt   detach_session(   R=   R}   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt   client_lostΨ  s    c         C` s6   | |  j  k r" t d |   n  |  j  | j |  S(   uk   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

        u,   Application %s does not exist on this server(   R3   R   t   get_session(   R=   t   app_patht
   session_id(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR   ά  s    c         C` s6   | |  j  k r" t d |   n  t |  j  | j  S(   u   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]

        u,   Application %s does not exist on this server(   R3   R   R1   t   sessions(   R=   R   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt   get_sessionsο  s    c         c` sK   t  j d  x( |  j j   D] } | j |  j  Vq Wt j d    d  S(   Nu   Running session cleanup job(	   R   t   traceR3   R\   Rb   R$   R   t   ReturnR   (   R=   RS   (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRb     s    c         C` sΣ   t  j d  t  j   t j k r& d  St  j d t j   t |  j	   x |  j
 j   D]s \ } } t | j  } d } x* | D]" } | j d k r | d 7} q q Wt  j d t j   | t |  |  qX Wd  S(   Nu   Running stats log jobu   [pid %d] %d clients connectedi    i   u,   [pid %d]   %s has %d sessions with %d unused(   R   R   t   getEffectiveLevelt   loggingt   DEBUGR0   t   ost   getpidt   lenR]   R3   R4   R1   R   t   connection_count(   R=   R   RS   R   t   unused_countt   s(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR^     s    "	c         C` s)  d d  l  } | j t j    } t j d t j   | j   j d | j   j d  t j	   t
 j k rp d  Sd d  l } d d l m } d d l m } d d l m } xv d	 | f d
 | f d | f g D]S \ } } g  | j   D] }	 t |	 |  rη |	 ^ qη }
 t j d | t |
   qΞ Wd  S(   Ni    u5   [pid %d] Memory usage: %0.2f MB (RSS), %0.2f MB (VMS)i   i   (   t   Document(   t   Modeli   (   t   ServerSessionu	   Documentsu   Sessionsu   Modelsu     uncollected %s: %di   i   (   t   psutilt   ProcessR   R   R   R   t   memory_infot   rsst   vmsR   R   R   t   gct   documentR   t   modelR   R|   R   t   get_objectsR   R0   R   (   R=   R   t   processR   R   R   R   t   namet   typt   xt   objs(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR`     s    6..c         C` s/   t  j d  x |  j D] } | j   q Wd  S(   Nu   Running keep alive job(   R   R   R]   t	   send_ping(   R=   t   c(    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyRd   +  s    N(%   t   __name__t
   __module__t   __doc__R   R
   t   secret_key_bytesRC   t   TrueR   R!   R#   R%   R(   R*   R<   Rh   t   propertyRi   RM   Rf   R?   Rj   RB   RD   Rp   Rq   Ru   R~   R   R   R   R   t	   coroutineRb   R^   R`   Rd   (    (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyR   C   sH   e											i P  i  @(   u   BokehTornado(.   R§   t
   __future__R    R   R   R   R   t	   getLoggerR₯   R   R   t   pprintR   t   tornadoR   t   tornado.ioloopR   t   tornado.webR   t   TornadoApplicationR   t   applicationRp   R	   R
   t   util.dependenciesR   t   contextsR   R}   R   t   urlsR   R   t   views.root_handlerR   t   views.static_handlerR   R!   R   R(   R%   R#   R*   t   __all__R   (    (    (    s3   lib/python2.7/site-packages/bokeh/server/tornado.pyt   <module>	   s4   "	