Created
March 20, 2011 05:08
-
-
Save ssadler/878092 to your computer and use it in GitHub Desktop.
Cycle a tornado server passing server fd (buggy)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys, socket, passfd | |
import tornado.httpserver | |
import tornado.ioloop | |
import tornado.web | |
import time | |
class HelloHandler(tornado.web.RequestHandler): | |
def get(self): | |
self.write('hello from pid: %s' % os.getpid()) | |
class SpawnHandler(tornado.web.RequestHandler): | |
def get(self): | |
from subprocess import Popen | |
addr = '/tmp/tornado_fd' | |
if os.path.exists(addr): | |
os.remove(addr) | |
p = Popen(['python', __file__, addr]) | |
while not os.path.exists(addr): | |
time.sleep(0.01) | |
time.sleep(0.1) | |
ipc = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
ipc.connect(addr) | |
passfd.sendfd(ipc, http_server._socket) | |
assert ipc.recv(2) == 'OK' | |
ipc.close() | |
self.write('spawned') | |
app = tornado.web.Application([ | |
(r"/", HelloHandler), | |
(r"/spawn", SpawnHandler), | |
]) | |
if __name__ == '__main__': | |
try: | |
fd_pass_sock = sys.argv[1] | |
except IndexError: | |
fd = None | |
else: | |
ipc = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
ipc.bind(fd_pass_sock) | |
ipc.listen(4) | |
conn, addr = ipc.accept() | |
fd = int(passfd.recvfd(conn)[0]) | |
conn.send('OK') | |
conn.close() | |
ipc.close() | |
http_server = tornado.httpserver.HTTPServer(app) | |
if fd: | |
http_server._socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) | |
else: | |
http_server.bind(8891) | |
is_main = http_server.start(4) | |
ioloop = tornado.ioloop.IOLoop.instance() | |
ioloop.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment