<commit_before>import asyncio
import logging
import sys
import threading
import traceback

from mitmproxy import addonmanager, hooks
from mitmproxy import command
from mitmproxy import eventsequence
from mitmproxy import http
from mitmproxy import log
from mitmproxy import options
from mitmproxy.net import server_spec
from . import ctx as mitmproxy_ctx

# Conclusively preventing cross-thread races on proxy shutdown turns out to be
# very hard. We could build a thread sync infrastructure for this, or we could
# wait until we ditch threads and move all the protocols into the async loop.
# Until then, silence non-critical errors.
logging.getLogger('asyncio').setLevel(logging.CRITICAL)


class Master:
    """
        The master handles mitmproxy's main event loop.
    """

    def __init__(self, opts):
        self.should_exit = threading.Event()
        self.event_loop = asyncio.get_event_loop()
        self.options: options.Options = opts or options.Options()
        self.commands = command.CommandManager(self)
        self.addons = addonmanager.AddonManager(self)
        self._server = None
        self.log = log.Log(self)

        mitmproxy_ctx.master = self
        mitmproxy_ctx.log = self.log
        mitmproxy_ctx.options = self.options

    def start(self):
        self.should_exit.clear()

    async def running(self):
        self.addons.trigger(hooks.RunningHook())

    def run_loop(self, loop):
        self.start()
        asyncio.ensure_future(self.running())

        exc = None
        try:
            loop()
        except Exception:  # pragma: no cover
            exc = traceback.format_exc()
        finally:
            if not self.should_exit.is_set():  # pragma: no cover
                self.shutdown()
            loop = asyncio.get_event_loop()
            tasks = asyncio.all_tasks(loop)
            for p in tasks:
                p.cancel()
            loop.close()

        if exc:  # pragma: no cover
            print(exc, file=sys.stderr)
            print("mitmproxy has crashed!", file=sys.stderr)
            print("Please lodge a bug report at:", file=sys.stderr)
            print("\thttps://github.com/mitmproxy/mitmproxy/issues", file=sys.stderr)

        self.addons.trigger(hooks.DoneHook())

    def run(self):
        loop = asyncio.get_event_loop()
        self.run_loop(loop.run_forever)
<commit_msg>set an exception handler for asyncio, fix #5159, refs #5016<commit_after>import asyncio
import logging
import sys
import threading
import traceback
from typing import Callable

from mitmproxy import addonmanager, hooks
from mitmproxy import command
from mitmproxy import eventsequence
from mitmproxy import http
from mitmproxy import log
from mitmproxy import options
from mitmproxy.net import server_spec
from . import ctx as mitmproxy_ctx

# Conclusively preventing cross-thread races on proxy shutdown turns out to be
# very hard. We could build a thread sync infrastructure for this, or we could
# wait until we ditch threads and move all the protocols into the async loop.
# Until then, silence non-critical errors.
logging.getLogger('asyncio').setLevel(logging.CRITICAL)


class Master:
    """
        The master handles mitmproxy's main event loop.
    """

    def __init__(self, opts):
        self.should_exit = threading.Event()
        self.event_loop = asyncio.get_event_loop()
        self.options: options.Options = opts or options.Options()
        self.commands = command.CommandManager(self)
        self.addons = addonmanager.AddonManager(self)
        self._server = None
        self.log = log.Log(self)

        mitmproxy_ctx.master = self
        mitmproxy_ctx.log = self.log
        mitmproxy_ctx.options = self.options

    def start(self):
        self.should_exit.clear()

    async def running(self):
        self.addons.trigger(hooks.RunningHook())

        # We set the exception handler here because urwid's run() method overwrites it.
        asyncio.get_running_loop().set_exception_handler(self._asyncio_exception_handler)

    def _asyncio_exception_handler(self, loop, context):
        exc: Exception = context["exception"]
        if isinstance(exc, OSError) and exc.errno == 10038:
            return  # suppress https://bugs.python.org/issue43253
        self.log.error(
            "\n".join(traceback.format_exception(exc)) +
            "\nPlease lodge a bug report at:" +
            "\n\thttps://github.com/mitmproxy/mitmproxy/issues"
        )

    def run_loop(self, run_forever: Callable) -> None:
        self.start()
        asyncio.ensure_future(self.running())

        exc = None
        try:
            run_forever()
        except Exception:  # pragma: no cover
            exc = traceback.format_exc()
        finally:
            if not self.should_exit.is_set():  # pragma: no cover
                self.shutdown()
            loop = asyncio.get_event_loop()
            tasks = asyncio.all_tasks(loop)
            for p in tasks:
                p.cancel()
            loop.close()

        if exc:  # pragma: no cover
            print(exc, file=sys.stderr)
            print("mitmproxy has crashed!", file=sys.stderr)
            print("Please lodge a bug report at:", file=sys.stderr)
            print("\thttps://github.com/mitmproxy/mitmproxy/issues", file=sys.stderr)

        self.addons.trigger(hooks.DoneHook())

    def run(self):
        loop = asyncio.get_event_loop()
        self.run_loop(loop.run_forever)

{'fraction_non_alphanumeric': 0.08887256702166728, 'fraction_numerical': 0.0033051781123760557, 'mean_word_length': 2.5554830287206265, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6468882', 'n_tokens_mistral': 1586, 'n_tokens_neox': 1531, 'n_words': 435}