Exemple #1
0
    def _prepare_web_app(self):
        ''' Config and Views'''
        logger.debug("tornado web app setup")

        self._web_app = Application(
            gzip=self.config.gzip,
            debug=self.config.debug,
            static_path=self.config.static_path,
            handlers=self.handlers,
            cookie_secret=self.config.cookie_secret,
            login_url=self.config.login_url,
            xsrf_cookies=self.config.xsrf_cookies,
            template_path=self.config.template_path,
        )

        if self.config.debug and not self.config.autoreload:
            # FIXME hack to disable autoreload when debug is True
            from tornado import autoreload
            autoreload._reload_attempted = True
            autoreload._reload = lambda: None

        if self.config.ssl:
            ssl_options = dict(
                certfile=os.path.expanduser(self.config.ssl_certificate),
                keyfile=os.path.expanduser(self.config.ssl_certificate_key))
            self.server = HTTPServer(self._web_app, ssl_options=ssl_options)
        else:
            self.server = HTTPServer(self._web_app)
Exemple #2
0
    def run(self):
        if self.enable_https:
            protocol = "https"
            self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key})
        else:
            protocol = "http"
            self.server = HTTPServer(self.app)

        logger.log(u"Starting SickRage on " + protocol + "://" + str(self.options['host']) + ":" + str(
            self.options['port']) + "/")

        try:
            self.server.listen(self.options['port'], self.options['host'])
        except:
            etype, evalue, etb = sys.exc_info()
            logger.log(
                "Could not start webserver on %s. Excpeption: %s, Error: %s" % (self.options['port'], etype, evalue),
                logger.ERROR)
            return

        try:
            self.io_loop.start()
            self.io_loop.close(True)
        except (IOError, ValueError):
            # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload.
            pass
class Proxy:

    def __init__(self, proxy_port, app_port):
        self._proxy_port = proxy_port
        self._app_port = app_port

    def _create_app(self):
        app = tornado.web.Application(
            [
                (r"/.*", MainHandler, dict(app_port=self._app_port))
            ],
            xsrf_cookies=False,
            debug=True)
        return app

    def serve_forever(self):
        app = self._create_app()
        self._server = HTTPServer(app)
        self._server.listen(port=self._proxy_port, address='127.0.0.1')
        self._ioloop = tornado.ioloop.IOLoop.instance()
        self._ioloop.start()  # this is a blocking call, server has stopped on next line
        self._ioloop = None

    def shutdown(self):
        if self._ioloop:
            self._server.stop()
            self._ioloop.stop()

    def run_on_a_thread(self):
        process = multiprocessing.Process(target=self.serve_forever)
        process.start()
        time.sleep(1)  # just let it start
        return lambda: process.terminate()
Exemple #4
0
def http_server(io_loop, listener, ssl_options=None, registration_db=None):

    # initialize the registry
    registration_db = registration_db or Registry(loop=io_loop._loop)

    # lookup routes
    user_settings = { "registration_db": registration_db }
    lookup_router = sockjs.SockJSRouter(LookupConnection, "/lookup",
            io_loop=io_loop, user_settings=user_settings)

    # initialize handlers
    handlers = [
            (r'/', WelcomeHandler),
            (r'/ping', PingHandler),
            (r'/version', VersionHandler),
            (r'/nodes', NodesHandler),
            (r'/sessions', SessionsHandler),
            (r'/sessions/([^/]+)', SessionsHandler),
            (r'/jobs', JobsHandler),
            (r'/findJob', FindJobHandler),
            (r'/findSession', FindSessionHandler),
            (r'/ws', LookupWebSocket)] + lookup_router.urls

    # initialize the server
    app = Application(handlers, registration_db=registration_db)
    server = HTTPServer(app, io_loop=io_loop, ssl_options=ssl_options)
    server.add_sockets(listener)
    return server
Exemple #5
0
def _go(args):
    app = create_app(args)
    port = app.app.config['PORT']
    app.setup()

    mode = app.app.config['SERVER']
    if args.mode == 'dev':
        mode = 'development'
        app.app.config['DEBUG'] = True
    elif args.mode == 'prd':
        mode = 'production'

    if mode == 'development':
        print("Starting development server on port %d..." % port)
        app.app.run(port=port)
    elif mode == 'production':
        appl = WSGIContainer(app.app)
        if 'SSL_KEY' in app.app.config:
            http_server = HTTPServer(appl, ssl_options={
                "certfile": app.app.config['SSL_CRT'],
                "keyfile": app.app.config['SSL_KEY'],
            })
        else:
            http_server = HTTPServer(appl)
        http_server.listen(port)
        print("Starting production server on port %d..." % port)
        IOLoop.instance().start()
    else:
        sys.stderr.write("Invalid SERVER setting '%s', aborting.\n" % args.mode)
        sys.exit(1)
Exemple #6
0
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        
	tapp = Application([
		(r"/ws", AdminWebSocket),
                (r".*", FallbackHandler, dict(fallback=WSGIContainer(admin_app)))
	])

	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)
	# listen on the interfaces
	if self.interfaces != "":
	    intf = self.interfaces.split(',')
	    for ip in get_ip_for_interfaces(intf):
	        self.http_server.listen(int(self.port), address=ip)
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
Exemple #7
0
    def __init__(self, listener, application=None, backlog=2048,
                 socket_type=socket.SOCK_STREAM,
                 address_family=socket.AF_INET):
        self.address_family = address_family
        self.socket_type = socket_type
        host, port = listener

        if isinstance(application, Application):
            self._server = HTTPServer(application)
        elif isinstance(application, TCPServer):
            self._server = application
        elif callable(application):
            tapp = tornado.wsgi.WSGIContainer(application)
            self._server = HTTPServer(tapp)
        else:
            raise TypeError(
                "Unsupported application type: %r" % (application,))

        if host.startswith('fd://'):
            fd = int(host.split('://')[1])
            set_close_exec(fd)
            sock = socket.fromfd(fd, address_family, socket_type)
            sock.setblocking(0)
            socks = [sock]
        elif self.address_family == socket.AF_UNIX:
            filename = host[len('unix:'):]
            sock = tornado.netutil.bind_unix_socket(filename, backlog=backlog)
            socks = [sock]
        else:
            socks = tornado.netutil.bind_sockets(
                port, host, address_family, backlog)
        self._server.add_sockets(socks)
        self.application = application
Exemple #8
0
def start_server():
    ''' Main entry point for the application '''
    if options.debug:
        logging.warn("%sDebug mode is enabled; DO NOT USE THIS IN PRODUCTION%s" % (
            bold + R, W
        ))
    # Setup server object
    if options.ssl:
        server = HTTPServer(app,
                            ssl_options={
                                "certfile": options.certfile,
                                "keyfile": options.keyfile,
                            },
                            xheaders=options.x_headers
                            )
    else:
        server = HTTPServer(app, xheaders=options.x_headers)
    sockets = netutil.bind_sockets(options.listen_port)
    server.add_sockets(sockets)
    try:
        io_loop.start()
    except KeyboardInterrupt:
        sys.stdout.write('\r' + WARN + 'Shutdown Everything!\n')
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        _exit(0)
Exemple #9
0
def runserver():
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    
    loop = tornado.ioloop.IOLoop.instance()
    
    def shutdown():
        logging.info('Server stopping ...')
        http_server.stop()
        
        logging.info('IOLoop wil  be terminate in 1 seconds')   
        deadline = time.time() + 1
        
        def terminate():
            now = time.time()
            
            if now < deadline and (loop._callbacks or loop._timeouts):
                loop.add_timeout(now + 1, terminate)
            else:
                loop.stop()
                logging.info('Server shutdown')
        
        terminate()
    
    def sig_handler(sig, frame):
        logging.warn('Caught signal:%s', sig)
        loop.add_callback(shutdown)
    
    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)
    
    logging.info('Server running on http://0.0.0.0:%d'%(options.port))
    loop.start()
