Example #1
0
def test_reload_dirs(tmpdir):
    update_file = os.path.join(str(tmpdir), "example.py")
    config = Config(app=None, reload_dirs=[str(tmpdir)])
    reloader = StatReload(config)
    reloader.run(wait_for_reload,
                 reloader=reloader,
                 until=1,
                 update_file=update_file)
Example #2
0
def test_statreload(certfile_and_keyfile):
    certfile, keyfile = certfile_and_keyfile
    config = Config(app=None, ssl_certfile=certfile, ssl_keyfile=keyfile)

    server = Server(config)
    type(server).run = lambda self: None

    reloader = StatReload(config)
    reloader.run(server.run)
Example #3
0
def test_statreload():
    """
    A basic sanity check.

    Simply run the reloader against a no-op server, and signal for it to
    quit immediately.
    """
    config = Config(app=None, reload=True)
    reloader = StatReload(config, target=run, sockets=[])
    reloader.signal_handler(sig=signal.SIGINT, frame=None)
    reloader.run()
Example #4
0
def run(app, **kwargs):
    config = Config(app, **kwargs)
    server = Server(config=config)

    if config.reload and not isinstance(app, str):
        config.logger_instance.warn(
            "auto-reload only works when app is passed as an import string.")

    if isinstance(app, str) and (config.debug or config.reload):
        socket = config.bind_socket()
        supervisor = StatReload(config)
        supervisor.run(server.run, sockets=[socket])
    elif config.workers > 1:
        socket = config.bind_socket()
        supervisor = Multiprocess(config)
        supervisor.run(server.run, sockets=[socket])
    else:
        server.run()
Example #5
0
def run(app, **kwargs):
    config = Config(app, **kwargs)
    server = Server(config=config)

    if config.reload and not isinstance(app, str):
        logger = logging.getLogger("uvicorn.error")
        logger.warn("auto-reload only works when app is passed as an import string.")

    if config.should_reload:
        sock = config.bind_socket()
        supervisor = StatReload(config)
        supervisor.run(server.run, sockets=[sock])
    elif config.workers > 1:
        sock = config.bind_socket()
        supervisor = Multiprocess(config)
        supervisor.run(server.run, sockets=[sock])
    else:
        server.run()
Example #6
0
def main():
    import blockexp

    directory = os.path.dirname(os.path.dirname(__file__))

    reloader = StatReload(Config(
        app=None,
        debug=True,
        reload_dirs=[directory],
    ))

    logger: Logger = reloader.config.logger_instance

    while True:
        uvicorn.run(
            f"{__name__}:app",
            host='0.0.0.0',
            port=8000,
            debug=True and RELOAD,
            reload=RELOAD,
            reload_dirs=[directory],
        )

        if not RELOAD:
            break

        logger.error("FAILURE RELOAD")

        while True:
            time.sleep(0.3)
            if reloader.should_restart():
                reloader.clear()

                # noinspection PyBroadException
                try:
                    reload(blockexp)
                    init_app(debug=True)
                except Exception:
                    traceback.print_exc()
                    logger.error("FAILURE RELOAD")
                else:
                    break
Example #7
0
def test_should_reload(tmpdir):
    update_file = Path(os.path.join(str(tmpdir), "example.py"))
    update_file.touch()

    working_dir = os.getcwd()
    os.chdir(str(tmpdir))
    try:
        config = Config(app=None, reload=True)
        reloader = StatReload(config, target=run, sockets=[])
        reloader.signal_handler(sig=signal.SIGINT, frame=None)
        reloader.startup()

        assert not reloader.should_restart()
        update_file.touch()
        assert reloader.should_restart()

        reloader.restart()
        reloader.shutdown()
    finally:
        os.chdir(working_dir)
Example #8
0
def run(app, **kwargs):
    config = Config(app, **kwargs)
    server = Server(config=config)

    if (config.reload or config.workers > 1) and not isinstance(app, str):
        logger = logging.getLogger("uvicorn.error")
        logger.warn(
            "You must pass the application as an import string to enable 'reload' or 'workers'."
        )
        sys.exit(1)

    if config.should_reload:
        sock = config.bind_socket()
        supervisor = StatReload(config, target=server.run, sockets=[sock])
        supervisor.run()
    elif config.workers > 1:
        sock = config.bind_socket()
        supervisor = Multiprocess(config, target=server.run, sockets=[sock])
        supervisor.run()
    else:
        server.run()
Example #9
0
def run(app, **kwargs):
    # Config.configure_logging = functools.partial(override_configure_logging, Config) #overwrite uvicorn method
    # kwargs["log_config"] = LOGGING_CONFIG #! overwrite
    config = Config(app, **kwargs)
    config.backlog = 2048  #! for some reason we need to specify this
    # config.log_config = LOGGING_CONFIG  #! overwrite write our own
    server = Server(config=config)

    if (config.reload or config.workers > 1) and not isinstance(app, str):
        logger.warn(
            "You must pass the application as an import string to enable 'reload' or 'workers'."
        )
        sys.exit(1)

    if config.should_reload:
        sock = config.bind_socket()
        supervisor = StatReload(config, target=server.run, sockets=[sock])
        supervisor.run()
    elif config.workers > 1:
        sock = config.bind_socket()
        supervisor = Multiprocess(config, target=server.run, sockets=[sock])
        supervisor.run()
    else:
        server.run()
Example #10
0
def test_exit_signal(tmpdir):
    config = Config(app=None)
    reloader = StatReload(config)
    reloader.run(mock_signal, handle_exit=reloader.handle_exit)
Example #11
0
    async def run(self):
        app = "bountydns.api.main:api"
        kwargs = self.get_kwargs()
        env = self.option("env")
        self.load_env(f"api.{env}")

        if self.should_import_check():
            logger.info("performing import check")
            from bountydns.api.main import api

        logger.critical("starting api server with options: {}".format(
            str(kwargs)))
        from bountydns.db.checks import is_db_up, is_db_setup

        if self.should_db_check():
            self.db_register()
            db_up = is_db_up()
            if not db_up:
                logger.critical("database not up error. please check logs")
                return self.exit(1)

        if self.option("db_setup"):
            logger.critical("running database migration")
            db_setup_options = self._args_to_dict(self.options)
            if self.option("db_seed"):
                db_setup_options["seed"] = True
            await DbSetup(db_setup_options).run()

        if self.should_db_check():
            db_setup = is_db_setup()
            if not db_setup:
                logger.critical("database not setup error. please check logs")
                return self.exit(1)

        from bountydns.broadcast import is_broadcast_up

        if self.should_bcast_check():
            bcast_up = await is_broadcast_up()
            if not bcast_up:
                logger.critical(
                    "broadcast (queue) not up error. please check logs")
                return self.exit(1)

        if self.option("db_seed_env", False):
            self.seed_from_env()

        # taken from uvicorn/main.py:run
        config = UvicornConfig(app, **kwargs)
        server = UvicornServer(config=config)

        if isinstance(app, str) and (config.debug or config.reload):
            sock = config.bind_socket()
            supervisor = StatReload(config)
            logger.warning(f"running bountydns api in dev mode...")
            return supervisor.run(server.run, sockets=[sock])
        elif config.workers > 1:
            sock = config.bind_socket()
            supervisor = Multiprocess(config)
            logger.warning(f"running bountydns api in worker mode...")
            return supervisor.run(server.run, sockets=[sock])
        else:
            sockets = None
            logger.warning(f"running bountydns api in standard mode...")
            return await server.serve(sockets=sockets)
Example #12
0
    async def run(self):
        app = "bountydns.api.main:api"
        kwargs = self.get_kwargs()
        env = self.option("env")
        self.load_env(f"api.{env}")

        if self.should_import_check():
            logger.info("run@api_server.py - Performing import check")
            from bountydns.api.main import api

        logger.critical(
            "run@api_server.py - Starting api server with options: {}".format(
                str(kwargs)))
        from bountydns.db.checks import is_db_up, is_db_setup

        # alembic just destroys the loggers, it's annoying
        if self.should_db_check():
            logger.info(
                "run@api_server.py - Waiting for database service to be up")
            db_wait_options = self._args_to_dict(self.options)
            await DbWait(db_wait_options).run()

        if self.option("db_setup"):
            logger.critical("run@api_server.py - Running database migration")
            db_setup_options = self._args_to_dict(self.options)
            if self.option("db_seed"):
                db_setup_options["seed"] = True
            await DbSetup(db_setup_options).run()

        if self.should_db_check():
            logger.info(
                "run@api_server.py - Checking if application database is setup and configured"
            )

            db_setup = is_db_setup()
            if not db_setup:
                logger.critical(
                    "run@api_server.py - Database not setup error. please check logs"
                )
                return self.exit(1)

        from bountydns.broadcast import is_broadcast_up

        if self.should_bcast_check():
            bcast_up = await is_broadcast_up()
            if not bcast_up:
                logger.critical(
                    "run@api_server.py - Broadcast (queue) not up error. please check logs"
                )
                return self.exit(1)

        if self.option("db_seed_env", False):
            self.seed_from_env()

        # taken from uvicorn/main.py:run

        logger.debug("run@api_server.py - Building Uvicorn Config and Server")
        config = UvicornConfig(app,
                               log_config=self.get_uvicorn_logging(),
                               **kwargs)
        server = UvicornServer(config=config)
        if self.option("force_exit"):
            server.force_exit = True

        if isinstance(app, str) and (config.debug or config.reload):
            logger.warning(
                f"run@api_server.py - Running bountydns api in dev mode...")
            sock = config.bind_socket()
            supervisor = StatReload(config)
            return supervisor.run(server.run, sockets=[sock])
        elif config.workers > 1:
            sock = config.bind_socket()
            supervisor = Multiprocess(config)
            logger.warning(
                f"run@api_server.py - Running bountydns api in worker mode...")
            return supervisor.run(server.run, sockets=[sock])
        else:
            sockets = None
            logger.warning(
                f"run@api_server.py - Running bountydns api in standard mode..."
            )
            return await server.serve(sockets=sockets)