σ
mάJ]c           @` sm  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 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 m Z d d	 l m Z m Z m Z m Z d d
 l m Z d d l m Z d d l m  Z  m! Z! d d l m" Z" m# Z# d Z$ d e% f d     YZ& d e& f d     YZ' d e f d     YZ( d S(   uΤ   Provide basic Bokeh server objects that use a Tornado ``HTTPServer`` and
``BokeTornado`` Tornado Application to service Bokeh Server Applications.
There are two public classes in this module:

:class:`~bokeh.server.server.BaseServer`
    This is a lightweight class to explicitly coordinate the components needed
    to run a Bokeh server (A :class:`~bokeh.server.tornado.BokehTornado`
    instance, and Tornado ``HTTPServer`` and a Tornado ``IOLoop``)

:class:`~bokeh.server.server.Server`
    This higher-level convenience class only needs to be configured with Bokeh
    :class:`~bokeh.application.application.Application` instances, and will
    automatically create and coordinate the lower level Tornado components.

i    (   t   absolute_importt   divisiont   print_functiont   unicode_literalsN(   t
   HTTPServer(   t   IOLoopi   (   t   __version__(   t   Application(   t   Boolt   Intt   Listt   String(   t   DEFAULT_SERVER_PORT(   t   Optionsi   (   t   bind_socketst   create_hosts_whitelist(   t   BokehTornadot(   DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE_BYTESu
   BaseServeru   Servert
   BaseServerc           B` s   e  Z d  Z d   Z e d    Z d   Z e d  Z d   Z	 d   Z
 d   Z d d  Z d d	 d
  Z e Z d   Z d   Z RS(   u4   Explicitly coordinate the level Tornado components required to run a
    Bokeh server:

    * A Tornado ``IOLoop`` to run the Bokeh server machinery.

    * a ``BokehTornado`` Tornado application that defines the Bokeh server
      machinery.

    * a Tornado ``HTTPServer`` to direct HTTP requests

    All three of these components must be passed to ``BaseServer``, which will
    initialize the ``BokehTornado`` instance on the ``io_loop``. The
    ``http_server`` must have been previously created and initialized with the
    ``BokehTornado`` instance.

    c         C` sA   t  |  _ t  |  _ | |  _ | |  _ | |  _ |  j j |  d S(   u7   Create a ``BaseServer`` instance.

        Args:
            io_loop (IOLoop) :
                A Tornado ``IOLoop`` to run the Bokeh Tornado application on.

            tornado_app (BokehTornado) :
                An instance of the Bokeh Tornado application that generates
                Bokeh Documents and Sessions.

            http_server (HTTPServer) :
                A Tornado ``HTTPServer`` to service HTTP requests for Bokeh
                applications. Should have already be configured with the
                ``tornado_app`` when created.

        N(   t   Falset   _startedt   _stoppedt   _httpt   _loopt   _tornadot
   initialize(   t   selft   io_loopt   tornado_appt   http_server(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyt   __init__V   s    					c         C` s   |  j  S(   uG    The Tornado ``IOLoop`` that this Bokeh Server is running on.

        (   R   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR   q   s    c         C` s0   |  j  s t d   t |  _  |  j j   d S(   u   Install the Bokeh Server and its background tasks on a Tornado
        ``IOLoop``.

        This method does *not* block and does *not* affect the state of the
        Tornado ``IOLoop``  You must start and stop the loop yourself, i.e.
        this method is typically useful when you are already explicitly
        managing an ``IOLoop`` yourself.

        To start a Bokeh server and immediately "run forever" in a blocking
        manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`.

        u   Already startedN(   R   t   AssertionErrort   TrueR   t   start(   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR!   x   s    	c         C` s@   |  j  s t d   t |  _  |  j j |  |  j j   d S(   uK   Stop the Bokeh Server.

        This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
        as stops the ``HTTPServer`` that this instance was configured with.

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

        Returns:
            None

        u   Already stoppedN(   R   R   R    R   t   stopR   (   R   t   wait(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR"      s    	c         c` s   |  j  j   V|  j  j   d S(   u    Stop listening on ports. The server will no longer be usable after
        calling this function.

        Returns:
            None

        N(   R   t   close_all_connectionsR"   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyt   unlisten   s    c         C` sy   |  j  s |  j   n  t j |  j  t j t j |  j  y |  j j   Wn t	 k
 rj t
 d  n X|  j   d S(   u   Run the Bokeh Server until shutdown is requested by the user,
        either via a Keyboard interrupt (Ctrl-C) or SIGTERM.

        Calling this method will start the Tornado ``IOLoop`` and block
        all execution in the calling process.

        Returns:
            None

        u   
Interrupted, shutting downN(   R   R!   t   atexitt   registert   _atexitt   signalt   SIGTERMt   _sigtermR   t   KeyboardInterruptt   printR"   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyt   run_until_shutdown§   s    	c         C` s   |  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

        (   R   t   get_session(   R   t   app_patht
   session_id(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR/   ½   s    c         C` sS   | d k	 r |  j j |  Sg  } x* |  j j D] } | |  j j |  7} q/ W| S(   ui   Gets all currently active sessions for applications.

        Args:
            app_path (str, optional) :
                The configured application path for the application to return
                sessions for. If None, return active sessions for all
                applications. (default: None)

        Returns:
            list[ServerSession]

        N(   t   NoneR   t   get_sessionst	   app_paths(   R   R0   t   all_sessionst   path(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR3   Ξ   s    u   tabc         C` s   | j  d  s t d   n  d } |  j d
 k	 rN |  j d k rN |  j } n  d | |  j |  j | f } d d l m } | | d | d	 | d
 S(   uΫ   Opens an app in a browser window or tab.

        This method is useful for testing or running Bokeh server applications
        on a local machine but should not call when running Bokeh server for
        an actual deployment.

        Args:
            app_path (str) : the app path to open
                The part of the URL after the hostname:port, with leading slash.

            browser (str, optional) : browser to show with (default: None)
                For systems that support it, the **browser** argument allows
                specifying which browser to display in, e.g. "safari", "firefox",
                "opera", "windows-default" (see the ``webbrowser`` module
                documentation in the standard lib for more details).

            new (str, optional) : window or tab (default: "tab")
                If ``new`` is 'tab', then opens a new tab.
                If ``new`` is 'window', then opens a new window.

        Returns:
            None

        u   /u   app_path must start with a /u	   localhostu    u   http://%s:%d%s%si    (   t   viewt   browsert   newN(   t
   startswitht
   ValueErrort   addressR2   t   portt   prefixt   bokeh.util.browserR7   (   R   R0   R8   R9   t   address_stringt   urlR7   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyt   showβ   s    c         C` sC   |  j  r d  St |  _  t j d  |  j s? |  j d t  n  d  S(   Nu   Shutdown: cleaning upR#   (   t   _atexit_ranR    t   logt   debugR   R"   R   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR(     s    			c         C` s+   t  d | f  |  j j |  j j  d  S(   Nu!   Received signal %d, shutting down(   R-   R   t   add_callback_from_signalR"   (   R   t   signumt   frame(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR+     s    N(   t   __name__t
   __module__t   __doc__R   t   propertyR   R!   R    R"   R%   R.   R/   R2   R3   RB   R   RC   R(   R+   (    (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR   D   s   					%		t   Serverc           B` sY   e  Z d  Z d d d  Z e d    Z e d    Z e d    Z e d    Z	 RS(   u§   A high level convenience class to run a Bokeh server.

    This class can automatically coordinate the three the base level
    components required to run a Bokeh server:

    * A Tornado ``IOLoop`` to run the Bokeh server machinery.

    * a ``BokehTornado`` Tornado application that defines the Bokeh server
      machinery.

    * a Tornado ``HTTPServer`` to direct HTTP requests

    This high level ``Server`` class has some limitations. In particular, it is
    not possible to set an explicit ``io_loop`` and ``num_procs`` other than 1
    at the same time. To do that, it is necessary to use ``BaseServer`` and
    coordinate the three components above explicitly.

    c         ` sρ  t  j d t t j f  d d l m } d d l m   t	 |  r[ t
 | |   } n  t | t
  rz i | d 6} n  x t | j    D]k \ } } t	 |  rΎ t
 | |   | | <n  t   f d   | | j D  r | | j      q q Wt |  } | j |  _ | j |  _ | j |  _ | j |  _ | j d k rrt d   | j   D  srt d	   n  | j d k r| d k	 rt d
   n  | j d k rΙt j  d k rΙt d   n  | d k rήi  } n  | j! d | j"  t# |  j |  j  \ }	 |  _ t$ | j% |  j  }
 y` t& | d |
 d |  j d |  j d | j' | } t( | |  } | j) | j  | j* |	  Wn/ t+ k
 r΅x |	 D] } | j,   qW  n X| d k rΡt- j.   } n  t/ t0 |   j1 | | |  d S(   u   Create a ``Server`` instance.

        Args:
            applications (dict[str, Application] or Application or callable) :
                A mapping from URL paths to Application instances, or a single
                Application to put at the root URL.

                The Application is a factory for Documents, with a new Document
                initialized for each Session. Each application is identified
                by a path that corresponds to a URL, like "/" or "/myapp"

                If a single Application is provided, it is mapped to the URL
                path "/" automatically.

                As a convenience, a callable may also be provided, in which
                an Application will be created for it using
                ``FunctionHandler``.

            io_loop (IOLoop, optional) :
                An explicit Tornado ``IOLoop`` to run Bokeh Server code on. If
                None, ``IOLoop.current()`` will be used (default: None)

            http_server_kwargs (dict, optional) :
                Extra arguments passed to ``tornado.httpserver.HTTPServer``.

                E.g. ``max_buffer_size`` to specify the maximum upload size.
                More details can be found at:

                http://www.tornadoweb.org/en/stable/httpserver.html#http-server

                If None, no extra arguments are passed (default: None)

        Additionally, the following options may be passed to configure the
        operation of ``Server``:

        .. bokeh-options:: _ServerOpts
            :module: bokeh.server.server

        Any remaining keyword arguments will be passed as-is to
        ``BokehTornado``.

        u8   Starting Bokeh server version %s (running on Tornado %s)i    (   t   FunctionHandler(   t   DocumentLifecycleHandleru   /c         3` s   |  ] } t  |    Vq d  S(   N(   t
   isinstance(   t   .0t   handler(   RO   (    s2   lib/python2.7/site-packages/bokeh/server/server.pys	   <genexpr>g  s   i   c         s` s   |  ] } | j  Vq d  S(   N(   t   safe_to_fork(   RQ   t   app(    (    s2   lib/python2.7/site-packages/bokeh/server/server.pys	   <genexpr>r  s    ut   User application code has run before attempting to start multiple processes. This is considered an unsafe operation.u   Setting both num_procs and io_loop in Server is incompatible. Use BaseServer to coordinate an explicit IOLoop and multi-process HTTPServeru   win32u&   num_procs > 1 not supported on Windowsu   xheaderst   extra_websocket_originsR>   t   indext    websocket_max_message_size_bytesN(2   RD   t   infoR   t   tornadot   versiont#   bokeh.application.handlers.functionRN   t-   bokeh.application.handlers.document_lifecycleRO   t   callableR   RP   t   listt   itemst   allt	   _handlerst   addt   _ServerOptsR=   t   _portR<   t   _addressR>   t   _prefixRV   t   _indext	   num_procst   valuesR   R2   t   RuntimeErrort   syst   platformt
   setdefaultt   use_xheadersR   R   t   allow_websocket_originR   t   websocket_max_message_sizeR   R!   t   add_socketst	   Exceptiont   closeR   t   currentt   superRM   R   (   R   t   applicationsR   t   http_server_kwargst   kwargsRN   t   kt   vt   optst   socketsRU   R   R   t   s(    (   RO   s2   lib/python2.7/site-packages/bokeh/server/server.pyR   .  s`    +					c         C` s   |  j  S(   u>    A path to a Jinja2 template to use for index at "/"

        (   Rg   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyRV     s    c         C` s   |  j  S(   uG    The configured URL prefix to use for all Bokeh server paths.

        (   Rf   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR>   €  s    c         C` s   |  j  S(   u[    The configured port number that the server listens on for HTTP
        requests.

        (   Rd   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR=   «  s    c         C` s   |  j  S(   uW    The configured address that the server listens on for HTTP
        requests.

        (   Re   (   R   (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyR<   ³  s    N(
   RI   RJ   RK   R2   R   RL   RV   R>   R=   R<   (    (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyRM     s   oRc   c           B` s³   e  Z e d  d d d  Z e d  d d d  Z e d  e d d  Z e d  d d d  Z	 e d  d d d  Z
 e e d  d d d	 Z e d  e d d
  Z e d  e d d  Z RS(   t   defaulti   t   helpu  
    The number of worker processes to start for the HTTP server. If an explicit
    ``io_loop`` is also configured, then ``num_procs=1`` is the only compatible
    value. Use ``BaseServer`` to coordinate an explicit ``IOLoop`` with a
    multi-process HTTP server.

    A value of 0 will auto detect number of cores.

    Note that due to limitations inherent in Tornado, Windows does not support
    ``num_procs`` values greater than one! In this case consider running
    multiple Bokeh server instances behind a load balancer.
    uD   
    The address the server should listen on for HTTP requests.
    uH   
    The port number the server should listen on for HTTP requests.
    u    u9   
    A URL prefix to use for all Bokeh server paths.
    u>   
    A path to a Jinja2 template to use for the index "/"
    uτ   
    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" is used.
    uγ   
    Whether to have the Bokeh server override the remote IP and URI scheme
    and protocol for all requests with ``X-Real-Ip``, ``X-Forwarded-For``,
    ``X-Scheme``, ``X-Forwarded-Proto`` headers (if they are provided).
    ux   
    Set the Tornado ``websocket_max_message_size`` value.

    NOTE: This setting has effect ONLY for Tornado>=4.5
    N(   RI   RJ   R	   Rh   R   R2   R<   R   R=   R>   RV   R
   Ro   R   R   Rn   R   Rp   (    (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyRc   Α  s    							(   u
   BaseServeru   Server()   RK   t
   __future__R    R   R   R   t   loggingt	   getLoggerRI   RD   R&   R)   Rk   RY   t   tornado.httpserverR   t   tornado.ioloopR   t    R   t   applicationR   t   core.propertiesR   R	   R
   R   t	   resourcesR   t   util.optionsR   t   utilR   R   R   R   t   __all__t   objectR   RM   Rc   (    (    (    s2   lib/python2.7/site-packages/bokeh/server/server.pyt   <module>   s*   "" Φ§