Exemplo n.º 1
0
    def _create_site(self) -> Optional[Union[TCPSite, UnixSite]]:
        site = None
        transport = self.app.conf.web_transport.scheme

        if transport == 'tcp':
            site = TCPSite(self._runner, self.app.conf.web_bind,
                           self.app.conf.web_port)
        elif transport == 'unix':
            site = UnixSite(self._runner, self.app.conf.web_transport.path)

        return site
Exemplo n.º 2
0
async def serve(loop, settings):

    app = await trackers.web_app.make_aio_app(settings)
    runner = AppRunner(
        app,
        debug=settings.get('aioserver_debug', False),
        access_log_format='%l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'
    )
    await runner.setup()

    if settings['server_type'] == 'inet':
        site = TCPSiteSocketName(runner, settings['inet_host'],
                                 settings['inet_port'])
    elif settings['server_type'] == 'unix':
        unix_path = settings['unix_path']
        if os.path.exists(unix_path):
            try:
                os.unlink(unix_path)
            except OSError:
                logging.exception(
                    "Could not unlink socket '{}'".format(unix_path))
        site = UnixSite(runner, unix_path)

    await site.start()

    if settings['server_type'] == 'unix':
        if 'unix_chmod' in settings:
            os.chmod(unix_path, settings['unix_chmod'])
        if 'unix_chown' in settings:
            shutil.chown(unix_path, **settings['unix_chown'])

    logging.info(f'Serving on {site.name}')

    try:
        # Run forever (or we get interupt)
        run_fut = asyncio.Future()
        for signame in ('SIGINT', 'SIGTERM'):
            loop.add_signal_handler(getattr(signal, signame),
                                    run_fut.set_result, None)
        try:
            await run_fut
        finally:
            for signame in ('SIGINT', 'SIGTERM'):
                loop.remove_signal_handler(getattr(signal, signame))
    finally:
        await site.stop()
        await runner.cleanup()
Exemplo n.º 3
0
 def _new_transport_unix(self) -> BaseSite:
     return UnixSite(
         self._runner,
         self.app.conf.web_transport.path,
     )
Exemplo n.º 4
0
def run_server(
        application,
        *,
        # asyncio config.
        threads=4,
        # Server config.
        host=None,
        port=8080,
        # Unix server config.
        unix_socket=None,
        unix_socket_perms=0o600,
        # Shared server config.
        backlog=1024,
        # aiohttp config.
        static=(),
        static_cors=None,
        script_name="",
        shutdown_timeout=60.0,
        **kwargs):
    # Set up async context.
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    assert threads >= 1, "threads should be >= 1"
    executor = ThreadPoolExecutor(threads)
    # Create aiohttp app.
    app = Application()
    # Add static routes.
    static = [(format_path(path), dirname) for path, dirname in static]
    for path, dirname in static:
        app.router.add_static(path, dirname)
    # Add the wsgi application. This has to be last.
    app.router.add_route(
        "*",
        "{}{{path_info:.*}}".format(format_path(script_name)),
        WSGIHandler(application, loop=loop, executor=executor,
                    **kwargs).handle_request,
    )
    # Configure middleware.
    if static_cors:
        app.middlewares.append(
            static_cors_middleware(
                static=static,
                static_cors=static_cors,
            ))
    # Start the app runner.
    runner = AppRunner(app)
    loop.run_until_complete(runner.setup())
    # Set up the server.
    if unix_socket is not None:
        site = UnixSite(runner,
                        path=unix_socket,
                        backlog=backlog,
                        shutdown_timeout=shutdown_timeout)
    else:
        site = TCPSite(runner,
                       host=host,
                       port=port,
                       backlog=backlog,
                       shutdown_timeout=shutdown_timeout)
    loop.run_until_complete(site.start())
    # Set socket permissions.
    if unix_socket is not None:
        os.chmod(unix_socket, unix_socket_perms)
    # Report.
    server_uri = " ".join(
        "http://{}:{}".format(*parse_sockname(socket.getsockname()))
        for socket in site._server.sockets)
    logger.info("Serving on %s", server_uri)
    try:
        yield loop, site
    finally:
        # Clean up unix sockets.
        for socket in site._server.sockets:
            host, port = parse_sockname(socket.getsockname())
            if host == "unix":
                os.unlink(port)
        # Close the server.
        logger.debug("Shutting down server on %s", server_uri)
        loop.run_until_complete(site.stop())
        # Shut down app.
        logger.debug("Shutting down app on %s", server_uri)
        loop.run_until_complete(runner.cleanup())
        # Shut down executor.
        logger.debug("Shutting down executor on %s", server_uri)
        executor.shutdown()
        # Shut down loop.
        logger.debug("Shutting down loop on %s", server_uri)
        loop.close()
        asyncio.set_event_loop(None)
        # All done!
        logger.info("Stopped serving on %s", server_uri)