Skip to content

Instantly share code, notes, and snippets.

@alejandrobernardis
Created November 7, 2014 15:28
Show Gist options
  • Save alejandrobernardis/7ee164b5142bb3e1bf3f to your computer and use it in GitHub Desktop.
Save alejandrobernardis/7ee164b5142bb3e1bf3f to your computer and use it in GitHub Desktop.
Tornado, start server
# https://groups.google.com/forum/#!starred/python-tornado/VpHp3kXHP7s
def start_httpserver(app_root, handler_map, opts):
# create app and http server
app = Application(handler_map, app_root, opts)
http_server = tornado.httpserver.HTTPServer(app, xheaders=True)
ioloop = tornado.ioloop.IOLoop.instance()
def mem_check_scheduler():
easylog.debug("Call Check MEM")
rss_mem = systool.mem('rss') / 1024
if rss_mem > app.sandbox_conf['restart_mem']:
easylog.error("RSS: %d MB Need to restart", rss_mem)
os.kill(os.getpid(), signal.SIGUSR1)
mem_check_scheduler = tornado.ioloop.PeriodicCallback(mem_check_scheduler,
1000 * app.sandbox_conf['mem_check_sec'])
mem_check_scheduler.start()
def restart_self():
easylog.error("Stopping the server")
http_server.stop() # dont accept the new request
mem_check_scheduler.stop()
deadline = time.time() + 10
def stop_loop():
now = time.time()
easylog.error("wait for ioloop finsh. %d", now)
if now < deadline and ioloop._callbacks:
ioloop.add_timeout(now+1, stop_loop)
else:
ioloop.stop()
easylog.error("IOLOOP stopped")
#restart code comes from autoreload.py in tornado
try:
os.execv(sys.executable, [sys.executable] + sys.argv)
except OSError:
os.spawnv(os.P_NOWAIT, sys.executable, [sys.executable] + sys.argv)
sys.exit(0)
stop_loop()
def shutdown():
easylog.error("Stopping the server")
http_server.stop() # dont accept the new request
mem_check_scheduler.stop()
deadline = time.time() + 10
def stop_loop():
now = time.time()
easylog.error("wait for ioloop finsh. %d", now)
if now < deadline and ioloop._callbacks:
ioloop.add_timeout(now+1, stop_loop)
else:
ioloop.stop()
easylog.error("IOLOOP stopped")
sys.exit(1)
stop_loop()
def exit_handler(sig, frame):
easylog.error("#### Caught signal:%d will exit ####", sig)
ioloop.spawn_callback(shutdown)
signal.signal(signal.SIGTERM, exit_handler)
signal.signal(signal.SIGINT, exit_handler)
signal.signal(signal.SIGABRT, exit_handler)
def restart_handler(sig, frame):
easylog.error("#### Caught signal:%d will restart self ####", sig)
ioloop.spawn_callback(restart_self)
signal.signal(signal.SIGPIPE, restart_handler)
signal.signal(signal.SIGUSR1, restart_handler)
# start http server
if opts.debug == True:
http_server.listen(opts.port, address=opts.address)
else:
http_server.bind(opts.port, address=opts.address)
http_server.start(num_processes=opts.process)
easylog.info('listen @ %s:%d' % (opts.address, opts.port))
ioloop.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment