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,82 @@
|
|
|
1
|
+
"""磁盘挂载点用量采集。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from ..utils import run_cmd, truncate
|
|
8
|
+
|
|
9
|
+
EXCLUDED_FS = {
|
|
10
|
+
"tmpfs",
|
|
11
|
+
"devtmpfs",
|
|
12
|
+
"sysfs",
|
|
13
|
+
"proc",
|
|
14
|
+
"cgroup",
|
|
15
|
+
"cgroup2",
|
|
16
|
+
"devpts",
|
|
17
|
+
"securityfs",
|
|
18
|
+
"pstore",
|
|
19
|
+
"bpf",
|
|
20
|
+
"debugfs",
|
|
21
|
+
"tracefs",
|
|
22
|
+
"configfs",
|
|
23
|
+
"fusectl",
|
|
24
|
+
"mqueue",
|
|
25
|
+
"hugetlbfs",
|
|
26
|
+
"autofs",
|
|
27
|
+
"nsfs",
|
|
28
|
+
"efivarfs",
|
|
29
|
+
"ramfs",
|
|
30
|
+
"squashfs",
|
|
31
|
+
"overlay",
|
|
32
|
+
"aufs",
|
|
33
|
+
"binfmt_misc",
|
|
34
|
+
"rpc_pipefs",
|
|
35
|
+
"selinuxfs",
|
|
36
|
+
"fuse.gvfsd-fuse",
|
|
37
|
+
"fuse.portal",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def collect_disks():
|
|
42
|
+
now = time.time()
|
|
43
|
+
ok, out, err, _ = run_cmd(["df", "-P", "-k", "-T"], timeout=8)
|
|
44
|
+
if not ok:
|
|
45
|
+
return {"updated_at": now, "items": [], "error": truncate(err or out or "df 执行失败")}
|
|
46
|
+
|
|
47
|
+
items = []
|
|
48
|
+
for line in out.splitlines()[1:]:
|
|
49
|
+
parts = line.split(None, 6)
|
|
50
|
+
if len(parts) < 7:
|
|
51
|
+
continue
|
|
52
|
+
filesystem, fstype, size_k, used_k, available_k, percent_text, mount = parts
|
|
53
|
+
if fstype in EXCLUDED_FS:
|
|
54
|
+
continue
|
|
55
|
+
if mount.startswith(("/sys", "/proc", "/dev")):
|
|
56
|
+
continue
|
|
57
|
+
try:
|
|
58
|
+
size = int(size_k) * 1024
|
|
59
|
+
used = int(used_k) * 1024
|
|
60
|
+
available = int(available_k) * 1024
|
|
61
|
+
except ValueError:
|
|
62
|
+
continue
|
|
63
|
+
if size <= 0:
|
|
64
|
+
continue
|
|
65
|
+
try:
|
|
66
|
+
percent = float(percent_text.rstrip("%"))
|
|
67
|
+
except ValueError:
|
|
68
|
+
percent = round(used * 100.0 / (used + available), 1) if (used + available) else 0.0
|
|
69
|
+
items.append(
|
|
70
|
+
{
|
|
71
|
+
"filesystem": filesystem,
|
|
72
|
+
"type": fstype,
|
|
73
|
+
"mount": mount,
|
|
74
|
+
"size": size,
|
|
75
|
+
"used": used,
|
|
76
|
+
"available": available,
|
|
77
|
+
"percent": round(percent, 1),
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
items.sort(key=lambda item: (item["mount"] != "/", item["mount"]))
|
|
82
|
+
return {"updated_at": now, "items": items, "error": None}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""网络接口、监听端口与 TCP 连接状态采集。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from ..utils import read_text, run_cmd, truncate
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def read_net_dev():
|
|
11
|
+
result = {}
|
|
12
|
+
lines = read_text("/proc/net/dev").splitlines()
|
|
13
|
+
for line in lines[2:]:
|
|
14
|
+
if ":" not in line:
|
|
15
|
+
continue
|
|
16
|
+
name, rest = line.split(":", 1)
|
|
17
|
+
fields = rest.split()
|
|
18
|
+
if len(fields) < 16:
|
|
19
|
+
continue
|
|
20
|
+
try:
|
|
21
|
+
result[name.strip()] = {
|
|
22
|
+
"rx_bytes": int(fields[0]),
|
|
23
|
+
"rx_packets": int(fields[1]),
|
|
24
|
+
"rx_errs": int(fields[2]),
|
|
25
|
+
"rx_drop": int(fields[3]),
|
|
26
|
+
"tx_bytes": int(fields[8]),
|
|
27
|
+
"tx_packets": int(fields[9]),
|
|
28
|
+
"tx_errs": int(fields[10]),
|
|
29
|
+
"tx_drop": int(fields[11]),
|
|
30
|
+
}
|
|
31
|
+
except ValueError:
|
|
32
|
+
continue
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def net_rates(previous, current, elapsed):
|
|
37
|
+
rates = {}
|
|
38
|
+
for name, counters in current.items():
|
|
39
|
+
old = previous.get(name)
|
|
40
|
+
if old and elapsed > 0:
|
|
41
|
+
rx = max(0, counters["rx_bytes"] - old["rx_bytes"]) / elapsed
|
|
42
|
+
tx = max(0, counters["tx_bytes"] - old["tx_bytes"]) / elapsed
|
|
43
|
+
else:
|
|
44
|
+
rx = tx = 0.0
|
|
45
|
+
rates[name] = (round(rx), round(tx))
|
|
46
|
+
return rates
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def split_local_address(value):
|
|
50
|
+
value = value.strip()
|
|
51
|
+
if value.startswith("["):
|
|
52
|
+
index = value.rfind("]:")
|
|
53
|
+
if index != -1:
|
|
54
|
+
port = value[index + 2 :]
|
|
55
|
+
return value[1:index], int(port) if port.isdigit() else None
|
|
56
|
+
if ":" in value:
|
|
57
|
+
address, port = value.rsplit(":", 1)
|
|
58
|
+
return address, int(port) if port.isdigit() else None
|
|
59
|
+
return value, None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def collect_listeners():
|
|
63
|
+
ok, out, err, _ = run_cmd(["ss", "-tulnpH"], timeout=6)
|
|
64
|
+
if not ok:
|
|
65
|
+
ok, out, err, _ = run_cmd(["ss", "-tulnp"], timeout=6)
|
|
66
|
+
if ok:
|
|
67
|
+
out = "\n".join(line for line in out.splitlines() if not line.startswith("Netid"))
|
|
68
|
+
if not ok:
|
|
69
|
+
return [], truncate(err or out or "ss 执行失败")
|
|
70
|
+
|
|
71
|
+
groups = {}
|
|
72
|
+
for line in out.splitlines():
|
|
73
|
+
parts = line.split(None, 5)
|
|
74
|
+
if len(parts) < 5:
|
|
75
|
+
continue
|
|
76
|
+
proto, state, local = parts[0], parts[1], parts[4]
|
|
77
|
+
rest = parts[5] if len(parts) > 5 else ""
|
|
78
|
+
if state not in ("LISTEN", "UNCONN"):
|
|
79
|
+
continue
|
|
80
|
+
address, port = split_local_address(local)
|
|
81
|
+
if port is None:
|
|
82
|
+
continue
|
|
83
|
+
match = re.search(r'users:\(\("([^"]*)",pid=(\d+)', rest)
|
|
84
|
+
process = match.group(1) if match else ""
|
|
85
|
+
pid = int(match.group(2)) if match else None
|
|
86
|
+
key = (proto, port, process, pid)
|
|
87
|
+
group = groups.get(key)
|
|
88
|
+
if group is None:
|
|
89
|
+
group = {
|
|
90
|
+
"proto": proto,
|
|
91
|
+
"port": port,
|
|
92
|
+
"addresses": [],
|
|
93
|
+
"process": process,
|
|
94
|
+
"pid": pid,
|
|
95
|
+
}
|
|
96
|
+
groups[key] = group
|
|
97
|
+
if address and address not in group["addresses"]:
|
|
98
|
+
group["addresses"].append(address)
|
|
99
|
+
|
|
100
|
+
items = sorted(groups.values(), key=lambda item: (item["port"], item["proto"]))
|
|
101
|
+
for item in items:
|
|
102
|
+
if len(item["addresses"]) > 6:
|
|
103
|
+
extra = len(item["addresses"]) - 6
|
|
104
|
+
item["addresses"] = item["addresses"][:6] + ["+%d" % extra]
|
|
105
|
+
return items[:300], None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def collect_tcp_states():
|
|
109
|
+
ok, out, err, _ = run_cmd(["ss", "-tanH"], timeout=8)
|
|
110
|
+
if not ok:
|
|
111
|
+
return {}, 0, truncate(err or out or "ss 执行失败")
|
|
112
|
+
states = {}
|
|
113
|
+
total = 0
|
|
114
|
+
for line in out.splitlines():
|
|
115
|
+
parts = line.split()
|
|
116
|
+
if not parts:
|
|
117
|
+
continue
|
|
118
|
+
states[parts[0]] = states.get(parts[0], 0) + 1
|
|
119
|
+
total += 1
|
|
120
|
+
return states, total, None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def collect_interface_addresses():
|
|
124
|
+
addresses = {}
|
|
125
|
+
ok, out, _, _ = run_cmd(["ip", "-o", "addr", "show"], timeout=6)
|
|
126
|
+
if not ok:
|
|
127
|
+
return addresses
|
|
128
|
+
for line in out.splitlines():
|
|
129
|
+
match = re.match(r"\d+:\s+(\S+)\s+inet6?\s+([0-9a-fA-F:.]+/\d+)", line)
|
|
130
|
+
if match:
|
|
131
|
+
addresses.setdefault(match.group(1), []).append(match.group(2))
|
|
132
|
+
return addresses
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""restic 仓库发现与快照采集。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from ..utils import (
|
|
13
|
+
clean_restic_error,
|
|
14
|
+
parse_iso_epoch,
|
|
15
|
+
read_text,
|
|
16
|
+
redact_repository,
|
|
17
|
+
run_cmd,
|
|
18
|
+
truncate,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
REPO_FLAG_RE = re.compile(r'(?:^|\s)(?:--repo(?:sitory)?(?:=|\s+)|-r\s+)(["\']?)([^\s"\']+)\1')
|
|
22
|
+
ENV_REPO_RE = re.compile(r'\bRESTIC_REPOSITORY=["\']?([^"\'\s]+)')
|
|
23
|
+
PASS_RE = re.compile(r'(?:--password-file(?:=|\s+)|RESTIC_PASSWORD_FILE=)(["\']?)([^\s"\']+)\1')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def iter_restic_config_sources():
|
|
27
|
+
"""产出 (来源, 文本),只读取,不执行。"""
|
|
28
|
+
dirs = [
|
|
29
|
+
Path("/etc/systemd/system"),
|
|
30
|
+
Path("/etc/systemd/user"),
|
|
31
|
+
Path.home() / ".config/systemd/user",
|
|
32
|
+
]
|
|
33
|
+
for base in dirs:
|
|
34
|
+
if not base.is_dir():
|
|
35
|
+
continue
|
|
36
|
+
for pattern in ("*.service", "*.timer", "*.path", "*.d/*.conf"):
|
|
37
|
+
try:
|
|
38
|
+
for path in base.glob(pattern):
|
|
39
|
+
if path.is_file() and path.stat().st_size <= 256 * 1024:
|
|
40
|
+
yield str(path), read_text(path)
|
|
41
|
+
except OSError:
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
cron_files = [Path("/etc/crontab")]
|
|
45
|
+
for folder in (
|
|
46
|
+
"/etc/cron.d",
|
|
47
|
+
"/etc/cron.daily",
|
|
48
|
+
"/etc/cron.weekly",
|
|
49
|
+
"/etc/cron.hourly",
|
|
50
|
+
"/etc/cron.monthly",
|
|
51
|
+
):
|
|
52
|
+
base = Path(folder)
|
|
53
|
+
if base.is_dir():
|
|
54
|
+
try:
|
|
55
|
+
cron_files.extend(path for path in base.iterdir() if path.is_file())
|
|
56
|
+
except OSError:
|
|
57
|
+
pass
|
|
58
|
+
for path in cron_files:
|
|
59
|
+
try:
|
|
60
|
+
if path.is_file() and path.stat().st_size <= 256 * 1024:
|
|
61
|
+
yield str(path), read_text(path)
|
|
62
|
+
except OSError:
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
ok, out, _, _ = run_cmd(["crontab", "-l"], timeout=5)
|
|
66
|
+
if ok and out:
|
|
67
|
+
yield "当前用户 crontab", out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def discover_restic_repos(restic_cfg):
|
|
71
|
+
repos = []
|
|
72
|
+
seen = set()
|
|
73
|
+
|
|
74
|
+
def add(repo, password_file=None, source="", name=None, env=None):
|
|
75
|
+
if not repo:
|
|
76
|
+
return
|
|
77
|
+
repo = str(repo).strip().strip("'\"")
|
|
78
|
+
if not repo or repo.startswith("-"):
|
|
79
|
+
return
|
|
80
|
+
if any(char in repo for char in "$`{}\\"):
|
|
81
|
+
return
|
|
82
|
+
if repo.startswith("~"):
|
|
83
|
+
repo = os.path.expanduser(repo)
|
|
84
|
+
if not (repo.startswith("/") or ":" in repo):
|
|
85
|
+
return
|
|
86
|
+
if repo in seen:
|
|
87
|
+
return
|
|
88
|
+
seen.add(repo)
|
|
89
|
+
|
|
90
|
+
if password_file:
|
|
91
|
+
password_file = str(password_file).strip().strip("'\"")
|
|
92
|
+
if password_file.startswith("~"):
|
|
93
|
+
password_file = os.path.expanduser(password_file)
|
|
94
|
+
if "$" in password_file or "`" in password_file:
|
|
95
|
+
password_file = None
|
|
96
|
+
|
|
97
|
+
if not name:
|
|
98
|
+
base = repo.rstrip("/").rsplit("/", 1)[-1]
|
|
99
|
+
name = base if base and ":" not in base else repo
|
|
100
|
+
repos.append(
|
|
101
|
+
{
|
|
102
|
+
"repository": repo,
|
|
103
|
+
"password_file": password_file,
|
|
104
|
+
"name": name,
|
|
105
|
+
"source": source,
|
|
106
|
+
"env": dict(env or {}),
|
|
107
|
+
}
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
# 1. 配置文件
|
|
111
|
+
for item in restic_cfg.get("repos") or []:
|
|
112
|
+
if isinstance(item, str):
|
|
113
|
+
add(item, source="配置文件")
|
|
114
|
+
elif isinstance(item, dict):
|
|
115
|
+
add(
|
|
116
|
+
item.get("repository") or item.get("repo"),
|
|
117
|
+
item.get("password_file"),
|
|
118
|
+
"配置文件",
|
|
119
|
+
item.get("name"),
|
|
120
|
+
item.get("env"),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# 2. 环境变量
|
|
124
|
+
add(
|
|
125
|
+
os.environ.get("RESTIC_REPOSITORY"),
|
|
126
|
+
os.environ.get("RESTIC_PASSWORD_FILE"),
|
|
127
|
+
"环境变量 RESTIC_REPOSITORY",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
# 3. 自动发现
|
|
131
|
+
for source, text in iter_restic_config_sources():
|
|
132
|
+
for raw_line in text.splitlines():
|
|
133
|
+
line = raw_line.strip()
|
|
134
|
+
if not line or line.startswith("#") or "restic" not in line.lower():
|
|
135
|
+
continue
|
|
136
|
+
password_match = PASS_RE.search(line)
|
|
137
|
+
password_file = password_match.group(2) if password_match else None
|
|
138
|
+
found = [match.group(2) for match in REPO_FLAG_RE.finditer(line)]
|
|
139
|
+
env_match = ENV_REPO_RE.search(line)
|
|
140
|
+
if env_match:
|
|
141
|
+
found.append(env_match.group(1))
|
|
142
|
+
for repo in found:
|
|
143
|
+
add(repo, password_file, source)
|
|
144
|
+
|
|
145
|
+
return repos
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def collect_one_restic(repo_cfg, restic_bin, timeout):
|
|
149
|
+
now = time.time()
|
|
150
|
+
repository = repo_cfg["repository"]
|
|
151
|
+
entry = {
|
|
152
|
+
"name": repo_cfg.get("name") or repository,
|
|
153
|
+
"repository": redact_repository(repository),
|
|
154
|
+
"source": repo_cfg.get("source") or "",
|
|
155
|
+
"ok": False,
|
|
156
|
+
"error": None,
|
|
157
|
+
"snapshot_count": 0,
|
|
158
|
+
"latest_time": None,
|
|
159
|
+
"latest_age": None,
|
|
160
|
+
"snapshots": [],
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
password_file = repo_cfg.get("password_file")
|
|
164
|
+
if password_file and not Path(password_file).exists():
|
|
165
|
+
entry["error"] = "密码文件不存在: %s" % password_file
|
|
166
|
+
return entry
|
|
167
|
+
if repository.startswith("/") and not Path(repository).exists():
|
|
168
|
+
entry["error"] = "仓库路径不存在: %s" % repository
|
|
169
|
+
return entry
|
|
170
|
+
|
|
171
|
+
cmd = [restic_bin, "-r", repository]
|
|
172
|
+
if password_file:
|
|
173
|
+
cmd += ["--password-file", password_file]
|
|
174
|
+
cmd += ["snapshots", "--json"]
|
|
175
|
+
|
|
176
|
+
ok, out, err, _ = run_cmd(cmd, timeout=timeout, env=repo_cfg.get("env"))
|
|
177
|
+
if not ok:
|
|
178
|
+
entry["error"] = truncate(clean_restic_error(err or out or "restic snapshots 执行失败"))
|
|
179
|
+
return entry
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
raw = json.loads(out) if out else []
|
|
183
|
+
except json.JSONDecodeError:
|
|
184
|
+
entry["error"] = "无法解析 restic 输出: %s" % truncate(out, 200)
|
|
185
|
+
return entry
|
|
186
|
+
if not isinstance(raw, list):
|
|
187
|
+
entry["error"] = "restic 返回了意外的数据结构"
|
|
188
|
+
return entry
|
|
189
|
+
|
|
190
|
+
snapshots = []
|
|
191
|
+
for item in raw:
|
|
192
|
+
timestamp = parse_iso_epoch(item.get("time"))
|
|
193
|
+
if timestamp is None:
|
|
194
|
+
continue
|
|
195
|
+
snapshots.append(
|
|
196
|
+
{
|
|
197
|
+
"time": timestamp,
|
|
198
|
+
"hostname": item.get("hostname") or "",
|
|
199
|
+
"paths": item.get("paths") or [],
|
|
200
|
+
"tags": item.get("tags") or [],
|
|
201
|
+
"id": (item.get("short_id") or item.get("id") or "")[:12],
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
snapshots.sort(key=lambda snapshot: snapshot["time"], reverse=True)
|
|
205
|
+
|
|
206
|
+
entry["ok"] = True
|
|
207
|
+
entry["snapshot_count"] = len(snapshots)
|
|
208
|
+
if snapshots:
|
|
209
|
+
entry["latest_time"] = snapshots[0]["time"]
|
|
210
|
+
entry["latest_age"] = max(0, round(now - snapshots[0]["time"]))
|
|
211
|
+
entry["snapshots"] = snapshots[:8]
|
|
212
|
+
return entry
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def collect_restic(restic_cfg):
|
|
216
|
+
now = time.time()
|
|
217
|
+
restic_bin = shutil.which("restic")
|
|
218
|
+
if not restic_cfg.get("enabled", True):
|
|
219
|
+
return {
|
|
220
|
+
"updated_at": now,
|
|
221
|
+
"enabled": False,
|
|
222
|
+
"available": bool(restic_bin),
|
|
223
|
+
"repos": [],
|
|
224
|
+
"error": None,
|
|
225
|
+
}
|
|
226
|
+
if not restic_bin:
|
|
227
|
+
return {
|
|
228
|
+
"updated_at": now,
|
|
229
|
+
"enabled": True,
|
|
230
|
+
"available": False,
|
|
231
|
+
"repos": [],
|
|
232
|
+
"error": "未安装 restic",
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
found = discover_restic_repos(restic_cfg)
|
|
236
|
+
timeout = restic_cfg.get("timeout", 60)
|
|
237
|
+
results = [collect_one_restic(repo, restic_bin, timeout) for repo in found]
|
|
238
|
+
return {
|
|
239
|
+
"updated_at": now,
|
|
240
|
+
"enabled": True,
|
|
241
|
+
"available": True,
|
|
242
|
+
"repos": results,
|
|
243
|
+
"error": None,
|
|
244
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""系统静态信息与 CPU / 内存 / 负载等基础指标。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
import socket
|
|
8
|
+
|
|
9
|
+
from ..utils import read_text
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def collect_static_system():
|
|
13
|
+
osrel = {}
|
|
14
|
+
for line in read_text("/etc/os-release").splitlines():
|
|
15
|
+
if "=" in line:
|
|
16
|
+
key, value = line.split("=", 1)
|
|
17
|
+
osrel[key.strip()] = value.strip().strip('"')
|
|
18
|
+
|
|
19
|
+
cpu_model = ""
|
|
20
|
+
for line in read_text("/proc/cpuinfo").splitlines():
|
|
21
|
+
low = line.lower()
|
|
22
|
+
if (
|
|
23
|
+
low.startswith("model name")
|
|
24
|
+
or low.startswith("hardware")
|
|
25
|
+
or low.startswith("processor\t:")
|
|
26
|
+
):
|
|
27
|
+
cpu_model = line.split(":", 1)[-1].strip()
|
|
28
|
+
if cpu_model:
|
|
29
|
+
break
|
|
30
|
+
|
|
31
|
+
boot_time = None
|
|
32
|
+
for line in read_text("/proc/stat").splitlines():
|
|
33
|
+
if line.startswith("btime "):
|
|
34
|
+
try:
|
|
35
|
+
boot_time = float(line.split()[1])
|
|
36
|
+
except (IndexError, ValueError):
|
|
37
|
+
pass
|
|
38
|
+
break
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
"hostname": socket.gethostname(),
|
|
42
|
+
"os": osrel.get("PRETTY_NAME") or osrel.get("NAME") or "Linux",
|
|
43
|
+
"kernel": platform.release(),
|
|
44
|
+
"arch": platform.machine(),
|
|
45
|
+
"cpu_model": cpu_model or "未知",
|
|
46
|
+
"cpu_cores": os.cpu_count() or 0,
|
|
47
|
+
"boot_time": boot_time,
|
|
48
|
+
"python": platform.python_version(),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_cpu_times():
|
|
53
|
+
"""返回 {'cpu': (total, idle), 'cpu0': ...},单位是 USER_HZ 的累计值。"""
|
|
54
|
+
result = {}
|
|
55
|
+
for line in read_text("/proc/stat").splitlines():
|
|
56
|
+
if not line.startswith("cpu"):
|
|
57
|
+
continue
|
|
58
|
+
parts = line.split()
|
|
59
|
+
name = parts[0]
|
|
60
|
+
try:
|
|
61
|
+
values = [float(value) for value in parts[1:]]
|
|
62
|
+
except ValueError:
|
|
63
|
+
continue
|
|
64
|
+
if len(values) < 8:
|
|
65
|
+
values += [0.0] * (8 - len(values))
|
|
66
|
+
total = sum(values[:8])
|
|
67
|
+
idle = values[3] + values[4] # idle + iowait
|
|
68
|
+
result[name] = (total, idle)
|
|
69
|
+
return result
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cpu_usage(previous, current):
|
|
73
|
+
if not previous:
|
|
74
|
+
return 0.0, []
|
|
75
|
+
|
|
76
|
+
def delta(key):
|
|
77
|
+
if key not in previous or key not in current:
|
|
78
|
+
return None
|
|
79
|
+
total_delta = current[key][0] - previous[key][0]
|
|
80
|
+
idle_delta = current[key][1] - previous[key][1]
|
|
81
|
+
if total_delta <= 0:
|
|
82
|
+
return None
|
|
83
|
+
return round(max(0.0, min(100.0, 100.0 * (1.0 - idle_delta / total_delta))), 1)
|
|
84
|
+
|
|
85
|
+
usage = delta("cpu") or 0.0
|
|
86
|
+
cores = []
|
|
87
|
+
for key in current:
|
|
88
|
+
if key == "cpu":
|
|
89
|
+
continue
|
|
90
|
+
value = delta(key)
|
|
91
|
+
if value is not None:
|
|
92
|
+
cores.append(value)
|
|
93
|
+
return usage, cores
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def read_cpu_mhz():
|
|
97
|
+
values = []
|
|
98
|
+
for line in read_text("/proc/cpuinfo").splitlines():
|
|
99
|
+
if line.startswith("cpu MHz"):
|
|
100
|
+
try:
|
|
101
|
+
values.append(float(line.split(":", 1)[1]))
|
|
102
|
+
except (IndexError, ValueError):
|
|
103
|
+
pass
|
|
104
|
+
return round(sum(values) / len(values)) if values else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def read_memory():
|
|
108
|
+
info = {}
|
|
109
|
+
for line in read_text("/proc/meminfo").splitlines():
|
|
110
|
+
if ":" not in line:
|
|
111
|
+
continue
|
|
112
|
+
key, value = line.split(":", 1)
|
|
113
|
+
try:
|
|
114
|
+
info[key] = int(value.split()[0]) * 1024
|
|
115
|
+
except (IndexError, ValueError):
|
|
116
|
+
pass
|
|
117
|
+
total = info.get("MemTotal", 0)
|
|
118
|
+
available = info.get("MemAvailable")
|
|
119
|
+
if available is None:
|
|
120
|
+
available = info.get("MemFree", 0) + info.get("Buffers", 0) + info.get("Cached", 0)
|
|
121
|
+
used = max(0, total - available)
|
|
122
|
+
swap_total = info.get("SwapTotal", 0)
|
|
123
|
+
swap_free = info.get("SwapFree", 0)
|
|
124
|
+
return {
|
|
125
|
+
"total": total,
|
|
126
|
+
"used": used,
|
|
127
|
+
"available": available,
|
|
128
|
+
"free": info.get("MemFree", 0),
|
|
129
|
+
"buffers": info.get("Buffers", 0),
|
|
130
|
+
"cached": info.get("Cached", 0) + info.get("SReclaimable", 0),
|
|
131
|
+
"swap_total": swap_total,
|
|
132
|
+
"swap_used": max(0, swap_total - swap_free),
|
|
133
|
+
"percent": round(used * 100.0 / total, 1) if total else 0.0,
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def read_load():
|
|
138
|
+
parts = read_text("/proc/loadavg").split()
|
|
139
|
+
if len(parts) < 4:
|
|
140
|
+
return [0.0, 0.0, 0.0], {"running": 0, "total": 0}
|
|
141
|
+
load = []
|
|
142
|
+
for value in parts[:3]:
|
|
143
|
+
try:
|
|
144
|
+
load.append(float(value))
|
|
145
|
+
except ValueError:
|
|
146
|
+
load.append(0.0)
|
|
147
|
+
try:
|
|
148
|
+
running, total = parts[3].split("/", 1)
|
|
149
|
+
processes = {"running": int(running), "total": int(total)}
|
|
150
|
+
except (ValueError, IndexError):
|
|
151
|
+
processes = {"running": 0, "total": 0}
|
|
152
|
+
return load, processes
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def read_uptime():
|
|
156
|
+
try:
|
|
157
|
+
return float(read_text("/proc/uptime").split()[0])
|
|
158
|
+
except (IndexError, ValueError):
|
|
159
|
+
return None
|