Skip to content

Commit

Permalink
Merge pull request mitmproxy#2610 from mhils/log-threadsafe
Browse files Browse the repository at this point in the history
Make master.add_log threadsafe
  • Loading branch information
mhils authored Oct 26, 2017
2 parents 671b012 + 7314081 commit b32dff7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 8 additions & 1 deletion mitmproxy/addonmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from mitmproxy import eventsequence
from mitmproxy import controller
from mitmproxy import flow
from mitmproxy import log
from . import ctx
import pprint

Expand Down Expand Up @@ -54,7 +55,13 @@ def flush(self): # pragma: no cover

@contextlib.contextmanager
def safecall():
stdout_replacement = StreamLog(ctx.log.warn)
# resolve ctx.master here.
# we want to be threadsafe, and ctx.master may already be cleared when an addon prints().
tell = ctx.master.tell
# don't use master.add_log (which is not thread-safe). Instead, put on event queue.
stdout_replacement = StreamLog(
lambda message: tell("log", log.LogEntry(message, "warn"))
)
try:
with contextlib.redirect_stdout(stdout_replacement):
yield
Expand Down
5 changes: 3 additions & 2 deletions test/mitmproxy/addons/test_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from mitmproxy import addonmanager
from mitmproxy import exceptions
from mitmproxy import log
from mitmproxy.addons import script
from mitmproxy.test import taddons
from mitmproxy.test import tflow
Expand Down Expand Up @@ -50,15 +51,15 @@ def test_load_fullname():

def test_script_print_stdout():
with taddons.context() as tctx:
with mock.patch('mitmproxy.ctx.log.warn') as mock_warn:
with mock.patch('mitmproxy.ctx.master.tell') as mock_warn:
with addonmanager.safecall():
ns = script.load_script(
tutils.test_data.path(
"mitmproxy/data/addonscripts/print.py"
)
)
ns.load(addonmanager.Loader(tctx.master))
mock_warn.assert_called_once_with("stdoutprint")
mock_warn.assert_called_once_with("log", log.LogEntry("stdoutprint", "warn"))


class TestScript:
Expand Down

0 comments on commit b32dff7

Please sign in to comment.