2

I have a simple Python uwsgi app that follows the basic pattern:

def application(env, start_response):
    ... do something ...
    ... create some threads ...
    ... handover the work to the threads ...
    start_response('200 OK', [('Content-Type','text/html')])
    return result

My sysadmin is complaining that my app is not handling shutdown and he has to wait for uwsgi's timeout to kill the app processes each time he wants to restart the uwsgi service. Which, apparently, can take up to 30 seconds, time in which the service is unavailable.

Is there a specific signal or call that uwsgi sends the app when it wants to close it? How do I handle that?

daphtdazz
  • 7,754
  • 34
  • 54
evilpenguin
  • 5,448
  • 6
  • 41
  • 49

2 Answers2

3
def goodbye():
    print "Goodbye from worker %d" % uwsgi.worker_id()

uwsgi.atexit = goodbye

Or this standard python module

vav
  • 4,584
  • 2
  • 19
  • 39
0

Simply use python's atexit module to do tidy up:

import atexit

atexit.register(uwsgi_tidy_up)

And if your tidy-up only makes sense under uwsgi, check for it first:

try:
    import uwsgi
    atexit.register(uwsgi_tidy_up)
except ImportError:
    pass

However, you should be aware that atexit handlers are not called until all non-daemon threads are finished. This means that if you want to use this method to stop your threads and join them you need to make them daemon=True.

As I understand it the reason this works is that when uwsgi is told to reload it signals the "emperor" worker (which is the parent of all the workers) to do so. However the emperor does not directly signal (in the sense of kill -SIGNAL) the workers, but uses an internal mechanism to tell them to finish gracefully. This is why the atexit handlers get a chance to run, because the workers are terminating normally on request from the "emperor". And that's why it's important that any threads you create from the workers are daemon=True, so as not to block the normal termination procedures (and that might have been partly why termination was timing out).

daphtdazz
  • 7,754
  • 34
  • 54