コード例 #1
0
def serve(
    gateway: Gateway,
    host: str = "localhost",
    port: int = constants.DEFAULT_PORT_EDGE,
    use_reloader: bool = True,
    ssl_creds: Optional[Tuple[Any, Any]] = None,
    **kwargs,
) -> None:
    """
    Serve the given Gateway through a hypercorn server and block until it is completed.

    :param gateway: the Gateway instance to serve
    :param host: the host to expose the server on
    :param port: the port to expose the server on
    :param use_reloader: whether to use the reloader
    :param ssl_creds: the ssl credentials (tuple of certfile and keyfile)
    :param kwargs: any oder parameters that can be passed to the hypercorn.Config object
    """
    config = Config()
    config.bind = f"{host}:{port}"
    config.use_reloader = use_reloader

    if ssl_creds:
        cert_file_name, key_file_name = ssl_creds
        if cert_file_name:
            kwargs["certfile"] = cert_file_name
        if key_file_name:
            kwargs["keyfile"] = key_file_name

    for k, v in kwargs.items():
        setattr(config, k, v)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(
        serve_hypercorn(AsgiGateway(gateway, event_loop=loop), config))
コード例 #2
0
ファイル: https.py プロジェクト: perplext/SILENTTRINITY
    def run(self):

        if (self['Key'] == 'data/key.pem') and (self['Cert']
                                                == 'data/cert.pem'):
            if not os.path.exists(self['Key']) or not os.path.exists(
                    self['Cert']) or self['RegenCert']:
                create_self_signed_cert()

        config = Config()
        config.ciphers = 'ALL'
        config.accesslog = './data/logs/access.log'
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.certfile = self['Cert']
        config.keyfile = self['Key']
        config.include_server_header = False  # This doesn't seem to do anything?
        config.use_reloader = False
        config.debug = False
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        http_blueprint = Blueprint(__name__, 'https')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        #logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        #logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
コード例 #3
0
    def run(self):
        if (self['Key'] == f'{self.certs_path}/artic2_private.key') and (
                self['Cert'] == f'{self.certs_path}/artic2_cert.pem'):
            if not os.path.exists(get_path_in_data_folder(
                    "artic2_private.key")) or not os.path.exists(
                        get_path_in_data_folder(
                            "artic2_cert.pem")) or self['RegenCert']:
                create_self_signed_cert()

        config = Config()
        config.ciphers = 'ALL'
        config.accesslog = os.path.join(get_path_in_artic2("logs"),
                                        "access.log")
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.certfile = os.path.expanduser(self['Cert'])
        config.keyfile = os.path.expanduser(self['Key'])
        config.include_server_header = False
        config.use_reloader = False
        config.debug = False
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        http_blueprint = Blueprint(__name__, 'https')
        http_blueprint.before_request(self.check_if_naughty)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
コード例 #4
0
    def _create(app: ASGI3Framework,
                config: Config = None,
                event_loop: AbstractEventLoop = None) -> HypercornServer:
        if not config:
            config = Config()
            config.bind = f"localhost:{net.get_free_tcp_port()}"

        srv = HypercornServer(app, config, loop=event_loop)
        _servers.append(srv)
        srv.start()
        assert srv.wait_is_up(
            timeout=10), "gave up waiting for server to start up"
        return srv
コード例 #5
0
ファイル: cli.py プロジェクト: jsiembida/quart
def run_command(info: ScriptInfo, host: str, port: int) -> None:
    config = Config()
    config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
    config.access_logger = create_serving_logger()
    config.debug = True
    config.error_logger = config.access_logger
    config.host = host
    config.port = port
    config.use_reloader = True
    run_single(info.load_app(), config)
コード例 #6
0
    def run(self):

        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        config = Config()
        config.accesslog = os.path.join(get_path_in_data_folder("logs"), "access.log")
        config.bind = f"{self['BindIP']}:{self['Port']}"
        config.insecure_bind = True
        config.include_server_header = False
        config.use_reloader = False
        config.debug = False

        http_blueprint = Blueprint(__name__, 'http')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>', 'key_exchange', self.key_exchange, methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>', 'stage', self.stage, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs', 'jobs', self.jobs, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>', 'job_result', self.job_result, methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/', 'unknown_path', self.unknown_path, defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>', 'unknown_path', self.unknown_path, methods=['GET', 'POST'])

        #logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        #logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
コード例 #7
0
ファイル: gql.py プロジェクト: linuseing/hub
 async def setup(self):
     schema = make_executable_schema(self.type_defs, self.query,
                                     self.subscription, self.mutations)
     app = CORSMiddleware(
         GraphQL(schema),
         allow_origins=["*"],
         allow_methods=("GET", "POST", "OPTIONS"),
     )
     conf = Config()
     conf.bind = ["0.0.0.0:8006"]
     conf.loglevel = "fatal"  # to suppress lifespan error
     LOGGER.info("starting GQL API")
     try:  # also to suppress lifespan error
         await serve(app, conf)
     except Exception as e:
         print(e)
コード例 #8
0
ファイル: edge.py プロジェクト: localstack/localstack
def serve_gateway(bind_address, port, use_ssl, asynchronous=False):
    """
    Implementation of the edge.do_start_edge_proxy interface to start a Hypercorn server instance serving the
    LocalstackAwsGateway.
    """
    from hypercorn import Config

    from localstack.aws.app import LocalstackAwsGateway
    from localstack.aws.serving.asgi import AsgiGateway
    from localstack.http.hypercorn import HypercornServer
    from localstack.services.generic_proxy import GenericProxy, install_predefined_cert_if_available

    # build server config
    config = Config()

    if isinstance(bind_address, str):
        bind_address = [bind_address]
    config.bind = [f"{addr}:{port}" for addr in bind_address]

    if use_ssl:
        install_predefined_cert_if_available()
        _, cert_file_name, key_file_name = GenericProxy.create_ssl_cert(serial_number=port)
        config.certfile = cert_file_name
        config.keyfile = key_file_name

    # build gateway
    loop = asyncio.new_event_loop()
    app = AsgiGateway(LocalstackAwsGateway(SERVICE_PLUGINS), event_loop=loop)

    # start serving gateway
    server = HypercornServer(app, config, loop)
    server.start()

    if not asynchronous:
        server.join()

    return server._thread
コード例 #9
0
 async def _run(self) -> None:
     ssl_context = self._create_ssl_context()
     config = Config()
     if self.cfg.accesslog:
         config.access_logger = self.log.access_log
     config.access_log_format = self.cfg.access_log_format
     if self.cfg.errorlog:
         config.error_logger = self.log.error_log
     config.keep_alive_timeout = self.cfg.keepalive
     max_fields_size = self.cfg.limit_request_fields * self.cfg.limit_request_field_size
     config.h11_max_incomplete_size = self.cfg.limit_request_line + max_fields_size
     for sock in self.sockets:
         server = await self.loop.create_server(  # type: ignore
             lambda: Server(self.wsgi, self.loop, config),
             sock=sock.sock, ssl=ssl_context,
         )
         self.servers.append(server)  # type: ignore
コード例 #10
0
def run_hypercorn(app: quart.Quart):
    config = HyperConfig()
    config.access_log_format = (
        "%(h)s %(l)s %(u)s [%(asctime)s] \"%(r)s\" %(s)s %(b)s %(D)s")
    config.accesslog = logging.getLogger('quart.serving')
    config.bind = [app.config.get('LISTEN', 'localhost:5000')]
    config.errorlog = config.accesslog
    config.use_reloader = (app.env == 'development')

    loop = asyncio.get_event_loop()
    loop.add_signal_handler(signal.SIGTERM, _signal_handler)
    loop.add_signal_handler(signal.SIGINT, _signal_handler)
    loop.set_exception_handler(_loop_exception_handler)
    loop.run_until_complete(
        hypercorn_serve(
            waterfurnace.app,
            config,
            shutdown_trigger=waterfurnace.app.shutdown_trigger.wait))
