Skip to content

Add IOLoop.is_running() - #2085

Closed
pitrou wants to merge 3 commits into
tornadoweb:masterfrom
pitrou:loop_is_running
Closed

pitrou wants to merge 3 commits into
tornadoweb:masterfrom
pitrou:loop_is_running

Conversation

@pitrou

@pitrou pitrou commented Jun 12, 2017

Copy link
Copy Markdown
Contributor

This provides a public API to replace the private _running flag specific to PollIOLoop.
Also mirrors equivalent APIs provided by asyncio and Twisted.

This provides a public API to replace the private `_running` flag specific to PollIOLoop.
Also mirrors equivalent APIs provided by asyncio and Twisted.
Comment thread tornado/ioloop.py

finally:
# reset the stopped flag so another start/stop pair can be issued
self._running = False

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.

This was not necessary for this PR, but it seems more robust to add this (if loop.start gets crashed by an exception, the "running" flag should be reset to False).

@bdarnell

Copy link
Copy Markdown
Member

I just discussed this with @mrocklin in #2070.

@pitrou

pitrou commented Jun 12, 2017

Copy link
Copy Markdown
Contributor Author

This is different and much simpler than what @mrocklin was asking for, though.

@bdarnell

Copy link
Copy Markdown
Member

Yeah, I'm more comfortable with this than the more complicated proposal of #2070 (especially since the long-term plan is for IOLoop to disappear in favor of asyncio's event loop). But doesn't #2070 (comment) indicate that this method doesn't actually meet your needs?

@mrocklin

mrocklin commented Jun 18, 2017 via email

Copy link
Copy Markdown
Contributor

@bdarnell

Copy link
Copy Markdown
Member

Can you elaborate on this use case? I'm still not seeing where this would be useful. (and I fear that in practice people would use it incorrectly to check for "in an event loop")

@mrocklin

Copy link
Copy Markdown
Contributor

Looking through the codebase we currently use the private _running attribute in a few places:

  • When starting a new client and given an explicit IOLoop we check to see if it is running. If not then we start a new thread and call loop.start in that thread. We only want to do this if some other service isn't already running that IOLoop somewhere.
  • After starting the IOLoop in the separate thread we then want to block until it starts up. Currently we do this by polling and checking the _running attribute. There are probably better ways to do this with threading.Events though.
  • Same with using Clients as context managers. We want to start things if the IOLoop isn't running.
  • When closing down we capture signals. If the IOLoop is running we want to send a quick coroutine on it. Otherwise we want to clean up slightly differently.

@mrocklin

Copy link
Copy Markdown
Contributor

It could be that we should handle all of these cases in different ways though. I'm not sure. Regardless, having access to the _running attribute has been handy in development so far. I'm sure that we can work around its absence if necessary though.

@bdarnell

Copy link
Copy Markdown
Member
  • When starting a new client and given an explicit IOLoop we check to see if it is running. If not then we start a new thread and call loop.start in that thread. We only want to do this if some other service isn't already running that IOLoop somewhere.

This seems like a very peculiar pattern to me. The usual idiom for initializing a Tornado app is to construct an Application object before starting the IOLoop. At least in debug mode, the Application will schedule callbacks on the current IOLoop, with the expectation that the caller will start that IOLoop (on the current thread). You're making the opposite assumption, that a non-running IOLoop is an indication that you should start it in another thread.

I don't have the big picture of how this API is used, but IMHO it would benefit from passing around "executors" instead of IOLoop. Then you could have an executor to schedule callbacks on an IOLoop running on the current thread, or another one to schedule them on an IOLoop that the executor (lazily) starts in a background thread.

  • After starting the IOLoop in the separate thread we then want to block until it starts up. Currently we do this by polling and checking the _running attribute. There are probably better ways to do this with threading.Events though.

I can see why you need to block here to avoid starting two threads, given the above behavior. Would you still need this if you no longer relied on _running to decide whether to spawn a thread and start the IOLoop?

  • When closing down we capture signals. If the IOLoop is running we want to send a quick coroutine on it. Otherwise we want to clean up slightly differently.

What if the signal comes after a thread has been started to run the IOLoop, but before the loop has started? The decision to start the IOLoop is not atomic with the setting of the _running variable, and in most respects an IOLoop that is about to start should be treated the same as one that is already running.

Do you ever stop your IOLoop before the program exits? If not, you could swap your signal handler to one that uses the IOLoop just before starting it.

@pitrou

pitrou commented Oct 19, 2017

Copy link
Copy Markdown
Contributor Author

@bdarnell do you have reservations about this PR? The additions are quite simple IMHO, and the same API already exists on the asyncio loop.

@bdarnell

Copy link
Copy Markdown
Member

Yes, I have reservations about this change. We had this method before, and I can't recall ever seeing a use of it that wasn't buggy (and it seemed to be an especially attractive nuisance to people who hadn't quite grasped the right idioms to use for event loops). Even the uses proposed in this thread look like they're full of race conditions to me.

The fact that asyncio has this method softens my resistance a little bit, since in Tornado 5.0 you'll be able to access the asyncio loop's is_running method no matter what I do here, but I still don't see a compelling reason to add this.

@pitrou

pitrou commented Oct 21, 2017

Copy link
Copy Markdown
Contributor Author

Well, I'm not sure, but about this suggestion:

Do you ever stop your IOLoop before the program exits? If not, you could swap your signal handler to one that uses the IOLoop just before starting it.

What if a signal arrives between registration of the signal handler and starting the IOLoop?

@bdarnell

Copy link
Copy Markdown
Member

What if a signal arrives between registration of the signal handler and starting the IOLoop?

The signal handler that uses the IOLoop would just use IOLoop.add_callback_from_signal to defer all further processing until the next IOLoop iteration. This works just fine whether the IOLoop is started or not; the callback will run as soon as the IOLoop starts if it hasn't yet.

@mrocklin

mrocklin commented Oct 23, 2017 •

Copy link
Copy Markdown
Contributor

The usual idiom for initializing a Tornado app is to construct an Application object before starting the IOLoop.

@bdarnell the use case in Dask is a bit different because we need to support our own concurrency alongside Jupyter's concurrency for user interactions. Given how Jupyter works we actually need two event loops, otherwise our application hangs whenever a user executes a long-running cell. This definitely isn't the common case, and is certainly suboptimal, but I suspect that it's also unlikely to change in the near-to-moderate future given Jupyter's wide-spread use (fixing this within Jupyter and telling everyone to upgrade isn't a viable solution for us).

Having a way to check if the IOLoop has been started has been helpful for us. Here is one such use case:

  1. User starts up jupyter/ipython/whatever

  2. User imports dask and imports dask.distributed.Client

  3. User instantiates a Client, which instantiates an IOLoop running in a separate thread.

    >>> client = Client()
    
  4. The call to Client() blocks until the thread has started and the IOLoop is alive and kicking

  5. User plays

  6. Advanced user comes along and starts multiple clients and correctly wants them to all operate on the same IOLoop:

    client = Client(loop=loop)
    

    In these cases we probably shouldn't start the IOLoop in a separate thread if it is already running. We could pass a separate start_loop= keyword (and maybe this is the right thing to do), but we know that IOLoops started by Dask are always entirely started before moving on.

@bdarnell

Copy link
Copy Markdown
Member

That advanced use case is based on a subtle set of assumptions: Either the caller is responsible for starting the IOLoop, or Dask is.

If the caller is responsible, they might do something like threading.Thread(target=loop.start).start(). But this may not be done by the time Client(loop=loop) runs, so the Dask client might try to start the loop a second time. Either the caller creates the Dask clients from inside the loop once it's running (probably not feasible in a Jupyter environment) or they have to do extra synchronization to ensure that it's (visibly) running before they let Dask touch it.

If Dask is responsible, you take on that synchronization burden yourself, which is feasible as long as the caller is single-threaded. If the caller is multi-threaded, though, you can no longer coordinate among the different caller threads and multiple of them may try to start the IOLoop simultaneously.

In short, I think it's important to be explicit about who will start an IOLoop. My suggestion is that the creator of the loop should always be responsible: if a loop is passed in, the caller is responsible for starting it.

I'm not sure what the lifecycle of your Client objects is, but it might make sense to implicitly share a global IOLoop thread between them. This may reduce the need for the "advanced" use case of passing in a loop. Then the first client to start would be responsible for starting the IOLoop (but note that even with this "running" variable you'd need some sort of external synchronization for this to work).

@mrocklin

Copy link
Copy Markdown
Contributor

In practice users interact from a single thread and aren't comfortable with the threading or IOLoop APIs directly. Most Dask users don't really know anything about Tornado or IOLoops. Hiding details from them is messy, but definitely helps to expand our userbase.

@mrocklin

Copy link
Copy Markdown
Contributor

I don't disagree with your suggestions, and looking through the code here has given me ideas to reduce our dependence on the ._running attribute (although not entirely). My goal here is to give an example use case that goes beyond typical Tornado use, in hopes that it helps to justify adding the is_running() method.

@friedcell

Copy link
Copy Markdown

This seems very useful. Going through my code I use it only to detect when it's IOLoop is not running:

  • in tests to provide better errors when sync fetch is used in async tests
  • in code to prevent reconnects to external services when server is shutting down

Only in one case (some magic code to handle async test setUp) the code using access to ._running actually interacts with the IOLoop in any way. I think the fact that it is potentially dangerous is better communicated in docs for .is_running() then having people use ._running and not knowing the pitfalls of doing that.

@pitrou

pitrou commented Nov 2, 2017

Copy link
Copy Markdown
Contributor Author

I'd like to second what @friedcell said about tests. It's important to check that a test didn't leave a loop running (for example in another thread). For that I haven't found any other solution than inspecting a running flag.

@bdarnell

bdarnell commented Nov 2, 2017

Copy link
Copy Markdown
Member

I understand @friedcell's desire for better error reporting when you have both sync and async tests. (but note that we now have better "ioloop is already running" messaging than we used to, so as long as it's the same IOLoop you can just run it and let the IOLoop report the error. Are you asking about being able to do this for something other than AsyncHTTPTestCase.fetch on the same IOLoop used by gen_test?)

