diff --git a/mkdocs/docs/concepts/volumes.md b/mkdocs/docs/concepts/volumes.md index 0eea02cc3..e71e104aa 100644 --- a/mkdocs/docs/concepts/volumes.md +++ b/mkdocs/docs/concepts/volumes.md @@ -42,6 +42,24 @@ size: 100GB If you use this configuration, `dstack` will create a new volume based on the specified options. +??? info "Runpod" + Runpod volumes are regional by default. For global volumes, set `global: true` + and omit `size` and `region`. + + ```yaml + type: volume + backend: runpod + name: my-volume + global: true + ``` + + Each run can mount one volume. Global volumes require Secure Cloud and do not support Instant Clusters. + See Runpod's [storage limitations](https://docs.runpod.io/storage/globalvolume/overview#limitations). + + > Global volume charges are not included in the costs shown by `dstack`. + + > Do not configure `auto_cleanup_duration` for regional or global Runpod volumes: it may request deletion while a run is still using the volume ([#3789](https://github.com/dstackai/dstack/issues/3789)). + ??? info "Daytona" Daytona volumes use [S3-backed FUSE storage](https://www.daytona.io/docs/en/volumes/). Storage grows with usage, and the same volume can be mounted in any Daytona region. diff --git a/mkdocs/docs/reference/dstack.yml/volume.md b/mkdocs/docs/reference/dstack.yml/volume.md index 717209571..91ac31d77 100644 --- a/mkdocs/docs/reference/dstack.yml/volume.md +++ b/mkdocs/docs/reference/dstack.yml/volume.md @@ -20,11 +20,31 @@ The `volume` configuration type allows creating, registering, and updating [volu === "Runpod" - #SCHEMA# dstack._internal.core.models.volumes.RunpodVolumeConfiguration - overrides: - show_root_heading: false - backend: - required: true + === "Regional (default)" + + #SCHEMA# dstack._internal.core.models.volumes.RunpodVolumeConfiguration + overrides: + show_root_heading: false + backend: + required: true + global_: + name: global + type: bool + + === "Global" + + Set `global: true` and omit `region` and `size`. + See [usage and limitations](../../concepts/volumes.md#network-volumes). + + #SCHEMA# dstack._internal.core.models.volumes.RunpodGlobalVolumeConfiguration + overrides: + show_root_heading: false + backend: + required: true + global_: + name: global + type: bool + required: true === "Daytona" diff --git a/src/dstack/_internal/core/backends/runpod/api_client.py b/src/dstack/_internal/core/backends/runpod/api_client.py index bc4ac2ffe..992f2e4c8 100644 --- a/src/dstack/_internal/core/backends/runpod/api_client.py +++ b/src/dstack/_internal/core/backends/runpod/api_client.py @@ -45,7 +45,7 @@ class V2Pod(TypedDict): name: str status: Literal["PROVISIONING", "STARTING", "RUNNING", "EXITED", "ERROR", "TERMINATED"] runtime: Optional["V2PodRuntime"] - mounts: "V2Mounts" + mounts: "V2PodMounts" cluster: NotRequired["V2PodCluster"] createdAt: str dataCenterId: Optional[str] @@ -87,6 +87,21 @@ class V2NetworkMount(TypedDict): path: str +class V2GlobalMount(TypedDict): + volumeId: str + path: str + + +# `global` is a Python keyword, so this TypedDict uses the functional syntax. +V2PodMounts = TypedDict( + "V2PodMounts", + { + "network": NotRequired[list[V2NetworkMount]], + "global": NotRequired[list[V2GlobalMount]], + }, +) + + class V2CreatePodRequest(TypedDict): """ Request body for creating a pod. Exactly one of `gpu` or `cpu` must be set. @@ -105,7 +120,7 @@ class V2CreatePodRequest(TypedDict): the same container settings you could otherwise spread into this body.""" disk: NotRequired[int] """Container disk in GB (ephemeral, wiped on restart)""" - mounts: NotRequired["V2Mounts"] + mounts: NotRequired[V2PodMounts] image: NotRequired[str] """`image` is required unless `templateId` is set""" registry: NotRequired[Optional[str]] @@ -228,6 +243,17 @@ class V2CreateNetworkVolumeRequest(TypedDict): storage tier.""" +class V2GlobalVolume(TypedDict): + id: str + name: str + createdAt: str + createdByUserId: Optional[str] + + +class V2CreateGlobalVolumeRequest(TypedDict): + name: str + + class RunpodGraphqlClientError(BackendError): errors: List[Dict] @@ -284,6 +310,8 @@ def create_pod( container_disk_in_gb: int, network_volume_id: Optional[str] = None, volume_mount_path: Optional[str] = None, + global_volume_id: Optional[str] = None, + global_volume_mount_path: Optional[str] = None, image_name: str, container_registry_credentials_id: Optional[str] = None, entrypoint: list[str], @@ -326,8 +354,17 @@ def create_pod( } body["cpu"] = cpu_config - mounts = _build_v2_mounts(network_volume_id, volume_mount_path) - if mounts is not None: + mounts: V2PodMounts = {} + network_mounts = _build_v2_mounts(network_volume_id, volume_mount_path) + if network_mounts is not None and "network" in network_mounts: + mounts["network"] = network_mounts["network"] + if global_volume_id is not None: + if global_volume_mount_path is None: + raise ValueError("global_volume_mount_path must be set if global_volume_id is set") + mounts["global"] = [{"volumeId": global_volume_id, "path": global_volume_mount_path}] + elif global_volume_mount_path is not None: + raise ValueError("global_volume_mount_path requires global_volume_id") + if mounts: body["mounts"] = mounts if data_center_ids is not None: @@ -476,6 +513,29 @@ def delete_network_volume(self, volume_id: str) -> bool: raise return True + def get_global_volume(self, volume_id: str) -> Optional[V2GlobalVolume]: + try: + response = self._make_v2_request("GET", "global-volumes", volume_id) + except RunpodV2ClientError as e: + if e.status == HTTPStatus.NOT_FOUND: + return None + raise + return response.json() + + def create_global_volume(self, *, name: str) -> V2GlobalVolume: + body: V2CreateGlobalVolumeRequest = {"name": name} + response = self._make_v2_request("POST", "global-volumes", json=body) + return response.json() + + def delete_global_volume(self, volume_id: str) -> bool: + try: + self._make_v2_request("DELETE", "global-volumes", volume_id) + except RunpodV2ClientError as e: + if e.status == HTTPStatus.NOT_FOUND: + return False + raise + return True + def create_cluster( self, *, diff --git a/src/dstack/_internal/core/backends/runpod/compute.py b/src/dstack/_internal/core/backends/runpod/compute.py index fc9a9dff2..7a6139ff9 100644 --- a/src/dstack/_internal/core/backends/runpod/compute.py +++ b/src/dstack/_internal/core/backends/runpod/compute.py @@ -24,7 +24,7 @@ from dstack._internal.core.backends.runpod.api_client import RunpodApiClient, V2Pod from dstack._internal.core.backends.runpod.models import RunpodConfig from dstack._internal.core.consts import DSTACK_RUNNER_SSH_PORT -from dstack._internal.core.errors import BackendError, ComputeError +from dstack._internal.core.errors import BackendError, ComputeError, SkipOffer from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import ( ListedResourceGroup, @@ -42,6 +42,7 @@ from dstack._internal.core.models.resources import Memory, Range from dstack._internal.core.models.runs import Job, JobProvisioningData, Requirements, Run from dstack._internal.core.models.volumes import ( + RunpodGlobalVolumeConfiguration, RunpodVolumeConfiguration, Volume, VolumeProvisioningData, @@ -152,11 +153,19 @@ def run_job( network_volume_id = None volume_mount_path = None + global_volume_id = None + global_volume_mount_path = None if len(volumes) > 1: - raise ComputeError("Mounting more than one network volume is not supported in runpod") + raise ComputeError("Mounting more than one volume is not supported in runpod") if len(volumes) == 1: - network_volume_id = volumes[0].volume_id - volume_mount_path = run.run_spec.configuration.volumes[0].path + if isinstance(volumes[0].configuration, RunpodGlobalVolumeConfiguration): + if not _is_secure_cloud(instance_offer.region): + raise SkipOffer("Runpod global volumes require Secure Cloud") + global_volume_id = get_or_error(volumes[0].volume_id) + global_volume_mount_path = run.run_spec.configuration.volumes[0].path + else: + network_volume_id = volumes[0].volume_id + volume_mount_path = run.run_spec.configuration.volumes[0].path if instance_offer.instance.resources.spot: raise ComputeError("Runpod spot offers are not supported") @@ -207,6 +216,8 @@ def run_job( container_disk_in_gb=offer_disk_gib, network_volume_id=network_volume_id, volume_mount_path=volume_mount_path, + global_volume_id=global_volume_id, + global_volume_mount_path=global_volume_mount_path, image_name=job.job_spec.image_name, container_registry_credentials_id=container_registry_credentials_id, entrypoint=["/bin/sh"], @@ -285,6 +296,12 @@ def run_jobs( requirements: Requirements, extra_authorized_keys: list[str], ) -> ComputeGroupProvisioningData: + if any( + isinstance(volume.configuration, RunpodGlobalVolumeConfiguration) + for job_configuration in job_configurations + for volume in job_configuration.volumes + ): + raise SkipOffer("Runpod global volumes are not supported with Instant Clusters") master_job_configuration = job_configurations[0] master_job = master_job_configuration.job if master_job.job_spec.registry_auth is not None: @@ -445,6 +462,18 @@ def delete_resource_group(self, group: ListedResourceGroup) -> None: self.api_client.terminate_pod(group.primary_id) def register_volume(self, volume: Volume) -> VolumeProvisioningData: + if isinstance(volume.configuration, RunpodGlobalVolumeConfiguration): + volume_id = get_or_error(volume.configuration.volume_id) + global_volume = self.api_client.get_global_volume(volume_id) + if global_volume is None: + raise ComputeError(f"Volume {volume_id} not found") + return VolumeProvisioningData( + backend=BackendType.RUNPOD, + volume_id=global_volume["id"], + size_gb=None, + attachable=False, + detachable=False, + ) assert isinstance(volume.configuration, RunpodVolumeConfiguration) volume_id = get_or_error(volume.configuration.volume_id) network_volume = self.api_client.get_network_volume(volume_id) @@ -461,8 +490,17 @@ def register_volume(self, volume: Volume) -> VolumeProvisioningData: ) def create_volume(self, volume: Volume) -> VolumeProvisioningData: - assert isinstance(volume.configuration, RunpodVolumeConfiguration) volume_name = generate_unique_volume_name(volume, max_length=MAX_RESOURCE_NAME_LEN) + if isinstance(volume.configuration, RunpodGlobalVolumeConfiguration): + global_volume = self.api_client.create_global_volume(name=volume_name) + return VolumeProvisioningData( + backend=BackendType.RUNPOD, + volume_id=global_volume["id"], + size_gb=None, + attachable=False, + detachable=False, + ) + assert isinstance(volume.configuration, RunpodVolumeConfiguration) size_gb = volume.configuration.size_gb # Runpod regions must be uppercase. # Lowercase regions are accepted in the API but they break Runpod in several ways. @@ -484,7 +522,10 @@ def create_volume(self, volume: Volume) -> VolumeProvisioningData: def delete_volume(self, volume: Volume): if volume.volume_id is None: return - deleted = self.api_client.delete_network_volume(volume.volume_id) + if isinstance(volume.configuration, RunpodGlobalVolumeConfiguration): + deleted = self.api_client.delete_global_volume(volume.volume_id) + else: + deleted = self.api_client.delete_network_volume(volume.volume_id) if not deleted: logger.debug("The volume %s not found. Skipping deletion.", volume.volume_id) diff --git a/src/dstack/_internal/core/compatibility/volumes.py b/src/dstack/_internal/core/compatibility/volumes.py index 1f5e1e3ab..9537edb7c 100644 --- a/src/dstack/_internal/core/compatibility/volumes.py +++ b/src/dstack/_internal/core/compatibility/volumes.py @@ -1,6 +1,7 @@ from dstack._internal.core.models.common import IncludeExcludeStrDictType from dstack._internal.core.models.volumes import ( AnyVolumeConfiguration, + RunpodVolumeConfiguration, VolumeSpec, ) @@ -31,4 +32,6 @@ def _get_volume_configuration_excludes( configuration: AnyVolumeConfiguration, ) -> IncludeExcludeStrDictType: configuration_excludes: IncludeExcludeStrDictType = {} + if isinstance(configuration, RunpodVolumeConfiguration): + configuration_excludes["global_"] = True return configuration_excludes diff --git a/src/dstack/_internal/core/models/volumes.py b/src/dstack/_internal/core/models/volumes.py index 41ed12fee..a3da0e689 100644 --- a/src/dstack/_internal/core/models/volumes.py +++ b/src/dstack/_internal/core/models/volumes.py @@ -4,7 +4,8 @@ from pathlib import PurePosixPath from typing import Annotated, Any, Dict, List, Literal, Optional, Self, Tuple, Union -from pydantic import Field, RootModel, ValidationError, field_validator +from pydantic import ConfigDict, Field, RootModel, ValidationError, field_validator +from typing_extensions import TypeAliasType from dstack._internal.core.errors import ConfigurationError from dstack._internal.core.models.backends.base import BackendType @@ -132,13 +133,37 @@ class GCPVolumeConfiguration( class RunpodVolumeConfiguration( VolumeConfigurationWithRegion, VolumeConfigurationWithVolumeID, VolumeConfigurationWithSize ): + model_config = ConfigDict(serialize_by_alias=True) + backend: Annotated[Literal[BackendType.RUNPOD], Field(description="The volume backend")] = ( BackendType.RUNPOD ) + global_: Annotated[ + Literal[False], Field(alias="global", description="Use a Runpod global volume") + ] = False availability_zone: Annotated[Optional[str], Field(exclude=True)] = None """Runpod doesn't have AZs but we accept this field for compatibility with older clients.""" +class RunpodGlobalVolumeConfiguration(VolumeConfigurationWithVolumeID): + model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True) + + backend: Annotated[Literal[BackendType.RUNPOD], Field(description="The volume backend")] = ( + BackendType.RUNPOD + ) + global_: Annotated[ + Literal[True], Field(alias="global", description="Use a Runpod global volume") + ] + + +# A named alias gives the nested union a schema reference, as required by OpenAPI's +# backend discriminator mapping. +AnyRunpodVolumeConfiguration = TypeAliasType( + "AnyRunpodVolumeConfiguration", + Union[RunpodVolumeConfiguration, RunpodGlobalVolumeConfiguration], +) + + class KubernetesVolumeConfiguration(VolumeConfigurationWithRegion, VolumeConfigurationWithSize): backend: Annotated[ Literal[BackendType.KUBERNETES], Field(description="The volume backend") @@ -196,7 +221,7 @@ class LiumVolumeConfiguration(VolumeConfigurationWithVolumeID): AnyVolumeConfiguration = Union[ AWSVolumeConfiguration, GCPVolumeConfiguration, - RunpodVolumeConfiguration, + AnyRunpodVolumeConfiguration, KubernetesVolumeConfiguration, DaytonaVolumeConfiguration, LiumVolumeConfiguration, diff --git a/src/dstack/_internal/server/compatibility/volumes.py b/src/dstack/_internal/server/compatibility/volumes.py new file mode 100644 index 000000000..9f7406a4b --- /dev/null +++ b/src/dstack/_internal/server/compatibility/volumes.py @@ -0,0 +1,23 @@ +from typing import Optional + +from packaging.version import Version + +from dstack._internal.core.models.volumes import ( + RunpodGlobalVolumeConfiguration, + RunpodVolumeConfiguration, + Volume, +) + + +def patch_volume(volume: Volume, client_version: Optional[Version]) -> None: + if client_version is None or client_version >= Version("0.22.9"): + return + if isinstance(volume.configuration, RunpodGlobalVolumeConfiguration): + if client_version < Version("0.22.2"): + # These clients require a fixed capacity, but allow absent provisioning data. + volume.provisioning_data = None + # Older clients require a Runpod region even when only displaying a volume. + # Keep listing/get working; configuring global volumes requires a newer client. + volume.configuration = RunpodVolumeConfiguration( + **volume.configuration.model_dump(exclude={"global_"}), region="" + ) diff --git a/src/dstack/_internal/server/routers/volumes.py b/src/dstack/_internal/server/routers/volumes.py index 8daee52bd..befc158f6 100644 --- a/src/dstack/_internal/server/routers/volumes.py +++ b/src/dstack/_internal/server/routers/volumes.py @@ -1,11 +1,13 @@ from typing import List, Tuple from fastapi import APIRouter, Depends +from packaging.version import Version from sqlalchemy.ext.asyncio import AsyncSession import dstack._internal.server.services.volumes as volumes_services from dstack._internal.core.errors import ResourceNotExistsError from dstack._internal.core.models.volumes import Volume +from dstack._internal.server.compatibility.volumes import patch_volume from dstack._internal.server.db import get_session from dstack._internal.server.models import ProjectModel, UserModel from dstack._internal.server.schemas.volumes import ( @@ -19,6 +21,7 @@ from dstack._internal.server.utils.routers import ( CustomJSONResponse, get_base_api_additional_responses, + get_client_version, ) root_router = APIRouter( @@ -34,6 +37,7 @@ async def list_volumes( body: ListVolumesRequest, session: AsyncSession = Depends(get_session), user: UserModel = Depends(Authenticated()), + client_version: Version | None = Depends(get_client_version), ): """ Returns all volumes visible to user sorted by descending `created_at`. @@ -42,32 +46,35 @@ async def list_volumes( The results are paginated. To get the next page, pass `created_at` and `id` of the last fleet from the previous page as `prev_created_at` and `prev_id`. """ - return CustomJSONResponse( - await volumes_services.list_volumes( - session=session, - user=user, - project_name=body.project_name, - only_active=body.only_active, - prev_created_at=body.prev_created_at, - prev_id=body.prev_id, - limit=body.limit, - ascending=body.ascending, - ) + volumes = await volumes_services.list_volumes( + session=session, + user=user, + project_name=body.project_name, + only_active=body.only_active, + prev_created_at=body.prev_created_at, + prev_id=body.prev_id, + limit=body.limit, + ascending=body.ascending, ) + for volume in volumes: + patch_volume(volume, client_version) + return CustomJSONResponse(volumes) @project_router.post("/list", summary="List project volumes", response_model=List[Volume]) async def list_project_volumes( session: AsyncSession = Depends(get_session), user_project: Tuple[UserModel, ProjectModel] = Depends(ProjectMember()), + client_version: Version | None = Depends(get_client_version), ): """ Returns all volumes in the project. """ _, project = user_project - return CustomJSONResponse( - await volumes_services.list_project_volumes(session=session, project=project) - ) + volumes = await volumes_services.list_project_volumes(session=session, project=project) + for volume in volumes: + patch_volume(volume, client_version) + return CustomJSONResponse(volumes) @project_router.post("/get", summary="Get volume", response_model=Volume) @@ -75,6 +82,7 @@ async def get_volume( body: GetVolumeRequest, session: AsyncSession = Depends(get_session), user_project: Tuple[UserModel, ProjectModel] = Depends(ProjectMember()), + client_version: Version | None = Depends(get_client_version), ): """ Returns a volume given a volume name. @@ -85,6 +93,7 @@ async def get_volume( ) if volume is None: raise ResourceNotExistsError() + patch_volume(volume, client_version) return CustomJSONResponse(volume) @@ -94,20 +103,21 @@ async def create_volume( session: AsyncSession = Depends(get_session), user_project: Tuple[UserModel, ProjectModel] = Depends(ProjectMember()), pipeline_hinter: PipelineHinterProtocol = Depends(get_pipeline_hinter), + client_version: Version | None = Depends(get_client_version), ): """ Creates a volume given a volume configuration. """ user, project = user_project - return CustomJSONResponse( - await volumes_services.create_volume( - session=session, - project=project, - user=user, - configuration=body.configuration, - pipeline_hinter=pipeline_hinter, - ) + volume = await volumes_services.create_volume( + session=session, + project=project, + user=user, + configuration=body.configuration, + pipeline_hinter=pipeline_hinter, ) + patch_volume(volume, client_version) + return CustomJSONResponse(volume) @project_router.post("/delete", summary="Delete volumes") diff --git a/src/tests/_internal/core/backends/runpod/test_api_client.py b/src/tests/_internal/core/backends/runpod/test_api_client.py index 315a57cbd..ee559ae10 100644 --- a/src/tests/_internal/core/backends/runpod/test_api_client.py +++ b/src/tests/_internal/core/backends/runpod/test_api_client.py @@ -66,7 +66,8 @@ def test_gpu_pod(self, requests_mock): "env": {"RUNPOD_POD_USER": "0"}, } - def test_cpu_pod(self, requests_mock): + @pytest.mark.parametrize("global_volume_id", [None, "global-1"]) + def test_cpu_pod(self, requests_mock, global_volume_id): requests_mock.post(f"{API_V2_URL}/pods", status_code=201, json={"id": "pod-1"}) _client().create_pod( @@ -75,12 +76,14 @@ def test_cpu_pod(self, requests_mock): cpu_type_id="cpu3c", cpu_count=4, container_disk_in_gb=20, + global_volume_id=global_volume_id, + global_volume_mount_path="/models" if global_volume_id else None, image_name="dstackai/base:latest", entrypoint=["/bin/sh"], cmd=["-c", "echo hi"], ) - assert requests_mock.last_request.json() == { + expected = { "name": "test-pod", "cloud": "SECURE", "cpu": {"id": "cpu3c", "vcpuCount": 4}, @@ -89,6 +92,9 @@ def test_cpu_pod(self, requests_mock): "entrypoint": ["/bin/sh"], "cmd": ["-c", "echo hi"], } + if global_volume_id: + expected["mounts"] = {"global": [{"volumeId": global_volume_id, "path": "/models"}]} + assert requests_mock.last_request.json() == expected def test_rejects_both_gpu_and_cpu(self): with pytest.raises(ValueError, match="Exactly one"): @@ -185,6 +191,20 @@ def test_delete_network_volume(self, requests_mock): assert _client().delete_network_volume("vol-1") is False + def test_get_global_volume(self, requests_mock): + requests_mock.get( + f"{API_V2_URL}/global-volumes/vol-1", status_code=404, json=_error(404, "-") + ) + + assert _client().get_global_volume("vol-1") is None + + def test_delete_global_volume(self, requests_mock): + requests_mock.delete( + f"{API_V2_URL}/global-volumes/vol-1", status_code=404, json=_error(404, "-") + ) + + assert _client().delete_global_volume("vol-1") is False + def test_other_errors_are_raised(self, requests_mock): requests_mock.delete( f"{API_V2_URL}/pods/pod-1", @@ -196,6 +216,35 @@ def test_other_errors_are_raised(self, requests_mock): _client().terminate_pod("pod-1") +class TestRunpodApiClientGlobalVolumes: + def test_create_get_and_delete(self, requests_mock): + volume = { + "id": "global-1", + "name": "models", + "createdAt": "2026-11-25T10:00:00Z", + "createdByUserId": None, + } + create = requests_mock.post(f"{API_V2_URL}/global-volumes", status_code=201, json=volume) + requests_mock.get(f"{API_V2_URL}/global-volumes/global-1", json=volume) + requests_mock.delete(f"{API_V2_URL}/global-volumes/global-1", status_code=204) + client = _client() + + assert client.create_global_volume(name="models") == volume + assert create.last_request.json() == {"name": "models"} + assert client.get_global_volume("global-1") == volume + assert client.delete_global_volume("global-1") is True + + def test_delete_preserves_in_use_error(self, requests_mock): + requests_mock.delete( + f"{API_V2_URL}/global-volumes/global-1", + status_code=409, + json=_error(409, "Volume is in use"), + ) + + with pytest.raises(RunpodV2ClientError, match="Volume is in use"): + _client().delete_global_volume("global-1") + + class TestRunpodApiClientListPods: def _page(self, pod_ids: list[str], next_cursor: str | None) -> dict: return { diff --git a/src/tests/_internal/core/backends/runpod/test_compute.py b/src/tests/_internal/core/backends/runpod/test_compute.py index 8173e82ff..1aa4d5f54 100644 --- a/src/tests/_internal/core/backends/runpod/test_compute.py +++ b/src/tests/_internal/core/backends/runpod/test_compute.py @@ -8,15 +8,22 @@ from dstack._internal.core.backends.runpod.api_client import RunpodV2ClientError from dstack._internal.core.backends.runpod.compute import RunpodCompute from dstack._internal.core.backends.runpod.models import RunpodAPIKeyCreds, RunpodConfig -from dstack._internal.core.errors import ComputeError +from dstack._internal.core.errors import ComputeError, SkipOffer from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import ListedResourceGroup, OwnerType from dstack._internal.core.models.instances import InstanceOfferWithAvailability from dstack._internal.core.models.resources import ResourcesSpec from dstack._internal.core.models.runs import JobProvisioningData, Requirements +from dstack._internal.core.models.volumes import ( + RunpodGlobalVolumeConfiguration, + RunpodVolumeConfiguration, + Volume, + VolumeMountPoint, +) from dstack._internal.server.testing.common import ( get_instance_offer_with_availability, get_job_provisioning_data, + get_volume, ) # build_authorized_keys() rejects the project key unless it actually parses @@ -63,6 +70,7 @@ def _job() -> MagicMock: def _run() -> MagicMock: run = MagicMock() run.user = "test-user" + run.run_spec.configuration.volumes = [VolumeMountPoint(name="data", path="/data")] return run @@ -70,6 +78,7 @@ def _run_job( compute: RunpodCompute, offer: InstanceOfferWithAvailability, job: Optional[MagicMock] = None, + volumes: Optional[list[Volume]] = None, ) -> JobProvisioningData: with patch( "dstack._internal.core.backends.runpod.compute.get_docker_commands", @@ -82,19 +91,24 @@ def _run_job( project_name="main", project_ssh_public_key=PROJECT_SSH_PUBLIC_KEY, project_ssh_private_key="private-key", - volumes=[], + volumes=volumes or [], placement_group=None, requirements=Requirements(resources=ResourcesSpec()), extra_authorized_keys=[], ) -def _run_jobs(compute: RunpodCompute, offer: InstanceOfferWithAvailability, job_count: int): +def _run_jobs( + compute: RunpodCompute, + offer: InstanceOfferWithAvailability, + job_count: int, + volumes: Optional[list[Volume]] = None, +): job_configurations = [] for _ in range(job_count): job_configuration = MagicMock() job_configuration.job = _job() - job_configuration.volumes = [] + job_configuration.volumes = volumes or [] job_configurations.append(job_configuration) with patch( "dstack._internal.core.backends.runpod.compute.get_docker_commands", @@ -140,6 +154,37 @@ def _pod( class TestRunpodComputeRunJob: + @pytest.mark.parametrize("global_volume", [False, True]) + def test_volume_mount(self, global_volume): + compute, api_client = _compute_with_mocked_api_client() + api_client.create_pod.return_value = {"id": "pod-1"} + config = ( + RunpodGlobalVolumeConfiguration(global_=True) + if global_volume + else RunpodVolumeConfiguration(region="EU-RO-1") + ) + volume = get_volume(configuration=config, volume_id="vol-1") + + _run_job(compute, _gpu_offer(), volumes=[volume]) + + kwargs = api_client.create_pod.call_args.kwargs + assert kwargs["network_volume_id"] == (None if global_volume else "vol-1") + assert kwargs["volume_mount_path"] == (None if global_volume else "/data") + assert kwargs["global_volume_id"] == ("vol-1" if global_volume else None) + assert kwargs["global_volume_mount_path"] == ("/data" if global_volume else None) + + def test_global_volume_skips_community_offer_before_api_calls(self): + compute, api_client = _compute_with_mocked_api_client() + offer = _gpu_offer().model_copy(update={"region": "US"}) + volume = get_volume( + configuration=RunpodGlobalVolumeConfiguration(global_=True), volume_id="vol-1" + ) + + with pytest.raises(SkipOffer, match="Secure Cloud"): + _run_job(compute, offer, volumes=[volume]) + + assert api_client.mock_calls == [] + def test_requests_per_gpu_minimums_rounded_down(self): compute, api_client = _compute_with_mocked_api_client() api_client.create_pod.return_value = {"id": "pod-1"} @@ -180,6 +225,17 @@ def test_encodes_provider_ref_in_pod_name(self): class TestRunpodComputeRunJobs: + def test_global_volume_skips_cluster_before_api_calls(self): + compute, api_client = _compute_with_mocked_api_client() + volume = get_volume( + configuration=RunpodGlobalVolumeConfiguration(global_=True), volume_id="vol-1" + ) + + with pytest.raises(SkipOffer, match="Instant Clusters"): + _run_jobs(compute, _cluster_offer([2]), 2, volumes=[volume]) + + assert api_client.mock_calls == [] + def test_sets_internal_ip_from_cluster_ip(self): compute, api_client = _compute_with_mocked_api_client() api_client.create_cluster.return_value = {"id": "cluster-1", "name": "test"} @@ -225,6 +281,43 @@ def test_raises_original_error_if_cluster_deletion_fails(self): _run_jobs(compute, _cluster_offer([2, 4]), job_count=2) +class TestRunpodComputeGlobalVolumes: + @pytest.mark.parametrize("external", [False, True]) + def test_create_or_register_and_delete(self, external): + compute, api_client = _compute_with_mocked_api_client() + api_client.create_global_volume.return_value = {"id": "global-1"} + api_client.get_global_volume.return_value = {"id": "global-1"} + volume = get_volume( + configuration=RunpodGlobalVolumeConfiguration( + global_=True, volume_id="global-1" if external else None + ), + external=external, + ) + + data = compute.register_volume(volume) if external else compute.create_volume(volume) + + assert data.volume_id == "global-1" + assert data.size_gb is None + assert data.price is None + assert not data.attachable and not data.detachable + api_client.create_network_volume.assert_not_called() + api_client.get_network_volume.assert_not_called() + volume.volume_id = data.volume_id + compute.delete_volume(volume) + api_client.delete_global_volume.assert_called_once_with("global-1") + api_client.delete_network_volume.assert_not_called() + + def test_register_missing_volume(self): + compute, api_client = _compute_with_mocked_api_client() + api_client.get_global_volume.return_value = None + volume = get_volume( + configuration=RunpodGlobalVolumeConfiguration(global_=True, volume_id="missing") + ) + + with pytest.raises(ComputeError, match="Volume missing not found"): + compute.register_volume(volume) + + class TestRunpodComputeUpdateProvisioningData: def _update(self, compute: RunpodCompute, jpd: JobProvisioningData) -> None: compute.update_provisioning_data( diff --git a/src/tests/_internal/core/compatibility/test_volumes.py b/src/tests/_internal/core/compatibility/test_volumes.py new file mode 100644 index 000000000..72f3d7552 --- /dev/null +++ b/src/tests/_internal/core/compatibility/test_volumes.py @@ -0,0 +1,27 @@ +import pytest + +from dstack._internal.core.compatibility.volumes import ( + get_create_volume_excludes, + get_volume_spec_excludes, +) +from dstack._internal.core.models.volumes import VolumeSpec + + +class TestVolumeExcludes: + @pytest.mark.parametrize("global_volume", [False, True]) + def test_runpod_global_is_sent_only_when_enabled(self, global_volume): + config = ( + {"backend": "runpod", "global": True} + if global_volume + else {"backend": "runpod", "region": "EU-CZ-1", "size": "100GB"} + ) + spec = VolumeSpec.model_validate({"configuration": config}) + for excludes in ( + get_volume_spec_excludes(spec), + get_create_volume_excludes(spec.configuration), + ): + payload = spec.model_dump(exclude=excludes)["configuration"] + if global_volume: + assert payload["global"] is True + else: + assert "global" not in payload diff --git a/src/tests/_internal/core/models/test_volumes.py b/src/tests/_internal/core/models/test_volumes.py index 46b692e2a..0b102f288 100644 --- a/src/tests/_internal/core/models/test_volumes.py +++ b/src/tests/_internal/core/models/test_volumes.py @@ -6,6 +6,8 @@ from dstack._internal.core.models.volumes import ( DaytonaVolumeConfiguration, InstanceMountPoint, + RunpodGlobalVolumeConfiguration, + RunpodVolumeConfiguration, VolumeConfiguration, VolumeConfigurationWithSize, VolumeMountPoint, @@ -13,6 +15,48 @@ VolumeSpec, parse_mount_point, ) +from dstack._internal.server.testing.common import get_volume + + +class TestRunpodVolumeConfiguration: + def test_schema_requires_explicit_global_opt_in(self): + schema = VolumeSpec.model_json_schema() + global_schema = schema["$defs"]["RunpodGlobalVolumeConfiguration"] + assert "global" in global_schema["required"] + assert global_schema["properties"]["global"]["const"] is True + + @pytest.mark.parametrize("volume_id", [None, "existing-global"]) + def test_global_volume_roundtrip_and_location(self, volume_id): + spec = VolumeSpec.model_validate( + {"configuration": {"backend": "runpod", "global": True, "volume_id": volume_id}} + ) + assert isinstance(spec.configuration, RunpodGlobalVolumeConfiguration) + assert spec.configuration.is_external == (volume_id is not None) + assert "region" not in spec.configuration.model_dump() + assert "size" not in spec.configuration.model_dump() + assert spec.configuration.model_dump()["global"] is True + assert VolumeSpec.model_validate_json(spec.model_dump_json()) == spec + volume = get_volume(configuration=spec.configuration) + assert volume.get_region() == "" + assert volume.matches_location(spec.configuration.backend, "EU-CZ-1") + assert volume.matches_location(spec.configuration.backend, "US-MD-1") + + @pytest.mark.parametrize(("field", "value"), [("size", 100), ("region", "EU-CZ-1")]) + def test_global_volume_rejects_size_and_region(self, field, value): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + VolumeConfiguration.model_validate({"backend": "runpod", "global": True, field: value}) + + @pytest.mark.parametrize("global_fields", [{}, {"global": False}]) + def test_network_volume_still_requires_region(self, global_fields): + with pytest.raises(ValidationError, match="region"): + VolumeConfiguration.model_validate({"backend": "runpod", **global_fields}) + config = VolumeConfiguration.model_validate( + {"backend": "runpod", "region": "EU-CZ-1", **global_fields} + ).root + assert isinstance(config, RunpodVolumeConfiguration) + volume = get_volume(configuration=config) + assert volume.matches_location(config.backend, "eu-cz-1") + assert not volume.matches_location(config.backend, "US-MD-1") @pytest.mark.parametrize("backend", ["aws", "gcp", "runpod", "kubernetes"]) diff --git a/src/tests/_internal/server/compatibility/test_volumes.py b/src/tests/_internal/server/compatibility/test_volumes.py new file mode 100644 index 000000000..adb9d01c1 --- /dev/null +++ b/src/tests/_internal/server/compatibility/test_volumes.py @@ -0,0 +1,43 @@ +import pytest +from packaging.version import Version + +from dstack._internal.core.models.backends.base import BackendType +from dstack._internal.core.models.volumes import ( + RunpodGlobalVolumeConfiguration, + VolumeProvisioningData, + VolumeStatus, +) +from dstack._internal.server.compatibility.volumes import patch_volume +from dstack._internal.server.testing.common import get_volume + + +class TestPatchVolume: + @pytest.mark.parametrize( + ("client_version", "has_provisioning_data"), + [ + (Version("0.22.1"), False), + (Version("0.22.2"), True), + (Version("0.22.9"), True), + (None, True), + ], + ) + def test_provisioned_global_volume(self, client_version, has_provisioning_data): + provisioning_data = VolumeProvisioningData( + backend=BackendType.RUNPOD, + volume_id="global-1", + size_gb=None, + attachable=False, + detachable=False, + ) + volume = get_volume( + configuration=RunpodGlobalVolumeConfiguration(global_=True), + volume_id=provisioning_data.volume_id, + provisioning_data=provisioning_data, + ) + + patch_volume(volume, client_version) + + # Clients before 0.22.2 require an integer capacity, but allow absent provisioning data. + assert volume.provisioning_data == (provisioning_data if has_provisioning_data else None) + assert volume.volume_id == "global-1" + assert volume.status == VolumeStatus.ACTIVE diff --git a/src/tests/_internal/server/routers/test_volumes.py b/src/tests/_internal/server/routers/test_volumes.py index 30cab2423..b2118eb93 100644 --- a/src/tests/_internal/server/routers/test_volumes.py +++ b/src/tests/_internal/server/routers/test_volumes.py @@ -301,6 +301,44 @@ async def test_returns_400_if_volume_does_not_exist( class TestCreateVolume: + @pytest.mark.asyncio + @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) + @pytest.mark.parametrize("client_version", [None, "0.22.8"]) + async def test_global_volume_and_legacy_read_responses( + self, test_db, session: AsyncSession, client: AsyncClient, client_version + ): + user = await create_user(session, global_role=GlobalRole.ADMIN) + project = await create_project(session, owner=user) + headers = get_auth_headers(user.token) + response = await client.post( + f"/api/project/{project.name}/volumes/create", + headers=headers, + json={"configuration": {"backend": "runpod", "name": "models", "global": True}}, + ) + assert response.status_code == 200 + assert response.json()["configuration"]["global"] is True + assert "region" not in response.json()["configuration"] + if client_version is not None: + headers["x-api-version"] = client_version + for path, body in ( + ("/api/volumes/list", {}), + (f"/api/project/{project.name}/volumes/list", {}), + (f"/api/project/{project.name}/volumes/get", {"name": "models"}), + ): + response = await client.post(path, headers=headers, json=body) + assert response.status_code == 200 + payload = response.json() + config = (payload[0] if isinstance(payload, list) else payload)["configuration"] + if client_version is None: + assert config["global"] is True + assert "region" not in config + else: + assert config["region"] == "" + # Compatibility adaptation is only applied to the response, not the stored configuration. + volume = await session.scalar(select(VolumeModel)) + assert volume is not None + assert json.loads(volume.configuration)["global"] is True + @pytest.mark.asyncio async def test_returns_40x_if_not_authenticated(self, client: AsyncClient): response = await client.post("/api/project/main/volumes/create") diff --git a/src/tests/_internal/server/services/test_instances.py b/src/tests/_internal/server/services/test_instances.py index e54f0ad97..4cabea41e 100644 --- a/src/tests/_internal/server/services/test_instances.py +++ b/src/tests/_internal/server/services/test_instances.py @@ -23,7 +23,10 @@ Profile, ) from dstack._internal.core.models.runs import JobStatus -from dstack._internal.core.models.volumes import DaytonaVolumeConfiguration +from dstack._internal.core.models.volumes import ( + DaytonaVolumeConfiguration, + RunpodGlobalVolumeConfiguration, +) from dstack._internal.server.models import InstanceModel from dstack._internal.server.schemas.runner import TaskListItem, TaskListResponse, TaskStatus from dstack._internal.server.services.runner.client import ShimClient @@ -127,7 +130,11 @@ def test_preserves_volume_availability_zone_matching( assert result == ([instance] if matches else []) - def test_global_volume_matches_cpu_and_gpu_regions(self): + @pytest.mark.parametrize( + "configuration", + [DaytonaVolumeConfiguration(), RunpodGlobalVolumeConfiguration(global_=True)], + ) + def test_global_volume_matches_cpu_and_gpu_regions(self, configuration): instances = [ InstanceModel( unreachable=False, @@ -138,8 +145,8 @@ def test_global_volume_matches_cpu_and_gpu_regions(self): ).model_dump_json(), ) for backend, region, gpu_count in [ - (BackendType.DAYTONA, "us", 0), - (BackendType.DAYTONA, "earth", 1), + (configuration.backend, "us", 0), + (configuration.backend, "earth", 1), (BackendType.AWS, "us", 0), ] ] @@ -147,7 +154,7 @@ def test_global_volume_matches_cpu_and_gpu_regions(self): result = instances_services.filter_instances( instances=instances, profile=Profile(), - volumes=[[get_volume(configuration=DaytonaVolumeConfiguration())]], + volumes=[[get_volume(configuration=configuration)]], ) assert result == instances[:2] diff --git a/src/tests/_internal/server/services/test_offers.py b/src/tests/_internal/server/services/test_offers.py index ca5d26199..45b6deca7 100644 --- a/src/tests/_internal/server/services/test_offers.py +++ b/src/tests/_internal/server/services/test_offers.py @@ -6,7 +6,10 @@ from dstack._internal.core.models.profiles import Profile from dstack._internal.core.models.resources import ResourcesSpec from dstack._internal.core.models.runs import Requirements -from dstack._internal.core.models.volumes import DaytonaVolumeConfiguration +from dstack._internal.core.models.volumes import ( + DaytonaVolumeConfiguration, + RunpodGlobalVolumeConfiguration, +) from dstack._internal.server.services.offers import get_offers_by_requirements from dstack._internal.server.testing.common import ( get_instance_offer_with_availability, @@ -124,25 +127,31 @@ async def test_returns_volume_offers(self): assert res == [(runpod_backend_mock, runpod_offer2)] @pytest.mark.asyncio - async def test_global_volume_matches_cpu_and_gpu_regions(self): - daytona_backend = Mock(TYPE=BackendType.DAYTONA) - cpu_offer = get_instance_offer_with_availability(backend=BackendType.DAYTONA, region="us") + @pytest.mark.parametrize( + "configuration", + [DaytonaVolumeConfiguration(), RunpodGlobalVolumeConfiguration(global_=True)], + ) + async def test_global_volume_matches_cpu_and_gpu_regions(self, configuration): + volume_backend = Mock(TYPE=configuration.backend) + cpu_offer = get_instance_offer_with_availability( + backend=configuration.backend, region="us" + ) gpu_offer = get_instance_offer_with_availability( - backend=BackendType.DAYTONA, region="earth", gpu_count=1 + backend=configuration.backend, region="earth", gpu_count=1 ) - daytona_backend.compute.return_value.get_offers.return_value = [cpu_offer, gpu_offer] + volume_backend.compute.return_value.get_offers.return_value = [cpu_offer, gpu_offer] aws_backend = Mock(TYPE=BackendType.AWS) aws_offer = get_instance_offer_with_availability(backend=BackendType.AWS, region="us") aws_backend.compute.return_value.get_offers.return_value = [aws_offer] offers = await get_offers_by_requirements( - backends=[daytona_backend, aws_backend], + backends=[volume_backend, aws_backend], profile=Profile(), requirements=Requirements(resources=ResourcesSpec()), - volumes=[[get_volume(configuration=DaytonaVolumeConfiguration())]], + volumes=[[get_volume(configuration=configuration)]], ) - assert offers == [(daytona_backend, cpu_offer), (daytona_backend, gpu_offer)] + assert offers == [(volume_backend, cpu_offer), (volume_backend, gpu_offer)] @pytest.mark.asyncio async def test_returns_volume_offers_without_region(self):