From cfea50016dd25bca9ed198c00c9ade73db3e38a9 Mon Sep 17 00:00:00 2001 From: Dmitry Meyer Date: Thu, 26 Nov 2026 12:15:20 +0000 Subject: [PATCH] Get Runpod offers from the online gpuhunt provider Switch RunpodCompute to gpuhunt 0.1.37's online RunpodProvider, based on Runpod REST API v2, and to ComputeWithFilteredOffersCached: the provider queries offers for the run's GPU count, vCPU, and RAM, and lists only data centers where the offer is available. Only Secure Cloud GPU and CPU pods are supported. Community Cloud and Instant Clusters are dropped; the `community_cloud` backend setting is deprecated and ignored. The backend can no longer terminate Runpod Instant Clusters created by older server versions. Terminate runs and fleets that use them before upgrading. Otherwise, their instances get stuck in the terminating state, and the clusters must be deleted manually in the Runpod console. Fixes: https://github.com/dstackai/dstack/issues/4400 Assisted-by: Claude Opus 5.5 --- mkdocs/docs/concepts/backends.md | 37 -- mkdocs/docs/concepts/fleets.md | 2 - mkdocs/docs/guides/migration/slurm.md | 2 +- pyproject.toml | 2 +- .../_internal/core/backends/base/offers.py | 8 +- .../core/backends/runpod/api_client.py | 304 +--------------- .../_internal/core/backends/runpod/compute.py | 326 ++++-------------- .../_internal/core/backends/runpod/models.py | 14 +- .../core/backends/runpod/test_api_client.py | 7 - .../core/backends/runpod/test_compute.py | 253 ++++++++------ .../pipeline_tasks/test_jobs_submitted.py | 24 +- 11 files changed, 228 insertions(+), 751 deletions(-) diff --git a/mkdocs/docs/concepts/backends.md b/mkdocs/docs/concepts/backends.md index df1d4820bd..4bf546951f 100644 --- a/mkdocs/docs/concepts/backends.md +++ b/mkdocs/docs/concepts/backends.md @@ -1651,43 +1651,6 @@ projects: -??? info "Community Cloud" - By default, `dstack` considers instance offers only from the Secure Cloud. - To also include the - [Community Cloud](https://docs.runpod.io/references/faq/#secure-cloud-vs-community-cloud), - set `community_cloud: true` in the backend settings. - -
- - ```yaml - projects: - - name: main - backends: - - type: runpod - creds: - type: api_key - api_key: US9XTPDIV8AR42MMINY8TCKRB8S4E7LNRQ6CAUQ9 - community_cloud: true - ``` - -
- - You can tell Secure Cloud and Community Cloud apart by their regions. - Secure Cloud regions contain datacenter IDs such as `CA-MTL-3`. - Community Cloud regions contain country codes such as `CA`. - -
- - ```shell - $ dstack apply -f .dstack.yml -b runpod - - # BACKEND REGION INSTANCE SPOT PRICE - 1 runpod CA NVIDIA A100 80GB PCIe yes $0.6 - 2 runpod CA-MTL-3 NVIDIA A100 80GB PCIe yes $0.82 - ``` - -
- ### Vast.ai Log into your [Vast.ai](https://cloud.vast.ai/) account, click Account in the sidebar, and copy your diff --git a/mkdocs/docs/concepts/fleets.md b/mkdocs/docs/concepts/fleets.md index 412ddf15bd..b6a4ff7bea 100644 --- a/mkdocs/docs/concepts/fleets.md +++ b/mkdocs/docs/concepts/fleets.md @@ -175,8 +175,6 @@ This property ensures that instances are interconnected. This is required for ru If the Kubernetes cluster has interconnect configured, `dstack` can use it without additional setup. See the [Lambda](../examples/clusters/lambda.md#kubernetes) or [Crusoe](../examples/clusters/crusoe.md#kubernetes) examples. - - === "SSH fleets" If the hosts in the SSH fleet have interconnect configured, you only need to set `placement` to `cluster`. diff --git a/mkdocs/docs/guides/migration/slurm.md b/mkdocs/docs/guides/migration/slurm.md index 6c9ce2aac1..a8f9648c56 100644 --- a/mkdocs/docs/guides/migration/slurm.md +++ b/mkdocs/docs/guides/migration/slurm.md @@ -936,7 +936,7 @@ resources: -Network volumes cannot be used with multi-node tasks (no multi-attach support), except where multi-attach is supported (Runpod) or via volume interpolation. +Network volumes cannot be used with multi-node tasks (no multi-attach support), except via volume interpolation. For multi-node tasks, use interpolation to attach different volumes to each node. diff --git a/pyproject.toml b/pyproject.toml index 5633ddfe69..af0bad5d1d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,7 @@ dependencies = [ "python-multipart>=0.0.31", "filelock", "psutil", - "gpuhunt==0.1.36", + "gpuhunt==0.1.37", "argcomplete>=3.5.0", "ignore-python>=0.2.0", "apscheduler<4", diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 4055a058f1..2ea059d64d 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -27,8 +27,6 @@ "gcp-a4", "gcp-g4", "gcp-dws-calendar-mode", - "runpod-cpu", - "runpod-cluster", "hotaisle-bm", ] @@ -51,6 +49,7 @@ def get_catalog_offers( extra_filter: Optional[Callable[[InstanceOffer], bool]] = None, catalog: Optional[gpuhunt.Catalog] = None, catalog_item_filter: Optional[Callable[[gpuhunt.CatalogItem], bool]] = None, + check_disk: bool = True, ) -> List[InstanceOffer]: """ Returns offers from the `gpuhunt` catalog for the given `backend`. @@ -68,6 +67,8 @@ def get_catalog_offers( catalog_item_filter: applied to raw catalog items before the conversion to `InstanceOffer` models. Use it for filtering that can be done on raw catalog fields to avoid expensive model construction for items that will be discarded. + check_disk: filter catalog items by the required disk size. Set to `False` if the + backend fits offer disks to requirements itself, e.g. with `OfferDiskFitter`. """ provider = backend.value if backend == BackendType.DATACRUNCH: @@ -78,6 +79,9 @@ def get_catalog_offers( provider = "digitalocean" q = requirements_to_query_filter(requirements) q.provider = [provider] + if not check_disk: + q.min_disk_size = None + q.max_disk_size = None offers = [] catalog = catalog if catalog is not None else gpuhunt.default_catalog() diff --git a/src/dstack/_internal/core/backends/runpod/api_client.py b/src/dstack/_internal/core/backends/runpod/api_client.py index bc4ac2ffe2..eafd3b1d04 100644 --- a/src/dstack/_internal/core/backends/runpod/api_client.py +++ b/src/dstack/_internal/core/backends/runpod/api_client.py @@ -1,6 +1,6 @@ from collections.abc import Mapping from http import HTTPStatus -from typing import Any, Dict, List, Literal, NotRequired, Optional, TypedDict, cast +from typing import Any, List, Literal, NotRequired, Optional, TypedDict, cast import requests from gpuhunt.providers.runpod import RunpodProvider @@ -10,9 +10,7 @@ logger = get_logger(__name__) -API_BASE_URL = "https://api.runpod.io" -API_GRAPHQL_URL = f"{API_BASE_URL}/graphql" -API_V2_URL = f"{API_BASE_URL}/v2" +API_V2_URL = "https://api.runpod.io/v2" REQUEST_TIMEOUT = 120 @@ -46,26 +44,15 @@ class V2Pod(TypedDict): status: Literal["PROVISIONING", "STARTING", "RUNNING", "EXITED", "ERROR", "TERMINATED"] runtime: Optional["V2PodRuntime"] mounts: "V2Mounts" - cluster: NotRequired["V2PodCluster"] createdAt: str dataCenterId: Optional[str] -class V2PodList(TypedDict): - pods: list[V2Pod] - - class V2Pagination(TypedDict): nextCursor: Optional[str] hasNextPage: bool -class V2PodCluster(TypedDict): - id: str - rank: Optional[int] - ip: NotRequired[str] - - class V2PodRuntime(TypedDict): ports: NotRequired[list["V2PodRuntimePort"]] @@ -146,50 +133,6 @@ class V2CreateCpuConfig(TypedDict): """Number of vCPUs. Must be valid for the selected CPU flavor and must be a power of two.""" -class V2Cluster(TypedDict): - id: str - name: str - type: "V2ClusterType" - compute: "V2ClusterCompute" - - -V2ClusterType = Literal["APPLICATION", "TRAINING", "SLURM", "RAY"] -""""Cluster type. `TRAINING` is the generic distributed-training cluster; `SLURM` provisions -a managed Slurm controller/compute topology; `RAY` provisions a managed Ray head/worker topology; -`APPLICATION` is a general multi-node application cluster.""" - - -class V2ClusterCompute(TypedDict): - gpuTypeId: str - gpuCountPerPod: int - podCount: int - - -class V2CreateClusterRequest(TypedDict): - name: str - type: V2ClusterType - compute: V2ClusterCompute - dataCenterIds: NotRequired[list[str]] - """Preferred data centers for placement. Omit or pass an empty array to let the scheduler - choose. A cluster is always placed within a single data center.""" - templateId: NotRequired[str] - """ID of a pod template to provision every member pod from. The template supplies the container - settings (image, args, disk, env, ports) and the container registry credential for private - images — the only private-image path for clusters.""" - disk: NotRequired[int] - """Container disk in GB (ephemeral, wiped on restart)""" - mounts: NotRequired["V2Mounts"] - image: NotRequired[str] - """`image` is required unless `templateId` is set""" - entrypoint: NotRequired[list[str]] - """Container ENTRYPOINT in exec form""" - cmd: NotRequired[list[str]] - """Container CMD in exec form""" - ports: NotRequired[list[str]] - """Exposed ports, formatted as port/protocol""" - env: NotRequired[dict[str, str]] - - class V2Registry(TypedDict): id: str name: str @@ -228,14 +171,6 @@ class V2CreateNetworkVolumeRequest(TypedDict): storage tier.""" -class RunpodGraphqlClientError(BackendError): - errors: List[Dict] - - def __init__(self, errors: List[Dict]): - self.errors = errors - super().__init__(errors) - - class RunpodV2ClientError(BackendError): def __init__( self, *, status: int, title: str, detail: str, errors: Optional[list[str]] = None @@ -342,62 +277,6 @@ def create_pod( response = self._make_v2_request("POST", "pods", json=body) return response.json() - def create_gpu_pod_graphql( - self, - name: str, - image_name: str, - gpu_type_id: str, - cloud_type: str, - support_public_ip: bool = True, - start_ssh: bool = True, - data_center_id: Optional[str] = None, - country_code: Optional[str] = None, - gpu_count: int = 1, - volume_in_gb: int = 0, - container_disk_in_gb: Optional[int] = None, - min_vcpu_count: int = 1, - min_memory_in_gb: int = 1, - docker_args: str = "", - ports: Optional[str] = None, - volume_mount_path: Optional[str] = None, - env: Optional[Dict[str, Any]] = None, - template_id: Optional[str] = None, - network_volume_id: Optional[str] = None, - allowed_cuda_versions: Optional[List[str]] = None, - bid_per_gpu: Optional[float] = None, - container_registry_auth_id: Optional[str] = None, - ) -> Dict: - resp = self._make_graphql_request( - { - "query": _generate_pod_deployment_mutation( - name=name, - image_name=image_name, - gpu_type_id=gpu_type_id, - cloud_type=cloud_type, - support_public_ip=support_public_ip, - start_ssh=start_ssh, - data_center_id=data_center_id, - country_code=country_code, - gpu_count=gpu_count, - volume_in_gb=volume_in_gb, - container_disk_in_gb=container_disk_in_gb, - min_vcpu_count=min_vcpu_count, - min_memory_in_gb=min_memory_in_gb, - docker_args=docker_args, - ports=ports, - volume_mount_path=volume_mount_path, - env=env, - template_id=template_id, - network_volume_id=network_volume_id, - allowed_cuda_versions=allowed_cuda_versions, - bid_per_gpu=bid_per_gpu, - container_registry_auth_id=container_registry_auth_id, - ) - } - ) - data = resp.json()["data"] - return data["podRentInterruptable"] if bid_per_gpu else data["podFindAndDeployOnDemand"] - def get_pod(self, pod_id: str) -> Optional[V2Pod]: try: response = self._make_v2_request("GET", "pods", pod_id) @@ -409,7 +288,7 @@ def get_pod(self, pod_id: str) -> Optional[V2Pod]: def list_pods(self) -> list[V2Pod]: """ - Lists pods except cluster member pods. Deleted pods are not listed. + Lists pods. Deleted pods are not listed. """ return self._paginate_v2("pods", response_key="pods") @@ -476,82 +355,6 @@ def delete_network_volume(self, volume_id: str) -> bool: raise return True - def create_cluster( - self, - *, - name: str, - cluster_type: V2ClusterType, - gpu_type_id: str, - gpu_count_per_pod: int, - pod_count: int, - data_center_ids: Optional[list[str]] = None, - container_disk_in_gb: int, - network_volume_id: Optional[str] = None, - volume_mount_path: Optional[str] = None, - image_name: str, - entrypoint: list[str], - cmd: list[str], - ports: Optional[list[str]] = None, - env: Optional[dict[str, str]] = None, - ) -> V2Cluster: - body: V2CreateClusterRequest = { - "name": name, - "type": cluster_type, - "compute": { - "gpuTypeId": gpu_type_id, - "gpuCountPerPod": gpu_count_per_pod, - "podCount": pod_count, - }, - "image": image_name, - "entrypoint": entrypoint, - "cmd": cmd, - "disk": container_disk_in_gb, - } - mounts = _build_v2_mounts(network_volume_id, volume_mount_path) - if mounts is not None: - body["mounts"] = mounts - if data_center_ids is not None: - body["dataCenterIds"] = data_center_ids - if ports is not None: - body["ports"] = ports - if env is not None: - body["env"] = env - response = self._make_v2_request("POST", "clusters", json=body) - return response.json() - - def delete_cluster(self, cluster_id: str) -> bool: - try: - self._make_v2_request("DELETE", "clusters", cluster_id) - except RunpodV2ClientError as e: - if e.status == HTTPStatus.NOT_FOUND: - return False - raise - return True - - def list_cluster_pods(self, cluster_id: str) -> list[V2Pod]: - response = self._make_v2_request("GET", "clusters", cluster_id, "pods") - pod_list: V2PodList = response.json() - return pod_list["pods"] - - def _make_graphql_request(self, data: Optional[Dict[str, Any]] = None) -> requests.Response: - try: - response = self._session.request( - method="POST", - url=API_GRAPHQL_URL, - json=data, - timeout=REQUEST_TIMEOUT, - ) - response.raise_for_status() - response_json = response.json() - # Runpod returns 200 on client errors - if "errors" in response_json: - raise RunpodGraphqlClientError(errors=response_json["errors"]) - return response - except requests.HTTPError as e: - if e.response is not None and e.response.status_code in AUTH_ERROR_STATUS_CODES: - raise BackendInvalidCredentialsError(e.response.text) - raise - def _paginate_v2(self, *path_parts: str, response_key: str) -> list[Any]: """ Follows `pagination.nextCursor` of a cursor-paginated GET endpoint and returns @@ -635,104 +438,3 @@ def _build_v2_mounts( elif volume_mount_path is not None: raise ValueError("volume_mount_path must not be set if network_volume_id is not set") return None - - -def _generate_pod_deployment_mutation( - name: str, - image_name: str, - gpu_type_id: str, - cloud_type: str, - support_public_ip: bool = True, - start_ssh: bool = True, - data_center_id: Optional[str] = None, - country_code: Optional[str] = None, - gpu_count: Optional[int] = None, - volume_in_gb: Optional[int] = None, - container_disk_in_gb: Optional[int] = None, - min_vcpu_count: Optional[int] = None, - min_memory_in_gb: Optional[int] = None, - docker_args: Optional[str] = None, - ports: Optional[str] = None, - volume_mount_path: Optional[str] = None, - env: Optional[Dict[str, Any]] = None, - template_id: Optional[str] = None, - network_volume_id: Optional[str] = None, - allowed_cuda_versions: Optional[List[str]] = None, - bid_per_gpu: Optional[float] = None, - container_registry_auth_id: Optional[str] = None, -) -> str: - """ - Generates a mutation to deploy pod. - """ - input_fields = [] - input_fields.append(f'name: "{name}"') - input_fields.append(f'imageName: "{image_name}"') - input_fields.append(f'gpuTypeId: "{gpu_type_id}"') - input_fields.append(f"cloudType: {cloud_type}") - input_fields.append(f'minCudaVersion: "{RunpodProvider.MIN_CUDA_VERSION}"') - - if start_ssh: - input_fields.append("startSsh: true") - if support_public_ip: - input_fields.append("supportPublicIp: true") - else: - input_fields.append("supportPublicIp: false") - if bid_per_gpu is not None: - input_fields.append(f"bidPerGpu: {bid_per_gpu}") - if data_center_id is not None: - input_fields.append(f'dataCenterId: "{data_center_id}"') - if country_code is not None: - input_fields.append(f'countryCode: "{country_code}"') - if gpu_count is not None: - input_fields.append(f"gpuCount: {gpu_count}") - if volume_in_gb is not None: - input_fields.append(f"volumeInGb: {volume_in_gb}") - if container_disk_in_gb is not None: - input_fields.append(f"containerDiskInGb: {container_disk_in_gb}") - if min_vcpu_count is not None: - input_fields.append(f"minVcpuCount: {min_vcpu_count}") - if min_memory_in_gb is not None: - input_fields.append(f"minMemoryInGb: {min_memory_in_gb}") - if docker_args is not None: - input_fields.append(f'dockerArgs: "{docker_args}"') - if ports is not None: - ports = ports.replace(" ", "") - input_fields.append(f'ports: "{ports}"') - if volume_mount_path is not None: - input_fields.append(f'volumeMountPath: "{volume_mount_path}"') - if env is not None: - env_string = ", ".join( - [f'{{ key: "{key}", value: "{value}" }}' for key, value in env.items()] - ) - input_fields.append(f"env: [{env_string}]") - if template_id is not None: - input_fields.append(f'templateId: "{template_id}"') - if network_volume_id is not None: - input_fields.append(f'networkVolumeId: "{network_volume_id}"') - if allowed_cuda_versions is not None: - allowed_cuda_versions_string = ", ".join( - [f'"{version}"' for version in allowed_cuda_versions] - ) - input_fields.append(f"allowedCudaVersions: [{allowed_cuda_versions_string}]") - if container_registry_auth_id is not None: - input_fields.append(f'containerRegistryAuthId: "{container_registry_auth_id}"') - - pod_deploy = "podFindAndDeployOnDemand" if bid_per_gpu is None else "podRentInterruptable" - - input_string = ", ".join(input_fields) - return f""" - mutation {{ - {pod_deploy}( - input: {{ - {input_string} - }} - ) {{ - id - lastStatusChange - imageName - machine {{ - podHostId - }} - }} - }} - """ diff --git a/src/dstack/_internal/core/backends/runpod/compute.py b/src/dstack/_internal/core/backends/runpod/compute.py index fc9a9dff23..910af1af3c 100644 --- a/src/dstack/_internal/core/backends/runpod/compute.py +++ b/src/dstack/_internal/core/backends/runpod/compute.py @@ -1,15 +1,15 @@ -import json import re import uuid from datetime import datetime, timedelta -from typing import Callable, List, Optional +from typing import List, Optional + +import gpuhunt +from gpuhunt.providers.runpod import RunpodProvider from dstack._internal.core.backends.base.authorized_keys import build_authorized_keys from dstack._internal.core.backends.base.backend import Compute from dstack._internal.core.backends.base.compute import ( - ComputeWithAllOffersCached, - ComputeWithGroupProvisioningSupport, - ComputeWithMultinodeSupport, + ComputeWithFilteredOffersCached, ComputeWithResourceListingSupport, ComputeWithVolumeSupport, generate_unique_instance_name, @@ -19,8 +19,7 @@ get_job_provider_ref, parse_provider_ref_from_name, ) -from dstack._internal.core.backends.base.models import JobConfiguration -from dstack._internal.core.backends.base.offers import get_catalog_offers +from dstack._internal.core.backends.base.offers import OfferDiskFitter, get_catalog_offers 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 @@ -31,8 +30,7 @@ OwnerType, ResourceListing, ) -from dstack._internal.core.models.common import CoreModel, RegistryAuth, validate_extra_ignore -from dstack._internal.core.models.compute_groups import ComputeGroup, ComputeGroupProvisioningData +from dstack._internal.core.models.common import RegistryAuth from dstack._internal.core.models.instances import ( InstanceAvailability, InstanceConfiguration, @@ -56,26 +54,18 @@ CONTAINER_REGISTRY_AUTH_CLEANUP_INTERVAL = 60 * 60 * 24 # 24 hour -# Runpod does not seem to have any limits on the disk size. +# GPU pods do not seem to have any limits on the container disk size. CONFIGURABLE_DISK_SIZE = Range[Memory](min=Memory.parse("1GB"), max=None) -# gpuhunt, as of 0.1.30, builds CPU instance type names as +# gpuhunt builds CPU instance type names as # {CPU flavor (aka type) identifier}-{vCPU count}-{memory in GB}, e.g., cpu3c-2-4 -# The deprecated GraphQL API (used by old dstack servers) accepts the whole string as -# `instanceId` field; REST API v2, which we currently use, accepts separate `id` and `vcpuCount` -# fields (memory is inferred) +# REST API v2 accepts separate `id` and `vcpuCount` fields (memory is inferred) CPU_INSTANCE_ID_REGEX = re.compile(r"(?P.+)-(?P\d+)-(?P\d+)") -class RunpodOfferBackendData(CoreModel): - pod_counts: Optional[list[int]] = None - - class RunpodCompute( - ComputeWithAllOffersCached, + ComputeWithFilteredOffersCached, ComputeWithVolumeSupport, - ComputeWithMultinodeSupport, - ComputeWithGroupProvisioningSupport, ComputeWithResourceListingSupport, Compute, ): @@ -85,44 +75,30 @@ def __init__(self, config: RunpodConfig): super().__init__() self.config = config self.api_client = RunpodApiClient(config.creds.api_key) + self.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) + self.catalog.add_provider(RunpodProvider(api_key=config.creds.api_key)) - def get_all_offers_with_availability( - self, unallocated_resources: bool + def get_offers_by_requirements( + self, requirements: Requirements, full_offers: bool, unallocated_resources: bool ) -> List[InstanceOfferWithAvailability]: + # Offers depend on requirements: the catalog lists data centers with hosts that fit + # the required vCPU and RAM and reports the minimum vCPU and RAM of such hosts offers = get_catalog_offers( backend=BackendType.RUNPOD, locations=self.config.regions or None, - requirements=None, - extra_filter=lambda o: _is_secure_cloud(o.region) or self.config.allow_community_cloud, + requirements=requirements, + catalog=self.catalog, + check_disk=False, ) - offers = [ - offer.with_availability(availability=InstanceAvailability.AVAILABLE) - for offer in offers - ] - return offers - - def get_offer_disk_size_range( - self, offer: InstanceOfferWithAvailability - ) -> Optional[Range[Memory]]: - if len(offer.instance.resources.gpus) > 0: - return CONFIGURABLE_DISK_SIZE - # For Runpod CPU offers, gpuhunt disk is the per-flavor max. - return Range[Memory]( - min=Memory.parse("1GB"), - max=Memory(offer.instance.resources.disk.size_mib / 1024), - ) - - def get_offers_post_filter( - self, requirements: Requirements - ) -> Optional[Callable[[InstanceOfferWithAvailability], bool]]: - def offers_post_filter(offer: InstanceOfferWithAvailability) -> bool: - pod_counts = _get_offer_pod_counts(offer) - is_cluster_offer = len(pod_counts) > 0 and any(pc != 1 for pc in pod_counts) - if requirements.multinode: - return is_cluster_offer - return not is_cluster_offer - - return offers_post_filter + disk_fitter = OfferDiskFitter(requirements) + offers_with_availability = [] + for offer in offers: + # The catalog only lists data centers where the offer is available + offer = offer.with_availability(availability=InstanceAvailability.AVAILABLE) + fitted_offer = disk_fitter.fit(offer, _get_offer_disk_size_range(offer)) + if fitted_offer is not None: + offers_with_availability.append(fitted_offer) + return offers_with_availability def run_job( self, @@ -166,22 +142,17 @@ def run_job( offer_memory_gib = round(instance_offer.instance.resources.memory_mib / 1024) offer_disk_gib = round(instance_offer.instance.resources.disk.size_mib / 1024) - is_gpu_offer = offer_gpu_count > 0 - is_secure_cloud = _is_secure_cloud(instance_offer.region) - if not is_gpu_offer and not is_secure_cloud: - raise ComputeError("Runpod CPU offers are only supported in secure cloud regions") - gpu_type_id: Optional[str] = None gpu_count: Optional[int] = None min_cpu_count_per_gpu: Optional[int] = None min_memory_in_gb_per_gpu: Optional[int] = None cpu_type_id: Optional[str] = None cpu_count: Optional[int] = None - if is_gpu_offer: + if offer_gpu_count > 0: gpu_type_id = instance_offer.instance.name gpu_count = offer_gpu_count - # Offer resources are host totals. Round down, since these are lower bounds, and - # rounding up may exclude the host the offer is based on + # Offer resources are the minimum host totals that fit the requirements. + # Round down, since rounding up may exclude the hosts the offer is based on min_cpu_count_per_gpu = offer_cpu_count // gpu_count min_memory_in_gb_per_gpu = offer_memory_gib // gpu_count else: @@ -192,55 +163,27 @@ def run_job( job.job_spec.registry_auth ) - if is_secure_cloud: - # API v2 is used by default; its unified method supports both CPU and GPU pods - pod = self.api_client.create_pod( - name=pod_name, - cloud="SECURE", - data_center_ids=[instance_offer.region], - gpu_type_id=gpu_type_id, - gpu_count=gpu_count, - min_cpu_count_per_gpu=min_cpu_count_per_gpu, - min_memory_in_gb_per_gpu=min_memory_in_gb_per_gpu, - cpu_type_id=cpu_type_id, - cpu_count=cpu_count, - container_disk_in_gb=offer_disk_gib, - network_volume_id=network_volume_id, - volume_mount_path=volume_mount_path, - image_name=job.job_spec.image_name, - container_registry_credentials_id=container_registry_credentials_id, - entrypoint=["/bin/sh"], - cmd=["-c", " && ".join(get_docker_commands(authorized_keys))], - ports=[f"{DSTACK_RUNNER_SSH_PORT}/tcp"], - env={"RUNPOD_POD_USER": "0"}, - ) - instance_id = pod["id"] - else: - # Deprecated GraphQL API is used for Community Cloud, as API v2 does not support - # country codes - assert gpu_type_id is not None - assert gpu_count is not None - resp = self.api_client.create_gpu_pod_graphql( - name=pod_name, - cloud_type="COMMUNITY", - data_center_id=None, - country_code=instance_offer.region, - bid_per_gpu=None, - support_public_ip=True, - gpu_type_id=gpu_type_id, - gpu_count=gpu_count, - min_vcpu_count=offer_cpu_count, - min_memory_in_gb=offer_memory_gib, - container_disk_in_gb=offer_disk_gib, - network_volume_id=network_volume_id, - volume_mount_path=volume_mount_path, - image_name=job.job_spec.image_name, - container_registry_auth_id=container_registry_credentials_id, - docker_args=_get_docker_args(authorized_keys), - ports=f"{DSTACK_RUNNER_SSH_PORT}/tcp", - env={"RUNPOD_POD_USER": "0"}, - ) - instance_id = resp["id"] + pod = self.api_client.create_pod( + name=pod_name, + cloud="SECURE", + data_center_ids=[instance_offer.region], + gpu_type_id=gpu_type_id, + gpu_count=gpu_count, + min_cpu_count_per_gpu=min_cpu_count_per_gpu, + min_memory_in_gb_per_gpu=min_memory_in_gb_per_gpu, + cpu_type_id=cpu_type_id, + cpu_count=cpu_count, + container_disk_in_gb=offer_disk_gib, + network_volume_id=network_volume_id, + volume_mount_path=volume_mount_path, + image_name=job.job_spec.image_name, + container_registry_credentials_id=container_registry_credentials_id, + entrypoint=["/bin/sh"], + cmd=["-c", " && ".join(get_docker_commands(authorized_keys))], + ports=[f"{DSTACK_RUNNER_SSH_PORT}/tcp"], + env={"RUNPOD_POD_USER": "0"}, + ) + instance_id = pod["id"] if ( self._last_cleanup_time is None @@ -273,109 +216,6 @@ def run_job( backend_data=None, ) - def run_jobs( - self, - run: Run, - job_configurations: List[JobConfiguration], - instance_offer: InstanceOfferWithAvailability, - project_name: str, - project_ssh_public_key: str, - project_ssh_private_key: str, - placement_group: Optional[PlacementGroup], - requirements: Requirements, - extra_authorized_keys: list[str], - ) -> ComputeGroupProvisioningData: - master_job_configuration = job_configurations[0] - master_job = master_job_configuration.job - if master_job.job_spec.registry_auth is not None: - raise ComputeError("Runpod clusters with private registries are not supported") - master_job_volumes = master_job_configuration.volumes - all_volumes_names = set(v.name for jc in job_configurations for v in jc.volumes) - instance_config = InstanceConfiguration( - project_name=project_name, - instance_name=get_job_instance_name(run, master_job), - ssh_keys=[], - user=run.user, - ) - - cluster_name = generate_unique_instance_name( - instance_config, max_length=MAX_RESOURCE_NAME_LEN - ) - authorized_keys = build_authorized_keys(project_ssh_public_key, extra_authorized_keys) - disk_size = round(instance_offer.instance.resources.disk.size_mib / 1024) - - network_volume_id = None - volume_mount_path = None - if len(master_job_volumes) > 1: - raise ComputeError("Mounting more than one network volume is not supported in runpod") - if len(all_volumes_names) > 1: - raise ComputeError( - "Mounting different volumes to different jobs is not supported in runpod" - ) - if len(master_job_volumes) == 1: - network_volume_id = master_job_volumes[0].volume_id - volume_mount_path = run.run_spec.configuration.volumes[0].path - - offer_pod_counts = _get_offer_pod_counts(instance_offer) - pod_count = len(job_configurations) - gpu_count = len(instance_offer.instance.resources.gpus) - data_center_id = instance_offer.region - - if pod_count not in offer_pod_counts: - raise ComputeError( - f"Failed to provision {pod_count} pods. Available pod counts: {offer_pod_counts}" - ) - - cluster = self.api_client.create_cluster( - name=cluster_name, - cluster_type="TRAINING", - gpu_type_id=instance_offer.instance.name, - gpu_count_per_pod=gpu_count, - pod_count=pod_count, - data_center_ids=[data_center_id], - container_disk_in_gb=disk_size, - network_volume_id=network_volume_id, - volume_mount_path=volume_mount_path, - image_name=master_job.job_spec.image_name, - entrypoint=["/bin/sh"], - cmd=["-c", " && ".join(get_docker_commands(authorized_keys))], - ports=[f"{DSTACK_RUNNER_SSH_PORT}/tcp"], - env={"RUNPOD_POD_USER": "0"}, - ) - try: - pods = self.api_client.list_cluster_pods(cluster["id"]) - if len(pods) != pod_count: - raise ComputeError( - f"Expected {pod_count} pods in cluster {cluster['id']}, got {len(pods)}" - ) - except Exception: - # dstack does not track the cluster until run_jobs() returns - self._delete_cluster_after_failed_provisioning(cluster["id"]) - raise - - jpds = [ - JobProvisioningData( - backend=instance_offer.backend, - instance_type=instance_offer.instance, - instance_id=pod["id"], - hostname=None, - # May not be assigned yet, see update_provisioning_data() - internal_ip=_get_pod_cluster_ip(pod), - region=instance_offer.region, - price=instance_offer.price, - username="root", - dockerized=False, - ) - for pod in pods - ] - return ComputeGroupProvisioningData( - compute_group_id=cluster["id"], - compute_group_name=cluster["name"], - backend=BackendType.RUNPOD, - region=instance_offer.region, - job_provisioning_datas=jpds, - ) - def terminate_instance( self, instance_id: str, region: str, backend_data: Optional[str] = None ): @@ -383,12 +223,6 @@ def terminate_instance( if not terminated: logger.debug("The instance %s not found. Skipping deletion.", instance_id) - def terminate_compute_group(self, compute_group: ComputeGroup): - cluster_id = compute_group.provisioning_data.compute_group_id - deleted = self.api_client.delete_cluster(cluster_id) - if not deleted: - logger.debug("The cluster %s not found. Skipping deletion.", cluster_id) - def update_provisioning_data( self, provisioning_data: JobProvisioningData, @@ -402,13 +236,6 @@ def update_provisioning_data( ports = pod["runtime"].get("ports") if ports is None: return - if "cluster" in pod: - # The job copies the instance's provisioning data only until the hostname is set, - # so the internal IP must be set no later than the hostname - internal_ip = _get_pod_cluster_ip(pod) - if internal_ip is None: - return - provisioning_data.internal_ip = internal_ip for port in ports: if port.get("private") == DSTACK_RUNNER_SSH_PORT: provisioning_data.hostname = port.get("ip") @@ -513,25 +340,15 @@ def _clean_stale_container_registry_credentials(self) -> None: except Exception: break - def _delete_cluster_after_failed_provisioning(self, cluster_id: str) -> None: - try: - self.api_client.delete_cluster(cluster_id) - except Exception as e: - logger.error( - "Failed to delete cluster %s after failed provisioning." - " Please delete it manually to avoid unexpected charges. Error: %r", - cluster_id, - e, - exc_info=not isinstance(e, BackendError), - ) - -def _get_docker_args(authorized_keys: List[str]) -> str: - commands = get_docker_commands(authorized_keys) - command = " && ".join(commands) - docker_args = {"cmd": [command], "entrypoint": ["/bin/sh", "-c"]} - docker_args_escaped = json.dumps(json.dumps(docker_args)).strip('"') - return docker_args_escaped +def _get_offer_disk_size_range(offer: InstanceOfferWithAvailability) -> Range[Memory]: + if len(offer.instance.resources.gpus) > 0: + return CONFIGURABLE_DISK_SIZE + # For Runpod CPU offers, gpuhunt disk is the per-flavor max. + return Range[Memory]( + min=Memory.parse("1GB"), + max=Memory(offer.instance.resources.disk.size_mib / 1024), + ) def _get_volume_price(size: int) -> float: @@ -540,20 +357,6 @@ def _get_volume_price(size: int) -> float: return 0.05 * size -def _is_secure_cloud(region: str) -> bool: - """ - Secure cloud regions are datacenter IDs: CA-MTL-1, EU-NL-1, etc. - Community cloud regions are country codes: CA, NL, etc. - """ - return "-" in region - - -def _get_offer_pod_counts(offer: InstanceOfferWithAvailability) -> list[int]: - backend_data = validate_extra_ignore(RunpodOfferBackendData, offer.backend_data) - pod_counts = backend_data.pod_counts or [] - return pod_counts - - def _get_cpu_type_id(offer: InstanceOfferWithAvailability) -> str: match = CPU_INSTANCE_ID_REGEX.fullmatch(offer.instance.name) if match is None: @@ -561,13 +364,6 @@ def _get_cpu_type_id(offer: InstanceOfferWithAvailability) -> str: return match.group("flavor_id") -def _get_pod_cluster_ip(pod: V2Pod) -> Optional[str]: - cluster = pod.get("cluster") - if cluster is None: - return None - return cluster.get("ip") - - def _parse_pod_created_at(pod: V2Pod) -> Optional[datetime]: try: return parse_datetime(pod["createdAt"]) diff --git a/src/dstack/_internal/core/backends/runpod/models.py b/src/dstack/_internal/core/backends/runpod/models.py index 7bc11c2818..bfdb60e33e 100644 --- a/src/dstack/_internal/core/backends/runpod/models.py +++ b/src/dstack/_internal/core/backends/runpod/models.py @@ -4,8 +4,6 @@ from dstack._internal.core.models.common import CoreModel -RUNPOD_COMMUNITY_CLOUD_DEFAULT = False - class RunpodAPIKeyCreds(CoreModel): type: Literal["api_key"] = "api_key" @@ -26,11 +24,13 @@ class RunpodBackendConfig(CoreModel): Optional[bool], Field( description=( - "Whether Community Cloud offers can be suggested in addition to Secure Cloud." - f" Defaults to `{str(RUNPOD_COMMUNITY_CLOUD_DEFAULT).lower()}`" + "Deprecated and ignored since 0.22.10." + " Only Secure Cloud offers are suggested." + " Will be removed in future versions" ) ), ] = None + """`community_cloud` is kept so that existing configs that set it still load.""" class RunpodBackendConfigWithCreds(RunpodBackendConfig): @@ -46,9 +46,3 @@ class RunpodStoredConfig(RunpodBackendConfig): class RunpodConfig(RunpodStoredConfig): creds: AnyRunpodCreds - - @property - def allow_community_cloud(self) -> bool: - if self.community_cloud is not None: - return self.community_cloud - return RUNPOD_COMMUNITY_CLOUD_DEFAULT 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 315a57cbdd..d2bf7cba5f 100644 --- a/src/tests/_internal/core/backends/runpod/test_api_client.py +++ b/src/tests/_internal/core/backends/runpod/test_api_client.py @@ -171,13 +171,6 @@ def test_terminate_pod(self, requests_mock): assert _client().terminate_pod("pod-1") is False - def test_delete_cluster(self, requests_mock): - requests_mock.delete( - f"{API_V2_URL}/clusters/cluster-1", status_code=404, json=_error(404, "-") - ) - - assert _client().delete_cluster("cluster-1") is False - def test_delete_network_volume(self, requests_mock): requests_mock.delete( f"{API_V2_URL}/network-volumes/vol-1", status_code=404, json=_error(404, "-") diff --git a/src/tests/_internal/core/backends/runpod/test_compute.py b/src/tests/_internal/core/backends/runpod/test_compute.py index 8173e82ff3..dc68251c9e 100644 --- a/src/tests/_internal/core/backends/runpod/test_compute.py +++ b/src/tests/_internal/core/backends/runpod/test_compute.py @@ -2,16 +2,19 @@ from typing import Optional from unittest.mock import MagicMock, patch -import pytest +import gpuhunt +from gpuhunt.providers.base import OnlineProvider from dstack._internal.core.backends.base.compute import parse_provider_ref_from_name 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.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.instances import ( + InstanceAvailability, + InstanceOfferWithAvailability, +) from dstack._internal.core.models.resources import ResourcesSpec from dstack._internal.core.models.runs import JobProvisioningData, Requirements from dstack._internal.server.testing.common import ( @@ -46,12 +49,6 @@ def _gpu_offer( ) -def _cluster_offer(pod_counts: list[int]) -> InstanceOfferWithAvailability: - offer = _gpu_offer(gpu_count=8, cpu_count=128, memory_gib=1024) - offer.backend_data = {"pod_counts": pod_counts} - return offer - - def _job() -> MagicMock: job = MagicMock() job.job_spec.job_name = "test-job-0" @@ -89,48 +86,13 @@ def _run_job( ) -def _run_jobs(compute: RunpodCompute, offer: InstanceOfferWithAvailability, job_count: int): - job_configurations = [] - for _ in range(job_count): - job_configuration = MagicMock() - job_configuration.job = _job() - job_configuration.volumes = [] - job_configurations.append(job_configuration) - with patch( - "dstack._internal.core.backends.runpod.compute.get_docker_commands", - return_value=["echo hi"], - ): - return compute.run_jobs( - run=_run(), - job_configurations=job_configurations, - instance_offer=offer, - project_name="main", - project_ssh_public_key=PROJECT_SSH_PUBLIC_KEY, - project_ssh_private_key="private-key", - placement_group=None, - requirements=Requirements(resources=ResourcesSpec(), multinode=True), - extra_authorized_keys=[], - ) - - -def _pod( - pod_id: str = "pod-1", - *, - ports: Optional[list[dict]] = None, - cluster_ip: Optional[str] = None, - is_cluster_pod: bool = False, -) -> dict: - pod: dict = { +def _pod(pod_id: str = "pod-1", *, ports: Optional[list[dict]] = None) -> dict: + return { "id": pod_id, "status": "RUNNING", "runtime": None if ports is None else {"ports": ports}, "mounts": {}, } - if is_cluster_pod or cluster_ip is not None: - pod["cluster"] = {"id": "cluster-1", "rank": 0} - if cluster_ip is not None: - pod["cluster"]["ip"] = cluster_ip - return pod SSH_PORTS = [ @@ -139,6 +101,120 @@ def _pod( ] +class _FakeRunpodProvider(OnlineProvider): + NAME = "runpod" + + def __init__(self, items: list[gpuhunt.CatalogItem]): + self.items = items + self.query_filters: list[Optional[gpuhunt.QueryFilter]] = [] + + @classmethod + def from_env(cls) -> "_FakeRunpodProvider": + raise NotImplementedError + + def get( + self, + query_filter: Optional[gpuhunt.QueryFilter] = None, + balance_resources: bool = True, + apply_filter: bool = False, + ) -> list[gpuhunt.CatalogItem]: + self.query_filters.append(query_filter) + return self.items + + +def _gpu_item(location: str = "EU-RO-1") -> gpuhunt.CatalogItem: + return gpuhunt.CatalogItem( + provider="runpod", + instance_name="NVIDIA H100 80GB HBM3", + location=location, + price=4.39, + cpu=16, + memory=251, + gpu_vendor=gpuhunt.AcceleratorVendor.NVIDIA, + gpu_count=1, + gpu_name="H100", + gpu_memory=80, + spot=False, + disk_size=None, + ) + + +def _cpu_item(vcpu: int, max_disk_size: float) -> gpuhunt.CatalogItem: + return gpuhunt.CatalogItem( + provider="runpod", + instance_name=f"cpu3c-{vcpu}-{vcpu * 2}", + location="EU-RO-1", + price=0.03 * vcpu, + cpu=vcpu, + memory=vcpu * 2, + gpu_count=0, + gpu_name=None, + gpu_memory=None, + spot=False, + disk_size=max_disk_size, + ) + + +def _get_offers( + items: list[gpuhunt.CatalogItem], resources: dict, regions: Optional[list[str]] = None +) -> tuple[list[InstanceOfferWithAvailability], _FakeRunpodProvider]: + compute = RunpodCompute(RunpodConfig(creds=RunpodAPIKeyCreds(api_key="test"), regions=regions)) + provider = _FakeRunpodProvider(items) + compute.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False) + compute.catalog.add_provider(provider) + requirements = Requirements(resources=ResourcesSpec.model_validate(resources)) + offers = list(compute.get_offers(requirements, full_offers=False, unallocated_resources=False)) + return offers, provider + + +class TestRunpodComputeGetOffers: + def test_queries_catalog_with_requirements(self): + _, provider = _get_offers( + [], {"cpu": "16..", "memory": "64GB..", "gpu": "H100:2..4", "disk": "50GB"} + ) + + [query_filter] = provider.query_filters + assert query_filter is not None + assert (query_filter.min_cpu, query_filter.min_memory) == (16, 64) + assert (query_filter.min_gpu_count, query_filter.max_gpu_count) == (2, 4) + assert query_filter.gpu_name == ["H100"] + # Disks are fitted by the compute + assert (query_filter.min_disk_size, query_filter.max_disk_size) == (None, None) + + def test_offers_are_available(self): + offers, _ = _get_offers([_gpu_item()], {"gpu": "1"}) + + [offer] = offers + assert offer.availability == InstanceAvailability.AVAILABLE + assert offer.region == "EU-RO-1" + assert (offer.instance.resources.cpus, offer.instance.resources.memory_mib) == ( + 16, + 251 * 1024, + ) + + def test_fits_gpu_offer_disk_to_requirements(self): + offers, _ = _get_offers([_gpu_item()], {"gpu": "1", "disk": "500GB.."}) + + [offer] = offers + assert offer.instance.resources.disk.size_mib == 500 * 1024 + + def test_fits_cpu_offer_disk_to_requirements_within_max_disk_size(self): + items = [_cpu_item(vcpu=2, max_disk_size=20), _cpu_item(vcpu=8, max_disk_size=80)] + + offers, _ = _get_offers(items, {"gpu": 0, "disk": "50GB"}) + + [offer] = offers + assert offer.instance.name == "cpu3c-8-16" + assert offer.instance.resources.disk.size_mib == 50 * 1024 + + def test_filters_by_configured_regions(self): + items = [_gpu_item("EU-RO-1"), _gpu_item("US-KS-2")] + + offers, _ = _get_offers(items, {"gpu": "1"}, regions=["US-KS-2"]) + + assert [o.region for o in offers] == ["US-KS-2"] + + class TestRunpodComputeRunJob: def test_requests_per_gpu_minimums_rounded_down(self): compute, api_client = _compute_with_mocked_api_client() @@ -178,51 +254,27 @@ def test_encodes_provider_ref_in_pod_name(self): pod_name = api_client.create_pod.call_args.kwargs["name"] assert parse_provider_ref_from_name(pod_name) == "abcdef123456" - -class TestRunpodComputeRunJobs: - 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"} - api_client.list_cluster_pods.return_value = [ - _pod("pod-1", cluster_ip="10.65.0.2"), - _pod("pod-2", is_cluster_pod=True), - ] - - cgpd = _run_jobs(compute, _cluster_offer([2, 4]), job_count=2) - - assert cgpd.compute_group_id == "cluster-1" - assert [jpd.instance_id for jpd in cgpd.job_provisioning_datas] == ["pod-1", "pod-2"] - assert [jpd.internal_ip for jpd in cgpd.job_provisioning_datas] == ["10.65.0.2", None] - - def test_deletes_cluster_if_pod_count_mismatch(self): + def test_cpu_offer(self): compute, api_client = _compute_with_mocked_api_client() - api_client.create_cluster.return_value = {"id": "cluster-1", "name": "test"} - api_client.list_cluster_pods.return_value = [_pod("pod-1", is_cluster_pod=True)] - - with pytest.raises(ComputeError, match="Expected 2 pods"): - _run_jobs(compute, _cluster_offer([2, 4]), job_count=2) - - api_client.delete_cluster.assert_called_once_with("cluster-1") - - def test_deletes_cluster_if_listing_pods_fails(self): - compute, api_client = _compute_with_mocked_api_client() - api_client.create_cluster.return_value = {"id": "cluster-1", "name": "test"} - error = RunpodV2ClientError(status=429, title="Too Many Requests", detail="-") - api_client.list_cluster_pods.side_effect = error - - with pytest.raises(RunpodV2ClientError): - _run_jobs(compute, _cluster_offer([2, 4]), job_count=2) - - api_client.delete_cluster.assert_called_once_with("cluster-1") + api_client.create_pod.return_value = {"id": "pod-1"} + offer = get_instance_offer_with_availability( + backend=BackendType.RUNPOD, + region="EU-RO-1", + cpu_count=16, + memory_gib=32, + disk_gib=50, + instance_type="cpu3c-16-32", + ) - def test_raises_original_error_if_cluster_deletion_fails(self): - compute, api_client = _compute_with_mocked_api_client() - api_client.create_cluster.return_value = {"id": "cluster-1", "name": "test"} - api_client.list_cluster_pods.return_value = [] - api_client.delete_cluster.side_effect = RuntimeError("delete failed") + _run_job(compute, offer) - with pytest.raises(ComputeError, match="Expected 2 pods"): - _run_jobs(compute, _cluster_offer([2, 4]), job_count=2) + kwargs = api_client.create_pod.call_args.kwargs + assert kwargs["cloud"] == "SECURE" + assert kwargs["data_center_ids"] == ["EU-RO-1"] + assert kwargs["cpu_type_id"] == "cpu3c" + assert kwargs["cpu_count"] == 16 + assert kwargs["container_disk_in_gb"] == 50 + assert kwargs["gpu_type_id"] is None class TestRunpodComputeUpdateProvisioningData: @@ -252,31 +304,6 @@ def test_waits_for_runtime(self): assert jpd.hostname is None - def test_cluster_pod_waits_for_cluster_ip(self): - compute, api_client = _compute_with_mocked_api_client() - api_client.get_pod.return_value = _pod(ports=SSH_PORTS, is_cluster_pod=True) - jpd = get_job_provisioning_data( - backend=BackendType.RUNPOD, hostname=None, internal_ip=None - ) - - self._update(compute, jpd) - - assert jpd.hostname is None - assert jpd.internal_ip is None - - def test_cluster_pod_sets_internal_ip(self): - compute, api_client = _compute_with_mocked_api_client() - api_client.get_pod.return_value = _pod(ports=SSH_PORTS, cluster_ip="10.65.0.3") - jpd = get_job_provisioning_data( - backend=BackendType.RUNPOD, hostname=None, internal_ip=None - ) - - self._update(compute, jpd) - - assert jpd.hostname == "203.0.113.10" - assert jpd.ssh_port == 40022 - assert jpd.internal_ip == "10.65.0.3" - def _listed_pod( pod_id: str, diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py index d250daffa0..fc30d4852e 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py @@ -2426,7 +2426,7 @@ async def test_provisions_compute_group( waiting_master_job=True, ) - offer = get_instance_offer_with_availability(backend=BackendType.RUNPOD) + offer = get_instance_offer_with_availability(backend=BackendType.SLURM) backend_mock = Mock() with patch( "dstack._internal.server.services.backends.cache.lease_project_backends", @@ -2434,12 +2434,12 @@ async def test_provisions_compute_group( ): compute_mock = Mock(spec=ComputeMockSpec) backend_mock.compute.return_value = compute_mock - backend_mock.TYPE = BackendType.RUNPOD + backend_mock.TYPE = BackendType.SLURM compute_mock.get_offers.return_value = [offer] compute_mock.run_jobs.return_value = get_compute_group_provisioning_data( job_provisioning_datas=[ - get_job_provisioning_data(dockerized=True, backend=BackendType.RUNPOD), - get_job_provisioning_data(dockerized=True, backend=BackendType.RUNPOD), + get_job_provisioning_data(dockerized=True, backend=BackendType.SLURM), + get_job_provisioning_data(dockerized=True, backend=BackendType.SLURM), ] ) @@ -2461,7 +2461,7 @@ async def test_provisions_one_job_node_group_via_run_job( ): """1-node hetero groups use run_job (not run_jobs). - RunPod Instant Clusters reject pod_count=1; Slurm gets node_count=1 from run_job. + Slurm gets node_count=1 from run_job. """ project = await create_project(session=session) user = await create_user(session=session) @@ -2498,7 +2498,7 @@ async def test_provisions_one_job_node_group_via_run_job( waiting_master_job=True, ) - offer = get_instance_offer_with_availability(backend=BackendType.RUNPOD) + offer = get_instance_offer_with_availability(backend=BackendType.SLURM) backend_mock = Mock() with patch( "dstack._internal.server.services.backends.cache.lease_project_backends", @@ -2506,10 +2506,10 @@ async def test_provisions_one_job_node_group_via_run_job( ): compute_mock = Mock(spec=ComputeMockSpec) backend_mock.compute.return_value = compute_mock - backend_mock.TYPE = BackendType.RUNPOD + backend_mock.TYPE = BackendType.SLURM compute_mock.get_offers.return_value = [offer] compute_mock.run_job.return_value = get_job_provisioning_data( - dockerized=True, backend=BackendType.RUNPOD + dockerized=True, backend=BackendType.SLURM ) await _process_job(session=session, worker=worker, job_model=job0) @@ -3090,7 +3090,7 @@ async def test_run_jobs_uses_server_default_registry( waiting_master_job=True, ) - offer = get_instance_offer_with_availability(backend=BackendType.RUNPOD) + offer = get_instance_offer_with_availability(backend=BackendType.SLURM) backend_mock = Mock() with patch( "dstack._internal.server.services.backends.cache.lease_project_backends", @@ -3098,12 +3098,12 @@ async def test_run_jobs_uses_server_default_registry( ): compute_mock = Mock(spec=ComputeMockSpec) backend_mock.compute.return_value = compute_mock - backend_mock.TYPE = BackendType.RUNPOD + backend_mock.TYPE = BackendType.SLURM compute_mock.get_offers.return_value = [offer] compute_mock.run_jobs.return_value = get_compute_group_provisioning_data( job_provisioning_datas=[ - get_job_provisioning_data(dockerized=False, backend=BackendType.RUNPOD), - get_job_provisioning_data(dockerized=False, backend=BackendType.RUNPOD), + get_job_provisioning_data(dockerized=False, backend=BackendType.SLURM), + get_job_provisioning_data(dockerized=False, backend=BackendType.SLURM), ] )