Repository navigation
Description
i use mitmproxy for interactive browsing a lot.
that is, i run an mitmdump instance continuously, and use it from multiple browsers on multiple computers.
recently this started to be a rather frustrating experience.
i suspect it's related to the new proxy core,
or it could be related to debian upgrading to python 3.9? sadly it turned out non-trivial to roll this back.
initially after mitmproxy startup, everything works smoothly, but then suddenly stalls,
many requests hang for a very long time until mitmproxy returns a response.
sometimes this starts almost immediately, sometimes after hours,
it possibly recovers by itself, but usually i give up waiting and restart mitmproxy.
(most times the requests seem to do finish, but only after many minutes.)
this is probably most easily reproduced with resource-heavy sites, like facebook.com, openstreetmap.org, ...
in netstat, i don't see mitmproxy having many connections to the destination servers open, so i suspect it's an internal limitation.
( i typically check with $ netstat -ntp | grep EST.*python | grep -v :8080 | awk '{print $5}' | sort | uniq -c | sort -n)
my initial suspicion was that there is a limit on the number of concurrent connections, and that that pool is used up by connections that are in some invalid state and/or waiting for a timeout.
i already found a per-connection.address] limit at
mitmproxy/mitmproxy/proxy/server.py
Line 84 in dc6c5f5
| self.max_conns = collections.defaultdict(lambda: asyncio.Semaphore(5)) |
and increased it significantly, but that did not lead to consistent improvements.
(i also added a warning on
if self.max_conns[command.connection.address].locked():, but it doesn't seem to trigger.)
can you suggest what else i could do to diagnose this?
is there another connection limit besides max_conns in proxy?
is there existing code/facilities to introspect/dump the currently open incoming connections and their state?
an option to log connection-level tracing info?
System Information
Paste the output of "mitmproxy --version" here.
(venv) user@host[~/mitmproxy]$ mitmproxy --version
Mitmproxy: 7.0.0.dev (+332, commit aebc40c)
Python: 3.9.1+
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: Linux-5.8.0-1-amd64-x86_64-with-glibc2.31
Activity
mhils commentedon Feb 15, 2021
Thanks, this is super important feedback!
curl -x localhost:8080 -k mitmproxy.orgstill work?You can also try running
mitmdump --set proxy_debug -vvv > logfile, which is very verbose. More practical: mitmproxy dumps a whole lot of state when you send a SIGUSR1 signal to it.r00t- commentedon Feb 15, 2021
essentially mitmdump (note, not mitmproxy, which obviously keeps the data around for the GUI) seems to allocate memory for any data it transmits and only free it on exit, but i realize my use-case is not the most common one, so i'm fine with restarting it regularly to cope with that.
(sometimes it goes beyond that even, and the usage skyrockets until the system goes OOM, i'm guessing this is due to some particular requests)
i have grafana graphs for this.
max_conns.i.e. either of facebook or openstreetmap or duckduckgo will hang, while other sites continue loading fine.
mitmproxytomitmdumpin my report, but then it was already hanging again ;)max_conns.locked()warning, which also did not seem to fire.r00t- commentedon Feb 15, 2021
thanks for pointing out SIGUSR1,
(i found that mitmproxy crashed after printing the log, maybe good for another issue?
sys:1: RuntimeWarning: coroutine 'ConnectionHandler.hook_task' was never awaited)here's the dump, maybe you can make anything of it:
https://gist.github.com/r00t-/a35b52b68cd457a455bc515c4294a36a
(i left the names of some public websites in, that's ok)
(will also add
--set proxy_debug -vvvand hope my disk will cope with it)r00t- commentedon Feb 15, 2021
thanks for pointing out SIGUSR1,
(i found that mitmproxy crashed after printing the log, maybe good for another issue?
sys:1: RuntimeWarning: coroutine 'ConnectionHandler.hook_task' was never awaited)here's the dump, can maybe you can make anything of this:
https://gist.github.com/r00t-/a35b52b68cd457a455bc515c4294a36a
(i left the names of some public websites in, that's ok)
(will also add
--set proxy_debug -vvvand hope my disk will cope with it)r00t- commentedon Feb 15, 2021
the above duplicate post is a good example.
i tried to post it through mitmproxy, and it stalled.
i re-submitted it in a browser session not using mitmproxy (but left the original attempt running)
and then twelve minutes later the post-request made it through mitmproxy.
r00t- commentedon Feb 16, 2021
i tried
SIGUSR1with a known hanging connection (from browser's network debug view),and could not identify that connection in the dumped list. (at least not by destination hostname.)
enabled the verbose log (six times as large as the actual dump, but manageable).
for what i tried, i could also not pinpoint a hanging connection there, but did not try for long.
i went back to the debian package, and have not seen the issue since.
mhils commentedon Feb 16, 2021
Thanks! This is incredibly helpful.
Interesting! The "crashing" is intentional:
mitmproxy/mitmproxy/utils/debug.py
Lines 102 to 103 in aebc40c
...but the warning you saw is not:
This means we created a coroutine, but then never let it run. The only place where we create
hook_taskcoroutines is here:mitmproxy/mitmproxy/proxy/server.py
Lines 299 to 304 in bc3f39a
asyncio_utils.create_taskis a thin wrapper aroundasyncio.create_task, and the latter schedules the coroutine to be run on the event loop immediately. However, the error message indicates that the coroutine is never run. There are two possible reasons for that:It would be interesting to see if this warning was a fluke or if you get some warnings repeatedly.
curl -x localhost:8080 -k facebook.comfrom a separate terminal still work?r00t- commentedon Feb 16, 2021
-p,-wand a short--ignore-hostslist, and the debug changes in proxy.py mentioned above.r00t- commentedon Feb 16, 2021
you got me there.
actually it seems i never looked at the stderr logs in detail,
only when mitmdump exited (for me) unexpectedly after SIGUR1.
in the SIGUSR1 case, i saw a few instances of "mitmproxy hash crashed" with a traceback leading to
and also the
was never awaitedmessage, which looked far more suspicious.here's statistics for the root causes of exceptions, can you say which might be interesting to you?
these maybe?
or these:
(note that in general my system is not low on memory when the issue occurs.
but as mentioned, it sometimes does run out of memory, which could be causing some of these,
but not all.)
mhils commentedon Feb 16, 2021
Excellent, thanks. Based on what you are describing, my assumption would be that
curlfrom a different window should still work fine, we're "only" getting the browser in a state where all connections are stalled. That kind of stuff persists across browser tabs.Let me focus on
AttributeError: 'NoneType' object has no attribute 'state_machine'first, which seems like an easy bug in our HTTP/2 state machine. I can reproduce this locally on openstreetmap.org (#4452), which thank to you I learned is an excellent resource to uncover HTTP/2 race conditions. Better than testing with nytimes.com 😄The OpenSSL one is puzzling. I can't reproduce it and I don't expect it to disappear after fixing #4452, but let's tackle them one-by-one.
r00t- commentedon Feb 16, 2021
as for
curl:i switched back to mitmproxy from git,
and started this script while also browsing openstreetmap.org:
$ while time http_proxy=http://localhost:8080/ timeout 60 curl -v a.tile.openstreetmap.org ; do : ;doneand while the timeout was not hit yet, i see some of those requests taking 40 seconds, average guessed at ~15 seconds.
(they take <1 second without proxy).
also i still have max_conns set to 1024 instead of 5 (so it shouldn't be blocking on that), and system load isn't heavy.
and most of the time mitmdump doesn't actually hold a connection to the remote server at all:
i never see more than one in ESTABLISHED state (typically zero). while multiple clients are waiting on requests to that host.
mhils commentedon Feb 16, 2021
@r00t-: Thanks for all the help in tracking this down. I've just merged a PR that fixes the state machine bug, and I can't trigger any crashes locally now. Which browser are you on for your openstreetmap tests?
mhils commentedon Feb 16, 2021
On
7.0.0.dev (+333, commit c8eca9a)with Firefox 85.0.2 on Windows 10, I can't reproduce #4451 (comment). curl consistently loads <1s, the browser shows no issues, and there are no errors for me in the event log.r00t- commentedon Feb 17, 2021
thanks for providing this great tool and your work on improving it!
i'm running c8eca9a for ~8 hours now.
i can confirm the
state_machinecrashes are gone,only those from openssl remain:
and it DOES seem that #4452 was the biggest source of slowness,
i haven't seen multi-minute delays again since the #4452 fix.
40 remaining items
mhils commentedon Feb 21, 2021
HTTP/2 is a tricky, tricky protocol. 😉 Facebook upload now works flawlessly for me with #4464 applied. Can you confirm?
r00t- commentedon Feb 21, 2021
checking...
i just ran into this cool test page,
it gets mitmdump's cpu usage above 100% (by embedding ~1.7k images in a single page):
https://github.com/ikatyang/emoji-cheat-sheet/blob/master/README.md
didn't error out, but took a few minutes to load, other requests suffered a lot during that time, and - before i noticed i had clicked that link - the debug output looked like mitmproxy got into a loop talking to itself.
mhils commentedon Feb 21, 2021
On Windows, the page you linked only issues ~50 requests. Everything else is served as Emojis. 😄
r00t- commentedon Feb 21, 2021
as it seems that every website i mention leads to you finding bugs, let's try another,
while also getting back to the original topic of this issue ticket:
one website that even with all the fixes so far is still no fun to browse with mitmproxy,
but where i'm sadly unable to pinpoint the specific issue, and thus hesitant to report it
(but that is also likely to run a custrom http stack),
is aliexpress ("amazon for china imports").
just run some search, like: https://www.aliexpress.com/wholesale?SearchText=usb+c
and scroll down the page for a bit while opening results in new tabs (10-20 of them maybe),
without mitmproxy, by the time i switch to any of the new tabs, it's already mostly finished loading.
with mitmproxy, i have to wait for many minutes until they finish loading, if they ever do.
speculative HTTP/2 fixes, refs #4451 (#4464)
mhils commentedon Feb 21, 2021
@r00t-: What kind of CPU usage do you have on Aliexpress? Loads generally fine for me, but of course quickly opening 20 tabs with 50 requests each is no easy feat. We're not really built to handle high volumes.
To expand on this, I've written a small benchmarking tool a while ago which gives me the following stats on my machine:
What you are seeing is numbers for a client -> mitmdump as reverse proxy -> server setting in 9 different configurations. https denotes TLS handshakes between all ends, h2 denotes HTTP/2, and the number after the last slash is the number of concurrent clients who work on a shared backlog of 100 requests.
Long story short, a realistic expectation is somewhere between 50-200 requests/s. We could optimize for more here, but large-scale "mass interception" is not really something we are aiming for.
r00t- commentedon Feb 21, 2021
thanks for your insights on this one.
i'm only looking to capture my own personal traffic :)
and i could live with a limited request rate, if any queued up requests would still finish be it minutes later i wouldn't care - but they don't seem to. (but it could also be the application misbehaving if requests are slow, that i can't tell)
i will try to get your benchmark running on my hardware.
can you maybe come up with some quick code to log the number of queued/outstanding requests from the mitmproxy mainloop?
(the debug log is not really useful for such large numbers of requests.)
mhils commentedon Feb 21, 2021
This isn't super accurate, but
print(f"{len(self.active_flows)=}")in one of the event hooks in https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/save.py should give you a rough estimate. That does not include requests that have not reached therequestheadershook yet.r00t- commentedon Feb 23, 2021
it appears that the issue with aliexpress disappeared when i removed
--set proxy_debug -vvv,so possibly it was the extra cpu load generated by the logging that caused the extreme slowness.
(i had issues with that site before the fixes, so those were probably already resolved by your other changes.)
i might still try the benchmark (with and without proxy_debug),
but it doesn't look like i'll get to it soon.
so if you like, this can be closed for now.
thanks for this great tool and your dedication to improving it!
r00t- commentedon Mar 11, 2021
just noticed: your fixes also fixed https://buff.ly/
magodo commentedon Jul 25, 2022
@mhils I observed that when "peer closed connection" error occurs, I always need to wait for 10 minutes until the client retry logic take into place. This is happening in (at least) v8.0.0 of mitmproxy. Is there a way that I can modify the timeout interval for the watchdog? Or mitmproxy can detect this automatically?
mhils commentedon Jul 25, 2022
@magodo: Do you have a repro/example of the behavior you're seeing? The timeout watchdog should only kick in to remove absolutely dead connections, it's the wrong tool for the job here.
magodo commentedon Jul 25, 2022
@mhils Appreciate for the quick response 👍
I don't have a steady repro, the issue happens intermittently when I'm sending APIs to some platform. I've checked the underlying API client code and ensured the retry logic of it won't wait for so long time (10 min), even it doesn't specifically handle the reset error. So I suspect it is due to mitmproxy.
mhils commentedon Jul 25, 2022
We do indeed kill open connections after 10 minutes of total inactivity. In this case it sounds like the client is still waiting for a response for some reason. A log with
--set proxy_debug -vvvwould go a long way in identifying the root cause. Feel free to shoot that by email if you have sensitive stuff in there.