Skip to content

Instantly share code, notes, and snippets.

@teh
Created August 4, 2011 21:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teh/1126302 to your computer and use it in GitHub Desktop.
Save teh/1126302 to your computer and use it in GitHub Desktop.
Proper shut down in-flight requests for eventlet's wsgi server
import daemon, lockfile, signal, logging
import eventlet
from eventlet import wsgi, timeout
worker_pool = eventlet.GreenPool(20)
sock = eventlet.listen(('', 8000))
def proper_shutdown():
worker_pool.resize(0)
sock.close()
logging.info("Shutting down. Requests left: %s", worker_pool.running())
worker_pool.waitall()
logging.info("Exiting.")
raise SystemExit()
def queue_shutdown(signal_number, stack_frame):
eventlet.spawn_n(proper_shutdown)
def test_app(evn, start_response):
start_response('200 OK', {})
eventlet.sleep(20)
return ['hi']
# Daemon things
context = daemon.DaemonContext(
working_directory='.',
umask=0o002,
pidfile=lockfile.FileLock('shutdown-example.pid'),
)
context.signal_map = {
signal.SIGTERM: queue_shutdown,
}
context.files_preserve = [sock]
with context:
logging.basicConfig(filename='shutdown.log', level=logging.INFO)
logging.info("Starting")
wsgi.server(sock, test_app, custom_pool=worker_pool)
@apatrushev
Copy link

How to fix this code to force end keep alive connections ?

@teh
Copy link
Author

teh commented Feb 23, 2012

Hey apatrushev. eventlet's wsgi enables keep alive by default, so you should not have to do anything.

@apatrushev
Copy link

apatrushev commented Feb 23, 2012 via email

@teh
Copy link
Author

teh commented Feb 23, 2012

Apologies, I misunderstood your question.

If you have keepalive connections open you'll need to be a bit harsher, maybe with the following (untested!) code:

worker_pool.resize(0)
sock.close()
eventlet.sleep(2) # Give running requests 2 seconds to shut down
for coro in worker_pool.coroutines_running:
     coro.kill()

@aryzhov
Copy link

aryzhov commented Aug 15, 2016

No need to close the socket as wsgi.server() closes it upon exit.

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