Exemplo n.º 1
0
	def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]:
		assert self._handler is None
		self._handler = self.app.make_handler(loop = loop)
		loop.run_until_complete(self.app.startup())
		
		ret = []
		if not self.ssl_only:
			ret.append(loop.create_server(self._handler, self.host, self.port, ssl = None))
		if self.ssl_context is not None:
			ret.append(loop.create_server(self._handler, self.host, (self.port if self.ssl_only else 443), ssl = self.ssl_context))
		return ret
Exemplo n.º 2
0
def initialize(loop: asyncio.AbstractEventLoop, port: int, username: str, password: str, dbcon: DBConnection,
               active_monitor_manager: ActiveMonitorManager) -> None:
    """Initialize the webmgmt listener."""
    stats.set('num_calls', 0, 'WEBMGMT')
    app = web.Application(loop=loop, logger=log.logger,
                          middlewares=[
                              middleware.logging_middleware_factory,
                              middleware.error_handler_middleware_factory,
                              middleware.basic_auth_middleware_factory,
                          ])
    app['username'] = username
    app['password'] = password
    app['dbcon'] = dbcon
    app['active_monitor_manager'] = active_monitor_manager
    setup_routes(app)
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.PackageLoader('irisett.webmgmt', 'templates'),
        filters={
            'timestamp': jinja_filters.timestamp
        },
    )

    listener = loop.create_server(app.make_handler(), '0.0.0.0', port)
    asyncio.ensure_future(listener)
    log.msg('Webmgmt listening on port %s' % port)
Exemplo n.º 3
0
 def create_server(self,
                   loop: asyncio.AbstractEventLoop = None,
                   host='0.0.0.0',
                   port=2775):
     factory = loop.create_server(lambda: SmppProtocol(app=self),
                                  host=host,
                                  port=port)
     server = loop.run_until_complete(factory)
     return server
Exemplo n.º 4
0
def create_server(host: str="",
                  port: int=8000,
                  loop: asyncio.AbstractEventLoop=None):
    """
    Creates server sockets bound to a specific address:port supporting the protocols provided

    :param port: local port to bind
    :param host: local host to bind
    :param loop: asyncio event loop
    :return:
    """
    loop = loop or asyncio.get_event_loop()
    server = loop.create_server(Server, host=host, port=port, reuse_address=True)
    log = make_logger()
    log.info("Server Created on {}:{}".format(host, port))
    return server
Exemplo n.º 5
0
def initialize(loop: asyncio.AbstractEventLoop, port: int, username: str, password: str, dbcon: DBConnection,
               active_monitor_manager: ActiveMonitorManager) -> None:
    """Initialize the webapi listener."""
    stats.set('num_calls', 0, 'WEBAPI')
    app = web.Application(loop=loop, logger=log.logger,
                          middlewares=[
                              middleware.logging_middleware_factory,
                              middleware.error_handler_middleware_factory,
                              middleware.basic_auth_middleware_factory,
                          ])
    app['username'] = username
    app['password'] = password
    app['dbcon'] = dbcon
    app['active_monitor_manager'] = active_monitor_manager
    setup_routes(app)
    listener = loop.create_server(app.make_handler(), '0.0.0.0', port)
    loop.create_task(listener)
    log.msg('Webapi listening on port %s' % port)
Exemplo n.º 6
0
def serve_main_app(config: Config, loop: asyncio.AbstractEventLoop = None):
    setup_logging(config.verbose)

    loop = loop or asyncio.get_event_loop()

    if isinstance(config.app_factory, Application):
        app = config.app_factory
    else:
        app = config.app_factory(loop=loop)

    modify_main_app(app, config)

    loop.run_until_complete(check_port_open(config.main_port, loop))
    handler = app.make_handler(
        logger=dft_logger,
        access_log_format='%r %s %b',
        loop=loop,
    )
    co = asyncio.gather(loop.create_server(handler,
                                           HOST,
                                           config.main_port,
                                           backlog=128),
                        app.startup(),
                        loop=loop)
    server, startup_res = loop.run_until_complete(co)

    try:
        loop.run_forever()
    except KeyboardInterrupt:  # pragma: no cover
        pass
    finally:
        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.run_until_complete(app.shutdown())
        try:
            loop.run_until_complete(handler.shutdown(0.1))
        except asyncio.TimeoutError:
            pass
        loop.run_until_complete(app.cleanup())
    loop.close()
