Skip to content

Fix running hook issue and signal proxyserver updates. - #5512

Merged
mhils merged 13 commits into
mitmproxy:mainfrom
meitinger:finish-running
Aug 13, 2022
Merged

mhils merged 13 commits into
mitmproxy:mainfrom
meitinger:finish-running

Conversation

@meitinger

@meitinger meitinger commented Aug 3, 2022 •

Copy link
Copy Markdown
Contributor

Description

Fix #5376 by introducing StartupHook, which allows addons to execute tasks after everything is loaded, but before the running state is reached.
For proxyserver.py this means: If any server instance fails to start, mitmproxy shows the appropriate error and exits, so there is no "half-loaded" state.

@mhils: Ideally we should also handle the case if a mode change after startup fails.
What would you think about removing the mode from ctx.options.mode if the shutdown succeeds but starting the new mode fails? That way the UI would be in sync with the current modes. Or maybe even starting the new instance first and do the shutdown later, that way having a better fallback? (I.e. keeping the old instance alive and reverting the mode to the old one.)

Checklist

  • I have updated tests where applicable.
  • I have added an entry to the CHANGELOG.

@Prinzhorn

Copy link
Copy Markdown
Member

Thanks for all the great PRs!

ideally we should also handle the case if a mode change after startup fails.

That's a tricky problem and one that I brought up here #5288 (comment) . I am essentially using mitmdump in an Electron app. If you change the proxy configuration in the UI (add, remove change port, etc.) I will tell mitmdump to ctx.options.update to the new list of modes. First of all I would never want mitmdump to ever go down if one of the listeners fails (except of course for the very initial launch). I plan on using --no-server and then use ctx.options.update to configure the listeners. This way my mitmdump process should always be up and I can also use it to make requests without having a listener (I'm using http.Request and "replay.client" to make manual requests through mitmdump)

What would you think about removing the mode from ctx.options.mode if the shutdown succeeds but starting the new mode fails? That way the UI would be in sync with the current modes.

Depends on the definition of "in sync", the UI would basically hide a listener. What I would love to see is each mode having a state. So that the mitmproxy UI (and my UI) can show you something like this:

regular@8080: up
regular@8081: starting...
regular@8082: stopping...
regular@8083: failed (some error message)

A new hook that tells us if any of the listeners' state changed would allow mitmproxy and me to react to it and update the UI. In my UI the user could then for example change the port of one of the listeners and tell mitmproxy about the new modes.

One thing that would be important as well is "retry". So if one listener failed because the port wasn't available and I made it available, then I would expect to be able to tell mitmdump to try again. This could be as simple as ctx.options.update(modes=ctx.options.modes)

@meitinger

Copy link
Copy Markdown
Contributor Author

Depends on the definition of "in sync", the UI would basically hide a listener. What I would love to see is each mode having a state. So that the mitmproxy UI (and my UI) can show you something like this:

regular@8080: up
regular@8081: starting...
regular@8082: stopping...
regular@8083: failed (some error message)

That's a great idea. Proxyserver already has servers mapping modes to ServerInstances, so the latter would just need status and last exception properties. We could of course also opt for just implementing __repr__, but I'd prefer semantic properties. (not every UI might want to display the same text, etc.)

A new hook that tells us if any of the listeners' state changed would allow mitmproxy and me to react to it and update the UI. In my UI the user could then for example change the port of one of the listeners and tell mitmproxy about the new modes.

One thing that would be important as well is "retry". So if one listener failed because the port wasn't available and I made it available, then I would expect to be able to tell mitmdump to try again. This could be as simple as ctx.options.update(modes=ctx.options.modes)

That makes a lot more sense than my suggestion (which was rooted in OptManager concept of rollback).
So setup_servers would do a trigger_event with a new hook for every change, keep servers with failed shutdown in servers, and retry to start instances that failed earlier.

If that sounds fine to everyone, I'm going to implement these changes. Any suggestions for the name of the hook? ServerStatusChanged, InstanceStatusChanged, or without the Changed? Or ...Updated?
If we don't need "starting" and "stopping" as status, we could also just trigger ServersUpdated once after setup_servers ran.

@mhils

mhils commented Aug 4, 2022

Copy link
Copy Markdown
Member

Startup Hook

