Skip to content
Snippets Groups Projects
Commit 6fb88e57 authored by Thomas Kluyver's avatar Thomas Kluyver
Browse files

Run subprocess to use proxy

parent c2ff41cb
No related branches found
No related tags found
No related merge requests found
...@@ -13,11 +13,11 @@ try: ...@@ -13,11 +13,11 @@ try:
except ImportError: except ImportError:
restful_config = {} restful_config = {}
def main(): async def amain():
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument('--debug', action='store_true') ap.add_argument('--debug', action='store_true')
ap.add_argument('--db', default='calparrot.sqlite') ap.add_argument('--db', default='calparrot.sqlite')
ap.add_argument('--port-file', help="File to write port number into") ap.add_argument('command', nargs='+')
args = ap.parse_args() args = ap.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
# Suppress tornado's access logging when things are working correctly: # Suppress tornado's access logging when things are working correctly:
...@@ -40,15 +40,17 @@ def main(): ...@@ -40,15 +40,17 @@ def main():
app = ProxyApp(base_url, oauth_info, args.db) app = ProxyApp(base_url, oauth_info, args.db)
log.info("CalParrot will serve constant queries on http://127.0.0.1:%d", app.port) log.info("CalParrot will serve constant queries on http://127.0.0.1:%d", app.port)
if args.port_file:
with open(args.port_file, 'w') as f:
f.write(str(app.port))
if os.fork() == 0: try:
asyncio.run(app.serve()) env = os.environ.copy()
else: # Tell the child process (running the notebook) to talk to our proxy:
# Parent process - exit now env['CAL_CAL_TOOLS_CALCAT'] = "{base-api-url='http://127.0.0.1:{app.port}/api', use-oauth2=false}"
return 0 proc = await asyncio.create_subprocess_exec(*args.command, env=env)
retcode = await proc.wait()
finally:
await app.shutdown()
return retcode
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(asyncio.run(amain()))
...@@ -181,17 +181,7 @@ class ProxyHandler(RequestHandler): ...@@ -181,17 +181,7 @@ class ProxyHandler(RequestHandler):
await self.finish(response.body) await self.finish(response.body)
class ShutdownHandler(RequestHandler):
def initialize(self, proxy_app):
self.proxy_app = proxy_app
def post(self):
self.proxy_app.shutdown()
class ProxyApp: class ProxyApp:
quit_event: asyncio.Event
def __init__(self, base_url, oauth_info=None, db_path='calparrot.sqlite'): def __init__(self, base_url, oauth_info=None, db_path='calparrot.sqlite'):
self.response_store = ResponsesDB(db_path) self.response_store = ResponsesDB(db_path)
base_url = base_url.rstrip('/') # e.g. https://in.xfel.eu/calibration base_url = base_url.rstrip('/') # e.g. https://in.xfel.eu/calibration
...@@ -208,7 +198,6 @@ class ProxyApp: ...@@ -208,7 +198,6 @@ class ProxyApp:
self.client = AsyncHTTPClient() self.client = AsyncHTTPClient()
self.tornado_app = Application([ self.tornado_app = Application([
('/.calparrot/stop', ShutdownHandler, {'proxy_app': self}),
('(/.*)', ProxyHandler, { ('(/.*)', ProxyHandler, {
'base_url': base_url, 'base_url': base_url,
'upstream_client': self.client, 'upstream_client': self.client,
...@@ -218,25 +207,18 @@ class ProxyApp: ...@@ -218,25 +207,18 @@ class ProxyApp:
# Bind a random port to listen on # Bind a random port to listen on
self.sockets = bind_sockets(0, '127.0.0.1') self.sockets = bind_sockets(0, '127.0.0.1')
self.server = HTTPServer(self.tornado_app)
# add_sockets hooks up the server to the event loop
self.server.add_sockets(self.sockets)
@property @property
def port(self): def port(self):
return self.sockets[0].getsockname()[1] return self.sockets[0].getsockname()[1]
async def serve(self): async def shutdown(self):
"""Serve requests until asked to quit""" """Cleanly shut down the server"""
self.quit_event = asyncio.Event()
server = HTTPServer(self.tornado_app)
# add_sockets hooks up the server to the event loop
server.add_sockets(self.sockets)
await self.quit_event.wait()
log.info("CalParrot shutting down") log.info("CalParrot shutting down")
server.stop() # Stop accepting new connections self.server.stop() # Stop accepting new connections
await server.close_all_connections() # Close existing connections await self.server.close_all_connections() # Close existing connections
self.response_store.close() self.response_store.close()
log.info("Query stats: %s", self.response_store.stats) log.info("Query stats: %s", self.response_store.stats)
def shutdown(self):
self.quit_event.set()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment