Beispiel #1
0
def main():
    SocketRouter = SockJSRouter(SocketConnection, '/socket')
    AppRouter = SockJSRouter(AppSocketConnection, '/app')
    app = tornado.web.Application(
        SocketRouter.urls + AppRouter.urls + [
            (r"/", Mainhandler),
            (r"/dev", Devhandler),
            (r"/user/([0-9]+)/([0-9]+)", Userhandler),
            (r"/login", LoginHandler),
            (r"/logout", LogoutHandler),
            (r"/signup", SignupHandler),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        cookie_secret="98RaTgemQjS/zVMMFr8oZ35z9S1UsEaGgl/E3cpxm/E=",
        login_url="/login",
        xsrf_cookies="True",
        degug="True",
        websocket_ping_interval=40,
        websocket_ping_timeout=120,
    )
    serverDB.initDatabase()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(os.environ.get('PORT'))
    tornado.ioloop.IOLoop.instance().start()
Beispiel #2
0
def run_tornado(addr, port, *args, **kwargs):
    """
    Starts the tornado webserver as wsgi server for OpenSlides.

    It runs in one thread.
    """
    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    from openslides.core.chatbox import ChatboxSocketHandler
    chatbox_socket_js_router = SockJSRouter(ChatboxSocketHandler, '/core/chatbox')
    sock_js_router = SockJSRouter(OpenSlidesSockJSConnection, '/sockjs')
    other_urls = [
        (r"%s(.*)" % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))]

    # Start the application
    debug = settings.DEBUG
    tornado_app = Application(sock_js_router.urls + chatbox_socket_js_router.urls + other_urls, autoreload=debug, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()
Beispiel #3
0
    def __init__(self, settings):

        handlers = [
            tornado.web.url(
                r'/', MainHandler, name="main"
            ),
            tornado.web.url(
                r'/project/create$',
                ProjectCreateHandler,
                name="project_create"
            ),
            tornado.web.url(
                r'/project/([^/]+)/settings/([^/]+)$',
                ProjectSettingsHandler,
                name="project_settings"
            ),
            tornado.web.url(
                r'/rpc/([^/]+)$', RpcHandler, name="store"
            ),
            tornado.web.url(
                r'/auth$', AuthHandler, name="auth"
            ),
            tornado.web.url(
                r'/logout$', LogoutHandler, name="logout"
            )
        ]

        # create SockJS route for admin connections
        AdminConnectionRouter = SockJSRouter(
            AdminSocketHandler, '/socket'
        )
        handlers = AdminConnectionRouter.urls + handlers

        # create SockJS route for client connections
        SockjsConnectionRouter = SockJSRouter(
            SockjsConnection, '/connection'
        )
        handlers = SockjsConnectionRouter.urls + handlers

        # match everything else to 404 handler
        handlers.append(
            tornado.web.url(
                r'.*', Http404Handler, name='http404'
            )
        )

        AdminSocketHandler.application = self
        SockjsConnection.application = self

        tornado.web.Application.__init__(
            self,
            handlers,
            **settings
        )
Beispiel #4
0
    def __init__(self,
                 socket_path="/updates",
                 websockets=True,
                 subscriptions=None,
                 redis_host="127.0.0.1",
                 redis_port=6379,
                 exit_gracefully=True,
                 debug=False):
        """
        RedisVisualization server. Servers updates from redis using websockets
        and also provide static files using Tornado.

        Inputs
        ------
        @socket_path         str : where should client ask for redis updates (default = '/updates')
        @websockets         bool : use websockets ? (default = True)
        @subscriptions list<str> : what to subscribe to on Redis (default=['namespace_*', 'updates_*'])
        @redis_host          str : what hostname is redis server on (default='127.0.0.1')
        @redis_port          int : what port to listen to for redis server (default=6379)
        @exit_gracefully    bool : capture SIGINT event & shut down server from ioloop (default=True)

        """
        self.exit_gracefully = exit_gracefully
        if subscriptions is None:
            subscriptions = ["updates_*"]
        # 2. Start a connection pool to redis:
        pool = tornadoredis.ConnectionPool(host=redis_host, port=redis_port)
        self.clients = tornadoredis.Client(connection_pool=pool, password="")
        init_redis(tornadoredis.Client(connection_pool=pool, password=""))
        self.clients.connect()
        get_redis().connect()
        # make sure redis reports expiration and set events:
        try:
            self.clients.psubscribe(
                subscriptions,
                lambda msg: self.clients.listen(Connection.pubsub_message))
        except tornadoredis.exceptions.ConnectionError:
            print("""
                Could not connect to Redis. Start server with:
                    > redis-server
                """)
            signal_handler(None, None)
            try_exit()
        if not websockets:
            Router = SockJSRouter(Connection, socket_path,
                                  dict(disabled_transports=['websocket']))
        else:
            Router = SockJSRouter(Connection, socket_path)
        # 4. Creater router for http + sockets:
        self.App = tornado.web.Application(
            generate_routes(debug) + Router.urls)
Beispiel #5
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    # currently only allow one command-line argument, the port to run on.
    logging.getLogger().setLevel(logging.DEBUG)
    port = int(argv[1]) if (len(argv) > 1) else settings.WEBSOCKET_PORT
    ParticipantRouter = SockJSRouter(ParticipantConnection, '%s/participant' % settings.WEBSOCKET_URI)
    ExperimenterRouter = SockJSRouter(ExperimenterConnection, '%s/experimenter' % settings.WEBSOCKET_URI)
    urls = list(chain.from_iterable([ParticipantRouter.urls, ExperimenterRouter.urls]))
    app = web.Application(urls)
    logger.info("starting sockjs server on port %s", port)
    app.listen(port)
    if getattr(settings, 'RAVEN_CONFIG', None):
        app.sentry_client = AsyncSentryClient(settings.RAVEN_CONFIG['dsn'])
    ioloop.IOLoop.instance().start()
Beispiel #6
0
    def run(self):
        self.tord_static_path = os.path.join(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         'static'), 'tord')
        self.template = template.Loader(os.path.abspath(self.templates_dir))

        settings.pubsub['klass'] = import_path(
            'async_pubsub.%s_pubsub.%sPubSub' %
            (self.pubsub_klass.lower(), self.pubsub_klass))
        settings.pubsub['opts'] = self.pubsub_opts

        self._add_http_route('%s/(.*)' % self.static_path,
                             web.StaticFileHandler,
                             {'path': os.path.abspath(self.static_dir)}, True)
        self._add_http_route('%s/tord/(.*)' % self.static_path,
                             web.StaticFileHandler,
                             {'path': self.tord_static_path}, True)

        self.app = web.Application(
            SockJSRouter(WebSocketHandler, self.ws_path).urls +
            settings.routes['http'],
            debug=self.debug)
        self.app.listen(self.port)
        logger.info('Listening on port %s ...' % self.port)

        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            pass
        finally:
            logger.info('Shutting down ...')
