|
| 1 | +import hashlib |
| 2 | +from typing import Any, Dict, List, Optional |
| 3 | + |
| 4 | +import requests |
| 5 | +from gpuhunt.providers.jarvislabs import API_URL, JARVISLABS_REGION_URLS |
| 6 | + |
| 7 | +from dstack._internal.core.errors import ( |
| 8 | + BackendError, |
| 9 | + BackendInvalidCredentialsError, |
| 10 | + NoCapacityError, |
| 11 | +) |
| 12 | + |
| 13 | +TIMEOUT = 120 |
| 14 | + |
| 15 | + |
| 16 | +class JarvisLabsNotFoundError(BackendError): |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class JarvisLabsAPIClient: |
| 21 | + def __init__(self, api_key: str): |
| 22 | + self.api_key = api_key |
| 23 | + |
| 24 | + def validate_api_key(self) -> bool: |
| 25 | + try: |
| 26 | + self.get_user_info() |
| 27 | + except BackendInvalidCredentialsError: |
| 28 | + return False |
| 29 | + return True |
| 30 | + |
| 31 | + def get_user_info(self) -> Dict[str, Any]: |
| 32 | + resp = self._make_request("GET", "users/user_info") |
| 33 | + if not isinstance(resp, dict): |
| 34 | + raise BackendError("Unexpected JarvisLabs user_info response") |
| 35 | + return resp |
| 36 | + |
| 37 | + def list_ssh_keys(self) -> List[Dict[str, Any]]: |
| 38 | + resp = self._make_request("GET", "ssh/") |
| 39 | + if isinstance(resp, list): |
| 40 | + return resp |
| 41 | + raise BackendError("Unexpected JarvisLabs SSH key list response") |
| 42 | + |
| 43 | + def add_ssh_key(self, public_key: str, key_name: str) -> None: |
| 44 | + resp = self._make_request( |
| 45 | + "POST", |
| 46 | + "ssh/", |
| 47 | + json={ |
| 48 | + "ssh_key": public_key, |
| 49 | + "key_name": key_name, |
| 50 | + }, |
| 51 | + ) |
| 52 | + _raise_if_unsuccessful(resp, "Failed to add JarvisLabs SSH key") |
| 53 | + |
| 54 | + def add_ssh_key_if_needed(self, public_key: str) -> None: |
| 55 | + normalized_key = _normalize_public_key(public_key) |
| 56 | + for ssh_key in self.list_ssh_keys(): |
| 57 | + if _normalize_public_key(str(ssh_key.get("ssh_key", ""))) == normalized_key: |
| 58 | + return |
| 59 | + key_name = _get_ssh_key_name(normalized_key) |
| 60 | + self.add_ssh_key(public_key=public_key, key_name=key_name) |
| 61 | + |
| 62 | + def create_gpu_vm( |
| 63 | + self, |
| 64 | + *, |
| 65 | + gpu_type: str, |
| 66 | + num_gpus: int, |
| 67 | + is_spot: bool, |
| 68 | + storage: int, |
| 69 | + region: str, |
| 70 | + name: str, |
| 71 | + ) -> str: |
| 72 | + resp = self._make_request( |
| 73 | + "POST", |
| 74 | + "templates/vm/create", |
| 75 | + region=region, |
| 76 | + json={ |
| 77 | + "gpu_type": gpu_type, |
| 78 | + "num_gpus": num_gpus, |
| 79 | + "hdd": storage, |
| 80 | + "region": region, |
| 81 | + "name": name, |
| 82 | + "is_spot": is_spot, |
| 83 | + "duration": "hour", |
| 84 | + "disk_type": "ssd", |
| 85 | + "http_ports": "", |
| 86 | + "script_id": None, |
| 87 | + "script_args": "", |
| 88 | + "fs_id": None, |
| 89 | + "arguments": "", |
| 90 | + }, |
| 91 | + ) |
| 92 | + return _get_created_machine_id(resp, "GPU VM creation") |
| 93 | + |
| 94 | + def create_cpu_vm( |
| 95 | + self, |
| 96 | + *, |
| 97 | + vcpus: int, |
| 98 | + ram_gb: int, |
| 99 | + storage: int, |
| 100 | + region: str, |
| 101 | + name: str, |
| 102 | + ) -> str: |
| 103 | + resp = self._make_request( |
| 104 | + "POST", |
| 105 | + "templates/vm/cpu/create", |
| 106 | + region=region, |
| 107 | + json={ |
| 108 | + "num_cpus": 1, |
| 109 | + "vcpus": vcpus, |
| 110 | + "ram_gb": ram_gb, |
| 111 | + "hdd": storage, |
| 112 | + "region": region, |
| 113 | + "name": name, |
| 114 | + "duration": "hour", |
| 115 | + "disk_type": "ssd", |
| 116 | + }, |
| 117 | + ) |
| 118 | + return _get_created_machine_id(resp, "CPU VM creation") |
| 119 | + |
| 120 | + def get_instance(self, machine_id: str) -> Optional[Dict[str, Any]]: |
| 121 | + try: |
| 122 | + resp = self._make_request("GET", f"users/fetch/{machine_id}") |
| 123 | + except JarvisLabsNotFoundError: |
| 124 | + return None |
| 125 | + if not _is_successful(resp): |
| 126 | + return None |
| 127 | + if isinstance(resp, dict): |
| 128 | + instance = resp.get("instance") |
| 129 | + if isinstance(instance, dict): |
| 130 | + return instance |
| 131 | + return None |
| 132 | + |
| 133 | + def get_instance_status(self, *, machine_id: str, region: str) -> Optional[Dict[str, Any]]: |
| 134 | + try: |
| 135 | + resp = self._make_request( |
| 136 | + "GET", |
| 137 | + "misc/status", |
| 138 | + region=region, |
| 139 | + params={"machine_id": machine_id}, |
| 140 | + ) |
| 141 | + except JarvisLabsNotFoundError: |
| 142 | + return None |
| 143 | + if isinstance(resp, dict): |
| 144 | + return resp |
| 145 | + return None |
| 146 | + |
| 147 | + def destroy_instance(self, *, machine_id: str, region: str) -> None: |
| 148 | + instance = self.get_instance(machine_id) |
| 149 | + if instance is None: |
| 150 | + return |
| 151 | + endpoint = "templates/vm/destroy" |
| 152 | + if is_cpu_vm(instance): |
| 153 | + endpoint = "templates/vm/cpu/destroy" |
| 154 | + elif _instance_template(instance) != "vm": |
| 155 | + endpoint = "misc/destroy" |
| 156 | + |
| 157 | + try: |
| 158 | + resp = self._make_request( |
| 159 | + "POST", |
| 160 | + endpoint, |
| 161 | + region=instance.get("region") or region, |
| 162 | + params={"machine_id": machine_id}, |
| 163 | + ) |
| 164 | + except JarvisLabsNotFoundError: |
| 165 | + return |
| 166 | + _raise_if_unsuccessful(resp, "Failed to destroy JarvisLabs instance") |
| 167 | + |
| 168 | + def _make_request( |
| 169 | + self, |
| 170 | + method: str, |
| 171 | + path: str, |
| 172 | + *, |
| 173 | + json: Optional[Dict[str, Any]] = None, |
| 174 | + params: Optional[Dict[str, Any]] = None, |
| 175 | + region: Optional[str] = None, |
| 176 | + ) -> Any: |
| 177 | + response = requests.request( |
| 178 | + method=method, |
| 179 | + url=self._url(path=path, region=region), |
| 180 | + headers={"Authorization": f"Bearer {self.api_key}"}, |
| 181 | + json=json, |
| 182 | + params=params, |
| 183 | + timeout=TIMEOUT, |
| 184 | + ) |
| 185 | + if response.ok: |
| 186 | + if not response.content: |
| 187 | + return {} |
| 188 | + return response.json() |
| 189 | + message = _get_response_error(response) |
| 190 | + if response.status_code in [401, 403]: |
| 191 | + raise BackendInvalidCredentialsError(fields=[["creds", "api_key"]]) |
| 192 | + if response.status_code == 404: |
| 193 | + raise JarvisLabsNotFoundError(message) |
| 194 | + if response.status_code in [400, 409] and _looks_like_no_capacity(message): |
| 195 | + raise NoCapacityError(message) |
| 196 | + raise BackendError(message) |
| 197 | + |
| 198 | + def _url(self, *, path: str, region: Optional[str] = None) -> str: |
| 199 | + if region is None: |
| 200 | + base_url = API_URL |
| 201 | + else: |
| 202 | + # gpuhunt owns this allowlist because it filters JarvisLabs offers. Do not |
| 203 | + # fall back for unknown regions: regional VM APIs use separate hosts and |
| 204 | + # JarvisLabs does not expose endpoint discovery in server_meta. |
| 205 | + base_url = JARVISLABS_REGION_URLS.get(region) |
| 206 | + if base_url is None: |
| 207 | + raise BackendError( |
| 208 | + f"Unsupported JarvisLabs region {region!r}. " |
| 209 | + "JarvisLabs does not expose provisioning endpoint discovery." |
| 210 | + ) |
| 211 | + return base_url.rstrip("/") + "/" + path.lstrip("/") |
| 212 | + |
| 213 | + |
| 214 | +def is_cpu_vm(instance: Dict[str, Any]) -> bool: |
| 215 | + return _instance_template(instance) == "vm" and str(instance.get("gpu_type")).upper() == "CPU" |
| 216 | + |
| 217 | + |
| 218 | +def _instance_template(instance: Dict[str, Any]) -> str: |
| 219 | + return str(instance.get("template") or instance.get("framework") or "").lower() |
| 220 | + |
| 221 | + |
| 222 | +def _get_created_machine_id(resp: Any, operation: str) -> str: |
| 223 | + _raise_if_unsuccessful(resp, f"JarvisLabs {operation} failed") |
| 224 | + if isinstance(resp, dict): |
| 225 | + machine_id = resp.get("machine_id") |
| 226 | + if machine_id is not None: |
| 227 | + return str(machine_id) |
| 228 | + raise BackendError(f"JarvisLabs {operation} failed: missing machine_id") |
| 229 | + |
| 230 | + |
| 231 | +def _raise_if_unsuccessful(resp: Any, message: str) -> None: |
| 232 | + if _is_successful(resp): |
| 233 | + return |
| 234 | + backend_message = _backend_message(resp) |
| 235 | + if _looks_like_no_capacity(backend_message): |
| 236 | + raise NoCapacityError(backend_message) |
| 237 | + raise BackendError(f"{message}: {backend_message}") |
| 238 | + |
| 239 | + |
| 240 | +def _is_successful(resp: Any) -> bool: |
| 241 | + if not isinstance(resp, dict): |
| 242 | + return True |
| 243 | + if "success" in resp: |
| 244 | + return _coerce_bool(resp["success"]) |
| 245 | + if "sucess" in resp: |
| 246 | + return _coerce_bool(resp["sucess"]) |
| 247 | + return True |
| 248 | + |
| 249 | + |
| 250 | +def _coerce_bool(value: Any) -> bool: |
| 251 | + if isinstance(value, bool): |
| 252 | + return value |
| 253 | + if isinstance(value, str): |
| 254 | + return value.strip().lower() in {"1", "true", "yes", "success"} |
| 255 | + return bool(value) |
| 256 | + |
| 257 | + |
| 258 | +def _get_response_error(response: requests.Response) -> str: |
| 259 | + try: |
| 260 | + data = response.json() |
| 261 | + except ValueError: |
| 262 | + return response.text or f"HTTP {response.status_code}" |
| 263 | + message = _backend_message(data) |
| 264 | + return message or f"HTTP {response.status_code}" |
| 265 | + |
| 266 | + |
| 267 | +def _backend_message(resp: Any) -> str: |
| 268 | + if isinstance(resp, dict): |
| 269 | + detail = resp.get("detail") |
| 270 | + if isinstance(detail, list): |
| 271 | + return "; ".join(str(item.get("msg", item)) for item in detail) |
| 272 | + return str( |
| 273 | + resp.get("message") |
| 274 | + or resp.get("error") |
| 275 | + or resp.get("detail") |
| 276 | + or resp.get("msg") |
| 277 | + or resp |
| 278 | + ) |
| 279 | + return str(resp) |
| 280 | + |
| 281 | + |
| 282 | +def _looks_like_no_capacity(message: str) -> bool: |
| 283 | + message = message.lower() |
| 284 | + return "capacity" in message or "available" in message or "stock" in message |
| 285 | + |
| 286 | + |
| 287 | +def _normalize_public_key(public_key: str) -> str: |
| 288 | + return " ".join(public_key.strip().split()[:2]) |
| 289 | + |
| 290 | + |
| 291 | +def _get_ssh_key_name(public_key: str) -> str: |
| 292 | + return "dstack-" + hashlib.sha1(public_key.encode()).hexdigest()[:16] |
0 commit comments