I'm not sure if there's much of a use case outside of the proxyserver addon? Or differently, is there a plausible scenario why an addon other than Proxyserver would want to implement startup and not running? To me it feels like we could just call await self.addons.get("proxyserver").setup_servers() and not add new API surface.

Listener State

This discussion is kind of adjacent to this PR, but overall that sounds good to me. It probably make sense to eventually have a self-updating /state API for mitmweb which then also includes options.

So setup_servers would do a trigger_event with a new hook for every change...

I would try to keep things as simple as possible here for now until we find out we have super special needs when building out the UI. In the simplest case, we could just notify everyone once setup_servers() is done and be done with it? We could also just add a blinker.Signal to distribute empty "something has changed" messages and then make the mitmweb API go get the state from the proxyserver addon. The benefit of this would be that the web addon and the console ui don't need to keep a copy of the listener states around.

...keep servers with failed shutdown in servers, and retry to start instances that failed earlier.

if shutdown fails I propose we just rm -rf the instance, nuke it from earth and claim it never happened. 😄 Failed starts we need to keep around so that it can be polled.

One thing that would be important as well is "retry".

Setting options to their current value does not trigger a configure event AFAIK, but you should be able to easily do a manual retry by removing and then re-adding it.

@Prinzhorn

Prinzhorn commented Aug 4, 2022 •

Copy link
Copy Markdown
Member

Listener State

Did you see my comment on the original PR? #5393 (comment) I know this is yet another discussion, but I just wanted to bring that up one last time. The discussion in this PR alone has shown to be that "mode" is not the correct terminology. They are listeners. Things like "starting the new mode" sounds odd to me. Listeners have a mode or are of a mode type.

I would try to keep things as simple as possible here for now until we find out we have super special needs when building out the UI. In the simplest case, we could just notify everyone once setup_servers() is done and be done with it? We could also just add a blinker.Signal to distribute empty "something has changed" messages and then make the mitmweb API go get the state from the proxyserver addon.

That sounds a little backwards to me. Couldn't this empty "something has changed" just collect the state and send that instead of being empty? This sounds like you want to force mitmweb/mitmproxy to do a pull instead of doing a push.

The benefit of this would be that the web addon and the console ui don't need to keep a copy of the listener states around.

I don't understand that part. No matter if we pull the state or the core pushes it, you still need a copy for rendering? As I said, to me this is just the difference between push and pull, the implementation of the other end will use the data in the exact same way. So for mitmweb the React component holds a copy anyway, it doesn't matter if it arrived there using a push (we already have a WebSocket) or a pull via fetch (which would be signaled...via WebSocket?)

I don't know if that makes sense? I'd like to see a listeners_updated hook or similar that I can use. It would be called initially and for every change but with the full state of all of them (no diffing or something like that).

@Prinzhorn

Copy link
Copy Markdown
Member

If we don't need "starting" and "stopping" as status, we could also just trigger ServersUpdated once after setup_servers ran.

From a UX point I'd love to have these states. That's the difference between clicking a button and after 700 confusing milliseconds the state changes from "stopped" to "started" and clicking a button and instantly getting feedback via "starting...". Yes, this could probably be simulated on each UI end, but we already have that information.

@mhils

mhils commented Aug 4, 2022

Copy link
Copy Markdown
Member

Did you see my comment on the original PR? #5393 (comment) I know this is yet another discussion, but I just wanted to bring that up one last time. The discussion in this PR alone has shown to be that "mode" is not the correct terminology. They are listeners. Things like "starting the new mode" sounds odd to me. Listeners have a mode or are of a mode type.

On a greenfield I'd definitely opt for something else than mode, given that we have existing CLI/config switches I think mode is bearable. Obviously we can use slightly different terminology in the rest of the user interface.

That sounds a little backwards to me. Couldn't this empty "something has changed" just collect the state and send that instead of being empty? This sounds like you want to force mitmweb/mitmproxy to do a pull instead of doing a push.
[...]

Let's take mitmweb: If a new browser window connects we need to deliver the current state to that browser instance (technically, the browser requests it). For that you either need to ask the proxyserver addon for the current state, or you need to remember the last state that was published ("keep a copy of the listener states"). So we need/want pull anyways. Does that make sense now?

From a UX point I'd love to have these states.

Maybe a second generic "state updated" event within setup_servers should do just fine. :)

@Prinzhorn

Prinzhorn commented Aug 4, 2022 •

Copy link
Copy Markdown
Member

So we need/want pull anyways. Does that make sense now?

I still can't really follow 😄 . What keeps mitmweb from opening a WebSocket which would give you the current state and in the future all changes? How is the first "message" event different from a response using fetch? So "ask the proxyserver addon for the current state" can be done both through a request or a WebSocket. I think my mental model for this comes from Svelte stores (unsurprisingly). If you subscribe to a store you instantly get the current value and then all updates in the future. That's the pattern I'm proposing. The "ListenerState.tsx" component initially has { listeners: [] } and renders an empty list. And then it subscribes, gets the current state and renders that. And the same subscription updates the listeners array until you close the browser window.

or you need to remember the last state that was published ("keep a copy of the listener states").

I honestly still don't know what you mean with remember in this case. But maybe I'm misunderstanding the internals of mitmproxy. Is mitmproxy not able to ad-hoc tell me the current state of all listeners? Is this info only available when something changes? But even that wouldn't make sense, given you want to pull that data ad-hoc 🤔

@mhils

mhils commented Aug 4, 2022 •

Copy link
Copy Markdown
Member

What keeps mitmweb from opening a WebSocket which would give you the current state and in the future all changes?

Yes. The React code would/should do that, but then the Python API endpoint handler needs to obtain the state from somewhere (or remember the latest update). 😄 I'm talking about the Proxyserver <-> mitmweb REST API addon interaction, not the REST API <-> web client part. Does that make sense now?

The Proxyserver addon notifies the REST API addon via a blinker.Signal (or a hook or whatever) that the listener state has been updated. The REST API addon then pulls the data from the proxyserver (it needs to be able to do that on demand for new clients anyways, this was my entire point) and broadcasts the change via WebSockets to all web clients.

@Prinzhorn

Copy link
Copy Markdown
Member

Alright, I think I see the problem here. I just looked at the dev tools in mitmweb. I had no idea about it's architecture. It looks like mitmweb fetches the current flows and then also opens a WebSocket (I assume that also opens a slight window for race conditions and you might miss flows).

The pattern that I use exclusively in my app is that in the open event on the server I instantly send down all current flows that match a given filter. And the same socket is then used to send down changes or added/removed flows. That's the viewpoint from what I was looking at this problem. But you are looking at it from the current mitmweb architecture.

@Prinzhorn

Copy link
Copy Markdown
Member

but then the Python API endpoint handler needs to obtain the state from somewhere (or remember the latest update).

That's the missing piece. But I was assuming we had the power from an adddon (via ctx) to obtain the state

@mhils

mhils commented Aug 4, 2022

Copy link
Copy Markdown
Member

(@meitinger: sorry for derailing your PR discussion)

It looks like mitmweb fetches the current flows and then also opens a WebSocket (I assume that also opens a slight window for race conditions and you might miss flows).

Yes. This is done because sending a huge JSON block via WebSockets has (maybe had?) absymal performance on some browsers. There's no race condition because we open the WS connection first, then fetch the JSON, and then process all events that arrived in the meantime. It's tolerant towards re-receiving a flow that's both in events and JSON.

But I was assuming we had the power from an adddon (via ctx) to obtain the state

We absolutely have, that's the "pull" part I was referring to. Not sending the state as part of the event hook data, but instead notifying all interested parties that they should re-pull (and the broadcast via WebSockets/...).

@Prinzhorn

Copy link
Copy Markdown
Member

The REST API addon then pulls the data from the proxyserver (it needs to be able to do that on demand for new clients anyways, this was my entire point) and broadcasts the change via WebSockets to all web clients.

I swear that's the last comment 😄 . I understand now. There's a fundamental difference between my architecture and that of mitmweb. I don't need to pull at all, that's why a hook would've been enough for me. Because when the hook would fire (either initially or for future updates) I can send that to Electron immediately via gRPC. Which holds all the state ("remembers") and would send it to the frontend.

We absolutely have, that's the "pull" part I was referring to. Not sending the state as part of the event hook data, but instead notifying all interested parties that they should re-pull (and the broadcast via WebSockets/...).

👍 🚀

I think I learned something, so it was worth it 😄

