dsh-quay-bot 0.7.4 → 1.0.0

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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -28
  3. package/bin/doctor.mjs +148 -0
  4. package/botscreen/requirements-offline.txt +11 -0
  5. package/client.js +1 -2
  6. package/cordis.patch.yml +1 -1
  7. package/host/api.js +0 -4
  8. package/host/remote.js +2 -140
  9. package/host/screen.js +85 -21
  10. package/market/index.json +41 -0
  11. package/package.json +32 -13
  12. package/vendor/wheels/any/annotated_doc-0.0.7-py3-none-any.whl +0 -0
  13. package/vendor/wheels/any/annotated_types-0.8.0-py3-none-any.whl +0 -0
  14. package/vendor/wheels/any/anyio-4.16.0-py3-none-any.whl +0 -0
  15. package/vendor/wheels/any/certifi-2026.11.20-py3-none-any.whl +0 -0
  16. package/vendor/wheels/any/click-8.5.1-py3-none-any.whl +0 -0
  17. package/vendor/wheels/any/fastapi-0.165.0-py3-none-any.whl +0 -0
  18. package/vendor/wheels/any/h11-0.16.0-py3-none-any.whl +0 -0
  19. package/vendor/wheels/any/httpcore-1.0.9-py3-none-any.whl +0 -0
  20. package/vendor/wheels/any/httpx-0.29.0-py3-none-any.whl +0 -0
  21. package/vendor/wheels/any/idna-3.20-py3-none-any.whl +0 -0
  22. package/vendor/wheels/any/mss-10.2.0-py3-none-any.whl +0 -0
  23. package/vendor/wheels/any/opentelemetry_api-1.45.2-py3-none-any.whl +0 -0
  24. package/vendor/wheels/any/pydantic-2.14.4-py3-none-any.whl +0 -0
  25. package/vendor/wheels/any/python_multipart-0.0.34-py3-none-any.whl +0 -0
  26. package/vendor/wheels/any/python_xlib-0.33-py2.py3-none-any.whl +0 -0
  27. package/vendor/wheels/any/six-1.17.0-py2.py3-none-any.whl +0 -0
  28. package/vendor/wheels/any/starlette-1.10.0-py3-none-any.whl +0 -0
  29. package/vendor/wheels/any/typing_extensions-4.16.0-py3-none-any.whl +0 -0
  30. package/vendor/wheels/any/typing_inspection-0.4.5-py3-none-any.whl +0 -0
  31. package/vendor/wheels/any/uvicorn-0.54.0-py3-none-any.whl +0 -0
  32. package/vendor/wheels/linux-aarch64/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
  33. package/vendor/wheels/linux-aarch64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
  34. package/vendor/wheels/linux-aarch64/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl +0 -0
  35. package/vendor/wheels/linux-x86_64/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
  36. package/vendor/wheels/linux-x86_64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
  37. package/vendor/wheels/linux-x86_64/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl +0 -0
  38. package/botscreen/botscreen/__init__.py +0 -2
  39. package/botscreen/botscreen/__main__.py +0 -5
  40. package/botscreen/botscreen/artifacts.py +0 -388
  41. package/botscreen/botscreen/audit.py +0 -94
  42. package/botscreen/botscreen/cgroup.py +0 -293
  43. package/botscreen/botscreen/config.py +0 -320
  44. package/botscreen/botscreen/desktop/assets/chrome.png +0 -0
  45. package/botscreen/botscreen/desktop/assets/codex.png +0 -0
  46. package/botscreen/botscreen/desktop/assets/drive.png +0 -0
  47. package/botscreen/botscreen/desktop/assets/folder.png +0 -0
  48. package/botscreen/botscreen/desktop/assets/search.png +0 -0
  49. package/botscreen/botscreen/desktop/assets/terminal.png +0 -0
  50. package/botscreen/botscreen/desktop/assets/trash.png +0 -0
  51. package/botscreen/botscreen/desktop/assets/wallpaper.png +0 -0
  52. package/botscreen/botscreen/desktop.py +0 -244
  53. package/botscreen/botscreen/driver.py +0 -832
  54. package/botscreen/botscreen/gateway.py +0 -2089
  55. package/botscreen/botscreen/iconlayer.py +0 -841
  56. package/botscreen/botscreen/mcp_server.py +0 -435
  57. package/botscreen/botscreen/resources.py +0 -494
  58. package/botscreen/botscreen/screen.py +0 -1282
  59. package/botscreen/botscreen/session.py +0 -706
  60. package/botscreen/botscreen/state.py +0 -330
  61. package/botscreen/botscreen/streamer.py +0 -388
  62. package/remote/bin/dsh-remote.mjs +0 -418
  63. package/remote/package.json +0 -27
  64. package/remote/src/config.mjs +0 -183
  65. package/remote/src/crypto.mjs +0 -220
  66. package/remote/src/keys.mjs +0 -226
  67. package/remote/src/proxy.mjs +0 -1028
  68. package/remote/src/sessions.mjs +0 -163
  69. package/remote/src/shim.js +0 -838
  70. package/remote/src/supervisor.mjs +0 -207
  71. package/remote/src/tunnel.mjs +0 -489
  72. package/remote/src/upstream.mjs +0 -372
  73. package/remote/src/util.mjs +0 -139
  74. package/remote/src/ws.mjs +0 -313
  75. package/requirements.txt +0 -8