Exemple #10
0
    def run(self):
        if self.enable_https:
            protocol = "https"
            self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key})
        else:
            protocol = "http"
            self.server = HTTPServer(self.app)

        logger.log(
            u"Starting SickRage on "
            + protocol
            + "://"
            + str(self.options["host"])
            + ":"
            + str(self.options["port"])
            + "/"
        )

        try:
            self.server.listen(self.options["port"], self.options["host"])
        except Exception:
            if sickbeard.LAUNCH_BROWSER and not self.daemon:
                sickbeard.launchBrowser(
                    "https" if sickbeard.ENABLE_HTTPS else "http", self.options["port"], sickbeard.WEB_ROOT
                )
                logger.log(u"Launching browser and exiting")
            logger.log(u"Could not start webserver on port {0}, already in use!".format(self.options["port"]))
            os._exit(1)  # pylint: disable=protected-access

        try:
            self.io_loop.start()
            self.io_loop.close(True)
        except (IOError, ValueError):
            # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload.
            pass
def startTornado():
    global http_server
    http_server = HTTPServer(WSGIContainer(create_app("settings.DevelopmentConfig")))
    http_server.listen(80)
    ioloop = IOLoop.instance()
    autoreload.start(ioloop)
    ioloop.start()
Exemple #12
0
 def build_webapp_thread(self, port=26000):
     app.session = self
     http_server = HTTPServer(WSGIContainer(app))
     http_server.listen(port)
     flask_thread = threading.Thread(target=IOLoop.instance().start)
     flask_thread.daemon = True
     return flask_thread
Exemple #13
0
def zoe_web_main() -> int:
    """
    This is the entry point for the Zoe Web script.
    :return: int
    """
    load_configuration()
    args = get_conf()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("tornado").setLevel(logging.DEBUG)

    log.info("Starting HTTP server...")
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
    app.secret_key = args.cookie_secret

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(args.listen_port, args.listen_address)
    ioloop = IOLoop.instance()
    try:
        ioloop.start()
    except KeyboardInterrupt:
        print("CTRL-C detected, terminating")
Exemple #14
0
def main():
    global http_server

    try:
        signal(SIGTERM, on_signal)

        parse_command_line()
        if options.config != None:
            parse_config_file(options.config)

        path = join(dirname(__file__), "templates")

        application = Application(
            [(r"/", IndexHandler), (r"/stock", StockHandler)],
            template_path=path,
            static_path=join(dirname(__file__), "static"),
        )

        application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name]

        http_server = HTTPServer(application)
        http_server.listen(options.port, options.address)
        log().info("server listening on port %s:%d" % (options.address, options.port))
        if log().isEnabledFor(DEBUG):
            log().debug("autoreload enabled")
            tornado.autoreload.start()
        IOLoop.instance().start()

    except KeyboardInterrupt:
        log().info("exiting...")

    except BaseException as ex:
        log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines())))
        exit(1)
def main():
    '''Create server, begin IOLoop 
    '''
    tornado.options.parse_command_line()
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    IOLoop.instance().start()
Exemple #16
0
def main():

    global NODES_DATABASE

    ###--log_file_prefix=./server.log
    ###--logging=debug
    enable_pretty_logging()
    options.parse_command_line()

    cur_dir = os.path.split(os.path.realpath(__file__))[0]

    if options.mode == 'online':
        fetch_node_info()
    else:
        db_file_path = '%s/nodes_db_lean.json' % cur_dir

        if not os.path.exists(db_file_path):
            fetch_node_info()
        else:
            NODES_DATABASE = json.load(open(db_file_path))
            gen_log.info('load nodes database from json done!')
            gen_log.debug(NODES_DATABASE)


    app = myApplication()
    http_server = HTTPServer(app)
    http_server.listen(8080)


    tcp_server = DeviceServer()
    tcp_server.listen(8000)

    gen_log.info("server's running in lean mode ...")

    ioloop.IOLoop.current().start()
Exemple #17
0
    def _create_http_server(self,port_start,port_end,ioloop):
        import socket

        server = HTTPServer(self.application, io_loop=ioloop)

        for portnum in range(port_start, port_end):
            try:

                server.listen(portnum,
                                    address=self._address_requested)
                logger.info('Server listening on port {0}'.format(portnum))
                self._port_used = portnum
                self._address_used = self._address_requested

                return server, portnum

            except socket.error as  e:
                # try remaining ports if port used, raise otherwise
                if e.errno != errno.EADDRINUSE or portnum == port_end-1:
                    logger.error(str(e)) # pragma: no cover
                    try:
                        server.stop()
                    except:
                        pass
                    raise
Exemple #18
0
def main():
    port = int(os.environ['CTPLOT_PORT']) if 'CTPLOT_PORT' in os.environ else 8080
    print 'listening on', port

    http_server = HTTPServer(WSGIContainer(application))
    http_server.listen(port)
    IOLoop.instance().start()
def run_tornado(addr, port, reload=False):
    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Print listening address and port to command line
    if addr == '0.0.0.0':
        url_string = _("the machine's local ip address")
    else:
        url_string = 'http://%s:%s' % (addr, port)
    print _("Starting OpenSlides' tornado webserver listening to %(url_string)s") % {'url_string': url_string}

    socket_js_router = SockJSRouter(ProjectorSocketHandler, '/projector/socket')

    # Start the application
    app = WSGIContainer(Django_WSGIHandler())
    tornado_app = Application(socket_js_router.urls + [
        (r"%s(.*)" % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))
    ], debug=reload)

    server = HTTPServer(tornado_app)
    server.listen(port=port,
                  address=addr)
    IOLoop.instance().start()
