콘텐츠로 이동

JupyterHub란: 구성 요소와 Kubernetes 배포(Zero to JupyterHub) 메모 (2021)

Interactive Diagram

새 탭 ↗

이 글은 2021년 구성과 관찰을 보존한 기록이다. 현재 운영 runbook이 아니며, stable/latest 링크는 당시 버전에 고정된 문서가 아니다. 재사용 전 인증 클래스, 패키지 호환성, 사용자별 Storage와 실제 single-user 실행 경로를 확인한다.

Jupyter Hub 는 multi user 에게 Jupyter Notebook 을 제공하는 좋은 방안이다. 또한, 단일 사용자 Jupyter Notebook 의 다수의 인스턴스를 생성 및 관리할 수 있으며, Proxy 처리까지 담당하는 Multi-User Hub 이다.

  • 크게 4개의 subsystem 으로 구성.
    • 사용자 환경 UI 제공 및 subsystem 간 연계를 위한 Hub.
    • Client Browser 의 request 처리를 위한 HTTP Proxy.
    • multiple single-user Jupyter notebook 서버를 관리하는 Spawner.
    • 사용자 제어를 위한 Authentication class.

원본 그림: JupyterHub 문서 (라이선스 문제로 이미지는 싣지 않고 링크만 남김)

Jupyter Hub Docs 참조 https://jupyterhub.readthedocs.io/en/stable/index.html

Jupyter Hub for kubernetes Project 는 Cloud / On-premise 의 기존 k8s 환경에서 self managed JupyterHub를 설정하고 대규모 사용자 그룹을 지원하기 위한 Project. 특정 CSP 업체와 관련이 없으며, Helm Chart Version 을 통하여 제공. (당시 문서의 요구 조건: Kubernetes >= 1.14 / Helm >= 2.16; 현재 요구 조건은 선택한 차트에서 확인한다)

  • Architecture
    • Proxy, Hub 등의 사용자 request 처리를 위한 서비스 동일
    • 관리자 지정 Docker Image 를 가져오기 위한 Puller 및 Resource 관리를 위한 Idle Culler 내장

Kubernetes 위 JupyterHub 구성도: Proxy, Hub, 사용자별 Pod와 Volume, Cloud Volume과 Image Registry 출처: Zero to JupyterHub with Kubernetes 문서, Architecture, Project Jupyter Contributors, BSD-3-Clause

  • 주요 특징
    • helm 배포시 사용되는 config.yml 파일을 수정하여 hub, singleuser, proxy 등 설정
    • nbgitpuller 를 사용하여 git 과 동기화 가능
    • 일반적으로 사용자가 직접 conda kernel 을 구성
    • profileList 를 정의하여 docker image, gpu, volume 등 별도 환경 구성
    • profileList에서 환경을 선택한다. 차트 0.11.1의 hub.allowNamedServers: false 설정에서는 사용자별 기본 Server 하나를 사용하며, JupyterHub 전체의 고정 제한은 아니다
    • 사용자 ID 로 Notebook Server Pod 생성

Jupyter Hub for kubernetes Docs 참조 https://zero-to-jupyterhub.readthedocs.io/en/stable/index.html

Jupyter Hub KubeSpawner Docs 참조 https://jupyterhub-kubespawner.readthedocs.io/en/latest/spawner.html

  • helm install 및 upgrade 를 통하여, Jupyter Hub for kubernetes 관리
  • Environment
    • k8s v1.19.7
    • helm v3.5.2
    • JupyterHub Helm chart v0.11.1
구성 요소이 기록의 버전/근거
Kubernetes1.19.7
Helm3.5.2
JupyterHub Helm chart0.11.1 (helm upgrade --version=0.11.1)
Notebook 이미지의 JupyterHub package아래 Official Image Dockerfile 발췌는 1.3.0; Hub package와 Custom Image package의 실제 버전은 별도 확인 대상이다