I don't understand the "prevent reconnects when server is shutting down" - nothing happens after the IOLoop exits, so when would you ever observe is_running == False during a shutdown? Don't you want to go into a "draining" mode anyway before the final shutdown, so you'd stop reconnections some time before the IOLoop stops?

I also don't quite get @pitrou's concern about an IOLoop left running. A running IOLoop must be running in a thread, so A) you can ask the thread if it's running regardless of whether IOLoop supports this, and B) you generally don't just want to ask the thread, you want to join() it. And when threads are involved, concerns about races between the change of the running variable and the actual start/stop of the IOLoop are more salient.

@friedcell

Copy link
Copy Markdown

@bdarnell in test code I'll have helpers that have a sync and async version depending on type of test - to nicely error out when wrong type is used I'm currently inspecting ._running.

The reconnect case is checking ._running to only allow it when it's true. I've not looked into that code for a while - I'll check why I have it there, might have been a quick fix :)

@pitrou

pitrou commented Nov 2, 2017

Copy link
Copy Markdown
Contributor Author

I also don't quite get @pitrou's concern about an IOLoop left running. A running IOLoop must be running in a thread, so A) you can ask the thread if it's running regardless of whether IOLoop supports this, and B) you generally don't just want to ask the thread, you want to join() it.

Agreed as long as the test harness started the thread itself (and therefore knows about it). But sometimes we pass a loop and it will be started by some of the code under test. Unless by peeking into threading.enumerate at the teardown phase, I see no way of knowing whether there's a runaway thread still running an IOLoop somewhere.

@mrocklin

mrocklin commented Nov 2, 2017

Copy link
Copy Markdown
Contributor

Stepping back a moment, it seems like having some indication of if an IOLoop is started or not is useful to a variety of people in a variety of atypical situations for debugging, diagnostics, testing, and so on. They may not be using Tornado in an ideal way, but they are using it in a way that they find useful for their application. Turning around the discussion a bit, why not provide some indication of if an IOLoop is running? What harm does this cause? Is this just about stopping users from shooting themselves in the foot?

If so then perhaps there are other ways to warn users about the proper use of this method, such as with loud warnings in documentation or docstrings. These methods might suitably indemnify Tornado maintainers from dealing with problems here while still allowing Tornado users control if they choose to take it. As someone who uses Tornado a fair amount these days I'm asking for bullets and I'm ready to accept the loss of a toe or two.

@bdarnell

bdarnell commented Nov 5, 2017

Copy link
Copy Markdown
Member

