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
1 change: 1 addition & 0 deletions frontend/src/types/backend.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ declare type TBackendType =
| 'kubernetes'
| 'lambda'
| 'lium'
| 'massedcompute'
| 'local'
| 'nebius'
| 'remote'
Expand Down
22 changes: 22 additions & 0 deletions mkdocs/docs/concepts/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,28 @@ projects:

</div>

### MassedCompute

Create a full-access API key in [MassedCompute settings](https://vm-docs.massedcompute.com/docs/settings/api-settings)
and configure the backend in the server configuration.

<div editor-title="~/.dstack/server/config.yml">

```yaml
projects:
- name: main
backends:
- type: massedcompute
creds:
type: api_key
api_key: YOUR_MASSEDCOMPUTE_API_KEY
```

</div>

The backend supports single-node, on-demand CPU and GPU VMs.
MassedCompute chooses the region for each VM.

### Vultr

Log into your [Vultr](https://www.vultr.com/) account, click `Account` in the sidebar, select `API`, find the `Personal Access Token` panel and click the `Enable API` button. In the `Access Control` panel, allow API requests from all addresses or from the subnet where your `dstack` server is deployed.
Expand Down
17 changes: 17 additions & 0 deletions mkdocs/docs/reference/server/config.yml.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,23 @@ to configure [backends](../../concepts/backends.md) and other [server-level sett
type:
required: true

##### `projects[n].backends[type=massedcompute]` { #massedcompute data-toc-label="massedcompute" }

#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeBackendConfigWithCreds
overrides:
show_root_heading: false
type:
required: true
item_id_prefix: massedcompute-

###### `projects[n].backends[type=massedcompute].creds` { #massedcompute-creds data-toc-label="creds" }

#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeAPIKeyCreds
overrides:
show_root_heading: false
type:
required: true

##### `projects[n].backends[type=nebius]` { #nebius data-toc-label="nebius" }

#SCHEMA# dstack._internal.core.backends.nebius.models.NebiusBackendFileConfigWithCreds
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ dependencies = [
"python-multipart>=0.0.31",
"filelock",
"psutil",
"gpuhunt==0.1.37",
"gpuhunt==0.1.38",
"argcomplete>=3.5.0",
"ignore-python>=0.2.0",
"apscheduler<4",
Expand Down
7 changes: 7 additions & 0 deletions src/dstack/_internal/core/backends/configurators.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@
except ImportError:
pass

try:
from dstack._internal.core.backends.massedcompute.configurator import MassedComputeConfigurator

_CONFIGURATOR_CLASSES.append(MassedComputeConfigurator)
except ImportError:
pass

try:
from dstack._internal.core.backends.nebius.configurator import (
NebiusConfigurator,
Expand Down
Empty file.
126 changes: 126 additions & 0 deletions src/dstack/_internal/core/backends/massedcompute/api_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
from typing import Optional, TypeVar, Union
from urllib.parse import quote
from uuid import UUID

import requests
from pydantic import AwareDatetime, Field, ValidationError
from typing_extensions import TypedDict

from dstack._internal.core.errors import BackendAuthError, ComputeError
from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore

API_URL = "https://vm.massedcompute.com/api/v1"
_T = TypeVar("_T", bound=CoreModel)


class MassedComputeInstance(CoreModel):
uuid: str
name: str
status: str
ip: Optional[str] = None
username: Optional[str] = None
os_booted: bool = False
created: Optional[AwareDatetime] = None


class _Instances(CoreModel):
instances: list[MassedComputeInstance] = Field(alias="runningInstances")


class _LaunchResponse(CoreModel):
response: UUID


class _LaunchRequest(TypedDict, closed=True):
instanceName: str
productName: str
imageId: int
regionName: str
command: str
sshKeys: list[str]


class _TerminateRequest(TypedDict, closed=True):
instanceUuids: list[str]


class MassedComputeAPIClient:
def __init__(self, api_key: str):
self.api_key = api_key

def validate_api_key(self) -> bool:
try:
self._request("POST", "/account/token/validation")
except BackendAuthError:
return False
return True

def launch(self, name: str, product: str, command: str) -> str:
"""Launch once using a unique name. If the response is lost, look up that name.

Return the VM ID only when creation is confirmed. If the VM is not yet visible,
propagate the launch error. Its name still lets orphan cleanup find it later.
"""
payload: _LaunchRequest = {
"instanceName": name,
"productName": product,
"imageId": 84, # Ubuntu Server 22.04 w/ drivers
"regionName": "any",
"sshKeys": [],
"command": command,
}
try:
response = self._request("POST", "/instance/launch", payload)
return str(_parse_response(_LaunchResponse, response).response)
except ComputeError:
matches = [vm.uuid for vm in self.list_instances() if vm.name == name]
if len(matches) != 1:
raise
return matches[0]

def list_instances(self) -> list[MassedComputeInstance]:
return _parse_response(_Instances, self._request("GET", "/instance")).instances

def get_instance(self, instance_id: str) -> Optional[MassedComputeInstance]:
response = self._request("GET", "/instance/" + quote(instance_id, safe=""))
# The detail endpoint returns the same array as the list endpoint, empty after deletion.
instances = _parse_response(_Instances, response).instances
if not instances:
return None
if len(instances) != 1 or instances[0].uuid != instance_id:
raise ComputeError("MassedCompute returned an unexpected instance ID")
return instances[0]

def terminate(self, instance_id: str) -> None:
self._request("POST", "/instance/terminate", {"instanceUuids": [instance_id]})

def _request(
self,
method: str,
path: str,
payload: Optional[Union[_LaunchRequest, _TerminateRequest]] = None,
) -> requests.Response:
try:
response = requests.request(
method,
API_URL + path,
json=payload,
timeout=30,
allow_redirects=False, # A redirect can replay a launch POST.
headers={"Authorization": f"Bearer {self.api_key}"},
)
except requests.RequestException as e:
raise ComputeError(f"MassedCompute {method} {path}: {type(e).__name__}") from None
if response.status_code == 401:
raise BackendAuthError("Invalid MassedCompute API key")
if not 200 <= response.status_code < 300:
raise ComputeError(f"MassedCompute {method} {path}: HTTP {response.status_code}")
return response


def _parse_response(model: type[_T], response: requests.Response) -> _T:
try:
return validate_json_extra_ignore(model, response.content)
except ValidationError:
# Instance payloads contain plaintext passwords, including in Pydantic's error inputs.
raise ComputeError("Unexpected response from MassedCompute") from None
16 changes: 16 additions & 0 deletions src/dstack/_internal/core/backends/massedcompute/backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from dstack._internal.core.backends.base.backend import Backend
from dstack._internal.core.backends.massedcompute.compute import MassedComputeCompute
from dstack._internal.core.backends.massedcompute.models import MassedComputeConfig
from dstack._internal.core.models.backends.base import BackendType


class MassedComputeBackend(Backend):
TYPE = BackendType.MASSEDCOMPUTE
COMPUTE_CLASS = MassedComputeCompute

def __init__(self, config: MassedComputeConfig):
self.config = config
self._compute = MassedComputeCompute(self.config)

def compute(self) -> MassedComputeCompute:
return self._compute
137 changes: 137 additions & 0 deletions src/dstack/_internal/core/backends/massedcompute/compute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import shlex
from typing import Optional

import gpuhunt
from gpuhunt.providers.massedcompute import MassedComputeProvider

from dstack._internal.core.backends.base.authorized_keys import get_add_authorized_keys_script
from dstack._internal.core.backends.base.compute import (
Compute,
ComputeWithAllOffersCached,
ComputeWithCreateInstanceSupport,
ComputeWithInstanceVolumesSupport,
ComputeWithPrivilegedSupport,
ComputeWithResourceListingSupport,
generate_unique_instance_name,
get_shim_commands,
parse_provider_ref_from_name,
)
from dstack._internal.core.backends.base.offers import get_catalog_offers
from dstack._internal.core.backends.massedcompute.api_client import MassedComputeAPIClient
from dstack._internal.core.backends.massedcompute.models import MassedComputeConfig
from dstack._internal.core.errors import NotYetTerminated, ProvisioningError
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.backends.orphans import (
ListedResourceGroup,
OwnerType,
ResourceListing,
)
from dstack._internal.core.models.instances import (
InstanceAvailability,
InstanceConfiguration,
InstanceOfferWithAvailability,
)
from dstack._internal.core.models.placement import PlacementGroup
from dstack._internal.core.models.runs import JobProvisioningData


class MassedComputeCompute(
ComputeWithAllOffersCached,
ComputeWithCreateInstanceSupport,
ComputeWithInstanceVolumesSupport,
ComputeWithPrivilegedSupport,
ComputeWithResourceListingSupport,
Compute,
):
def __init__(self, config: MassedComputeConfig):
super().__init__()
self.api_client = MassedComputeAPIClient(config.creds.api_key)
self.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False)
self.catalog.add_provider(MassedComputeProvider(config.creds.api_key))

def get_all_offers_with_availability(
self, unallocated_resources: bool
) -> list[InstanceOfferWithAvailability]:
offers = get_catalog_offers(backend=BackendType.MASSEDCOMPUTE, catalog=self.catalog)
return [
offer.with_availability(availability=InstanceAvailability.AVAILABLE)
for offer in offers
]

def create_instance(
self,
instance_offer: InstanceOfferWithAvailability,
instance_config: InstanceConfiguration,
placement_group: Optional[PlacementGroup],
) -> JobProvisioningData:
name = generate_unique_instance_name(instance_config, with_provider_ref=True)
# The image's SSH user is case-sensitive. The startup command runs as root.
key_script = get_add_authorized_keys_script(instance_config.get_public_keys())
install_keys = shlex.join(["sudo", "-H", "-u", "Ubuntu", "sh", "-c", key_script])
command = " && ".join(
[install_keys, *get_shim_commands(arch=instance_offer.instance.resources.cpu_arch)]
)
instance_id = self.api_client.launch(name, instance_offer.instance.name, command)
return JobProvisioningData(
backend=instance_offer.backend,
instance_type=instance_offer.instance,
instance_id=instance_id,
hostname=None,
internal_ip=None,
region=instance_offer.region,
price=instance_offer.price,
username="Ubuntu",
ssh_port=22,
dockerized=True,
ssh_proxy=None,
backend_data=None,
)

def update_provisioning_data(
self,
provisioning_data: JobProvisioningData,
project_ssh_public_key: str,
project_ssh_private_key: str,
) -> None:
instance = self.api_client.get_instance(provisioning_data.instance_id)
if instance is None:
return
if instance.status.lower() == "stopped":
raise ProvisioningError("MassedCompute instance stopped during provisioning")
if instance.os_booted and instance.ip and instance.username:
provisioning_data.hostname = instance.ip
provisioning_data.username = instance.username

def terminate_instance(
self, instance_id: str, region: str, backend_data: Optional[str] = None
) -> None:
instance = self.api_client.get_instance(instance_id)
if instance is None:
return
if instance.status.lower() not in {"terminating", "deleting"}:
self.api_client.terminate(instance_id)
raise NotYetTerminated(f"Waiting for MassedCompute instance {instance_id} to terminate")

def list_resource_groups(self) -> ResourceListing:
groups = []
for instance in self.api_client.list_instances():
provider_ref = parse_provider_ref_from_name(instance.name)
if provider_ref is None or instance.status.lower() in {"terminating", "deleting"}:
continue
groups.append(
ListedResourceGroup(
backend=BackendType.MASSEDCOMPUTE,
owner_type=OwnerType.INSTANCE,
provider_ref=provider_ref,
primary_id=instance.uuid,
region="any",
created_at=instance.created,
description=instance.name,
backend_data=None,
)
)
return ResourceListing(resource_groups=groups)

def delete_resource_group(self, group: ListedResourceGroup) -> None:
if group.primary_id is not None:
self.terminate_instance(group.primary_id, "any")
Loading
Loading