|
| 1 | +""" |
| 2 | +Singleuser server quotas |
| 3 | +""" |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import json |
| 7 | +import os |
| 8 | +from collections import namedtuple |
| 9 | + |
| 10 | +import kubernetes.config |
| 11 | +from kubernetes import client |
| 12 | +from traitlets import Any, Integer, Unicode, default |
| 13 | +from traitlets.config import LoggingConfigurable |
| 14 | + |
| 15 | +from .utils import KUBE_REQUEST_TIMEOUT |
| 16 | + |
| 17 | + |
| 18 | +class LaunchQuotaExceeded(Exception): |
| 19 | + """Raised when a quota will be exceeded by a launch""" |
| 20 | + |
| 21 | + def __init__(self, message, *, quota, used, status): |
| 22 | + """ |
| 23 | + message: User-facing message |
| 24 | + quota: Quota limit |
| 25 | + used: Quota used |
| 26 | + status: String indicating the type of quota |
| 27 | + """ |
| 28 | + super().__init__() |
| 29 | + self.message = message |
| 30 | + self.quota = quota |
| 31 | + self.used = used |
| 32 | + self.status = status |
| 33 | + |
| 34 | + |
| 35 | +ServerQuotaCheck = namedtuple("ServerQuotaCheck", ["total", "matching", "quota"]) |
| 36 | + |
| 37 | + |
| 38 | +class LaunchQuota(LoggingConfigurable): |
| 39 | + |
| 40 | + executor = Any( |
| 41 | + allow_none=True, help="Optional Executor to use for blocking operations" |
| 42 | + ) |
| 43 | + |
| 44 | + total_quota = Integer( |
| 45 | + None, |
| 46 | + help=""" |
| 47 | + The number of concurrent singleuser servers that can be run. |
| 48 | +
|
| 49 | + None: no quota |
| 50 | + 0: the hub can't run any singleuser servers (e.g. in maintenance mode) |
| 51 | + Positive integer: sets the quota |
| 52 | + """, |
| 53 | + allow_none=True, |
| 54 | + config=True, |
| 55 | + ) |
| 56 | + |
| 57 | + async def check_repo_quota(self, image_name, repo_config, repo_url): |
| 58 | + """ |
| 59 | + Check whether launching a repository would exceed a quota. |
| 60 | +
|
| 61 | + Parameters |
| 62 | + ---------- |
| 63 | + image_name: str |
| 64 | + repo_config: dict |
| 65 | + repo_url: str |
| 66 | +
|
| 67 | + Returns |
| 68 | + ------- |
| 69 | + If quotas are disabled returns None |
| 70 | + If quotas are exceeded raises LaunchQuotaExceeded |
| 71 | + Otherwise returns: |
| 72 | + - total servers |
| 73 | + - matching servers running image_name |
| 74 | + - quota |
| 75 | + """ |
| 76 | + return None |
| 77 | + |
| 78 | + |
| 79 | +class KubernetesLaunchQuota(LaunchQuota): |
| 80 | + |
| 81 | + api = Any( |
| 82 | + help="Kubernetes API object to make requests (kubernetes.client.CoreV1Api())", |
| 83 | + ) |
| 84 | + |
| 85 | + @default("api") |
| 86 | + def _default_api(self): |
| 87 | + try: |
| 88 | + kubernetes.config.load_incluster_config() |
| 89 | + except kubernetes.config.ConfigException: |
| 90 | + kubernetes.config.load_kube_config() |
| 91 | + return client.CoreV1Api() |
| 92 | + |
| 93 | + namespace = Unicode(help="Kubernetes namespace to check", config=True) |
| 94 | + |
| 95 | + @default("namespace") |
| 96 | + def _default_namespace(self): |
| 97 | + return os.getenv("BUILD_NAMESPACE", "default") |
| 98 | + |
| 99 | + async def check_repo_quota(self, image_name, repo_config, repo_url): |
| 100 | + # the image name (without tag) is unique per repo |
| 101 | + # use this to count the number of pods running with a given repo |
| 102 | + # if we added annotations/labels with the repo name via KubeSpawner |
| 103 | + # we could do this better |
| 104 | + image_no_tag = image_name.rsplit(":", 1)[0] |
| 105 | + |
| 106 | + # TODO: put busy users in a queue rather than fail? |
| 107 | + # That would be hard to do without in-memory state. |
| 108 | + repo_quota = repo_config.get("quota") |
| 109 | + pod_quota = self.total_quota |
| 110 | + |
| 111 | + # Fetch info on currently running users *only* if quotas are set |
| 112 | + if pod_quota is not None or repo_quota: |
| 113 | + matching_pods = 0 |
| 114 | + |
| 115 | + # TODO: run a watch to keep this up to date in the background |
| 116 | + f = self.executor.submit( |
| 117 | + self.api.list_namespaced_pod, |
| 118 | + self.namespace, |
| 119 | + label_selector="app=jupyterhub,component=singleuser-server", |
| 120 | + _request_timeout=KUBE_REQUEST_TIMEOUT, |
| 121 | + _preload_content=False, |
| 122 | + ) |
| 123 | + resp = await asyncio.wrap_future(f) |
| 124 | + pods = json.loads(resp.read())["items"] |
| 125 | + total_pods = len(pods) |
| 126 | + |
| 127 | + if pod_quota is not None and total_pods >= pod_quota: |
| 128 | + # check overall quota first |
| 129 | + self.log.error(f"BinderHub is full: {total_pods}/{pod_quota}") |
| 130 | + raise LaunchQuotaExceeded( |
| 131 | + "Too many users on this BinderHub! Try again soon.", |
| 132 | + quota=pod_quota, |
| 133 | + used=total_pods, |
| 134 | + status="pod_quota", |
| 135 | + ) |
| 136 | + |
| 137 | + for pod in pods: |
| 138 | + for container in pod["spec"]["containers"]: |
| 139 | + # is the container running the same image as us? |
| 140 | + # if so, count one for the current repo. |
| 141 | + image = container["image"].rsplit(":", 1)[0] |
| 142 | + if image == image_no_tag: |
| 143 | + matching_pods += 1 |
| 144 | + break |
| 145 | + |
| 146 | + if repo_quota and matching_pods >= repo_quota: |
| 147 | + self.log.error( |
| 148 | + f"{repo_url} has exceeded quota: {matching_pods}/{repo_quota} ({total_pods} total)" |
| 149 | + ) |
| 150 | + raise LaunchQuotaExceeded( |
| 151 | + f"Too many users running {repo_url}! Try again soon.", |
| 152 | + quota=repo_quota, |
| 153 | + used=matching_pods, |
| 154 | + status="repo_quota", |
| 155 | + ) |
| 156 | + |
| 157 | + return ServerQuotaCheck( |
| 158 | + total=total_pods, matching=matching_pods, quota=repo_quota |
| 159 | + ) |
| 160 | + |
| 161 | + return None |
0 commit comments