Beispiel #7
0
    def handle(self, **options):
        if len(settings.SOCKJS_CLASSES) > 1:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "Multiple connections not yet supported")

        module_name, cls_name = settings.SOCKJS_CLASSES[0].rsplit('.', 1)
        module = import_module(module_name)
        cls = getattr(module, cls_name)
        channel = getattr(settings, 'SOCKJS_CHANNEL', '/echo')
        if not channel.startswith('/'):
            channel = '/%s' % channel

        router = SockJSRouter(cls, channel)
        app_settings = {
            'debug': settings.DEBUG,
        }

        PORT = 9999
        app = web.Application(router.urls, **app_settings)
        app.listen(PORT, no_keep_alive=False)
        print "Running sock app on port", PORT, "with channel", channel
        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            # so you don't think you errored when ^C'ing out
            pass
Beispiel #8
0
    def start(self):
        self.router = SockJSRouter(PubSubConnection,
                                   '/pubsub',
                                   user_settings={'master': self})

        app = web.Application(self.router.urls)
        app.listen(9000)
        for monitor in self.monitors:
            t = threading.Thread(target=monitor, args=(self, ))
            t.daemon = True
            t.start()

        t = threading.Thread(target=self.ioloop.start)
        t.daemon = True
        t.start()
        logging.info('Realtime listener started.')

        # Returning control to the parent application so we can catch keyword
        # interrupts.
        try:
            while 1:
                t.join(1)
                if not t.isAlive():
                    break
        except KeyboardInterrupt:
            print '\nExiting...'
            sys.exit(1)
Beispiel #9
0
def start():
    """Setup HTTP/WS server. **MUST** be called prior to any operation."""
    StatusRouter = SockJSRouter(handlers.StatusConnection, "/data")

    application = tornado.web.Application(
        [
            # FIXME daltonism workaround, should be implemented client-side
            (r'/(?:|blind)', handlers.HomePageHandler),
            (r'/log', handlers.LogPageHandler),
            (r'/status', handlers.StatusPageHandler),
            (r'/presence', handlers.PresenceForecastHandler),
            (r'/(info)', handlers.MarkdownPageHandler),
            (r'/login', handlers.LoginPageHandler),
            (r'/logout', handlers.LogoutPageHandler),
            (r'/admin', handlers.AdminPageHandler),
            (r'/message', handlers.MessagePageHandler),
            (r'/data.php', handlers.RTCHandler)
        ] + StatusRouter.urls,
        ui_modules=uimodules,
        gzip=True,
        debug=options.developer_mode,
        static_path=options.assets_path,
        xsrf_cookies=True,
        cookie_secret=options.cookie_secret)
    server = tornado.httpserver.HTTPServer(application)  #TODO other options
    LOG.info('Starting HTTP/WS server...')
    bind(server, options.web_port, options.web_usocket)
Beispiel #10
0
    def run(self):
        # Setup SockJS

        flaskwsgi = WSGIContainer(self.flaskapp)

        self.socketrouter = SockJSRouter(SocketConnection, '/sockjs')

        tornado_app = tornado.web.Application(self.socketrouter.urls +
                                              [(r".*",
                                                tornado.web.FallbackHandler, {
                                                    "fallback": flaskwsgi
                                                })])
        tornado_app.listen(80)

        # Wake up robot
        Robot.wake()

        # Start default app
        startup_app = Preferences.get('general', 'startup_app', None)
        if startup_app in Apps.apps:
            self.request_handler.page_openapp(startup_app)

        # SSL security
        # http_server = tornado.httpserver.HTTPServer(tornado_app, ssl_options={
        # 	"certfile": "/etc/ssl/certs/server.crt",
        # 	"keyfile": "/etc/ssl/private/server.key",
        # 	})
        # http_server.listen(443)

        try:
            # ioloop.PeriodicCallback(UserSocketConnection.dump_stats, 1000).start()
            IOLoop.instance().start()
        except KeyboardInterrupt:
            print_info('Keyboard interupt')
Beispiel #11
0
def create_application_handlers(sockjs_settings):

    handlers = [
        tornado.web.url(r'/api/([^/]+)/?$', ApiHandler, name="api"),
        tornado.web.url(r'/info/$', InfoHandler, name="info"),
        tornado.web.url(r'/action/$', ActionHandler, name="action"),
        tornado.web.url(r'/auth/$', AuthHandler, name="auth"),
        (r'/socket', AdminWebSocketHandler),
    ]

    if options.web:
        logger.info("serving web application from {0}".format(
            os.path.abspath(options.web)))
        handlers.append((r'/(.*)', tornado.web.StaticFileHandler, {
            "path": options.web,
            "default_filename": "index.html"
        }))

    # create SockJS route for client connections
    client_sock_router = SockJSRouter(SockjsConnection,
                                      '/connection',
                                      user_settings=sockjs_settings)
    handlers = client_sock_router.urls + handlers

    return handlers
Beispiel #12
0
    def handle(self, *args, **options):
        # connect to redis
        url = urlparse.urlparse(settings.REDIS_URL)
        pool = tornadoredis.ConnectionPool(host=url.hostname, port=url.port)
        redis_connection = tornadoredis.Client(connection_pool=pool,
                                               password=url.password)
        redis_connection.connect()
        sys.stdout.write("\nConnected to Redis ({}) \n".format(url))
        redis_connection.psubscribe(
            "*", lambda message: redis_connection.listen(
                connections.MainConnection.pubsub_message))

        # enable sockjs routing
        router = SockJSRouter(
            connections.MainConnection,
            '/chat',
            dict(disabled_transports=DISABLED_TRANSPORTS),
        )
        app = web.Application(
            router.urls,
            "0.0.0.0",
        )
        app.listen(IO_PORT)
        sys.stdout.write("\nApp listening at port {}\n".format(IO_PORT))
        sys.stdout.flush()
        ioloop.IOLoop.instance().start()
    def handle(self, **options):
        if len(settings.SOCKJS_CLASSES) > 1:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                "Multiple connections not yet supported")

        module_name, cls_name = settings.SOCKJS_CLASSES[0].rsplit('.', 1)
        module = import_module(module_name)
        cls = getattr(module, cls_name)
        channel = getattr(settings, 'SOCKJS_CHANNEL', '/chat')
        if not channel.startswith('/'):
            channel = '/%s' % channel

        router = SockJSRouter(cls, channel)
        app_settings = {
            'debug': settings.DEBUG,
        }

        port = int(options['port'])
        app = web.Application(router.urls, **app_settings)
        app.listen(port, no_keep_alive=options['no_keep_alive'])
        print("Running sock app on port", port, "with channel", channel)
        try:
            ioloop.IOLoop.instance().start()
        except KeyboardInterrupt:
            pass
Beispiel #14
0
    def __init__(self, **kwargs):
        if options.baseurl is None:
            raise ValueError('Base URL must be configured')

        router = SockJSRouter(SearchConnection, '/search',
                              self.sockjs_settings)
        # Allow connections to find the application
        router.application = self

        handlers = list(self.handlers)
        router.apply_routes(handlers)
        settings = dict(self.app_settings)
        settings.update(kwargs)
        tornado.web.Application.__init__(self, handlers, **settings)

        if not os.path.isdir(options.blob_cache_dir):
            os.makedirs(options.blob_cache_dir, 0700)
        self.blob_cache = BlobCache(options.blob_cache_dir)

        self.search_cache = SearchCache(options.search_cache_dir)

        self._pruner = threading.Thread(target=self._prune_cache_thread,
                                        name='prune-cache')
        self._pruner.daemon = True
        self._pruner.start()
Beispiel #15
0
def run():
    router = SockJSRouter(connections.PhotoStream, settings.SOCKET_STREAMER_URL)

    handlers = router.urls

    runtime_vars = dict()

    runtime_vars["last_obj_count"] = None
    runtime_vars.update(MultiuploaderImage.objects.aggregate(last_upload=Max('upload_date')))

    def db_periodic_check(*a, **kw):
        obj_count = MultiuploaderImage.objects.count()
        if obj_count != runtime_vars["last_obj_count"]:
            runtime_vars["last_obj_count"] = obj_count
            if not runtime_vars["last_upload"] is None:
                objs = MultiuploaderImage.objects.filter(upload_date__gt=runtime_vars["last_upload"])
                runtime_vars.update(MultiuploaderImage.objects.aggregate(last_upload=Max('upload_date')))
                for obj in objs:
                    for user in connections.PhotoStream.connected_users:
                        user.notify_new_entry(obj)

    app = web.Application(handlers)
    app.listen(int(settings.SOCKET_STREAMER_PORT), "0.0.0.0")
    ioloop.PeriodicCallback(db_periodic_check, 1000).start()
    autoreload.start(ioloop.IOLoop.instance())
    print "socket streamer is (re)started"
    try:
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        return
Beispiel #16
0
def main():
    import core

    # turn on heavy debug logging
    #setup_logging()

    try:
        SockRouter = SockJSRouter(Status)

        application = Application(
            SockRouter.apply_routes([(r"/", IndexHandler),
                                     (r"/record", RecordHandler),
                                     (r"/resetPeaks", ResetPeaksHandler),
                                     (r"/resetBTimer", ResetBTimerHandler),
                                     (
                                         r"/flac/(.*)",
                                         tornado.web.StaticFileHandler,
                                         {
                                             "path": "."
                                         },
                                     )]),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=sys.DEV_MODE)

        if not sys.DEV_MODE:
            port = 80
        else:
            port = 8080

        application.listen(port)
        ioloop.IOLoop.instance().start()

    finally:
        core.port.stop()
        core.port.waitTillFinished()
