Skip to content

poor interactive performance / hanging requests #4451

Closed

Description

@r00t-

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

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

  1. added
    kind/triage
    on Feb 15, 2021
  2. mhils commented on Feb 15, 2021

    @mhils
    Member

    Thanks, this is super important feedback!

    1. Can you reproduce this on 6.0.2? The most important part would be to find out if this is due to the new proxy core or due to other things. I suspect the former, but let's rule out the rest first.
    2. When it hangs, do you see any particular increase in memory or CPU usage?
    3. When it hangs, is your mitmproxy instance still accepting new connections? Does a simple curl -x localhost:8080 -k mitmproxy.org still work?
    4. When it hangs, is the UI still responsive?
    5. Is there anything interesting in mitmproxy's regular event log?

    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.

  3. r00t- commented on Feb 15, 2021

    @r00t-
    ContributorAuthor
    1. i have not yet tried to go back to a release version, will try that asap. (i had tried going back a few weeks in the git history, with inconclusive results. (and then tried downgrading python and failed.) maybe i'll have to switch to docker or something to check with an older python release.
    2. i have some strong memory usage issues aswell, but would report those separately.
      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.
    3. it only hangs for SOME remote servers, which is why i was suspecting max_conns.
      i.e. either of facebook or openstreetmap or duckduckgo will hang, while other sites continue loading fine.
    4. not using the ui, sorry i meant to change mitmproxy to mitmdump in my report, but then it was already hanging again ;)
    5. i've been hoping for anything in the log, but i can't see anything special there. which was also why i added that max_conns.locked() warning, which also did not seem to fire.
  4. r00t- commented on Feb 15, 2021

    @r00t-
    ContributorAuthor

    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 -vvv and hope my disk will cope with it)

  5. r00t- commented on Feb 15, 2021

    @r00t-
    ContributorAuthor

    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 -vvv and hope my disk will cope with it)

  6. r00t- commented on Feb 15, 2021

    @r00t-
    ContributorAuthor

    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.

  7. r00t- commented on Feb 16, 2021

    @r00t-
    ContributorAuthor

    i tried SIGUSR1 with 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.

    Mitmproxy: 6.0.2
    Python:    3.9.1+
    OpenSSL:   OpenSSL 1.1.1i  8 Dec 2020
    Platform:  Linux-5.8.0-1-amd64-x86_64-with-glibc2.31
    
  8. mhils commented on Feb 16, 2021

    @mhils
    Member

    Thanks! This is incredibly helpful.

    i found that mitmproxy crashed after printing the log, maybe good for another issue?

    Interesting! The "crashing" is intentional:

    if not testing:
    sys.exit(1)

    ...but the warning you saw is not:

    'ConnectionHandler.hook_task' was never awaited
    

    This means we created a coroutine, but then never let it run. The only place where we create hook_task coroutines is here:

    elif isinstance(command, commands.StartHook):
    asyncio_utils.create_task(
    self.hook_task(command),
    name=f"handle_hook({command.name})",
    client=self.client.peername,
    )

    asyncio_utils.create_task is a thin wrapper around asyncio.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:

    1. You just happened to hit a particular race condition. We're not shutting down cleanly, so occasional "not awaited" warnings are to be expected.
    2. Our event loop is blocking somewhere, which is not good.

    It would be interesting to see if this warning was a fluke or if you get some warnings repeatedly.

    1. Your SIGUSR1 output is mitmdump, not mitmproxy - correct?
    2. Do you have any custom addons or non-default settings?
    3. There are no tracebacks in your event log?
    4. You mentioned that it "hangs for SOME remote servers". Assuming it hangs for facebook.com, does curl -x localhost:8080 -k facebook.com from a separate terminal still work?
    5. What's your output for SIGUSR2? If we have a blocking event loop, this might indicate the root cause.
  9. r00t- commented on Feb 16, 2021

    @r00t-
    ContributorAuthor
    1. yes, i basically never run mitmproxy, only mitmdump
    2. ~/.mitmproxy/ contains only the ca-cert/key, my invocation has only -p, -w and a short --ignore-hosts list, and the debug changes in proxy.py mentioned above.
    3. see next post
    4. will try, but i'm pretty sure it will, from my experience with browsers
    5. will check
  10. r00t- commented on Feb 16, 2021

    @r00t-
    ContributorAuthor
    1. There are no tracebacks in your event log?

    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

    OpenSSL.SSL.Error: [('common libcrypto routines', 'CRYPTO_memdup', 'malloc failure'), ('SSL routines', 'SSL_CTX_set_alpn_protos', 'malloc failure')]
    

    and also the was never awaited message, which looked far more suspicious.

    here's statistics for the root causes of exceptions, can you say which might be interesting to you?

    $ grep -A80 "mitmproxy has crashed" [...]/2020-02/*.err | grep -B1 -- '-$' | grep ... | sed 's|.*\.err-||' | grep .. | sort | uniq -c | sort -rn
        689 AttributeError: 'NoneType' object has no attribute 'state_machine'
        481 OpenSSL.SSL.Error: [('common libcrypto routines', 'CRYPTO_memdup', 'malloc failure'), ('SSL routines', 'SSL_CTX_set_alpn_protos', 'malloc failure')]
        188 Error in WebSocket connection to pubsub-edge.twitch.tv:443: WebSocket Error: ABNORMAL_CLOSURE
        170 During handling of the above exception, another exception occurred:
         44 AttributeError: 'NoneType' object has no attribute 'bio_write'
         43 AssertionError
         37 AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got RequestEndOfMessage(stream_id=1).
         16 Error in WebSocket connection to irc-ws.chat.twitch.tv:443: WebSocket Error: ABNORMAL_CLOSURE
          6 KeyError: 7
          6 h2.exceptions.StreamClosedError: 3
          6 h2.exceptions.StreamClosedError: 1
          6 Error in TCP connection to mtalk.google.com:5228: Multiple exceptions: [Errno 110] Connect call failed ('108.177.126.188', 5228), [Errno 101] Network is unreachable
          5 KeyError: 1
          4 KeyError: 17
          4 KeyError: 15
    

    these maybe?

    Traceback (most recent call last):
      File "mitmproxy/proxy/server.py", line 275, in server_event
        for command in layer_commands:
      File "mitmproxy/proxy/layer.py", line 112, in handle_event
        yield from self.__process(command_generator)
    [...]
      File "mitmproxy/proxy/layer.py", line 112, in handle_event
        yield from self.__process(command_generator)
      File "mitmproxy/proxy/layer.py", line 121, in __process
        command = command_generator.send(send)
      File "mitmproxy/proxy/layers/http/_http2.py", line 266, in _handle_event
        yield from super()._handle_event(event)
      File "mitmproxy/proxy/layers/http/_http2.py", line 91, in _handle_event
        if stream.state_machine.state is not h2.stream.StreamState.CLOSED:
    AttributeError: 'NoneType' object has no attribute 'state_machine'
    

    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.)

      File "mitmproxy/proxy/tunnel.py", line 71, in _handle_event
        yield from self.receive_data(event.data)
      File "mitmproxy/proxy/layers/tls.py", line 217, in receive_data
        plaintext.extend(self.tls.recv(65535))
      File "venv/lib/python3.9/site-packages/OpenSSL/SSL.py", line 1702, in recv
        self._raise_ssl_error(self._ssl, result)
      File "venv/lib/python3.9/site-packages/OpenSSL/SSL.py", line 1566, in _raise_ssl_error
        _raise_current_error()
      File "venv/lib/python3.9/site-packages/OpenSSL/_util.py", line 57, in exception_from_error_queue
        raise exception_type(errors)
    OpenSSL.SSL.Error: [('common libcrypto routines', 'CRYPTO_memdup', 'malloc failure'), ('SSL routines', 'SSL_CTX_set_alpn_protos', 'malloc failure')]
    
  11. mhils commented on Feb 16, 2021

    @mhils
    Member

    Excellent, thanks. Based on what you are describing, my assumption would be that curl from 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.

  12. r00t- commented on Feb 16, 2021

    @r00t-
    ContributorAuthor

    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 : ;done
    and 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:

    $ netstat -ntp | grep 151.101.114.217
    (Not all processes could be identified, non-owned process info
     will not be shown, you would have to be root to see it all.)
    tcp        0      0 192.168.1.4:59942       151.101.114.217:80      TIME_WAIT   -                   
    tcp        0      0 192.168.1.4:60106       151.101.114.217:80      TIME_WAIT   -                   
    tcp        0      0 192.168.1.4:59764       151.101.114.217:80      TIME_WAIT   -                   
    tcp        0      0 192.168.1.4:60026       151.101.114.217:80      TIME_WAIT   -                   
    tcp        0      0 192.168.1.4:59856       151.101.114.217:80      TIME_WAIT   -                   
    tcp        0      0 192.168.1.4:60214       151.101.114.217:80      ESTABLISHED 8348/python3        
    tcp        0      0 192.168.1.4:59686       151.101.114.217:80      TIME_WAIT   -                   
    

    i never see more than one in ESTABLISHED state (typically zero). while multiple clients are waiting on requests to that host.

  13. mhils commented on Feb 16, 2021

    @mhils
    Member

    @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?

  14. mhils commented on Feb 16, 2021

    @mhils
    Member

    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.

  15. r00t- commented on Feb 17, 2021

    @r00t-
    ContributorAuthor

    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_machine crashes are gone,
    only those from openssl remain:

    $ grep -A80 "mitmproxy has crashed" 2021-02-16[e-z].err 2021-02-17*.err /dev/null | grep -B1 -- '-$' | grep ... | sed 's|.*\.err-||' | grep .. | sort | uniq -c | sort -rn
        198 OpenSSL.SSL.Error: [('common libcrypto routines', 'CRYPTO_memdup', 'malloc failure'), ('SSL routines', 'SSL_CTX_set_alpn_protos', 'malloc failure')]
          6 Error in WebSocket connection to pubsub-edge.twitch.tv:443: WebSocket Error: ABNORMAL_CLOSURE
          1   File "/usr/lib/python3.9/asyncio/selector_events.py", line 700, in close
          1 Error in WebSocket connection to alive.github.com:443: WebSocket Error: SERVICE_RESTART (reason: Alive Reconnect)
    

    and it DOES seem that #4452 was the biggest source of slowness,
    i haven't seen multi-minute delays again since the #4452 fix.

  16. 40 remaining items

  17. mhils commented on Feb 21, 2021

    @mhils
    Member

    HTTP/2 is a tricky, tricky protocol. 😉 Facebook upload now works flawlessly for me with #4464 applied. Can you confirm?

  18. r00t- commented on Feb 21, 2021

    @r00t-
    ContributorAuthor

    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.

  19. mhils commented on Feb 21, 2021

    @mhils
    Member

    On Windows, the page you linked only issues ~50 requests. Everything else is served as Emojis. 😄

  20. r00t- commented on Feb 21, 2021

    @r00t-
    ContributorAuthor

    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.

  21. mhils commented on Feb 21, 2021

    @mhils
    Member

    @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:

    $ cargo bench proxy
    proxy-plain/100/1      thrpt:  [178.03  elem/s 189.02  elem/s 200.74  elem/s]
    proxy-plain/100/20     thrpt:  [276.04  elem/s 279.37  elem/s 282.86  elem/s]
    proxy-plain/100/99     thrpt:  [277.93  elem/s 281.24  elem/s 284.47  elem/s]
    proxy-https-h1/100/1   thrpt:  [45.288  elem/s 47.316  elem/s 48.967  elem/s]
    proxy-https-h1/100/20  thrpt:  [52.881  elem/s 55.530  elem/s 58.185  elem/s]
    proxy-https-h1/100/99  thrpt:  [50.890  elem/s 53.044  elem/s 55.296  elem/s]
    proxy-https-h2/100/1   thrpt:  [58.165  elem/s 62.608  elem/s 65.179  elem/s]
    proxy-https-h2/100/20  thrpt:  [59.841  elem/s 63.869  elem/s 67.246  elem/s]
    proxy-https-h2/100/99  thrpt:  [51.212  elem/s 52.779  elem/s 54.532  elem/s]
    

    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.

  22. r00t- commented on Feb 21, 2021

    @r00t-
    ContributorAuthor

    thanks for your insights on this one.

    large-scale "mass interception"

    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.)

  23. mhils commented on Feb 21, 2021

    @mhils
    Member

    can you maybe come up with some quick code to log the number of queued/outstanding requests from the mitmproxy mainloop?

    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 the requestheaders hook yet.

  24. r00t- commented on Feb 23, 2021

    @r00t-
    ContributorAuthor

    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!

  25. r00t- commented on Mar 11, 2021

    @r00t-
    ContributorAuthor
  26. magodo commented on Jul 25, 2022

    @magodo

    Kind of, it's really quite straightforward. Here's what was happening:

    ...
    8. After 10 minutes, mitmproxy's timeout watchdog kicks in: the client hasn't sent anything anymore, we're closing everything down.
    ...

    @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?

  27. mhils commented on Jul 25, 2022

    @mhils
    Member

    @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.

  28. magodo commented on Jul 25, 2022

    @magodo

    @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.

  29. mhils commented on Jul 25, 2022

    @mhils
    Member

    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 -vvv would go a long way in identifying the root cause. Feel free to shoot that by email if you have sensitive stuff in there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions