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.
- serverdeck/__init__.py +13 -0
- serverdeck/__main__.py +8 -0
- serverdeck/assets/app.css +381 -0
- serverdeck/assets/app.js +819 -0
- serverdeck/assets/index.html +152 -0
- serverdeck/cli.py +96 -0
- serverdeck/collector.py +255 -0
- serverdeck/collectors/__init__.py +1 -0
- serverdeck/collectors/containers.py +112 -0
- serverdeck/collectors/disks.py +82 -0
- serverdeck/collectors/network.py +132 -0
- serverdeck/collectors/restic.py +244 -0
- serverdeck/collectors/system.py +159 -0
- serverdeck/collectors/timers.py +171 -0
- serverdeck/config.py +114 -0
- serverdeck/utils.py +99 -0
- serverdeck/web.py +125 -0
- serverdeck-1.1.0.dist-info/METADATA +124 -0
- serverdeck-1.1.0.dist-info/RECORD +21 -0
- serverdeck-1.1.0.dist-info/WHEEL +4 -0
- serverdeck-1.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""systemd 定时任务采集。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
|
|
10
|
+
from ..utils import run_cmd, to_epoch, truncate
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def parse_show_blocks(text):
|
|
14
|
+
blocks = {}
|
|
15
|
+
current = {}
|
|
16
|
+
for line in text.splitlines():
|
|
17
|
+
if not line.strip():
|
|
18
|
+
if current.get("Id"):
|
|
19
|
+
blocks[current["Id"]] = current
|
|
20
|
+
current = {}
|
|
21
|
+
continue
|
|
22
|
+
if "=" in line:
|
|
23
|
+
key, value = line.split("=", 1)
|
|
24
|
+
current[key] = value
|
|
25
|
+
if current.get("Id"):
|
|
26
|
+
blocks[current["Id"]] = current
|
|
27
|
+
return blocks
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def query_units(units, timeout=10):
|
|
31
|
+
"""批量 systemctl show,返回 {unit: {property: value}}。"""
|
|
32
|
+
result = {}
|
|
33
|
+
clean = [unit for unit in dict.fromkeys(units) if unit]
|
|
34
|
+
for index in range(0, len(clean), 40):
|
|
35
|
+
chunk = clean[index : index + 40]
|
|
36
|
+
ok, out, _, _ = run_cmd(
|
|
37
|
+
[
|
|
38
|
+
"systemctl",
|
|
39
|
+
"show",
|
|
40
|
+
*chunk,
|
|
41
|
+
"--property=Id",
|
|
42
|
+
"--property=ActiveState",
|
|
43
|
+
"--property=SubState",
|
|
44
|
+
"--property=Result",
|
|
45
|
+
"--property=ExecMainStatus",
|
|
46
|
+
],
|
|
47
|
+
timeout=timeout,
|
|
48
|
+
)
|
|
49
|
+
if out:
|
|
50
|
+
result.update(parse_show_blocks(out))
|
|
51
|
+
elif not ok:
|
|
52
|
+
continue
|
|
53
|
+
return result
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def parse_timer_time(text):
|
|
57
|
+
"""解析 'Wed 2026-11-25 18:12:03 CST' 为 epoch(按本机时区)。"""
|
|
58
|
+
match = re.match(r"[A-Za-z]{3}\s+(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})", text or "")
|
|
59
|
+
if not match:
|
|
60
|
+
return None
|
|
61
|
+
try:
|
|
62
|
+
year, month, day, hour, minute, second = (int(value) for value in match.groups())
|
|
63
|
+
return datetime(year, month, day, hour, minute, second).timestamp()
|
|
64
|
+
except ValueError:
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_timers_table(text):
|
|
69
|
+
"""旧版 systemd 的回退解析:按表头列位置切分。"""
|
|
70
|
+
lines = [line for line in text.splitlines() if line.strip()]
|
|
71
|
+
header_index = None
|
|
72
|
+
for index, line in enumerate(lines):
|
|
73
|
+
if "UNIT" in line and "ACTIVATES" in line and "NEXT" in line:
|
|
74
|
+
header_index = index
|
|
75
|
+
break
|
|
76
|
+
if header_index is None:
|
|
77
|
+
return []
|
|
78
|
+
|
|
79
|
+
header = lines[header_index]
|
|
80
|
+
positions = []
|
|
81
|
+
for name in ("NEXT", "LEFT", "LAST", "PASSED", "UNIT", "ACTIVATES"):
|
|
82
|
+
match = re.search(r"\b%s\b" % name, header)
|
|
83
|
+
if match:
|
|
84
|
+
positions.append((name, match.start()))
|
|
85
|
+
if not positions:
|
|
86
|
+
return []
|
|
87
|
+
|
|
88
|
+
items = []
|
|
89
|
+
for line in lines[header_index + 1 :]:
|
|
90
|
+
values = {}
|
|
91
|
+
for index, (name, start) in enumerate(positions):
|
|
92
|
+
end = positions[index + 1][1] if index + 1 < len(positions) else len(line)
|
|
93
|
+
values[name] = line[start:end].strip() if start < len(line) else ""
|
|
94
|
+
unit = values.get("UNIT", "")
|
|
95
|
+
if not unit.endswith(".timer"):
|
|
96
|
+
continue
|
|
97
|
+
items.append(
|
|
98
|
+
{
|
|
99
|
+
"unit": unit,
|
|
100
|
+
"activates": values.get("ACTIVATES", ""),
|
|
101
|
+
"next": parse_timer_time(values.get("NEXT", "")),
|
|
102
|
+
"last": parse_timer_time(values.get("LAST", "")),
|
|
103
|
+
}
|
|
104
|
+
)
|
|
105
|
+
return items
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def collect_timers():
|
|
109
|
+
now = time.time()
|
|
110
|
+
ok, out, err, _ = run_cmd(
|
|
111
|
+
["systemctl", "list-timers", "--all", "--no-pager", "--output=json"],
|
|
112
|
+
timeout=10,
|
|
113
|
+
)
|
|
114
|
+
items = []
|
|
115
|
+
if ok and out.startswith("["):
|
|
116
|
+
try:
|
|
117
|
+
raw = json.loads(out)
|
|
118
|
+
except json.JSONDecodeError:
|
|
119
|
+
raw = None
|
|
120
|
+
if raw is not None:
|
|
121
|
+
for entry in raw:
|
|
122
|
+
unit = entry.get("unit") or ""
|
|
123
|
+
if not unit:
|
|
124
|
+
continue
|
|
125
|
+
items.append(
|
|
126
|
+
{
|
|
127
|
+
"unit": unit,
|
|
128
|
+
"activates": entry.get("activates") or "",
|
|
129
|
+
"next": to_epoch(entry.get("next")),
|
|
130
|
+
"last": to_epoch(entry.get("last")),
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
else:
|
|
134
|
+
# 回退:解析表格
|
|
135
|
+
ok2, out2, err2, _ = run_cmd(
|
|
136
|
+
["systemctl", "list-timers", "--all", "--no-pager"],
|
|
137
|
+
timeout=10,
|
|
138
|
+
)
|
|
139
|
+
if not ok2:
|
|
140
|
+
return {
|
|
141
|
+
"updated_at": now,
|
|
142
|
+
"items": [],
|
|
143
|
+
"error": truncate(err2 or err or "systemctl list-timers 执行失败"),
|
|
144
|
+
}
|
|
145
|
+
items = parse_timers_table(out2)
|
|
146
|
+
if not items:
|
|
147
|
+
return {
|
|
148
|
+
"updated_at": now,
|
|
149
|
+
"items": [],
|
|
150
|
+
"error": truncate(err or "无法解析 systemctl list-timers 输出"),
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
# 批量补充 timer 与对应 service 的状态
|
|
154
|
+
units = []
|
|
155
|
+
for item in items:
|
|
156
|
+
units.append(item["unit"])
|
|
157
|
+
if item["activates"]:
|
|
158
|
+
units.append(item["activates"])
|
|
159
|
+
info = query_units(units)
|
|
160
|
+
|
|
161
|
+
for item in items:
|
|
162
|
+
timer_info = info.get(item["unit"], {})
|
|
163
|
+
service_info = info.get(item["activates"], {})
|
|
164
|
+
item["timer_state"] = timer_info.get("ActiveState") or ""
|
|
165
|
+
item["timer_substate"] = timer_info.get("SubState") or ""
|
|
166
|
+
item["service_state"] = service_info.get("ActiveState") or ""
|
|
167
|
+
item["service_result"] = service_info.get("Result") or ""
|
|
168
|
+
item["service_exit"] = service_info.get("ExecMainStatus") or ""
|
|
169
|
+
|
|
170
|
+
items.sort(key=lambda item: (item["next"] is None, item["next"] or 0, item["unit"]))
|
|
171
|
+
return {"updated_at": now, "items": items, "error": None}
|
serverdeck/config.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""配置加载与合并。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
11
|
+
DEFAULT_PORT = 8787
|
|
12
|
+
DEFAULT_REFRESH = 5.0
|
|
13
|
+
DEFAULT_RESTIC_INTERVAL = 300.0
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_config_file(path=None):
|
|
17
|
+
candidates = []
|
|
18
|
+
if path:
|
|
19
|
+
candidates.append(Path(path).expanduser())
|
|
20
|
+
else:
|
|
21
|
+
env_path = os.environ.get("SERVER_INFO_CONFIG")
|
|
22
|
+
if env_path:
|
|
23
|
+
candidates.append(Path(env_path).expanduser())
|
|
24
|
+
candidates.extend(
|
|
25
|
+
[
|
|
26
|
+
Path.cwd() / "serverdeck.json",
|
|
27
|
+
Path.home() / ".config" / "serverdeck" / "config.json",
|
|
28
|
+
]
|
|
29
|
+
)
|
|
30
|
+
for candidate in candidates:
|
|
31
|
+
if not candidate.is_file():
|
|
32
|
+
continue
|
|
33
|
+
try:
|
|
34
|
+
data = json.loads(candidate.read_text(encoding="utf-8"))
|
|
35
|
+
if isinstance(data, dict):
|
|
36
|
+
return data, str(candidate)
|
|
37
|
+
print("警告: 配置文件顶层必须是对象: %s" % candidate, file=sys.stderr)
|
|
38
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
39
|
+
print("警告: 无法读取配置文件 %s: %s" % (candidate, exc), file=sys.stderr)
|
|
40
|
+
break
|
|
41
|
+
return {}, None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_config(args):
|
|
45
|
+
file_cfg, config_path = load_config_file(args.config)
|
|
46
|
+
file_restic = file_cfg.get("restic") or {}
|
|
47
|
+
if not isinstance(file_restic, dict):
|
|
48
|
+
file_restic = {}
|
|
49
|
+
|
|
50
|
+
repos = []
|
|
51
|
+
for item in file_restic.get("repos") or []:
|
|
52
|
+
if isinstance(item, str):
|
|
53
|
+
repos.append(item)
|
|
54
|
+
elif isinstance(item, dict) and (item.get("repository") or item.get("repo")):
|
|
55
|
+
repos.append(item)
|
|
56
|
+
|
|
57
|
+
for repo in args.restic_repo or []:
|
|
58
|
+
repos.append({"repository": repo, "password_file": args.restic_password_file})
|
|
59
|
+
|
|
60
|
+
container_cfg = file_cfg.get("containers") or {}
|
|
61
|
+
if not isinstance(container_cfg, dict):
|
|
62
|
+
container_cfg = {}
|
|
63
|
+
|
|
64
|
+
def pick(cli_value, key, default):
|
|
65
|
+
if cli_value is not None:
|
|
66
|
+
return cli_value
|
|
67
|
+
return file_cfg.get(key, default)
|
|
68
|
+
|
|
69
|
+
host = pick(args.host, "host", DEFAULT_HOST)
|
|
70
|
+
try:
|
|
71
|
+
port = int(pick(args.port, "port", DEFAULT_PORT))
|
|
72
|
+
except (TypeError, ValueError):
|
|
73
|
+
raise SystemExit("端口无效: %r" % pick(args.port, "port", DEFAULT_PORT)) from None
|
|
74
|
+
try:
|
|
75
|
+
refresh = float(pick(args.refresh, "refresh_seconds", DEFAULT_REFRESH))
|
|
76
|
+
except (TypeError, ValueError):
|
|
77
|
+
raise SystemExit(
|
|
78
|
+
"刷新间隔无效: %r" % pick(args.refresh, "refresh_seconds", DEFAULT_REFRESH)
|
|
79
|
+
) from None
|
|
80
|
+
|
|
81
|
+
if args.restic_interval is not None:
|
|
82
|
+
restic_interval = args.restic_interval
|
|
83
|
+
else:
|
|
84
|
+
restic_interval = file_restic.get("interval", DEFAULT_RESTIC_INTERVAL)
|
|
85
|
+
|
|
86
|
+
token = pick(args.token, "token", "") or ""
|
|
87
|
+
enabled = file_restic.get("enabled", True) and not args.no_restic
|
|
88
|
+
|
|
89
|
+
if port < 1 or port > 65535:
|
|
90
|
+
raise SystemExit("端口无效: %s" % port)
|
|
91
|
+
if refresh < 2:
|
|
92
|
+
refresh = 2.0
|
|
93
|
+
try:
|
|
94
|
+
restic_interval = max(30.0, float(restic_interval))
|
|
95
|
+
except (TypeError, ValueError):
|
|
96
|
+
restic_interval = DEFAULT_RESTIC_INTERVAL
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
"host": host,
|
|
100
|
+
"port": port,
|
|
101
|
+
"refresh_seconds": refresh,
|
|
102
|
+
"token": token,
|
|
103
|
+
"verbose": args.verbose,
|
|
104
|
+
"config_path": config_path,
|
|
105
|
+
"containers": {
|
|
106
|
+
"runtime": args.container_runtime or container_cfg.get("runtime") or "auto",
|
|
107
|
+
},
|
|
108
|
+
"restic": {
|
|
109
|
+
"enabled": enabled,
|
|
110
|
+
"repos": repos,
|
|
111
|
+
"interval": restic_interval,
|
|
112
|
+
"timeout": 60,
|
|
113
|
+
},
|
|
114
|
+
}
|
serverdeck/utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""通用工具:命令执行、文本读取与格式化辅助。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def run_cmd(args, timeout=10, env=None):
|
|
14
|
+
"""执行命令,返回 (ok, stdout, stderr, returncode)。永不抛异常。"""
|
|
15
|
+
full_env = os.environ.copy()
|
|
16
|
+
full_env.setdefault("LC_ALL", "C")
|
|
17
|
+
full_env.setdefault("LANG", "C")
|
|
18
|
+
if env:
|
|
19
|
+
full_env.update({str(k): str(v) for k, v in env.items()})
|
|
20
|
+
try:
|
|
21
|
+
process = subprocess.run(
|
|
22
|
+
args,
|
|
23
|
+
stdout=subprocess.PIPE,
|
|
24
|
+
stderr=subprocess.PIPE,
|
|
25
|
+
stdin=subprocess.DEVNULL,
|
|
26
|
+
text=True,
|
|
27
|
+
errors="replace",
|
|
28
|
+
timeout=timeout,
|
|
29
|
+
env=full_env,
|
|
30
|
+
)
|
|
31
|
+
return (
|
|
32
|
+
process.returncode == 0,
|
|
33
|
+
(process.stdout or "").strip(),
|
|
34
|
+
(process.stderr or "").strip(),
|
|
35
|
+
process.returncode,
|
|
36
|
+
)
|
|
37
|
+
except FileNotFoundError:
|
|
38
|
+
return False, "", "未找到命令: %s" % args[0], 127
|
|
39
|
+
except subprocess.TimeoutExpired:
|
|
40
|
+
return False, "", "命令超时(%ss): %s" % (timeout, " ".join(args[:4])), -1
|
|
41
|
+
except Exception as exc: # noqa: BLE001 - 采集失败不能中断服务
|
|
42
|
+
return False, "", str(exc), -1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def truncate(text, limit=500):
|
|
46
|
+
text = (text or "").strip()
|
|
47
|
+
if len(text) > limit:
|
|
48
|
+
return text[:limit] + "…"
|
|
49
|
+
return text
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_text(path, default=""):
|
|
53
|
+
try:
|
|
54
|
+
return Path(path).read_text(encoding="utf-8", errors="replace")
|
|
55
|
+
except OSError:
|
|
56
|
+
return default
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def to_epoch(value):
|
|
60
|
+
"""把 systemd JSON 中的时间(可能是秒或微秒)转成 epoch 秒。"""
|
|
61
|
+
try:
|
|
62
|
+
number = float(value)
|
|
63
|
+
except (TypeError, ValueError):
|
|
64
|
+
return None
|
|
65
|
+
if number <= 0:
|
|
66
|
+
return None
|
|
67
|
+
if number > 1e12: # 微秒
|
|
68
|
+
number /= 1e6
|
|
69
|
+
return number
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_iso_epoch(value):
|
|
73
|
+
if not value:
|
|
74
|
+
return None
|
|
75
|
+
try:
|
|
76
|
+
return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
|
|
77
|
+
except ValueError:
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def redact_repository(repo):
|
|
82
|
+
"""隐藏 URL 中的凭据。"""
|
|
83
|
+
return re.sub(r"(://)[^/\s@]+@", r"\1***@", repo or "")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def clean_restic_error(text):
|
|
87
|
+
"""restic --json 的错误会带 JSON 外壳,提取其中的可读 message。"""
|
|
88
|
+
text = (text or "").strip()
|
|
89
|
+
for candidate in [text] + list(reversed(text.splitlines())):
|
|
90
|
+
candidate = candidate.strip()
|
|
91
|
+
if not candidate.startswith("{"):
|
|
92
|
+
continue
|
|
93
|
+
try:
|
|
94
|
+
obj = json.loads(candidate)
|
|
95
|
+
except json.JSONDecodeError:
|
|
96
|
+
continue
|
|
97
|
+
if isinstance(obj, dict) and obj.get("message"):
|
|
98
|
+
return str(obj["message"])
|
|
99
|
+
return text
|
serverdeck/web.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""HTTP 服务与内嵌前端资源加载。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
10
|
+
from importlib.resources import files
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
from urllib.parse import parse_qs, urlparse
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load_assets(refresh_seconds, version):
|
|
16
|
+
"""读取打包在 wheel 中的 index / CSS / JS,并替换运行参数。"""
|
|
17
|
+
base = files("serverdeck").joinpath("assets")
|
|
18
|
+
index = base.joinpath("index.html").read_text(encoding="utf-8")
|
|
19
|
+
index = index.replace("__REFRESH_INTERVAL__", str(int(refresh_seconds))).replace(
|
|
20
|
+
"__VERSION__", version
|
|
21
|
+
)
|
|
22
|
+
javascript = base.joinpath("app.js").read_text(encoding="utf-8")
|
|
23
|
+
javascript = javascript.replace("__REFRESH_MS__", str(int(refresh_seconds * 1000)))
|
|
24
|
+
stylesheet = base.joinpath("app.css").read_text(encoding="utf-8")
|
|
25
|
+
return {
|
|
26
|
+
"/": (index.encode("utf-8"), "text/html; charset=utf-8"),
|
|
27
|
+
"/assets/app.css": (stylesheet.encode("utf-8"), "text/css; charset=utf-8"),
|
|
28
|
+
"/assets/app.js": (javascript.encode("utf-8"), "application/javascript; charset=utf-8"),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Server(ThreadingHTTPServer):
|
|
33
|
+
daemon_threads = True
|
|
34
|
+
allow_reuse_address = True
|
|
35
|
+
collector: Any = None
|
|
36
|
+
assets: dict[str, tuple[bytes, str]] = {}
|
|
37
|
+
token: str = ""
|
|
38
|
+
verbose: bool = False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Handler(BaseHTTPRequestHandler):
|
|
42
|
+
server_version = "serverdeck"
|
|
43
|
+
sys_version = ""
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def app(self) -> "Server":
|
|
47
|
+
return cast("Server", self.server)
|
|
48
|
+
|
|
49
|
+
def log_message(self, format, *args):
|
|
50
|
+
if self.app.verbose:
|
|
51
|
+
sys.stderr.write("%s - %s\n" % (self.address_string(), format % args))
|
|
52
|
+
|
|
53
|
+
def _send(self, status, body, content_type):
|
|
54
|
+
self.send_response(status)
|
|
55
|
+
self.send_header("Content-Type", content_type)
|
|
56
|
+
self.send_header("Content-Length", str(len(body)))
|
|
57
|
+
self.send_header("Cache-Control", "no-store")
|
|
58
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
59
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
60
|
+
self.end_headers()
|
|
61
|
+
try:
|
|
62
|
+
self.wfile.write(body)
|
|
63
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
def _send_json(self, status, obj):
|
|
67
|
+
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
|
68
|
+
self._send(status, body, "application/json; charset=utf-8")
|
|
69
|
+
|
|
70
|
+
def _authorized(self, parsed):
|
|
71
|
+
expected = self.app.token
|
|
72
|
+
if not expected:
|
|
73
|
+
return True
|
|
74
|
+
supplied = ""
|
|
75
|
+
auth = self.headers.get("Authorization", "")
|
|
76
|
+
if auth.lower().startswith("bearer "):
|
|
77
|
+
supplied = auth[7:].strip()
|
|
78
|
+
if not supplied:
|
|
79
|
+
supplied = (self.headers.get("X-Auth-Token") or "").strip()
|
|
80
|
+
if not supplied:
|
|
81
|
+
supplied = (parse_qs(parsed.query).get("token") or [""])[0]
|
|
82
|
+
return hmac.compare_digest(supplied, expected)
|
|
83
|
+
|
|
84
|
+
def do_GET(self):
|
|
85
|
+
try:
|
|
86
|
+
parsed = urlparse(self.path)
|
|
87
|
+
if parsed.path in self.app.assets:
|
|
88
|
+
body, content_type = self.app.assets[parsed.path]
|
|
89
|
+
self._send(200, body, content_type)
|
|
90
|
+
elif parsed.path == "/healthz":
|
|
91
|
+
self._send(200, b"ok\n", "text/plain; charset=utf-8")
|
|
92
|
+
elif parsed.path == "/api/status":
|
|
93
|
+
if not self._authorized(parsed):
|
|
94
|
+
self._send_json(401, {"error": "需要访问令牌"})
|
|
95
|
+
return
|
|
96
|
+
self._send_json(200, self.app.collector.snapshot())
|
|
97
|
+
else:
|
|
98
|
+
self._send_json(404, {"error": "not found"})
|
|
99
|
+
except Exception as exc: # noqa: BLE001
|
|
100
|
+
sys.stderr.write("请求处理失败: %s\n" % exc)
|
|
101
|
+
try:
|
|
102
|
+
self._send_json(500, {"error": "internal error"})
|
|
103
|
+
except Exception:
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
def do_POST(self):
|
|
107
|
+
try:
|
|
108
|
+
parsed = urlparse(self.path)
|
|
109
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
110
|
+
if length:
|
|
111
|
+
self.rfile.read(min(length, 8192))
|
|
112
|
+
if parsed.path == "/api/refresh":
|
|
113
|
+
if not self._authorized(parsed):
|
|
114
|
+
self._send_json(401, {"error": "需要访问令牌"})
|
|
115
|
+
return
|
|
116
|
+
self.app.collector.request_refresh("all")
|
|
117
|
+
self._send_json(200, {"ok": True, "requested_at": time.time()})
|
|
118
|
+
else:
|
|
119
|
+
self._send_json(404, {"error": "not found"})
|
|
120
|
+
except Exception as exc: # noqa: BLE001
|
|
121
|
+
sys.stderr.write("请求处理失败: %s\n" % exc)
|
|
122
|
+
try:
|
|
123
|
+
self._send_json(500, {"error": "internal error"})
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: serverdeck
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: A lightweight, read-only server status dashboard: systemd timers, restic, containers, disks, CPU, memory and network.
|
|
5
|
+
Keywords: dashboard,docker,monitoring,podman,restic,server,sysadmin,systemd
|
|
6
|
+
Classifier: Environment :: Web Environment
|
|
7
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Topic :: System :: Monitoring
|
|
11
|
+
Classifier: Topic :: System :: Systems Administration
|
|
12
|
+
Classifier: Topic :: Utilities
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# serverdeck
|
|
17
|
+
|
|
18
|
+
一个轻量的服务器状态面板:systemd 定时任务、restic 备份、容器、磁盘、内存、
|
|
19
|
+
CPU 与网络信息集中在一个只读页面里。后端仅使用 Python 标准库,前端不依赖任何
|
|
20
|
+
CDN 或前端框架。
|
|
21
|
+
|
|
22
|
+
## 功能
|
|
23
|
+
|
|
24
|
+
- **systemd 定时任务**:下次 / 上次触发时间、timer 状态、上次 service 执行结果。
|
|
25
|
+
- **restic 备份**:仓库可访问性、快照数量、最新快照时间、最近快照列表与错误原因。
|
|
26
|
+
- **容器**:自动识别 docker / podman;优先使用 docker,两者都不存在时不显示容器 tab。
|
|
27
|
+
- **资源**:CPU 总体与逐核占用、内存 / 缓存 / 交换、各挂载点磁盘用量。
|
|
28
|
+
- **网络**:接口地址、实时收发速率、累计流量、TCP 状态统计、监听端口及进程。
|
|
29
|
+
- **页面**:按功能拆分为 tab(系统、网络、定时任务、容器、Restic),系统页内含
|
|
30
|
+
CPU、内存与磁盘详情;自动刷新,可选访问令牌;默认只监听回环地址。
|
|
31
|
+
|
|
32
|
+
## 安装
|
|
33
|
+
|
|
34
|
+
需要 Python 3.9+。
|
|
35
|
+
|
|
36
|
+
从源码使用 uv:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
uv sync
|
|
40
|
+
uv run serverdeck
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
构建并安装本地 wheel:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
uv build
|
|
47
|
+
uv pip install dist/*.whl
|
|
48
|
+
serverdeck
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
发布到 PyPI 后也可以用:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
uv tool install serverdeck
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## 使用
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
serverdeck
|
|
61
|
+
# 打开 http://127.0.0.1:8787
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
对外监听时建议设置访问令牌:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
serverdeck --host 0.0.0.0 --port 8787 --token 'your-token'
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### restic
|
|
71
|
+
|
|
72
|
+
通过命令行指定仓库:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
serverdeck \
|
|
76
|
+
--restic-repo /mnt/backup/restic \
|
|
77
|
+
--restic-password-file /etc/restic/pass
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`--restic-repo` 可以重复指定。脚本也会自动扫描 systemd 单元和 cron 中出现的
|
|
81
|
+
restic 命令(仅限当前用户可读的文件),并读取 `RESTIC_REPOSITORY` 环境变量。
|
|
82
|
+
|
|
83
|
+
### 配置文件
|
|
84
|
+
|
|
85
|
+
默认查找当前目录的 `serverdeck.json` 或
|
|
86
|
+
`~/.config/serverdeck/config.json`,也可以用 `--config` 指定:
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{
|
|
90
|
+
"host": "127.0.0.1",
|
|
91
|
+
"port": 8787,
|
|
92
|
+
"refresh_seconds": 5,
|
|
93
|
+
"token": "",
|
|
94
|
+
"containers": {"runtime": "auto"},
|
|
95
|
+
"restic": {
|
|
96
|
+
"enabled": true,
|
|
97
|
+
"interval": 300,
|
|
98
|
+
"repos": [
|
|
99
|
+
{
|
|
100
|
+
"name": "本机备份",
|
|
101
|
+
"repository": "/mnt/backup/restic",
|
|
102
|
+
"password_file": "/etc/restic/pass",
|
|
103
|
+
"env": {}
|
|
104
|
+
}
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## 开发
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
uv sync
|
|
114
|
+
uv run pytest
|
|
115
|
+
uv run ruff check .
|
|
116
|
+
uv build
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## 说明
|
|
120
|
+
|
|
121
|
+
- 默认监听 `127.0.0.1`。对外暴露时请配合 `--token` 使用。
|
|
122
|
+
- 监听端口表中的进程列通常需要相应权限才能看到其他用户的进程。
|
|
123
|
+
- restic 采集默认每 300 秒执行一次;页面上的“刷新”按钮会立即触发全量采集。
|
|
124
|
+
- 面板是只读的,不会修改 systemd、容器、restic 或系统配置。
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
serverdeck/__init__.py,sha256=YIkWcuBIc4aacpTWnneAzoYMnO6WkYeTqCYKsmyC4BE,384
|
|
2
|
+
serverdeck/__main__.py,sha256=0VQ-TLSAFy1jyLHzaRe8-4CVnew-cP4sgCBO9uejIIY,121
|
|
3
|
+
serverdeck/cli.py,sha256=SVo67n777l0N66wgvf3R9L9U4fN2TMFYMBYMNmIUcdw,3381
|
|
4
|
+
serverdeck/collector.py,sha256=DyrhYaUdHlZcItR6Rznhl0jzGkufLuivVOU9372UBdY,8867
|
|
5
|
+
serverdeck/config.py,sha256=ci3MnExFHAzU7b2_RnMlA8FyKDdh3-g3vmwgAvdPz8U,3626
|
|
6
|
+
serverdeck/utils.py,sha256=eKy9wjNmF2YPv0Ff85cOIyid9IBov9QDwwh0SK3n97I,2830
|
|
7
|
+
serverdeck/web.py,sha256=ss75POflm9hN-CGXOTXZIohQEDfSr6otTMjSjy52EWo,4775
|
|
8
|
+
serverdeck/assets/app.css,sha256=vmnwnEk2dug5Ev_Kh7RbFfuQCAM4wXkBHoCAv6xhhDA,13866
|
|
9
|
+
serverdeck/assets/app.js,sha256=4yK3MF6aogLERR-w4eURkD6Yn-r98yI5-wDJltyuyaw,34225
|
|
10
|
+
serverdeck/assets/index.html,sha256=uqD5uYzFZPFHUepRHSWsH6YczRjIjHWypRYP9_5qe74,7558
|
|
11
|
+
serverdeck/collectors/__init__.py,sha256=tkJ-2Wht6JMYQ5etsEVO9sdFyuul5Ixq3nNZ5PbEZcc,31
|
|
12
|
+
serverdeck/collectors/containers.py,sha256=TdJw6QFD10yhdmi9BQ1cJ0B1OLVCotel5BrRe1n2EjA,3691
|
|
13
|
+
serverdeck/collectors/disks.py,sha256=pdnB4-E-XdD-1Mf29_BSNcjbuGnj4_6Vt0DNU8hyv20,2017
|
|
14
|
+
serverdeck/collectors/network.py,sha256=ndf00ztjdL1rt0gowgUBS9mTipXYOtV5XtmsJ9dENOQ,4213
|
|
15
|
+
serverdeck/collectors/restic.py,sha256=K4UNq203ykMpip0FzNJLl_uEJRrzOA395fGsVUO2LL8,7619
|
|
16
|
+
serverdeck/collectors/system.py,sha256=WGz7DzcEojyjFFsys_k-7ToFw2z5wr23Nt2oHnhR8lQ,4746
|
|
17
|
+
serverdeck/collectors/timers.py,sha256=enczLQCTjaxxuaOXAVfNJkdFXO0eFTUSXCSuOOJ0H5M,5558
|
|
18
|
+
serverdeck-1.1.0.dist-info/METADATA,sha256=4eVjagzJIdtB4lRCtC6rX5Tku_vR9uOdyAkcI7dshmQ,3400
|
|
19
|
+
serverdeck-1.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
20
|
+
serverdeck-1.1.0.dist-info/entry_points.txt,sha256=IGRL8Dzulqmv-8lc_t1qHujdPN9TOf2dfq0iHa63pms,51
|
|
21
|
+
serverdeck-1.1.0.dist-info/RECORD,,
|