Beispiel #17
0
def run_app():
    # configure logging level
    if settings.VERBOSE:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    ThunderRouter = SockJSRouter(ThunderSocketHandler, "/connect")
    urls = ThunderRouter.urls + api.urls
    application = tornado.web.Application(urls, settings.DEBUG)

    ss = SortingStation.instance()

    # Single-client only at the moment.
    ss.create_messenger(settings.APIKEY, settings.APISECRET)

    logger.info("Starting Thunderpush server at %s:%d", settings.HOST,
                settings.PORT)

    application.listen(settings.PORT, settings.HOST)

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        logger.info("Shutting down...")
Beispiel #18
0
    def __init__(self):
        self.db = db
        self.config = config

        from bcloud.handlers.host import HostHandler, HostsHandler
        from bcloud.handlers.index import MainHandler

        from bcloud.handlers.websocket import BCloudSocketHandler
        from bcloud.handlers.project import ProjectHandler

        from bcloud.handlers.websocket import WSocketHandler
        from sockjs.tornado import SockJSRouter

        from bcloud.handlers.project import ProjectsHandler
        handlers = [
            (r"/", MainHandler),
            (r"/terminal/(?P<tid>.*)", TermHandler),
            (r"/terminal1/(?P<tid>.*)", Term1Handler),
            (r"/host", HostsHandler),
            (r"/host/(?P<hid>.*)", HostHandler),
            (r"/project", ProjectsHandler),
            (r"/project/(?P<pid>.*)", ProjectHandler),
            (r"/task", TasksHandler),
            (r"/task/(?P<tid>.*)", TaskHandler),

            (r"/docker", DockerHandle),
        ]
        handlers += SockJSRouter(WSocketHandler, '/ws').urls
        handlers += SockJSRouter(BCloudSocketHandler, '/term').urls
        handlers += SockJSRouter(BCloudSocket1Handler, '/term1').urls

        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            ui_modules={
                "Entry": EntryModule,
                "Sidebar": SidebarModule,
                "Menubar": MenubarModule,
                "Footer": FooterModule,
                'include': TemplateModule,
            },
            xsrf_cookies=False,
            cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
            # login_url="/auth/login",
            debug=True,
        )
        super(Application, self).__init__(handlers, **settings)
Beispiel #19
0
def main():
  # Parse args
  parser = argparse.ArgumentParser(description="dead simple commits feed")
  parser.add_argument('-s', '--secret', type=str, default=gen_secret(18),
                      help="auth secret")
  parser.add_argument('-p', '--port', type=int, default=5000,
                      help="port")
  parser.add_argument('--redis-prefix', type=str, default='revfeed',
                      help="redis prefix")
  parser.add_argument('--redis-host', type=str, default='localhost',
                      help="redis host")
  parser.add_argument('--redis-port', type=int, default=6379,
                      help="redis port")
  parser.add_argument('--clear', action='store_true', help="clear feed")
  args = parser.parse_args()

  # Setup redis connection
  redis_prefix = args.redis_prefix
  redis_conn = redis.StrictRedis(args.redis_host, args.redis_port)

  # Clear feed if requested
  if args.clear:
    count = 0
    for key in redis_conn.keys(redis_key(redis_prefix, '*')):
      count += redis_conn.delete(key)
    logger.info("deleted {} keys".format(count))
    return

  # Setup handlers
  handlers = []
  handlers.append((r'/', IndexHandler, dict(
    redis_prefix=redis_prefix,
    redis_conn=redis_conn,
  )))
  handlers.append((r'/commits', CommitsHandler, dict(
    secret=args.secret,
    redis_prefix=redis_prefix,
    redis_conn=redis_conn,
  )))
  handlers.extend(SockJSRouter(NotifierConnection, '/notifier').urls)

  # Setup app
  static_path = pkg_resources.resource_filename(__package__, 'static')
  app = web.Application(
    handlers,
    gzip=True,
    static_path=static_path,
    log_function=log_request,
  )

  app.listen(args.port)
  for a in ('secret', 'port'):
    logger.info("{}={!r}".format(a, getattr(args, a)))

  # Start IOLoop
  try:
    ioloop.IOLoop.instance().start()
  except (KeyboardInterrupt, SystemExit):
    pass
Beispiel #20
0
def getsocks(logsock=None, cmdsock=None):
    """
    """
    socks = []
    if logsock:
        LoggerConnection.subscriber = ZMQSubscriber(logsock)
        socks += SockJSRouter(LoggerConnection, '/logs').urls
    return socks
Beispiel #21
0
def make_app():
    sock_router = SockJSRouter(WebSocketHandler, '/websocket')
    return Application(sock_router.urls + [
        (r'/static/(.*)', StaticFileHandler, {
            'path': 'static'
        }),
        url(r'/(.*)', IndexHandler),
    ])
Beispiel #22
0
def make_router():
    return SockJSRouter(
        MultiplexConnection.get(
            main=MainConnection,
            shell=ShellConnection,
        ),
        '/socket'
    )
def sockjs_webapp_factory(connection):
    """
    `sockjs_webapp_factory` provied a Tornado web application with a sockjs
    handler for incoming connections.
    """
    from sockjs.tornado import SockJSRouter

    return web.Application(SockJSRouter(connection, SERVER_BASE_URL).urls)
Beispiel #24
0
def start_tornado():
    # logging.getLogger().setLevel(logging.DEBUG)
    # logging.getLogger().setLevel(logging.INFO)

    EchoRouter = SockJSRouter(PlansqTornadoChat, '/socket')

    app = web.Application(EchoRouter.urls)
    app.listen(config.TORNADO_PORT)
    ioloop.IOLoop.instance().start()
Beispiel #25
0
    def __init__(self):
        options = {'disconnect_delay': 5, 'jsessionid': False, 'sockjs_url': 'https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.min.js'}
        self.WaitRouter = SockJSRouter(WaitingRoomConnection, '/sockjs/wait', options)
        self.GameRouter = SockJSRouter(GameConnection, '/sockjs/game', options)
        self.SessionRouter = SockJSRouter(SessionConnection, '/sockjs/session', options)

        GameConnection.ready = 0
        GameConnection.size = 2

        urls = [
            (r'/', handlers.MainHandler),
            (r'/session', handlers.SessionHandler),
            (r'/about', RegisterHandler),
            (r'/quiz/user/([a-zA-Z0-9])*', handlers.QuizHandler),
            (r'/instructionsemployer([^/]*)', handlers.InstructionsHandler),
            (r'/instructionsemployee([^/]*)', handlers.Instructions2Handler),
            (r'/tutorial1/user/([a-zA-Z0-9])*', handlers.TutorialHandler),
            (r'/tutorial2/user/([a-zA-Z0-9])*', handlers.Tutorial2Handler),
            (r'/welcome([^/]*)', handlers.WelcomeHandler),
            (r'/payment([^/]*)', handlers.PaymentHandler),
            (r'/game/user/([a-zA-Z0-9])*', handlers.GameHandler),
            (r'/api/player/register([^/]*)', handlers.PlayerCreateHandler),
            (r'/api/player/(.*)', handlers.PlayerHandler),
            (r'/api/credential', handlers.CredentialHandler),
            (r'/experimenter/config/sync/activate/([a-zA-Z0-9]+$)', handlers.SyncExperimentLaunchHandler),
            (r'/admin/user', handlers.UserHandler),
            (r'/admin', AdminHandler)

        ] + self.WaitRouter.urls + self.GameRouter.urls + self.SessionRouter.urls
        settings = {
            "debug": True,
            "template_path": os.path.join(os.path.dirname(__file__), "templates"),
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
            "cookie_secret": "__TODO:_GENERATE_RANDOM_VALUE_HERE__"
        }

        self.redis_cmd = redis.Redis(db=0, \
        password='******', \
        unix_socket_path='/tmp/redis.sock')

        self.redis_pub = Client()
        self.redis_pub.connect_usocket('/tmp/redis.sock', callback=self.auth)

        tornado.web.Application.__init__(self, urls, **settings)
Beispiel #26
0
def create_application_handlers(sockjs_settings):

    handlers = [
        tornado.web.url(r'/', MainHandler, name="main"),
        tornado.web.url(r'/project/create$',
                        ProjectCreateHandler,
                        name="project_create"),
        tornado.web.url(r'/project/([^/]+)/([^/]+)$',
                        ProjectDetailHandler,
                        name="project_detail"),
        tornado.web.url(r'/project/([^/]+)/namespace/create$',
                        NamespaceFormHandler,
                        name="namespace_create"),
        tornado.web.url(r'/project/([^/]+)/namespace/edit/([^/]+)/',
                        NamespaceFormHandler,
                        name="namespace_edit"),
        tornado.web.url(r'/api/([^/]+)$', ApiHandler, name="api"),
        tornado.web.url(r'/auth$', AuthHandler, name="auth"),
        tornado.web.url(r'/logout$', LogoutHandler, name="logout"),
        tornado.web.url(r'/dumps$',
                        StructureDumpHandler,
                        name="dump_structure"),
        tornado.web.url(r'/loads$',
                        StructureLoadHandler,
                        name="load_structure")
    ]

    # create SockJS route for admin connections
    admin_sock_router = SockJSRouter(AdminSocketHandler,
                                     '/socket',
                                     user_settings=sockjs_settings)
    handlers = admin_sock_router.urls + handlers

    # create SockJS route for client connections
    client_sock_router = SockJSRouter(SockjsConnection,
                                      '/connection',
                                      user_settings=sockjs_settings)
    handlers = client_sock_router.urls + handlers

    # match everything else to 404 handler
    handlers.append(tornado.web.url(r'.*', Http404Handler, name='http404'))

    return handlers
Beispiel #27
0
def start_warrior_server(warrior,
                         bind_address="localhost",
                         port_number=8001,
                         http_username=None,
                         http_password=None):
    '''Starts the warrior web interface.'''
    SeesawConnection.warrior = warrior

    warrior.on_projects_loaded += SeesawConnection.handle_projects_loaded
    warrior.on_project_refresh += SeesawConnection.handle_project_refresh
    warrior.on_project_installing += SeesawConnection.handle_project_installing
    warrior.on_project_installed += SeesawConnection.handle_project_installed
    warrior.on_project_installation_failed += \
        SeesawConnection.handle_project_installation_failed
    warrior.on_project_selected += SeesawConnection.handle_project_selected
    warrior.on_broadcast_message_received += SeesawConnection.handle_broadcast_message
    warrior.on_status += SeesawConnection.handle_warrior_status
    warrior.runner.on_pipeline_start_item += SeesawConnection.handle_start_item
    warrior.runner.on_pipeline_finish_item += \
        SeesawConnection.handle_finish_item
    warrior.runner.on_status += SeesawConnection.handle_runner_status

    if not http_username:
        http_username = warrior.http_username
    if not http_password:
        http_password = warrior.http_password

    ioloop.PeriodicCallback(SeesawConnection.broadcast_bandwidth, 1000).start()
    ioloop.PeriodicCallback(SeesawConnection.broadcast_timestamp, 1000).start()

    router = SockJSRouter(SeesawConnection)

    application = web.Application(
        router.apply_routes([(r"/(.*\.(html|css|js|swf|png|ico))$",
                              web.StaticFileHandler, {
                                  "path": PUBLIC_PATH
                              }), ("/", IndexHandler),
                             ("/api/(.+)$", ApiHandler, {
                                 "warrior": warrior
                             })]),
        #   flash_policy_port = 843,
        #   flash_policy_file = os.path.join(PUBLIC_PATH, "flashpolicy.xml"),
        socket_io_address=bind_address,
        socket_io_port=port_number,

        # settings for AuthenticatedApplication
        auth_enabled=lambda: (realize(http_password) or "").strip() != "",
        check_auth=lambda r, username, password:
        (password == realize(http_password) and
         (realize(http_username) or "").strip() in ["", username]),
        auth_realm="ArchiveTeam Warrior",
        skip_auth=[])

    application.listen(port_number, bind_address)
Beispiel #28
0
def make_router():
    conns = {
        'main': MainConnection,
        'logs': LogsConnection,
        'shell': ShellConnection,
    }
    if config.HAS_MANAGE:
        from mist.manage.sock import ManageLogsConnection
        conns['manage_logs'] = ManageLogsConnection

    return SockJSRouter(MultiplexConnection.get(**conns), '/socket')
Beispiel #29
0
    def get_routes(cls, service_registry, path=""):
        """Returns a list of routes matching this request handler,
        suitable for use in :py:class:`tornado.web.Application`.
        """

        # Since SockJS does not provide (AFAIK) a mechanism to pass arguments
        # to the SockJSConnection constructor, we use an ad-hoc subclass
        class ThisSockJSHandler(cls):
            def __init__(self, *args, **kwargs):
                cls.__init__(self, service_registry, *args, **kwargs)

        return SockJSRouter(ThisSockJSHandler, path).urls
Beispiel #30
0
 def __init__(self, default_host="", transforms=None, **settings):
     sockjs_path = settings.pop('sockjs_path', '/msg-listen')
     self.router = SockJSRouter(MessageNotifier, sockjs_path)
     self.router.__app__ = self
     super(MessageDeliveryApp,
           self).__init__(self.router.urls, default_host, transforms,
                          **settings)
     self._registry = {}
     self._redis_client = None
     self.init_redis()
     self._authenticator = TokenAuthentication()
     self._log('initialized')