serverdeck 1.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,152 @@
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>服务器状态</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%230f2224'/%3E%3Crect x='10' y='10' width='12' height='12' rx='3' fill='%234fb3a6'/%3E%3C/svg%3E">
8
+ <link rel="stylesheet" href="/assets/app.css">
9
+ </head>
10
+ <body>
11
+ <div class="top">
12
+ <header class="topbar">
13
+ <div class="brand">
14
+ <span class="mark" aria-hidden="true"></span>
15
+ <div>
16
+ <h1>服务器状态</h1>
17
+ <div class="sub" id="hostname">连接中…</div>
18
+ </div>
19
+ </div>
20
+ <div class="controls">
21
+ <span class="statusline"><span class="dot" id="health-dot"></span><span id="updated">等待数据</span></span>
22
+ <button class="btn" id="refresh" type="button">刷新</button>
23
+ <label class="switch"><input type="checkbox" id="auto" checked>自动刷新</label>
24
+ </div>
25
+ </header>
26
+
27
+ <nav class="tabs" id="tabs" role="tablist" aria-label="页面分组">
28
+ <button class="tab-button active" id="tab-system" type="button" role="tab" data-tab="system" aria-selected="true" aria-controls="panel-system">系统</button>
29
+ <button class="tab-button" id="tab-network" type="button" role="tab" data-tab="network" aria-selected="false" aria-controls="panel-network">网络</button>
30
+ <button class="tab-button" id="tab-timers" type="button" role="tab" data-tab="timers" aria-selected="false" aria-controls="panel-timers">定时任务<span class="tab-count" id="tab-count-timers" hidden></span></button>
31
+ <button class="tab-button" id="tab-containers" type="button" role="tab" data-tab="containers" aria-selected="false" aria-controls="panel-containers">容器<span class="tab-count" id="tab-count-containers" hidden></span></button>
32
+ <button class="tab-button" id="tab-restic" type="button" role="tab" data-tab="restic" aria-selected="false" aria-controls="panel-restic">Restic 备份<span class="tab-count" id="tab-count-restic" hidden></span></button>
33
+ </nav>
34
+ </div>
35
+
36
+ <div class="banner" id="banner" hidden></div>
37
+
38
+ <main class="tab-panels">
39
+ <section class="tab-panel active" id="panel-system" role="tabpanel" aria-labelledby="tab-system">
40
+ <div class="grid">
41
+ <section class="card span-6">
42
+ <div class="card-head"><h2>系统信息</h2><span class="card-note" id="sys-note"></span></div>
43
+ <div class="kv" id="sys-body"><div class="empty">加载中…</div></div>
44
+ </section>
45
+ <section class="card span-6">
46
+ <div class="card-head"><h2>运行概况</h2><span class="card-note" id="summary-note"></span></div>
47
+ <div class="summary" id="summary-body"><div class="empty">加载中…</div></div>
48
+ </section>
49
+
50
+ <section class="card span-6" id="card-cpu">
51
+ <div class="card-head"><h2>CPU 使用率</h2><span class="card-note" id="cpu-note"></span></div>
52
+ <div class="metric"><span class="metric-value" id="cpu-pct">—</span><span class="metric-unit">%</span></div>
53
+ <div class="meter"><div class="meter-fill" id="cpu-bar"></div></div>
54
+ <div class="spark" id="cpu-spark"></div>
55
+ <div class="hint">曲线保留最近 60 次前台刷新采样。</div>
56
+ </section>
57
+ <section class="card span-6">
58
+ <div class="card-head"><h2>核心与频率</h2><span class="card-note">每 2 秒采样</span></div>
59
+ <div class="cores" id="cpu-cores"></div>
60
+ <div class="kv" id="cpu-meta"></div>
61
+ </section>
62
+
63
+ <section class="card span-5" id="card-memory">
64
+ <div class="card-head"><h2>内存使用率</h2><span class="card-note" id="mem-note"></span></div>
65
+ <div class="metric"><span class="metric-value" id="mem-pct">—</span><span class="metric-unit">%</span></div>
66
+ <div class="meter"><div class="meter-fill" id="mem-bar"></div></div>
67
+ <div class="spark" id="mem-spark"></div>
68
+ </section>
69
+ <section class="card span-7">
70
+ <div class="card-head"><h2>内存明细</h2><span class="card-note">/proc/meminfo</span></div>
71
+ <div class="kv" id="mem-body"></div>
72
+ </section>
73
+
74
+ <section class="card span-12" id="card-disk">
75
+ <div class="card-head"><h2>磁盘挂载点</h2><span class="card-note" id="disk-note"></span></div>
76
+ <div class="stack" id="disk-body"><div class="empty">加载中…</div></div>
77
+ </section>
78
+ </div>
79
+ </section>
80
+
81
+ <section class="tab-panel" id="panel-network" role="tabpanel" aria-labelledby="tab-network">
82
+ <div class="grid">
83
+ <section class="card span-5">
84
+ <div class="card-head"><h2>接口流量</h2><span class="card-note" id="net-iface-note"></span></div>
85
+ <div class="iface-list" id="net-ifaces"></div>
86
+ </section>
87
+ <section class="card span-7">
88
+ <div class="card-head"><h2>TCP 连接状态</h2><span class="card-note">ss -tan</span></div>
89
+ <div class="chips" id="net-states"></div>
90
+ <div class="hint">ESTAB 为已建立连接,TIME-WAIT 属于正常回收状态。</div>
91
+ </section>
92
+ <section class="card span-12">
93
+ <div class="card-head">
94
+ <h2>监听端口</h2>
95
+ <div class="head-tools">
96
+ <span class="card-note" id="net-note"></span>
97
+ <input class="filter" id="listener-filter" placeholder="过滤端口 / 进程" autocomplete="off">
98
+ </div>
99
+ </div>
100
+ <div class="table-wrap tall">
101
+ <table class="data">
102
+ <thead><tr><th>协议</th><th>端口</th><th>地址</th><th title="查看其他用户的进程通常需要 root 权限">进程</th></tr></thead>
103
+ <tbody id="listener-body"></tbody>
104
+ </table>
105
+ </div>
106
+ </section>
107
+ </div>
108
+ </section>
109
+
110
+ <section class="tab-panel" id="panel-timers" role="tabpanel" aria-labelledby="tab-timers">
111
+ <div class="grid">
112
+ <section class="card span-12">
113
+ <div class="card-head"><h2>systemd 定时任务</h2><span class="card-note" id="timer-note"></span></div>
114
+ <div class="table-wrap tall">
115
+ <table class="data timers">
116
+ <thead><tr><th>任务</th><th>状态</th><th>下次触发</th><th>上次触发</th></tr></thead>
117
+ <tbody id="timer-body"></tbody>
118
+ </table>
119
+ </div>
120
+ </section>
121
+ </div>
122
+ </section>
123
+
124
+ <section class="tab-panel" id="panel-containers" role="tabpanel" aria-labelledby="tab-containers">
125
+ <div class="grid">
126
+ <section class="card span-12">
127
+ <div class="card-head"><h2>容器</h2><span class="card-note" id="container-note"></span></div>
128
+ <div class="table-wrap tall">
129
+ <table class="data">
130
+ <thead><tr><th>状态</th><th>名称</th><th>镜像 / 端口</th><th class="num">CPU</th><th class="num">内存</th></tr></thead>
131
+ <tbody id="container-body"></tbody>
132
+ </table>
133
+ </div>
134
+ </section>
135
+ </div>
136
+ </section>
137
+
138
+ <section class="tab-panel" id="panel-restic" role="tabpanel" aria-labelledby="tab-restic">
139
+ <div class="grid">
140
+ <section class="card span-12">
141
+ <div class="card-head"><h2>Restic 备份</h2><span class="card-note" id="restic-note"></span></div>
142
+ <div id="restic-body" class="restic-list"><div class="empty">加载中…</div></div>
143
+ </section>
144
+ </div>
145
+ </section>
146
+ </main>
147
+
148
+ <footer>serverdeck __VERSION__ · 只读面板 · 每 __REFRESH_INTERVAL__ 秒自动刷新</footer>
149
+
150
+ <script src="/assets/app.js" defer></script>
151
+ </body>
152
+ </html>
serverdeck/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """命令行入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .collector import Collector
10
+ from .config import build_config
11
+ from .web import Handler, Server, load_assets
12
+
13
+
14
+ def parse_args(argv=None):
15
+ parser = argparse.ArgumentParser(
16
+ prog="serverdeck",
17
+ description="服务器状态面板:systemd timer、restic、容器、磁盘、内存、CPU、网络",
18
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
19
+ )
20
+ parser.add_argument("--host", default=None, help="监听地址,默认 127.0.0.1")
21
+ parser.add_argument("--port", type=int, default=None, help="监听端口,默认 8787")
22
+ parser.add_argument("--refresh", type=float, default=None, help="前端自动刷新间隔(秒)")
23
+ parser.add_argument("--config", default=None, help="配置文件路径")
24
+ parser.add_argument("--token", default=None, help="可选的访问令牌;设置后 API 需要 Bearer 认证")
25
+ parser.add_argument(
26
+ "--restic-repo",
27
+ action="append",
28
+ default=[],
29
+ metavar="REPO",
30
+ help="restic 仓库路径,可重复指定",
31
+ )
32
+ parser.add_argument(
33
+ "--restic-password-file",
34
+ default=None,
35
+ help="与 --restic-repo 搭配的密码文件",
36
+ )
37
+ parser.add_argument("--restic-interval", type=float, default=None, help="restic 刷新间隔(秒)")
38
+ parser.add_argument("--no-restic", action="store_true", help="禁用 restic 采集")
39
+ parser.add_argument(
40
+ "--container-runtime",
41
+ choices=["auto", "docker", "podman"],
42
+ default=None,
43
+ help="容器运行时,默认自动检测",
44
+ )
45
+ parser.add_argument("--verbose", action="store_true", help="打印访问日志")
46
+ parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
47
+ return parser.parse_args(argv)
48
+
49
+
50
+ def main(argv=None):
51
+ args = parse_args(argv)
52
+ cfg = build_config(args)
53
+
54
+ collector = Collector(cfg)
55
+ assets = load_assets(cfg["refresh_seconds"], __version__)
56
+
57
+ try:
58
+ server = Server((cfg["host"], cfg["port"]), Handler)
59
+ except OSError as exc:
60
+ print("无法监听 %s:%s: %s" % (cfg["host"], cfg["port"], exc), file=sys.stderr)
61
+ return 1
62
+
63
+ server.collector = collector
64
+ server.assets = assets
65
+ server.token = cfg["token"]
66
+ server.verbose = cfg["verbose"]
67
+ Handler.server_version = "serverdeck/" + __version__
68
+
69
+ collector.start()
70
+
71
+ display_host = cfg["host"]
72
+ if display_host in ("0.0.0.0", "::", ""):
73
+ display_host = "127.0.0.1"
74
+ print(
75
+ "serverdeck v%s 已启动: http://%s:%s" % (__version__, display_host, cfg["port"]),
76
+ flush=True,
77
+ )
78
+ if cfg["config_path"]:
79
+ print("配置文件: %s" % cfg["config_path"], flush=True)
80
+ if cfg["host"] not in ("127.0.0.1", "::1", "localhost"):
81
+ if cfg["token"]:
82
+ print("注意: 正在对外监听,已启用访问令牌", flush=True)
83
+ else:
84
+ print(
85
+ "警告: 正在对外监听且未设置 --token,面板信息可被任何能访问该端口的人读取",
86
+ file=sys.stderr,
87
+ )
88
+
89
+ try:
90
+ server.serve_forever()
91
+ except KeyboardInterrupt:
92
+ print("\n正在退出…")
93
+ finally:
94
+ collector.stop()
95
+ server.server_close()
96
+ return 0
@@ -0,0 +1,255 @@
1
+ """后台采集线程:把各个采集器组装成一份完整快照。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import os
7
+ import shutil
8
+ import threading
9
+ import time
10
+
11
+ from . import __version__
12
+ from .collectors import containers, disks, network, restic, system, timers
13
+
14
+ FAST_INTERVAL = 2.0
15
+ SLOW_INTERVAL = 15.0
16
+
17
+
18
+ class Collector:
19
+ def __init__(self, cfg):
20
+ self.cfg = cfg
21
+ self.lock = threading.Lock()
22
+ self._stop = threading.Event()
23
+ self._wake = {
24
+ "fast": threading.Event(),
25
+ "slow": threading.Event(),
26
+ "restic": threading.Event(),
27
+ }
28
+ now = time.time()
29
+ self._prev_cpu = system.read_cpu_times()
30
+ initial_network = network.read_net_dev()
31
+ self._prev_net = initial_network
32
+ self._prev_net_ts = now
33
+ initial_interfaces = [
34
+ {
35
+ "name": name,
36
+ "addresses": [],
37
+ "rx_bytes": counters["rx_bytes"],
38
+ "tx_bytes": counters["tx_bytes"],
39
+ "rx_rate": 0,
40
+ "tx_rate": 0,
41
+ "rx_packets": counters["rx_packets"],
42
+ "tx_packets": counters["tx_packets"],
43
+ "rx_errs": counters["rx_errs"],
44
+ "tx_errs": counters["tx_errs"],
45
+ }
46
+ for name, counters in initial_network.items()
47
+ ]
48
+ initial_interfaces.sort(key=lambda item: (item["name"] == "lo", item["name"]))
49
+
50
+ self.data = {
51
+ "version": __version__,
52
+ "started_at": now,
53
+ "server_time": now,
54
+ "system": dict(
55
+ system.collect_static_system(),
56
+ updated_at=now,
57
+ error=None,
58
+ uptime_seconds=system.read_uptime(),
59
+ load=[0.0, 0.0, 0.0],
60
+ processes={"running": 0, "total": 0},
61
+ ),
62
+ "cpu": {
63
+ "updated_at": None,
64
+ "usage": 0.0,
65
+ "per_core": [],
66
+ "mhz": None,
67
+ "cores": os.cpu_count() or 0,
68
+ },
69
+ "memory": {"updated_at": None},
70
+ "disks": {"updated_at": None, "items": [], "error": None},
71
+ "timers": {"updated_at": None, "items": [], "error": None},
72
+ "containers": {
73
+ "updated_at": None,
74
+ "runtime": None,
75
+ "items": [],
76
+ "counts": {"total": 0, "running": 0},
77
+ "error": None,
78
+ "stats_error": None,
79
+ },
80
+ "network": {
81
+ "updated_at": None,
82
+ "interfaces": initial_interfaces,
83
+ "addresses": {},
84
+ "listeners": [],
85
+ "tcp_states": {},
86
+ "tcp_total": 0,
87
+ "error": None,
88
+ },
89
+ "restic": {
90
+ "updated_at": None,
91
+ "enabled": cfg["restic"]["enabled"],
92
+ "available": bool(shutil.which("restic")),
93
+ "repos": [],
94
+ "error": None,
95
+ },
96
+ }
97
+ self._threads = []
98
+
99
+ def update_fast(self):
100
+ now = time.time()
101
+ cpu_now = system.read_cpu_times()
102
+ usage, cores = system.cpu_usage(self._prev_cpu, cpu_now)
103
+ self._prev_cpu = cpu_now
104
+
105
+ memory = system.read_memory()
106
+ load, processes = system.read_load()
107
+ uptime = system.read_uptime()
108
+
109
+ net = network.read_net_dev()
110
+ rates = network.net_rates(self._prev_net, net, now - self._prev_net_ts)
111
+ self._prev_net = net
112
+ self._prev_net_ts = now
113
+
114
+ with self.lock:
115
+ self.data["cpu"] = {
116
+ "updated_at": now,
117
+ "usage": usage,
118
+ "per_core": cores,
119
+ "mhz": system.read_cpu_mhz(),
120
+ "cores": len(cores) or (os.cpu_count() or 0),
121
+ }
122
+ self.data["memory"] = dict(memory, updated_at=now)
123
+ system_data = self.data["system"]
124
+ system_data["updated_at"] = now
125
+ system_data["uptime_seconds"] = uptime
126
+ system_data["load"] = load
127
+ system_data["processes"] = processes
128
+ system_data["boot_time"] = (
129
+ (now - uptime) if uptime is not None else system_data.get("boot_time")
130
+ )
131
+
132
+ net_data = self.data["network"]
133
+ addresses = net_data.get("addresses", {})
134
+ interfaces = []
135
+ for name, counters in net.items():
136
+ rx_rate, tx_rate = rates.get(name, (0, 0))
137
+ interfaces.append(
138
+ {
139
+ "name": name,
140
+ "addresses": addresses.get(name, []),
141
+ "rx_bytes": counters["rx_bytes"],
142
+ "tx_bytes": counters["tx_bytes"],
143
+ "rx_rate": rx_rate,
144
+ "tx_rate": tx_rate,
145
+ "rx_packets": counters["rx_packets"],
146
+ "tx_packets": counters["tx_packets"],
147
+ "rx_errs": counters["rx_errs"],
148
+ "tx_errs": counters["tx_errs"],
149
+ }
150
+ )
151
+ interfaces.sort(key=lambda item: (item["name"] == "lo", item["name"]))
152
+ net_data["interfaces"] = interfaces
153
+ net_data["updated_at"] = now
154
+
155
+ def update_slow(self):
156
+ now = time.time()
157
+ results = {}
158
+ tasks = {
159
+ "disks": disks.collect_disks,
160
+ "timers": timers.collect_timers,
161
+ "containers": lambda: containers.collect_containers(self.cfg),
162
+ }
163
+ for name, function in tasks.items():
164
+ try:
165
+ results[name] = function()
166
+ except Exception as exc: # noqa: BLE001
167
+ results[name] = {
168
+ "updated_at": now,
169
+ "items": [],
170
+ "error": "采集失败: %s" % exc,
171
+ }
172
+
173
+ addresses = network.collect_interface_addresses()
174
+ listeners, listener_error = network.collect_listeners()
175
+ tcp_states, tcp_total, tcp_error = network.collect_tcp_states()
176
+
177
+ with self.lock:
178
+ for name in ("disks", "timers", "containers"):
179
+ self.data[name] = results[name]
180
+ net = self.data["network"]
181
+ net["addresses"] = addresses
182
+ net["listeners"] = listeners
183
+ net["tcp_states"] = tcp_states
184
+ net["tcp_total"] = tcp_total
185
+ net["error"] = listener_error or tcp_error
186
+ net["updated_at_slow"] = now
187
+
188
+ def update_restic(self):
189
+ try:
190
+ result = restic.collect_restic(self.cfg["restic"])
191
+ except Exception as exc: # noqa: BLE001
192
+ result = {
193
+ "updated_at": time.time(),
194
+ "enabled": self.cfg["restic"]["enabled"],
195
+ "available": bool(shutil.which("restic")),
196
+ "repos": [],
197
+ "error": "采集失败: %s" % exc,
198
+ }
199
+ with self.lock:
200
+ self.data["restic"] = result
201
+
202
+ def _loop(self, name, function, interval):
203
+ while not self._stop.is_set():
204
+ try:
205
+ function()
206
+ except Exception as exc: # noqa: BLE001
207
+ with self.lock:
208
+ self.data.setdefault("_errors", {})[name] = str(exc)
209
+ self._wake[name].wait(interval)
210
+ self._wake[name].clear()
211
+
212
+ def _fast_loop(self):
213
+ # 给 CPU / 网络计数一个采样间隔,避免首个读数为 0
214
+ self._stop.wait(1.0)
215
+ self._loop("fast", self.update_fast, FAST_INTERVAL)
216
+
217
+ def _slow_loop(self):
218
+ self._loop("slow", self.update_slow, SLOW_INTERVAL)
219
+
220
+ def _restic_loop(self):
221
+ self._loop("restic", self.update_restic, self.cfg["restic"]["interval"])
222
+
223
+ def start(self):
224
+ for target, name in (
225
+ (self._fast_loop, "fast"),
226
+ (self._slow_loop, "slow"),
227
+ (self._restic_loop, "restic"),
228
+ ):
229
+ thread = threading.Thread(
230
+ target=target,
231
+ name="serverdeck-%s" % name,
232
+ daemon=True,
233
+ )
234
+ thread.start()
235
+ self._threads.append(thread)
236
+
237
+ def stop(self):
238
+ self._stop.set()
239
+ for event in self._wake.values():
240
+ event.set()
241
+
242
+ def request_refresh(self, scope="all"):
243
+ if scope in ("all", "fast"):
244
+ self._wake["fast"].set()
245
+ if scope in ("all", "slow"):
246
+ self._wake["slow"].set()
247
+ if scope in ("all", "restic"):
248
+ self._wake["restic"].set()
249
+
250
+ def snapshot(self):
251
+ with self.lock:
252
+ snapshot = copy.deepcopy(self.data)
253
+ snapshot["server_time"] = time.time()
254
+ snapshot["uptime_seconds"] = system.read_uptime()
255
+ return snapshot
@@ -0,0 +1 @@
1
+ """数据采集器子包。"""
@@ -0,0 +1,112 @@
1
+ """容器运行时(docker / podman)采集。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import time
7
+
8
+ from ..utils import run_cmd, truncate
9
+
10
+
11
+ def detect_runtime(preference):
12
+ if preference and preference != "auto":
13
+ return preference if shutil.which(preference) else None
14
+ for name in ("docker", "podman"):
15
+ if shutil.which(name):
16
+ return name
17
+ return None
18
+
19
+
20
+ def normalize_percent(value, digits=1):
21
+ """统一 docker / podman 的百分比输出:'0.12%' 或 '7.37' -> '7.4%'。"""
22
+ value = (value or "").strip()
23
+ if not value:
24
+ return None
25
+ if value.endswith("%"):
26
+ return value
27
+ try:
28
+ return ("%." + str(digits) + "f%%") % float(value)
29
+ except ValueError:
30
+ return value
31
+
32
+
33
+ def collect_containers(cfg):
34
+ now = time.time()
35
+ runtime = detect_runtime(cfg["containers"]["runtime"])
36
+ if not runtime:
37
+ return {
38
+ "updated_at": now,
39
+ "runtime": None,
40
+ "items": [],
41
+ "counts": {"total": 0, "running": 0},
42
+ "error": "未找到 docker 或 podman",
43
+ "stats_error": None,
44
+ }
45
+
46
+ fmt = "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
47
+ ok, out, err, _ = run_cmd([runtime, "ps", "-a", "--format", fmt], timeout=12)
48
+ if not ok:
49
+ return {
50
+ "updated_at": now,
51
+ "runtime": runtime,
52
+ "items": [],
53
+ "counts": {"total": 0, "running": 0},
54
+ "error": truncate(err or out or "%s ps 执行失败" % runtime),
55
+ "stats_error": None,
56
+ }
57
+
58
+ items = []
59
+ for line in out.splitlines():
60
+ parts = line.split("\t")
61
+ if len(parts) < 5:
62
+ parts += [""] * (5 - len(parts))
63
+ container_id, name, image, status, ports = parts[:5]
64
+ items.append(
65
+ {
66
+ "id": container_id[:12],
67
+ "name": name or container_id[:12],
68
+ "image": image,
69
+ "status": status,
70
+ "ports": ports,
71
+ "running": status.strip().lower().startswith("up"),
72
+ "cpu": None,
73
+ "mem_usage": None,
74
+ "mem_percent": None,
75
+ }
76
+ )
77
+
78
+ stats_error = None
79
+ if any(item["running"] for item in items):
80
+ if runtime == "docker":
81
+ stats_fmt = "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}"
82
+ else:
83
+ stats_fmt = "{{.Name}}\t{{.CPU}}\t{{.MemUsage}}\t{{.MemPerc}}"
84
+ ok_stats, stats_out, stats_err, _ = run_cmd(
85
+ [runtime, "stats", "--no-stream", "--format", stats_fmt],
86
+ timeout=15,
87
+ )
88
+ if ok_stats:
89
+ stats = {}
90
+ for line in stats_out.splitlines():
91
+ parts = line.split("\t")
92
+ if len(parts) >= 4:
93
+ stats[parts[0]] = (parts[1], parts[2], parts[3])
94
+ for item in items:
95
+ if item["name"] in stats:
96
+ cpu, mem_usage, mem_percent = stats[item["name"]]
97
+ item["cpu"] = normalize_percent(cpu, 1)
98
+ item["mem_usage"] = mem_usage or None
99
+ item["mem_percent"] = normalize_percent(mem_percent, 2)
100
+ else:
101
+ stats_error = truncate(stats_err or stats_out or "容器统计不可用")
102
+
103
+ items.sort(key=lambda item: (not item["running"], item["name"].lower()))
104
+ running_count = sum(1 for item in items if item["running"])
105
+ return {
106
+ "updated_at": now,
107
+ "runtime": runtime,
108
+ "items": items,
109
+ "counts": {"total": len(items), "running": running_count},
110
+ "error": None,
111
+ "stats_error": stats_error,
112
+ }