Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 153 additions & 2 deletions config/jupyterhub/01-spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# ruff: noqa: F821 - `c` is a magic global provided by JupyterHub

import asyncio
import copy
import json
import logging
import os
Expand Down Expand Up @@ -74,6 +75,104 @@
},
]

# ---------------------------------------------------------------------------
# Shared memory (/dev/shm)
# ---------------------------------------------------------------------------
# Container runtimes default /dev/shm to 64 MiB, which is too small for PyTorch
# DataLoader workers and Ray's object store. Mount a memory-backed emptyDir
# instead. Profiles can resize it with the chart-only ``shm_size_limit`` key,
# translated in _translate_profile_shared_memory.
_DSHM_NAME = "dshm"
_DSHM_PATH = "/dev/shm"
_DEFAULT_SHM_SIZE_LIMIT = "8Gi"
_MISSING_OVERRIDE = object()


def _shared_memory_size_or(value, setting, fallback):
"""Return ``value`` stripped, or warn and return ``fallback``.

A bad size only warns, because raising at load would stop the hub.
"""
if isinstance(value, str) and value.strip():
return value.strip()
log.warning(
"%s is %r, expected a non-empty string; using %s",
setting, value, fallback,
)
return fallback


def _shared_memory_volume(size_limit):
return {
"name": _DSHM_NAME,
"emptyDir": {"medium": "Memory", "sizeLimit": size_limit},
}


def _shared_memory_mount():
return {"name": _DSHM_NAME, "mountPath": _DSHM_PATH}


def _upsert_named(entries, addition):
"""Return entries with exactly one item bearing ``addition``'s name."""
retained = [
entry
for entry in list(entries or [])
if entry.get("name") != addition["name"]
]
return [*retained, addition]


def _with_shared_memory_volume(volumes, size_limit):
return _upsert_named(volumes, _shared_memory_volume(size_limit))


def _with_shared_memory_mount(volume_mounts):
retained = [
mount
for mount in list(volume_mounts or [])
if mount.get("name") != _DSHM_NAME and mount.get("mountPath") != _DSHM_PATH
]
return [*retained, _shared_memory_mount()]


def _resolve_list_override(spawner, trait_name, configured):
if configured is _MISSING_OVERRIDE:
return getattr(spawner, trait_name, [])
if callable(configured):
return configured(spawner)
return configured


def _profile_volumes_override(configured, size_limit):
def apply(spawner):
volumes = _resolve_list_override(spawner, "volumes", configured)
return _with_shared_memory_volume(volumes, size_limit)

return apply


def _profile_volume_mounts_override(configured):
def apply(spawner):
mounts = _resolve_list_override(spawner, "volume_mounts", configured)
return _with_shared_memory_mount(mounts)

return apply


_shared_memory_enabled = bool(get_chart_config("shared-memory-enabled", True))
_shared_memory_size_limit = get_chart_config(
"shared-memory-size-limit", _DEFAULT_SHM_SIZE_LIMIT
)
if _shared_memory_enabled:
_shared_memory_size_limit = _shared_memory_size_or(
_shared_memory_size_limit,
"singleuser.sharedMemory.sizeLimit",
_DEFAULT_SHM_SIZE_LIMIT,
)
c.KubeSpawner.volumes.append(_shared_memory_volume(_shared_memory_size_limit))
c.KubeSpawner.volume_mounts.append(_shared_memory_mount())

# ---------------------------------------------------------------------------
# Admin-provisioned nebi config (OCI registries, default-registry seed flag).
# Helm renders the deployer's `nebi.registries` / `nebi.seedDefaultRegistry`
Expand Down Expand Up @@ -374,13 +473,64 @@ def _setup_trust_bundle(spawner):
# code changes. Empty list = no profile selector (single-instance mode).
# Keys used only for group gating; KubeSpawner must never see them. They are
# stripped per user in _filter_profiles because gating is a per-user decision.
# ``image-variant`` is the other chart-only key — it is stripped once at load
# ``image-variant`` is another chart-only key — it is stripped once at load
# in _resolve_image_variants because its effect (image injection) is the same
# for every user and jhub-apps reads the resolved list too. A future custom key
# for every user and jhub-apps reads the resolved list too.
# ``shm_size_limit`` is translated once at load in
# _translate_profile_shared_memory for the same reason. A future custom key
# belongs in whichever of the two matches how it is evaluated.
_PROFILE_GATING_KEYS = ("access", "groups", "users")


def _profile_shared_memory_size(name, requested_size):
"""Return a profile's valid size limit, or the chart-wide one."""
if requested_size is _MISSING_OVERRIDE:
return _shared_memory_size_limit
return _shared_memory_size_or(
requested_size,
f"profiles: {name!r} shm_size_limit",
_shared_memory_size_limit,
)


def _translate_profile_shared_memory(profile):
"""Translate the chart-owned ``shm_size_limit`` into KubeSpawner traits.

Like ``image-variant``, this runs once at load because the result is the
same for every user. A bad size only warns and falls back to the
chart-wide size, because raising here would stop the hub for every user.
"""
translated = copy.deepcopy(profile)
overrides = translated.get("kubespawner_override")
if not isinstance(overrides, dict):
return translated

name = translated.get("slug") or translated.get("display_name")
requested_size = overrides.pop("shm_size_limit", _MISSING_OVERRIDE)
if not _shared_memory_enabled:
if requested_size is not _MISSING_OVERRIDE:
log.warning(
"profiles: ignoring shm_size_limit for %r because shared memory is disabled",
name,
)
return translated

overrides_shared_memory = (
requested_size is not _MISSING_OVERRIDE
or "volumes" in overrides
or "volume_mounts" in overrides
)
if not overrides_shared_memory:
return translated

size_limit = _profile_shared_memory_size(name, requested_size)
configured_volumes = overrides.get("volumes", _MISSING_OVERRIDE)
configured_mounts = overrides.get("volume_mounts", _MISSING_OVERRIDE)
overrides["volumes"] = _profile_volumes_override(configured_volumes, size_limit)
overrides["volume_mounts"] = _profile_volume_mounts_override(configured_mounts)
return translated


def _get_profile_groups(auth_state):
"""Resolve the user's full Keycloak group list for profile gating.

Expand Down Expand Up @@ -593,6 +743,7 @@ def _resolve_image_variants(profiles, base_name, base_tag, overrides):
get_config("singleuser.image.tag", ""),
get_config("custom.image-variants", {}),
)
_profiles = [_translate_profile_shared_memory(profile) for profile in _profiles]
if _profiles:
c.KubeSpawner.profile_list = _render_profile_list
log.info(
Expand Down
45 changes: 45 additions & 0 deletions docs/src/content/docs/server-profiles.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,51 @@ satisfy leaves the server `Pending` forever with no message in the UI.
`kubespawner_override` accepts any KubeSpawner trait — `node_selector`, `image`,
`extra_resource_limits`, `tolerations`, `environment`, and the rest.

## Shared memory

The chart mounts a memory-backed `emptyDir` at `/dev/shm` in every singleuser pod.
The chart-wide default is controlled by `singleuser.sharedMemory`:

```yaml
singleuser:
sharedMemory:
enabled: true
sizeLimit: 8Gi
```

Profiles inherit that size. Use the chart-specific `shm_size_limit` override when a
larger profile needs a different limit:

```yaml
jupyterhub:
custom:
profiles:
- slug: gpu-instance
display_name: "GPU Instance"
kubespawner_override:
mem_limit: "32G"
shm_size_limit: "16Gi"
```

If a profile's `shm_size_limit` is empty or not a string, the hub logs a warning
and that profile uses the chart-wide size.

`sizeLimit` caps tmpfs consumption; it does not reserve memory. Pages written to
`/dev/shm` count against the writing container's memory limit, so leave enough
memory for the notebook and its worker processes. The effective filesystem
capacity can be lower than `sizeLimit` because of node or pod memory constraints.
Ray commonly targets about 30% of available memory for its object store.

Set `singleuser.sharedMemory.enabled: false` to retain the runtime's default
`/dev/shm`, or to manage that mount yourself through a profile's `volumes` and
`volume_mounts` overrides. With chart management disabled, those overrides are
left unchanged and `shm_size_limit` is ignored.

The shared-memory setting applies to profile-level `kubespawner_override`.
KubeSpawner applies `profile_options` choice overrides afterward, so choices
that replace `volumes` or `volume_mounts` must include any required shared-memory
entries themselves.

## Image choices within a profile

`profile_options` adds a second dropdown under the selected profile:
Expand Down
6 changes: 6 additions & 0 deletions docs/src/content/docs/values-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ Not to be confused with `jupyterhub.singleuser`, which is the upstream passthrou

| Field | Default | What it does |
|---|---|---|
| `singleuser.sharedMemory.enabled` | `true` | Mount a memory-backed `emptyDir` at `/dev/shm` in singleuser pods. |
| `singleuser.sharedMemory.sizeLimit` | `8Gi` | Maximum tmpfs consumption; used pages count against the writing container's memory limit. |
| `singleuser.networkPolicy.allowEgressToGateway` | `true` | Renders a NetworkPolicy letting user pods reach the Envoy Gateway pod. |
| `singleuser.networkPolicy.gatewayNamespace` | `envoy-gateway-system` | Where the gateway runs. |
| `singleuser.networkPolicy.gatewayName` | `nebari-gateway` | Gateway name, matched on `gateway.envoyproxy.io/owning-gateway-name`. |
Expand All @@ -102,6 +104,10 @@ proxy pod IP *before* the subchart's pod-level policy is evaluated — without i
cannot reach `https://<hub>/services/japps` or the Nebi host. Kubernetes unions egress rules
across policies selecting the same pod, so it is harmless where it is not needed.

Profiles can set their own shared-memory size with `kubespawner_override.shm_size_limit`.
See [Shared memory](/server-profiles/#shared-memory) for how the size counts against
memory limits and how it works with profile volume overrides.

## `singleuserCuller`

In-pod idle culling, separate from the hub-level `jupyterhub.cull`. This one fires even when
Expand Down
7 changes: 7 additions & 0 deletions templates/hub-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ data:
# syntax error that CrashLoops the hub), not as "". A deployer's
# explicit 0 already means "disabled", so nothing real is swallowed.
"shutdown-no-activity-timeout": {{ .Values.singleuserCuller.server.shutdownNoActivityTimeout | default 0 | quote }},
# Shared-memory defaults are chart-level values because the spawner
# owns the volume list. Profile-specific size overrides are translated
# in 01-spawner.py before KubeSpawner applies them. `default ""` is the
# same nil-safety as above; when enabled, the spawner warns about an
# empty size and uses 8Gi.
"shared-memory-enabled": {{ ternary "True" "False" .Values.singleuser.sharedMemory.enabled }},
"shared-memory-size-limit": {{ .Values.singleuser.sharedMemory.sizeLimit | default "" | quote }},
}


Expand Down
65 changes: 65 additions & 0 deletions tests/e2e/test_shared_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Live singleuser shared-memory verification."""

import json

from _process import kctl_out

EIGHT_GIBIBYTES = 8 * 1024**3
SHARED_MEMORY_PROBE_BYTES = 128 * 1024**2
SHARED_MEMORY_PROBE = f"""
from multiprocessing import shared_memory

size = {SHARED_MEMORY_PROBE_BYTES}
chunk = b"\\x01" * (1024**2)
segment = shared_memory.SharedMemory(create=True, size=size)
try:
for offset in range(0, size, len(chunk)):
segment.buf[offset : offset + len(chunk)] = chunk
print(len(segment.buf))
finally:
segment.close()
segment.unlink()
""".strip()


def _get_pod(user):
returncode, pod_json, error = kctl_out("get", "pod", user.pod, "-o", "json")
assert returncode == 0, error
return json.loads(pod_json)


def _shared_memory_capacity(user):
returncode, output = user.exec(
"python",
"-c",
"import os; s = os.statvfs('/dev/shm'); print(s.f_frsize * s.f_blocks)",
)
assert returncode == 0, output
return int(output)


def _write_shared_memory_above_runtime_default(user):
returncode, output = user.exec("python", "-c", SHARED_MEMORY_PROBE)
assert returncode == 0, output
assert output.splitlines()[-1] == str(SHARED_MEMORY_PROBE_BYTES)


def test_singleuser_has_memory_backed_shared_memory(spawn_user):
user = spawn_user("alice-data")
pod = _get_pod(user)

dshm = next(volume for volume in pod["spec"]["volumes"] if volume["name"] == "dshm")
assert dshm["emptyDir"] == {"medium": "Memory", "sizeLimit": "8Gi"}

notebook = next(
container
for container in pod["spec"]["containers"]
if container["name"] == "notebook"
)
mount = next(item for item in notebook["volumeMounts"] if item["name"] == "dshm")
assert mount["mountPath"] == "/dev/shm"

# Kubelet may cap tmpfs below sizeLimit based on node or pod memory.
capacity = _shared_memory_capacity(user)
assert SHARED_MEMORY_PROBE_BYTES <= capacity <= EIGHT_GIBIBYTES
_write_shared_memory_above_runtime_default(user)
7 changes: 7 additions & 0 deletions tests/unit/test_chart_derived.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,10 @@ def test_shutdown_no_activity_timeout_reaches_spawner(rendered_chart_derived):
string; the spawner int-parses it)."""
ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={})
assert ns["get_chart_config"]("shutdown-no-activity-timeout") == "900"


def test_shared_memory_defaults_are_available_to_spawner(rendered_chart_derived):
ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={})

assert ns["get_chart_config"]("shared-memory-enabled") is True
assert ns["get_chart_config"]("shared-memory-size-limit") == "8Gi"
Loading