@meitinger

Copy link
Copy Markdown
Contributor Author

Startup Hook

I'm not sure if there's much of a use case outside of the proxyserver addon? Or differently, is there a plausible scenario why an addon other than Proxyserver would want to implement startup and not running? To me it feels like we could just call await self.addons.get("proxyserver").setup_servers() and not add new API surface.

Sounds good to me too. I introduced the startup hook to not favor the built-in addons, then again, Proxyserver warrants special treatment. I will make the changes.

As for the rest: The only thing I would be careful with is blinker, because once you're outside async in Python, you are I-need-another-thread-plus-event-loop-please outside of async 😅
If we opt for blinker, let me do something like await asyncio.gather((res[1] for res in servers.changed.send() if inspect.isawaitable(res[1])), ...)1. Otherwise maybe go for ServersUpdatedHook?

And I'll (try) to implement the rest according to the requirements/preferences mentioned before :)

Footnotes

  1. I might have spend a good amount of time trying to solve running hook is triggered too early, before "address already in use" exit #5376 in what I would call the most elegant way, i.e. by making ConfigureHook async. But options/blinker are just used in way to many sync contexts. ↩

@meitinger
meitinger marked this pull request as draft August 6, 2022 13:15
@meitinger

meitinger commented Aug 8, 2022 •

Copy link
Copy Markdown
Contributor Author

The following has now been implemented:

  • fix running hook is triggered too early, before "address already in use" exit #5376
  • ensure other startup errors are catched by ErrorCheck before running as well
  • allow ServiceInstance to report its state, independently of Proxyserver
  • support listening for Proxyserver.server changes
  • retry start/stop of ServiceInstance on every reconfigure or setup_servers
  • prevent one instance taking a long time to start or stop from affecting other instances

@mhils The changes lean more towards what @Prinzhorn suggested in the UI example. But actually having separate notifications per instance allows us to better split tasks between ServerInstances and Proxyserver and make sure "bad" instances won't block Proxyserver.

@Prinzhorn

Copy link
Copy Markdown
Member

I'm currently wondering what "stopping" of a listener is supposed to mean. We should define and document that. Right now on main the listener will stop accepting connections but any connections still open will stay open as long as they want. So previously when I wanted to switch from port 8080 to 8081 I would kill mitmdump and start a new process. Now if I ctx.options.update(mode=["regular@8081"]) it looks like it does the same but it doesn't. I'm not saying connections should be killed but we need to talk about that (I hope this is the right time and place? 😄 ).

switch-mode.py

from mitmproxy import ctx


def request(flow):
    if flow.request.path == "/switch":
        ctx.options.update(mode=["regular@8081"])
  1. ncat -vkl 1337 (our server)
  2. mitmdump --scripts switch-mode.py
  3. ncat --proxy localhost:8080 localhost 1337 (connect to the server)

I can now send messages back and forth between the two ncat

  1. curl --proxy localhost:8080 http://example.com/switch

The proxy is now listening on 8081. Trying to connect a second ncat client yields Ncat: Proxy connection failed: Connection refused.. However, I can still communicate with the original client, which connected through 8080. I just want to make sure that this is desired behavior. It could be viewed as a bug if a browsing sessions keeps working through the old port because Chrome keeps using the same connection through the now-closed listener. So the UI wouldn't list regular@8080 any longer but it still "exists" (the port is free though).

@meitinger

Copy link
Copy Markdown
Contributor Author

This behavior is (currently) more or less by design, as removing a mode = stopping a server instance = closing the socket + wait on transport, but not cancelling all handle_*_connection tasks. (The test_start_stop method in test_proxyserver.py shows how this can be done more gracefully.)
If the latter is desired, I can make the necessary changes in this PR.

@mhils

mhils commented Aug 8, 2022

Copy link
Copy Markdown
Member

If the latter is desired, I can make the necessary changes in this PR.

I don't think anyone has super strong opinions yet, so let's just keep things as-is unless convincing arguments show up. Of course you can make up some edge case arguments either way, but IMO the current behavior is relatively reasonable. :)

@mhils mhils left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm perfectly happy with the fix for #5376, but I think I don't understand (yet) why we need most of the other complexity here.

  • prevent one instance taking a long time to start or stop from affecting other instances

Do we have any evidence of this being a problem? My understanding is that binding and closing sockets is quick pretty much all the time. Most of the comment below is based on this assumption, so feel free to reject it right off the bat.

The new implementation here is really a bit harder to follow and I haven't fully wrapped my mind around it. Proxyserver.configure() calls Servers.setup(), which spawns instance.start(), which repeatedly calls instance.report(), which calls Proxyserver.update_instance(), which calls Servers.notify(), which then notifies all listeners? This looping around makes things hard to understand for me.

Just from reading the code I think changing the mode from reverse:example.com to reverse:example.org wouldn't work consistently because the new listener is already spawned while the old one is shut down? I might have missed something and this works just fine, but it's definitely a bit hard to reason about for me.

Some ideas on how we could simplify things:

  1. For shutting down, we just attempt to close the socket and then forget about the instance completely. Or do we have convincing examples where shutdown fails or takes a long time? Or examples where this is not good enough? Put differently, I don't see why retrying to shutdown would ever help. If shutdown fails, I'd be perfectly fine with emitting a log message and putting our hands up in the air.
  2. For starting, we try once and then give up. If someone wants retry logic in their UI, they shall send two consecutive option updates (the first one removing the mode the second one adding the mode).
  3. Instead of adding notify/report logic to the instances, we could also just do batched notifications from the proxyserver addon itself (see above: do we have cases where startup is surprisingly slow? Even if that would be the case, we could just add a timeout and treat them as failed). The individual instances would then only set .state attributes that are accessed by interested parties. This avoids the Proxyserver -> Servers -> Instance -> Proxyserver -> Servers loop described above.

Some smaller nits below, but that's only details. Sorry for the hard feedback, but it feels like we could simplify tremendously here (or I'm wrong and I get to learn why, also good)! :-)

asyncio.create_task(self._shutdown_if_errored())

async def _shutdown_if_errored(self):
await asyncio.sleep(0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: I have growing sympathies for replacing our logging event hook setup with the builtin logging module. We wouldn't need such asyncio.sleep(0) shenanigans anymore and we wouldn't need to add plumbing for log events everywhere. That's definitely a project for another day though.

Comment thread mitmproxy/addons/proxyserver.py Outdated
async def restart(instance: ServerInstance):
try:
await instance.start()
except:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: except Exception: please, except: defaults to except BaseException: and we generally don't want to catch KeyboardInterrupt or SystemExit. Always using except Exception saves us from thinking about whether it's necessary or not.

Comment thread mitmproxy/master.py Resolved
Comment thread mitmproxy/addons/proxyserver.py Outdated
if ret is not None and inspect.iscoroutine(ret)
]
if coroutines:
await asyncio.gather(*coroutines)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might make sense to add a standalone async blinker implementation somewhere (simple homegrown or third-party) so that we can just await self.changed.send(...)? Implementation should be rather trivial, we can assume everything is safely on the same thread. It's basically a simple collection of weak references that can be called. Supporting both sync and async is easy (see here).

We can probably replace most of our usage of blinker with that if we add a SyncSignal subclass that errors when adding async listeners and provides a non-async send method.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, I'll implement AsyncSignal and SyncSignal classes. Do you prefer in-order like with hooks in addons, i.e.

for aw in aws:
  await aw

or concurrently as in this PR with asyncio.gather? (Since it's a signal, I personally lean towards gather.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either is perfectly fine for me. Feel free to land this in a separate PR that just adds the signals (but does not add any usage), whatever is easier for you. :)

Comment thread release/build.py Resolved
@meitinger

Copy link
Copy Markdown
Contributor Author

Do we have any evidence of this being a problem? My understanding is that binding and closing sockets is quick pretty much all the time. Most of the comment below is based on this assumption, so feel free to reject it right off the bat.

Not really, no. If we do #5512 (comment) within instance.stop(), then yes. Starting might need a couple of msec, sometimes even a second...
(Then again, we don't know what other people's ServerInstances might do, that don't inherit from AsyncioServerInstance.)

The new implementation here is really a bit harder to follow and I haven't fully wrapped my mind around it. Proxyserver.configure() calls Servers.setup(), which spawns instance.start(), which repeatedly calls instance.report(), which calls Proxyserver.update_instance(), which calls Servers.notify(), which then notifies all listeners? This looping around makes things hard to understand for me.

I know, it could be more straight forward, and I had that in the beginning, i.e Proxyserver does all the controlling and notifying, but that had the following drawbacks:

  • No reusability for other ServerManager classes.
  • ServerInstances cannot fail on their own outside of start or stop. (Again, not relevant for our AsyncioServerInstances.)
  • Using Servers allows proxyserver.servers.changed.connect, which is nicer than proxyserver.servers_changed.connect and consistent with options. Plus it moves the relevant logic out of Proxyserver.

Just from reading the code I think changing the mode from reverse:example.com to reverse:example.org wouldn't work consistently because the new listener is already spawned while the old one is shut down? I might have missed something and this works just fine, but it's definitely a bit hard to reason about for me.

No, you're right: If stopping takes a long time (it is scheduled before start), starting will fail. But starting can be retried as the instance is kept. We could actually add a check for instances with EADDRINUSE exceptions and retry them automatically once an instance stops.

  1. For shutting down, we just attempt to close the socket and then forget about the instance completely. Or do we have convincing examples where shutdown fails or takes a long time? Or examples where this is not good enough? Put differently, I don't see why retrying to shutdown would ever help. If shutdown fails, I'd be perfectly fine with emitting a log message and putting our hands up in the air.

IMHO a failed AsyncioServerInstance shutdown should be even more... fatal. In your example, if reverse:example.com really fails to shutdown and doesn't close the socket, reverse:example.org will never be possible until the process is killed.
But again, other ServerInstances might do something completely different in stop.

  1. For starting, we try once and then give up. If someone wants retry logic in their UI, they shall send two consecutive option updates (the first one removing the mode the second one adding the mode).

This is what the current code does. The UI can also call setup_servers again.

  1. Instead of adding notify/report logic to the instances, we could also just do batched notifications from the proxyserver addon itself (see above: do we have cases where startup is surprisingly slow? Even if that would be the case, we could just add a timeout and treat them as failed). The individual instances would then only set .state attributes that are accessed by interested parties. This avoids the Proxyserver -> Servers -> Instance -> Proxyserver -> Servers loop described above.

We definitely can do this for our instances. The question is, whether we should then allow such a generic ServerInstance, or whether AsyncServerInstance should be the base class.

Some smaller nits below, but that's only details. Sorry for the hard feedback, but it feels like we could simplify tremendously here (or I'm wrong and I get to learn why, also good)! :-)

Basically, if we say that we'll never do something else in start and stop than what AsyncioServerInstance does, we can keep the old code, and just do .send() before and after setup_servers. Instead of .state, we just have .is_running. In @Prinzhorn example, I'd then suggest something like drawing a spinner over the entire server UI list during this period and refreshing once setup_servers is done.

If we decide to allow more in start and stop, this won't work. (Or let's say: Won't be very user-friendly.)
As mentioned before, whatever decision we make, it might be wise to reflect that in what functionality/flexibility ServerInstance offers.

@mhils

mhils commented Aug 9, 2022

Copy link
Copy Markdown
Member

Not really, no. If we do #5512 (comment) within instance.stop(), then yes. Starting might need a couple of msec, sometimes even a second... (Then again, we don't know what other people's ServerInstances might do, that don't inherit from AsyncioServerInstance.)

Ok, let's assume for now that it's always fast. If our assumptions change, we can always revisit and add complexity later.

I know, it could be more straight forward, and I had that in the beginning, i.e Proxyserver does all the controlling and notifying, but that had the following drawbacks:

  • No reusability for other ServerManager classes.

I would argue we only want Proxyserver and no other server managers. If our assumptions change, we can always revisit and add complexity later. :-)

  • ServerInstances cannot fail on their own outside of start or stop. (Again, not relevant for our AsyncioServerInstances.)

I think that's perfectly fine as well. Again, when our assumptions change, we can always revisit and add complexity later.

  • Using Servers allows proxyserver.servers.changed.connect, which is nicer than proxyserver.servers_changed.connect and consistent with options. Plus it moves the relevant logic out of Proxyserver.

We can definitely keep Servers if you think it's useful (I'm happy either way), but that shouldn't stop us from the dumb old approach with an added .send() in there.

