Merge pull request #5318 from nneonneo/fix-exit-shutdown

Fix terminal breakage if an error occurs at startup
This commit is contained in:
Maximilian Hils 2022-05-05 10:57:08 +02:00 committed by GitHub
commit c91685efeb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 8 deletions

View file

@ -1,6 +1,5 @@
import asyncio
import sys
from typing import Optional
from mitmproxy import log
@ -9,12 +8,12 @@ class ErrorCheck:
"""Monitor startup for error log entries, and terminate immediately if there are some."""
def __init__(self, log_to_stderr: bool = False):
self.has_errored: Optional[str] = None
self.has_errored: list[str] = []
self.log_to_stderr = log_to_stderr
def add_log(self, e: log.LogEntry):
if not self.has_errored and e.level == "error":
self.has_errored = e.msg
if e.level == "error":
self.has_errored.append(e.msg)
async def running(self):
# don't run immediately, wait for all logging tasks to finish.
@ -23,5 +22,8 @@ class ErrorCheck:
async def _shutdown_if_errored(self):
if self.has_errored:
if self.log_to_stderr:
print(f"Error on startup: {self.has_errored}", file=sys.stderr)
plural = "s" if len(self.has_errored) > 1 else ""
msg = "\n".join(self.has_errored)
print(f"Error{plural} on startup: {msg}", file=sys.stderr)
sys.exit(1)

View file

@ -46,9 +46,11 @@ class Master:
# Handle scheduled tasks (configure()) first.
await asyncio.sleep(0)
await self.running()
await self.should_exit.wait()
await self.done()
try:
await self.should_exit.wait()
finally:
# .wait might be cancelled (e.g. by sys.exit)
await self.done()
finally:
self.event_loop.set_exception_handler(old_handler)