Exemple #20
0
 def inner_run(self, *args, **options):    
     wsgi_app = WSGIContainer(WSGIHandler())
     tornado_app = Application([(r'/static/(.*)',
         DjangoStaticFilesHandler, {'default_filename': 'none.img'}),
         (r'/media/(.*)', StaticFileHandler, {'path': settings.MEDIA_ROOT}),
         ('/hello-tornado', HelloHandler), 
         ('/ws/doc/(\w+)', DocumentWS), 
         ('.*', FallbackHandler, dict(fallback=wsgi_app))])
     quit_command = (platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
     
     self.stdout.write("Validating models...\n\n")
     self.validate(display_num_errors=True)
     self.stdout.write((
         "%(started_at)s\n"
         "Django version %(version)s, using settings %(settings)r\n"
         "Django tornado server is running at http://%(addr)s:%(port)s/\n"
         "Quit the server with %(quit_command)s.\n"
     ) % {
         "started_at": datetime.now().strftime('%B %d, %Y - %X'),
         "version": self.get_version(),
         "settings": settings.SETTINGS_MODULE,
         "addr": '127.0.0.1',
         "port": self.port,
         "quit_command": quit_command,
     })
     # django.core.management.base forces the locale to en-us. We should
     # set it up correctly for the first request (particularly important
     # in the "--noreload" case).
     translation.activate(settings.LANGUAGE_CODE)
     
     server = HTTPServer(tornado_app)
     server.listen(int(self.port))
     IOLoop.instance().start()
Exemple #21
0
    def _prepare_web_app(self):
        ''' Config and Views'''
        logger.debug("tornado web app setup")

        self._web_app = Application(
            gzip=self.config.get('gzip'),
            debug=self.config.get('debug'),
            static_path=self.config.get('static_dir'),
            handlers=self.handlers,
            cookie_secret=self.config.get('cookie_secret'),
            login_url=self.config.get('login_url'),
            xsrf_cookies=self.config.get('xsrf_cookies'),
            template_path=self.config.get('templates_dir'),
        )

        if self.config.get('debug') and not self.config.get('autoreload'):
            # FIXME hack to disable autoreload when debug is True
            from tornado import autoreload
            autoreload._reload_attempted = True
            autoreload._reload = lambda: None

        if self.config.get('ssl'):
            ssl_options = dict(
                certfile=os.path.expanduser(
                    self.config.get('ssl_certificate')),
                keyfile=os.path.expanduser(
                    self.config.get('ssl_certificate_key')))
            self.server = HTTPServer(self._web_app,
                                     ssl_options=ssl_options)
        else:
            self.server = HTTPServer(self._web_app)
Exemple #22
0
def runserver():
    tornado.options.parse_command_line()
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    loop = tornado.ioloop.IOLoop.instance()
    print 'Server running on http://localhost:%d' % (options.port)
    loop.start()
Exemple #23
0
def main(arguments=None):
    """Runs thumbor server with the specified arguments."""

    server_parameters = get_server_parameters(arguments)
    logging.basicConfig(level=getattr(logging, server_parameters.log_level.upper()))

    lookup_paths = [os.curdir, expanduser("~"), "/etc/", dirname(__file__)]

    config = Config.load(server_parameters.config_path, conf_name="thumbor.conf", lookup_paths=lookup_paths)
    importer = Importer(config)
    importer.import_modules()

    if server_parameters.security_key is None:
        server_parameters.security_key = config.SECURITY_KEY

    if not isinstance(server_parameters.security_key, basestring):
        raise RuntimeError(
            "No security key was found for this instance of thumbor. Please provide one using the conf file or a security key file."
        )

    context = Context(server=server_parameters, config=config, importer=importer)
    application = ThumborServiceApp(context)

    server = HTTPServer(application)
    server.bind(context.server.port, context.server.ip)
    server.start(1)

    try:
        logging.debug("thumbor running at %s:%d" % (context.server.ip, context.server.port))
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        print
        print "-- thumbor closed by user interruption --"
Exemple #24
0
def start_server():
    ''' Main entry point for the application '''
    sockets = netutil.bind_sockets(config.listen_port)
    server = HTTPServer(app)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    scoring = PeriodicCallback(
        scoring_round, int(5 * 60 * 1000), io_loop=io_loop
    )
    scoring.start()
    try:
        sys.stdout.write("\r" + INFO + "The game has begun, good hunting!\n")
        if config.debug:
            sys.stdout.write(WARN + "WARNING: Debug mode is enabled.\n")
        sys.stdout.flush()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(
            game_history.take_snapshot, int(60 * 1000), io_loop=io_loop
        )
        history_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        print('\r' + WARN + 'Shutdown Everything!')
    except:
      logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and \
                raw_input(PROMPT + "Flush Memcache? [Y/n]: ").lower() == 'y':
            print(INFO + 'Flushing cache ...'),
            FileCache.flush()
            print('OK')
        _exit(0)
Exemple #25
0
def run_tornado(addr, port, *args, **kwargs):
    """
    Starts the tornado webserver as wsgi server for OpenSlides.

    It runs in one thread.
    """
    # Save the port and the addr in a global var
    global RUNNING_HOST, RUNNING_PORT
    RUNNING_HOST = addr
    RUNNING_PORT = port

    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    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 + other_urls, autoreload=debug, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()

    # Reset the global vars
    RUNNING_HOST = None
    RUNNING_PORT = None
def create_async_client(path, station_coordinates_callback=None,
                        event_info_callback=None,
                        travel_time_callback=None):
    application = get_application()
    application.db = InstaseisDB(path)
    application.station_coordinates_callback = station_coordinates_callback
    application.event_info_callback = event_info_callback
    application.travel_time_callback = travel_time_callback
    application.max_size_of_finite_sources = 1000
    # Build server as in testing:311
    sock, port = bind_unused_port()
    server = HTTPServer(application, io_loop=IOLoop.instance())
    server.add_sockets([sock])
    client = AsyncClient(server, AsyncHTTPClient())
    client.application = application
    client.filepath = path
    client.port = port
    # Flag to help deal with forward/backwards databases.
    if "bwd" in os.path.basename(path):
        client.is_reciprocal = True
        client.source_depth = 0.0
    else:
        client.is_reciprocal = False
        client.source_depth = application.db.info.source_depth * 1000
    client.info = application.db.info
    return client
Exemple #27
0
class Server():
    def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False):
        self._app = app
        self._configfile = configfile
        self._basedir = basedir 
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
    
    def run(self):

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler
        app.debug=self._debug

        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
        # app.run(host=self._host, port=self._port, server="tornado",reloader=self._debug)
        self._tornado_app = Application(self._router.urls + [
            (r".*", FallbackHandler, {"fallback": WSGIContainer(app)})
            ])
        self._server = HTTPServer(self._tornado_app)
        self._server.listen(self._port, address=self._host)
        IOLoop.instance().start() 

    def _createSocketConnection(self, session):
        return PiMillSocket(session)
Exemple #28
0
class ServerManager:
    """
    The server manager is responsible for bootstraping the tornado webserver
    with a wsgi container on the given port. Currently the server manager is
    only able to instanciate one instance on one port. Multiple instances
    are not supported.
    """

    def __init__(self):
        self._http_server = HTTPServer(WSGIContainer(app))

    def start_server(self, portapi=5000, mode="development"):
        """
        starts the tornado webserver with wsgi container on the specified mode.
        The mode determines which configuration should be used by the api. Possible values are
        - development
        - staging
        - production
        :param portapi: port where the server should listen on. Default is 5000
        :param mode: defines the mode on which the server should run on
        :return: Nothing
        """
        set_app_mode(mode)

        self._http_server.listen(portapi)
        IOLoop.instance().start()
Exemple #29
0
def main(arguments=None):
    '''Runs r³ server with the specified arguments.'''

    parser = argparse.ArgumentParser(description='runs the application that processes stream requests for r³')
    parser.add_argument('-b', '--bind', type=str, default='0.0.0.0', help='the ip that r³ will bind to')
    parser.add_argument('-p', '--port', type=int, default=9999, help='the port that r³ will bind to')
    parser.add_argument('-l', '--loglevel', type=str, default='warning', help='the log level that r³ will run under')
    parser.add_argument('-i', '--hide-index-page', action='store_true', default=False, help='indicates whether r³ app should show the help page')
    parser.add_argument('-d', '--debug', action='store_true', default=False, help='indicates whether r³ app should run in debug mode')
    parser.add_argument('--redis-host', type=str, default='0.0.0.0', help='the ip that r³ will use to connect to redis')
    parser.add_argument('--redis-port', type=int, default=6379, help='the port that r³ will use to connect to redis')
    parser.add_argument('--redis-db', type=int, default=0, help='the database that r³ will use to connect to redis')
    parser.add_argument('--redis-pass', type=str, default='', help='the password that r³ will use to connect to redis')
    parser.add_argument('-c', '--config-file', type=str, help='the config file that r³ will use to load input stream classes and reducers', required=True)

    args = parser.parse_args(arguments)

    cfg = Config(args.config_file)

    c = redis.StrictRedis(host=args.redis_host, port=args.redis_port, db=args.redis_db, password=args.redis_pass)

    logging.basicConfig(level=getattr(logging, args.loglevel.upper()))

    application = R3ServiceApp(redis=c, config=cfg, log_level=args.loglevel.upper(), debug=args.debug, show_index_page=not args.hide_index_page)

    server = HTTPServer(application)
    server.bind(args.port, args.bind)
    server.start(1)

    try:
        logging.debug('r³ service app running at %s:%d' % (args.bind, args.port))
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        print
        print "-- r³ service app closed by user interruption --"