Stepping back a moment, it seems like having some indication of if an IOLoop is started or not is useful to a variety of people in a variety of atypical situations for debugging, diagnostics, testing, and so on.

It is attractive in a variety of situations. I'm not convinced it's useful.

What harm does this cause? Is this just about stopping users from shooting themselves in the foot?

Yes, it's about stopping users from shooting themselves in the foot. This method is inherently subject to race conditions. Let's look at how dask is using it:

This function is only safe to call from multiple threads if the IOLoop is known to be running in advance. (Otherwise, it could fail in a variety of ways, including two threads trying to start the loop at once in their own run_sync() calls, or more subtly if one starts the loop, another schedules a callback on it, then the first stops the loop when it's done and the second thread just times out)

Maybe thread safety is not required for this usage. That's fine, but in that case why even bother with the possibility of a shared IOLoop on another thread? sync() can just create a new IOLoop every time and use run_sync() on it.

Starting an IOLoop in another thread so that is_running() can be safely used with it is tricky. Dask does the necessary dance in LoopRunner, but event loops started any other way probably wouldn't. Maybe sync() should take a LoopRunner instead of an IOLoop?

If I were designing this API without regard for backwards compatibility, I'd make the loop argument to sync() optional (falling back to run_sync() on a temporary IOLoop), and if it is supplied it would be the caller's responsibility to make sure it's running. Do you require preserving compatibility with callers passing non-running IOLoops? What about callers passing running IOLoops started some way other than LoopRunner?

@mrocklin

mrocklin commented Nov 5, 2017

Copy link
Copy Markdown
Contributor

So that code in sync is only really used in our testing infrastructure here:

@pytest.fixture
def loop():
    with pristine_loop() as loop:
        yield loop
        # Stop the loop in case it's still running
        try:
            sync(loop, loop.stop)
        except RuntimeError as e:
            if not re.match("IOLoop is clos(ed|ing)", str(e)):
                raise

There we want to cleanly shut down an IOLoop, regardless of if it is running or not. Usually our tests don't stop the IOLoop, but some do. In the context of this pytest fixture we actually don't know which situation we're in and need some mechanism to figure out what to do to stop things cleanly. Can you recommend a better solution here? I think that this is the last usage of _running that we have not yet been able to remove.

(though, to be clear, even if dask is able to remove all uses of the _running property I still think that it would be good to keep around.)

@bdarnell

bdarnell commented Nov 5, 2017

Copy link
Copy Markdown
Member

My first suggestion[1] is to run loop.add_callback(loop.stop) and don't worry about doing anything synchronously. If the loop is running, it'll stop itself and its thread will exit (or if the thread doesn't exit, you have non-IOLoop problems); if it's not, nothing will happen.

If you want to wait for some sort of cleanup before you proceed to the next test, you probably want to join the thread where the IOLoop was running, not just stop the loop itself.

[1] Actually, my first suggestion is to unconditionally start the IOLoop thread when creating it so there's never ambiguity about whether it's running or not. But since you're committed to ambiguous IOLoop states, this is how I'd handle it.

@pitrou

pitrou commented Nov 5, 2017

Copy link
Copy Markdown
Contributor Author

My first suggestion[1] is to run loop.add_callback(loop.stop) and don't worry about doing anything synchronously. If the loop is running, it'll stop itself and its thread will exit (or if the thread doesn't exit, you have non-IOLoop problems); if it's not, nothing will happen.

But we also want to call loop.close afterwards, and that only works if the loop has stopped.
(by looking at the code, if loop.close isn't called explicitly, the IOLoop may leak file descriptors, right? On POSIX at least, it has a pair of fds open for wakeup)

@bdarnell

bdarnell commented Nov 5, 2017

Copy link
Copy Markdown
Member

GC will eventually free up the file descriptors if you don't close the IOLoop, but in tests it's easy to accumulate enough unclosed file descriptors to exhaust your limits, so you're right that it's necessary to close the loop. Unfortunately, sync() doesn't do this correctly. The threading event is set by one of the callbacks in the last IOLoop iteration; there is no guarantee that the loop has actually stopped by the time you close it. IOLoop.close() needs to be called after the return of IOLoop.start() (which usually means running it from the thread that calls start()); there is no other synchronization point available.

@friedcell

Copy link
Copy Markdown

@bdarnell I still think it would be better to add the function and in docs show all the ways you can shoot yourself in the foot with it. Currently a naïve approach to this is to find the _running property, wonder why it's not exposed, find nothing and then access it to shoot yourself in the foot. If an .is_running property is available it can be properly documented to inform people that doing anything with the loop in that case can lead to race conditions so that a developer can be steered into other options exposed in this thread.

I think all of us will survive if it's not added, but there will be more devs that hit this issue and will only find instructions and reasons for it not existing in this issue and not the docs.

@pitrou

pitrou commented Nov 13, 2017

Copy link
Copy Markdown
Contributor Author

GC will eventually free up the file descriptors if you don't close the IOLoop,

Uh, yes, thank you. I had missed that.

Unfortunately, sync() doesn't do this correctly. The threading event is set by one of the callbacks in the last IOLoop iteration; there is no guarantee that the loop has actually stopped by the time you close it.

You're right... But there doesn't seem to be a better way for us to do it -- not with that API anyway. We can't even busy-loop before close() since there's no official way to introspect the running state of the loop.

@bdarnell

Copy link
Copy Markdown
Member

You're right... But there doesn't seem to be a better way for us to do it -- not with that API anyway.

Right - is_running() is the wrong API for this. The right API is threading.Thread.join: when you start a thread for the IOLoop, save the Thread object, and then in your cleanup phase do loop.add_callback(loop.stop); thread.join().

@minrk

minrk commented Jan 3, 2018

Copy link
Copy Markdown
Contributor

This would be handy for me, where I've been doing some cleanup in a new, temporary eventloop (IOLoop().run_sync(cleanup)). This has stopped working in tornado 5 because calling .run_sync() fails when there's already an eventloop:

from tornado.ioloop import IOLoop

async def outer():
    async def inner():
        print('ok')
    IOLoop(make_current=False).run_sync(inner)

IOLoop.current().run_sync(outer)
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    IOLoop.current().run_sync(outer)
  File "/Users/benjaminrk/dev/py/tornado/tornado/ioloop.py", line 571, in run_sync
    return future_cell[0].result()
  File "test.py", line 6, in outer
    IOLoop(make_current=False).run_sync(inner)
  File "/Users/benjaminrk/dev/py/tornado/tornado/ioloop.py", line 566, in run_sync
    self.start()
  File "/Users/benjaminrk/dev/py/tornado/tornado/platform/asyncio.py", line 111, in start
    self.asyncio_loop.run_forever()
  File "/Users/benjaminrk/conda/lib/python3.6/asyncio/base_events.py", line 411, in run_forever
    'Cannot run the event loop while another loop is running')
RuntimeError: Cannot run the event loop while another loop is running

In my case, if I could check if the eventloop is running, I could hand it off, otherwise call it synchronously:

if IOLoop.current().is_running():
    IOLoop.current().add_callback(f)
else:
    IOLoop().run_sync(f)

I'm not super concerned with the cleanest or most robust solution to this, since it is only testing machinery and doesn't come up in real application code. I've chosen to follow what you've mentioned and create a dedicated thread for this, so that there is only one thread in the temporary loop. It works fine that way.

@bdarnell

bdarnell commented Jan 5, 2018

Copy link
Copy Markdown
Member

This has stopped working in tornado 5 because calling .run_sync() fails when there's already an eventloop:

OK, that's a regression (I thought we had tests for this, but I guess not). I remember fixing something to make the synchronous tornado.httpclient.HTTPClient work inside an event loop (this would block the loop, of course, but it was sometimes useful for transitions in a WSGIContainer when you didn't want to have a completely separate HTTP client like requests in addition to AsyncHTTPClient)

Unfortunately, since this is coming from inside asyncio, there's not much we can do about it besides lobbying asyncio to be less prescriptive in this respect (maybe a context manager to temporarily do asyncio._set_running_loop(None)?). Otherwise, I'd agree that making a new IOLoop and running it synchronously is a good solution.

if IOLoop.current().is_running():
    IOLoop.current().add_callback(f)
else:
    IOLoop().run_sync(f)

But those are very different! You can't tell when (or whether) f will run.

@bdarnell

Copy link
Copy Markdown
Member

I'm still not a fan of this method, but if you want it, you can get it on python 3 withasyncio.get_event_loop().is_running(). I don't plan to add a version of this for python 2.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants