cloudgpu 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloudgpu/__init__.py +1 -0
- cloudgpu/__main__.py +4 -0
- cloudgpu/adapters/__init__.py +0 -0
- cloudgpu/adapters/autodl.py +1240 -0
- cloudgpu/adapters/base.py +15 -0
- cloudgpu/adapters/gongji.py +810 -0
- cloudgpu/adapters/gpugeek.py +924 -0
- cloudgpu/adapters/gpushare.py +653 -0
- cloudgpu/adapters/matpool.py +521 -0
- cloudgpu/adapters/mornai.py +155 -0
- cloudgpu/autodl_buy.py +266 -0
- cloudgpu/cli.py +3007 -0
- cloudgpu/config.py +340 -0
- cloudgpu/dashboard.py +267 -0
- cloudgpu/desktop.py +249 -0
- cloudgpu/doctor.py +295 -0
- cloudgpu/errors.py +39 -0
- cloudgpu/gongji_auth.py +179 -0
- cloudgpu/gongji_deploy.py +314 -0
- cloudgpu/gongji_state.py +320 -0
- cloudgpu/jobs.py +566 -0
- cloudgpu/lock.py +83 -0
- cloudgpu/models.py +65 -0
- cloudgpu/notify.py +295 -0
- cloudgpu/orders.py +319 -0
- cloudgpu/snapshot.py +136 -0
- cloudgpu/tui.py +513 -0
- cloudgpu/watch.py +669 -0
- cloudgpu/web.py +110 -0
- cloudgpu/webui.html +428 -0
- cloudgpu-0.1.0.dist-info/METADATA +303 -0
- cloudgpu-0.1.0.dist-info/RECORD +35 -0
- cloudgpu-0.1.0.dist-info/WHEEL +5 -0
- cloudgpu-0.1.0.dist-info/entry_points.txt +3 -0
- cloudgpu-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1240 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Callable, Mapping, Optional
|
|
13
|
+
|
|
14
|
+
from cloudgpu.errors import (
|
|
15
|
+
AdapterError,
|
|
16
|
+
AuthFailedError,
|
|
17
|
+
AuthRequiredError,
|
|
18
|
+
OrderRejectedError,
|
|
19
|
+
OrderUncertainError,
|
|
20
|
+
)
|
|
21
|
+
from cloudgpu.models import AdapterCapabilities, GpuOffer, filter_offers
|
|
22
|
+
|
|
23
|
+
Fetch = Callable[[str, str, dict, Optional[dict], float], object]
|
|
24
|
+
|
|
25
|
+
BASE_URL = "https://www.autodl.com/api/v1"
|
|
26
|
+
MARKET_URL = "https://www.autodl.com/market/list"
|
|
27
|
+
DEFAULT_TOKEN_FILE = Path.home() / ".cloudgpu" / "autodl.token"
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class AutoDLGpu:
|
|
30
|
+
name: str
|
|
31
|
+
memory_gb: Optional[int]
|
|
32
|
+
series: Optional[str]
|
|
33
|
+
chip_corp: Optional[str]
|
|
34
|
+
cpu_arch: Optional[str]
|
|
35
|
+
extra: Optional[dict] = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class AutoDLRegion:
|
|
40
|
+
region_sign: str
|
|
41
|
+
region_name: str
|
|
42
|
+
data_center: str
|
|
43
|
+
visible: str
|
|
44
|
+
used_for: str
|
|
45
|
+
extra: Optional[dict] = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class AutoDLRegionGroup:
|
|
50
|
+
data_center: str
|
|
51
|
+
region_name: str
|
|
52
|
+
region_signs: tuple
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class AutoDLImage:
|
|
57
|
+
id: str
|
|
58
|
+
label: str
|
|
59
|
+
kind: str
|
|
60
|
+
uuid: str
|
|
61
|
+
cuda: Optional[str]
|
|
62
|
+
cpu_arch: Optional[str]
|
|
63
|
+
chip_corp: Optional[str]
|
|
64
|
+
raw: dict
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class AutoDLQuote:
|
|
69
|
+
price_info: dict
|
|
70
|
+
hourly_total: float
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class AutoDLInstance:
|
|
75
|
+
uuid: str
|
|
76
|
+
name: str
|
|
77
|
+
status: str
|
|
78
|
+
gpu_name: Optional[str]
|
|
79
|
+
gpu_count: Optional[int]
|
|
80
|
+
region: Optional[str]
|
|
81
|
+
machine_id: Optional[str]
|
|
82
|
+
raw: dict
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class AutoDLAdapter:
|
|
86
|
+
platform = "autodl"
|
|
87
|
+
BASE_URL = BASE_URL
|
|
88
|
+
MARKET_URL = MARKET_URL
|
|
89
|
+
HEADERS = {
|
|
90
|
+
"Content-Type": "application/json",
|
|
91
|
+
"Referer": "https://www.autodl.com/create",
|
|
92
|
+
"AppVersion": "0.0.0",
|
|
93
|
+
"User-Agent": "cloudgpu/0.1",
|
|
94
|
+
}
|
|
95
|
+
capabilities = AdapterCapabilities(
|
|
96
|
+
read_only=True,
|
|
97
|
+
machine_level=True,
|
|
98
|
+
region=True,
|
|
99
|
+
price=True,
|
|
100
|
+
total=True,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
token: Optional[str] = None,
|
|
106
|
+
token_env: str = "CLOUDGPU_AUTODL_TOKEN",
|
|
107
|
+
token_file=None,
|
|
108
|
+
timeout: float = 15.0,
|
|
109
|
+
fetch: Optional[Fetch] = None,
|
|
110
|
+
clock=None,
|
|
111
|
+
env: Optional[Mapping[str, str]] = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
self._explicit_token = (token or "").strip()
|
|
114
|
+
self._token_env = token_env
|
|
115
|
+
self._token_file = (
|
|
116
|
+
Path(token_file).expanduser()
|
|
117
|
+
if token_file
|
|
118
|
+
else DEFAULT_TOKEN_FILE
|
|
119
|
+
)
|
|
120
|
+
self.timeout = timeout
|
|
121
|
+
self._fetch = fetch or _http_json
|
|
122
|
+
self._clock = clock or (lambda: datetime.now(timezone.utc))
|
|
123
|
+
self._env = os.environ if env is None else env
|
|
124
|
+
|
|
125
|
+
def _resolve_token(self) -> str:
|
|
126
|
+
if self._explicit_token:
|
|
127
|
+
return self._explicit_token
|
|
128
|
+
|
|
129
|
+
for name in (self._token_env, "AUTODL_TOKEN"):
|
|
130
|
+
value = (self._env.get(name) or "").strip()
|
|
131
|
+
if value:
|
|
132
|
+
return value
|
|
133
|
+
|
|
134
|
+
path = self._token_file
|
|
135
|
+
if path and path.exists():
|
|
136
|
+
try:
|
|
137
|
+
for line in path.read_text(encoding="utf-8").splitlines():
|
|
138
|
+
value = line.strip()
|
|
139
|
+
if value:
|
|
140
|
+
return value
|
|
141
|
+
except OSError:
|
|
142
|
+
raise AuthRequiredError(
|
|
143
|
+
f"读取 token 文件失败: {path}"
|
|
144
|
+
) from None
|
|
145
|
+
return ""
|
|
146
|
+
|
|
147
|
+
def _require_token(self) -> str:
|
|
148
|
+
token = self._resolve_token()
|
|
149
|
+
if not token:
|
|
150
|
+
raise AuthRequiredError(
|
|
151
|
+
"缺少 AutoDL token。浏览器登录 autodl.com,F12 Network "
|
|
152
|
+
"复制任意 /api/v1/ 请求的 Authorization,写入 "
|
|
153
|
+
f"{self._token_file}(chmod 600)或设置 "
|
|
154
|
+
f"{self._token_env}"
|
|
155
|
+
)
|
|
156
|
+
expiry = jwt_expiry(token)
|
|
157
|
+
if expiry is not None and expiry <= self._clock():
|
|
158
|
+
raise AuthRequiredError(
|
|
159
|
+
f"AutoDL token 已过期,请重新获取并写入 "
|
|
160
|
+
f"{self._token_file}"
|
|
161
|
+
)
|
|
162
|
+
return token
|
|
163
|
+
|
|
164
|
+
def require_token(self) -> str:
|
|
165
|
+
return self._require_token()
|
|
166
|
+
|
|
167
|
+
def _call(
|
|
168
|
+
self,
|
|
169
|
+
method: str,
|
|
170
|
+
path: str,
|
|
171
|
+
payload: Optional[dict] = None,
|
|
172
|
+
require_auth: bool = True,
|
|
173
|
+
):
|
|
174
|
+
headers = dict(self.HEADERS)
|
|
175
|
+
if require_auth:
|
|
176
|
+
headers["Authorization"] = self._require_token()
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
response = self._fetch(
|
|
180
|
+
method,
|
|
181
|
+
self.BASE_URL + path,
|
|
182
|
+
headers,
|
|
183
|
+
payload,
|
|
184
|
+
self.timeout,
|
|
185
|
+
)
|
|
186
|
+
except AdapterError:
|
|
187
|
+
raise
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
raise AdapterError(
|
|
190
|
+
f"请求 AutoDL 失败: {type(exc).__name__}"
|
|
191
|
+
) from None
|
|
192
|
+
|
|
193
|
+
if not isinstance(response, dict):
|
|
194
|
+
raise AdapterError("AutoDL 响应格式异常: 顶层不是对象")
|
|
195
|
+
|
|
196
|
+
code = response.get("code")
|
|
197
|
+
if code == "Success":
|
|
198
|
+
return response.get("data")
|
|
199
|
+
if code == "AuthorizeFailed":
|
|
200
|
+
raise AuthFailedError(response.get("msg") or "登录态失效")
|
|
201
|
+
raise AdapterError(
|
|
202
|
+
f"AutoDL 返回错误 {code}: {response.get('msg') or ''}"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
def list_models(self) -> list:
|
|
206
|
+
data = self._call(
|
|
207
|
+
"GET", "/machine/gpu_type", require_auth=False
|
|
208
|
+
)
|
|
209
|
+
if not isinstance(data, list):
|
|
210
|
+
raise AdapterError("AutoDL 响应格式异常: gpu_type 不是列表")
|
|
211
|
+
|
|
212
|
+
models = []
|
|
213
|
+
for index, item in enumerate(data):
|
|
214
|
+
if not isinstance(item, dict):
|
|
215
|
+
raise AdapterError(
|
|
216
|
+
f"AutoDL 响应格式异常: gpu_type[{index}] 不是对象"
|
|
217
|
+
)
|
|
218
|
+
name = item.get("gpu_name")
|
|
219
|
+
if not isinstance(name, str) or not name:
|
|
220
|
+
raise AdapterError(
|
|
221
|
+
f"AutoDL 响应格式异常: gpu_type[{index}].gpu_name 非法"
|
|
222
|
+
)
|
|
223
|
+
memory = item.get("gpu_memory")
|
|
224
|
+
if memory is not None and (
|
|
225
|
+
isinstance(memory, bool)
|
|
226
|
+
or not isinstance(memory, int)
|
|
227
|
+
or memory < 0
|
|
228
|
+
):
|
|
229
|
+
raise AdapterError(
|
|
230
|
+
f"AutoDL 响应格式异常: {name}.gpu_memory 非法"
|
|
231
|
+
)
|
|
232
|
+
models.append(
|
|
233
|
+
AutoDLGpu(
|
|
234
|
+
name=name,
|
|
235
|
+
memory_gb=(
|
|
236
|
+
round(memory / 1024 ** 3)
|
|
237
|
+
if memory is not None
|
|
238
|
+
else None
|
|
239
|
+
),
|
|
240
|
+
series=_optional_str(
|
|
241
|
+
item.get("gpu_series_type"), name, "gpu_series_type"
|
|
242
|
+
),
|
|
243
|
+
chip_corp=_optional_str(
|
|
244
|
+
item.get("chip_corp"), name, "chip_corp"
|
|
245
|
+
),
|
|
246
|
+
cpu_arch=_optional_str(
|
|
247
|
+
item.get("cpu_arch"), name, "cpu_arch"
|
|
248
|
+
),
|
|
249
|
+
extra=dict(item),
|
|
250
|
+
)
|
|
251
|
+
)
|
|
252
|
+
return models
|
|
253
|
+
|
|
254
|
+
def list_regions(self, include_hidden: bool = False) -> list:
|
|
255
|
+
data = self._call(
|
|
256
|
+
"GET", "/region/list", require_auth=False
|
|
257
|
+
)
|
|
258
|
+
if not isinstance(data, list):
|
|
259
|
+
raise AdapterError("AutoDL 响应格式异常: region/list 不是列表")
|
|
260
|
+
|
|
261
|
+
regions = []
|
|
262
|
+
for index, item in enumerate(data):
|
|
263
|
+
if not isinstance(item, dict):
|
|
264
|
+
raise AdapterError(
|
|
265
|
+
f"AutoDL 响应格式异常: region[{index}] 不是对象"
|
|
266
|
+
)
|
|
267
|
+
region_sign = item.get("region_sign")
|
|
268
|
+
region_name = item.get("region_name")
|
|
269
|
+
data_center = item.get("data_center")
|
|
270
|
+
for field, value in (
|
|
271
|
+
("region_sign", region_sign),
|
|
272
|
+
("region_name", region_name),
|
|
273
|
+
("data_center", data_center),
|
|
274
|
+
):
|
|
275
|
+
if not isinstance(value, str) or not value:
|
|
276
|
+
raise AdapterError(
|
|
277
|
+
f"AutoDL 响应格式异常: region[{index}].{field} 非法"
|
|
278
|
+
)
|
|
279
|
+
visible = item.get("visible")
|
|
280
|
+
used_for = item.get("used_for")
|
|
281
|
+
if not isinstance(visible, str) or not isinstance(used_for, str):
|
|
282
|
+
raise AdapterError(
|
|
283
|
+
f"AutoDL 响应格式异常: region[{index}] 可见性字段非法"
|
|
284
|
+
)
|
|
285
|
+
if not include_hidden and (
|
|
286
|
+
visible != "all" or used_for != "all"
|
|
287
|
+
):
|
|
288
|
+
continue
|
|
289
|
+
regions.append(
|
|
290
|
+
AutoDLRegion(
|
|
291
|
+
region_sign=region_sign,
|
|
292
|
+
region_name=region_name,
|
|
293
|
+
data_center=data_center,
|
|
294
|
+
visible=visible,
|
|
295
|
+
used_for=used_for,
|
|
296
|
+
extra=dict(item),
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
return regions
|
|
300
|
+
|
|
301
|
+
def region_groups(self, include_hidden: bool = False) -> list:
|
|
302
|
+
order = []
|
|
303
|
+
grouped = {}
|
|
304
|
+
for region in self.list_regions(include_hidden):
|
|
305
|
+
if region.data_center not in grouped:
|
|
306
|
+
grouped[region.data_center] = {
|
|
307
|
+
"region_name": region.region_name,
|
|
308
|
+
"region_signs": [],
|
|
309
|
+
}
|
|
310
|
+
order.append(region.data_center)
|
|
311
|
+
grouped[region.data_center]["region_signs"].append(
|
|
312
|
+
region.region_sign
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
groups = []
|
|
316
|
+
for data_center in order:
|
|
317
|
+
item = grouped[data_center]
|
|
318
|
+
signs = tuple(dict.fromkeys(item["region_signs"]))
|
|
319
|
+
groups.append(
|
|
320
|
+
AutoDLRegionGroup(
|
|
321
|
+
data_center=data_center,
|
|
322
|
+
region_name=item["region_name"],
|
|
323
|
+
region_signs=signs,
|
|
324
|
+
)
|
|
325
|
+
)
|
|
326
|
+
return groups
|
|
327
|
+
|
|
328
|
+
def list_offers(
|
|
329
|
+
self,
|
|
330
|
+
*,
|
|
331
|
+
kind: Optional[str] = None,
|
|
332
|
+
regions=None,
|
|
333
|
+
models=None,
|
|
334
|
+
) -> list:
|
|
335
|
+
self._require_token()
|
|
336
|
+
if kind is None:
|
|
337
|
+
kind = "region"
|
|
338
|
+
if kind != "region":
|
|
339
|
+
raise ValueError(f"不支持的 kind: {kind}")
|
|
340
|
+
|
|
341
|
+
region_patterns = _as_list(regions)
|
|
342
|
+
groups = self.region_groups()
|
|
343
|
+
if region_patterns:
|
|
344
|
+
groups = [
|
|
345
|
+
group
|
|
346
|
+
for group in groups
|
|
347
|
+
if any(
|
|
348
|
+
pattern in (group.region_name, group.data_center)
|
|
349
|
+
or pattern in group.region_signs
|
|
350
|
+
for pattern in region_patterns
|
|
351
|
+
)
|
|
352
|
+
]
|
|
353
|
+
if not groups:
|
|
354
|
+
raise ValueError(
|
|
355
|
+
f"未找到匹配地区: {', '.join(region_patterns)}"
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
catalog = {gpu.name: gpu for gpu in self.list_models()}
|
|
359
|
+
checked_at = _format_time(self._clock())
|
|
360
|
+
offers = []
|
|
361
|
+
|
|
362
|
+
for group in groups:
|
|
363
|
+
data = self._call(
|
|
364
|
+
"POST",
|
|
365
|
+
"/machine/region/gpu_type",
|
|
366
|
+
{"region_sign_list": list(group.region_signs)},
|
|
367
|
+
)
|
|
368
|
+
if not isinstance(data, list):
|
|
369
|
+
raise AdapterError(
|
|
370
|
+
"AutoDL 响应格式异常: region/gpu_type 不是列表"
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
parsed = {}
|
|
374
|
+
for index, item in enumerate(data):
|
|
375
|
+
if not isinstance(item, dict):
|
|
376
|
+
raise AdapterError(
|
|
377
|
+
f"AutoDL 响应格式异常: region/gpu_type[{index}] 不是对象"
|
|
378
|
+
)
|
|
379
|
+
for model, info in item.items():
|
|
380
|
+
if not isinstance(model, str) or not model:
|
|
381
|
+
raise AdapterError(
|
|
382
|
+
f"AutoDL 响应格式异常: region/gpu_type[{index}] 型号非法"
|
|
383
|
+
)
|
|
384
|
+
if not isinstance(info, dict):
|
|
385
|
+
raise AdapterError(
|
|
386
|
+
f"AutoDL 响应格式异常: {model} 计数不是对象"
|
|
387
|
+
)
|
|
388
|
+
idle = info.get("idle_gpu_num")
|
|
389
|
+
total = info.get("total_gpu_num")
|
|
390
|
+
if not _is_non_negative_int(idle):
|
|
391
|
+
raise AdapterError(
|
|
392
|
+
f"AutoDL 响应格式异常: {model}.idle_gpu_num 非法"
|
|
393
|
+
)
|
|
394
|
+
if not _is_non_negative_int(total):
|
|
395
|
+
raise AdapterError(
|
|
396
|
+
f"AutoDL 响应格式异常: {model}.total_gpu_num 非法"
|
|
397
|
+
)
|
|
398
|
+
parsed[model] = (idle, total, dict(info))
|
|
399
|
+
|
|
400
|
+
for model, (idle, total, info) in parsed.items():
|
|
401
|
+
meta = catalog.get(model)
|
|
402
|
+
offers.append(
|
|
403
|
+
GpuOffer(
|
|
404
|
+
platform=self.platform,
|
|
405
|
+
service_kind="region",
|
|
406
|
+
gpu_model=model,
|
|
407
|
+
display_name=model,
|
|
408
|
+
description="",
|
|
409
|
+
gpu_memory_gb=(
|
|
410
|
+
meta.memory_gb if meta is not None else None
|
|
411
|
+
),
|
|
412
|
+
free=idle,
|
|
413
|
+
total=total,
|
|
414
|
+
region=group.region_name,
|
|
415
|
+
machine_id=None,
|
|
416
|
+
price_per_hour=None,
|
|
417
|
+
charge_type="payg",
|
|
418
|
+
url=self.MARKET_URL,
|
|
419
|
+
checked_at=checked_at,
|
|
420
|
+
extra={
|
|
421
|
+
"data_center": group.data_center,
|
|
422
|
+
"region_signs": list(group.region_signs),
|
|
423
|
+
"series": (
|
|
424
|
+
meta.series if meta is not None else None
|
|
425
|
+
),
|
|
426
|
+
"chip_corp": (
|
|
427
|
+
meta.chip_corp
|
|
428
|
+
if meta is not None
|
|
429
|
+
else None
|
|
430
|
+
),
|
|
431
|
+
"cpu_arch": (
|
|
432
|
+
meta.cpu_arch
|
|
433
|
+
if meta is not None
|
|
434
|
+
else None
|
|
435
|
+
),
|
|
436
|
+
"raw": info,
|
|
437
|
+
},
|
|
438
|
+
)
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
return filter_offers(offers, _as_list(models), min_free=0)
|
|
442
|
+
|
|
443
|
+
def list_machines(
|
|
444
|
+
self,
|
|
445
|
+
*,
|
|
446
|
+
region: str,
|
|
447
|
+
gpu_model: str,
|
|
448
|
+
min_idle: int = 1,
|
|
449
|
+
page_size: int = 90,
|
|
450
|
+
max_pages: int = 20,
|
|
451
|
+
) -> list:
|
|
452
|
+
self._require_token()
|
|
453
|
+
if not isinstance(region, str) or not region:
|
|
454
|
+
raise ValueError("region 不能为空")
|
|
455
|
+
if not isinstance(gpu_model, str) or not gpu_model:
|
|
456
|
+
raise ValueError("gpu_model 不能为空")
|
|
457
|
+
if min_idle < 0:
|
|
458
|
+
raise ValueError("min_idle 不能为负数")
|
|
459
|
+
if page_size < 1:
|
|
460
|
+
raise ValueError("page_size 必须大于 0")
|
|
461
|
+
if max_pages < 1:
|
|
462
|
+
raise ValueError("max_pages 必须大于 0")
|
|
463
|
+
|
|
464
|
+
matches = [
|
|
465
|
+
item
|
|
466
|
+
for item in self.list_regions()
|
|
467
|
+
if region
|
|
468
|
+
in (item.region_name, item.data_center, item.region_sign)
|
|
469
|
+
]
|
|
470
|
+
if not matches:
|
|
471
|
+
raise ValueError(f"未知地区: {region}")
|
|
472
|
+
|
|
473
|
+
signs = tuple(
|
|
474
|
+
dict.fromkeys(item.region_sign for item in matches)
|
|
475
|
+
)
|
|
476
|
+
region_name = matches[0].region_name
|
|
477
|
+
catalog = {gpu.name: gpu for gpu in self.list_models()}
|
|
478
|
+
meta = catalog.get(gpu_model)
|
|
479
|
+
checked_at = _format_time(self._clock())
|
|
480
|
+
offers = []
|
|
481
|
+
page = 1
|
|
482
|
+
|
|
483
|
+
while True:
|
|
484
|
+
data = self._call(
|
|
485
|
+
"POST",
|
|
486
|
+
"/user/machine/list",
|
|
487
|
+
{
|
|
488
|
+
"charge_type": "payg",
|
|
489
|
+
"region_sign": "",
|
|
490
|
+
"region_sign_list": list(signs),
|
|
491
|
+
"gpu_type_name": [gpu_model],
|
|
492
|
+
"machine_tag_name": [],
|
|
493
|
+
"gpu_idle_num": min_idle,
|
|
494
|
+
"mount_net_disk": False,
|
|
495
|
+
"cpu_arch": [],
|
|
496
|
+
"chip_corp": [],
|
|
497
|
+
"default_order": True,
|
|
498
|
+
"page_index": page,
|
|
499
|
+
"page_size": page_size,
|
|
500
|
+
},
|
|
501
|
+
)
|
|
502
|
+
if not isinstance(data, dict):
|
|
503
|
+
raise AdapterError(
|
|
504
|
+
"AutoDL 响应格式异常: machine/list 不是对象"
|
|
505
|
+
)
|
|
506
|
+
items = data.get("list")
|
|
507
|
+
if not isinstance(items, list):
|
|
508
|
+
raise AdapterError(
|
|
509
|
+
"AutoDL 响应格式异常: machine/list.list 不是列表"
|
|
510
|
+
)
|
|
511
|
+
result_total = data.get("result_total")
|
|
512
|
+
if not _is_non_negative_int(result_total):
|
|
513
|
+
raise AdapterError(
|
|
514
|
+
"AutoDL 响应格式异常: machine/list.result_total 非法"
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
for index, item in enumerate(items):
|
|
518
|
+
offer = self._machine_offer(
|
|
519
|
+
item,
|
|
520
|
+
index,
|
|
521
|
+
region_name,
|
|
522
|
+
meta,
|
|
523
|
+
checked_at,
|
|
524
|
+
min_idle,
|
|
525
|
+
)
|
|
526
|
+
if offer is not None:
|
|
527
|
+
offers.append(offer)
|
|
528
|
+
|
|
529
|
+
if not items or page * page_size >= result_total:
|
|
530
|
+
break
|
|
531
|
+
if page >= max_pages:
|
|
532
|
+
raise AdapterError(
|
|
533
|
+
"AutoDL 机器列表分页不完整,已超过 max_pages"
|
|
534
|
+
)
|
|
535
|
+
page += 1
|
|
536
|
+
|
|
537
|
+
offers.sort(
|
|
538
|
+
key=lambda offer: (
|
|
539
|
+
offer.price_per_hour is None,
|
|
540
|
+
offer.price_per_hour or 0,
|
|
541
|
+
offer.machine_id or "",
|
|
542
|
+
)
|
|
543
|
+
)
|
|
544
|
+
return offers
|
|
545
|
+
|
|
546
|
+
def _machine_offer(
|
|
547
|
+
self,
|
|
548
|
+
item,
|
|
549
|
+
index: int,
|
|
550
|
+
region_name: str,
|
|
551
|
+
meta,
|
|
552
|
+
checked_at: str,
|
|
553
|
+
min_idle: int,
|
|
554
|
+
):
|
|
555
|
+
if not isinstance(item, dict):
|
|
556
|
+
raise AdapterError(
|
|
557
|
+
f"AutoDL 响应格式异常: machine/list[{index}] 不是对象"
|
|
558
|
+
)
|
|
559
|
+
machine_id = item.get("machine_id")
|
|
560
|
+
gpu_name = item.get("gpu_name")
|
|
561
|
+
if not isinstance(machine_id, str) or not machine_id:
|
|
562
|
+
raise AdapterError(
|
|
563
|
+
f"AutoDL 响应格式异常: machine/list[{index}].machine_id 非法"
|
|
564
|
+
)
|
|
565
|
+
if not isinstance(gpu_name, str) or not gpu_name:
|
|
566
|
+
raise AdapterError(
|
|
567
|
+
f"AutoDL 响应格式异常: {machine_id}.gpu_name 非法"
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
if item.get("on_line") in (0, 3, 4, 5, 6):
|
|
571
|
+
return None
|
|
572
|
+
|
|
573
|
+
max_instances = item.get("max_instance_num")
|
|
574
|
+
bound = item.get("binding_instance_num")
|
|
575
|
+
if (
|
|
576
|
+
isinstance(max_instances, int)
|
|
577
|
+
and not isinstance(max_instances, bool)
|
|
578
|
+
and isinstance(bound, int)
|
|
579
|
+
and not isinstance(bound, bool)
|
|
580
|
+
and max_instances <= bound
|
|
581
|
+
):
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
idle = item.get("gpu_idle_num")
|
|
585
|
+
total = item.get("gpu_number")
|
|
586
|
+
if not _is_non_negative_int(idle):
|
|
587
|
+
raise AdapterError(
|
|
588
|
+
f"AutoDL 响应格式异常: {machine_id}.gpu_idle_num 非法"
|
|
589
|
+
)
|
|
590
|
+
if not _is_non_negative_int(total):
|
|
591
|
+
raise AdapterError(
|
|
592
|
+
f"AutoDL 响应格式异常: {machine_id}.gpu_number 非法"
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
if idle < min_idle:
|
|
596
|
+
return None
|
|
597
|
+
|
|
598
|
+
price_raw = item.get("payg_price")
|
|
599
|
+
if price_raw is None:
|
|
600
|
+
price = None
|
|
601
|
+
elif isinstance(price_raw, bool) or not isinstance(
|
|
602
|
+
price_raw, (int, float)
|
|
603
|
+
):
|
|
604
|
+
raise AdapterError(
|
|
605
|
+
f"AutoDL 响应格式异常: {machine_id}.payg_price 非法"
|
|
606
|
+
)
|
|
607
|
+
else:
|
|
608
|
+
price = float(price_raw) / 1000
|
|
609
|
+
|
|
610
|
+
base = item.get("machine_base_info") or {}
|
|
611
|
+
if not isinstance(base, dict):
|
|
612
|
+
raise AdapterError(
|
|
613
|
+
f"AutoDL 响应格式异常: {machine_id}.machine_base_info 非法"
|
|
614
|
+
)
|
|
615
|
+
cpu_name = base.get("cpu_name")
|
|
616
|
+
if cpu_name is not None and not isinstance(cpu_name, str):
|
|
617
|
+
raise AdapterError(
|
|
618
|
+
f"AutoDL 响应格式异常: {machine_id}.cpu_name 非法"
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
host_region = item.get("region_name")
|
|
622
|
+
if not isinstance(host_region, str) or not host_region:
|
|
623
|
+
host_region = region_name
|
|
624
|
+
|
|
625
|
+
return GpuOffer(
|
|
626
|
+
platform=self.platform,
|
|
627
|
+
service_kind="machine",
|
|
628
|
+
gpu_model=gpu_name,
|
|
629
|
+
display_name=gpu_name,
|
|
630
|
+
description=item.get("machine_alias") or "",
|
|
631
|
+
gpu_memory_gb=meta.memory_gb if meta is not None else None,
|
|
632
|
+
free=idle,
|
|
633
|
+
total=total,
|
|
634
|
+
region=host_region,
|
|
635
|
+
machine_id=machine_id,
|
|
636
|
+
price_per_hour=price,
|
|
637
|
+
charge_type="payg",
|
|
638
|
+
url=self.MARKET_URL,
|
|
639
|
+
checked_at=checked_at,
|
|
640
|
+
extra={
|
|
641
|
+
"machine_alias": item.get("machine_alias"),
|
|
642
|
+
"cpu_per_gpu": item.get("cpu_per_gpu"),
|
|
643
|
+
"mem_per_gpu": item.get("mem_per_gpu"),
|
|
644
|
+
"highest_cuda_version": item.get(
|
|
645
|
+
"highest_cuda_version"
|
|
646
|
+
),
|
|
647
|
+
"cpu_name": cpu_name,
|
|
648
|
+
"on_line": item.get("on_line"),
|
|
649
|
+
"region_sign": item.get("region_sign"),
|
|
650
|
+
"raw": dict(item),
|
|
651
|
+
},
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
def list_images(self, *, gpu_model: str) -> list:
|
|
655
|
+
if not isinstance(gpu_model, str) or not gpu_model:
|
|
656
|
+
raise ValueError("gpu_model 不能为空")
|
|
657
|
+
models = {item.name: item for item in self.list_models()}
|
|
658
|
+
model = models.get(gpu_model)
|
|
659
|
+
if model is None:
|
|
660
|
+
raise ValueError(f"未知 AutoDL 型号: {gpu_model}")
|
|
661
|
+
if not model.cpu_arch or not model.chip_corp:
|
|
662
|
+
raise AdapterError(
|
|
663
|
+
f"AutoDL 型号缺少架构信息: {gpu_model}"
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
filters = {
|
|
667
|
+
"cpu_arch": [model.cpu_arch],
|
|
668
|
+
"chip_corp": [model.chip_corp],
|
|
669
|
+
}
|
|
670
|
+
base = self._call("POST", "/image/all", filters)
|
|
671
|
+
private = self._call(
|
|
672
|
+
"POST", "/image/private/get", filters
|
|
673
|
+
)
|
|
674
|
+
if not isinstance(base, list):
|
|
675
|
+
raise AdapterError(
|
|
676
|
+
"AutoDL 响应格式异常: image/all 不是列表"
|
|
677
|
+
)
|
|
678
|
+
if not isinstance(private, list):
|
|
679
|
+
raise AdapterError(
|
|
680
|
+
"AutoDL 响应格式异常: image/private/get 不是列表"
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
images = []
|
|
684
|
+
for image in _flatten_base_images(base):
|
|
685
|
+
if (
|
|
686
|
+
image.cpu_arch != model.cpu_arch
|
|
687
|
+
or image.chip_corp != model.chip_corp
|
|
688
|
+
):
|
|
689
|
+
continue
|
|
690
|
+
if not _image_cuda_ok(image, model.series):
|
|
691
|
+
continue
|
|
692
|
+
images.append(image)
|
|
693
|
+
|
|
694
|
+
for index, item in enumerate(private):
|
|
695
|
+
if not isinstance(item, dict):
|
|
696
|
+
raise AdapterError(
|
|
697
|
+
f"AutoDL 响应格式异常: 私有镜像[{index}] 不是对象"
|
|
698
|
+
)
|
|
699
|
+
uuid = item.get("image_uuid")
|
|
700
|
+
name = item.get("name")
|
|
701
|
+
if not isinstance(uuid, str) or not uuid:
|
|
702
|
+
raise AdapterError(
|
|
703
|
+
f"AutoDL 响应格式异常: 私有镜像[{index}].image_uuid 非法"
|
|
704
|
+
)
|
|
705
|
+
if not isinstance(name, str):
|
|
706
|
+
name = ""
|
|
707
|
+
image = AutoDLImage(
|
|
708
|
+
id="private:" + uuid,
|
|
709
|
+
label="我的镜像 / " + name,
|
|
710
|
+
kind="private",
|
|
711
|
+
uuid=uuid,
|
|
712
|
+
cuda=_optional_str(
|
|
713
|
+
item.get("cuda_v"), str(uuid), "cuda_v"
|
|
714
|
+
),
|
|
715
|
+
cpu_arch=_optional_str(
|
|
716
|
+
item.get("cpu_arch"), str(uuid), "cpu_arch"
|
|
717
|
+
),
|
|
718
|
+
chip_corp=_optional_str(
|
|
719
|
+
item.get("chip_corp"), str(uuid), "chip_corp"
|
|
720
|
+
),
|
|
721
|
+
raw=dict(item),
|
|
722
|
+
)
|
|
723
|
+
if (
|
|
724
|
+
image.cpu_arch != model.cpu_arch
|
|
725
|
+
or image.chip_corp != model.chip_corp
|
|
726
|
+
):
|
|
727
|
+
continue
|
|
728
|
+
if not _image_cuda_ok(image, model.series):
|
|
729
|
+
continue
|
|
730
|
+
images.append(image)
|
|
731
|
+
|
|
732
|
+
images.sort(
|
|
733
|
+
key=lambda image: (image.kind, image.label, image.id)
|
|
734
|
+
)
|
|
735
|
+
return images
|
|
736
|
+
|
|
737
|
+
def search_candidates(
|
|
738
|
+
self,
|
|
739
|
+
*,
|
|
740
|
+
gpu_model: str,
|
|
741
|
+
count: int,
|
|
742
|
+
region=None,
|
|
743
|
+
page_size: int = 90,
|
|
744
|
+
max_pages: int = 20,
|
|
745
|
+
) -> list:
|
|
746
|
+
if not isinstance(gpu_model, str) or not gpu_model:
|
|
747
|
+
raise ValueError("gpu_model 不能为空")
|
|
748
|
+
if (
|
|
749
|
+
isinstance(count, bool)
|
|
750
|
+
or not isinstance(count, int)
|
|
751
|
+
or count < 1
|
|
752
|
+
):
|
|
753
|
+
raise ValueError("count 必须是 >=1 的整数")
|
|
754
|
+
if page_size < 1:
|
|
755
|
+
raise ValueError("page_size 必须大于 0")
|
|
756
|
+
if max_pages < 1:
|
|
757
|
+
raise ValueError("max_pages 必须大于 0")
|
|
758
|
+
|
|
759
|
+
signs = ()
|
|
760
|
+
if region:
|
|
761
|
+
matches = [
|
|
762
|
+
item
|
|
763
|
+
for item in self.list_regions()
|
|
764
|
+
if region
|
|
765
|
+
in (
|
|
766
|
+
item.region_name,
|
|
767
|
+
item.data_center,
|
|
768
|
+
item.region_sign,
|
|
769
|
+
)
|
|
770
|
+
]
|
|
771
|
+
if not matches:
|
|
772
|
+
raise ValueError(f"未知 AutoDL 地区: {region}")
|
|
773
|
+
signs = tuple(
|
|
774
|
+
dict.fromkeys(
|
|
775
|
+
item.region_sign for item in matches
|
|
776
|
+
)
|
|
777
|
+
)
|
|
778
|
+
|
|
779
|
+
catalog = {
|
|
780
|
+
item.name: item for item in self.list_models()
|
|
781
|
+
}
|
|
782
|
+
meta = catalog.get(gpu_model)
|
|
783
|
+
checked_at = _format_time(self._clock())
|
|
784
|
+
offers = []
|
|
785
|
+
page = 1
|
|
786
|
+
|
|
787
|
+
while True:
|
|
788
|
+
data = self._call(
|
|
789
|
+
"POST",
|
|
790
|
+
"/user/machine/list",
|
|
791
|
+
{
|
|
792
|
+
"charge_type": "payg",
|
|
793
|
+
"region_sign": "",
|
|
794
|
+
"region_sign_list": list(signs),
|
|
795
|
+
"gpu_type_name": [gpu_model],
|
|
796
|
+
"machine_tag_name": [],
|
|
797
|
+
"gpu_idle_num": count,
|
|
798
|
+
"mount_net_disk": False,
|
|
799
|
+
"cpu_arch": [],
|
|
800
|
+
"chip_corp": [],
|
|
801
|
+
"default_order": True,
|
|
802
|
+
"page_index": page,
|
|
803
|
+
"page_size": page_size,
|
|
804
|
+
},
|
|
805
|
+
)
|
|
806
|
+
if not isinstance(data, dict):
|
|
807
|
+
raise AdapterError(
|
|
808
|
+
"AutoDL 响应格式异常: machine/list 不是对象"
|
|
809
|
+
)
|
|
810
|
+
items = data.get("list")
|
|
811
|
+
if not isinstance(items, list):
|
|
812
|
+
raise AdapterError(
|
|
813
|
+
"AutoDL 响应格式异常: machine/list.list 不是列表"
|
|
814
|
+
)
|
|
815
|
+
result_total = data.get("result_total")
|
|
816
|
+
if not _is_non_negative_int(result_total):
|
|
817
|
+
raise AdapterError(
|
|
818
|
+
"AutoDL 响应格式异常: machine/list.result_total 非法"
|
|
819
|
+
)
|
|
820
|
+
|
|
821
|
+
for index, item in enumerate(items):
|
|
822
|
+
offer = self._machine_offer(
|
|
823
|
+
item,
|
|
824
|
+
index,
|
|
825
|
+
"",
|
|
826
|
+
meta,
|
|
827
|
+
checked_at,
|
|
828
|
+
count,
|
|
829
|
+
)
|
|
830
|
+
if offer is not None:
|
|
831
|
+
offers.append(offer)
|
|
832
|
+
|
|
833
|
+
if not items or page * page_size >= result_total:
|
|
834
|
+
break
|
|
835
|
+
if page >= max_pages:
|
|
836
|
+
raise AdapterError(
|
|
837
|
+
"AutoDL 机器列表分页不完整,已超过 max_pages"
|
|
838
|
+
)
|
|
839
|
+
page += 1
|
|
840
|
+
|
|
841
|
+
offers.sort(
|
|
842
|
+
key=lambda offer: (
|
|
843
|
+
offer.price_per_hour is None,
|
|
844
|
+
offer.price_per_hour or 0,
|
|
845
|
+
offer.machine_id or "",
|
|
846
|
+
)
|
|
847
|
+
)
|
|
848
|
+
return offers
|
|
849
|
+
|
|
850
|
+
def preview_order(
|
|
851
|
+
self, *, machine_id: str, count: int
|
|
852
|
+
) -> AutoDLQuote:
|
|
853
|
+
if not isinstance(machine_id, str) or not machine_id:
|
|
854
|
+
raise ValueError("machine_id 不能为空")
|
|
855
|
+
if (
|
|
856
|
+
isinstance(count, bool)
|
|
857
|
+
or not isinstance(count, int)
|
|
858
|
+
or count < 1
|
|
859
|
+
):
|
|
860
|
+
raise ValueError("count 必须是 >=1 的整数")
|
|
861
|
+
|
|
862
|
+
data = self._call(
|
|
863
|
+
"POST",
|
|
864
|
+
"/order/price/preview",
|
|
865
|
+
{
|
|
866
|
+
"machine_id": machine_id,
|
|
867
|
+
"charge_type": "payg",
|
|
868
|
+
"duration": 1,
|
|
869
|
+
"num": count,
|
|
870
|
+
"coupon_id_list": [],
|
|
871
|
+
"expand_data_disk": 0,
|
|
872
|
+
},
|
|
873
|
+
)
|
|
874
|
+
if not isinstance(data, dict):
|
|
875
|
+
raise AdapterError(
|
|
876
|
+
"AutoDL 响应格式异常: 报价不是对象"
|
|
877
|
+
)
|
|
878
|
+
raw = data.get("origin_price")
|
|
879
|
+
if isinstance(raw, bool):
|
|
880
|
+
raise AdapterError(
|
|
881
|
+
"AutoDL 响应格式异常: origin_price 非法"
|
|
882
|
+
)
|
|
883
|
+
try:
|
|
884
|
+
value = float(raw)
|
|
885
|
+
except (TypeError, ValueError):
|
|
886
|
+
raise AdapterError(
|
|
887
|
+
"AutoDL 响应格式异常: origin_price 非法"
|
|
888
|
+
) from None
|
|
889
|
+
if not math.isfinite(value) or value <= 0:
|
|
890
|
+
raise AdapterError(
|
|
891
|
+
"AutoDL 响应格式异常: origin_price 非法"
|
|
892
|
+
)
|
|
893
|
+
return AutoDLQuote(
|
|
894
|
+
price_info=dict(data),
|
|
895
|
+
hourly_total=value / 1000,
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
def create_payg_order(
|
|
899
|
+
self,
|
|
900
|
+
*,
|
|
901
|
+
machine_id: str,
|
|
902
|
+
count: int,
|
|
903
|
+
image: AutoDLImage,
|
|
904
|
+
instance_name: str,
|
|
905
|
+
price_info: dict,
|
|
906
|
+
) -> str:
|
|
907
|
+
if not isinstance(machine_id, str) or not machine_id:
|
|
908
|
+
raise ValueError("machine_id 不能为空")
|
|
909
|
+
if (
|
|
910
|
+
isinstance(count, bool)
|
|
911
|
+
or not isinstance(count, int)
|
|
912
|
+
or count < 1
|
|
913
|
+
):
|
|
914
|
+
raise ValueError("count 必须是 >=1 的整数")
|
|
915
|
+
if not isinstance(instance_name, str) or not instance_name:
|
|
916
|
+
raise ValueError("instance_name 不能为空")
|
|
917
|
+
if image.kind not in ("base", "private"):
|
|
918
|
+
raise ValueError(f"未知镜像类型: {image.kind}")
|
|
919
|
+
if not isinstance(price_info, dict):
|
|
920
|
+
raise ValueError("price_info 必须是对象")
|
|
921
|
+
|
|
922
|
+
instance = {
|
|
923
|
+
"machine_id": machine_id,
|
|
924
|
+
"charge_type": "payg",
|
|
925
|
+
"req_gpu_amount": count,
|
|
926
|
+
"instance_name": instance_name,
|
|
927
|
+
"base_image_uuid": (
|
|
928
|
+
image.uuid if image.kind == "base" else ""
|
|
929
|
+
),
|
|
930
|
+
"private_image_uuid": (
|
|
931
|
+
image.uuid if image.kind == "private" else ""
|
|
932
|
+
),
|
|
933
|
+
"reproduction_uuid": "",
|
|
934
|
+
"cg_application_uuid": "",
|
|
935
|
+
"reproduction_id": 0,
|
|
936
|
+
"cg_application_info": {
|
|
937
|
+
"image_name": "",
|
|
938
|
+
"current_version_id": 0,
|
|
939
|
+
"current_version": "",
|
|
940
|
+
"image_id": 0,
|
|
941
|
+
},
|
|
942
|
+
"expand_data_disk": 0,
|
|
943
|
+
}
|
|
944
|
+
payload = {
|
|
945
|
+
"instance_info": instance,
|
|
946
|
+
"price_info": price_info,
|
|
947
|
+
}
|
|
948
|
+
headers = dict(self.HEADERS)
|
|
949
|
+
headers["Authorization"] = self._require_token()
|
|
950
|
+
|
|
951
|
+
try:
|
|
952
|
+
response = self._fetch(
|
|
953
|
+
"POST",
|
|
954
|
+
self.BASE_URL + "/order/instance/create/payg",
|
|
955
|
+
headers,
|
|
956
|
+
payload,
|
|
957
|
+
self.timeout,
|
|
958
|
+
)
|
|
959
|
+
except Exception as exc:
|
|
960
|
+
raise OrderUncertainError(
|
|
961
|
+
f"AutoDL 下单结果未知: {type(exc).__name__}"
|
|
962
|
+
) from None
|
|
963
|
+
|
|
964
|
+
if not isinstance(response, dict):
|
|
965
|
+
raise OrderUncertainError(
|
|
966
|
+
"AutoDL 下单响应不是对象"
|
|
967
|
+
)
|
|
968
|
+
code = response.get("code")
|
|
969
|
+
message = response.get("msg")
|
|
970
|
+
if not isinstance(code, str) or not code:
|
|
971
|
+
raise OrderUncertainError(
|
|
972
|
+
"AutoDL 下单响应缺少 code"
|
|
973
|
+
)
|
|
974
|
+
if code == "Success":
|
|
975
|
+
data = response.get("data")
|
|
976
|
+
if not isinstance(data, str) or not data.strip():
|
|
977
|
+
raise OrderUncertainError(
|
|
978
|
+
"AutoDL 下单响应缺少实例 ID"
|
|
979
|
+
)
|
|
980
|
+
return data
|
|
981
|
+
if code == "AuthorizeFailed":
|
|
982
|
+
raise AuthFailedError(message or "登录态失效")
|
|
983
|
+
if code == "MachineGpuNumUpdateFailed":
|
|
984
|
+
raise OrderRejectedError(
|
|
985
|
+
message or "库存已变化",
|
|
986
|
+
kind="sold_out",
|
|
987
|
+
code=code,
|
|
988
|
+
)
|
|
989
|
+
raise OrderRejectedError(
|
|
990
|
+
f"AutoDL 拒绝下单 {code}: {message or ''}",
|
|
991
|
+
kind="rejected",
|
|
992
|
+
code=code,
|
|
993
|
+
)
|
|
994
|
+
|
|
995
|
+
def list_instances(
|
|
996
|
+
self,
|
|
997
|
+
*,
|
|
998
|
+
name: str = "",
|
|
999
|
+
page_size: int = 50,
|
|
1000
|
+
max_pages: int = 20,
|
|
1001
|
+
) -> list:
|
|
1002
|
+
if not isinstance(name, str):
|
|
1003
|
+
raise ValueError("name 必须是字符串")
|
|
1004
|
+
if page_size < 1:
|
|
1005
|
+
raise ValueError("page_size 必须大于 0")
|
|
1006
|
+
if max_pages < 1:
|
|
1007
|
+
raise ValueError("max_pages 必须大于 0")
|
|
1008
|
+
|
|
1009
|
+
page = 1
|
|
1010
|
+
rows = []
|
|
1011
|
+
seen = set()
|
|
1012
|
+
while True:
|
|
1013
|
+
data = self._call(
|
|
1014
|
+
"POST",
|
|
1015
|
+
"/instance",
|
|
1016
|
+
{
|
|
1017
|
+
"page_index": page,
|
|
1018
|
+
"page_size": page_size,
|
|
1019
|
+
"name": name,
|
|
1020
|
+
"status": [],
|
|
1021
|
+
"charge_type": [],
|
|
1022
|
+
},
|
|
1023
|
+
)
|
|
1024
|
+
if not isinstance(data, dict):
|
|
1025
|
+
raise AdapterError(
|
|
1026
|
+
"AutoDL 响应格式异常: instance 不是对象"
|
|
1027
|
+
)
|
|
1028
|
+
items = data.get("list")
|
|
1029
|
+
if not isinstance(items, list):
|
|
1030
|
+
raise AdapterError(
|
|
1031
|
+
"AutoDL 响应格式异常: instance.list 不是列表"
|
|
1032
|
+
)
|
|
1033
|
+
total = data.get("result_total")
|
|
1034
|
+
if not _is_non_negative_int(total):
|
|
1035
|
+
raise AdapterError(
|
|
1036
|
+
"AutoDL 响应格式异常: instance.result_total 非法"
|
|
1037
|
+
)
|
|
1038
|
+
|
|
1039
|
+
for index, item in enumerate(items):
|
|
1040
|
+
row = _instance(item, index)
|
|
1041
|
+
if row.uuid in seen:
|
|
1042
|
+
raise AdapterError(
|
|
1043
|
+
f"AutoDL 实例分页出现重复 uuid {row.uuid}"
|
|
1044
|
+
)
|
|
1045
|
+
seen.add(row.uuid)
|
|
1046
|
+
rows.append(row)
|
|
1047
|
+
|
|
1048
|
+
if not items or page * page_size >= total:
|
|
1049
|
+
break
|
|
1050
|
+
if page >= max_pages:
|
|
1051
|
+
raise AdapterError(
|
|
1052
|
+
"AutoDL 实例列表分页不完整,已超过 max_pages"
|
|
1053
|
+
)
|
|
1054
|
+
page += 1
|
|
1055
|
+
|
|
1056
|
+
if len(rows) != total:
|
|
1057
|
+
raise AdapterError(
|
|
1058
|
+
f"AutoDL 实例列表不完整:预期 {total} 条,"
|
|
1059
|
+
f"实得 {len(rows)} 条"
|
|
1060
|
+
)
|
|
1061
|
+
return rows
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def _flatten_base_images(nodes, path=()):
|
|
1065
|
+
if not isinstance(nodes, list):
|
|
1066
|
+
raise AdapterError(
|
|
1067
|
+
"AutoDL 响应格式异常: 镜像树不是列表"
|
|
1068
|
+
)
|
|
1069
|
+
for node in nodes:
|
|
1070
|
+
if not isinstance(node, dict):
|
|
1071
|
+
raise AdapterError(
|
|
1072
|
+
"AutoDL 响应格式异常: 镜像节点不是对象"
|
|
1073
|
+
)
|
|
1074
|
+
label = node.get("label_name")
|
|
1075
|
+
if isinstance(label, str):
|
|
1076
|
+
yield from _flatten_base_images(
|
|
1077
|
+
node.get("children", []), (*path, label)
|
|
1078
|
+
)
|
|
1079
|
+
elif isinstance(label, dict):
|
|
1080
|
+
uuid = label.get("uuid")
|
|
1081
|
+
if not isinstance(uuid, str) or not uuid:
|
|
1082
|
+
continue
|
|
1083
|
+
cuda = label.get("v")
|
|
1084
|
+
yield AutoDLImage(
|
|
1085
|
+
id="base:" + uuid,
|
|
1086
|
+
label=" / ".join(
|
|
1087
|
+
(*path, str(cuda) if cuda is not None else "")
|
|
1088
|
+
).strip(" /"),
|
|
1089
|
+
kind="base",
|
|
1090
|
+
uuid=uuid,
|
|
1091
|
+
cuda=(
|
|
1092
|
+
str(cuda) if cuda is not None else None
|
|
1093
|
+
),
|
|
1094
|
+
cpu_arch=_optional_str(
|
|
1095
|
+
label.get("cpu_arch"), uuid, "cpu_arch"
|
|
1096
|
+
),
|
|
1097
|
+
chip_corp=_optional_str(
|
|
1098
|
+
label.get("chip_corp"), uuid, "chip_corp"
|
|
1099
|
+
),
|
|
1100
|
+
raw=dict(node),
|
|
1101
|
+
)
|
|
1102
|
+
else:
|
|
1103
|
+
raise AdapterError(
|
|
1104
|
+
"AutoDL 响应格式异常: 镜像标签非法"
|
|
1105
|
+
)
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
_CUDA_FLOORS = {
|
|
1109
|
+
"NVIDIA-Ampere": (11, 0),
|
|
1110
|
+
"NVIDIA-Ada": (11, 3),
|
|
1111
|
+
"NVIDIA-Blackwell": (12, 8),
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def _cuda_version(value):
|
|
1116
|
+
if value is None:
|
|
1117
|
+
return None
|
|
1118
|
+
parts = str(value).strip().split(".")
|
|
1119
|
+
try:
|
|
1120
|
+
major = int(parts[0])
|
|
1121
|
+
minor = int(parts[1]) if len(parts) > 1 else 0
|
|
1122
|
+
except (ValueError, IndexError):
|
|
1123
|
+
return None
|
|
1124
|
+
return major, minor
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
def _image_cuda_ok(image, series) -> bool:
|
|
1128
|
+
if not image.cuda:
|
|
1129
|
+
return image.chip_corp != "nvidia"
|
|
1130
|
+
version = _cuda_version(image.cuda)
|
|
1131
|
+
if version is None:
|
|
1132
|
+
return image.chip_corp != "nvidia"
|
|
1133
|
+
floor = _CUDA_FLOORS.get(series or "", (0, 0))
|
|
1134
|
+
return version >= floor
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def _instance(item, index: int) -> AutoDLInstance:
|
|
1138
|
+
if not isinstance(item, dict):
|
|
1139
|
+
raise AdapterError(
|
|
1140
|
+
f"AutoDL 响应格式异常: instance[{index}] 不是对象"
|
|
1141
|
+
)
|
|
1142
|
+
uuid = item.get("uuid")
|
|
1143
|
+
if not isinstance(uuid, str) or not uuid:
|
|
1144
|
+
raise AdapterError(
|
|
1145
|
+
f"AutoDL 响应格式异常: instance[{index}].uuid 非法"
|
|
1146
|
+
)
|
|
1147
|
+
name = item.get("name")
|
|
1148
|
+
status = item.get("status")
|
|
1149
|
+
gpu_name = item.get("gpu_name")
|
|
1150
|
+
region = item.get("region_name") or item.get("region_sign")
|
|
1151
|
+
machine_id = item.get("machine_id")
|
|
1152
|
+
count = item.get("req_gpu_amount")
|
|
1153
|
+
return AutoDLInstance(
|
|
1154
|
+
uuid=uuid,
|
|
1155
|
+
name=name if isinstance(name, str) else "",
|
|
1156
|
+
status=status if isinstance(status, str) else "",
|
|
1157
|
+
gpu_name=gpu_name if isinstance(gpu_name, str) else None,
|
|
1158
|
+
gpu_count=(
|
|
1159
|
+
count
|
|
1160
|
+
if _is_non_negative_int(count)
|
|
1161
|
+
else None
|
|
1162
|
+
),
|
|
1163
|
+
region=region if isinstance(region, str) else None,
|
|
1164
|
+
machine_id=(
|
|
1165
|
+
machine_id if isinstance(machine_id, str) else None
|
|
1166
|
+
),
|
|
1167
|
+
raw=dict(item),
|
|
1168
|
+
)
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _as_list(value):
|
|
1172
|
+
if value is None:
|
|
1173
|
+
return []
|
|
1174
|
+
if isinstance(value, str):
|
|
1175
|
+
return [value]
|
|
1176
|
+
return list(value)
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def _is_non_negative_int(value) -> bool:
|
|
1180
|
+
return (
|
|
1181
|
+
isinstance(value, int)
|
|
1182
|
+
and not isinstance(value, bool)
|
|
1183
|
+
and value >= 0
|
|
1184
|
+
)
|
|
1185
|
+
|
|
1186
|
+
|
|
1187
|
+
def _format_time(value: datetime) -> str:
|
|
1188
|
+
if value.tzinfo is None:
|
|
1189
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
1190
|
+
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
1191
|
+
|
|
1192
|
+
|
|
1193
|
+
def _optional_str(value, name: str, field: str) -> Optional[str]:
|
|
1194
|
+
if value is None:
|
|
1195
|
+
return None
|
|
1196
|
+
if not isinstance(value, str):
|
|
1197
|
+
raise AdapterError(
|
|
1198
|
+
f"AutoDL 响应格式异常: {name}.{field} 不是字符串"
|
|
1199
|
+
)
|
|
1200
|
+
return value
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
def jwt_expiry(token: str) -> Optional[datetime]:
|
|
1204
|
+
try:
|
|
1205
|
+
payload = token.split(".")[1]
|
|
1206
|
+
payload += "=" * (-len(payload) % 4)
|
|
1207
|
+
data = json.loads(base64.urlsafe_b64decode(payload))
|
|
1208
|
+
return datetime.fromtimestamp(int(data["exp"]), tz=timezone.utc)
|
|
1209
|
+
except Exception:
|
|
1210
|
+
return None
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def _http_json(
|
|
1214
|
+
method: str,
|
|
1215
|
+
url: str,
|
|
1216
|
+
headers: dict,
|
|
1217
|
+
payload: Optional[dict],
|
|
1218
|
+
timeout: float,
|
|
1219
|
+
) -> object:
|
|
1220
|
+
body = None
|
|
1221
|
+
if payload is not None:
|
|
1222
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
1223
|
+
|
|
1224
|
+
request = urllib.request.Request(
|
|
1225
|
+
url,
|
|
1226
|
+
data=body,
|
|
1227
|
+
headers=headers,
|
|
1228
|
+
method=method,
|
|
1229
|
+
)
|
|
1230
|
+
try:
|
|
1231
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
1232
|
+
raw = response.read()
|
|
1233
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
1234
|
+
reason = getattr(exc, "reason", None) or type(exc).__name__
|
|
1235
|
+
raise AdapterError(f"请求 AutoDL 失败: {reason}") from None
|
|
1236
|
+
|
|
1237
|
+
try:
|
|
1238
|
+
return json.loads(raw.decode("utf-8"))
|
|
1239
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
1240
|
+
raise AdapterError("AutoDL 响应不是合法 JSON") from None
|