Example #1
0
    def __call__(self,*args,**options):
        from thepian.conf import structure
        from os.path import join
        
        sys.path.append(structure.PROJECT_DIR)
        
        from thepian.conf import ensure_target_tree
        ensure_target_tree(structure.PROJECT_DIR)
        #TODO part add_themaestro functionality

        import logging
        LOG_FILENAME = join(structure.PROJECT_DIR,'testing.log')
        logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
                
        from mediaserver import Application, HTTPServer
        import tornado.httpserver
        import tornado.ioloop
        import tornado.autoreload
        
        # print "js dir =", structure.JS_DIR
        # tornado.options.parse_command_line()
        ioloop = tornado.ioloop.IOLoop.instance()

        sock_path = join(structure.PROJECT_DIR,"mediasite.sock")
        port_no = structure.MEDIASERVER_PORT
        if port_no:
            http_server = tornado.httpserver.HTTPServer(Application(ioloop=ioloop))
            http_server.listen(port_no)
        else:
            http_server = HTTPServer(Application(ioloop=ioloop))
            http_server.listen(0,address = sock_path)
        
        tornado.autoreload.start(io_loop=ioloop)
        ioloop.start()
Example #2
0
 def serve(self):
     self.app.listen(8888)
     ioloop = tornado.ioloop.IOLoop.instance()
     update_cb = tornado.ioloop.PeriodicCallback(
         self.update_status, 100, ioloop)
     update_cb.start()
     ioloop.start()
Example #3
0
    def __call__(self):
        if not os.path.exists(self.devtools_path):
            print "Error: devtools directory %s does not exist. Use 'ponyd update-devtools' to download a compatible version of Chrome Developer Tools." % self.devtools_path
            return

        if self.verbose:
            tornado.options.options.logging = 'debug'
            tornado.log.enable_pretty_logging(options=tornado.options.options)
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)

        application = tornado.web.Application([
            (r"/devtools/page/([0-9]*)/?", DevToolsHandler),
            (r"/lobby", LobbyHandler),
            (r"/device", DeviceHandler),
            (r"/devtools/(.*)", tornado.web.StaticFileHandler, {"path": self.devtools_path}),
            (r"/(.*)", tornado.web.StaticFileHandler, {"path": self.static_path, "default_filename": 'index.html'}),
        ])

        print "PonyGateway starting. Listening on http://%s:%s" % (self.listen_interface, self.listen_port)

        bonjour.register_service(self.bonjour_name, "_ponyd._tcp", self.listen_port)

        application.listen(self.listen_port, self.listen_interface)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.start()
Example #4
0
def run():

    tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")

    xmpp = XMPPHandler('*****@*****.**', 'popcorn', 'http://localhost:8080/callback')
    xmpp.register_plugin('xep_0030')

    if xmpp.connect():
        xmpp.process(block=False)

    application = tornado.web.Application([
            tornado.web.URLSpec(r"/send", SendHandler, {'xmpp': xmpp}),
            tornado.web.URLSpec(r"/callback", CallbackProxyHandler, {'callback': "http://localhost:8080/testcallback"}),
            tornado.web.URLSpec(r"/testcallback", TestCallbackHandler),
        ],
        )

    application.listen(8080)

    ioloop = tornado.ioloop.IOLoop.instance()

    try:
        ioloop.start()
    except KeyboardInterrupt:
        print "I'm out"
        xmpp.disconnect()    
Example #5
0
def main():
    pika_client = PikaClient()
    database={}
    database['g'] = 'f'
    database['gg'] = 'ff'
    database['ggg'] = 'gff'
    global g_port;
    
    application = tornado.web.Application(
    [(r'/sensor/.*', SensorHandler,dict(database=database)),(r'/.*',MainHandler,dict(database=database))],
#        [(r'/index.html',MainHandler)],
#        [(r'/tom/*',SensorHandler),(r'/index.html',MainHandler)],
#        **{'pika_client': pika_client, 'debug': True}

        #     **{'pika_client': pika_client, 'debug': True}
        #     [(r'/tom/*', Fib)],
             **{'pika_client': pika_client, 'debug': True}
    )
    try:
        port = int(sys.argv[1])  # $ python tornadoweb_pika.py 80
    except:
        port = 8000 
    g_port = port
    application.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_timeout(time.time() + .1, pika_client.connect)
    ioloop.start()
Example #6
0
    def __call__(self,*args,**options):
        from thepian.conf import structure
        from os.path import join
        
        from thepian.conf import ensure_target_tree
        ensure_target_tree(structure.PROJECT_DIR)
        #TODO part add_themaestro functionality

        sys.path.insert(0,structure.PROJECT_DIR)
        
        import logging
        print 'logging to testing.log', structure.DEFAULT_HOSTNAME
        LOG_FILENAME = join(structure.PROJECT_DIR,'testing.log')
        logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
        
        from mediaserver import Application, HTTPServer
        import tornado.httpserver
        import tornado.ioloop
        import tornado.autoreload
        
        ioloop = tornado.ioloop.IOLoop.instance()
        for n in structure.SITES:
            site = structure.SITES[n]
            print n+":", site["port"], site["package"]
            if site["package"] in ("tornado", "mediaserver"):
                http_server = tornado.httpserver.HTTPServer(Application(site,ioloop=ioloop))
                http_server.listen(site["port"])
        
        tornado.autoreload.start(io_loop=ioloop)
        ioloop.start()
Example #7
0
    def main(self):

        #settings passed to tornado app
        tornado_settings = {
            "template_path": settings.template_path,
            "static_path": settings.static_path,
            "cookie_secret": settings.cookie_secret,
            "login_url": settings.login_url,
        }

        #init a logger
        self.init_logging(settings.log)

        #routes
        routes = self.init_routes()

        self._application = web.Application(routes,**tornado_settings)

        http_server = httpserver.HTTPServer(self._application)
        http_server.listen(settings.port)

        Log.info("Ready and listening")

        ioloop = tornado.ioloop.IOLoop().instance()
        autoreload.start(ioloop)
        try:
            ioloop.start()
        except KeyboardInterrupt:
            pass
    def _actually_run(self):

        import logging
        import tornado.options

        logging.getLogger().setLevel(logging.INFO)
        tornado.options.enable_pretty_logging()

        import tornado.web
        import tornado.httpserver
        import tornado.ioloop
        import tornado.autoreload

#        import hashlib
#        import random
#        m = hashlib.md5()
#        m.update((str(random.random()) + str(random.random())).encode('utf-8'))
#        secret = m.digest()
#        print("SECRET:", secret)
        secret = random_key(100)
        secret = "reiujgerjregiuj"

        app = tornado.web.Application(self.handlers, static_path=self.static, cookie_secret=secret)

        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(self.port)
        logging.info("waiting for requests on http://%s:%d" % (self.hostname or "localhost", self.port))
        ioloop = tornado.ioloop.IOLoop.instance()
        tornado.autoreload.start(ioloop)
        ioloop.start()
Example #9
0
def main():
    try:
        """
        defining/parsing the options
        """
        define("port", default=8082, help="run on the given port", type=int)
        define("debug", default=False, help="run in debug mode", type=bool)
        tornado.options.parse_command_line()        
        logging.debug(options.logging)
        """
        initalising applications
        """ 
        app = MyApplication(options)

        """
        starting tornado server
        """
        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        ioloop = tornado.ioloop.IOLoop.instance()
        tornado.autoreload.add_reload_hook(app.reloadTasks)
        tornado.autoreload.start(ioloop)
        ioloop.start()

    except KeyboardInterrupt:
        pass
    except:
        print traceback.format_exc()
Example #10
0
def main():

    # Defines
    define("port", default=8082, help="run on the given port", type=int)
    define("log_level", default="INFO", type=str,
           help="[NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL]")
    define("dbconf", default="sqlite:///vanzilla.db", type=str,
           help="sqlalchemy db config string")
    define("mail_server", default="localhost", help="server mail", type=str)
    define("mail_from", default="", help="sender address for mail error reports", type=str)
    define("mail_to", default="", help="recipient addresses for mail error reports", type=str)
    define("root_ips", default=[], help="IPs with global access", type=list)
    define("promiscuous_load", default=False,
           help="load all apps, whether they are enabled or not", type=bool)

    options.parse_config_file("vanzilla.conf")
    options.parse_command_line()
    logging.debug(options.logging)

    # Initalising applications
    apps = AppsLoader(options)

    # Starting tornado server
    http_server = tornado.httpserver.HTTPServer(apps)
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()
    tornado.autoreload.add_reload_hook(apps.reload_tasks)
    tornado.autoreload.start(ioloop)
    ioloop.start()
Example #11
0
    def _actually_run(self, postbind_cb):

        import logging
        import tornado.options

        logging.getLogger().setLevel(logging.INFO)
        tornado.options.enable_pretty_logging()

        import tornado.web
        import tornado.httpserver
        import tornado.ioloop
        import tornado.autoreload

        import hashlib
        import random
        m = hashlib.md5()
        m.update(str(random.random()) + str(random.random()))
        secret = m.digest()

        app = tornado.web.Application(self.handlers, static_path=self.static, cookie_secret=secret)

        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(self.port)
        logging.info("waiting for requests on http://%s:%d" % (self.hostname or "localhost", self.port))
        ioloop = tornado.ioloop.IOLoop.instance()
        tornado.autoreload.start(ioloop)
	postbind_cb()
        ioloop.start()
Example #12
0
def main():
    tornado.options.parse_command_line()
    
    settings = {
        "template_path"     : config.TEMPLATE_PATH,
        "static_path"       : config.STATIC_PATH,
        "debug"             : config.DEBUG,
        "compress_response" : config.COMPRESS_RESPONSE,
        "cookie_secret"     : config.COOKIE_SECRET,
        "xsrf_cookies"      : config.XSRF_COOKIES,
        "login_url"         : config.LOGIN_URL
        }

    ioloop = tornado.ioloop.IOLoop.instance()
    
    app = tornado.web.Application(
            urls.handler_urls,
            **settings)

    app.db = momoko.Pool(
                dsn='dbname={} user={} password={} host={} port={}'.format(
                    config.DATABASE_NAME,
                    config.DATABASE_USER,
                    config.DATABASE_PASSWORD,
                    config.DATABASE_HOST,
                    config.DATABASE_PORT),
                cursor_factory=psycopg2.extras.RealDictCursor,
                size=1,
                ioloop=ioloop)
    future = app.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop.start()
Example #13
0
def run_proxy(bind, debug=False):
    #  /proxy/[?](?P<url>.*) # r'/proxy/[?](.*)' # r'/proxy/(.*)'
    handler = [(r'/proxy/', ProxyHandler, {})]
    app = tornado.web.Application(handler, debug=debug)
    app.listen(bind[1], bind[0])
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #14
0
def main():
    global server_state

    parse_command_line()

    ioloop = tornado.ioloop.IOLoop.instance()

    application = ExproxymentApplication()

    if options.soft_sticky and options.hard_sticky:
        raise Exception("can't be both soft_sticky and hard_sticky")

    if options.backends:
        backends = parse_backends(options.backends)
        backends = [Backend(host['host'], host['port'])
                    for host in backends]
        server_state.set_backends(backends)

    if options.weights:
        weights = parse_weights(options.weights)
        server_state.weights = weights

    HealthDaemon(ioloop).start()
    application.listen(options.port)

    logger.info("Starting on :%d", options.port)
    ioloop.start()
Example #15
0
def main():
    parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop().instance()
    autoreload.start(ioloop)
    ioloop.start()
Example #16
0
    def __init__(self):
        handlers = [
            (r"/", AllLists),
            (r"/create/", CreateLists),
        ]
        settings = dict(
            todo_title=u"ToDo",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            cookie_secret=base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes),
            login_url="/auth/login",
            debug=True,
        )

        super(Application, self).__init__(handlers, **settings)

        ioloop = tornado.ioloop.IOLoop.instance()
        self.db = momoko.Pool(
            dsn='dbname=todo user={0} password={1} '
                'host=localhost port=5432'.format(USERNAME, PASSWORD),
            size=1,
            ioloop=ioloop,
            cursor_factory=psycopg2.extras.RealDictCursor
        )

        future = self.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()
        future.result()
Example #17
0
def main():
    args = sys.argv
    cur_sys = system()
    file_name = GLOBALS["db_name"]+"-"+str(options.port)+".log"
    # if cur_sys == "Darwin":
    #     f = "/Users/"+os.getlogin()+"/Desktop/"+ file_name
    # elif cur_sys == "Linux":
    #     f = os.getcwd() + "/" + file_name
    # else:
    #     raise NotImplementedError
    # args.append("--log_file_prefix=" + f)
    # logging.basicConfig(filename=f, level=logging.DEBUG)

    tornado.options.parse_command_line()
    applicaton = Application()
    http_server = tornado.httpserver.HTTPServer(applicaton, xheaders=True)

    http_server.listen(options.port)
    print("="*50)
    print("initializing program with port : ", options.port)
    print("="*50)
    print("my ip is : ", socket.gethostbyname(socket.gethostname()))
    print("="*50)
    print("File system DEFAULT Encoding-type is : ", sys.getdefaultencoding())
    print("File system Encoding-type is : ", sys.getfilesystemencoding())
    print("="*50)
    logging.info("File system DEFAULT Encoding-type is : " + str(sys.getdefaultencoding()))
    logging.info("File system Encoding-type is : " +  str(sys.getfilesystemencoding()))

    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #18
0
def main():
	options.parse_command_line()
	# set up database connection
	client = pymongo.MongoClient(options.dbhost, options.dbport)
	database = client[options.dbname]
	# list of handlers
	handlers = []
	# generate list
	for handler in settings.handlers:
		# import the handler we need
		handler_class = __import__(handler)
		# register the URLS with the handler
		for routes in handler_class.routes:
			# each handler exports a urls list and class
			endpoint, class_name = routes
			url = ('/api' + endpoint, class_name, dict(database=database))
			# append to our handlers list
			handlers.append(url)

	ioloop = tornado.ioloop.IOLoop.instance()
	# register our handlers with our application and give it our settings
	application = tornado.web.Application(handlers, **settings.settings)
	http_server = tornado.httpserver.HTTPServer(application)
	# listen on port defined in options
	http_server.listen(options.port)
	#start ioloop
	ioloop.start()
Example #19
0
def run():
    logging.basicConfig(level=logging.DEBUG)
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
 def __init__(self, port=None, uri=None, debug=False):
     """Create http server, register callbacks and start immediatelly."""
     
     #nprint(uri, debug=debug)
     re_uri = re.compile('/' + uri )
     txt_uri = re_uri.pattern
     
     build_odl_topology(debug=debug)
     
     #nprint('patterned to ' + repr(txt_uri), debug=debug)
     logging.info('patterned to ' + repr(txt_uri))
     tuple_register2 = (txt_uri, CommandHandler2, dict(debug=debug))
     
     application = tornado.web.Application([
         tuple_register2,
         (r'/pathman/client/(.*)', tornado.web.StaticFileHandler, {"path": "client"}),
         (r'/pathman/topology', dataHandler),
     ], dict(debug=debug))
     """
         http_server = tornado.httpserver.HTTPServer(application, ssl_options={
         "certfile": os.path.join(data_dir, "server.crt"),
         "keyfile": os.path.join(data_dir, "server.key"),
         })
         """
     
     #http_server.listen(int(port))
     application.listen(int(port))
     ioloop = tornado.ioloop.IOLoop.instance()
     #nprint('Pathman REST API Launched on port %s' % port, debug=debug)
     logging.info('Pathman REST API Launched on port %s' % port)
     ioloop.start()
Example #21
0
def main():
    global sources, collector, collector_stream
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/echo",EchoWebSocket),
        (r"/p7",P7WebSocket)
    ], static_path=os.path.join(os.path.dirname(__file__), "client"))
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    
    
    # Start the time signal
    time_signal()
    # Start the fake source providers
    fake_sources()
    
    ioloop = tornado.ioloop.IOLoop.instance()
    
    # Set up collector
    collector = collectd.Reader(host="0.0.0.0")
    collector._sock.setblocking(0)
    ioloop.add_handler(collector._sock.fileno(), on_collect, ioloop.READ)

    ioloop.start()
Example #22
0
def main():
  global tornadoApp
  watermark.printWatermark()

  tornado.options.parse_command_line()

  sockJSRouter = sockjs.tornado.SockJSRouter(SockJSClient, '/socket')

  app = Application(sockJSRouter.urls)
  tornadoApp = app # globals cheating
  ioloop = tornado.ioloop.IOLoop.instance()

  # instance sockJS server
  # app.sockjs = sockjs.tornado.SockJSRouter(SockJSClient, '/socket')
  # for handler in app.sockjs.urls:
  #   print(handler)
  #   print("")
  #   # app.add_handlers(handler[0], handler[1])
  # app.add_handlers(r"*", app.sockjs.urls)

  # instance rabbitMQ server
  app.rabbit = RabbitClient(app, ioloop)
  app.listen(options.port)
  
  ioloop.add_timeout(500, app.rabbit.connect)
  ioloop.start()
Example #23
0
def main():
    """ main program, start local server """
    app = make_app()
    app.listen(8080)
    ioloop = tornado.ioloop.IOLoop.instance()
    signal.signal(signal.SIGINT, lambda sig, frame: ioloop.add_callback_from_signal(on_shutdown))
    ioloop.start()
Example #24
0
def main():
    app = LetSpotify()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()

    app.db = momoko.Pool(
        dsn=settings['dsn'],
        size=5,
        raise_connect_errors=False,
        reconnect_interval=50,
        ioloop=ioloop,
    )

    future = app.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    future.result()  # raises exception on connection error

    Service.users = Users(app.db)
    Service.facebook = FacebookAPI(app.db)
    Service.rooms = Rooms(app.db)
    Service.login_token = LoginToken(app.db)

    ioloop.start()
def run_service(port, address='0.0.0.0', configuration=None):
    ioloop = tornado.ioloop.IOLoop.instance()
    app = create_service()
    app.listen(port, address)
    app.logger.info('Started THC service on %s:%s', address, port)

    def discovered_service(index, fullname, host, port, txtRecord):
        app.logger.info('Found service: %s@%s:%s', fullname, host, port)

    def lost_service(index, name, regtype, domain):
        app.logger.info('Lost service: %s.%s@%s', name, regtype, domain)

    app.mdns = mdns_util.MDNS(ioloop)
    app.mdns.register('TurretHostController', '_thc_http._tcp', 'local', port)
    app.logger.info('Registered THC service.')

    app.mdns.discover('_thc_http._tcp', discovered_service, lost_service)
    app.logger.info('Listening for neighboring services.')

    try:
        ioloop.start()
    except KeyboardInterrupt:
        app.logger.info('Cancelling service discovery.')
        app.mdns.disable_discovery('_thc_http._tcp')
        app.logger.info('Cancelling service broadcast.')
        app.mdns.unregister('TurretHostController', '_thc_http._tcp', 'local',
                            port)

        app.logger.info('Shutting down.')
Example #26
0
def main():
    ioloop = tornado.ioloop.IOLoop.instance()

    http_server = tornado.httpserver.HTTPServer(Windseed())
    http_server.listen(8000, 'localhost')

    ioloop.start()
Example #27
0
 def __init__(self):
     self.handlers = routs
     ioloop = tornado.ioloop.IOLoop.instance()
     self.settings = dict(
         debug=config.debug,
         template_path=config.template_path,
         static_path=config.static_path,
         cookie_secret=config.cookie_secret,
         login_url=config.login_url
     )
     super(Application, self).__init__(self.handlers, **self.settings)
     self.db_async = momoko.Pool(
         dsn=config.get_db_url(options.db_name,
                               options.db_user_name,
                               options.db_host,
                               options.db_port,
                               options.db_password),
         size=1,
         ioloop=ioloop,
         cursor_factory=DictCursor
     )
     future = self.db_async.connect()
     ioloop.add_future(future, lambda x: ioloop.stop())
     ioloop.start()
     future.result()
def main():
    try:
        # create an api for the webserver
        api = HotTubAPI();
        app = tornado.web.Application(
            handlers=[
                (r"/images/(.*)", tornado.web.StaticFileHandler, {"path":"./images"}),
                (r"/css/(.*)", tornado.web.StaticFileHandler, {"path":"./css"}),
                (r"/js/(.*)", tornado.web.StaticFileHandler, {"path":"./js"}),
                (r"/*", IndexHandler),
                (r"/twilio.api", TwilioHandler, dict(api=api)),
                (r"/ws", WebSocketHandler, dict(api=api))
            ]
        )
        server = tornado.httpserver.HTTPServer(app)
        port = 9999
        server.listen(port,address="0.0.0.0")
        print "Tornado listening on port: %s" % port

        ioloop = tornado.ioloop.IOLoop.instance()
        set_ping(ioloop, timedelta(seconds=2))
        ioloop.start()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        api.close()
        server.stop();
Example #29
0
def main():
    tornado.options.parse_command_line()
    ioloop = tornado.ioloop.IOLoop.instance()
    http_server = tornado.httpserver.HTTPServer(GovLove(ioloop))
    http_server.listen(options.port)
    tornado.autoreload.start()
    ioloop.start()
Example #30
0
def start_server(args):
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret'
    app.jinja_env.globals['static'] = static

    blueprint.url_prefix = args.url_prefix
    app.register_blueprint(blueprint)

    # app.run(port=args.port, debug=args.debug)

    wsgi_app = tornado.wsgi.WSGIContainer(app)
    condajs_ws = sockjs.tornado.SockJSRouter(views.CondaJsWebSocketRouter, '/condajs_ws')
    routes = condajs_ws.urls
    routes.append((r".*", tornado.web.FallbackHandler, dict(fallback=wsgi_app)))
    application = tornado.web.Application(routes, debug=args.debug)

    try:
        application.listen(args.port)
    except OSError as e:
        print("There was an error starting the server:")
        print(e)
        return

    ioloop = tornado.ioloop.IOLoop.instance()
    if not args.debug:
        callback = lambda: webbrowser.open_new_tab('http://localhost:%s' % args.port)
        ioloop.add_callback(callback)
    ioloop.start()
Example #31
0
def run_proxy(port, start_ioloop=True):
    """
    Run proxy on the specified port. If start_ioloop is True (default),
    the tornado IOLoop will be started immediately.
    """
    app = tornado.web.Application([
        (r'.*', ProxyHandler),
    ])
    app.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    if start_ioloop:
        ioloop.start()
Example #32
0
def Start():
    tornado.log.logging.info("Server starting at {0}".format(
        server.config.hostname))

    matchmaker.StartPolling()

    routes = server.generated_routes.GetRoutes()
    routes.append(
        (r'/_01/rpc/GetEvent', server.services.event_service.GetEventHandler))
    app.add_handlers(r'.*', routes)
    app.listen(server.config.port)
    ioloop.start()
Example #33
0
def run_forever(application, port=None, num_processes=1):
    """run server
    port='8888'
    port='8801, 8802, 8803'
    """

    logger = logging.getLogger('appserver')

    if sys.platform == 'win32':
        title = 'Tornado'
        from .win32 import set_windows_console_title, set_windows_console_size
        set_windows_console_title(title)
        set_windows_console_size(120, 24)

    ports = []
    if port:
        if isinstance(port, str):
            ports.extends(re.split('[,;\s]+', port))
        elif isinstance(port, Mapping):
            for p in port:
                ports.append(p)
        elif isinstance(port, int):
            ports.append(port)

    if not ports:
        ports.append(8888)

    application.setup()

    if num_processes <= 0:
        import multiprocessing
        num_processes = multiprocessing.cpu_count()

    if application.settings.get('debug', False) and num_processes != 1:
        num_processes = 1
        logger.warn('In debug mode, it should be in single process mode')

    httpserver = tornado.httpserver.HTTPServer(application)
    for port in ports:
        httpserver.bind(port)
    httpserver.start(num_processes)

    ioloop = tornado.ioloop.IOLoop.instance()

    def sigint_int(s, f):
        logger.info('server is shutting')
        ioloop.add_callback(ioloop.stop)

    signal.signal(signal.SIGINT, sigint_int)

    print('Server Started. Press <CRTL-C> to kill server')
    ioloop.start()  # 启动服务器
    logger.info('server stopped')
Example #34
0
def run(port=config.GLOBAL_SETTINGS['default_port']):
    # pdb.set_trace()
    load_config()
    import routes
    init()

    application = tornado.web.Application(routes.URL_PATTERN,
                                          **config.TORNADO_SETTINGS)
    application.listen(port)
    print port
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #35
0
def run(port=8888, processes=4, debug=False, static=False, pid=None):
    '''
    Runs an instance of the JSonic server.
    
    :param port: Server port
    :type port: int
    :param processes: Number of worker processes for synthesis and caching
        operations. Defaults to 4.
    :type processes: int
    :param debug: True to enable automatic server reloading for debugging.
        Defaults to False.
    :type debug: bool
    :param static: True to serve ../ as static files to allow running of the
        example code and downloading of the JS directly from this server. 
        False to disable static file sharing when this server should handle the
        JSonic REST API only.
    :type static: bool
    :param pid: Name of a pid file to write if launching as a daemon or None
        to run in the foreground
    :type pid: string
    '''
    if pid is not None:
        # log to file
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(levelname)s %(message)s',
                            filename='jsonic.log',
                            filemode='w')
        # launch as a daemon and write the pid file
        import daemon
        daemon.daemonize(pid)
    else:
        # log to console
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(levelname)s %(message)s')
    synthesizer.init()
    kwargs = {}
    kwargs['pool'] = pool = multiprocessing.Pool(processes=processes)
    if static:
        # serve static files for debugging purposes
        kwargs['static_path'] = os.path.join(os.path.dirname(__file__), "../")
    application = tornado.web.Application(
        [(r'/engine', EngineHandler),
         (r'/engine/([a-zA-Z0-9]+)', EngineHandler), (r'/synth', SynthHandler),
         (r'/files/([a-f0-9]+-[a-f0-9]+\..*)', FilesHandler, {
             'path': './files'
         }), (r'/version', VersionHandler)],
        debug=debug,
        **kwargs)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #36