コード例 #11
0
            try:
                # start server
                await serve(app, cornfig)
            finally:
                # guarantee DB connection to be closed on exception.
                await connection.aclose()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-c",
        "--config",
        type=trio.Path,
        default=ROOT.joinpath("db_conf.ini"),
        help="Path to the configuration ini file.",
    )

    # parse args
    args = parser.parse_args()

    # read configuration file
    CONFIG.read(args.config)

    # HyperCorn's config, so Cornfig. I'm sorry.
    cornfig = Config()
    cornfig.bind = "localhost:8000"

    trio.run(main_task)
コード例 #12
0
 lambda app: cherrypy.server.start(),
 'django':
 lambda app: djserver.Command().handle(addrport=f'{HOST}:{PORT}',
                                       use_reloader=RELOAD,
                                       use_threading=True,
                                       use_ipv6=False),
 'falcon':
 lambda app: run_simple(
     HOST, PORT, app, use_debugger=DEBUG, use_reloader=RELOAD),
 'flask':
 lambda app: app.run(HOST, PORT, debug=DEBUG, use_reloader=RELOAD),
 'hypercorn':
 lambda app: run.run_single(app,
                            Config.from_mapping({
                                'host': HOST,
                                'port': PORT,
                                'debug': DEBUG,
                                'use_reloader': RELOAD
                            }),
                            loop=asyncio.get_event_loop()),
 'molten':
 lambda app: run_simple(
     HOST, PORT, app, use_debugger=DEBUG, use_reloader=RELOAD),
 'pulsar':
 lambda app: WSGIServer(callable=app,
                        load_config=False,
                        bind=f'{HOST}:{PORT}',
                        debug=DEBUG,
                        reload=RELOAD).start(),
 'pyramid':
 lambda app: run_simple(
     HOST, PORT, app, use_debugger=DEBUG, use_reloader=RELOAD),
コード例 #13
0
        return rtn(1, "noJSON")
    else:
        try:
            for i in addrs:
                if i["name"] == form["name"]:
                    return rtn(1, "exist")
            addrs.append({"name": form["name"], "ipv6": form["ipv6"], "ipv4": form["ipv4"]})
        except:
            if "name" not in form:
                return rtn(1, "no name")
            elif "ipv6" not in form:
                return rtn(1, "no ipv6")
            elif "ipv4" not in form:
                return rtn(1, "no ipv4")
            else:
                return rtn(1, "Unknown Error")
    return rtn()


if __name__ == '__main__':
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))
    config = Config()
    config.bind = ["0.0.0.0:5699", ":::5699"]
    config.access_logger = logger
    config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
    config.error_logger = logger
    asyncio.run(serve(app=app, config=config))
    # app.run(host="0.0.0.0",port=5699,use_reloader=True)
コード例 #14
0
        await websocket.send(rtn(1, "No Join"))


def get_tools(user_table, logger):
    ctools = ClientTools(user_table, logger)
    sstools = ServerSTools("pppwaw", ctools, logger)
    sctools = ServerCTools(sstools, logger)
    ctools.set_stools(sstools)
    sstools.set_url_queue(sctools.urlqueue)
    return ctools, sstools, sctools


if __name__ == '__main__':
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))
    config = Config()
    config.bind = ["0.0.0.0:5700", ":::5700"]
    config.access_logger = logger
    config.error_logger = logger
    config.use_reloader = False
    ctools, stools, sctools = get_tools("user.json", logger)
    web = lambda: asyncio.run(serve(app=app, config=config))
    sts = lambda: sctools.main()  # servertoserver
    pool = [
        multiprocessing.Process(target=web),
        multiprocessing.Process(target=sts)
    ]
    [i.start() for i in pool]
    [i.join() for i in pool]