Exemplo n.º 7
0
def serve_main_app(config: Config,
                   tty_path: Optional[str],
                   loop: asyncio.AbstractEventLoop = None):
    with set_tty(tty_path):
        setup_logging(config.verbose)

        # imports the factory. This gives users a chance to register alternative event loops
        config.app_factory

        loop = loop or asyncio.get_event_loop()

        app = config.load_app(loop)

        modify_main_app(app, config)

        loop.run_until_complete(check_port_open(config.main_port, loop))
        handler = app.make_handler(
            logger=dft_logger,
            access_log_format='%r %s %b',
            loop=loop,
        )
        loop.run_until_complete(app.startup())
        server = loop.run_until_complete(
            loop.create_server(handler, HOST, config.main_port, backlog=128))

        try:
            loop.run_forever()
        except KeyboardInterrupt:  # pragma: no cover
            pass
        finally:
            server.close()
            loop.run_until_complete(server.wait_closed())
            loop.run_until_complete(app.shutdown())
            with contextlib.suppress(asyncio.TimeoutError, KeyboardInterrupt):
                loop.run_until_complete(handler.shutdown(0.1))
            with contextlib.suppress(KeyboardInterrupt):
                loop.run_until_complete(app.cleanup())
            with contextlib.suppress(KeyboardInterrupt):
                loop.close()
Exemplo n.º 8
0
def run_single(
    app: Type[ASGIFramework],
    config: Config,
    *,
    loop: asyncio.AbstractEventLoop,
    sock: Optional[socket] = None,
    is_child: bool = False,
) -> None:
    """Create a server to run the app on given the options.

    Arguments:
        app: The ASGI Framework to run.
        config: The configuration that defines the server.
        loop: Asyncio loop to create the server in, if None, take default one.
    """
    if loop is None:
        warnings.warn(
            'Event loop is not specified, this can cause unexpected errors')
        loop = asyncio.get_event_loop()

    if config.pid_path is not None and not is_child:
        _write_pid_file(config.pid_path)

    loop.set_debug(config.debug)

    if hasattr(app, 'startup'):
        loop.run_until_complete(app.startup())  # type: ignore

    if sock is not None:
        create_server = loop.create_server(
            lambda: Server(app, loop, config),
            ssl=config.ssl,
            sock=sock,
            reuse_port=is_child,
        )
    elif config.file_descriptor is not None:
        sock = socket_fromfd(config.file_descriptor, AF_UNIX, SOCK_STREAM)
        create_server = loop.create_server(
            lambda: Server(app, loop, config),
            ssl=config.ssl,
            sock=sock,
        )
    elif config.unix_domain is not None:
        create_server = loop.create_unix_server(
            lambda: Server(app, loop, config),
            config.unix_domain,
            ssl=config.ssl,
        )
    else:
        create_server = loop.create_server(
            lambda: Server(app, loop, config),
            host=config.host,
            port=config.port,
            ssl=config.ssl,
            reuse_port=is_child,
        )
    server = loop.run_until_complete(create_server)

    if platform.system() == 'Windows':
        loop.create_task(_windows_signal_support())

    try:
        loop.add_signal_handler(signal.SIGINT, _raise_shutdown)
        loop.add_signal_handler(signal.SIGTERM, _raise_shutdown)
    except NotImplementedError:
        pass  # Unix only

    reload_ = False
    try:
        if config.use_reloader:
            loop.run_until_complete(_observe_changes())
            reload_ = True
        else:
            loop.run_forever()
    except (SystemExit, KeyboardInterrupt):
        pass
    finally:
        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.run_until_complete(loop.shutdown_asyncgens())

        try:
            loop.remove_signal_handler(signal.SIGINT)
            loop.remove_signal_handler(signal.SIGTERM)
        except NotImplementedError:
            pass  # Unix only

        if hasattr(app, 'cleanup'):
            loop.run_until_complete(app.cleanup())  # type: ignore
        loop.close()
    if reload_:
        # Restart this process (only safe for dev/debug)
        os.execv(sys.executable, [sys.executable] + sys.argv)
Exemplo n.º 9
0
	def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]:
		return [loop.create_server(self._protocol, self.host, self.port, ssl = self.ssl_context)]