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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion runpod/apps/datacenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,37 @@
class DataCenter(str, Enum):

# north america
CA_MTL_1 = "CA-MTL-1"
CA_MTL_3 = "CA-MTL-3"
CA_MTL_4 = "CA-MTL-4"
US_CA_2 = "US-CA-2"
US_CO_1 = "US-CO-1"
US_GA_2 = "US-GA-2"
US_IL_1 = "US-IL-1"
US_KS_2 = "US-KS-2"
US_MO_1 = "US-MO-1"
US_MO_2 = "US-MO-2"
US_NC_1 = "US-NC-1"
US_NC_2 = "US-NC-2"
US_NE_1 = "US-NE-1"
US_TX_3 = "US-TX-3"
US_WA_1 = "US-WA-1"

# europe
EU_CZ_1 = "EU-CZ-1"
EU_FR_1 = "EU-FR-1"
EU_NL_1 = "EU-NL-1"
EU_RO_1 = "EU-RO-1"
EU_SE_1 = "EU-SE-1"
EUR_IS_1 = "EUR-IS-1"
EUR_IS_3 = "EUR-IS-3"
EUR_IS_4 = "EUR-IS-4"
EUR_NO_1 = "EUR-NO-1"
EUR_NO_2 = "EUR-NO-2"

# asia pacific
AP_IN_1 = "AP-IN-1"
Comment thread
KAJdev marked this conversation as resolved.
Resolved
AP_JP_1 = "AP-JP-1"
Comment thread
KAJdev marked this conversation as resolved.
Resolved

@classmethod
def from_string(cls, value: str) -> "DataCenter":
Expand Down Expand Up @@ -57,8 +75,23 @@ def datacenter_id(value: str) -> str:
return value.strip()


DEFAULT_DATACENTERS: List[DataCenter] = [
DataCenter.US_CA_2,
DataCenter.US_IL_1,
DataCenter.US_KS_2,
DataCenter.US_MO_1,
DataCenter.US_MO_2,
DataCenter.US_NC_2,
DataCenter.US_NE_1,
DataCenter.US_WA_1,
DataCenter.EU_CZ_1,
DataCenter.EU_RO_1,
DataCenter.EUR_NO_1,
]


