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/config.py ADDED
@@ -0,0 +1,340 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ from cloudgpu.adapters.gpushare import is_valid_cuda_version
9
+ from cloudgpu.notify import CHANNEL_ENV
10
+
11
+
12
+ class ConfigError(ValueError):
13
+ """配置文件缺失、语法错误或字段非法。"""
14
+
15
+
16
+ KNOWN_PLATFORMS = {
17
+ "mornai",
18
+ "autodl",
19
+ "gpushare",
20
+ "gongji",
21
+ "matpool",
22
+ "gpugeek",
23
+ }
24
+ TOP_LEVEL_KEYS = {
25
+ "interval",
26
+ "jitter",
27
+ "state_file",
28
+ "notify",
29
+ "platforms",
30
+ "targets",
31
+ }
32
+ COMMON_TARGET_KEYS = {"name", "platform", "notify", "min_free"}
33
+ CREDENTIAL_KEYS = {
34
+ "token",
35
+ "password",
36
+ "secret",
37
+ "api_key",
38
+ "authorization",
39
+ }
40
+ NOTIFY_CHANNELS = set(CHANNEL_ENV) | {"terminal", "desktop"}
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class TargetConfig:
45
+ name: str
46
+ platform: str
47
+ options: dict
48
+ notify: Optional[tuple] = None
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class AppConfig:
53
+ interval: float
54
+ jitter: float
55
+ state_file: str
56
+ notify: tuple
57
+ platforms: dict
58
+ targets: tuple
59
+
60
+
61
+ def load_config(path) -> AppConfig:
62
+ path = Path(path).expanduser()
63
+ try:
64
+ raw = path.read_text(encoding="utf-8")
65
+ except (OSError, UnicodeDecodeError) as exc:
66
+ raise ConfigError(f"读取配置失败: {exc}") from None
67
+ try:
68
+ data = json.loads(raw)
69
+ except json.JSONDecodeError as exc:
70
+ raise ConfigError(f"配置不是合法 JSON: {exc}") from None
71
+ return _parse_config(data)
72
+
73
+
74
+ def _parse_config(data) -> AppConfig:
75
+ if not isinstance(data, dict):
76
+ raise ConfigError("配置顶层必须是对象")
77
+ _check_keys(data, TOP_LEVEL_KEYS, "配置")
78
+
79
+ interval = _number(
80
+ data.get("interval", 30), "interval", minimum=5
81
+ )
82
+ jitter = _number(
83
+ data.get("jitter", 5), "jitter", minimum=0
84
+ )
85
+ state_file = data.get("state_file", "~/.cloudgpu/state.json")
86
+ if not isinstance(state_file, str) or not state_file.strip():
87
+ raise ConfigError("state_file 必须是非空字符串")
88
+ notify = _notify(data.get("notify", ["terminal"]), "notify")
89
+ platforms = _parse_platforms(data.get("platforms", {}))
90
+
91
+ raw_targets = data.get("targets")
92
+ if not isinstance(raw_targets, list) or not raw_targets:
93
+ raise ConfigError("targets 必须是非空数组")
94
+
95
+ targets = []
96
+ names = set()
97
+ for index, item in enumerate(raw_targets):
98
+ target = _parse_target(item, index, platforms)
99
+ if target.name in names:
100
+ raise ConfigError(f"target 名称重复: {target.name}")
101
+ names.add(target.name)
102
+ targets.append(target)
103
+
104
+ return AppConfig(
105
+ interval=interval,
106
+ jitter=jitter,
107
+ state_file=state_file,
108
+ notify=notify,
109
+ platforms=platforms,
110
+ targets=tuple(targets),
111
+ )
112
+
113
+
114
+ def _parse_platforms(value) -> dict:
115
+ if not isinstance(value, dict):
116
+ raise ConfigError("platforms 必须是对象")
117
+ platforms = {}
118
+ for name, item in value.items():
119
+ if name not in KNOWN_PLATFORMS:
120
+ raise ConfigError(f"未知平台: {name}")
121
+ if not isinstance(item, dict):
122
+ raise ConfigError(f"platforms.{name} 必须是对象")
123
+ _check_keys(item, {"token_file"}, f"platforms.{name}")
124
+ token_file = item.get("token_file")
125
+ if token_file is not None and (
126
+ not isinstance(token_file, str) or not token_file.strip()
127
+ ):
128
+ raise ConfigError(
129
+ f"platforms.{name}.token_file 必须是非空字符串"
130
+ )
131
+ platforms[name] = {
132
+ "token_file": (
133
+ token_file.strip() if token_file else None
134
+ )
135
+ }
136
+ return platforms
137
+
138
+
139
+ def _parse_target(item, index: int, platforms: dict) -> TargetConfig:
140
+ label = f"targets[{index}]"
141
+ if not isinstance(item, dict):
142
+ raise ConfigError(f"{label} 必须是对象")
143
+
144
+ name = item.get("name")
145
+ if not isinstance(name, str) or not name.strip():
146
+ raise ConfigError(f"{label}.name 必须是非空字符串")
147
+ name = name.strip()
148
+
149
+ platform = item.get("platform")
150
+ if platform not in KNOWN_PLATFORMS:
151
+ raise ConfigError(f"{label}.platform 非法: {platform!r}")
152
+
153
+ min_free = item.get("min_free", 1)
154
+ if (
155
+ isinstance(min_free, bool)
156
+ or not isinstance(min_free, int)
157
+ or min_free < 1
158
+ ):
159
+ raise ConfigError(f"{label}.min_free 必须是 >=1 的整数")
160
+
161
+ notify = None
162
+ if "notify" in item:
163
+ notify = _notify(item["notify"], f"{label}.notify")
164
+
165
+ if platform == "mornai":
166
+ allowed = COMMON_TARGET_KEYS | {"kind", "gpu"}
167
+ _check_keys(item, allowed, label)
168
+ kind = item.get("kind", "cloud")
169
+ if kind not in ("cloud", "container", "both"):
170
+ raise ConfigError(f"{label}.kind 非法: {kind!r}")
171
+ options = {
172
+ "kind": kind,
173
+ "gpu": _str_list(item.get("gpu", []), f"{label}.gpu"),
174
+ "min_free": min_free,
175
+ }
176
+ elif platform == "autodl":
177
+ allowed = COMMON_TARGET_KEYS | {"scope", "regions", "region", "gpu"}
178
+ _check_keys(item, allowed, label)
179
+ scope = item.get("scope", "region")
180
+ if scope not in ("region", "machine"):
181
+ raise ConfigError(f"{label}.scope 非法: {scope!r}")
182
+ if "regions" in item and "region" in item:
183
+ raise ConfigError(
184
+ f"{label} 不能同时设置 regions 和 region"
185
+ )
186
+ if "regions" in item:
187
+ regions = _str_list(item["regions"], f"{label}.regions")
188
+ elif "region" in item:
189
+ regions = _str_list(item["region"], f"{label}.region")
190
+ else:
191
+ regions = ()
192
+ gpu = _str_list(item.get("gpu", []), f"{label}.gpu")
193
+ if scope == "machine" and (
194
+ len(regions) != 1 or len(gpu) != 1
195
+ ):
196
+ raise ConfigError(
197
+ f"{label} 机器级需要恰好一个 region 和一个 gpu"
198
+ )
199
+ options = {
200
+ "scope": scope,
201
+ "regions": regions,
202
+ "gpu": gpu,
203
+ "min_free": min_free,
204
+ }
205
+ elif platform in ("gongji", "matpool", "gpugeek"):
206
+ allowed = COMMON_TARGET_KEYS | {
207
+ "gpu",
208
+ "region",
209
+ "max_price",
210
+ "min_vram",
211
+ "min_ram",
212
+ }
213
+ _check_keys(item, allowed, label)
214
+ options = {
215
+ "gpu": _single_optional_str(
216
+ item.get("gpu"), f"{label}.gpu"
217
+ ),
218
+ "region": _single_optional_str(
219
+ item.get("region"), f"{label}.region"
220
+ ),
221
+ "min_free": min_free,
222
+ "max_price": _optional_number(
223
+ item.get("max_price"), f"{label}.max_price"
224
+ ),
225
+ "min_vram": _optional_number(
226
+ item.get("min_vram"), f"{label}.min_vram"
227
+ ),
228
+ "min_ram": _optional_number(
229
+ item.get("min_ram"), f"{label}.min_ram"
230
+ ),
231
+ }
232
+ else:
233
+ allowed = COMMON_TARGET_KEYS | {
234
+ "gpu",
235
+ "region",
236
+ "max_price",
237
+ "min_vram",
238
+ "min_ram",
239
+ "min_cuda",
240
+ }
241
+ _check_keys(item, allowed, label)
242
+ gpu = _single_optional_str(item.get("gpu"), f"{label}.gpu")
243
+ region = _single_optional_str(
244
+ item.get("region"), f"{label}.region"
245
+ )
246
+ max_price = _optional_number(
247
+ item.get("max_price"), f"{label}.max_price"
248
+ )
249
+ min_vram = _optional_number(
250
+ item.get("min_vram"), f"{label}.min_vram"
251
+ )
252
+ min_ram = _optional_number(
253
+ item.get("min_ram"), f"{label}.min_ram"
254
+ )
255
+ min_cuda = item.get("min_cuda")
256
+ if min_cuda is not None and not is_valid_cuda_version(min_cuda):
257
+ raise ConfigError(f"{label}.min_cuda 非法: {min_cuda!r}")
258
+ options = {
259
+ "gpu": gpu,
260
+ "region": region,
261
+ "min_free": min_free,
262
+ "max_price": max_price,
263
+ "min_vram": min_vram,
264
+ "min_ram": min_ram,
265
+ "min_cuda": min_cuda,
266
+ }
267
+
268
+ return TargetConfig(
269
+ name=name,
270
+ platform=platform,
271
+ options=options,
272
+ notify=notify,
273
+ )
274
+
275
+
276
+ def _check_keys(mapping: dict, allowed: set, label: str) -> None:
277
+ for key in mapping:
278
+ if key in CREDENTIAL_KEYS or key.lower() in CREDENTIAL_KEYS:
279
+ raise ConfigError(
280
+ f"{label} 不允许凭据字段: {key}"
281
+ )
282
+ if key not in allowed:
283
+ raise ConfigError(f"{label} 未知字段: {key}")
284
+
285
+
286
+ def _number(value, field: str, minimum: float) -> float:
287
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
288
+ raise ConfigError(f"{field} 必须是数字")
289
+ if value < minimum:
290
+ raise ConfigError(f"{field} 不能小于 {minimum}")
291
+ return float(value)
292
+
293
+
294
+ def _optional_number(value, field: str):
295
+ if value is None:
296
+ return None
297
+ return _number(value, field, minimum=0)
298
+
299
+
300
+ def _str_list(value, field: str) -> tuple:
301
+ if value is None:
302
+ return ()
303
+ if isinstance(value, str):
304
+ value = [value]
305
+ if not isinstance(value, list):
306
+ raise ConfigError(f"{field} 必须是字符串或字符串数组")
307
+ result = []
308
+ for item in value:
309
+ if not isinstance(item, str) or not item.strip():
310
+ raise ConfigError(f"{field} 包含非空字符串")
311
+ result.append(item.strip())
312
+ return tuple(result)
313
+
314
+
315
+ def _single_optional_str(value, field: str):
316
+ if value is None:
317
+ return None
318
+ if isinstance(value, str):
319
+ if not value.strip():
320
+ raise ConfigError(f"{field} 不能为空")
321
+ return value.strip()
322
+ if isinstance(value, list):
323
+ if len(value) != 1:
324
+ raise ConfigError(f"{field} 最多只能有一个值")
325
+ return _single_optional_str(value[0], field)
326
+ raise ConfigError(f"{field} 必须是字符串")
327
+
328
+
329
+ def _notify(value, field: str) -> tuple:
330
+ if isinstance(value, str):
331
+ value = [value]
332
+ if not isinstance(value, list) or not value:
333
+ raise ConfigError(f"{field} 必须是非空数组")
334
+ result = []
335
+ for item in value:
336
+ if not isinstance(item, str) or item not in NOTIFY_CHANNELS:
337
+ raise ConfigError(f"{field} 包含未知渠道: {item!r}")
338
+ if item not in result:
339
+ result.append(item)
340
+ return tuple(result)
cloudgpu/dashboard.py ADDED
@@ -0,0 +1,267 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ import threading
5
+ from dataclasses import dataclass, replace
6
+ from datetime import datetime, timezone
7
+
8
+ from cloudgpu.snapshot import collect_snapshot
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class DashboardState:
13
+ snapshot: object = None
14
+ last_error: object = None
15
+ last_started_at: object = None
16
+ last_finished_at: object = None
17
+ refreshing: bool = False
18
+ paused: bool = False
19
+ last_success_at: object = None
20
+ stale: bool = False
21
+
22
+
23
+ class DashboardService:
24
+ def __init__(
25
+ self,
26
+ config,
27
+ *,
28
+ adapters=None,
29
+ env=None,
30
+ clock=None,
31
+ sleeper=None,
32
+ random_func=None,
33
+ ) -> None:
34
+ self.config = config
35
+ self.adapters = adapters
36
+ self.env = env
37
+ self._clock = clock or (
38
+ lambda: datetime.now(timezone.utc)
39
+ )
40
+ self._random = random_func or random.random
41
+ self._lock = threading.Lock()
42
+ self._state = DashboardState()
43
+ self._stop_event = threading.Event()
44
+ self._paused_event = threading.Event()
45
+ self._refresh_lock = threading.Lock()
46
+ self._thread = None
47
+
48
+ def refresh(self):
49
+ if not self._refresh_lock.acquire(blocking=False):
50
+ return None
51
+ try:
52
+ started = _now_text(self._clock())
53
+ with self._lock:
54
+ previous = self._state.snapshot
55
+ previous_success = self._state.last_success_at
56
+ self._state = DashboardState(
57
+ snapshot=previous,
58
+ last_error=self._state.last_error,
59
+ last_started_at=started,
60
+ last_finished_at=self._state.last_finished_at,
61
+ refreshing=True,
62
+ paused=self._state.paused,
63
+ last_success_at=self._state.last_success_at,
64
+ )
65
+ try:
66
+ snapshot = collect_snapshot(
67
+ self.config,
68
+ adapters=self.adapters,
69
+ env=self.env,
70
+ )
71
+ except Exception as exc:
72
+ with self._lock:
73
+ self._state = DashboardState(
74
+ snapshot=previous,
75
+ last_error=str(exc),
76
+ last_started_at=started,
77
+ last_finished_at=_now_text(self._clock()),
78
+ refreshing=False,
79
+ paused=self._state.paused,
80
+ last_success_at=(
81
+ self._state.last_success_at
82
+ ),
83
+ )
84
+ return None
85
+ finished = _now_text(self._clock())
86
+ all_failed = (
87
+ snapshot.targets_total > 0
88
+ and snapshot.targets_ok == 0
89
+ )
90
+ with self._lock:
91
+ self._state = DashboardState(
92
+ snapshot=snapshot,
93
+ last_error=(
94
+ "所有 target 查询失败"
95
+ if all_failed else None
96
+ ),
97
+ last_started_at=started,
98
+ last_finished_at=finished,
99
+ refreshing=False,
100
+ paused=self._state.paused,
101
+ last_success_at=(
102
+ previous_success
103
+ if all_failed else finished
104
+ ),
105
+ stale=False,
106
+ )
107
+ if all_failed:
108
+ return None
109
+ return snapshot
110
+ finally:
111
+ self._refresh_lock.release()
112
+
113
+ def set_paused(self, paused: bool) -> None:
114
+ with self._lock:
115
+ self._state = replace(
116
+ self._state, paused=bool(paused)
117
+ )
118
+ if paused:
119
+ self._paused_event.set()
120
+ else:
121
+ self._paused_event.clear()
122
+
123
+ def start(self) -> None:
124
+ if self._thread is not None and self._thread.is_alive():
125
+ return
126
+ self._stop_event.clear()
127
+ self._thread = threading.Thread(
128
+ target=self._run, daemon=True
129
+ )
130
+ self._thread.start()
131
+
132
+ def stop(self) -> None:
133
+ self._stop_event.set()
134
+ thread = self._thread
135
+ if (
136
+ thread is not None
137
+ and thread is not threading.current_thread()
138
+ ):
139
+ thread.join(timeout=2.0)
140
+ self._thread = None
141
+
142
+ def state(self) -> DashboardState:
143
+ with self._lock:
144
+ state = self._state
145
+ return replace(
146
+ state,
147
+ stale=_is_stale(
148
+ state, self.config, self._clock()
149
+ ),
150
+ )
151
+
152
+ def next_delay(self) -> float:
153
+ return max(
154
+ 0.0,
155
+ float(self.config.interval)
156
+ + self._random() * float(self.config.jitter),
157
+ )
158
+
159
+ def _run(self) -> None:
160
+ self.refresh()
161
+ while not self._stop_event.wait(self.next_delay()):
162
+ if not self._paused_event.is_set():
163
+ self.refresh()
164
+
165
+
166
+ def snapshot_rows(snapshot) -> list:
167
+ if snapshot is None:
168
+ return []
169
+ rows = []
170
+ for item in snapshot.items:
171
+ offer = item.offer
172
+ rows.append(
173
+ {
174
+ "target": item.target,
175
+ "platform": offer.platform,
176
+ "service_kind": offer.service_kind,
177
+ "gpu_model": offer.gpu_model,
178
+ "region": offer.region,
179
+ "free": offer.free,
180
+ "total": offer.total,
181
+ "price_per_hour": offer.price_per_hour,
182
+ "gpu_memory_gb": offer.gpu_memory_gb,
183
+ "machine_id": offer.machine_id,
184
+ }
185
+ )
186
+ return rows
187
+
188
+
189
+ def snapshot_payload(state: DashboardState) -> dict:
190
+ snapshot = state.snapshot
191
+ if snapshot is None:
192
+ offers = []
193
+ errors = []
194
+ checked_at = None
195
+ targets_ok = 0
196
+ targets_total = 0
197
+ else:
198
+ offers = [
199
+ {
200
+ **item.offer.to_dict(),
201
+ "target": item.target,
202
+ }
203
+ for item in snapshot.items
204
+ ]
205
+ errors = [
206
+ {
207
+ "target": error.target,
208
+ "platform": error.platform,
209
+ "error": error.error,
210
+ }
211
+ for error in snapshot.errors
212
+ ]
213
+ checked_at = snapshot.checked_at
214
+ targets_ok = snapshot.targets_ok
215
+ targets_total = snapshot.targets_total
216
+ return {
217
+ "checked_at": checked_at,
218
+ "targets_ok": targets_ok,
219
+ "targets_total": targets_total,
220
+ "offers": offers,
221
+ "errors": errors,
222
+ "last_error": state.last_error,
223
+ "last_started_at": state.last_started_at,
224
+ "last_finished_at": state.last_finished_at,
225
+ "refreshing": state.refreshing,
226
+ "paused": state.paused,
227
+ "last_success_at": state.last_success_at,
228
+ "stale": state.stale,
229
+ }
230
+
231
+
232
+ def format_price(value) -> str:
233
+ if value is None:
234
+ return "-"
235
+ return f"¥{value:.2f}"
236
+
237
+
238
+ def format_free(free, total) -> str:
239
+ return f"{free}/{total if total is not None else '?'}"
240
+
241
+
242
+ def _is_stale(state, config, now: datetime) -> bool:
243
+ if state.snapshot is None:
244
+ return False
245
+ if not state.last_success_at:
246
+ return False
247
+ try:
248
+ success = datetime.fromisoformat(
249
+ str(state.last_success_at).replace("Z", "+00:00")
250
+ )
251
+ except ValueError:
252
+ return True
253
+ if success.tzinfo is None:
254
+ success = success.replace(tzinfo=timezone.utc)
255
+ if now.tzinfo is None:
256
+ now = now.replace(tzinfo=timezone.utc)
257
+ age = (now - success.astimezone(timezone.utc)).total_seconds()
258
+ threshold = max(2.0 * float(config.interval), 30.0)
259
+ return age > threshold
260
+
261
+
262
+ def _now_text(value: datetime) -> str:
263
+ if value.tzinfo is None:
264
+ value = value.replace(tzinfo=timezone.utc)
265
+ return value.astimezone(timezone.utc).strftime(
266
+ "%Y-%m-%dT%H:%M:%SZ"
267
+ )