Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
trungleduc committed Mar 8, 2024
1 parent 3ead40f commit 8a9de41
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 5 deletions.
33 changes: 28 additions & 5 deletions tljh_repo2docker/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
from traitlets import Dict, Int, List, Unicode, default, validate
from traitlets.config.application import Application
from jupyterhub.utils import url_path_join
from .builder import BuildHandler
from .docker import list_images
from .handlers.servers import ServersHandler
from .images import ImagesHandler
from .logs import LogsHandler

if os.environ.get("JUPYTERHUB_API_TOKEN"):
from jupyterhub.services.auth import HubOAuthCallbackHandler
Expand All @@ -34,9 +39,15 @@ class TljhRepo2Docker(Application):

port = Int(6789, help="Port of the service", config=True)

api_prefix = Unicode(help="JupyterHub service prefix", config=True)
base_url = Unicode(help="JupyterHub base URL", config=True)

@default("api_prefix")
@default("base_url")
def _default_base_url(self):
return os.environ.get("JUPYTERHUB_BASE_URL", "/")

service_prefix = Unicode(help="JupyterHub service prefix", config=True)

@default("service_prefix")
def _default_api_prefix(self):
return os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "/")

Expand Down Expand Up @@ -89,7 +100,7 @@ def _default_log_level(self):
def init_settings(self) -> tp.Dict:
"""Initialize settings for the service application."""
static_path = str(HERE / "static")
static_url_prefix = self.api_prefix + "static/"
static_url_prefix = self.service_prefix + "static/"
env_opt = {"autoescape": True}

env = Environment(
Expand All @@ -104,6 +115,8 @@ def init_settings(self) -> tp.Dict:
static_url_prefix=static_url_prefix,
jinja2_env=env,
cookie_secret=os.urandom(32),
base_url=self.base_url,
service_prefix=self.service_prefix
)
return settings

Expand All @@ -114,11 +127,21 @@ def init_handlers(self) -> tp.List:
handlers.extend(
[
(
url_path_join(self.api_prefix, r"/static/(.*)"),
url_path_join(self.service_prefix, r"/static/(.*)"),
web.StaticFileHandler,
{"path": static_path},
),
(self.api_prefix + "oauth_callback", HubOAuthCallbackHandler),
(
url_path_join(self.service_prefix, "oauth_callback"),
HubOAuthCallbackHandler,
),
(url_path_join(self.service_prefix, r"servers"), ServersHandler),
# (url_path_join(self.service_prefix, r"environments"), ImagesHandler),
# (url_path_join(self.service_prefix, r"api/environments"), BuildHandler),
# (
# url_path_join(self.service_prefix, r"api/environments/([^/]+)/logs"),
# LogsHandler,
# ),
]
)

Expand Down
Empty file.
48 changes: 48 additions & 0 deletions tljh_repo2docker/handlers/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import os
from typing import Dict
from tornado import web
from jupyterhub.utils import url_path_join
from jupyterhub.services.auth import HubOAuthenticated
from jinja2 import Template

JUPYTERHUB_API_URL = os.environ.get("JUPYTERHUB_API_URL", None)


class BaseHandler(HubOAuthenticated, web.RequestHandler):
"""
Base handler for tljh_repo2docker service
"""

def fetch_user(self) -> Dict:
user = self.current_user
print("AAAAAAAAAAAAA", user)
return user

def get_template(self, name: str) -> Template:
"""Return the jinja template object for a given name
Args:
name: Template name
Returns:
jinja2.Template object
"""
return self.settings["jinja2_env"].get_template(name)

def render_template(self, name: str, **kwargs) -> str:
"""Render the given template with the provided arguments
Args:
name: Template name
**kwargs: Template arguments
Returns:
The generated template
"""
template_ns = dict(
service_prefix=self.settings.get("service_prefix", "/"),
static_url=self.static_url,
)
template_ns.update(kwargs)
template = self.get_template(name)
return template.render(**template_ns)
73 changes: 73 additions & 0 deletions tljh_repo2docker/handlers/servers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from inspect import isawaitable
from typing import Any, Dict
from jupyterhub.orm import Spawner
from .base import BaseHandler
from tornado import web

# from .docker import list_images


class ServersHandler(BaseHandler):
"""
Handler to show the list of servers available
"""

@web.authenticated
async def get(self):
images = []#await list_images()
user = self.current_user
# if user.running:
# # trigger poll_and_notify event in case of a server that died
# await user.spawner.poll_and_notify()
# auth_state = await user.get_auth_state()
# named_spawners = user.all_spawners(include_default=False)
server_data = []
# for sp in named_spawners:
# server_data.append(
# self._spawner_to_server_data(sp, user)
# )
try:
named_server_limit = await self.get_current_user_named_server_limit()
except Exception:
named_server_limit = 0
result = self.render_template(
"servers.html",
images=images,
allow_named_servers=True,
named_server_limit_per_user=named_server_limit,
server_data=server_data,
default_server_data={},
user_is_admin=True
)

if isawaitable(result):
self.write(await result)
else:
self.write(result)

def _spawner_to_server_data(self, sp: Spawner, user: Any) -> Dict:
data = {
"name": sp.name,
}
try:
data["url"] = user.server_url(sp.name)
except Exception:
data["url"] = ""
try:
data["last_activity"] = sp.last_activity.isoformat() + "Z"
except Exception:
data["last_activity"] = ""

try:
data["active"] = sp.active
except Exception:
data["active"] = False

try:
if sp.user_options:
data["user_options"] = sp.user_options
else:
data["user_options"] = {}
except Exception:
data["user_options"] = {}
return data

0 comments on commit 8a9de41

Please sign in to comment.