Exemple #30
0
def setup_server():
    # Config tornado.curl_httpclient to use NullHandler
    tornado_logger = logging.getLogger('tornado.curl_httpclient')
    tornado_logger.addHandler(logging.NullHandler())
    tornado_logger.propagate = False

    settings = dict(
        autoreload=True,
        secret="ElasticKube",
    )

    configure(settings)

    handlers = [
        (r"/api/v1/auth/providers", AuthProvidersHandler),
        (r"/api/v1/auth/signup", SignupHandler),
        (r"/api/v1/auth/login", PasswordHandler),
        (r"/api/v1/auth/google", GoogleOAuth2LoginHandler),
        (r"/api/v1/ws", MainWebSocketHandler),
        (r"/icons/(?P<entity_id>[^\/]+)\/(?P<chart_id>[^\/]+)", IconGenerator)
    ]

    application = Application(handlers, **settings)

    server = HTTPServer(application)
    socket = bind_unix_socket("/var/run/elastickube-api.sock", mode=0777)
    server.add_socket(socket)

    IOLoop.current().add_callback(initialize, settings)
Exemple #31
0
    def inner_run(self, *args, **options):
        from django.conf import settings
        from django.utils import translation

        threading = options.get('use_threading')
        shutdown_message = options.get('shutdown_message', '')
        quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'

        self.stdout.write("Performing system checks...\n\n")
        self.validate(display_num_errors=True)
        try:
            self.check_migrations()
        except ImproperlyConfigured:
            pass
        now = datetime.now().strftime('%B %d, %Y - %X')
        if six.PY2:
            now = now.decode(get_system_encoding())
        self.stdout.write((
            "%(started_at)s\n"
            "Django version %(version)s, using settings %(settings)r\n"
            "Starting development server at http://%(addr)s:%(port)s/\n"
            "Quit the server with %(quit_command)s.\n"
        ) % {
            "started_at": now,
            "version": self.get_version(),
            "settings": settings.SETTINGS_MODULE,
            "addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
            "port": self.port,
            "quit_command": quit_command,
        })
        # django.core.management.base forces the locale to en-us. We should
        # set it up correctly for the first request (particularly important
        # in the "--noreload" case).
        translation.activate(settings.LANGUAGE_CODE)

        try:
            handler = self.get_handler(*args, **options)
            django_handle = WSGIContainer(handler)
            tornado_handle = Application([
                ('/hello', HelloHandler),
                ('.*', FallbackHandler, {
                    'fallback': django_handle,
                }),
            ])
            server = HTTPServer(tornado_handle)
            server.listen(int(self.port), self.addr)
            IOLoop.instance().start()
        except socket.error as e:
            # Use helpful error messages instead of ugly tracebacks.
            ERRORS = {
                errno.EACCES: "You don't have permission to access that port.",
                errno.EADDRINUSE: "That port is already in use.",
                errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
            }
            try:
                error_text = ERRORS[e.errno]
            except KeyError:
                error_text = str(e)
            self.stderr.write("Error: %s" % error_text)
            # Need to use an OS exit because sys.exit doesn't work in a thread
            os._exit(1)
        except KeyboardInterrupt:
            if shutdown_message:
                self.stdout.write(shutdown_message)
            sys.exit(0)
Exemple #32
0
  comments = mdb.comments
  tags_collection = mdb.tags
  goaway_collection = mdb.goaway
  follow_collection = mdb.follow
  print('mongodb tweets_top1 collection size:', tweets_top1.count())
  print('mongodb tweets_top7 collection size:', tweets_top7.count())
  print('mongodb tweets_top30 collection size:', tweets_top30.count())
  print('mongodb comments collection size:', comments.count())
  print('mongodb tags collection size:', tags_collection.count())
  print('mongodb goaway collection size:', goaway_collection.count())
  print('mongodb follow collection size:', follow_collection.count())
  
  TAGS = ['insightful!', 'thank you', 'agree', 'disagree', 'not constructive', 'troll', 'spam']

  # start
  if args.prod:
    # run on Tornado instead, since running raw Flask in prod is not recommended
    print('starting tornado!')
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop
    from tornado.log import enable_pretty_logging
    enable_pretty_logging()
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(args.port)
    IOLoop.instance().start()
  else:
    print('starting flask!')
    app.debug = False
    app.run(port=args.port, host='0.0.0.0')
Exemple #33
0
# -*- coding: utf-8 -*-
# @Time    : 2020/7/26 22:07
# @Author  : Bruce
# @Email   : [email protected]
# @File    : test3.py
# @Software: PyCharm


from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
import tornado.options


# 定义变量
tornado.options.define('port', default=8000, type=int, help='this is the port')

class IndexHandler(RequestHandler):
    def get(self):
        self.write('这是第三个tornado测试,测试端口参数设置')

if __name__ == '__main__':
    app = Application([(r'/', IndexHandler)])
    tornado.options.parse_command_line()
    # tornado.options.parse_config_file('./config')  # 从本地读取配置

    http_server = HTTPServer(app)
    http_server.bind(tornado.options.options.port)
    http_server.start(1)

    IOLoop.current().start()
Exemple #34
0
#coding=utf-8
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from entity_server import app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(6000)  #flask默认的端口
IOLoop.instance().start()
Exemple #35
0
        time.sleep(10)  # 传递参数 10 秒。
        _result[tid] = {"finish"}

    @gen.coroutine
    def get(self):
        tid = str(int(time.time() * 10000))
        self.background_task(tid)
        self.write(tid)


class JobCheckHandler(RequestHandler):
    def get(self):
        tid = self.get_argument("tid")
        if tid in _result.keys():
            out = _result[tid]  # 结果
            del _result[tid]  # 删除tid的数据。
            self.write(str(out))
        else:
            self.write("")


# main 启动。
if __name__ == "__main__":
    HTTPServer(Application([
        ("/", MainPage),
        ("/add_job", AddJobHandler),
        ("/job_check", JobCheckHandler)
    ], debug=True)).listen(9999)
    print("start web .")
    IOLoop.instance().start()
Exemple #36
0
    conn = None
    cur = None
    try:
        conn = lite.connect(database_path)
        conn.row_factory = lite.Row
        cur = conn.cursor()
        cur.execute('SELECT SQLITE_VERSION()')
        data = cur.fetchone()
        gen_log.info("SQLite version: %s" % data[0])
    except lite.Error, e:
        gen_log.error(e)
        sys.exit(1)

    app = myApplication(conn, cur)
    http_server = HTTPServer(app, xheaders=True)
    http_server.listen(app_port)

    app2 = myApplication_OTA(conn, cur)
    http_server2 = HTTPServer(app2)
    http_server2.listen(ota_port)

    tcp_server = DeviceServer(conn, cur, 'xchange')
    tcp_server.listen(tcp_xchange_port)

    tcp_server2 = DeviceServer(conn, cur, 'ota')
    tcp_server2.listen(tcp_ota_port)

    stat = Statistics()

    if options.suppress_access_log:
# -*- coding: utf-8 -*-
"""
    @ Author:
    @ E-Mail:
    @ Date:

"""
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

from app import app

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(8080)  # 监听端口
IOLoop.instance().start()
Exemple #38
0
def start_server():
    """ Main entry point for the application """
    if options.debug:
        logging.warn(
            "%sDebug mode is enabled; DO NOT USE THIS IN PRODUCTION%s" %
            (bold + R, W))
    locale.set_default_locale("en_US")
    locale.load_translations("locale")
    if options.autostart_game:
        logging.info("The game is about to begin, good hunting!")
        app.settings["game_started"] = True
        app.settings["history_callback"].start()
        if options.use_bots:
            app.settings["score_bots_callback"].start()
    # Setup server object
    if options.ssl:
        server = HTTPServer(
            app,
            ssl_options={
                "certfile": options.certfile,
                "keyfile": options.keyfile
            },
            xheaders=options.x_headers,
        )
    else:
        server = HTTPServer(app, xheaders=options.x_headers)
    try:
        sockets = netutil.bind_sockets(options.listen_port,
                                       options.listen_interface)
    except (OSError, IOError) as err:
        logging.error("Problem binding socket to port %s",
                      str(options.listen_port))
        if err.errno == 13:
            pypath = sys.executable
            if os_path.islink(pypath):
                pypath = os_path.realpath(pypath)
            logging.error(
                "Possible Fix: sudo setcap CAP_NET_BIND_SERVICE=+eip %s",
                pypath)
        elif err.errno == 98:
            logging.error(
                "The port may be in use by an existing service.  RTB already running?"
            )
        else:
            logging.error(err)
        sys.exit()
    server.add_sockets(sockets)
    try:
        Scoreboard.update_gamestate(app)
    except OperationalError as err:
        if "Table definition has changed" in str(err):
            logging.info(
                "Table definitions have changed -restarting RootTheBox.")
            return "restart"
        else:
            logging.error("There was a problem starting RootTheBox. Error: " +
                          str(err))
    try:
        io_loop.start()
    except KeyboardInterrupt:
        sys.stdout.write("\r" + WARN + "Shutdown Everything!\n")
    except:
        logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        _exit(0)
Exemple #39
0
    logger.warn("%s, try to pip install setproctitle, otherwise, you can't use the process to customize the function" %e)
else:
    setproctitle.setproctitle(ProcessName)
    logger.info("The process is %s" % ProcessName)

try:
    msg = '%s has been launched, %s:%d' %(ProcessName, Host, Port)
    print(msg)
    logger.info(msg)
    if ProductType == 'gevent':
        from gevent.wsgi import WSGIServer
        http_server = WSGIServer((Host, Port), app)
        http_server.serve_forever()

    elif ProductType == 'tornado':
        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        http_server = HTTPServer(WSGIContainer(app))
        http_server.listen(Port)
        IOLoop.instance().start()

    else:
        msg = 'Start the program does not support with %s, abnormal exit!' %ProductType
        logger.error(msg)
        raise RuntimeError(msg)

except Exception,e:
    print(e)
    logger.error(e, exc_info=True)
Exemple #40
0
class HttpsServerManage:
    """
    Instance of HttpsServerManage encapsulates the construction of an HTTPServer
    """

    # Main motivation for this object is to be able to change the ssl
    # certificates from an http request without restarting the whole pcsd
    # daemon.
    #
    # For this purpose an application, which handles http requests, gets
    # a reference to the HttpsServerManage instance. When new certificates
    # arrive via a request the application asks the HttpsServerManage instance
    # for necessary steps (it stops listening of the current HTTPServer and
    # starts a new one with updated certificates).

    def __init__(self, make_app, port, bind_addresses, ssl: PcsdSSL):
        self.__make_app = make_app
        self.__port = port
        self.__bind_addresses = bind_addresses

        self.__server = None
        self.__ssl = ssl
        self.__server_is_running = False

    @property
    def server_is_running(self):
        return self.__server_is_running

    def stop(self):
        self.__server.stop()
        self.__server_is_running = False

    def start(self):
        self.__ssl.guarantee_valid_certs()

        log.pcsd.info("Starting server...")

        self.__server = HTTPServer(self.__make_app(self),
                                   ssl_options=self.__ssl.create_context())

        # It is necessary to bind sockets for every new HTTPServer since
        # HTTPServer.stop calls sock.close() inside.
        sockets = []
        for address in self.__bind_addresses:
            log.pcsd.info("Binding socket for address '%s' and port '%s'",
                          address if address is not None else "*", self.__port)
            sockets.extend(bind_sockets(self.__port, address))

        self.__server.add_sockets(sockets)

        log.pcsd.info(f"Server is listening")
        self.__server_is_running = True
        return self

    def reload_certs(self):
        if not self.server_is_running:
            raise HttpsServerManageException(
                "Could not reload certificates, server is not running")
        log.pcsd.info("Stopping server to reload ssl certificates...")
        self.stop()
        self.start()
Exemple #41
0
class Server():
    def __init__(self,
                 configfile=None,
                 basedir=None,
                 host="0.0.0.0",
                 port=5000,
                 debug=False,
                 allowRoot=False,
                 logConf=None):
        self._configfile = configfile
        self._basedir = basedir
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
        self._logConf = logConf
        self._ioLoop = None

    def stop(self):
        if self._ioLoop:
            self._ioLoop.stop()
            self._ioLoop = None

    def run(self):
        if not self._allowRoot:
            self._checkForRoot()

        global userManager
        global eventManager
        global loginManager
        global debug
        global softwareManager
        global discoveryManager
        global VERSION
        global UI_API_KEY

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler

        from astroprint.printfiles.watchdogs import UploadCleanupWatchdogHandler

        debug = self._debug

        # first initialize the settings singleton and make sure it uses given configfile and basedir if available
        self._initSettings(self._configfile, self._basedir)
        s = settings()

        if not s.getBoolean(['api', 'regenerate']) and s.getString(
            ['api', 'key']):
            UI_API_KEY = s.getString(['api', 'key'])
        else:
            UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)

        # then initialize logging
        self._initLogging(self._debug, self._logConf)
        logger = logging.getLogger(__name__)

        if s.getBoolean(["accessControl", "enabled"]):
            userManagerName = s.get(["accessControl", "userManager"])
            try:
                clazz = util.getClass(userManagerName)
                userManager = clazz()
            except AttributeError, e:
                logger.exception(
                    "Could not instantiate user manager %s, will run with accessControl disabled!"
                    % userManagerName)

        softwareManager = swManager()
        VERSION = softwareManager.versionString

        logger.info("Starting AstroBox (%s) - Commit (%s)" %
                    (VERSION, softwareManager.commit))

        from astroprint.migration import migrateSettings
        migrateSettings()

        pluginManager().loadPlugins()

        eventManager = events.eventManager()
        printer = printerManager(printerProfileManager().data['driver'])

        #Start some of the managers here to make sure there are no thread collisions
        from astroprint.network.manager import networkManager
        from astroprint.boxrouter import boxrouterManager

        networkManager()
        boxrouterManager()

        # configure timelapse
        #octoprint.timelapse.configureTimelapse()

        app.wsgi_app = ReverseProxied(app.wsgi_app)

        app.secret_key = boxrouterManager().boxId
        loginManager = LoginManager()
        loginManager.session_protection = "strong"
        loginManager.user_callback = load_user
        if userManager is None:
            loginManager.anonymous_user = users.DummyUser
            principals.identity_loaders.appendleft(users.dummy_identity_loader)
        loginManager.init_app(app)

        # setup command triggers
        events.CommandTrigger(printer)
        if self._debug:
            events.DebugEventListener()

        if networkManager().isOnline():
            softwareManager.checkForcedUpdate()

        if self._host is None:
            self._host = s.get(["server", "host"])
        if self._port is None:
            self._port = s.getInt(["server", "port"])

        app.debug = self._debug

        from octoprint.server.api import api

        app.register_blueprint(api, url_prefix="/api")

        boxrouterManager(
        )  # Makes sure the singleton is created here. It doesn't need to be stored
        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")

        discoveryManager = DiscoveryManager()

        externalDriveManager()

        def access_validation_factory(validator):
            """
			Creates an access validation wrapper using the supplied validator.

			:param validator: the access validator to use inside the validation wrapper
			:return: an access validation wrapper taking a request as parameter and performing the request validation
			"""
            def f(request):
                """
				Creates a custom wsgi and Flask request context in order to be able to process user information
				stored in the current session.

				:param request: The Tornado request for which to create the environment and context
				"""
                wsgi_environ = tornado.wsgi.WSGIContainer.environ(request)
                with app.request_context(wsgi_environ):
                    app.session_interface.open_session(app, request)
                    loginManager.reload_user()
                    validator(request)

            return f

        self._tornado_app = Application(self._router.urls + [
            #(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": s.getBaseFolder("timelapse"), "as_attachment": True}),
            (r"/downloads/files/local/([^/]*\.(gco|gcode))",
             LargeResponseHandler, {
                 "path": s.getBaseFolder("uploads"),
                 "as_attachment": True
             }),
            (r"/downloads/logs/([^/]*)", LargeResponseHandler, {
                "path": s.getBaseFolder("logs"),
                "as_attachment": True,
                "access_validation": access_validation_factory(admin_validator)
            }),
            #(r"/downloads/camera/current", UrlForwardHandler, {"url": s.get(["webcam", "snapshot"]), "as_attachment": True, "access_validation": access_validation_factory(user_validator)}),
            (r".*", FallbackHandler, {
                "fallback": WSGIContainer(app.wsgi_app)
            })
        ])
        self._server = HTTPServer(self._tornado_app,
                                  max_buffer_size=1048576 *
                                  s.getInt(['server', 'maxUploadSize']))
        self._server.listen(self._port, address=self._host)

        logger.info("Listening on http://%s:%d" % (self._host, self._port))

        eventManager.fire(events.Events.STARTUP)
        if s.getBoolean(["serial", "autoconnect"]):
            (port, baudrate) = s.get(["serial", "port"
                                      ]), s.getInt(["serial", "baudrate"])
            connectionOptions = printer.getConnectionOptions()
            if port in connectionOptions["ports"]:
                t = threading.Thread(target=printer.connect,
                                     args=(port, baudrate))
                t.daemon = True
                t.start()

        # start up watchdogs
        observer = Observer()
        observer.daemon = True
        observer.schedule(UploadCleanupWatchdogHandler(),
                          s.getBaseFolder("uploads"))
        observer.start()

        #Load additional Tasks
        additionalTasksManager()

        #Load maintenance menu
        maintenanceMenuManager()

        try:
            self._ioLoop = IOLoop.instance()
            self._ioLoop.start()

        except SystemExit:
            pass

        except:
            logger.fatal(
                "Please report this including the stacktrace below in AstroPrint's bugtracker. Thanks!"
            )
            logger.exception("Stacktrace follows:")

        finally:
            observer.stop()
            self.cleanup()
            logger.info('Cleanup complete')

        observer.join(1.0)
        logger.info('Good Bye!')
Exemple #42
0

def shutdown_handler(signum=None, frame=None):
    LOG.info('Shutting down...')
    IOLoop.instance().stop()


if __name__ == '__main__':
    eds_app = connexion.App(__name__)
    eds_app.add_api('api.yaml',
                    arguments={'title': 'ElasTest Device Emulator API'},
                    resolver=RestyResolver('api'))

    eds_ip = os.environ.get('EDS_IP', '0.0.0.0')
    eds_port = os.environ.get('EDS_PORT', 8080)
    eds_server = HTTPServer(WSGIContainer(eds_app))
    eds_server.listen(address=eds_ip, port=eds_port)
    LOG.info('EDS available at http://{IP}:{PORT}'.format(IP=eds_ip,
                                                          PORT=eds_port))

    check_ip = os.environ.get('EDS_CHECK_IP', '0.0.0.0')
    check_port = os.environ.get('EDS_CHECK_PORT', 9090)
    check_server = HTTPServer(WSGIContainer(add_check_api()))
    check_server.listen(address=check_ip, port=check_port)
    LOG.info('EDS Health available at http://{IP}:{PORT}'.format(
        IP=check_ip, PORT=check_port))

    for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
        signal.signal(sig, shutdown_handler)

    LOG.info('Press CTRL+C to quit.')
Exemple #43
0
def runserver():
    from chat.app import Application
    click.echo('Running tornado http server')
    http_server = HTTPServer(Application)
    http_server.listen(8000)
    IOLoop.instance().start()
Exemple #44
0
from controllers.flow_ctr import FlowApiHandler
from controllers.admin import FlowAdminHandler, FlowAddHandler, FlowEditHandler, FlowEffectHandler, FlowDelHandler, FlowInitHandler

logging.basicConfig(
    level='INFO', format="[%(asctime)s](%(levelname)s)%(name)s : %(message)s")


def make_app():
    return tornado.web.Application(
        handlers=[
            (r"/admin", FlowAdminHandler),
            (r"/add", FlowAddHandler),
            (r"/edit", FlowEditHandler),
            (r"/delete", FlowDelHandler),
            (r"/effect", FlowEffectHandler),
            (r"/init", FlowInitHandler),
            (r"/.*", FlowApiHandler),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "public"),
        # autoreload = True,
        # debug = True,
    )


if __name__ == '__main__':
    server = HTTPServer(make_app())
    server.listen(8088)
    IOLoop.current().start()
    server.start(1)
Exemple #45
0
        backlog = Configuration.getBacklog()
        file_handler = RotatingFileHandler(logfile,
                                           maxBytes=maxLogSize,
                                           backupCount=backlog)
        file_handler.setLevel(logging.ERROR)
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        file_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)

    if flaskDebug:
        # start debug flask server
        app.run(host=flaskHost, port=flaskPort, debug=flaskDebug)
    else:
        # start asynchronous server using tornado wrapper for flask
        # ssl connection
        print("Server starting...")
        if Configuration.useSSL():
            cert = os.path.join(_runPath, "../", Configuration.getSSLCert())
            key = os.path.join(_runPath, "../", Configuration.getSSLKey())
            ssl_options = {"certfile": cert, "keyfile": key}
        else:
            ssl_options = None
        signal.signal(signal.SIGTERM, sig_handler)
        signal.signal(signal.SIGINT, sig_handler)
        global http_server
        http_server = HTTPServer(WSGIContainer(app), ssl_options=ssl_options)
        http_server.bind(flaskPort, address=flaskHost)
        http_server.start(0)  # Forks multiple sub-processes
        IOLoop.instance().start()
            object_dict = {
                "label": model.CLASSES[label],
                "x1": int(bbox[0]),
                "y1": int(bbox[1]),
                "x2": int(bbox[2]),
                "y2": int(bbox[3]),
                "confidence": float(bbox[-1])
            }
            box_objects.append(object_dict)
        final_result = {
            "filename": image_file.filename,
            "width": ori_height,
            "height": ori_width,
            "detectresult": box_objects
        }
        return {
            "filename": image_file.filename,
            "width": ori_height,
            "height": ori_width,
            "detectresult": box_objects
        }


if __name__ == '__main__':
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(ImageDetect, '/detect')
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(5000, "0.0.0.0")
    IOLoop.instance().start()
Exemple #47
0
from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(8000)
    IOLoop.instance().start()
        # self.write(res.read())

class cmdHandler(RequestHandler):
    def get(self):
        #接受url中的数据,并返回cmd执行的结果
        cmd = self.get_query_argument('cmd','')
        if cmd:
            res = os.popen(cmd,'r')
            res = res.read()
            self.write(res)
            # self.render('view/webshell.html',result=res.read())
        
        #返回数据
    

def makeApp():
    return Application([(r'/',indexHadler),(r'/cmd',cmdHandler)])

if __name__ == '__main__':
    #开始接收
    parse_command_line()
    #web应用
    app = makeApp()
    #将app部署到http服务器
    server = HTTPServer(app)
    #绑定配置-端口
    server.bind(options.port)
    #启动server
    server.start()
    #启动轮询
    IOLoop.current().start()   
Exemple #49
0
def main():
    """
    Main entry point for the application
    """

    # CLI arguments
    parser = argparse.ArgumentParser(description='Linkify Server')
    parser.add_argument('port',
                        metavar='Port',
                        type=int,
                        nargs='?',
                        default=8080,
                        help='port to run the application')
    parser.add_argument('--env',
                        '-e',
                        dest='environment',
                        action='store',
                        default='dev',
                        help='type of environment')
    parser.add_argument('--tornado',
                        '-t',
                        dest='tornado',
                        action='store_true',
                        help='run the server as tornado wsgi')
    parser.add_argument('--ssl',
                        '-s',
                        dest='use_ssl',
                        action='store_true',
                        help='run server with ssl certs')
    parser.add_argument('--ssl-certfile',
                        '-c',
                        dest='ssl_certfile',
                        action='store',
                        default='server.crt',
                        help='ssl certificate file')
    parser.add_argument('--ssl-keyfile',
                        '-k',
                        dest='ssl_keyfile',
                        action='store',
                        default='server.key',
                        help='ssl key file')
    parser.add_argument('--upload-s3',
                        '-s3',
                        dest='upload_s3',
                        action='store_true',
                        help='deploy s3 assets to AWS')
    parser.add_argument('--create-tables',
                        '-ct',
                        dest='create_tables',
                        action='store_true',
                        help='creates dynamodb tables in AWS')
    args = parser.parse_args()

    # Configure logging
    log_level = logging.INFO if args.environment == 'prod' else logging.DEBUG
    logging.basicConfig(format='[%(levelname)s]: %(message)s', level=log_level)

    # Create the app
    logging.info('Creating application environment: %s' % args.environment)
    app = create_app(env=args.environment)

    # Start app in tornado wsgi container
    if args.tornado:

        if HAS_TORNADO:
            try:
                logging.info('Starting Tornado Server on port %d' % args.port)
                if args.use_ssl:
                    ssl_options = {
                        'certfile': os.path.join(args.ssl_certfile),
                        'keyfile': os.path.join(args.ssl_keyfile)
                    }
                else:
                    ssl_options = None

                http_server = HTTPServer(WSGIContainer(app),
                                         ssl_options=ssl_options)
                http_server.listen(args.port)
                IOLoop.instance().start()
            except KeyboardInterrupt as e:
                logging.info('Stopping Tornado Server by Ctrl+C')
        else:
            logging.warning(
                'Failed to start Tornado server. Tornado not installed')
    elif args.upload_s3:
        logging.info('Uploading to S3...')
        import flask_s3
        flask_s3.create_all(app)
        logging.info('Upload complete.')
    elif args.create_tables:
        logging.info('Creating Dynamodb Tables')
        from service.models import create_tables
        create_tables()
        logging.info('Table creation complete')
    else:
        logging.info('Starting Flask Internal (dev) Server')
        app.run(port=args.port)
        logging.info('Stopping Flask Internal (dev) Server')

    logging.info('Shutting down...')
    return 0
Exemple #50
0
class WebhookServer:
    def __init__(self, listen: str, port: int, webhook_app: 'WebhookAppClass',
                 ssl_ctx: SSLContext):
        self.http_server = HTTPServer(webhook_app, ssl_options=ssl_ctx)
        self.listen = listen
        self.port = port
        self.loop: Optional[IOLoop] = None
        self.logger = logging.getLogger(__name__)
        self.is_running = False
        self.server_lock = Lock()
        self.shutdown_lock = Lock()

    def serve_forever(self,
                      force_event_loop: bool = False,
                      ready: Event = None) -> None:
        with self.server_lock:
            self.is_running = True
            self.logger.debug('Webhook Server started.')
            self._ensure_event_loop(force_event_loop=force_event_loop)
            self.loop = IOLoop.current()
            self.http_server.listen(self.port, address=self.listen)

            if ready is not None:
                ready.set()

            self.loop.start()
            self.logger.debug('Webhook Server stopped.')
            self.is_running = False

    def shutdown(self) -> None:
        with self.shutdown_lock:
            if not self.is_running:
                self.logger.warning('Webhook Server already stopped.')
                return
            self.loop.add_callback(self.loop.stop)  # type: ignore

    def handle_error(self, request: object, client_address: str) -> None:  # pylint: disable=W0613
        """Handle an error gracefully."""
        self.logger.debug(
            'Exception happened during processing of request from %s',
            client_address,
            exc_info=True,
        )

    def _ensure_event_loop(self, force_event_loop: bool = False) -> None:
        """If there's no asyncio event loop set for the current thread - create one."""
        try:
            loop = asyncio.get_event_loop()
            if (not force_event_loop and os.name == 'nt'
                    and sys.version_info >= (3, 8)
                    and isinstance(loop, asyncio.ProactorEventLoop)):
                raise TypeError(
                    '`ProactorEventLoop` is incompatible with '
                    'Tornado. Please switch to `SelectorEventLoop`.')
        except RuntimeError:
            # Python 3.8 changed default asyncio event loop implementation on windows
            # from SelectorEventLoop to ProactorEventLoop. At the time of this writing
            # Tornado doesn't support ProactorEventLoop and suggests that end users
            # change asyncio event loop policy to WindowsSelectorEventLoopPolicy.
            # https://github.com/tornadoweb/tornado/issues/2608
            # To avoid changing the global event loop policy, we manually construct
            # a SelectorEventLoop instance instead of using asyncio.new_event_loop().
            # Note that the fix is not applied in the main thread, as that can break
            # user code in even more ways than changing the global event loop policy can,
            # and because Updater always starts its webhook server in a separate thread.
            # Ideally, we would want to check that Tornado actually raises the expected
            # NotImplementedError, but it's not possible to cleanly recover from that
            # exception in current Tornado version.
            if (os.name == 'nt' and sys.version_info >= (3, 8)
                    # OS+version check makes hasattr check redundant, but just to be sure
                    and hasattr(asyncio, 'WindowsProactorEventLoopPolicy') and
                (isinstance(
                    asyncio.get_event_loop_policy(),
                    asyncio.WindowsProactorEventLoopPolicy,  # pylint: disable=E1101
                ))):  # pylint: disable=E1101
                self.logger.debug(
                    'Applying Tornado asyncio event loop fix for Python 3.8+ on Windows'
                )
                loop = asyncio.SelectorEventLoop()
            else:
                loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
Exemple #51
0
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
# 导入flask项目
from MICS_Server import app

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)  # 对应flask的端口
IOLoop.instance().start()

# 如果要开启多进程模式用下面的代码,不过仅在linux下
# http_server = HTTPServer(WSGIContainer(app))
# http_server.bind(8888)
# http_server.start(0)
# IOLoop.instance().start()
Exemple #52
0
def start(app, port=8080):
    logger.info('Server Start..' + str(port))
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(port)
    IOLoop.instance().start()
Exemple #53
0
def run():
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(5000)
    IOLoop.instance().start()
Exemple #54
0
class AsyncHTTPTestCase(AsyncTestCase):
    '''A test case that starts up an HTTP server.

    Subclasses must override get_app(), which returns the
    tornado.web.Application (or other HTTPServer callback) to be tested.
    Tests will typically use the provided self.http_client to fetch
    URLs from this server.

    Example:
        class MyHTTPTest(AsyncHTTPTestCase):
            def get_app(self):
                return Application([('/', MyHandler)...])

            def test_homepage(self):
                self.http_client.fetch(self.get_url('/'), self.stop)
                response = self.wait()
                # test contents of response
    '''
    __next_port = 10000

    def setUp(self):
        super(AsyncHTTPTestCase, self).setUp()
        self.__port = None

        self.http_client = AsyncHTTPClient(io_loop=self.io_loop)
        self._app = self.get_app()
        self.http_server = HTTPServer(self._app,
                                      io_loop=self.io_loop,
                                      **self.get_httpserver_options())
        self.http_server.listen(self.get_http_port())

    def get_app(self):
        """Should be overridden by subclasses to return a
        tornado.web.Application or other HTTPServer callback.
        """
        raise NotImplementedError()

    def get_httpserver_options(self):
        """May be overridden by subclasses to return additional
        keyword arguments for HTTPServer.
        """
        return {}

    def get_http_port(self):
        """Returns the port used by the HTTPServer.

        A new port is chosen for each test.
        """
        if self.__port is not None:
            return self.__port
        self.__port = AsyncHTTPTestCase.__next_port
        AsyncHTTPTestCase.__next_port = self.__port + 1
        return self.__port

    def get_url(self, path):
        """Returns an absolute url for the given path on the test server."""
        return 'http://localhost:%s%s' % (self.get_http_port(), path)

    def tearDown(self):
        self.http_server.stop()
        self.http_client.close()
        super(AsyncHTTPTestCase, self).tearDown()