No, you're right: If stopping takes a long time (it is scheduled before start), starting will fail. But starting can be retried as the instance is kept. We could actually add a check for instances with EADDRINUSE exceptions and retry them automatically once an instance stops.

That's even more complexity I would like to avoid. :-)

IMHO a failed AsyncioServerInstance shutdown should be even more... fatal. In your example, if reverse:example.com really fails to shutdown and doesn't close the socket, reverse:example.org will never be possible until the process is killed. But again, other ServerInstances might do something completely different in stop.

Do we have any concrete examples where shutdown even fails? If not I think it's mostly an academic question1 and we shouldn't add any additional complexity for it. Giving up is fine if we can't even think of a way to reach that state. :)

  1. For starting, we try once and then give up. If someone wants retry logic in their UI, they shall send two consecutive option updates (the first one removing the mode the second one adding the mode).

This is what the current code does. The UI can also call setup_servers again.

Yes. My not-very-well-articulated point here was that we don't even need to retry when setup_servers is called again. The instance is indefinitely dead once it errors and can only be removed.

We definitely can do this for our instances. The question is, whether we should then allow such a generic ServerInstance, or whether AsyncServerInstance should be the base class.

Let's not worry about third-party instances for this and only serve our own needs for now.

Basically, if we say that we'll never do something else in start and stop than what AsyncioServerInstance does, we can keep the old code, and just do .send() before and after setup_servers. Instead of .state, we just have .is_running. In @Prinzhorn example, I'd then suggest something like drawing a spinner over the entire server UI list during this period and refreshing once setup_servers is done.

This seems much simpler to me, so I'd prefer this approach. I think it needs to be a ternary state (starting/running/errored(msg)), but other than that it sounds good to me.

If we decide to allow more in start and stop, this won't work. (Or let's say: Won't be very user-friendly.) As mentioned before, whatever decision we make, it might be wise to reflect that in what functionality/flexibility ServerInstance offers.

I'd generally say that starting/stopping servers is a rare event that happens while the user is configuring mitmproxy (and not while running in production, whatever that would mean), so just having dumb starting/stopping makes our live easier and doesn't have a bad impact on user experience. So far the only way to configure that was to restart the entire proxy, and folks have not complained too loudly about that. :)

Thanks for takings this constructively! 😃

Footnotes

  1. I am allowed to self-discriminate. :-) ↩

@meitinger meitinger changed the title Add startup hook and fix running hook issue. Fix running hook issue and signal proxyserver updates. Aug 12, 2022
@meitinger

Copy link
Copy Markdown
Contributor Author

Do we have any concrete examples where shutdown even fails? If not I think it's mostly an academic question and we shouldn't add any additional complexity for it. Giving up is fine if we can't even think of a way to reach that state. :)

I agree and changed the code of AsyncioServerInstance.stop a bit to reflect this decision.

This seems much simpler to me, so I'd prefer this approach. I think it needs to be a ternary state (starting/running/errored(msg)), but other than that it sounds good to me.

With the simpler notifications, there is actually just one "updating" (starting/stopping) state, which can now be queried (and subscribed) in Proxyserver.servers with .is_updating and .updating.connect()/.updated.connect().
ServerInstances now have is_running and last_exception. (No longer catching BaseExceptions.)

The new AsyncSignal and SyncSignal have also been implemented.

@meitinger
meitinger marked this pull request as ready for review August 12, 2022 19:45

@mhils mhils left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks so much better! 😃 🍰

Very happy with how this turned out, thanks! My only comment is that we should avoid

with pytest.raises(AssertionError):
    await tctx.master.await_log("returned awaitable")

in the future because that takes a second to run (see implementation) - fixed now. I've also taken the liberty to exterminate exceptions.TypeError so that old sins are not picked up (see comment here). 😅

# def send(self, sender: Any, *args: P.args, **kwargs: P.kwargs) -> list[tuple[Callable[Concatenate[Any, P], R], R]]:
# ...
#
# Alternatively, once PEP 692 lands, we could make kwargs type-safe and use event args TypedDicts.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I strongly support adding better typing support, but let's not delay this PR here. While refactoring, have you seen any case where we use blinker for more than just simple notifications?

@mhils
mhils merged commit e116263 into mitmproxy:main Aug 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

running hook is triggered too early, before "address already in use" exit

3 participants