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.
@@ -0,0 +1,653 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import math
6
+ import os
7
+ import re
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Callable, Mapping, Optional
14
+
15
+ from cloudgpu.errors import AdapterError, AuthFailedError, AuthRequiredError
16
+ from cloudgpu.models import AdapterCapabilities, GpuOffer
17
+
18
+ Fetch = Callable[[str, str, dict, Optional[dict], float], object]
19
+
20
+ BASE_URL = "https://api.gpushare.com/app/api/market/machine/list"
21
+ MARKET_URL = "https://www.gpushare.com/store"
22
+ DEFAULT_TOKEN_FILE = Path.home() / ".cloudgpu" / "gpushare.token"
23
+ class GpuShareAdapter:
24
+ platform = "gpushare"
25
+ BASE_URL = BASE_URL
26
+ MARKET_URL = MARKET_URL
27
+ HEADERS = {
28
+ "Accept": "application/json",
29
+ "Referer": "https://www.gpushare.com/store",
30
+ "User-Agent": "cloudgpu/0.1",
31
+ }
32
+ capabilities = AdapterCapabilities(
33
+ read_only=True,
34
+ machine_level=True,
35
+ region=True,
36
+ price=True,
37
+ total=True,
38
+ )
39
+
40
+ def __init__(
41
+ self,
42
+ token: Optional[str] = None,
43
+ token_env: str = "CLOUDGPU_GPUSHARE_TOKEN",
44
+ token_file=None,
45
+ timeout: float = 15.0,
46
+ fetch: Optional[Fetch] = None,
47
+ env: Optional[Mapping[str, str]] = None,
48
+ clock=None,
49
+ ) -> None:
50
+ self._explicit_token = (token or "").strip()
51
+ self._token_env = token_env
52
+ self._token_file = (
53
+ Path(token_file).expanduser()
54
+ if token_file
55
+ else DEFAULT_TOKEN_FILE
56
+ )
57
+ self.timeout = timeout
58
+ self._fetch = fetch or _http_json
59
+ self._env = os.environ if env is None else env
60
+ self._clock = clock or (lambda: datetime.now(timezone.utc))
61
+
62
+ def _resolve_token(self) -> str:
63
+ if self._explicit_token:
64
+ return self._explicit_token
65
+
66
+ for name in (self._token_env, "GPUSHARE_TOKEN"):
67
+ value = (self._env.get(name) or "").strip()
68
+ if value:
69
+ return value
70
+
71
+ path = self._token_file
72
+ if path and path.exists():
73
+ try:
74
+ for line in path.read_text(encoding="utf-8").splitlines():
75
+ value = line.strip()
76
+ if value:
77
+ return value
78
+ except OSError:
79
+ raise AuthRequiredError(
80
+ f"读取 token 文件失败: {path}"
81
+ ) from None
82
+ return ""
83
+
84
+ def require_token(self) -> str:
85
+ token = self._resolve_token()
86
+ if not token:
87
+ raise AuthRequiredError(
88
+ f"缺少恒源云 token。请设置 {self._token_env},"
89
+ "或从 Cookie gpu_share_token 获取后写入 "
90
+ f"{self._token_file}(chmod 600)"
91
+ )
92
+ expiry = _jwt_expiry(token)
93
+ if expiry is not None and expiry <= self._clock():
94
+ raise AuthRequiredError(
95
+ "恒源云 token 已过期,请重新从 Cookie 获取 "
96
+ f"gpu_share_token 并写入 {self._token_file}"
97
+ )
98
+ return token
99
+
100
+ def _auth_value(self) -> str:
101
+ token = self.require_token()
102
+ if token.lower().startswith("bearer "):
103
+ return token
104
+ return f"Bearer {token}"
105
+
106
+ def list_machines(
107
+ self,
108
+ *,
109
+ gpu_model=None,
110
+ region=None,
111
+ min_free: int = 1,
112
+ max_price=None,
113
+ min_vram_gb=None,
114
+ min_ram_gb=None,
115
+ min_cuda=None,
116
+ page_size: int = 50,
117
+ max_pages: int = 200,
118
+ ) -> list:
119
+ if page_size < 1:
120
+ raise ValueError("page_size 必须大于 0")
121
+ if max_pages < 1:
122
+ raise ValueError("max_pages 必须大于 0")
123
+ if min_free < 0:
124
+ raise ValueError("min_free 不能为负数")
125
+ for name, value in (
126
+ ("max_price", max_price),
127
+ ("min_vram_gb", min_vram_gb),
128
+ ("min_ram_gb", min_ram_gb),
129
+ ):
130
+ if value is not None and value < 0:
131
+ raise ValueError(f"{name} 不能为负数")
132
+ if min_cuda is not None and _version_tuple(min_cuda) is None:
133
+ raise ValueError("min_cuda 不是合法版本号")
134
+
135
+ self.require_token()
136
+ items, total = self._fetch_page(1, page_size)
137
+ pages = math.ceil(total / page_size) if total else 0
138
+ if pages > max_pages:
139
+ raise AdapterError(
140
+ f"恒源云市场共 {total} 条,超出分页上限 {max_pages}"
141
+ )
142
+
143
+ all_items = list(items)
144
+ for page in range(2, pages + 1):
145
+ next_items, next_total = self._fetch_page(page, page_size)
146
+ if next_total != total:
147
+ raise AdapterError("恒源云分页期间总数发生变化")
148
+ all_items.extend(next_items)
149
+
150
+ if len(all_items) != total:
151
+ raise AdapterError(
152
+ f"恒源云分页结果不完整:预期 {total} 条,实得 "
153
+ f"{len(all_items)} 条"
154
+ )
155
+
156
+ seen = set()
157
+ for item in all_items:
158
+ if not isinstance(item, dict):
159
+ raise AdapterError("恒源云响应格式异常: 机器条目不是对象")
160
+ machine_id = item.get("machineId")
161
+ if not isinstance(machine_id, str) or not machine_id:
162
+ raise AdapterError("恒源云响应格式异常: machineId 缺失")
163
+ if machine_id in seen:
164
+ raise AdapterError(
165
+ f"恒源云分页出现重复机器 {machine_id}"
166
+ )
167
+ seen.add(machine_id)
168
+
169
+ offers = []
170
+ for item in all_items:
171
+ offer = self._machine_offer(item)
172
+ if offer is None:
173
+ continue
174
+ if not _matches_filters(
175
+ offer,
176
+ gpu_model=gpu_model,
177
+ region=region,
178
+ min_free=min_free,
179
+ max_price=max_price,
180
+ min_vram_gb=min_vram_gb,
181
+ min_ram_gb=min_ram_gb,
182
+ min_cuda=min_cuda,
183
+ ):
184
+ continue
185
+ offers.append(offer)
186
+
187
+ offers.sort(
188
+ key=lambda offer: (
189
+ offer.price_per_hour is None,
190
+ offer.price_per_hour or 0,
191
+ offer.machine_id or "",
192
+ )
193
+ )
194
+ return offers
195
+
196
+ def list_models(self) -> list:
197
+ offers = self.list_machines(min_free=0)
198
+ models = {}
199
+ for offer in offers:
200
+ entry = models.setdefault(
201
+ offer.gpu_model,
202
+ {"name": offer.gpu_model, "count": 0, "min_price": None},
203
+ )
204
+ entry["count"] += 1
205
+ if offer.price_per_hour is not None and (
206
+ entry["min_price"] is None
207
+ or offer.price_per_hour < entry["min_price"]
208
+ ):
209
+ entry["min_price"] = offer.price_per_hour
210
+ return sorted(models.values(), key=lambda item: item["name"])
211
+
212
+ def list_regions(self) -> list:
213
+ offers = self.list_machines(min_free=0)
214
+ counts = {}
215
+ for offer in offers:
216
+ name = offer.region or "未知"
217
+ counts[name] = counts.get(name, 0) + 1
218
+ return [
219
+ {"name": name, "count": count}
220
+ for name, count in sorted(counts.items())
221
+ ]
222
+
223
+ def _fetch_page(self, page: int, page_size: int):
224
+ params = {
225
+ "pn": page,
226
+ "ps": page_size,
227
+ "minGpuNum": 1,
228
+ "priceOrder": "asc",
229
+ "skuName": "payg",
230
+ }
231
+ url = f"{self.BASE_URL}?{urllib.parse.urlencode(params)}"
232
+ headers = dict(self.HEADERS)
233
+ headers["Authorization"] = self._auth_value()
234
+
235
+ try:
236
+ response = self._fetch(
237
+ "GET", url, headers, None, self.timeout
238
+ )
239
+ except AdapterError:
240
+ raise
241
+ except Exception as exc:
242
+ raise AdapterError(
243
+ f"请求恒源云失败: {type(exc).__name__}"
244
+ ) from None
245
+
246
+ return _validate_page(response)
247
+
248
+ def _machine_offer(self, item):
249
+ machine_id = item.get("machineId")
250
+ info = item.get("baseInfo") or {}
251
+ if not isinstance(info, dict):
252
+ raise AdapterError(
253
+ f"恒源云响应格式异常: {machine_id}.baseInfo 非法"
254
+ )
255
+
256
+ gpu_name = info.get("gpuName") or item.get("gpuName")
257
+ if not isinstance(gpu_name, str) or not gpu_name:
258
+ raise AdapterError(
259
+ f"恒源云响应格式异常: {machine_id}.gpuName 非法"
260
+ )
261
+
262
+ status = _as_int(item.get("status"), "status", machine_id)
263
+ is_online = item.get("isOnline")
264
+ if not isinstance(is_online, bool):
265
+ raise AdapterError(
266
+ f"恒源云响应格式异常: {machine_id}.isOnline 非法"
267
+ )
268
+ if status != 1 or not is_online:
269
+ return None
270
+
271
+ gpu_num = _as_int(item.get("gpuNum"), "gpuNum", machine_id)
272
+ gpu_used = _as_int(
273
+ item.get("gpuUsed"), "gpuUsed", machine_id
274
+ )
275
+ if gpu_num < 0 or gpu_used < 0 or gpu_used > gpu_num:
276
+ raise AdapterError(
277
+ f"恒源云响应格式异常: {machine_id}.gpuNum/gpuUsed 非法"
278
+ )
279
+
280
+ skus = item.get("skuList")
281
+ if not isinstance(skus, list):
282
+ raise AdapterError(
283
+ f"恒源云响应格式异常: {machine_id}.skuList 非法"
284
+ )
285
+ payg = [
286
+ sku
287
+ for sku in skus
288
+ if isinstance(sku, dict) and sku.get("skuName") == "payg"
289
+ ]
290
+ if not payg:
291
+ return None
292
+ if len(payg) != 1:
293
+ raise AdapterError(
294
+ f"恒源云响应格式异常: {machine_id} 有多个 payg SKU"
295
+ )
296
+ sku = payg[0]
297
+ sku_status = _as_int(
298
+ sku.get("status"), "payg.status", machine_id
299
+ )
300
+ sku_enable = _as_int(
301
+ sku.get("enable"), "payg.enable", machine_id
302
+ )
303
+ if sku_status != 1 or sku_enable != 1:
304
+ return None
305
+
306
+ price_raw = sku.get("price")
307
+ price = (
308
+ None
309
+ if price_raw is None
310
+ else _as_float(
311
+ price_raw, "payg.price", machine_id
312
+ )
313
+ )
314
+
315
+ memory = _size_gb(info.get("gpuMemory"), raw_bytes=False)
316
+ memory_total = _size_gb(
317
+ info.get("memoryTotal"), raw_bytes=True
318
+ )
319
+ ram_per_gpu = (
320
+ memory_total / gpu_num
321
+ if memory_total is not None and gpu_num > 0
322
+ else None
323
+ )
324
+
325
+ region = item.get("regionName")
326
+ if region is not None and not isinstance(region, str):
327
+ raise AdapterError(
328
+ f"恒源云响应格式异常: {machine_id}.regionName 非法"
329
+ )
330
+ cuda = info.get("gpuToolkitVersion")
331
+ if cuda is not None and not isinstance(cuda, str):
332
+ raise AdapterError(
333
+ f"恒源云响应格式异常: {machine_id}.gpuToolkitVersion 非法"
334
+ )
335
+ vm_type = info.get("vmType")
336
+ if vm_type is not None and not isinstance(vm_type, str):
337
+ raise AdapterError(
338
+ f"恒源云响应格式异常: {machine_id}.vmType 非法"
339
+ )
340
+
341
+ url = (
342
+ f"{MARKET_URL}/hire/create?"
343
+ + urllib.parse.urlencode(
344
+ {
345
+ "id": machine_id,
346
+ "skuName": "payg",
347
+ "regionName": region or "",
348
+ "system": vm_type or "docker",
349
+ }
350
+ )
351
+ )
352
+
353
+ return GpuOffer(
354
+ platform=self.platform,
355
+ service_kind="machine",
356
+ gpu_model=gpu_name,
357
+ display_name=gpu_name,
358
+ description=machine_id,
359
+ gpu_memory_gb=(
360
+ round(memory) if memory is not None else None
361
+ ),
362
+ free=gpu_num - gpu_used,
363
+ total=gpu_num,
364
+ region=region,
365
+ machine_id=machine_id,
366
+ price_per_hour=price,
367
+ charge_type="payg",
368
+ url=url,
369
+ checked_at=_format_time(datetime.now(timezone.utc)),
370
+ extra={
371
+ "gpu_used": gpu_used,
372
+ "gpu_toolkit_version": cuda,
373
+ "vm_type": vm_type,
374
+ "memory_total_gb": (
375
+ round(memory_total, 1)
376
+ if memory_total is not None
377
+ else None
378
+ ),
379
+ "ram_per_gpu_gb": (
380
+ round(ram_per_gpu, 1)
381
+ if ram_per_gpu is not None
382
+ else None
383
+ ),
384
+ "status": status,
385
+ "is_online": is_online,
386
+ "system": vm_type,
387
+ "payg_status": sku_status,
388
+ "payg_enable": sku_enable,
389
+ "sku_price": price,
390
+ "raw": dict(item),
391
+ },
392
+ )
393
+
394
+
395
+ def _jwt_expiry(token: str):
396
+ try:
397
+ payload = token.split(".")[1]
398
+ payload += "=" * (-len(payload) % 4)
399
+ data = json.loads(base64.urlsafe_b64decode(payload))
400
+ return datetime.fromtimestamp(int(data["exp"]), tz=timezone.utc)
401
+ except Exception:
402
+ return None
403
+
404
+
405
+ def _validate_page(response):
406
+ if not isinstance(response, dict):
407
+ raise AdapterError("恒源云响应格式异常: 顶层不是对象")
408
+ status = _normalize_status(response.get("status"))
409
+ if status != 0:
410
+ raise AdapterError(f"恒源云返回错误 status={status}")
411
+
412
+ payload = (
413
+ response
414
+ if isinstance(response.get("list"), list)
415
+ else response.get("data")
416
+ )
417
+ if not isinstance(payload, dict):
418
+ raise AdapterError("恒源云响应格式异常: 缺少 list/data")
419
+ items = payload.get("list")
420
+ total = _as_int(payload.get("total"), "total", "data")
421
+ if not isinstance(items, list):
422
+ raise AdapterError("恒源云响应格式异常: list 不是数组")
423
+ if total < 0 or total > 1000000:
424
+ raise AdapterError("恒源云响应格式异常: total 非法")
425
+ return items, total
426
+
427
+
428
+ def _normalize_status(value) -> int:
429
+ if isinstance(value, bool):
430
+ raise AdapterError("恒源云响应格式异常: status 非法")
431
+ if isinstance(value, int):
432
+ status = value
433
+ elif isinstance(value, float) and value.is_integer():
434
+ status = int(value)
435
+ elif isinstance(value, str):
436
+ text = value.strip()
437
+ if text in ("401", "403", "20013"):
438
+ raise AuthFailedError("恒源云登录态失效或无权访问")
439
+ try:
440
+ status = int(text)
441
+ except ValueError:
442
+ raise AdapterError(
443
+ "恒源云响应格式异常: status 非法"
444
+ ) from None
445
+ else:
446
+ raise AdapterError("恒源云响应格式异常: status 非法")
447
+
448
+ if status in (401, 403, 20013):
449
+ raise AuthFailedError("恒源云登录态失效或无权访问")
450
+ return status
451
+
452
+
453
+ def _as_int(value, field: str, context: str) -> int:
454
+ if isinstance(value, bool):
455
+ raise AdapterError(
456
+ f"恒源云响应格式异常: {context}.{field} 非法"
457
+ )
458
+ if isinstance(value, int):
459
+ return value
460
+ if isinstance(value, float) and value.is_integer():
461
+ return int(value)
462
+ if isinstance(value, str):
463
+ text = value.strip()
464
+ try:
465
+ number = float(text)
466
+ except ValueError:
467
+ raise AdapterError(
468
+ f"恒源云响应格式异常: {context}.{field} 非法"
469
+ ) from None
470
+ if not number.is_integer():
471
+ raise AdapterError(
472
+ f"恒源云响应格式异常: {context}.{field} 非法"
473
+ )
474
+ return int(number)
475
+ raise AdapterError(
476
+ f"恒源云响应格式异常: {context}.{field} 非法"
477
+ )
478
+
479
+
480
+ def _as_float(value, field: str, context: str) -> float:
481
+ if isinstance(value, bool):
482
+ raise AdapterError(
483
+ f"恒源云响应格式异常: {context}.{field} 非法"
484
+ )
485
+ if isinstance(value, (int, float)):
486
+ return float(value)
487
+ if isinstance(value, str):
488
+ try:
489
+ return float(value.strip())
490
+ except ValueError:
491
+ raise AdapterError(
492
+ f"恒源云响应格式异常: {context}.{field} 非法"
493
+ ) from None
494
+ raise AdapterError(
495
+ f"恒源云响应格式异常: {context}.{field} 非法"
496
+ )
497
+
498
+
499
+ def _matches_filters(
500
+ offer,
501
+ *,
502
+ gpu_model,
503
+ region,
504
+ min_free,
505
+ max_price,
506
+ min_vram_gb,
507
+ min_ram_gb,
508
+ min_cuda,
509
+ ) -> bool:
510
+ if gpu_model and gpu_model.casefold() not in offer.gpu_model.casefold():
511
+ return False
512
+ if region:
513
+ if not offer.region or region.casefold() not in offer.region.casefold():
514
+ return False
515
+ if offer.free < min_free:
516
+ return False
517
+ if max_price is not None:
518
+ if (
519
+ offer.price_per_hour is None
520
+ or offer.price_per_hour > max_price
521
+ ):
522
+ return False
523
+ if min_vram_gb is not None:
524
+ if (
525
+ offer.gpu_memory_gb is None
526
+ or offer.gpu_memory_gb < min_vram_gb
527
+ ):
528
+ return False
529
+ extra = offer.extra or {}
530
+ if min_ram_gb is not None:
531
+ ram = extra.get("ram_per_gpu_gb")
532
+ if ram is None or ram < min_ram_gb:
533
+ return False
534
+ if min_cuda is not None:
535
+ required = _version_tuple(min_cuda)
536
+ supported = _version_tuple(extra.get("gpu_toolkit_version"))
537
+ if supported is None or supported < required:
538
+ return False
539
+ return True
540
+
541
+
542
+ def is_valid_cuda_version(value) -> bool:
543
+ return _version_tuple(value) is not None
544
+
545
+
546
+ def _version_tuple(text):
547
+ if not isinstance(text, str):
548
+ return None
549
+ match = re.fullmatch(r"\d+(?:\.\d+){0,3}", text.strip())
550
+ if not match:
551
+ return None
552
+ parts = [int(part) for part in match.group(0).split(".")]
553
+ while len(parts) < 4:
554
+ parts.append(0)
555
+ return tuple(parts[:4])
556
+
557
+
558
+ def _size_gb(value, raw_bytes: bool):
559
+ if value is None:
560
+ return None
561
+ if isinstance(value, bool):
562
+ raise AdapterError("恒源云响应格式异常: 内存字段非法")
563
+
564
+ if isinstance(value, (int, float)):
565
+ number = float(value)
566
+ return number / 1024 ** 3 if raw_bytes else number
567
+
568
+ if not isinstance(value, str):
569
+ raise AdapterError("恒源云响应格式异常: 内存字段非法")
570
+
571
+ match = re.fullmatch(
572
+ r"\s*(\d+(?:\.\d+)?)\s*(TiB|TB|GiB|GB|MiB|MB|KiB|KB|B)?\s*",
573
+ value,
574
+ re.IGNORECASE,
575
+ )
576
+ if not match:
577
+ return None
578
+
579
+ number = float(match.group(1))
580
+ unit = (match.group(2) or "").upper()
581
+ if unit in ("TIB", "TB"):
582
+ return number * 1024
583
+ if unit in ("GIB", "GB"):
584
+ return number
585
+ if unit in ("MIB", "MB"):
586
+ return number / 1024
587
+ if unit in ("KIB", "KB"):
588
+ return number / 1048576
589
+ if unit == "B":
590
+ return number / 1073741824
591
+ return number / 1024 ** 3 if raw_bytes else number
592
+
593
+
594
+ def _is_non_negative_int(value) -> bool:
595
+ return (
596
+ isinstance(value, int)
597
+ and not isinstance(value, bool)
598
+ and value >= 0
599
+ )
600
+
601
+
602
+ def _format_time(value: datetime) -> str:
603
+ if value.tzinfo is None:
604
+ value = value.replace(tzinfo=timezone.utc)
605
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
606
+
607
+
608
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
609
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
610
+ raise AdapterError(
611
+ f"恒源云返回重定向 HTTP {code},已拒绝跟随"
612
+ )
613
+
614
+
615
+ def _http_json(
616
+ method: str,
617
+ url: str,
618
+ headers: dict,
619
+ payload: Optional[dict],
620
+ timeout: float,
621
+ ) -> object:
622
+ body = None
623
+ if payload is not None:
624
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
625
+
626
+ request = urllib.request.Request(
627
+ url,
628
+ data=body,
629
+ headers=headers,
630
+ method=method,
631
+ )
632
+ opener = urllib.request.build_opener(_NoRedirect)
633
+ try:
634
+ with opener.open(request, timeout=timeout) as response:
635
+ raw = response.read()
636
+ except urllib.error.HTTPError as exc:
637
+ if exc.code in (401, 403):
638
+ raise AuthFailedError(
639
+ "恒源云登录态失效或无权访问"
640
+ ) from None
641
+ if exc.code == 429:
642
+ raise AdapterError("恒源云请求被限流") from None
643
+ raise AdapterError(
644
+ f"请求恒源云失败: HTTP {exc.code}"
645
+ ) from None
646
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
647
+ reason = getattr(exc, "reason", None) or type(exc).__name__
648
+ raise AdapterError(f"请求恒源云失败: {reason}") from None
649
+
650
+ try:
651
+ return json.loads(raw.decode("utf-8"))
652
+ except (UnicodeDecodeError, json.JSONDecodeError):
653
+ raise AdapterError("恒源云响应不是合法 JSON") from None