Install Jupyter Hub 참조 https://zero-to-jupyterhub.readthedocs.io/en/stable/jupyterhub/installation.html

  • 당시 helm upgrade 관찰 (아래 명령은 역사적 배포 기록이며 이번 수정에서 실행하지 않았다)
    • hub, proxy pod Restart. (strategy type: Recreate, 1분 내로 restart 됨)
    • 신규 사용자 로그인 불가
    • 기존 사용자 로그인 불가
    • 기존 사용자 신규 notebook 파일 생성 불가
    • 기존 사용자 개발중인 notebook 파일에서 개발 작업은 가능

실제 중단 범위와 시간은 Hub/Proxy 재시작, 기존 연결, Notebook Server 상태에 따라 달라진다. 위 사용자 동작은 당시 관찰이지 모든 업그레이드의 보장이 아니다.

Terminal window
helm upgrade --cleanup-on-fail \
--install $RELEASE jupyterhub/jupyterhub \
--namespace $NAMESPACE \
--create-namespace \
--version=0.11.1 \
--values config.yaml
  • 배포 내역
$ kubectl get deploy
NAME READY UP-TO-DATE AVAILABLE AGE
hub 1/1 1 1 11d
proxy 1/1 1 1 11d
user-scheduler 2/2 2 2 11d
$ kubectl get ds
NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
continuous-image-puller 2 2 2 2 2 <none> 11d
$ kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
hub ClusterIP 10.0.0.10 <none> 8081/TCP 11d
proxy-api ClusterIP 10.0.0.11 <none> 8001/TCP 11d
proxy-public LoadBalancer 10.0.0.12 <EXTERNAL-IP> 443:31151/TCP,80:30780/TCP 11d

config.yaml 의 singleuser configuration 을 활용하여, Jupyter Notebook Official Image 기반 기본 Profile 생성

  • Jupyter Notebook Official Image Dockerfile 기본 설명
    • ubuntu base image 기반, conda 및 python 개발 환경 설치
    • jovyan user 의 home directory 에 작업 환경 구축
    • notebook, jupyterhub, jupyterlab 을 기본적으로 설치
    • Image 에 포함되어 있는 별도의 shell script 를 실행하여, container 구동
...
RUN conda install --quiet --yes \
'notebook=6.3.0' \
'jupyterhub=1.3.0' \
'jupyterlab=3.0.14' && \
conda clean --all -f -y && \
npm cache clean --force && \
jupyter notebook --generate-config && \
jupyter lab clean && \
rm -rf /home/$NB_USER/.cache/yarn && \
fix-permissions $CONDA_DIR && \
fix-permissions /home/$NB_USER
...
  • config.yaml 구성
    • singleuser 에서 default image 설정
    • profileList 를 통하여, profile 별 관리자 지정 image 설정 가능
    • kubespawner 에서 k8s 설정을 override 하여, image / resource / volume 등을 별도 관리
singleuser:
image:
name: jupyter/minimal-notebook
tag: latest
storage:
type: none
cpu:
limit: 0.5
guarantee: 0.05
memory:
limit: 1G
guarantee: 256M
profileList:
- display_name: "Minimal environment"
description: "Default env."
default: true
- display_name: "Data Science environment"
description: "Data Science env."
kubespawner_override:
# Data Science 를 위한 Official Image
image: jupyter/datascience-notebook:latest
# Resources
cpu_limit: 1
cpu_guarantee: 0.05
mem_limit: 2G
mem_guarantee: 256M
# Volumes
volume_mounts:
- name: jupyter-notebook-tf
mountPath: /home/jovyan
volumes:
- name: jupyter-notebook-tf
persistentVolumeClaim:
claimName: jupyter-notebook-tf

이 예시의 singleuser.storage.type: none은 기본 Profile에 사용자별 PVC를 만들지 않는다. Container writable layer의 파일은 Pod 교체 시 보존되지 않는다. Data Science 및 아래 Custom Profile의 고정 claimName: jupyter-notebook-tf는 같은 PVC를 공유하며, 사용자별 claim이나 subPath가 없다. /home/jovyan 또는 /root 전체 mount는 사용자별 파일 격리를 보장하지 않는다. Access mode, Node 배치, Storage backend에 따라 동시 mount 결과가 달라지므로 RWO라는 이유만으로 항상 실패한다고 단정하지 않는다. 운영에서는 사용자별 PVC와 파일 권한을 설계하고, 공유 데이터 volume은 별도 권한 경계로 다룬다.

  • Jupyter Hub Profile List 조회

