Example #1
0
def setGreedCoro(loop: asyncio.AbstractEventLoop):
    greedy_threshold = os.environ.get('SYN_GREEDY_CORO')
    if greedy_threshold is not None:  # pragma: no cover
        logger.info(
            f'Setting ioloop.slow_callback_duration to {greedy_threshold}')
        loop.set_debug(True)
        loop.slow_callback_duration = float(greedy_threshold)
Example #2
0
def setup_logging(args: argparse.Namespace, conf: Config,
                  loop: asyncio.AbstractEventLoop):
    default_formatter = logging.Formatter(
        "%(asctime)s %(levelname)-8s %(name)s:%(lineno)d: %(message)s")
    file_handler = logging.handlers.RotatingFileHandler(conf.log_file_path,
                                                        maxBytes=2097152,
                                                        backupCount=5)
    file_handler.setFormatter(default_formatter)
    log.addHandler(file_handler)
    logging.getLogger('torba').addHandler(file_handler)

    if not args.quiet:
        handler = logging.StreamHandler()
        handler.setFormatter(default_formatter)
        log.addHandler(handler)
        logging.getLogger('torba').addHandler(handler)
        logging.getLogger('torba').setLevel(logging.INFO)

    logging.getLogger('aioupnp').setLevel(logging.WARNING)
    logging.getLogger('aiohttp').setLevel(logging.CRITICAL)

    log.setLevel(logging.INFO)
    if args.verbose is not None:
        loop.set_debug(True)
        if len(args.verbose) > 0:
            for module in args.verbose:
                logging.getLogger(module).setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.DEBUG)

    if conf.share_usage_data:
        loggly_handler = get_loggly_handler()
        loggly_handler.setLevel(logging.ERROR)
        log.addHandler(loggly_handler)
Example #3
0
def enable_async_loop_debugging(
        event_loop: AbstractEventLoop) -> AbstractEventLoop:
    logging.info("Enabling coroutine debugging. Loop id {}.".format(
        id(asyncio.get_event_loop())))

    # Enable debugging
    event_loop.set_debug(True)

    # Make the threshold for "slow" tasks very very small for
    # illustration. The default is 0.1 (= 100 milliseconds).
    event_loop.slow_callback_duration = 0.001

    # Report all mistakes managing asynchronous resources.
    warnings.simplefilter("always", ResourceWarning)
    return event_loop
Example #4
0
def enable_async_loop_debugging(
        event_loop: AbstractEventLoop,
        slow_callback_duration: float = 0.1) -> AbstractEventLoop:
    """Enables debugging on an event loop.

    Args:
        event_loop: The event loop to enable debugging on
        slow_callback_duration: The threshold at which a callback should be
                                alerted as slow.
    """
    logging.info("Enabling coroutine debugging. Loop id {}.".format(
        id(asyncio.get_event_loop())))

    # Enable debugging
    event_loop.set_debug(True)

    # Make the threshold for "slow" tasks very very small for
    # illustration. The default is 0.1 (= 100 milliseconds).
    event_loop.slow_callback_duration = slow_callback_duration

    # Report all mistakes managing asynchronous resources.
    warnings.simplefilter("always", ResourceWarning)
    return event_loop
def async_debug(loop: asyncio.AbstractEventLoop):
    loop.set_debug(True)
    logging.basicConfig(level=logging.DEBUG)
Example #6
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)