# datacenters with high cpu serverless stock. storage support is checked
# separately; cpu5c/cpu5g are only stocked in EU-RO-1.
# separately.
CPU3_DATACENTERS: List[DataCenter] = [
DataCenter.EU_CZ_1,
DataCenter.EU_RO_1,
Expand Down
18 changes: 11 additions & 7 deletions runpod/apps/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ def _deployed_endpoint_input(
the environment. binding via flashEnvironmentId is also what makes
hosts deliver the build artifact to this endpoint's workers.
"""
from .datacenter import CPU3_DATACENTERS, CPU5_DATACENTERS, DataCenter
from .datacenter import CPU3_DATACENTERS, CPU5_DATACENTERS, DEFAULT_DATACENTERS
from .images import image_for_spec

from .secret import render_env
Expand Down Expand Up @@ -426,7 +426,7 @@ def _deployed_endpoint_input(
# artifact delivery rides the flash volume (network
# storage); machines outside storage-cluster regions fail
# with "requires network storage" and recycle forever
payload["locations"] = ",".join(dc.value for dc in DataCenter)
payload["locations"] = ",".join(dc.value for dc in DEFAULT_DATACENTERS)
return payload


Expand All @@ -445,8 +445,13 @@ async def reconcile_endpoints(
endpoints (matched by name) are updated in place; endpoints whose
resources disappeared are deleted.
"""
from .volume import VolumeResolver, attach_endpoint_volumes

for handle in app.resources.values():
handle.spec.validate()
if resolver is None:
resolver = VolumeResolver(client)
await resolver.preflight([handle.spec for handle in app.resources.values()])
existing_endpoints = environment.get("endpoints") or []
existing = {e["name"]: e["id"] for e in existing_endpoints}
# updates send the bound template's current name, so redeploying an
Expand All @@ -463,9 +468,7 @@ async def reconcile_endpoints(

from .gpu import needs_gpu_catalog
from .registry import resolve_registry_auth
from .volume import VolumeResolver, attach_endpoint_volumes

resolver = resolver or VolumeResolver(client)
endpoints: Dict[str, str] = {}
for name, handle in sorted(provisionable.items()):
members = None
Expand Down Expand Up @@ -578,6 +581,10 @@ async def deploy_app(
]
await validate_secrets(referenced, api=client)

from .volume import VolumeResolver

resolver = VolumeResolver(client, events=events)
await resolver.preflight([handle.spec for handle in app.resources.values()])
_phase(events, "vendor", f"python {python_version}")
build: BuildResult = build_environment(
app,
Expand All @@ -588,9 +595,6 @@ async def deploy_app(
)
if build.excluded:
manifest["excludedPackages"] = build.excluded
from .volume import VolumeResolver

resolver = VolumeResolver(client, events=events)
await _prepare_task_resources(app, manifest, client, events, resolver=resolver)
_phase(events, "package")
tar_path = package_project(project_root, manifest, env_dir=build.env_dir)
Expand Down
13 changes: 13 additions & 0 deletions runpod/apps/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ async def start(self) -> None:
for name in secret_names(handle.spec.env)
]
await validate_secrets(referenced, api=self.api)
from .volume import VolumeResolver

self._volume_resolver = VolumeResolver(self.api, events=self.events)
await self._volume_resolver.preflight(
[handle.spec for app in self.apps for handle in app.resources.values()]
)
for app in self.apps:
# task targets read the sink off the app at resolve time
app._dev_events = self.events
Expand Down Expand Up @@ -327,6 +333,13 @@ async def refresh(self, apps: List[App]) -> None:
requests execute in fresh processes. added resources are
provisioned, removed ones deleted."""

from .volume import VolumeResolver

if self._volume_resolver is None:
self._volume_resolver = VolumeResolver(self.api, events=self.events)
await self._volume_resolver.preflight(
[handle.spec for app in apps for handle in app.resources.values()]
)
self.generation += 1
self.apps = apps
for app in apps:
Expand Down
81 changes: 38 additions & 43 deletions runpod/apps/placement.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import logging
from typing import Dict, Iterable, List, Optional, Set, Tuple

from .datacenter import DataCenter, datacenter_id
from .datacenter import DEFAULT_DATACENTERS, DataCenter, datacenter_id
from .errors import AppError
from .gpu import GpuGroup
from .utils.client import default_client
Expand Down Expand Up @@ -68,49 +68,39 @@ def __init__(self, api=None):
self._gpu: Dict[Tuple[str, int, str], int] = {}
self._gpu_pod: Dict[Tuple[str, int, str], int] = {}
self._cpu: Dict[Tuple[str, str, bool], int] = {}
self._fetched_gpu: Set[Tuple[str, int]] = set()
self._fetched_gpu_pod: Set[Tuple[str, int]] = set()
self._fetched_cpu: Set[Tuple[str, bool]] = set()
self._fetched: Set[Tuple[StockKey, str]] = set()

async def _client(self):
self._api = default_client(self._api)
return self._api

async def fetch(self, keys: Iterable[StockKey]) -> None:
"""populate stock for the given hardware keys across all datacenters."""
keys = list(keys)
gpu_ids = {
(k[1], k[2])
for k in keys
if k[0] == "gpu" and k[1] != "*" and (k[1], k[2]) not in self._fetched_gpu
}
gpu_pod_ids = {
(k[1], k[2])
for k in keys
if k[0] == "gpu-pod"
and k[1] != "*"
and (k[1], k[2]) not in self._fetched_gpu_pod
}
cpu_ids = {
(k[1], k[0] == "cpu-pod")
for k in keys
if k[0] in ("cpu", "cpu-pod")
and (k[1], k[0] == "cpu-pod") not in self._fetched_cpu
async def fetch(
self, keys: Iterable[StockKey], *, datacenters: Optional[Iterable[str]] = None
) -> None:
"""populate stock for hardware in the default or requested datacenters."""
datacenters = {
datacenter_id(dc)
for dc in (DEFAULT_DATACENTERS if datacenters is None else datacenters)
if DataCenter.is_known(datacenter_id(dc))
}
client = await self._client()
jobs = []
for gpu_id, count in gpu_ids:
self._fetched_gpu.add((gpu_id, count))
for dc in DataCenter.all():
jobs.append(self._fetch_gpu(client, gpu_id, count, dc.value, False))
for gpu_id, count in gpu_pod_ids:
self._fetched_gpu_pod.add((gpu_id, count))
for dc in DataCenter.all():
jobs.append(self._fetch_gpu(client, gpu_id, count, dc.value, True))
for cpu_id, pods in cpu_ids:
self._fetched_cpu.add((cpu_id, pods))
for dc in DataCenter.all():
jobs.append(self._fetch_cpu(client, cpu_id, dc.value, pods))
for key in keys:
kind, hardware, count = key
if kind in ("gpu", "gpu-pod") and hardware == "*":
continue
for dc in datacenters:
if (key, dc) in self._fetched:
continue
self._fetched.add((key, dc))
if kind in ("gpu", "gpu-pod"):
jobs.append(
self._fetch_gpu(client, hardware, count, dc, kind == "gpu-pod")
)
elif kind in ("cpu", "cpu-pod"):
jobs.append(
self._fetch_cpu(client, hardware, dc, kind == "cpu-pod")
)
if jobs:
await asyncio.gather(*jobs)

Expand Down Expand Up @@ -153,20 +143,22 @@ def score(self, key: StockKey, dc: str) -> int:
return self._cpu.get((hw, dc, kind == "cpu-pod"), 0)


def candidates(spec, stock: StockMap) -> Set[str]:
def candidates(spec, stock: StockMap, *, volume_dc: Optional[str] = None) -> Set[str]:
"""datacenters where a resource is schedulable.

hardware needs stock in the DC (any of the resource's acceptable
devices/flavors), intersected with an explicit datacenter pin.
"""
spec.validate()
allowed = {dc.value for dc in DataCenter.all()}
allowed = {dc.value for dc in DEFAULT_DATACENTERS}
if volume_dc is not None and DataCenter.is_known(datacenter_id(volume_dc)):
allowed = {datacenter_id(volume_dc)}
# stock is only queried for built-in datacenters, so an unlisted pin
# cannot be ruled out here; the backend decides whether it schedules
unlisted: Set[str] = set()
if spec.datacenter:
unlisted = {dc for dc in spec.datacenter if not DataCenter.is_known(dc)}
allowed &= set(spec.datacenter)
allowed = {dc for dc in spec.datacenter if DataCenter.is_known(dc)}

keys = _hardware_keys(spec)
if not keys:
Expand Down Expand Up @@ -201,11 +193,14 @@ def solve_placement(
and every resource's candidate set, ranked maximin: the DC where the
most-constrained resource has the best stock.
"""
per_resource = {spec.name: candidates(spec, stock) for spec in specs}
per_resource = [
(spec.name, candidates(spec, stock, volume_dc=existing_dc or volume_dc))
for spec in specs
]

if existing_dc is not None:
existing_dc = datacenter_id(existing_dc)
blocked = [name for name, dcs in per_resource.items() if existing_dc not in dcs]
blocked = [name for name, dcs in per_resource if existing_dc not in dcs]
if blocked:
raise PlacementError(
f"volume '{volume_name}' lives in {existing_dc}, but "
Expand All @@ -214,13 +209,13 @@ def solve_placement(
)
return existing_dc

shared = volume_datacenters.intersection(*per_resource.values())
shared = volume_datacenters.intersection(*(dcs for _, dcs in per_resource))
if volume_dc is not None:
shared &= {volume_dc}
if not shared:
lines = [
f" {name:<12} schedulable in: {', '.join(sorted(dcs)) or '(nowhere)'}"
for name, dcs in per_resource.items()
for name, dcs in per_resource
]
raise PlacementError(
f"cannot place volume '{volume_name}': no datacenter can host "
Expand Down
7 changes: 4 additions & 3 deletions runpod/apps/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union

from .errors import InvalidResourceError
from .datacenter import CPU5_DATACENTERS, DataCenter, datacenter_id
from .datacenter import CPU5_DATACENTERS, DEFAULT_DATACENTERS, DataCenter, datacenter_id
from .gpu import GpuGroup, GpuLike, GpuType
from .volume import Volume, normalize_mounts, validate_mounts

Expand Down Expand Up @@ -243,12 +243,13 @@ def validate(self) -> None:
self.cpu
and all(instance.startswith("cpu5") for instance in self.cpu)
and self.datacenter
and all(DataCenter.is_known(dc) for dc in self.datacenter)
and all(dc in DEFAULT_DATACENTERS for dc in self.datacenter)
and not any(dc in CPU5_DATACENTERS for dc in self.datacenter)
):
supported = ", ".join(dc.value for dc in CPU5_DATACENTERS)
raise InvalidResourceError(
f"resource '{self.name}': cpu5 instances are only available in "
f"resource '{self.name}': cpu5 instances in the default datacenter "
"pool are only available in "
f"{supported}, but datacenter is pinned to {', '.join(self.datacenter)}. "
f"include a supported datacenter or remove the datacenter pin"
)
Expand Down
4 changes: 2 additions & 2 deletions runpod/apps/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def _pod_input(spec: ResourceSpec, token: str, task_name: str) -> Dict[str, Any]
else:
# spread across the storage-supported set; a null DC can pin
# repeated deploys to one (possibly broken) machine
from .datacenter import CPU3_DATACENTERS, CPU5_DATACENTERS, DataCenter
from .datacenter import CPU3_DATACENTERS, CPU5_DATACENTERS, DEFAULT_DATACENTERS

if spec.is_cpu:
pool = dict.fromkeys(
Expand All @@ -171,7 +171,7 @@ def _pod_input(spec: ResourceSpec, token: str, task_name: str) -> Dict[str, Any]
)
)
else:
pool = DataCenter.all()
pool = DEFAULT_DATACENTERS
pod["dataCenterIds"] = [dc.value for dc in pool]
if spec.is_cpu:
pod["instanceIds"] = spec.cpu
Expand Down
Loading
Loading