@@ -1,494 +0,0 @@
1
- """宿主资源门禁与系统信息采集:
2
- - 虚拟屏启动前内存门禁(cgroup 与 /proc/meminfo 取较小值)
3
- - 系统信息实时采集(磁盘占用、内存占用、CPU 占用、开机时长),纯标准库零第三方依赖
4
- """
5
- from __future__ import annotations
6
-
7
- import os
8
- import platform
9
- import shutil
10
- import socket
11
- import threading
12
- import time
13
- from dataclasses import dataclass
14
- from datetime import datetime, timezone
15
- from pathlib import Path
16
- from typing import Optional, Sequence
17
-
18
- from .config import DEFAULT_DISK_PATHS, MIN_FREE_MB
19
-
20
- _MIB = 1024 * 1024
21
- _GIB = 1024 * 1024 * 1024
22
- _CGROUP_V2 = Path("/sys/fs/cgroup")
23
- _CGROUP_V1 = Path("/sys/fs/cgroup/memory")
24
- _MEMINFO = Path("/proc/meminfo")
25
- _PROC_STAT = Path("/proc/stat")
26
- _PROC_UPTIME = Path("/proc/uptime")
27
-
28
- _CPU_LOCK = threading.Lock()
29
- _LAST_CPU_SAMPLE: Optional[tuple[int, int, float]] = None # (total_jiffies, idle_jiffies, mono_ts)
30
- _HOST_SUMMARY_LOCK = threading.Lock()
31
- _HOST_SUMMARY_CACHE: Optional[tuple[float, tuple[str, ...], Optional[bool], dict]] = None
32
- _HOST_SUMMARY_TTL_SEC = 0.4
33
-
34
-
35
- class MemoryBlocked(RuntimeError):
36
- """可用内存不足,拒绝拉起新屏。"""
37
-
38
-
39
- @dataclass
40
- class MemoryInfo:
41
- available_mb: Optional[int] # None = 读不到(非 Linux / 特殊沙箱)
42
- limit_mb: Optional[int] # cgroup 限额,无限额则为机器 MemTotal
43
-
44
-
45
- def _read_int(path: Path) -> Optional[int]:
46
- try:
47
- text = path.read_text(encoding="utf-8-sig").strip()
48
- except OSError:
49
- return None
50
- return int(text) if text.isdigit() else None # "max" → None
51
-
52
-
53
- def _meminfo() -> dict:
54
- out = {}
55
- try:
56
- with open(_MEMINFO, encoding="utf-8") as fh:
57
- for line in fh:
58
- key, _, rest = line.partition(":")
59
- parts = rest.split()
60
- if parts and parts[0].isdigit():
61
- out[key] = int(parts[0])
62
- except OSError:
63
- pass
64
- return out
65
-
66
-
67
- def _cgroup_limit_and_usage() -> tuple[Optional[int], Optional[int]]:
68
- """返回 (limit_bytes, usage_bytes);v2 优先,退到 v1。"""
69
- limit = _read_int(_CGROUP_V2 / "memory.max")
70
- usage = _read_int(_CGROUP_V2 / "memory.current")
71
- if limit is None and usage is None:
72
- limit = _read_int(_CGROUP_V1 / "memory.limit_in_bytes")
73
- usage = _read_int(_CGROUP_V1 / "memory.usage_in_bytes")
74
- if limit is not None and limit > 1 << 50: # "unlimited" 常见写法
75
- limit = None
76
- return limit, usage
77
-
78
-
79
- def memory_info() -> MemoryInfo:
80
- info = _meminfo()
81
- mem_available = info.get("MemAvailable")
82
- mem_total = info.get("MemTotal")
83
- limit, usage = _cgroup_limit_and_usage()
84
-
85
- candidates = []
86
- if mem_available is not None:
87
- candidates.append(mem_available // 1024) # kB → MB
88
- if limit is not None:
89
- candidates.append(max(0, (limit - (usage or 0)) // _MIB))
90
- if not candidates:
91
- return MemoryInfo(None, (mem_total // 1024) if mem_total else None)
92
- return MemoryInfo(min(candidates), (limit // _MIB) if limit else (mem_total // 1024 if mem_total else None))
93
-
94
-
95
- def min_free_mb() -> int:
96
- return MIN_FREE_MB
97
-
98
-
99
- def memory_blocker(info: Optional[MemoryInfo] = None, need_mb: Optional[int] = None) -> Optional[str]:
100
- """不能启动的原因;None 表示可以启动。读不到内存不算阻塞(宁可启动)。"""
101
- if need_mb is not None and need_mb <= 0:
102
- return None
103
- info = info or memory_info()
104
- need = min_free_mb() if need_mb is None else need_mb
105
- if info.available_mb is None:
106
- return None
107
- if info.available_mb >= need:
108
- return None
109
- limit = f" / 限额 {info.limit_mb} MB" if info.limit_mb else ""
110
- return (
111
- f"内存不足,暂不拉起虚拟屏:可用 {info.available_mb} MB{limit},"
112
- f"需要至少 {need} MB(BOTSCREEN_MIN_FREE_MB)。"
113
- f"先冻结空闲屏,或调低该阈值。"
114
- )
115
-
116
-
117
- def require_memory() -> None:
118
- """启动前的门禁:不足就抛 MemoryBlocked(消息可直接给前端看)。"""
119
- blocker = memory_blocker()
120
- if blocker:
121
- raise MemoryBlocked(blocker)
122
-
123
-
124
- def summarize() -> dict:
125
- info = memory_info()
126
- return {
127
- "available_mb": info.available_mb,
128
- "limit_mb": info.limit_mb,
129
- "min_free_mb": min_free_mb(),
130
- "blocker": memory_blocker(info),
131
- }
132
-
133
-
134
- # ---------------------------------------------------------------- 系统信息采集 ----
135
- _LAST_CPU_PCT: Optional[float] = None
136
-
137
-
138
- def _read_cpu_jiffies() -> Optional[tuple[int, int]]:
139
- """读取 /proc/stat 第一行汇总 CPU jiffies,返回 (total, idle_plus_iowait)。"""
140
- try:
141
- with open(_PROC_STAT, encoding="utf-8") as fh:
142
- for line in fh:
143
- if line.startswith("cpu "):
144
- parts = [int(x) for x in line.split()[1:] if x.isdigit()]
145
- if len(parts) >= 4:
146
- idle = parts[3] + (parts[4] if len(parts) > 4 else 0)
147
- return sum(parts), idle
148
- except OSError:
149
- pass
150
- return None
151
-
152
-
153
- def prime_cpu_sample() -> None:
154
- """在网关启动时预采样一次 CPU jiffies,确保首次接口查询无需等待。"""
155
- global _LAST_CPU_SAMPLE
156
- sample = _read_cpu_jiffies()
157
- if sample is not None:
158
- with _CPU_LOCK:
159
- _LAST_CPU_SAMPLE = (sample[0], sample[1], time.monotonic())
160
-
161
-
162
- def cpu_info(sample_interval: float = 0.08) -> dict:
163
- """采集 CPU 占用率、逻辑核心数与 1/5/15 分钟系统负载。"""
164
- global _LAST_CPU_SAMPLE, _LAST_CPU_PCT
165
- usage_pct: Optional[float] = None
166
- estimated = False
167
- now_mono = time.monotonic()
168
-
169
- with _CPU_LOCK:
170
- prev = _LAST_CPU_SAMPLE
171
- cached_pct = _LAST_CPU_PCT
172
-
173
- cur = _read_cpu_jiffies()
174
- if cur is not None:
175
- if prev is not None and (now_mono - prev[2]) < 0.15 and cached_pct is not None:
176
- # 高频并发查询时直接复用 150ms 内的最近计算值,避免 0-jiffy 抖动
177
- usage_pct = cached_pct
178
- elif prev is not None and (cur[0] - prev[0]) > 0:
179
- total_diff = cur[0] - prev[0]
180
- idle_diff = max(0, cur[1] - prev[1])
181
- usage_pct = max(0.0, min(100.0, (1.0 - idle_diff / total_diff) * 100.0))
182
- with _CPU_LOCK:
183
- _LAST_CPU_SAMPLE = (cur[0], cur[1], now_mono)
184
- _LAST_CPU_PCT = usage_pct
185
- else:
186
- # 冷启动首次采样:短间隔两次读取计算瞬时占用率
187
- wait = max(0.02, min(0.5, float(sample_interval))) if sample_interval > 0 else 0.0
188
- if wait > 0:
189
- time.sleep(wait)
190
- cur2 = _read_cpu_jiffies()
191
- now2 = time.monotonic()
192
- if cur2 is not None and (cur2[0] - cur[0]) > 0:
193
- total_diff = cur2[0] - cur[0]
194
- idle_diff = max(0, cur2[1] - cur[1])
195
- usage_pct = max(0.0, min(100.0, (1.0 - idle_diff / total_diff) * 100.0))
196
- with _CPU_LOCK:
197
- _LAST_CPU_SAMPLE = (cur2[0], cur2[1], now2)
198
- _LAST_CPU_PCT = usage_pct
199
- else:
200
- with _CPU_LOCK:
201
- _LAST_CPU_SAMPLE = (cur[0], cur[1], now_mono)
202
- usage_pct = cached_pct if cached_pct is not None else 0.0
203
- else:
204
- with _CPU_LOCK:
205
- _LAST_CPU_SAMPLE = (cur[0], cur[1], now_mono)
206
- usage_pct = cached_pct if cached_pct is not None else 0.0
207
-
208
- cores = os.cpu_count() or 1
209
- load_avg = None
210
- try:
211
- l1, l5, l15 = os.getloadavg()
212
- load_avg = {"1m": round(l1, 2), "5m": round(l5, 2), "15m": round(l15, 2)}
213
- except (OSError, AttributeError):
214
- load_avg = None
215
-
216
- # 极端受限沙箱无法读取 /proc/stat 时,用 1 分钟系统负载按核数估算 CPU 占用率
217
- if usage_pct is None and load_avg is not None:
218
- usage_pct = max(0.0, min(100.0, (load_avg["1m"] / max(1, cores)) * 100.0))
219
- estimated = True
220
-
221
- return {
222
- "usage_percent": round(usage_pct, 1) if usage_pct is not None else None,
223
- "cores": cores,
224
- "load_avg": load_avg,
225
- "estimated": estimated,
226
- }
227
-
228
-
229
- def memory_usage() -> dict:
230
- """采集内存占用详情(兼容 cgroup 限额与 /proc/meminfo 宿主机内存,无重复文件读取)。"""
231
- raw = _meminfo()
232
- mem_total_kb = raw.get("MemTotal")
233
- mem_available_kb = raw.get("MemAvailable")
234
- mem_free_kb = raw.get("MemFree")
235
- swap_total_kb = raw.get("SwapTotal", 0)
236
- swap_free_kb = raw.get("SwapFree", 0)
237
- cg_limit, cg_usage = _cgroup_limit_and_usage()
238
-
239
- host_total_bytes = mem_total_kb * 1024 if mem_total_kb is not None else None
240
- host_avail_bytes = mem_available_kb * 1024 if mem_available_kb is not None else None
241
- host_free_bytes = mem_free_kb * 1024 if mem_free_kb is not None else None
242
-
243
- # 有效总量取 cgroup 限额与宿主机物理内存的较小值
244
- cgroup_limited = False
245
- total_bytes = host_total_bytes
246
- if cg_limit is not None:
247
- if total_bytes is None or cg_limit < total_bytes:
248
- total_bytes = cg_limit
249
- cgroup_limited = True
250
-
251
- avail_candidates = []
252
- if host_avail_bytes is not None:
253
- avail_candidates.append(host_avail_bytes)
254
- if cg_limit is not None:
255
- avail_candidates.append(max(0, cg_limit - (cg_usage or 0)))
256
- available_bytes = min(avail_candidates) if avail_candidates else host_free_bytes
257
-
258
- used_bytes: Optional[int] = None
259
- usage_percent: Optional[float] = None
260
- if total_bytes is not None and total_bytes > 0 and available_bytes is not None:
261
- used_bytes = max(0, total_bytes - available_bytes)
262
- usage_percent = round((used_bytes / total_bytes) * 100.0, 1)
263
-
264
- gate_avail_mb = (available_bytes // _MIB) if avail_candidates else None
265
- gate_limit_mb = (
266
- (cg_limit // _MIB)
267
- if cg_limit is not None
268
- else ((mem_total_kb // 1024) if mem_total_kb is not None else None)
269
- )
270
- gate = MemoryInfo(gate_avail_mb, gate_limit_mb)
271
- swap_total_bytes = swap_total_kb * 1024
272
- swap_used_bytes = max(0, (swap_total_kb - swap_free_kb) * 1024)
273
-
274
- return {
275
- "total_bytes": total_bytes,
276
- "used_bytes": used_bytes,
277
- "available_bytes": available_bytes,
278
- "free_bytes": host_free_bytes,
279
- "total_mb": (total_bytes // _MIB) if total_bytes is not None else None,
280
- "used_mb": (used_bytes // _MIB) if used_bytes is not None else None,
281
- "available_mb": gate.available_mb,
282
- "limit_mb": gate.limit_mb,
283
- "usage_percent": usage_percent,
284
- "swap_total_mb": swap_total_bytes // _MIB,
285
- "swap_used_mb": swap_used_bytes // _MIB,
286
- "min_free_mb": min_free_mb(),
287
- "blocker": memory_blocker(gate),
288
- "cgroup_limited": cgroup_limited,
289
- "source": "cgroup" if cgroup_limited else "host",
290
- }
291
-
292
-
293
- def proc_tree_memory_bytes(pids: Sequence[int]) -> int:
294
- """在 cgroup 不可用的沙箱中,按 /proc/<pid>/status 的 VmRSS 汇总指定进程树的真实内存占用(字节)。"""
295
- total_kb = 0
296
- seen: set[int] = set()
297
- for raw_pid in pids:
298
- try:
299
- pid = int(raw_pid)
300
- except (TypeError, ValueError):
301
- continue
302
- if pid <= 0 or pid in seen:
303
- continue
304
- seen.add(pid)
305
- try:
306
- with open(f"/proc/{pid}/status", encoding="utf-8") as fh:
307
- for line in fh:
308
- if line.startswith("VmRSS:"):
309
- parts = line.split()
310
- if len(parts) >= 2 and parts[1].isdigit():
311
- total_kb += int(parts[1])
312
- break
313
- except OSError:
314
- continue
315
- return total_kb * 1024
316
-
317
-
318
- def _single_disk_usage(path: str) -> dict:
319
- try:
320
- usage = shutil.disk_usage(path)
321
- pct = round((usage.used / usage.total) * 100.0, 1) if usage.total > 0 else 0.0
322
- return {
323
- "path": path,
324
- "total_bytes": usage.total,
325
- "used_bytes": usage.used,
326
- "free_bytes": usage.free,
327
- "total_gb": round(usage.total / _GIB, 2),
328
- "used_gb": round(usage.used / _GIB, 2),
329
- "free_gb": round(usage.free / _GIB, 2),
330
- "usage_percent": pct,
331
- "ok": True,
332
- }
333
- except OSError as exc:
334
- return {
335
- "path": path,
336
- "total_bytes": None,
337
- "used_bytes": None,
338
- "free_bytes": None,
339
- "total_gb": None,
340
- "used_gb": None,
341
- "free_gb": None,
342
- "usage_percent": None,
343
- "ok": False,
344
- "error": str(exc),
345
- }
346
-
347
-
348
- def disk_info(paths: Optional[Sequence[str]] = None) -> dict:
349
- """采集一个或多个挂载点的磁盘占用信息;默认使用第一个有效路径作为主盘摘要。"""
350
- raw_paths = list(paths) if paths else list(DEFAULT_DISK_PATHS)
351
- clean_paths: list[str] = []
352
- for item in raw_paths:
353
- p = str(item or "").strip()
354
- if p and p not in clean_paths:
355
- clean_paths.append(p)
356
- if not clean_paths:
357
- clean_paths = ["/"]
358
-
359
- mounts = [_single_disk_usage(p) for p in clean_paths]
360
- primary = next((m for m in mounts if m.get("ok")), mounts[0])
361
- return {
362
- "path": primary["path"],
363
- "total_bytes": primary["total_bytes"],
364
- "used_bytes": primary["used_bytes"],
365
- "free_bytes": primary["free_bytes"],
366
- "total_gb": primary["total_gb"],
367
- "used_gb": primary["used_gb"],
368
- "free_gb": primary["free_gb"],
369
- "usage_percent": primary["usage_percent"],
370
- "mounts": mounts,
371
- }
372
-
373
-
374
- def _format_uptime(seconds: float) -> tuple[str, str, int, int, int, int]:
375
- total = max(0, int(seconds))
376
- days, rem = divmod(total, 86400)
377
- hours, rem = divmod(rem, 3600)
378
- minutes, secs = divmod(rem, 60)
379
- zh_parts = []
380
- en_parts = []
381
- if days:
382
- zh_parts.append(f"{days}天")
383
- en_parts.append(f"{days}d")
384
- if hours or days:
385
- zh_parts.append(f"{hours}小时")
386
- en_parts.append(f"{hours}h")
387
- zh_parts.append(f"{minutes}分")
388
- en_parts.append(f"{minutes}m")
389
- if not days and not hours:
390
- zh_parts.append(f"{secs}秒")
391
- en_parts.append(f"{secs}s")
392
- return " ".join(zh_parts), " ".join(en_parts), days, hours, minutes, secs
393
-
394
-
395
- def uptime_info() -> dict:
396
- """采集系统开机时长(优先读取 /proc/uptime)。"""
397
- uptime_seconds: Optional[float] = None
398
- try:
399
- raw = _PROC_UPTIME.read_text(encoding="utf-8").strip().split()
400
- if raw:
401
- uptime_seconds = float(raw[0])
402
- except (OSError, ValueError):
403
- uptime_seconds = None
404
-
405
- if uptime_seconds is None:
406
- uptime_seconds = time.monotonic()
407
-
408
- zh_fmt, en_fmt, days, hours, minutes, secs = _format_uptime(uptime_seconds)
409
- boot_ts = max(0.0, time.time() - uptime_seconds)
410
- boot_iso = datetime.fromtimestamp(boot_ts, tz=timezone.utc).isoformat()
411
- return {
412
- "seconds": int(uptime_seconds),
413
- "days": days,
414
- "hours": hours,
415
- "minutes": minutes,
416
- "secs": secs,
417
- "formatted": zh_fmt,
418
- "formatted_en": en_fmt,
419
- "boot_time": boot_iso,
420
- }
421
-
422
-
423
- def system_info(
424
- disk_paths: Optional[Sequence[str]] = None,
425
- sample_interval: float = 0.08,
426
- cgroup_available: Optional[bool] = None,
427
- ) -> dict:
428
- """汇总系统信息:主机标识、CPU 占用、内存占用、磁盘占用、开机时长。"""
429
- now = time.time()
430
- out = {
431
- "hostname": socket.gethostname(),
432
- "os": platform.system(),
433
- "arch": platform.machine(),
434
- "kernel": platform.release(),
435
- "platform": platform.platform(),
436
- "timestamp": now,
437
- "collected_at": datetime.fromtimestamp(now, tz=timezone.utc).isoformat(),
438
- "cpu": cpu_info(sample_interval=sample_interval),
439
- "memory": memory_usage(),
440
- "disk": disk_info(disk_paths),
441
- "uptime": uptime_info(),
442
- }
443
- if cgroup_available is not None:
444
- out["cgroup"] = bool(cgroup_available)
445
- return out
446
-
447
-
448
- def host_summary(
449
- disk_paths: Optional[Sequence[str]] = None,
450
- *,
451
- cgroup_available: Optional[bool] = None,
452
- fresh: bool = False,
453
- ) -> dict:
454
- """兼容旧版 `host` 摘要字段(available_mb/limit_mb/min_free_mb/blocker)并附带完整系统信息。"""
455
- global _HOST_SUMMARY_CACHE
456
- path_key = tuple(str(p).strip() for p in (disk_paths or DEFAULT_DISK_PATHS) if str(p).strip()) or ("/",)
457
- now_mono = time.monotonic()
458
- if not fresh:
459
- with _HOST_SUMMARY_LOCK:
460
- cached = _HOST_SUMMARY_CACHE
461
- if (
462
- cached is not None
463
- and (now_mono - cached[0]) < _HOST_SUMMARY_TTL_SEC
464
- and cached[1] == path_key
465
- and cached[2] == cgroup_available
466
- ):
467
- return dict(cached[3])
468
-
469
- sys_data = system_info(
470
- disk_paths=path_key,
471
- sample_interval=0.05,
472
- cgroup_available=cgroup_available,
473
- )
474
- mem = sys_data["memory"]
475
- summary = {
476
- "available_mb": mem["available_mb"],
477
- "limit_mb": mem["limit_mb"],
478
- "min_free_mb": mem["min_free_mb"],
479
- "blocker": mem["blocker"],
480
- **sys_data,
481
- }
482
- with _HOST_SUMMARY_LOCK:
483
- _HOST_SUMMARY_CACHE = (time.monotonic(), path_key, cgroup_available, summary)
484
- return dict(summary)
485
-
486
-
487
- def host_system(
488
- disk_paths: Optional[Sequence[str]] = None,
489
- *,
490
- cgroup_available: Optional[bool] = None,
491
- fresh: bool = False,
492
- ) -> dict:
493
- """`host_summary()` 语义别名,返回包含内存门禁四字段与完整主机系统指标的字典。"""
494
- return host_summary(disk_paths=disk_paths, cgroup_available=cgroup_available, fresh=fresh)