Official Image 가 아닌, 사용자가 직접 정의한 Dockerfile 및 command script 등으로 Custom Notebook Image 구성이 되어 있는 경우, Jupyter Hub 에서 구동하기 위해 확인해야 할 항목.

  1. jupyterhub package 설치
    • JupyterHub 의 Notebook Server Pod 생성 시, Notebook Image 에 설치된 jupyterhub-singleuser command 를 통하여 실행.
    • Official Image 에는 jupyterhub package 가 내장되어 있어, 별도의 설정 변경 없이 Jupyter Hub 에서 Notebook 실행 가능.
    • jupyterhub-singleuser 는 jupyterhub package 설치를 통하여 실행 가능하므로, custom image 에 jupyterhub package 설치 필요.
  • Custom Notebook Image Dockerfile (이관 전 root 기반 이미지의 역사적 발췌; 그대로 재배포하는 예시가 아니다)
    • ubuntu base image 기반으로, python3 설치 및 jupyter notebook / lab 이 설치되어 있다고 가정.

    • Hub용 image build 단계에서 Hub와 호환되는 jupyterhub package를 설치하고 버전을 고정한다. 아래 Dockerfile은 이관 전 발췌이며 이 설치 단계를 포함한 최종 image가 아니다.

    • Dockerfile

FROM ubuntu:18.04
USER root
RUN apt-get update
RUN apt-get install -y python3 python3-pip openjdk-8-jre wget
RUN ln -s /usr/bin/python3 /usr/bin/python
RUN ln -s /usr/bin/pip3 /usr/bin/pip
RUN python -m pip install --upgrade pip
RUN python -m pip install notebook -U && pip install jupyterlab
RUN jupyter notebook --generate-config --allow-root -y
COPY run.sh /usr/local/bin/
EXPOSE 8888
WORKDIR /root
  • command run.sh (이관 전 문제와 Hub 실행 경로 구분)
Terminal window
# 과거 script는 root + 빈 Notebook token으로 standalone 서버를 시작했다.
# 그 명령은 인증 없는 외부 노출 경로가 되어 실행 예시에서 제거했다.
# Hub 전용 image에서 호환되는 jupyterhub package를 build 시 설치하고,
# Hub가 주입한 환경에서 아래 entrypoint를 사용한다.
exec jupyterhub-singleuser "$@"
  1. 기존 root 이미지 이관 시 실행 권한 확인
    • Official Image 의 경우, jovyan 이라는 공통 user 를 생성하여 Notebook Server 를 구동하며, jupyterhub-singleuser command 실행 시에도 별도의 옵션 지정이 필요 없음.
    • uid / gid 설정을 통하여, securityContext 설정 변경.
    • 아래 uid: 0, gid: 0, --allow-root는 당시 이관 호환성 기록이다. 운영 기본값으로 채택하지 않는다. 비root UID/GID와 home volume 권한을 맞춘 이미지로 이관하고, Hub 인증을 사용하는 jupyterhub-singleuser와 standalone Notebook 실행을 혼합하지 않는다.
  • config.yaml
    • kubespawner_override 수정
...
- display_name: "Custom Notebook without conda"
description: "without conda"
kubespawner_override:
cpu_limit: 1
cpu_guarantee: 0.1
mem_limit: 2G
mem_guarantee: 512M
# 역사적 root 이관 설정; 운영 권장 설정이 아니다
uid: 0
gid: 0
cmd: ["jupyterhub-singleuser", "--allow-root", "--ip=0.0.0.0"]
image: registry.example.invalid/jupyter-notebook-custom:latest
image_pull_policy: Always
volume_mounts:
- name: jupyter-notebook-tf
mountPath: /root
volumes:
- name: jupyter-notebook-tf
persistentVolumeClaim:
claimName: jupyter-notebook-tf
...

Migration 시 필요한 Customization 확인.

기존에 사용하던 Notebook 혹은 Lab 개발 Container 환경을, Jupyter Hub 에서 동일하게 사용하기 위해 확인할 항목.
기존의 Container 환경은 Docker commit 을 통하여 Image 를 생성하고, 이를 Jupyter Hub 에서 구동한다고 가정.

  • 작업 순서
    1. Custom Image 로 Kubernetes 에 배포된 Notebook 개발 환경 생성
    2. Container 가 구동 중인 Worker Node 에 접속
    3. 해당 Container ID 를 찾아서 docker commit
    4. docker registry 에 push 하여, Migration Image 완성

Kubernetes 에 구동 되는 Pod 의 Docker commit 참조 https://stackoverflow.com/questions/49481849/is-there-a-way-to-download-the-container-image-from-a-pod-in-kuberentes-environm

  • Jupyter Hub 는 Notebook Server Pod 생성 시, 아래의 args 에 정의된 명령어를 실행하여 생성하며, 기본적으로 ip 허용 / port 지정 옵션만 추가되어 있음.
Args:
jupyterhub-singleuser
--ip=0.0.0.0
--port=8888
  • 기존에 k8s deployment 에, command 에 초기 실행 script 가 정의되어 있을 경우, 해당 script 가 실행되어 jupyterhub-singleuser notebook server 생성이 불가능.
containers:
- image: registry.example.invalid/jupyter-notebook-custom:latest
name: jupyter-notebook-custom
imagePullPolicy: Always
ports:
- containerPort: 8888
# 초기 실행 script
command: ["/bin/sh", "-c", "run.sh"]
  • Docker Commit 시, ENTRYPOINT 초기화 하거나, run.sh 에서 jupyterhub-singleuser 를 실행하도록 script 수정 필요
$ docker commit --change='ENTRYPOINT [""]' <container-id> jupyter-notebook-custom

Jupyter Lab 은 Project Jupyter 를 위한 차세대 웹 기반 사용자 인터페이스이다. Jupyter Lab을 활용하여, 유연하고 통합되며 확장 가능한 방식으로 Jupyter Notebook , Text Editor, Terminal 등을 활용할 수 있다.

Jupyter Lab Docs 참조 https://jupyterlab.readthedocs.io/en/latest/index.html

  • Jupyter Hub 에서 Lab 구동
    • 기본적으로 Jupyter Notebook Official Image 에 jupyterlab package 가 설치되어 있으므로, 해당 base image 기반으로 구동시 Notebook 과 Lab 의 인터페이스를 모두 사용 가능.
    • Custom Notebook Image 에도 jupyterlab package 를 설치하여 구동하면, Jupyter Lab 인터페이스 사용 가능.
    • URL context 로 인터페이스 변경
      • domain:port/tree
      • domain:port/lab
    • kubespawner_override 를 활용하여, profile 별 default_url 을 변경하여 초기 실행 인터페이스 별도 설정 가능.
    • Migration 시 확인할 항목은 Jupyter Notebook 과 동일함.
- display_name: "Bonjour Lab"
description: "Bonjour tensorflow."
kubespawner_override:
cpu_limit: 1
cpu_guarantee: 0.1
# Jupyter Lab 을 초기 실행 화면으로,,,
default_url: /lab
mem_limit: 4G
mem_guarantee: 512M
image: registry.example.invalid/jupyter-notebook:bonjour

Jupyter Hub 는 jupyterhub-idle-culler 서비스를 활용하여, 유휴 또는 장기 실행 Jupyter Notebook Server 를 식별하고 종료함.
Jupyter Hub API token 인증을 통하여, Python Standalone script 로 실행하여 jupyterhub-idle-culler 실행도 가능.

Terminal window
export JUPYTERHUB_API_TOKEN=$(jupyterhub token)
python3 -m jupyterhub-idle-culler [--timeout=900] [--url=http://localhost:8081/hub/api]

Jupyter Hub Idel Culler Github Repository 참조 https://github.com/jupyterhub/jupyterhub-idle-culler

  • timeout 설정 시간 동안, 활동이 없는 사용자 pod 자동 삭제 가능.
  • 당시 테스트에서는 Browser 연결이 유지되면 Pod가 cull되지 않았다. 실제 판정은 Server의 activity 보고, 연결 상태, culler 옵션과 버전에 따라 달라진다.
  • Server 재시작 시 메모리의 변수는 손실된다. Container writable layer에 설치한 패키지는 Pod 교체 시 손실되지만, Image에 포함된 패키지와 보존된 PVC의 파일은 별도다. PVC에 설치한 환경의 재사용은 mount와 경로 설정을 확인한다.

아래는 당시 설정에서의 관찰이며 이번 수정에서 재실행한 결과가 아니다.

  • cull: timeout: 120, every: 10 (seconds)
cull:
enabled: true
timeout: 120
every: 10
  • notebook 화면을 띄운 상태에서는 pod 가 유지됨
  • notebook 화면에 포커스가 없어도 pod 가 유지됨
  • notebook 화면을 닫아서 완전히 벗어나야 pod 가 kill 됨

기본값 대조: 차트 0.11.1 values.

여기서 임의 ID로 로그인한 동작은 차트 0.11.1의 기본 hub.config.JupyterHub.authenticator_class: dummy에서 관찰한 것이다. Base Authenticator는 공통 인증/인가 설정을 정의하며, 임의 ID 로그인이 모든 인증 클래스의 기본 동작은 아니다. 선택한 차트 values와 최종 Hub config의 JupyterHub.authenticator_class를 확인한다.

Jupyter Hub에는 특별한 권한을 가진 Admin 개념이 존재한다. 다른 사용자의 server 를 start/stop 하는 권한이 있으며, 선택적으로 사용자의 Notebook Server 에 access 할 수 있다. Control Panel 에 admin 버튼 이 표시되며, 이러한 모든 작업을 수행 할 수 있는 Admin Panel 에 접근할 수 있다.

DummyAuthenticator는 사용자별 password 저장소가 아니다. Admin/allowlist 설정은 신원 검증을 대체하지 않으며 실제 credential 검증은 선택한 Authenticator 또는 Identity Provider의 책임이다.

  • Jupyter Hub Admin Panel

  • DummyAuthenticator password 미설정 (제한된 테스트용)

    • 임의의 id 입력해도 login 가능 하며, 해당 id 로 hub user 생성됨.
  • admin user 설정 시

    • admin_users 에 등록된 id 로 login 할 때만, Admin Panel 접근 가능
    • admin 은 user 추가/수정/삭제, user server 접속/시작/중지 가능
    • password 없는 dummy 테스트에서 일반 user도 임의 ID로 login 가능; 본인 신원 증명이 아니다
  • whitelist user 설정 시

    • allowed_users 에 등록된 id 만 login 가능
    • admin 은 Admin Panel 에서 “Add Users” 기능을 이용하여, whitelist user 추가 가능
  • Data Repository

    • Hub DB PVC는 사용자 Notebook PVC와 별개다. helm uninstall 후 보존/삭제는 차트 template의 resource 소유권·보존 정책과 PVC 삭제 여부에 따라 달라지고, PVC 삭제 후 실제 PV/data 처리는 StorageClass/PV의 reclaimPolicy를 확인한다. 여기서는 uninstall 결과를 검증하지 않았다.
    • sqlite 로 data 관리하는 것이 default 설정임.
  • Rest API

  • User Config Example

hub:
config:
JupyterHub:
authenticator_class: "dummy"
Authenticator:
admin_users:
- admin
- user1
- user2
allowed_users:
- user3
- user4

DummyAuthenticator는 공통 password를 설정할 수 있지만 사용자별 신원을 검증하지 않는다. 아래 예시는 외부 노출 없는 제한된 테스트용이며 운영 인증에는 OAuthenticator 등 실제 Identity Provider 연계를 별도로 설계한다.

  • DummyAuthenticator password config
hub:
config:
Authenticator:
admin_users:
- admin
- user1
- user2
allowed_users:
- user3
- user4
DummyAuthenticator:
password: <password>
JupyterHub:
authenticator_class: "dummy"

JupyterHub의 oauthenticator 는 사용자가 GitHub, Google 및 CILogon과 같은 third-party OAuth2 identity provider 를 통해 인증할 수 있도록 지원함. OAuth2 Client ID 와 Secret 이 필요함.

Jupyter Hub oauthenticator Docs 참조 https://oauthenticator.readthedocs.io/en/stable/getting-started.html

GenericOAuthenticator class 를 활용한, KeyCloak Server 인증 Test

섹션 제목: “GenericOAuthenticator class 를 활용한, KeyCloak Server 인증 Test”

아래 HTTP IdP URL과 /auth 경로는 Keycloak 12.0.4 당시 구성 기록이다. 운영에서는 TLS termination과 Hub↔IdP 연결의 certificate 검증, 현재 Keycloak endpoint, OAuthenticator 버전과 조직 접근 정책을 별도 확인한다. OAuth app 생성만으로 조직 구성원 제한이 보장되는 것은 아니다.

Key Cloak 의 경우, OpenID / SAML2.0 모두를 지원하며, sso login 연계 혹은 oauth2 인증 방식의 third-pary 인증 서버 연계 등에 유용하게 사용 가능할 것으로 보임.

KeyCloak 공식 문서 참조 https://www.keycloak.org/docs/latest/getting_started/index.html#securing-a-sample-application

  • Environment

    • k8s v1.19.7
    • helm v3.5.2
    • JupyterHub Helm chart v0.11.1
    • keycloak v12.0.4
  • Test Architecture

PlantUML Diagram
$ kubectl get all -n keycloak
NAME READY STATUS RESTARTS
pod/keycloak-0 1/1 Running 0
pod/keycloak-postgresql-0 1/1 Running 0
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S)
service/keycloak-headless ClusterIP None <none> 80/TCP
service/keycloak-http LoadBalancer 10.0.0.13 <external-ip> 80:30339/TCP,8443:32239/TCP,9990:30459/TCP
service/keycloak-postgresql ClusterIP 10.0.0.14 <none> 5432/TCP
service/keycloak-postgresql-headless ClusterIP None <none> 5432/TCP
NAME READY
statefulset.apps/keycloak 1/1
statefulset.apps/keycloak-postgresql 1/1
  1. Jupyter Hub 전용 KeyCloak Realm / Client 구성

  2. Github Organization Oauth Apps 에, keycloak app. 추가

  3. 위에서 생성한 Client ID/secret 을 활용하여, KeyCloak Identity Provider 에 GitHub 추가

  4. Github Organization Oauth Apps, keycloak app. 에 Authorization Callback URL Update

  5. Jupyter Hub config.yaml 에 GenericOAuthenticator 설정
    : KeyCloak openid connect

