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/desktop.py ADDED
@@ -0,0 +1,249 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ import threading
6
+ from pathlib import Path
7
+
8
+ from cloudgpu.config import ConfigError, load_config
9
+ from cloudgpu.dashboard import (
10
+ DashboardService,
11
+ format_free,
12
+ format_price,
13
+ snapshot_rows,
14
+ )
15
+
16
+
17
+ def desktop_status(state) -> str:
18
+ snapshot = state.snapshot
19
+ if snapshot is None:
20
+ return (
21
+ f"尚未成功刷新 {state.last_error or ''}"
22
+ ).strip()
23
+ text = (
24
+ f"检查时间 {snapshot.checked_at} "
25
+ f"target {snapshot.targets_ok}/"
26
+ f"{snapshot.targets_total} "
27
+ f"错误 {len(snapshot.errors)} "
28
+ f"{'刷新中' if state.refreshing else ''}"
29
+ ).strip()
30
+ if state.stale:
31
+ text += " 数据已过期"
32
+ return text
33
+
34
+
35
+ def desktop_error_lines(state) -> list:
36
+ snapshot = state.snapshot
37
+ lines = [
38
+ f"{error.target} ({error.platform}): {error.error}"
39
+ for error in (snapshot.errors if snapshot else ())
40
+ ]
41
+ if state.last_error:
42
+ lines.append(f"刷新失败: {state.last_error}")
43
+ return lines
44
+
45
+
46
+ def desktop_rows(state) -> list:
47
+ rows = []
48
+ for row in snapshot_rows(state.snapshot):
49
+ rows.append(
50
+ (
51
+ row["target"],
52
+ row["platform"],
53
+ row["gpu_model"],
54
+ row["region"] or "-",
55
+ format_free(row["free"], row["total"]),
56
+ format_price(row["price_per_hour"]),
57
+ (
58
+ f"{row['gpu_memory_gb']}G"
59
+ if row["gpu_memory_gb"] is not None
60
+ else "-"
61
+ ),
62
+ )
63
+ )
64
+ return rows
65
+
66
+
67
+ def main(argv=None) -> int:
68
+ parser = argparse.ArgumentParser(
69
+ prog="cloudgpu-desktop",
70
+ description="cloudgpu 桌面监控",
71
+ )
72
+ parser.add_argument("--config", default=None)
73
+ args = parser.parse_args(argv)
74
+
75
+ try:
76
+ import tkinter as tk
77
+ from tkinter import messagebox, ttk
78
+ except ImportError:
79
+ print(
80
+ "错误: 缺少 tkinter,请安装 python3-tk 或使用"
81
+ "官方 Python",
82
+ file=sys.stderr,
83
+ )
84
+ return 2
85
+
86
+ path = _config_path(args.config)
87
+ if not path.exists():
88
+ path = _pick_config()
89
+ if path is None:
90
+ return 2
91
+
92
+ try:
93
+ config = load_config(path)
94
+ except ConfigError as exc:
95
+ try:
96
+ root = tk.Tk()
97
+ root.withdraw()
98
+ messagebox.showerror("配置错误", str(exc))
99
+ root.destroy()
100
+ except Exception:
101
+ print(f"错误: {exc}", file=sys.stderr)
102
+ return 2
103
+
104
+ try:
105
+ root = tk.Tk()
106
+ except Exception as exc:
107
+ print(f"错误: 无法打开桌面窗口: {exc}", file=sys.stderr)
108
+ return 2
109
+
110
+ service = DashboardService(config)
111
+ app = DesktopApp(root, service, str(path), tk, ttk)
112
+ try:
113
+ root.mainloop()
114
+ finally:
115
+ service.stop()
116
+ return 0
117
+
118
+
119
+ class DesktopApp:
120
+ def __init__(self, root, service, config_path, tk, ttk) -> None:
121
+ self.root = root
122
+ self.service = service
123
+ self.config_path = config_path
124
+ self.tk = tk
125
+ self.after_id = None
126
+ self.refresh_thread = None
127
+ self.closed = False
128
+
129
+ root.title("cloudgpu 空闲监控")
130
+ root.geometry("1180x640")
131
+
132
+ toolbar = tk.Frame(root, padx=10, pady=8)
133
+ toolbar.pack(fill="x")
134
+ tk.Label(toolbar, text=config_path).pack(
135
+ side="left"
136
+ )
137
+ tk.Button(
138
+ toolbar, text="立即刷新", command=self.refresh
139
+ ).pack(side="right")
140
+
141
+ columns = (
142
+ "target", "platform", "gpu", "region",
143
+ "free", "price", "vram",
144
+ )
145
+ headings = (
146
+ ("target", "Target", 160),
147
+ ("platform", "平台", 100),
148
+ ("gpu", "型号", 240),
149
+ ("region", "地区", 120),
150
+ ("free", "空闲", 80),
151
+ ("price", "价格/时", 90),
152
+ ("vram", "显存", 70),
153
+ )
154
+ self.tree = ttk.Treeview(
155
+ root, columns=columns, show="headings"
156
+ )
157
+ for key, label, width in headings:
158
+ self.tree.heading(key, text=label)
159
+ self.tree.column(key, width=width, anchor="w")
160
+ self.tree.pack(fill="both", expand=True, padx=10)
161
+
162
+ self.status = tk.StringVar(value="等待第一次刷新…")
163
+ tk.Label(
164
+ root, textvariable=self.status, anchor="w"
165
+ ).pack(fill="x", padx=10, pady=(6, 2))
166
+
167
+ tk.Label(
168
+ root, text="查询错误", anchor="w"
169
+ ).pack(fill="x", padx=10)
170
+ self.errors = tk.Text(
171
+ root, height=6, wrap="word", state="disabled"
172
+ )
173
+ self.errors.pack(fill="x", padx=10, pady=(0, 8))
174
+
175
+ self.service.start()
176
+ self._poll()
177
+ root.protocol("WM_DELETE_WINDOW", self.close)
178
+
179
+ def refresh(self) -> None:
180
+ if (
181
+ self.refresh_thread is not None
182
+ and self.refresh_thread.is_alive()
183
+ ):
184
+ return
185
+ self.refresh_thread = threading.Thread(
186
+ target=self.service.refresh, daemon=True
187
+ )
188
+ self.refresh_thread.start()
189
+
190
+ def _poll(self) -> None:
191
+ if self.closed:
192
+ return
193
+ self._render(self.service.state())
194
+ self.after_id = self.root.after(1000, self._poll)
195
+
196
+ def _render(self, state) -> None:
197
+ for item in self.tree.get_children():
198
+ self.tree.delete(item)
199
+ for row in desktop_rows(state):
200
+ self.tree.insert("", "end", values=row)
201
+
202
+ self.status.set(desktop_status(state))
203
+
204
+ lines = desktop_error_lines(state)
205
+ self.errors.configure(state="normal")
206
+ self.errors.delete("1.0", "end")
207
+ self.errors.insert("1.0", "\n".join(lines))
208
+ self.errors.configure(state="disabled")
209
+
210
+ def close(self) -> None:
211
+ self.closed = True
212
+ if self.after_id is not None:
213
+ try:
214
+ self.root.after_cancel(self.after_id)
215
+ except Exception:
216
+ pass
217
+ self.service.stop()
218
+ self.root.destroy()
219
+
220
+
221
+ def _config_path(value):
222
+ if value:
223
+ return Path(value).expanduser()
224
+ return Path.home() / ".cloudgpu" / "config.json"
225
+
226
+
227
+ def _pick_config():
228
+ try:
229
+ import tkinter as tk
230
+ from tkinter import filedialog
231
+ root = tk.Tk()
232
+ root.withdraw()
233
+ except Exception:
234
+ return None
235
+ try:
236
+ selected = filedialog.askopenfilename(
237
+ title="选择 cloudgpu 配置文件",
238
+ filetypes=[
239
+ ("JSON", "*.json"),
240
+ ("All files", "*.*"),
241
+ ],
242
+ )
243
+ finally:
244
+ root.destroy()
245
+ return Path(selected) if selected else None
246
+
247
+
248
+ if __name__ == "__main__":
249
+ raise SystemExit(main())
cloudgpu/doctor.py ADDED
@@ -0,0 +1,295 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from dataclasses import asdict, dataclass
6
+ from datetime import datetime, timedelta, timezone
7
+ from pathlib import Path
8
+
9
+ from cloudgpu.adapters.autodl import (
10
+ DEFAULT_TOKEN_FILE as AUTODL_TOKEN,
11
+ )
12
+ from cloudgpu.adapters.autodl import AutoDLAdapter
13
+ from cloudgpu.adapters.autodl import jwt_expiry as autodl_jwt
14
+ from cloudgpu.adapters.gongji import (
15
+ DEFAULT_TOKEN_FILE as GONGJI_TOKEN,
16
+ )
17
+ from cloudgpu.adapters.gongji import GongjiAdapter
18
+ from cloudgpu.adapters.gpushare import (
19
+ DEFAULT_TOKEN_FILE as GPUSHARE_TOKEN,
20
+ )
21
+ from cloudgpu.adapters.gpushare import GpuShareAdapter
22
+ from cloudgpu.adapters.gpushare import _jwt_expiry as gpushare_jwt
23
+ from cloudgpu.errors import AdapterError, AuthRequiredError
24
+ from cloudgpu.gongji_state import (
25
+ GongjiPendingStore,
26
+ GongjiStateError,
27
+ GongjiTtlStore,
28
+ )
29
+ from cloudgpu.orders import read_blocking_orders
30
+ from cloudgpu.snapshot import collect_snapshot
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Check:
35
+ name: str
36
+ status: str
37
+ detail: str
38
+
39
+
40
+ def run_doctor(
41
+ config,
42
+ *,
43
+ env=None,
44
+ check_api=False,
45
+ adapters=None,
46
+ ) -> list:
47
+ env = os.environ if env is None else env
48
+ checks = [
49
+ Check(
50
+ "config",
51
+ "ok",
52
+ f"{len(config.targets)} targets, platforms="
53
+ + ",".join(
54
+ sorted({t.platform for t in config.targets})
55
+ ),
56
+ )
57
+ ]
58
+
59
+ platforms = {target.platform for target in config.targets}
60
+ if "autodl" in platforms:
61
+ _check_autodl(config, env, checks)
62
+ if "gpushare" in platforms:
63
+ _check_gpushare(config, env, checks)
64
+ if "gongji" in platforms:
65
+ _check_gongji(config, env, checks)
66
+
67
+ _check_state_file(config, checks)
68
+ _check_orders(env, checks)
69
+ _check_gongji_pending(env, checks)
70
+ _check_gongji_ttl(env, checks)
71
+ checks.append(
72
+ Check(
73
+ "web",
74
+ "warn",
75
+ "Web 默认 loopback;--allow-lan 无鉴权,"
76
+ "请仅在可信局域网使用",
77
+ )
78
+ )
79
+
80
+ if check_api:
81
+ _check_api(config, env, adapters, checks)
82
+ return checks
83
+
84
+
85
+ def _check_autodl(config, env, checks):
86
+ path = _token_path(config, "autodl", AUTODL_TOKEN)
87
+ _mode_check("autodl.token", path, checks)
88
+ adapter = AutoDLAdapter(token_file=path, env=env)
89
+ try:
90
+ token = adapter.require_token()
91
+ except AdapterError as exc:
92
+ checks.append(Check("autodl.token", "fail", str(exc)))
93
+ return
94
+ _jwt_check("autodl.token", token, autodl_jwt, checks)
95
+
96
+
97
+ def _check_gpushare(config, env, checks):
98
+ path = _token_path(
99
+ config, "gpushare", GPUSHARE_TOKEN
100
+ )
101
+ _mode_check("gpushare.token", path, checks)
102
+ adapter = GpuShareAdapter(token_file=path, env=env)
103
+ try:
104
+ token = adapter.require_token()
105
+ except AdapterError as exc:
106
+ checks.append(
107
+ Check("gpushare.token", "fail", str(exc))
108
+ )
109
+ return
110
+ _jwt_check(
111
+ "gpushare.token", token, gpushare_jwt, checks
112
+ )
113
+
114
+
115
+ def _check_gongji(config, env, checks):
116
+ path = _token_path(config, "gongji", GONGJI_TOKEN)
117
+ _mode_check("gongji.token", path, checks)
118
+ key_path = env.get("CLOUDGPU_GONGJI_KEY_FILE")
119
+ key = (
120
+ Path(key_path).expanduser()
121
+ if key_path
122
+ else Path.home() / ".cloudgpu" / "gongji.key"
123
+ )
124
+ if key.exists():
125
+ _mode_check("gongji.key", key, checks)
126
+ try:
127
+ GongjiAdapter(
128
+ token_file=path,
129
+ env=env,
130
+ private_key_file=key if key.exists() else None,
131
+ ).require_token()
132
+ except AdapterError as exc:
133
+ checks.append(Check("gongji.token", "fail", str(exc)))
134
+
135
+
136
+ def _jwt_check(name, token, parser, checks):
137
+ expiry = parser(token)
138
+ if expiry is None:
139
+ checks.append(
140
+ Check(name, "ok", "token 存在(无法解析过期时间)")
141
+ )
142
+ return
143
+ now = datetime.now(timezone.utc)
144
+ if expiry <= now:
145
+ checks.append(Check(name, "fail", "token 已过期"))
146
+ elif expiry <= now + timedelta(days=7):
147
+ checks.append(
148
+ Check(
149
+ name,
150
+ "warn",
151
+ f"token 将于 {expiry.isoformat()} 过期",
152
+ )
153
+ )
154
+ else:
155
+ checks.append(
156
+ Check(name, "ok", f"token 有效至 {expiry.isoformat()}")
157
+ )
158
+
159
+
160
+ def _token_path(config, platform, default):
161
+ value = (
162
+ config.platforms.get(platform, {}).get("token_file")
163
+ )
164
+ return Path(value).expanduser() if value else default
165
+
166
+
167
+ def _mode_check(name, path, checks):
168
+ if not path or not path.exists():
169
+ return
170
+ try:
171
+ mode = path.stat().st_mode & 0o777
172
+ except OSError as exc:
173
+ checks.append(Check(name, "warn", f"无法读取权限: {exc}"))
174
+ return
175
+ if mode & 0o077:
176
+ checks.append(
177
+ Check(
178
+ name,
179
+ "warn",
180
+ f"权限过宽 {oct(mode)},建议 chmod 600",
181
+ )
182
+ )
183
+
184
+
185
+ def _check_state_file(config, checks):
186
+ path = Path(config.state_file).expanduser()
187
+ if not path.exists():
188
+ return
189
+ _mode_check("state_file", path, checks)
190
+
191
+
192
+ def _check_orders(env, checks):
193
+ default = Path.home() / ".cloudgpu" / "orders.db"
194
+ path = Path(env.get("CLOUDGPU_ORDERS_DB", default))
195
+ if not path.exists():
196
+ return
197
+ _mode_check("autodl.orders", path, checks)
198
+ try:
199
+ blocking = read_blocking_orders(path)
200
+ except Exception as exc:
201
+ checks.append(
202
+ Check("autodl.orders", "fail", f"读取失败: {exc}")
203
+ )
204
+ return
205
+ if blocking:
206
+ checks.append(
207
+ Check(
208
+ "autodl.orders",
209
+ "warn",
210
+ f"存在 {len(blocking)} 个未解决订单",
211
+ )
212
+ )
213
+
214
+
215
+ def _check_gongji_pending(env, checks):
216
+ default = Path.home() / ".cloudgpu" / "gongji_pending.json"
217
+ path = Path(
218
+ env.get("CLOUDGPU_GONGJI_PENDING_DB", default)
219
+ )
220
+ if not path.exists():
221
+ return
222
+ _mode_check("gongji.pending", path, checks)
223
+ try:
224
+ blocking = GongjiPendingStore(path).blocking()
225
+ except GongjiStateError as exc:
226
+ checks.append(
227
+ Check("gongji.pending", "fail", str(exc))
228
+ )
229
+ return
230
+ if blocking:
231
+ checks.append(
232
+ Check(
233
+ "gongji.pending",
234
+ "warn",
235
+ f"存在 {len(blocking)} 个未解决任务",
236
+ )
237
+ )
238
+
239
+
240
+ def _check_gongji_ttl(env, checks):
241
+ default = Path.home() / ".cloudgpu" / "gongji_ttl.json"
242
+ path = Path(env.get("CLOUDGPU_GONGJI_TTL_DB", default))
243
+ if not path.exists():
244
+ return
245
+ _mode_check("gongji.ttl", path, checks)
246
+ try:
247
+ GongjiTtlStore(path).all()
248
+ except GongjiStateError as exc:
249
+ checks.append(Check("gongji.ttl", "fail", str(exc)))
250
+
251
+
252
+ def _check_api(config, env, adapters, checks):
253
+ try:
254
+ snapshot = collect_snapshot(
255
+ config, adapters=adapters, env=env
256
+ )
257
+ except Exception as exc:
258
+ checks.append(
259
+ Check("api", "fail", f"检查失败: {exc}")
260
+ )
261
+ return
262
+ if snapshot.targets_ok == 0 and snapshot.targets_total:
263
+ checks.append(
264
+ Check("api", "fail", "所有 target 查询失败")
265
+ )
266
+ else:
267
+ checks.append(
268
+ Check(
269
+ "api",
270
+ "ok",
271
+ f"{snapshot.targets_ok}/"
272
+ f"{snapshot.targets_total} target 成功",
273
+ )
274
+ )
275
+ for error in snapshot.errors:
276
+ checks.append(
277
+ Check(
278
+ f"api.{error.target}",
279
+ "fail",
280
+ f"{error.platform}: {error.error}",
281
+ )
282
+ )
283
+
284
+
285
+ def checks_payload(checks) -> dict:
286
+ failures = sum(1 for check in checks if check.status == "fail")
287
+ warnings = sum(
288
+ 1 for check in checks if check.status == "warn"
289
+ )
290
+ return {
291
+ "checks": [asdict(check) for check in checks],
292
+ "ok": failures == 0,
293
+ "warnings": warnings,
294
+ "failures": failures,
295
+ }
cloudgpu/errors.py ADDED
@@ -0,0 +1,39 @@
1
+ class AdapterError(RuntimeError):
2
+ """平台查询或响应解析失败。保留原始原因,供 CLI 输出。"""
3
+
4
+
5
+ class AuthRequiredError(AdapterError):
6
+ """缺少平台凭据。"""
7
+
8
+
9
+ class AuthFailedError(AdapterError):
10
+ """平台返回鉴权失败。"""
11
+
12
+
13
+ class OrderRejectedError(AdapterError):
14
+ """平台明确拒绝下单,或库存已变化。"""
15
+
16
+ def __init__(self, message, kind="rejected", code=None):
17
+ super().__init__(message)
18
+ self.kind = kind
19
+ self.code = code
20
+
21
+
22
+ class OrderUncertainError(AdapterError):
23
+ """下单请求可能已到达平台,但无法确认结果。"""
24
+
25
+
26
+ class TaskRejectedError(AdapterError):
27
+ """平台明确拒绝任务创建或生命周期操作。"""
28
+
29
+ def __init__(self, message, code=None):
30
+ super().__init__(message)
31
+ self.code = code
32
+
33
+
34
+ class TaskUncertainError(AdapterError):
35
+ """任务创建请求可能已到达平台,但无法确认结果。"""
36
+
37
+
38
+ class TaskNotFoundError(AdapterError):
39
+ """平台明确表示任务不存在。"""