0
def run_proxy(port,
              methods=['GET', 'POST'], 
              req_callback=DEFAULT_CALLBACK,
              resp_callback=DEFAULT_CALLBACK,
              err_callback=DEFAULT_CALLBACK,
              test_ssl=False,
              start_ioloop=True,
              debug_level=0):

    """
    Run proxy on the specified port. 

    methods: the HTTP methods this proxy will support
    req_callback: a callback that is passed a RequestObj that it should
        modify and then return
    resp_callback: a callback that is given a ResponseObj that it should
        modify and then return
    err_callback: in the case of an error, this callback will be called.
        there's no difference between how this and the resp_callback are 
        used.
    test_ssl: if true, will wrap the socket in an self signed ssl cert
    start_ioloop: if True (default), the tornado IOLoop will be started 
        immediately.
    debug_level: 0 no debug, 1 basic, 2 verbose
    """

    app = tornado.web.Application([
        (r'.*', _make_proxy(methods=methods,
                            req_callback=req_callback,
                            resp_callback=resp_callback,
                            err_callback=err_callback,
                            debug_level=debug_level)),
    ])

    if test_ssl:
        this_dir, this_filename = os.path.split(__file__)
        kwargs = {
            "ssl_options": {
                "certfile": os.path.join(this_dir, "data", "test.crt"),
                "keyfile": os.path.join(this_dir, "data", "test.key"),
            }
        }
    else:
        kwargs = {}

    http_server = tornado.httpserver.HTTPServer(app, **kwargs)
    http_server.listen(port)     
    ioloop = tornado.ioloop.IOLoop.instance()
    if start_ioloop:
        print ("Starting HTTP proxy on port %d" % port)
        ioloop.start()
    return app
def run_proxy(eth, start_ioloop=True):
    """
    Run proxy on the specified port. If start_ioloop is True (default),
    the tornado IOLoop will be started immediately.
    """
    app = tornado.web.Application([
        ('/stat', StatHandler),
        (r'\S+', ProxyHandler),
    ])
    app.listen(port=eth[1], address=eth[0])
    ioloop = tornado.ioloop.IOLoop.instance()
    if start_ioloop:
        ioloop.start()
Example #38
0
def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    try:
        ioloop = tornado.ioloop.IOLoop.instance()
        sync_db = mongoclient.fbt
        async_db = motorclient.fbt
        OnlineResources.initialize(sync_db, async_db)
        ioloop.start()
    except Exception, e:
        print e
        print "OK. I will exit..."
Example #39
0
def main():

    application = get_app()
    tornado.options.parse_command_line()
    server = HTTPServer(application)  #, ssl_options=get_ssl())
    server.listen(8000)
    logging.info('starting server')
    ioloop = get_ioloop()
    try:
        ioloop.start()
    except KeyboardInterrupt:
        stop_server(server)
        logging.info('stopping server')
Example #40
0
def test_wraps():
    def exit_callback():
        client = tornado.httpclient.AsyncHTTPClient()
        ret = client.fetch('http://localhost:8000/home/welcome')
        nose.tools.assert_is_not_none(ret)
        tornado.ioloop.IOLoop.current().stop()

    httpserver = tornado.httpserver.HTTPServer(
        blueprint.wraps(tornado.web.Application()))
    httpserver.listen(8000)
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_timeout(ioloop.time() + 1, exit_callback)
    ioloop.start()
Example #41
0
 def run(self):
     ioloop = tornado.ioloop.IOLoop()
     ioloop.clear_current()
     ioloop.make_current()
     application = tornado.web.Application(self.handlers, gzip=True)
     # If tornado version is 5.0 or greater, io_loop arg does not exist
     if tornado.version_info[0] < 5:
         self.server = tornado.httpserver.HTTPServer(application,
                                                     io_loop=ioloop)
     else:
         self.server = tornado.httpserver.HTTPServer(application)
     self.server.listen(self.port)
     ioloop.start()
Example #42
0
def main():

    tornado.options.options.log_file_prefix = '/tmp/load_test.log'
    tornado.options.parse_command_line()

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)

    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_callback(init)
    logger.info("started")
    ioloop.start()
    logger.info("Exit...")
Example #43
0
def main():
    debug = int(os.environ.get("AS_DEV", "0"))
    logging.basicConfig(
        format=f"%(asctime)s captain:  %(levelname)s: %(message)s",
        level=logging.DEBUG if debug else logging.INFO,
    )

    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_callback(signal.signal, signal.SIGTERM, handle_sigterm)
    ioloop.add_future(asyncio.ensure_future(async_main()), lambda _: None)

    logging.debug("Entering the IOLoop...")
    ioloop.start()
Example #44
0
def run(scenario_dirs, max_capacity_mb=500, port=8081):
    app = make_app(scenario_dirs, max_capacity_mb)
    app.listen(port)
    logging.debug(f"Envision listening on port={port}")

    ioloop = tornado.ioloop.IOLoop.current()
    signal.signal(
        signal.SIGINT,
        lambda signal, _: ioloop.add_callback_from_signal(on_shutdown))
    signal.signal(
        signal.SIGTERM,
        lambda signal, _: ioloop.add_callback_from_signal(on_shutdown))
    ioloop.start()
Example #45
0
def main():
    options.parse_command_line()
    from api.v1.urls import urls
    from tornado.web import Application
    import tornado.ioloop
    app = Application(urls, debug=options.debug)
    app.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()
    Cache.connect(endpoint_url='http://localhost:8000')
    Persis.connect()
    Rds.connect()
    ioloop.spawn_callback(sync_record_data)
    ioloop.start()
Example #46
0
def run_proxy(system_config: Config, engine: AbstractEngine, http_port, https_port, ssl_options, start_ioloop=True):
    """
    Run proxy on the specified port. If start_ioloop is True (default),
    the tornado IOLoop will be started immediately.
    """

    start_https_msg = ""

    if https_port:
        start_https_msg = f"\n    https://{system_config['proxy']['url']}:{system_config['proxy']['ports']['https']:d}"

    logger.info(
        f"Starting Riptide Proxy at: \n"
        f"    http://{system_config['proxy']['url']}:{system_config['proxy']['ports']['http']:d}{start_https_msg}"
    )

    # Load projects initially
    projects = load_projects()

    # Configure global storage
    use_compression = True if 'compression' in system_config['proxy'] and system_config['proxy']['compression'] else False
    storage = {
        "config": system_config["proxy"],
        "engine": engine,
        "runtime_storage": RuntimeStorage(
            projects_mapping=projects, project_cache={}, ip_cache={}, engine=engine, use_compression=use_compression
        )
    }

    # Configure Routes
    app = tornado.web.Application(load_plugin_routes(system_config, engine, https_port, storage["runtime_storage"]) + [
        # http
        (RiptideNoWebSocketMatcher(r'^(?!/___riptide_proxy_ws).*$'), ProxyHttpHandler, storage),
        # Any non-autostart websockets
        (r'^(?!/___riptide_proxy_ws).*$', ProxyWebsocketHandler, storage),
        # autostart websockets
        (r'/___riptide_proxy_ws', AutostartHandler, storage),
    ], template_path=get_resources())

    # xheaders enables parsing of X-Forwarded-Ip etc. headers
    app.listen(http_port, xheaders=True)

    # Prepare HTTPS
    if https_port:
        https_app = tornado.httpserver.HTTPServer(app, ssl_options=ssl_options, xheaders=True)
        https_app.listen(https_port)

    # Start!
    ioloop = tornado.ioloop.IOLoop.current()
    if start_ioloop:
        ioloop.start()
Example #47
0
def main():
    parse_command_line()
    urls = []
    settings = {
        'debug': True,
        'db_conn': None,
    }

    application = tornado.web.Application(urls, **settings)
    logging.info("start application on port %s" % options.port)
    application.listen(options.port)

    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #48
0
    def run(self):

        ioloop = tornado.ioloop.IOLoop()

        application = get_webserver_application()  #tornado.web.Application
        http_server_api = tornado.httpserver.HTTPServer(application)
        try:
            http_server_api.listen(80)
            print("Starting webserver on " + str(self.ip))

            ioloop.start()
        except OSError:
            print("Already connected to this address or address blocked " +
                  str(self.ip))
Example #49
0
def main():  # pragma nocover
    """ parse command line, make and start """
    parse_command_line()
    app = make_app()
    app.listen(options.port)
    log.info('listening on port: %s', options.port)
    if options.debug:
        log.warning('running in debug mode')
    ioloop = tornado.ioloop.IOLoop.current()
    try:
        ioloop.start()
    except (KeyboardInterrupt, SystemExit):
        # graceful shutdown
        ioloop.stop()
Example #50
0
def main(port, shell):
    """Create and setup a new tornado server."""
    LOGGER.info("Server is now at: 127.0.0.1:{}".format(port))
    LOGGER.info('Shell: {0}'.format(shell))
    application = create_app(shell)
    ioloop = tornado.ioloop.IOLoop.instance()
    application.listen(port, address='127.0.0.1')
    try:
        ioloop.start()
    except KeyboardInterrupt:
        pass
    finally:
        LOGGER.info("Closing server...\n")
        tornado.ioloop.IOLoop.instance().stop()
Example #51
0
def main():
    try:
        #check database and create tables if doesn't exist
        checkDB()

        #setup the application with port 8888
        app = Application()
        app.listen(8888)
        ioloop = tornado.ioloop.IOLoop.instance()
        #prevent thread blocking with 2 seconds timeout
        set_ping(ioloop, datetime.timedelta(seconds=2))
        ioloop.start()
    except KeyboardInterrupt:
        tornado.ioloop.IOLoop.instance().stop()
Example #52
0
def main(handlers, port=None, config=None):
    """Site startup boilerplate."""
    magpyconf = MagpyConfigParser(config)
    if not port:
        port = getattr(magpyconf, 'port', 8000)

    tornado.options.parse_command_line()
    ioloop = tornado.ioloop.IOLoop.instance()
    http_server = tornado.httpserver.HTTPServer(
        App(ioloop, handlers, magpyconf.cookie_secret, magpyconf.databases,
            magpyconf.google_oauth, magpyconf.login_redirect))
    http_server.listen(port)
    tornado.autoreload.start()
    ioloop.start()
Example #53
0
def main():
    import tornado.options
    tornado.options.parse_command_line()
    ConfigurationManager.load()
    config = ConfigurationManager.get_config()
    service_config = config.get("messagebus_service")

    routes = [(service_config.get('route'), WebsocketEventHandler)]

    application = tornado.web.Application(routes, **settings)

    application.listen(service_config.get("port"), service_config.get("host"))
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
	def main(cls):
		parser = argparse.ArgumentParser(prog='python -m univention.management.server')
		parser.parse_args()
		tornado.httpclient.AsyncHTTPClient.configure('tornado.curl_httpclient.CurlAsyncHTTPClient')
		tornado.locale.load_gettext_translations('/usr/share/locale', 'univention-management-console-module-udm')
		cls.start_processes()
		cls.register_signal_handlers()
		app = tornado.web.Application([
			(r'.*', cls),
		], debug=False, serve_traceback=True,
		)
		app.listen(int(ucr.get('umc/server/port', 8888)))
		ioloop = tornado.ioloop.IOLoop.instance()
		ioloop.start()
Example #55
0
def main():
    app = tornado.web.Application(
        quiz.routes.ROUTES,
        cookie_secret=quiz.config.COOKIE_SECRET,
        login_url="/login",
        template_path=os.path.join(os.path.dirname(__file__),
                                   quiz.config.TEMPLATE_PATH),
        static_path=os.path.join(os.path.dirname(__file__),
                                 quiz.config.STATIC_PATH),
        xsrf_cookies=True,
        debug=True)
    app.listen(quiz.config.PORT)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.start()