hub:
config:
Authenticator:
auto_login: true
GenericOAuthenticator:
admin_users:
- admin
client_id: <keycloak-client-id>
client_secret: <keycloak-client-secret>
# jupyter hub oauth callback
oauth_callback_url: https://<jupyterhub-domain>/hub/oauth_callback
# 이하 keycloak auth / token / userdata URL
authorize_url: http://<keycloak-domain>/auth/realms/example-realm/protocol/openid-connect/auth
token_url: http://<keycloak-domain>/auth/realms/example-realm/protocol/openid-connect/token
userdata_url: http://<keycloak-domain>/auth/realms/example-realm/protocol/openid-connect/userinfo
login_service: keycloak
username_key: preferred_username
userdata_params:
state: state
JupyterHub:
authenticator_class: generic-oauth
  • Jupyter Hub Login 시, KeyCloak Login 으로 redirect

    • keycloak user 로 login 가능
    • identity provider 인 GitHub 로 login 가능
  • KeyCloak 에 Identity Provider 로 등록된 GitHub 를 통한 Login

    • 당시 구성에서는 해당 GitHub Organization의 User만 인가되는 것을 관찰했다. 현재 배포에서의 조직 제한 정책은 별도 검증한다.
  • 특이 사항 : Jupyter Hub Logout 기능을 사용할 경우, Jupyter Hub session 만 삭제됨. | Jupyter Hub Logout 시, KeyCloak 혹은 인증된 Identity Provider (SSO / GitHub etc.) session 까지 삭제하는 것은 Optional 영역일 것으로 보이며, Jupyter Hub Logout 을 통하여 인증된 모든 session 을 삭제할 경우, 추가 개발이 필요.