Exemple #55
0
def make_app():

    return tornado.web.Application([
            (r"/",IndexHandler),
            (r"/client/auth",ClientAuthHandler)
        ],debug=options.debug)

def make_db():
    client = motor_tornado.MotorClient(defaults['mongodb_backend_settings']['host'])
    db = None
    try:
        db = client[defaults['mongodb_backend_settings']['database']]
    except InvalidName:
        app_log.error("Database InvalidName")
        IOLoop.current().stop()
        exit()
    return db

if __name__ == '__main__':
    options.parse_command_line()
    app = make_app()

    http_server = HTTPServer(app)
    http_server.bind(options.port)
    http_server.start(1)
    app.settings['db'] = make_db()
    try:
        IOLoop.current().start()
    except KeyboardInterrupt:
        IOLoop.current().stop()
Exemple #56
0
class ProcessTest(LogTrapTestCase):
    def get_app(self):
        class ProcessHandler(RequestHandler):
            def get(self):
                if self.get_argument("exit", None):
                    # must use os._exit instead of sys.exit so unittest's
                    # exception handler doesn't catch it
                    os._exit(int(self.get_argument("exit")))
                if self.get_argument("signal", None):
                    os.kill(os.getpid(),
                            int(self.get_argument("signal")))
                self.write(str(os.getpid()))
        return Application([("/", ProcessHandler)])

    def tearDown(self):
        if task_id() is not None:
            # We're in a child process, and probably got to this point
            # via an uncaught exception.  If we return now, both
            # processes will continue with the rest of the test suite.
            # Exit now so the parent process will restart the child
            # (since we don't have a clean way to signal failure to
            # the parent that won't restart)
            logging.error("aborting child process from tearDown")
            logging.shutdown()
            os._exit(1)
        super(ProcessTest, self).tearDown()

    def test_multi_process(self):
        self.assertFalse(IOLoop.initialized())
        port = get_unused_port()
        def get_url(path):
            return "http://127.0.0.1:%d%s" % (port, path)
        sockets = bind_sockets(port, "127.0.0.1")
        # ensure that none of these processes live too long
        signal.alarm(5)  # master process
        try:
            id = fork_processes(3, max_restarts=3)
        except SystemExit, e:
            # if we exit cleanly from fork_processes, all the child processes
            # finished with status 0
            self.assertEqual(e.code, 0)
            self.assertTrue(task_id() is None)
            for sock in sockets: sock.close()
            signal.alarm(0)
            return
        signal.alarm(5)  # child process
        try:
            if id in (0, 1):
                signal.alarm(5)
                self.assertEqual(id, task_id())
                server = HTTPServer(self.get_app())
                server.add_sockets(sockets)
                IOLoop.instance().start()
            elif id == 2:
                signal.alarm(5)
                self.assertEqual(id, task_id())
                for sock in sockets: sock.close()
                client = HTTPClient()

                def fetch(url, fail_ok=False):
                    try:
                        return client.fetch(get_url(url))
                    except HTTPError, e:
                        if not (fail_ok and e.code == 599):
                            raise

                # Make two processes exit abnormally
                fetch("/?exit=2", fail_ok=True)
                fetch("/?exit=3", fail_ok=True)

                # They've been restarted, so a new fetch will work
                int(fetch("/").body)

                # Now the same with signals
                # Disabled because on the mac a process dying with a signal
                # can trigger an "Application exited abnormally; send error
                # report to Apple?" prompt.
                #fetch("/?signal=%d" % signal.SIGTERM, fail_ok=True)
                #fetch("/?signal=%d" % signal.SIGABRT, fail_ok=True)
                #int(fetch("/").body)

                # Now kill them normally so they won't be restarted
                fetch("/?exit=0", fail_ok=True)
                # One process left; watch it's pid change
                pid = int(fetch("/").body)
                fetch("/?exit=4", fail_ok=True)
                pid2 = int(fetch("/").body)
                self.assertNotEqual(pid, pid2)

                # Kill the last one so we shut down cleanly
                fetch("/?exit=0", fail_ok=True)

                os._exit(0)
        except Exception:
            logging.error("exception in child process %d", id, exc_info=True)
            raise
Exemple #57
0
class HTTPServerComms(ServerComms):
    """A class for communication between browser and server"""
    _loop = None
    _server = None
    _spawned = None
    _application = None
    use_cothread = False

    ReportHandlers = Hook()
    """Called at init() to get all the handlers that should make the application

    Args:
        context (Context): The context that should be used to perform operations
            on child blocks
        loop (IOLoop): The IO loop that the server is running under

    Returns:
        [`HandlerInfo`] - any handlers and their regexps that need to form part
            of the tornado Application
    """

    Publish = Hook()
    """Called when a new block is added

    Args:
        context (Context): The context that should be used to perform operations
            on child blocks
        published (list): [mri] list of published Controller mris
    """
    def do_init(self):
        super(HTTPServerComms, self).do_init()
        self._loop = IOLoop()
        part_info = self.run_hook(self.ReportHandlers,
                                  self.create_part_contexts(), self._loop)
        handler_infos = HandlerInfo.filter_values(part_info)
        handlers = []
        for handler_info in handler_infos:
            handlers.append((handler_info.regexp, handler_info.request_class,
                             handler_info.kwargs))
        self._application = Application(handlers)
        self.start_io_loop()

    def start_io_loop(self):
        if self._spawned is None:
            self._server = HTTPServer(self._application)
            self._server.listen(int(self.params.port))
            self._spawned = self.spawn(self._loop.start)

    def stop_io_loop(self):
        if self._spawned:
            self._loop.add_callback(self._server.stop)
            self._loop.add_callback(self._loop.stop)
            self._spawned.wait(timeout=10)
            self._spawned = None

    def do_disable(self):
        super(HTTPServerComms, self).do_disable()
        self.stop_io_loop()

    def do_reset(self):
        super(HTTPServerComms, self).do_reset()
        self.start_io_loop()

    @Process.Publish
    def publish(self, published):
        if self._spawned:
            self.run_hook(self.Publish, self.create_part_contexts(), published)
Exemple #58
0
        redicrt_url = pattern.findall(res.text)[0]
        # 匹配微信回调函数,调用微信app进行支付
        self.redirect(redicrt_url)
        # 重定向至微信


if __name__ == '__main__':

    define("port", default=8001, help="默认端口8000")
    parse_command_line()
    app = Application(
        [
            (r'/index', indexHandler),
            (r'/Notify_wx', Notify_wxHandler),
            (r'/Notify_URL', Notify_URLHandler),
        ],
        # 项目配置信息
        # 网页模板
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        # 静态文件
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        # debug=False
    )
    # 部署
    server = HTTPServer(app)
    server.listen(options.port)

    # 轮询监听
    IOLoop.current().start()
 def thread(self):
     self.app = Application([("/", WebSocket)])
     http_server = HTTPServer(self.app).listen(PORT)
     IOLoop.instance().start()
Exemple #60
0
 def start_io_loop(self):
     if self._spawned is None:
         self._server = HTTPServer(self._application)
         self._server.listen(int(self.params.port))
         self._spawned = self.spawn(self._loop.start)