use thread-local properties for hub, proxy

This commit is contained in:
Min RK
2015-07-09 11:20:57 -05:00
parent 48fe642c44
commit e866abe1a0
2 changed files with 41 additions and 8 deletions

View File

@@ -347,7 +347,6 @@ class JupyterHub(Application):
debug_db = Bool(False, config=True,
help="log all database transactions. This has A LOT of output"
)
db = Any()
session_factory = Any()
admin_access = Bool(False, config=True,
@@ -541,18 +540,43 @@ class JupyterHub(Application):
# store the loaded trait value
self.cookie_secret = secret
_db_local = None
# thread-local storage of db objects
_local = Instance(threading.local, ())
@property
def db(self):
if not hasattr(self._db_local, 'db'):
print("Making new connection", self)
self._db_local.db = scoped_session(self.session_factory)()
return self._db_local.db
if not hasattr(self._local, 'db'):
self._local.db = scoped_session(self.session_factory)()
return self._local.db
@property
def hub(self):
if not getattr(self._local, 'hub', None):
q = self.db.query(orm.Hub)
assert q.count() <= 1
self._local.hub = q.first()
return self._local.hub
@hub.setter
def hub(self, hub):
self._local.hub = hub
@property
def proxy(self):
if not getattr(self._local, 'proxy', None):
q = self.db.query(orm.Proxy)
assert q.count() <= 1
p = self._local.proxy = q.first()
if p:
p.auth_token = self.proxy_auth_token
return self._local.proxy
@proxy.setter
def proxy(self, proxy):
self._local.proxy = proxy
def init_db(self):
"""Create the database connection"""
self.log.debug("Connecting to db: %s", self.db_url)
self._db_local = threading.local()
try:
self.session_factory = orm.new_session_factory(
self.db_url,

View File

@@ -2,6 +2,7 @@
import json
import os
from queue import Queue
from subprocess import Popen
from .. import orm
@@ -100,7 +101,15 @@ def test_external_proxy(request, io_loop):
}))
r.raise_for_status()
assert app.proxy.api_server.port == proxy_port
assert app.proxy.auth_token == new_auth_token
# get updated auth token from main thread
def get_app_proxy_token():
q = Queue()
app.io_loop.add_callback(lambda : q.put(app.proxy.auth_token))
return q.get(timeout=2)
assert get_app_proxy_token() == new_auth_token
app.proxy.auth_token = new_auth_token
# check that the routes are correct
routes = io_loop.run_sync(app.proxy.get_routes)