Skip to content
Snippets Groups Projects
Commit 3549841c authored by Tim Kreuzer's avatar Tim Kreuzer
Browse files

outsource 'get_flavors' to an async + sync function, allow usage outside of...

outsource 'get_flavors' to an async + sync function, allow usage outside of outpostspawner more easily
parent 30e445a4
No related branches found
No related tags found
No related merge requests found
from . import api_flavors_update
from . import misc
from ._version import __version__
from .outpostspawner import OutpostSpawner
......@@ -10,43 +10,17 @@ from jupyterhub.utils import token_authenticated
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
_outpost_flavors_cache = {}
class OutpostFlavorsAPIHandler(APIHandler):
required_scopes = ["custom:outpostflavors:set"]
def check_xsrf_cookie(self):
pass
from .misc import Thread
@token_authenticated
async def post(self, outpost_name):
check_custom_scopes(self)
global _outpost_flavors_cache
body = self.request.body.decode("utf8")
try:
flavors = json.loads(body) if body else {}
except:
self.set_status(400)
self.log.exception(
f"{outpost_name} - Could not load body into json. Body: {body}"
)
return
_outpost_flavors_cache = {}
_outpost_flavors_cache[outpost_name] = flavors
self.set_status(200)
async def get(self):
async def async_get_flavors(log, user=None):
global _outpost_flavors_cache
try:
initial_system_names = os.environ.get(
"OUTPOST_FLAVOR_INITIAL_SYSTEM_NAMES", ""
)
initial_system_urls = os.environ.get(
"OUTPOST_FLAVOR_INITIAL_SYSTEM_URLS", ""
)
initial_system_names = os.environ.get("OUTPOST_FLAVOR_INITIAL_SYSTEM_NAMES", "")
initial_system_urls = os.environ.get("OUTPOST_FLAVOR_INITIAL_SYSTEM_URLS", "")
initial_system_tokens = os.environ.get(
"OUTPOST_FLAVOR_INITIAL_SYSTEM_TOKENS", ""
)
......@@ -66,14 +40,12 @@ class OutpostFlavorsAPIHandler(APIHandler):
if system_name not in _outpost_flavors_cache.keys():
initial_system_names_list.append(system_name)
initial_system_urls_list.append(initial_system_urls_list_all[i])
initial_system_tokens_list.append(
initial_system_tokens_list_all[i]
)
initial_system_tokens_list.append(initial_system_tokens_list_all[i])
i += 1
# If systems are left without successful initial check, try to reach the Outpost
if initial_system_names_list:
self.log.info(
log.info(
f"OutpostFlavors - Connect to {initial_system_names_list} / {initial_system_urls_list}"
)
......@@ -95,27 +67,24 @@ class OutpostFlavorsAPIHandler(APIHandler):
for name_result in names_results:
if name_result[1].code == 200:
try:
self.log.info(
f"OutpostFlavors - {name_result[0]} successful"
)
log.info(f"OutpostFlavors - {name_result[0]} successful")
result_json = json.loads(name_result[1].body)
_outpost_flavors_cache[name_result[0]] = result_json
except:
self.log.exception(
log.exception(
f"OutpostFlavors - {name_result[0]} Could not load result into json"
)
else:
self.log.warning(
log.warning(
f"OutpostFlavors - {name_result[0]} - Answered with {name_result[1].code}"
)
except:
self.log.exception("OutpostFlavors failed, return empty dict")
log.exception("OutpostFlavors failed, return empty dict")
# If it's an user authenticated request, we override the available flavors, if
# there's a dict with available flavors in auth_state.
# One can add this in Authenticator.post_auth_hook, to allow user-specific
# flavors for each Outpost.
user = self.current_user
if user:
auth_state = await user.get_auth_state()
if auth_state:
......@@ -139,11 +108,53 @@ class OutpostFlavorsAPIHandler(APIHandler):
.get(key, {})
.get("current", specific_current)
)
self.write(json.dumps(user_specific_ret))
self.set_status(200)
return user_specific_ret
return _outpost_flavors_cache
def sync_get_flavors(log, user):
loop = asyncio.new_event_loop()
def t_get_flavors(loop, log, user):
asyncio.set_event_loop(loop)
ret = loop.run_until_complete(async_get_flavors(log, user))
log.info(ret)
return ret
t = Thread(target=t_get_flavors, args=(loop, log, user))
t.start()
ret = t.join()
log.info(ret)
return ret
class OutpostFlavorsAPIHandler(APIHandler):
required_scopes = ["custom:outpostflavors:set"]
def check_xsrf_cookie(self):
pass
@token_authenticated
async def post(self, outpost_name):
check_custom_scopes(self)
global _outpost_flavors_cache
body = self.request.body.decode("utf8")
try:
flavors = json.loads(body) if body else {}
except:
self.set_status(400)
self.log.exception(
f"{outpost_name} - Could not load body into json. Body: {body}"
)
return
self.write(json.dumps(_outpost_flavors_cache))
_outpost_flavors_cache[outpost_name] = flavors
self.set_status(200)
async def get(self):
ret = await async_get_flavors(self.log, self.current_user)
self.write(json.dumps(ret))
self.set_status(200)
return
......
import sys
import threading
class Thread(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.result = None
def run(self):
if self._target is None:
return
try:
self.result = self._target(*self._args, **self._kwargs)
except Exception as exc:
print(f"{type(exc).__name__}: {exc}", file=sys.stderr)
def join(self, *args, **kwargs):
super().join(*args, **kwargs)
return self.result
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment