Skip to content
Merged
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
24 changes: 22 additions & 2 deletions mkdocs/docs/concepts/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -1276,7 +1276,7 @@ projects:
memory: 2Gi
```

Each SSH session through the jump pod takes about 2 MiB of memory. Each `dstack` server replica keeps at least one session open per running job, and each `dstack attach` adds one more. If the jump pod exceeds its memory limit, Kubernetes restarts it.
With the default image, each SSH session through the jump pod takes about 2 MiB of memory. Each `dstack` server replica keeps at least one session open per running job, and each `dstack attach` adds one more. If the jump pod exceeds its memory limit, Kubernetes restarts it.

When the jump pod restarts or is recreated, its SSH sessions drop. The `dstack` server reconnects automatically, but `dstack attach` may fail for runs submitted before that. If reliable SSH access to runs is important, deploy [`dstack-sshproxy`](../guides/server-deployment.md#ssh-proxy).

Expand All @@ -1296,13 +1296,33 @@ projects:

Each `tolerations` item is `key[=value][:effect]`, the `kubectl taint` format, so a taint added with `kubectl taint` can be copied as is. Without `=value`, any value is tolerated; without `:effect`, any effect. If `tolerations` isn't set, `dstack` tolerates the GPU node taints when every node is tainted, but not if `node_selector` is set.

!!! warning "Changing `cpu`, `memory`, `node_selector`, and `tolerations`"
By default, the jump pod runs `testcontainers/sshd`. To run your own image instead, e.g., one built on your organization's base image, scanned by your registry, or with your SSH policy, set `proxy_jump.image`:

```yaml
contexts:
- name: gpu-cluster-a
proxy_jump:
image: registry.example.com/sshd:1.0@sha256:...
```

`dstack` runs the jump pod's container as root, writes root's authorized keys, regenerates the host keys with `ssh-keygen -A`, and starts `sshd` with `PermitRootLogin`, `PasswordAuthentication`, and `AllowTcpForwarding` overridden. The server then connects as root and runs a shell script that adds users' keys. Other `sshd_config` settings, e.g., ciphers and MACs, apply as set in the image. The image must provide:

- a `root` user with a POSIX login shell, e.g., `sh` or `bash`
- OpenSSH `sshd` at `/usr/sbin/sshd`
- `/bin/sh`, `ssh-keygen`, `mkdir`, `chmod`, `rm`, `touch`, `tail`, and `grep`

`dstack` doesn't pass registry credentials for the jump pod's image, so a private image can be pulled only if the nodes have credentials for the registry or the namespace's `default` service account has `imagePullSecrets`.

!!! warning "Changing `image`, `cpu`, `memory`, `node_selector`, and `tolerations`"
New values don't apply to an existing jump pod. To apply them, update the jump pod's ReplicaSet in the context's namespace and delete the pod so that Kubernetes recreates it:

```shell
# cpu and memory
kubectl -n <namespace> set resources replicaset dstack-<project>-ssh-jump-pod \
--requests=cpu=1,memory=2Gi --limits=cpu=1,memory=2Gi
# image
kubectl -n <namespace> set image replicaset dstack-<project>-ssh-jump-pod \
dstack-<project>-ssh-jump-pod-container=registry.example.com/sshd:1.0@sha256:...
# node_selector and tolerations: edit spec.template.spec.affinity and .tolerations
kubectl -n <namespace> edit replicaset dstack-<project>-ssh-jump-pod
# Recreate the pod
Expand Down
23 changes: 17 additions & 6 deletions src/dstack/_internal/core/backends/kubernetes/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from dstack._internal.core.backends.kubernetes.features import resource_groups
from dstack._internal.core.backends.kubernetes.models import (
JUMP_POD_DEFAULT_CPU,
JUMP_POD_DEFAULT_IMAGE,
JUMP_POD_DEFAULT_MEMORY,
KubernetesConfig,
)
Expand Down Expand Up @@ -137,7 +138,6 @@

logger = get_logger(__name__)

JUMP_POD_IMAGE = "testcontainers/sshd:1.3.0@sha256:c50c0f59554dcdb2d9e5e705112144428ae9d04ac0af6322b365a18e24213a6a"
JUMP_POD_SSH_PORT = 22
JUMP_POD_USER = "root"
# Under disk pressure, the kubelet first evicts pods whose disk usage exceeds their
Expand Down Expand Up @@ -271,6 +271,7 @@ def run_job(
jump_pod_service_name=jump_pod_service_name,
jump_pod_port=cluster.proxy_jump.port,
authorized_keys=project_authorized_keys,
image=cluster.proxy_jump.image or JUMP_POD_DEFAULT_IMAGE,
cpu_request_limit=cluster.proxy_jump.cpu or JUMP_POD_DEFAULT_CPU,
memory_request_limit=cluster.proxy_jump.memory or JUMP_POD_DEFAULT_MEMORY,
node_selector=cluster.proxy_jump.node_selector,
Expand Down Expand Up @@ -949,6 +950,7 @@ def _create_jump_pod_service_if_not_exists(
jump_pod_service_name: str,
jump_pod_port: Optional[int],
authorized_keys: list[str],
image: str,
cpu_request_limit: str,
memory_request_limit: str,
node_selector: Optional[list[str]],
Expand Down Expand Up @@ -1064,7 +1066,7 @@ def _create_jump_pod_service_if_not_exists(
containers=[
client.V1Container(
name=f"{jump_pod_name}-container",
image=JUMP_POD_IMAGE,
image=image,
command=["/bin/sh"],
args=["-c", " && ".join(commands)],
ports=[
Expand All @@ -1076,6 +1078,11 @@ def _create_jump_pod_service_if_not_exists(
requests=requests,
limits=limits,
),
# sshd must run as root, whatever the image's USER is
security_context=client.V1SecurityContext(
run_as_user=0,
run_as_group=0,
),
)
],
restart_policy=RestartPolicy.ALWAYS,
Expand Down Expand Up @@ -1327,17 +1334,21 @@ def _get_jump_pod_tolerations_from_node_taints(
def _get_jump_pod_commands(authorized_keys: list[str]) -> list[str]:
authorized_keys_content = "\n".join(authorized_keys)
commands = [
"mkdir -p ~/.ssh",
"chmod 700 ~/.ssh",
f"echo {shlex.quote(authorized_keys_content)} > ~/.ssh/authorized_keys",
"chmod 600 ~/.ssh/authorized_keys",
# Not ~, which follows HOME, and the image may set HOME for its own user. sshd looks up
# authorized_keys in root's home directory from the user database, as ~root does
"mkdir -p ~root/.ssh",
"chmod 700 ~root/.ssh",
f"echo {shlex.quote(authorized_keys_content)} > ~root/.ssh/authorized_keys",
"chmod 600 ~root/.ssh/authorized_keys",
# regenerate host keys
"rm -rf /etc/ssh/ssh_host_*",
"ssh-keygen -A > /dev/null",
# start sshd
(
f"/usr/sbin/sshd -D -e -p {JUMP_POD_SSH_PORT}"
" -o LogLevel=ERROR"
# The image's sshd_config may forbid root login, and clients log in as root
" -o PermitRootLogin=prohibit-password"
" -o PasswordAuthentication=no"
" -o AllowTcpForwarding=local"
),
Expand Down
14 changes: 11 additions & 3 deletions src/dstack/_internal/core/backends/kubernetes/configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@
from dstack._internal.core.errors import ServerClientError
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.common import validate_extra_ignore, validate_json_extra_ignore
from dstack._internal.utils.docker import validate_image_name
from dstack._internal.utils.logging import get_logger

logger = get_logger(__name__)

# Sanity floors that catch unit mistakes, e.g., `memory: 512` (bytes). Measured with the jump pod
# image: below 100m, SSH handshakes through the jump pod slow down sharply (~0.5s at 50m, ~2s at
# 10m); 32Mi fits the container (~9Mi) and a few sessions (~1.6Mi each).
# Sanity floors that catch unit mistakes, e.g., `memory: 512` (bytes). Measured with the default
# jump pod image: below 100m, SSH handshakes through the jump pod slow down sharply (~0.5s at 50m,
# ~2s at 10m); 32Mi fits the container (~9Mi) and a few sessions (~1.6Mi each).
_JUMP_POD_MIN_CPU = "100m"
_JUMP_POD_MIN_MEMORY = "32Mi"

Expand Down Expand Up @@ -118,6 +119,13 @@ def _check_proxy_jump(
self, proxy_jump: KubernetesProxyJumpConfig, *, context_name: Optional[str] = None
):
in_context = f" in context {context_name!r}" if context_name is not None else ""
if proxy_jump.image is not None:
try:
validate_image_name(proxy_jump.image)
except ValueError as e:
raise ServerClientError(
f"invalid proxy_jump.image value {proxy_jump.image!r}{in_context}: {e}"
)
for field, quantity, min_quantity in [
("cpu", proxy_jump.cpu, _JUMP_POD_MIN_CPU),
("memory", proxy_jump.memory, _JUMP_POD_MIN_MEMORY),
Expand Down
17 changes: 14 additions & 3 deletions src/dstack/_internal/core/backends/kubernetes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
from dstack._internal.core.backends.base.models import fill_data
from dstack._internal.core.models.common import CoreModel

# Measured with the jump pod image (OpenSSH 9.9). The container takes ~9 MiB plus ~1.6 MiB per
# tunneled SSH session (two sshd-session processes), so 1Gi fits ~600 sessions. Each running job
# holds one or more sessions per server replica. At 500m, it tunnels ~130-180 MiB/s.
JUMP_POD_DEFAULT_IMAGE = "testcontainers/sshd:1.3.0@sha256:c50c0f59554dcdb2d9e5e705112144428ae9d04ac0af6322b365a18e24213a6a"

# Measured with the default jump pod image (OpenSSH 9.9). The container takes ~9 MiB plus ~1.6 MiB
# per tunneled SSH session (two sshd-session processes), so 1Gi fits ~600 sessions. Each running
# job holds one or more sessions per server replica. At 500m, it tunnels ~130-180 MiB/s.
JUMP_POD_DEFAULT_CPU = "500m"
JUMP_POD_DEFAULT_MEMORY = "1Gi"

Expand All @@ -19,6 +21,15 @@ class KubernetesProxyJumpConfig(CoreModel):
port: Annotated[
Optional[int], Field(description="Any port accessible outside of the cluster")
] = None
image: Annotated[
Optional[str],
Field(
description=(
"The jump pod's image, with OpenSSH `sshd`."
f" Defaults to `{JUMP_POD_DEFAULT_IMAGE}`"
)
),
] = None
cpu: Annotated[
Optional[str],
Field(
Expand Down
2 changes: 2 additions & 0 deletions src/dstack/_internal/core/compatibility/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def _get_kubernetes_proxy_jump_excludes(
) -> IncludeExcludeStrDictType:
# A field is excluded only if it's unset in all `proxy_jumps`
excludes: IncludeExcludeStrDictType = {}
if all(proxy_jump.image is None for proxy_jump in proxy_jumps):
excludes["image"] = True
if all(proxy_jump.cpu is None for proxy_jump in proxy_jumps):
excludes["cpu"] = True
if all(proxy_jump.memory is None for proxy_jump in proxy_jumps):
Expand Down
45 changes: 45 additions & 0 deletions src/dstack/_internal/utils/docker.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
from dataclasses import dataclass
from typing import Optional

Expand Down Expand Up @@ -41,5 +42,49 @@ def is_default_registry(registry: str) -> bool:
return registry in [DEFAULT_REGISTRY, LEGACY_DEFAULT_REGISTRY]


def validate_image_name(image: str) -> None:
"""
Validates an image reference, e.g., `ubuntu`, `ghcr.io/org/repo:tag`, `repo@sha256:...`,
as the kubelet and container runtimes parse it.

Raises:
ValueError: The reference is invalid.
"""
match = _REFERENCE_REGEX.fullmatch(image)
if match is None:
raise ValueError("Invalid reference format")
digest = match.group("digest")
if digest is None:
return
algorithm, encoded = digest.split(":", maxsplit=1)
length = _DIGEST_ENCODED_LENGTHS.get(algorithm)
if length is None:
raise ValueError(f"Unsupported digest algorithm: {algorithm}")
if re.fullmatch(rf"[a-f0-9]{{{length}}}", encoded) is None:
raise ValueError(f"Invalid {algorithm} digest: must be {length} lowercase hex digits")


# The reference grammar of
# https://github.com/distribution/reference/blob/v0.6.0/regexp.go
_ALPHANUMERIC = r"[a-z0-9]+"
_SEPARATOR = r"(?:[._]|__|[-]+)"
_PATH_COMPONENT = rf"{_ALPHANUMERIC}(?:{_SEPARATOR}{_ALPHANUMERIC})*"
_DOMAIN_NAME_COMPONENT = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])"
_DOMAIN_NAME = rf"{_DOMAIN_NAME_COMPONENT}(?:\.{_DOMAIN_NAME_COMPONENT})*"
_IPV6_ADDRESS = r"\[(?:[a-fA-F0-9:]+)\]"
_DOMAIN_AND_PORT = rf"(?:{_DOMAIN_NAME}|{_IPV6_ADDRESS})(?::[0-9]+)?"
_REMOTE_NAME = rf"{_PATH_COMPONENT}(?:/{_PATH_COMPONENT})*"
_NAME = rf"(?:{_DOMAIN_AND_PORT}/)?{_REMOTE_NAME}"
_TAG = r"[\w][\w.-]{0,127}"
_DIGEST = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}"
_REFERENCE_REGEX = re.compile(
rf"{_NAME}(?::{_TAG})?(?:@(?P<digest>{_DIGEST}))?",
# \w is ASCII-only in Go
re.ASCII,
)
# The algorithms that https://github.com/opencontainers/go-digest supports
_DIGEST_ENCODED_LENGTHS = {"sha256": 64, "sha384": 96, "sha512": 128}


def _is_host(s: str) -> bool:
return s == "localhost" or ":" in s or "." in s
31 changes: 28 additions & 3 deletions src/tests/_internal/core/backends/kubernetes/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
_get_pod_spec_parameters_for_gpu,
_KubernetesSkipOfferCache,
)
from dstack._internal.core.backends.kubernetes.models import KubeconfigConfig, KubernetesConfig
from dstack._internal.core.backends.kubernetes.models import (
JUMP_POD_DEFAULT_IMAGE,
KubeconfigConfig,
KubernetesConfig,
)
from dstack._internal.core.backends.kubernetes.resources import (
KubernetesOfferBackendData,
build_base_labels,
Expand Down Expand Up @@ -231,6 +235,7 @@ def call(
api: Mock,
apps_api: Mock,
jump_pod_port: Optional[int] = None,
image: str = JUMP_POD_DEFAULT_IMAGE,
cpu: str = "500m",
memory: str = "1Gi",
node_selector: Optional[list[str]] = None,
Expand All @@ -245,6 +250,7 @@ def call(
jump_pod_service_name=JUMP_POD_SERVICE_NAME,
jump_pod_port=jump_pod_port,
authorized_keys=["ssh-ed25519 AAAA project"],
image=image,
cpu_request_limit=cpu,
memory_request_limit=memory,
node_selector=node_selector,
Expand All @@ -257,15 +263,25 @@ def get_pod_spec(self, apps_api: Mock) -> client.V1PodSpec:
return replica_set.spec.template.spec

def assert_replica_set_created(
self, apps_api: Mock, *, cpu: str = "500m", memory: str = "1Gi"
self,
apps_api: Mock,
*,
image: str = JUMP_POD_DEFAULT_IMAGE,
cpu: str = "500m",
memory: str = "1Gi",
) -> None:
apps_api.create_namespaced_replica_set.assert_called_once()
replica_set = apps_api.create_namespaced_replica_set.call_args.kwargs["body"]
assert replica_set.metadata.name == JUMP_POD_NAME
assert replica_set.spec.replicas == 1
assert replica_set.spec.selector.match_labels == JUMP_POD_SELECTOR
assert replica_set.spec.template.metadata.labels == JUMP_POD_LABELS
resources = replica_set.spec.template.spec.containers[0].resources
container = replica_set.spec.template.spec.containers[0]
assert container.image == image
# Root regardless of the image's USER
assert container.security_context.run_as_user == 0
assert container.security_context.run_as_group == 0
resources = container.resources
# Equal CPU and memory requests and limits for the Guaranteed QoS class, and
# an ephemeral-storage request without a limit
assert resources.limits == {"cpu": cpu, "memory": memory}
Expand Down Expand Up @@ -303,6 +319,15 @@ def test_creates_replica_set_and_service_if_not_found(self):
self.assert_replica_set_created(apps_api)
self.assert_service_created(api, selector=JUMP_POD_SELECTOR, node_port=None)

def test_sets_jump_pod_image(self):
api, apps_api = self.make_apis()

image = "registry.example.com/sshd:1@sha256:" + "0" * 64

self.call(api, apps_api, image=image)

self.assert_replica_set_created(apps_api, image=image)

def test_sets_jump_pod_resources(self):
api, apps_api = self.make_apis()

Expand Down
68 changes: 68 additions & 0 deletions src/tests/_internal/core/backends/kubernetes/test_configurator.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,74 @@ def test_validate_config_invalid_context_proxy_jump_resources(self):
):
KubernetesConfigurator().validate_config(config, default_creds_enabled=True)

@pytest.mark.usefixtures("get_clusters_mock")
def test_validate_config_valid_proxy_jump_image(self):
config = KubernetesBackendConfigWithCreds(
kubeconfig=KubeconfigConfig(data="mocked", filename="-"),
contexts=[
KubernetesContextConfig(
name="ctx",
proxy_jump=KubernetesProxyJumpConfig(
image="registry.example.com:5000/sshd:1.0@sha256:" + "0" * 64
),
),
],
)
KubernetesConfigurator().validate_config(config, default_creds_enabled=True)

@pytest.mark.usefixtures("get_clusters_mock")
@pytest.mark.parametrize(
["proxy_jump", "expected_error"],
[
pytest.param(
KubernetesProxyJumpConfig(image=""),
"invalid proxy_jump.image value '': Invalid reference format",
id="empty",
),
pytest.param(
KubernetesProxyJumpConfig(image="registry.example.com/SSHD:1.0"),
"invalid proxy_jump.image value 'registry.example.com/SSHD:1.0':"
" Invalid reference format",
id="uppercase-repository",
),
pytest.param(
KubernetesProxyJumpConfig(image="sshd@sha256:" + "0" * 63),
f"invalid proxy_jump.image value 'sshd@sha256:{'0' * 63}':"
" Invalid sha256 digest: must be 64 lowercase hex digits",
id="short-digest",
),
],
)
def test_validate_config_invalid_proxy_jump_image(
self, proxy_jump: KubernetesProxyJumpConfig, expected_error: str
):
config = KubernetesBackendConfigWithCreds(
kubeconfig=KubeconfigConfig(data="mocked", filename="-"),
proxy_jump=proxy_jump,
namespace="ns",
)
with pytest.raises(ServerClientError, match=re.escape(expected_error)):
KubernetesConfigurator().validate_config(config, default_creds_enabled=True)

@pytest.mark.usefixtures("get_clusters_mock")
def test_validate_config_invalid_context_proxy_jump_image(self):
config = KubernetesBackendConfigWithCreds(
kubeconfig=KubeconfigConfig(data="mocked", filename="-"),
contexts=[
KubernetesContextConfig(
name="ctx",
proxy_jump=KubernetesProxyJumpConfig(image=" sshd"),
),
],
)
with pytest.raises(
ServerClientError,
match=re.escape(
"invalid proxy_jump.image value ' sshd' in context 'ctx': Invalid reference format"
),
):
KubernetesConfigurator().validate_config(config, default_creds_enabled=True)

@pytest.mark.usefixtures("get_clusters_mock")
def test_validate_config_valid_proxy_jump_placement(self):
config = KubernetesBackendConfigWithCreds(
Expand Down
Loading
Loading