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/web.py ADDED
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import webbrowser
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ from pathlib import Path
7
+
8
+ from cloudgpu.dashboard import DashboardService, snapshot_payload
9
+
10
+ WEBUI_PATH = Path(__file__).with_name("webui.html")
11
+
12
+
13
+ def create_web_server(service, *, host="127.0.0.1", port=8787):
14
+ html = WEBUI_PATH.read_text(encoding="utf-8")
15
+
16
+ class Handler(BaseHTTPRequestHandler):
17
+ def do_GET(self):
18
+ path = self.path.split("?", 1)[0]
19
+ if path == "/api/snapshot":
20
+ payload = snapshot_payload(service.state())
21
+ body = json.dumps(
22
+ payload, ensure_ascii=False
23
+ ).encode("utf-8")
24
+ self._send(
25
+ body, "application/json; charset=utf-8"
26
+ )
27
+ elif path in ("/", "/index.html"):
28
+ self._send(
29
+ html.encode("utf-8"),
30
+ "text/html; charset=utf-8",
31
+ )
32
+ else:
33
+ self.send_error(404)
34
+
35
+ def _send(self, body, content_type):
36
+ self.send_response(200)
37
+ self.send_header("Content-Type", content_type)
38
+ self.send_header("Cache-Control", "no-store")
39
+ self.send_header("Content-Length", str(len(body)))
40
+ self.end_headers()
41
+ self.wfile.write(body)
42
+
43
+ def log_message(self, format, *args):
44
+ pass
45
+
46
+ return ThreadingHTTPServer((host, port), Handler)
47
+
48
+
49
+ def run_web(
50
+ config,
51
+ *,
52
+ host="127.0.0.1",
53
+ port=8787,
54
+ open_browser=True,
55
+ allow_lan=False,
56
+ adapters=None,
57
+ env=None,
58
+ service=None,
59
+ ) -> int:
60
+ if not allow_lan and not _is_loopback(host):
61
+ raise ValueError(
62
+ "非 loopback 地址需要 --allow-lan"
63
+ )
64
+ active = service or DashboardService(
65
+ config, adapters=adapters, env=env
66
+ )
67
+ server = create_web_server(
68
+ active, host=host, port=port
69
+ )
70
+ actual_port = server.server_address[1]
71
+ url = f"http://{_browser_host(host)}:{actual_port}/"
72
+ print(f"Web 面板: {url}")
73
+ notice = _lan_notice(host, allow_lan)
74
+ if notice:
75
+ import sys
76
+
77
+ print(notice, file=sys.stderr)
78
+ active.start()
79
+ if open_browser:
80
+ webbrowser.open(url)
81
+ try:
82
+ server.serve_forever()
83
+ except KeyboardInterrupt:
84
+ pass
85
+ finally:
86
+ server.shutdown()
87
+ server.server_close()
88
+ active.stop()
89
+ return 0
90
+
91
+
92
+ def _is_loopback(host: str) -> bool:
93
+ return host in ("127.0.0.1", "localhost", "::1")
94
+
95
+
96
+ def _browser_host(host: str) -> str:
97
+ if host in ("0.0.0.0", "::", ""):
98
+ return "127.0.0.1"
99
+ if host == "::1":
100
+ return "[::1]"
101
+ return host
102
+
103
+
104
+ def _lan_notice(host: str, allow_lan: bool):
105
+ if allow_lan and not _is_loopback(host):
106
+ return (
107
+ "警告: Web 面板未鉴权,当前绑定 "
108
+ f"{host},局域网内可见"
109
+ )
110
+ return None
cloudgpu/webui.html ADDED
@@ -0,0 +1,428 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>cloudgpu 空闲监控</title>
7
+ <style>
8
+ :root {
9
+ --bg: #0f1115;
10
+ --panel: #171a21;
11
+ --panel-2: #1c2029;
12
+ --line: #2a2f3a;
13
+ --text: #e6e8ec;
14
+ --muted: #9aa3b2;
15
+ --accent: #6ea8fe;
16
+ --ok: #3ddc97;
17
+ --warn: #ffb020;
18
+ --err: #ff6b6b;
19
+ }
20
+ * { box-sizing: border-box; }
21
+ body {
22
+ margin: 0;
23
+ background: var(--bg);
24
+ color: var(--text);
25
+ font: 14px/1.5 ui-sans-serif, system-ui, -apple-system,
26
+ "Segoe UI", "Noto Sans SC", sans-serif;
27
+ }
28
+ header {
29
+ padding: 20px 24px 10px;
30
+ display: flex;
31
+ flex-wrap: wrap;
32
+ gap: 12px;
33
+ align-items: baseline;
34
+ justify-content: space-between;
35
+ }
36
+ h1 { margin: 0; font-size: 20px; font-weight: 650; }
37
+ .muted { color: var(--muted); }
38
+ .pills { display: flex; flex-wrap: wrap; gap: 8px; }
39
+ .pill {
40
+ border: 1px solid var(--line);
41
+ background: var(--panel);
42
+ border-radius: 999px;
43
+ padding: 3px 10px;
44
+ font-size: 12px;
45
+ color: var(--muted);
46
+ }
47
+ .pill.ok { color: var(--ok); border-color: #1f5c45; }
48
+ .pill.warn { color: var(--warn); border-color: #6b4a12; }
49
+ .pill.err { color: var(--err); border-color: #6b2424; }
50
+ main { padding: 0 24px 32px; }
51
+ .cards {
52
+ display: grid;
53
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
54
+ gap: 10px;
55
+ margin-bottom: 14px;
56
+ }
57
+ .card {
58
+ background: var(--panel);
59
+ border: 1px solid var(--line);
60
+ border-radius: 10px;
61
+ padding: 10px 12px;
62
+ }
63
+ .card .label { color: var(--muted); font-size: 12px; }
64
+ .card .value {
65
+ font-size: 20px;
66
+ font-weight: 650;
67
+ margin-top: 2px;
68
+ font-variant-numeric: tabular-nums;
69
+ }
70
+ .stale-banner {
71
+ margin-bottom: 12px;
72
+ border: 1px solid #6b2424;
73
+ background: #2a1717;
74
+ color: #ffd0d0;
75
+ padding: 9px 12px;
76
+ border-radius: 8px;
77
+ }
78
+ [hidden] { display: none !important; }
79
+ .filters {
80
+ display: flex;
81
+ flex-wrap: wrap;
82
+ gap: 8px;
83
+ align-items: end;
84
+ margin-bottom: 12px;
85
+ }
86
+ .field { display: flex; flex-direction: column; gap: 3px; }
87
+ .field label { color: var(--muted); font-size: 11px; }
88
+ input, select {
89
+ background: var(--panel);
90
+ color: var(--text);
91
+ border: 1px solid var(--line);
92
+ border-radius: 7px;
93
+ padding: 6px 8px;
94
+ font: inherit;
95
+ }
96
+ input[type="number"] { width: 90px; }
97
+ .table-wrap {
98
+ border: 1px solid var(--line);
99
+ border-radius: 10px;
100
+ overflow: auto;
101
+ background: var(--panel);
102
+ }
103
+ table { width: 100%; border-collapse: collapse; min-width: 820px; }
104
+ th, td {
105
+ padding: 9px 12px;
106
+ text-align: left;
107
+ border-bottom: 1px solid var(--line);
108
+ white-space: nowrap;
109
+ }
110
+ th {
111
+ position: sticky; top: 0;
112
+ background: var(--panel-2);
113
+ color: var(--muted);
114
+ font-weight: 600;
115
+ font-size: 12px;
116
+ letter-spacing: .02em;
117
+ }
118
+ tr:last-child td { border-bottom: 0; }
119
+ td.num { text-align: right; font-variant-numeric: tabular-nums; }
120
+ td.gpu { font-weight: 600; }
121
+ td.price { color: var(--accent); }
122
+ .empty { padding: 28px 12px; text-align: center; color: var(--muted); }
123
+ .errors { margin-top: 16px; }
124
+ .errors h2 { font-size: 13px; color: var(--muted); margin: 0 0 8px; }
125
+ .errors ul { margin: 0; padding: 0; list-style: none; }
126
+ .errors li {
127
+ border-left: 3px solid var(--err);
128
+ background: var(--panel);
129
+ padding: 7px 10px;
130
+ margin-bottom: 6px;
131
+ border-radius: 0 6px 6px 0;
132
+ color: #ffd0d0;
133
+ overflow-wrap: anywhere;
134
+ }
135
+ .refresh-error {
136
+ margin-top: 14px;
137
+ border: 1px solid #6b2424;
138
+ background: #2a1717;
139
+ color: #ffd0d0;
140
+ padding: 8px 10px;
141
+ border-radius: 8px;
142
+ }
143
+ @media (max-width: 640px) {
144
+ header, main { padding-left: 14px; padding-right: 14px; }
145
+ }
146
+ </style>
147
+ </head>
148
+ <body>
149
+ <header>
150
+ <div>
151
+ <h1>cloudgpu 空闲监控</h1>
152
+ <div class="muted" id="updated">等待数据…</div>
153
+ </div>
154
+ <div class="pills" id="summary"></div>
155
+ </header>
156
+ <main>
157
+ <div class="stale-banner" id="stale-banner" hidden></div>
158
+ <div class="cards" id="cards"></div>
159
+ <div class="filters">
160
+ <div class="field"><label for="platform-filter">平台</label>
161
+ <select id="platform-filter"><option value="">全部</option></select>
162
+ </div>
163
+ <div class="field"><label for="target-filter">Target</label>
164
+ <select id="target-filter"><option value="">全部</option></select>
165
+ </div>
166
+ <div class="field"><label for="search-input">型号/地区</label>
167
+ <input id="search-input" type="search" placeholder="4090 / 西北">
168
+ </div>
169
+ <div class="field"><label for="min-free">最少空闲</label>
170
+ <input id="min-free" type="number" min="0" step="1" placeholder="0">
171
+ </div>
172
+ <div class="field"><label for="max-price">最高价/时</label>
173
+ <input id="max-price" type="number" min="0" step="0.01" placeholder="不限">
174
+ </div>
175
+ <div class="field"><label for="sort-select">排序</label>
176
+ <select id="sort-select">
177
+ <option value="price-asc">价格升序</option>
178
+ <option value="price-desc">价格降序</option>
179
+ <option value="free-desc">空闲降序</option>
180
+ <option value="target">Target</option>
181
+ </select>
182
+ </div>
183
+ <div class="field"><label for="interval-select">刷新</label>
184
+ <select id="interval-select">
185
+ <option value="2">2 秒</option>
186
+ <option value="5" selected>5 秒</option>
187
+ <option value="10">10 秒</option>
188
+ <option value="30">30 秒</option>
189
+ </select>
190
+ </div>
191
+ </div>
192
+ <div class="table-wrap">
193
+ <table>
194
+ <thead>
195
+ <tr>
196
+ <th>Target</th><th>平台</th><th>型号</th><th>地区</th>
197
+ <th>空闲</th><th>价格/时</th><th>显存</th><th>规格/机器</th>
198
+ </tr>
199
+ </thead>
200
+ <tbody id="offers-body">
201
+ <tr><td colspan="8" class="empty">等待第一次刷新…</td></tr>
202
+ </tbody>
203
+ </table>
204
+ </div>
205
+ <div class="errors" id="errors"></div>
206
+ <div id="refresh-error"></div>
207
+ </main>
208
+ <script>
209
+ const STORAGE_KEY = "cloudgpu.web.filters";
210
+ let latest = null;
211
+ let timer = null;
212
+ let prefs = {};
213
+
214
+ function esc(value) {
215
+ return String(value ?? "").replace(/[&<>"']/g, c => ({
216
+ "&": "&amp;", "<": "&lt;", ">": "&gt;",
217
+ "\"": "&quot;", "'": "&#39;"
218
+ }[c]));
219
+ }
220
+ function price(value) {
221
+ return value === null || value === undefined
222
+ ? "-" : "¥" + Number(value).toFixed(2);
223
+ }
224
+ function freeText(offer) {
225
+ const total = offer.total === null || offer.total === undefined
226
+ ? "?" : offer.total;
227
+ return `${offer.free}/${total}`;
228
+ }
229
+ function store() {
230
+ try {
231
+ return JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
232
+ } catch (_) {
233
+ return {};
234
+ }
235
+ }
236
+ function save() {
237
+ prefs = {
238
+ platform: document.getElementById("platform-filter").value,
239
+ target: document.getElementById("target-filter").value,
240
+ search: document.getElementById("search-input").value,
241
+ minFree: document.getElementById("min-free").value,
242
+ maxPrice: document.getElementById("max-price").value,
243
+ sort: document.getElementById("sort-select").value,
244
+ interval: document.getElementById("interval-select").value
245
+ };
246
+ try {
247
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
248
+ } catch (_) {}
249
+ }
250
+ function restore() {
251
+ prefs = store();
252
+ const fields = {
253
+ search: "search-input", minFree: "min-free",
254
+ maxPrice: "max-price", sort: "sort-select",
255
+ interval: "interval-select"
256
+ };
257
+ Object.entries(fields).forEach(([key, id]) => {
258
+ if (prefs[key] !== undefined && prefs[key] !== "") {
259
+ document.getElementById(id).value = prefs[key];
260
+ }
261
+ });
262
+ }
263
+ function options(id, values, selected) {
264
+ const el = document.getElementById(id);
265
+ el.innerHTML = '<option value="">全部</option>' + values.map(v =>
266
+ `<option value="${esc(v)}">${esc(v)}</option>`
267
+ ).join("");
268
+ if (values.includes(selected)) el.value = selected;
269
+ }
270
+ function statusInfo(data) {
271
+ if (data.paused) return {text: "已暂停", cls: "warn"};
272
+ if (data.stale) return {text: "数据已过期", cls: "err"};
273
+ if (!data.checked_at) return {text: "等待", cls: "warn"};
274
+ if (data.targets_total > 0 && data.targets_ok === 0) {
275
+ return {text: "监控失败", cls: "err"};
276
+ }
277
+ if (data.refreshing) return {text: "刷新中", cls: "warn"};
278
+ return {text: "正常", cls: "ok"};
279
+ }
280
+ function filtered(offers) {
281
+ const platform = document.getElementById("platform-filter").value;
282
+ const target = document.getElementById("target-filter").value;
283
+ const search = document.getElementById("search-input").value.trim().toLowerCase();
284
+ const minFree = Number(document.getElementById("min-free").value || 0);
285
+ const maxPriceRaw = document.getElementById("max-price").value;
286
+ const maxPrice = maxPriceRaw === "" ? null : Number(maxPriceRaw);
287
+ let rows = offers.filter(o =>
288
+ (!platform || o.platform === platform) &&
289
+ (!target || o.target === target) &&
290
+ (!search || `${o.gpu_model} ${o.display_name || ""} ${o.region || ""}`.toLowerCase().includes(search)) &&
291
+ (o.free >= minFree) &&
292
+ (maxPrice === null || (o.price_per_hour !== null && o.price_per_hour !== undefined && o.price_per_hour <= maxPrice))
293
+ );
294
+ const sort = document.getElementById("sort-select").value;
295
+ const priceKey = o => o.price_per_hour == null ? Infinity : o.price_per_hour;
296
+ if (sort === "price-asc") rows.sort((a, b) => priceKey(a) - priceKey(b));
297
+ if (sort === "price-desc") rows.sort((a, b) => {
298
+ const av = a.price_per_hour == null ? -Infinity : a.price_per_hour;
299
+ const bv = b.price_per_hour == null ? -Infinity : b.price_per_hour;
300
+ return bv - av;
301
+ });
302
+ if (sort === "free-desc") rows.sort((a, b) => b.free - a.free);
303
+ if (sort === "target") rows.sort((a, b) =>
304
+ `${a.target} ${a.platform} ${a.gpu_model}`.localeCompare(
305
+ `${b.target} ${b.platform} ${b.gpu_model}`));
306
+ return rows;
307
+ }
308
+ function render(data) {
309
+ latest = data;
310
+ const offers = data.offers || [];
311
+ const errors = data.errors || [];
312
+ const ok = data.targets_ok || 0;
313
+ const total = data.targets_total || 0;
314
+ const selectedPlatform = prefs.platform !== undefined
315
+ ? prefs.platform
316
+ : document.getElementById("platform-filter").value;
317
+ const selectedTarget = prefs.target !== undefined
318
+ ? prefs.target
319
+ : document.getElementById("target-filter").value;
320
+
321
+ options("platform-filter",
322
+ [...new Set(offers.map(o => o.platform))].sort(),
323
+ selectedPlatform);
324
+ options("target-filter",
325
+ [...new Set(offers.map(o => o.target))].sort(),
326
+ selectedTarget);
327
+ prefs.platform = document.getElementById("platform-filter").value;
328
+ prefs.target = document.getElementById("target-filter").value;
329
+
330
+ const status = statusInfo(data);
331
+ const rows = filtered(offers);
332
+ const freeSum = rows.reduce((sum, o) => sum + (o.free || 0), 0);
333
+ const prices = rows.map(o => o.price_per_hour)
334
+ .filter(v => v !== null && v !== undefined);
335
+ const minPrice = prices.length ? Math.min(...prices) : null;
336
+ document.getElementById("summary").innerHTML = [
337
+ `<span class="pill ${ok > 0 ? "ok" : "err"}">target ${ok}/${total}</span>`,
338
+ `<span class="pill ${errors.length ? "warn" : "ok"}">错误 ${errors.length}</span>`,
339
+ `<span class="pill ${status.cls}">${esc(status.text)}</span>`
340
+ ].join("");
341
+ document.getElementById("cards").innerHTML = [
342
+ ["显示条目", rows.length],
343
+ ["空闲卡", freeSum],
344
+ ["最低价/时", minPrice === null ? "-" : price(minPrice)],
345
+ ["错误", errors.length],
346
+ ["数据状态", status.text]
347
+ ].map(([label, value]) =>
348
+ `<div class="card"><div class="label">${label}</div><div class="value">${esc(value)}</div></div>`
349
+ ).join("");
350
+
351
+ const stale = document.getElementById("stale-banner");
352
+ if (data.stale) {
353
+ stale.hidden = false;
354
+ stale.textContent = `数据已过期,最后成功刷新 ${data.last_success_at || "未知"}`;
355
+ } else {
356
+ stale.hidden = true;
357
+ }
358
+
359
+ document.getElementById("updated").textContent =
360
+ data.checked_at ? `检查时间 ${data.checked_at}` : "尚无成功快照";
361
+
362
+ const body = document.getElementById("offers-body");
363
+ if (!rows.length) {
364
+ const message = data.checked_at
365
+ ? "没有符合条件的空闲资源"
366
+ : "等待第一次刷新…";
367
+ body.innerHTML =
368
+ `<tr><td colspan="8" class="empty">${message}</td></tr>`;
369
+ } else {
370
+ body.innerHTML = rows.map(o => `
371
+ <tr>
372
+ <td>${esc(o.target)}</td>
373
+ <td>${esc(o.platform)}</td>
374
+ <td class="gpu">${esc(o.gpu_model)}</td>
375
+ <td>${esc(o.region || "-")}</td>
376
+ <td class="num">${esc(freeText(o))}</td>
377
+ <td class="num price">${esc(price(o.price_per_hour))}</td>
378
+ <td class="num">${o.gpu_memory_gb == null ? "-" : esc(o.gpu_memory_gb) + "G"}</td>
379
+ <td>${esc(o.machine_id || o.service_kind || "-")}</td>
380
+ </tr>`).join("");
381
+ }
382
+
383
+ const errorsBox = document.getElementById("errors");
384
+ errorsBox.innerHTML = errors.length
385
+ ? "<h2>查询错误</h2><ul>" + errors.map(e =>
386
+ `<li>${esc(e.target)} (${esc(e.platform)}): ${esc(e.error)}</li>`
387
+ ).join("") + "</ul>"
388
+ : "";
389
+ const refreshError = document.getElementById("refresh-error");
390
+ refreshError.innerHTML = data.last_error
391
+ ? `<div class="refresh-error">刷新失败: ${esc(data.last_error)}</div>`
392
+ : "";
393
+ }
394
+ function apply() {
395
+ save();
396
+ if (latest) render(latest);
397
+ }
398
+ function schedule() {
399
+ if (timer) clearInterval(timer);
400
+ const allowed = [2, 5, 10, 30];
401
+ const requested = Number(
402
+ document.getElementById("interval-select").value || 5
403
+ );
404
+ const seconds = allowed.includes(requested) ? requested : 5;
405
+ timer = setInterval(load, seconds * 1000);
406
+ }
407
+ async function load() {
408
+ try {
409
+ const response = await fetch("/api/snapshot", {cache: "no-store"});
410
+ if (!response.ok) throw new Error("HTTP " + response.status);
411
+ render(await response.json());
412
+ } catch (err) {
413
+ document.getElementById("refresh-error").innerHTML =
414
+ `<div class="refresh-error">无法读取数据: ${esc(err.message)}</div>`;
415
+ }
416
+ }
417
+ ["platform-filter", "target-filter", "search-input", "min-free", "max-price", "sort-select"]
418
+ .forEach(id => document.getElementById(id).addEventListener("input", apply));
419
+ document.getElementById("interval-select").addEventListener("change", () => {
420
+ save();
421
+ schedule();
422
+ });
423
+ restore();
424
+ schedule();
425
+ load();
426
+ </script>
427
+ </body>
428
+ </html>