Example #56
0
def start() :
    application = Application(drop=options.drop)
    http_server = tornado.httpserver.HTTPServer(application)
    try :
        http_server.listen(app_config.port)
    except :
        traceback.print_exc()
        os._exit(1) # since it otherwise hangs
    Settings.logging.info("Started news_crowdsourcer in %s mode." % app_config.environment)
    ioloop = tornado.ioloop.IOLoop.instance()
    try :
        ioloop.start()
    except :
        ioloop.add_callback(lambda : ioloop.stop())
Example #57
0
    def _listen(self, sid):
        pid = os.getpid()
        pid_file = open(
            "%s/backend_%s.pid" % (config.get_directory("pid_dir"),
                                   config.station_id_friendly[sid].lower()),
            'w')
        pid_file.write(str(pid))
        pid_file.close()

        db.connect()
        cache.connect()
        zeromq.init_pub()
        log.init(
            "%s/rw_%s.log" % (config.get_directory("log_dir"),
                              config.station_id_friendly[sid].lower()),
            config.get("log_level"))
        memory_trace.setup(config.station_id_friendly[sid].lower())

        if config.test_mode:
            playlist.remove_all_locks(sid)

        # (r"/refresh/([0-9]+)", RefreshScheduleRequest)
        app = tornado.web.Application([
            (r"/advance/([0-9]+)", AdvanceScheduleRequest),
        ],
                                      debug=(config.test_mode
                                             or config.get("developer_mode")))

        port = int(config.get("backend_port")) + sid
        server = tornado.httpserver.HTTPServer(app)
        server.listen(port, address='127.0.0.1')

        for station_id in config.station_ids:
            playlist.prepare_cooldown_algorithm(station_id)
        schedule.load()
        log.debug(
            "start",
            "Backend server started, station %s port %s, ready to go." %
            (config.station_id_friendly[sid], port))

        ioloop = tornado.ioloop.IOLoop.instance()
        try:
            ioloop.start()
        finally:
            ioloop.stop()
            server.stop()
            db.close()
            log.info("stop", "Backend has been shutdown.")
            log.close()
Example #58
0
def main():
    global db
    global log_db
    # if os.path.isfile("login_token.json") and os.path.isfile("login_user.json"):
    #     in_token = open("login_token.json")
    #     login_token = json.load(in_token)
    #     in_token.close()
    #     RedisHandler.f_hmset(LOGIN_T, login_token)
    #     in_user = open("login_user.json")
    #     SocketHandler.login_user = json.load(in_user)
    #     #util.RedisHandle.f_hmset(LOGIN_U, login_user)
    #     in_user.close()
    #     os.rename("login_token.json", "login_token"+str(long(time()))+".json")
    #     os.rename("login_user.json", "login_user"+str(long(time()))+".json")
    access = logging.getLogger("tornado.access")
    access.addHandler(NullHandler())
    access.propagate = False
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    try:
        util.MemCache.load(str(options.port))
        #util.RedisHandle.f_delete(*[CLIENT_UID_USER,CLIENT_USER_UID,USER_ONLINE_AT,USER_IP_LIST,HTTP_SERVER_INFO])
        ioloop = tornado.ioloop.IOLoop.instance()
        #db_client = motor.MotorReplicaSetClient(hosts_or_uri="127.0.0.1:27017",replicaSet='fbt_repl',io_loop=ioloop)
        #db_client.read_preference = ReadPreference.SECONDARY_ONLY
        #db = db_client.fbt
        #log_db = motor.MotorClient().fbt_log
        #log_db = db_client.fbt_log
        db = motorclient.fbt
        log_db = motorclient.fbt_log
        ResourceStoreManager.set_db(db)
        FBCoinManager.set_db(db)
        UserManager.set_db(db)
        msg_handle.set_db(db)
        LogForUser.set_db(log_db)
        #FBCoinManager.set_update_fb_callback(SocketHandler.update_fb)
        #FBRankManager.initialize() #load rank info from file
        #FBRankTimer.set_io_loop(ioloop)
        #FBRankTimer.run() #backup the weekly and monthly rank

        SocketHandler.set_io_loop(ioloop)
        SocketHandler.init()
        ioloop.add_timeout(
            long(time()) + 3600, lambda: SocketHandler.check_on_line())
        ioloop.start()
    except Exception, e:
        print e
        print "OK. I will exit..."
Example #59
0
def run_proxy(port, start_ioloop=True):
    """
    Run proxy on the specified port. If start_ioloop is True (default),
    the tornado IOLoop will be started immediately.
    """
    import asyncio
    if sys.platform == 'win32':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    app = tornado.web.Application([
        (r'.*', ProxyHandler),
    ], debug=True)
    app.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    if start_ioloop:
        ioloop.start()
Example #60
0
def main(ssl=False):
  tornado.options.parse_command_line()
  app = Application()
  if ssl:
    http_server = tornado.httpserver.HTTPServer(app, ssl_options={
      "certfile": os.path.expanduser("~/etc/key/server.crt"),
      "keyfile": os.path.expanduser("~/etc/key/server.key"),
    })
  else:
    http_server = tornado.httpserver.HTTPServer(app)
  http_server.listen(options.port)
  global ioloop
  ioloop = tornado.ioloop.IOLoop.instance()
  tornado.ioloop.PeriodicCallback(checkOnlineUsers, POLL_TIME * 100).start()
  ioloop.start()