feat: 内存回收改为大按钮样式 + 恢复Docker源码
This commit is contained in:
1 parent
de153140f4
commit
b9757e2ccb
9 files changed
+1241
No files matched your search
+11
@@ -0,0 +1,11 @@
|
||||
FROM python:3.11-slim
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends iproute2 util-linux && rm -rf /var/lib/apt/lists/* && pip install --no-cache-dir flask psutil -i https://mirrors.aliyun.com/pypi/simple/
|
||||
COPY app.py .
|
||||
COPY hw_mem.json .
|
||||
COPY hw_disk.json .
|
||||
COPY hw_net.json .
|
||||
COPY public ./public
|
||||
ENV PORT=7031
|
||||
EXPOSE 7031
|
||||
CMD ["python", "app.py"]
|
||||
@@ -0,0 +1,975 @@
|
||||
from flask import Flask, jsonify, request, send_from_directory
|
||||
import psutil, os, time, signal, threading, subprocess, platform, glob, json, struct
|
||||
try:
|
||||
psutil.PROCFS_PATH = os.environ.get("PROCFS_PATH", "/proc")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
PROCFS = os.environ.get("PROCFS_PATH", "/host/proc")
|
||||
if os.path.isdir(PROCFS):
|
||||
psutil.PROCFS_PATH = PROCFS
|
||||
|
||||
app = Flask(__name__, static_folder="public", static_url_path="")
|
||||
PORT = int(os.environ.get("PORT", "7031"))
|
||||
|
||||
# ---------- host netns helpers (桥接模式用) ----------
|
||||
# 容器切桥接后,直读 /proc/net 只能看到容器自身 netns。
|
||||
# 网络类数据统一经 nsenter 进入宿主(PID 1) netns 读取,保证与 host 模式一致。
|
||||
NSENTER = ["nsenter", "--target", "1", "--mount", "--net"]
|
||||
|
||||
def _nsenter_run(args, timeout=8):
|
||||
try:
|
||||
return subprocess.check_output(NSENTER + list(args), text=True,
|
||||
stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
from collections import namedtuple as _namedtuple
|
||||
_NC = _namedtuple("NC", ["bytes_sent", "bytes_recv"])
|
||||
|
||||
def _parse_proc_net_dev(txt):
|
||||
res = {}
|
||||
try:
|
||||
for line in (txt or "").splitlines():
|
||||
if ":" not in line:
|
||||
continue
|
||||
nic, rest = line.split(":", 1)
|
||||
nic = nic.strip()
|
||||
if not nic or nic == "Inter":
|
||||
continue
|
||||
f = rest.split()
|
||||
if len(f) < 16:
|
||||
continue
|
||||
try:
|
||||
recv, sent = int(f[0]), int(f[8])
|
||||
except Exception:
|
||||
continue
|
||||
res[nic] = _NC(sent, recv)
|
||||
except Exception:
|
||||
pass
|
||||
return res
|
||||
|
||||
def _host_nic_counters():
|
||||
"""宿主网卡流量;失败回退 psutil(容器视角)"""
|
||||
out = _parse_proc_net_dev(_nsenter_run(["cat", "/proc/net/dev"]))
|
||||
if out:
|
||||
return out
|
||||
try:
|
||||
return dict(psutil.net_io_counters(pernic=True) or {})
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _parse_ip_addr(txt):
|
||||
out = {}
|
||||
try:
|
||||
for line in (txt or "").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) < 4 or not parts[0].endswith(":"):
|
||||
continue
|
||||
nic, fam = parts[1], parts[2]
|
||||
e = out.setdefault(nic, {"v4": [], "v6": [], "mac": ""})
|
||||
if fam == "inet":
|
||||
addr = parts[3].split("/")[0]
|
||||
if addr and len(addr.split(".")) == 4 and addr not in e["v4"]:
|
||||
e["v4"].append(addr)
|
||||
elif fam == "inet6":
|
||||
addr = parts[3].split("/")[0].split("%")[0]
|
||||
if not addr:
|
||||
continue
|
||||
if addr.startswith("fe80"):
|
||||
addr = addr + "(链路)"
|
||||
if addr not in e["v6"]:
|
||||
e["v6"].append(addr)
|
||||
elif fam.startswith("link") and parts[2] == "link/ether":
|
||||
mac = parts[3]
|
||||
if mac and mac != "00:00:00:00:00:00":
|
||||
e["mac"] = e["mac"] or mac
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
def _host_ss():
|
||||
"""宿主 tcp/udp 连接+监听,经 nsenter 在宿主 netns 执行 ss;失败返回 None"""
|
||||
out = _nsenter_run(["ss", "-tunHn", "state", "all"])
|
||||
if not out or not out.strip():
|
||||
return None
|
||||
import re as _re
|
||||
tcp_list, listen_list = [], []
|
||||
|
||||
def _split(addr):
|
||||
if not addr or addr == "*:*":
|
||||
return "", 0
|
||||
if addr.startswith("["):
|
||||
host, _, port = addr.rpartition(":")
|
||||
try:
|
||||
return host.strip("[]"), int(port)
|
||||
except Exception:
|
||||
return host.strip("[]"), 0
|
||||
host, _, port = addr.rpartition(":")
|
||||
try:
|
||||
port = int(port)
|
||||
except Exception:
|
||||
port = 0
|
||||
return host, port
|
||||
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) < 6:
|
||||
continue
|
||||
proto = parts[0].lower()
|
||||
state = parts[1]
|
||||
lh, lp = _split(parts[4])
|
||||
rh, rp = _split(parts[5])
|
||||
m = _re.search(r'\("([^"]+)",pid=(\d+)', line)
|
||||
name = m.group(1) if m else ""
|
||||
try:
|
||||
pid = int(m.group(2)) if m else None
|
||||
except Exception:
|
||||
pid = None
|
||||
family = "ipv6" if (":" in lh and "." not in lh) else "ipv4"
|
||||
if state == "LISTEN":
|
||||
listen_list.append({"name": name, "laddr": lh, "port": lp,
|
||||
"family": family, "pid": pid, "proto": proto})
|
||||
else:
|
||||
tcp_list.append({"name": name,
|
||||
"laddr": f"{lh}:{lp}" if lh else "",
|
||||
"raddr": f"{rh}:{rp}" if rh else "",
|
||||
"family": family, "pid": pid, "status": state})
|
||||
return tcp_list, listen_list
|
||||
|
||||
# ---------- background sampler ----------
|
||||
cache = {"procs": [], "cpu": 0.0, "load": [0, 0, 0], "ts": 0}
|
||||
net_prev = {}
|
||||
net_rate = {}
|
||||
|
||||
def fmt_status(s):
|
||||
m = {
|
||||
psutil.STATUS_RUNNING: ("活动", 1),
|
||||
psutil.STATUS_SLEEPING: ("睡眠", 0),
|
||||
psutil.STATUS_DISK_SLEEP: ("睡眠", 0),
|
||||
psutil.STATUS_STOPPED: ("停止", 0),
|
||||
psutil.STATUS_ZOMBIE: ("僵尸", 0),
|
||||
}
|
||||
return m.get(s, ("睡眠", 0))
|
||||
|
||||
_uid_cache = {"map": {}, "ts": 0}
|
||||
|
||||
def uid_name(uid_str):
|
||||
# 容器内 /etc/passwd 没有宿主用户,uid 会显示成数字,用宿主 passwd 还原
|
||||
if not uid_str or not uid_str.isdigit():
|
||||
return uid_str
|
||||
now = time.time()
|
||||
if now - _uid_cache["ts"] > 300:
|
||||
m = {}
|
||||
try:
|
||||
with open("/host/etc/passwd") as f:
|
||||
for line in f:
|
||||
p = line.split(":")
|
||||
if len(p) > 3:
|
||||
try:
|
||||
m[p[2]] = p[0]
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
_uid_cache["map"] = m
|
||||
_uid_cache["ts"] = now
|
||||
return _uid_cache["map"].get(uid_str, uid_str)
|
||||
|
||||
def sample_procs():
|
||||
# init cpu percent calculation
|
||||
for p in psutil.process_iter():
|
||||
try:
|
||||
p.cpu_percent(None)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.0)
|
||||
procs = []
|
||||
try:
|
||||
cpu_total = psutil.cpu_percent(interval=None)
|
||||
except Exception:
|
||||
cpu_total = 0
|
||||
try:
|
||||
load = list(os.getloadavg())
|
||||
except Exception:
|
||||
load = [0, 0, 0]
|
||||
for p in psutil.process_iter(["pid", "name", "username", "status", "num_threads", "cmdline"]):
|
||||
try:
|
||||
with p.oneshot():
|
||||
cpu = p.cpu_percent(None)
|
||||
mem = p.memory_percent()
|
||||
try:
|
||||
rss = p.memory_info().rss
|
||||
except Exception:
|
||||
rss = 0
|
||||
uss = 0
|
||||
swap = 0
|
||||
try:
|
||||
mfi = p.memory_full_info()
|
||||
uss = getattr(mfi, "uss", 0) or 0
|
||||
swap = getattr(mfi, "swap", 0) or 0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
io = p.io_counters()
|
||||
rd, wr = io.read_bytes, io.write_bytes
|
||||
except Exception:
|
||||
rd, wr = 0, 0
|
||||
try:
|
||||
conns = len(p.net_connections())
|
||||
except Exception:
|
||||
conns = 0
|
||||
info = p.info
|
||||
name = info.get("name") or ""
|
||||
cmd = " ".join(info.get("cmdline") or [])[:120]
|
||||
desc = cmd if cmd else name
|
||||
st, act = fmt_status(info.get("status"))
|
||||
if (not act) and (cpu or 0) > 1.0:
|
||||
st, act = "活动", 1
|
||||
procs.append({
|
||||
"name": name[:40], "pid": info["pid"],
|
||||
"cpu": round(cpu or 0, 2), "mem": round(mem or 0, 2),
|
||||
"rss": rss, "uss": uss, "swap": swap, "threads": info.get("num_threads") or 0,
|
||||
"user": uid_name(str(info.get("username") or ""))[:20],
|
||||
"status": st, "active": act,
|
||||
"desc": desc[:80], "io_r": rd, "io_w": wr, "conns": conns,
|
||||
})
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
procs.sort(key=lambda x: x["cpu"], reverse=True)
|
||||
cache["procs"] = procs
|
||||
cache["cpu"] = round(cpu_total, 1)
|
||||
cache["load"] = [round(x, 2) for x in load]
|
||||
cache["ts"] = time.time()
|
||||
|
||||
def sampler_loop():
|
||||
while True:
|
||||
try:
|
||||
sample_procs()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
|
||||
threading.Thread(target=sampler_loop, daemon=True).start()
|
||||
# warm up immediately in background; serve stale until ready
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return send_from_directory("public", "index.html")
|
||||
|
||||
@app.route("/api/cpu")
|
||||
def api_cpu():
|
||||
active = sum(1 for p in cache["procs"] if p["active"])
|
||||
return jsonify({"cpu": cache["cpu"], "load": cache["load"],
|
||||
"active": active, "total": len(cache["procs"]),
|
||||
"info": get_cpu_info(), "percpu": get_percpu(),
|
||||
"items": cache["procs"][:100]})
|
||||
|
||||
_cpu_static = {}
|
||||
|
||||
def _parse_host_cpuinfo():
|
||||
info = {}
|
||||
try:
|
||||
with open("/host/proc/cpuinfo") as f:
|
||||
txt = f.read()
|
||||
except Exception:
|
||||
try:
|
||||
with open("/proc/cpuinfo") as f:
|
||||
txt = f.read()
|
||||
except Exception:
|
||||
return info
|
||||
# 取第一个 processor 段的 model name / cache size / cpu MHz
|
||||
for line in txt.splitlines():
|
||||
if ":" not in line:
|
||||
continue
|
||||
k, v = line.split(":", 1)
|
||||
k, v = k.strip(), v.strip()
|
||||
if k == "model name" and "model" not in info:
|
||||
info["model"] = v
|
||||
elif k == "cache size" and "cache" not in info:
|
||||
info["cache"] = v
|
||||
return info
|
||||
|
||||
def _parse_lscpu():
|
||||
out = {}
|
||||
try:
|
||||
txt = subprocess.run(["lscpu"], capture_output=True, text=True,
|
||||
timeout=5).stdout
|
||||
except Exception:
|
||||
return out
|
||||
for line in txt.splitlines():
|
||||
if ":" not in line and ":" not in line:
|
||||
continue
|
||||
line = line.replace(":", ":")
|
||||
k, v = line.split(":", 1)
|
||||
k, v = k.strip(), v.strip()
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
def get_cpu_info():
|
||||
global _cpu_static
|
||||
if not _cpu_static:
|
||||
ci = _parse_host_cpuinfo()
|
||||
lc = _parse_lscpu()
|
||||
def pick(*keys):
|
||||
for k in keys:
|
||||
if k in lc and lc[k]:
|
||||
return lc[k]
|
||||
return ""
|
||||
# L1d/L1i/L2/L3 键名中英文兼容
|
||||
l1d = pick("L1d 缓存", "L1d cache")
|
||||
l1i = pick("L1i 缓存", "L1i cache")
|
||||
l2 = pick("L2 缓存", "L2 cache")
|
||||
l3 = pick("L3 缓存", "L3 cache")
|
||||
_cpu_static = {
|
||||
"model": ci.get("model") or pick("型号名称", "Model name"),
|
||||
"arch": platform.machine(),
|
||||
"sockets": pick("座", "Socket(s)"),
|
||||
"cores_per_socket": pick("每个座的核数", "Core(s) per socket"),
|
||||
"threads_per_core": pick("每个核的线程数", "Thread(s) per core"),
|
||||
"l1d": l1d, "l1i": l1i, "l2": l2, "l3": l3,
|
||||
"cache": ci.get("cache", ""),
|
||||
}
|
||||
try:
|
||||
f = psutil.cpu_freq()
|
||||
cur = round(f.current, 0) if f else 0
|
||||
fmin = round(f.min, 0) if f and f.min else 0
|
||||
fmax = round(f.max, 0) if f and f.max else 0
|
||||
except Exception:
|
||||
cur = fmin = fmax = 0
|
||||
d = dict(_cpu_static)
|
||||
d.update({
|
||||
"logical": psutil.cpu_count() or 0,
|
||||
"physical": psutil.cpu_count(logical=False) or 0,
|
||||
"freq_cur": cur, "freq_min": fmin, "freq_max": fmax,
|
||||
})
|
||||
return d
|
||||
|
||||
def get_percpu():
|
||||
try:
|
||||
vals = psutil.cpu_percent(interval=None, percpu=True)
|
||||
return [round(v, 1) for v in (vals or [])]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
@app.route("/api/mem")
|
||||
def api_mem():
|
||||
vm = psutil.virtual_memory()
|
||||
sm = psutil.swap_memory()
|
||||
items = sorted(cache["procs"], key=lambda x: x["mem"], reverse=True)[:100]
|
||||
mi = _read_meminfo_host()
|
||||
dm = get_mem_hw()
|
||||
return jsonify({
|
||||
"total": vm.total, "used": vm.used, "available": vm.available,
|
||||
"percent": vm.percent, "cached": getattr(vm, "cached", 0),
|
||||
"swap_total": sm.total, "swap_used": sm.used, "swap_percent": sm.percent,
|
||||
"detail": mi, "hw": dm,
|
||||
"items": items})
|
||||
|
||||
_mem_hw_static = {}
|
||||
|
||||
def _read_meminfo_host():
|
||||
mi = {}
|
||||
for p in ("/host/proc/meminfo", "/proc/meminfo"):
|
||||
try:
|
||||
with open(p) as f:
|
||||
for line in f:
|
||||
if ":" not in line:
|
||||
continue
|
||||
k, v = line.split(":", 1)
|
||||
parts = v.strip().split()
|
||||
if not parts:
|
||||
continue
|
||||
try:
|
||||
num = int(parts[0])
|
||||
except ValueError:
|
||||
continue
|
||||
# 统一转 bytes
|
||||
if len(parts) > 1 and parts[1] == "kB":
|
||||
num *= 1024
|
||||
mi[k.strip()] = num
|
||||
if mi:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
return mi
|
||||
|
||||
def _walk_dmi(path):
|
||||
"""yield (type, raw_bytes, strings)"""
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
except Exception:
|
||||
return
|
||||
off, n = 0, 0
|
||||
L = len(data)
|
||||
while off + 4 <= L and n < 200:
|
||||
typ, ln = data[off], data[off + 1]
|
||||
if ln < 4 or off + ln > L:
|
||||
break
|
||||
if typ == 127: # end of table
|
||||
break
|
||||
s = off + ln
|
||||
strs = []
|
||||
ok = True
|
||||
while s < L:
|
||||
try:
|
||||
e = data.index(b"\x00", s)
|
||||
except ValueError:
|
||||
ok = False
|
||||
break
|
||||
if e == s:
|
||||
s += 1
|
||||
break
|
||||
strs.append(data[s:e].decode("utf-8", "replace").strip())
|
||||
s = e + 1
|
||||
if not ok:
|
||||
break
|
||||
yield typ, data[off:off + ln], strs
|
||||
off = s
|
||||
n += 1
|
||||
|
||||
_MEM_TYPE = {0x02: "Unknown", 0x03: "DRAM", 0x12: "DDR", 0x13: "DDR2",
|
||||
0x14: "DDR2 FB-DIMM", 0x18: "DDR3", 0x19: "FBD2", 0x1A: "DDR4",
|
||||
0x1B: "LPDDR", 0x1C: "LPDDR2", 0x1D: "LPDDR3", 0x1E: "LPDDR4",
|
||||
0x1F: "Logical NV", 0x20: "HBM", 0x21: "HBM2", 0x22: "DDR5",
|
||||
0x23: "LPDDR5", 0x24: "HBM3"}
|
||||
|
||||
def _parse_dmi_mem():
|
||||
dimms, max_cap_kb = [], 0
|
||||
for dmi_path in ("/host/sys/firmware/dmi/tables/DMI",
|
||||
"/sys/firmware/dmi/tables/DMI"):
|
||||
found = False
|
||||
for typ, raw, strs in _walk_dmi(dmi_path):
|
||||
found = True
|
||||
def S(i):
|
||||
return strs[i - 1] if 1 <= i <= len(strs) else ""
|
||||
if typ == 16 and len(raw) >= 11:
|
||||
import struct
|
||||
(cap,) = struct.unpack_from("<I", raw, 7)
|
||||
if cap not in (0, 0x80000000):
|
||||
max_cap_kb = cap # SMBIOS 单位 kB
|
||||
elif typ == 17 and len(raw) >= 28:
|
||||
import struct
|
||||
(size,) = struct.unpack_from("<H", raw, 12)
|
||||
if size == 0 or size == 0xFFFF:
|
||||
continue # 空槽
|
||||
if size & 0x8000:
|
||||
mb = size & 0x7FFF # bit15=1 时单位 KB→转MB(向上)
|
||||
size_mb = max(mb // 1024, 1) if mb >= 1024 else 1
|
||||
size_b = (size & 0x7FFF) * 1024
|
||||
else:
|
||||
size_mb = size & 0x7FFF
|
||||
size_b = size_mb * 1024 * 1024
|
||||
if size_mb == 0x7FFF:
|
||||
continue
|
||||
(speed,) = struct.unpack_from("<H", raw, 20)
|
||||
cspeed = 0
|
||||
if len(raw) >= 30:
|
||||
(cspeed,) = struct.unpack_from("<H", raw, 28)
|
||||
mtype = raw[18] if len(raw) > 18 else 0
|
||||
dimms.append({
|
||||
"locator": S(raw[16]) if len(raw) > 16 else "",
|
||||
"bank": S(raw[17]) if len(raw) > 17 else "",
|
||||
"size_b": size_b, "size_mb": size_mb,
|
||||
"type": _MEM_TYPE.get(mtype, "DDR4" if mtype == 0 else hex(mtype)),
|
||||
"speed": speed or 0, "cspeed": cspeed or 0,
|
||||
"maker": S(raw[22]) if len(raw) > 22 else "",
|
||||
"serial": S(raw[23]) if len(raw) > 23 else "",
|
||||
"part": S(raw[25]) if len(raw) > 25 else "",
|
||||
})
|
||||
if found:
|
||||
break
|
||||
return dimms, max_cap_kb
|
||||
|
||||
def _get_vram():
|
||||
total = 0
|
||||
for base in ("/host/sys/class/drm", "/sys/class/drm"):
|
||||
try:
|
||||
for p in glob.glob(base + "/card*/device/mem_info_vram_total"):
|
||||
try:
|
||||
with open(p) as f:
|
||||
total += int(f.read().strip())
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
if total:
|
||||
break
|
||||
return total
|
||||
|
||||
def get_mem_hw():
|
||||
global _mem_hw_static
|
||||
if not _mem_hw_static:
|
||||
dimms, max_cap_kb = [], 0
|
||||
# 优先读构建时从宿主 dmidecode 导出的静态槽位表
|
||||
for jp in ("hw_mem.json",
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"hw_mem.json")):
|
||||
try:
|
||||
with open(jp) as f:
|
||||
hj = json.load(f)
|
||||
dimms = hj.get("dimms", []) or []
|
||||
max_cap_kb = int((hj.get("max_cap_b", 0) or 0) // 1024)
|
||||
if dimms:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if not dimms:
|
||||
dimms, max_cap_kb = _parse_dmi_mem()
|
||||
installed = sum(d["size_b"] for d in dimms)
|
||||
_mem_hw_static = {"dimms": dimms, "installed": installed,
|
||||
"max_cap_kb": max_cap_kb}
|
||||
d = {"dimms": _mem_hw_static["dimms"],
|
||||
"installed": _mem_hw_static["installed"],
|
||||
"max_cap_kb": _mem_hw_static["max_cap_kb"]}
|
||||
try:
|
||||
mem_total = psutil.virtual_memory().total
|
||||
except Exception:
|
||||
mem_total = 0
|
||||
d["vram"] = _get_vram()
|
||||
d["system_total"] = mem_total
|
||||
d["reserved"] = (d["installed"] - mem_total) if d["installed"] and mem_total else 0
|
||||
return d
|
||||
|
||||
HOST_MNTS = [("/", "/host"), ("/vol1", "/host/vol1"),
|
||||
("/vol2", "/host/vol2"), ("/vol3", "/host/vol3")]
|
||||
|
||||
def _df_host():
|
||||
"""容器内 df 直读宿主路径(经 bind 进来的宿主目录),返回 {mnt: {...}}"""
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["df", "-B1", "--output=source,target,fstype,size,used,avail",
|
||||
"/host", "/host/vol1", "/host/vol2", "/host/vol3"],
|
||||
capture_output=True, text=True, timeout=5).stdout.splitlines()
|
||||
res = {}
|
||||
for line in out[1:]:
|
||||
p = line.split()
|
||||
if len(p) < 6:
|
||||
continue
|
||||
dev, tgt, fst, size, used, avail = p[0], p[1], p[2], int(p[3]), int(p[4]), int(p[5])
|
||||
mnt = tgt.replace("/host", "", 1) or "/"
|
||||
res[mnt] = {"device": dev, "mount": mnt, "fstype": fst,
|
||||
"total": size, "used": used, "free": avail,
|
||||
"percent": round(used / size * 100, 1) if size else 0}
|
||||
return res
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@app.route("/api/mem/drop", methods=["POST"])
|
||||
def api_mem_drop():
|
||||
import subprocess
|
||||
try:
|
||||
subprocess.run(["sync"], check=False, timeout=10)
|
||||
p = os.environ.get("PROCFS_PATH", "/proc")
|
||||
with open(os.path.join(p, "sys", "vm", "drop_caches"), "w") as f:
|
||||
f.write("3")
|
||||
vm = psutil.virtual_memory()
|
||||
return jsonify({"ok": True, "available": vm.available, "percent": vm.percent})
|
||||
except Exception as e:
|
||||
return jsonify({"ok": False, "error": str(e)}), 500
|
||||
@app.route("/api/disk")
|
||||
def api_disk():
|
||||
parts = []
|
||||
dfm = _df_host()
|
||||
for mp, hp in HOST_MNTS:
|
||||
if mp in dfm:
|
||||
parts.append(dfm[mp])
|
||||
continue
|
||||
try:
|
||||
st = os.statvfs(hp)
|
||||
total = st.f_blocks * st.f_frsize
|
||||
free = st.f_bavail * st.f_frsize
|
||||
used = total - free
|
||||
parts.append({"device": "?", "mount": mp, "fstype": "?",
|
||||
"total": total, "used": used, "free": free,
|
||||
"percent": round(used / total * 100, 1) if total else 0})
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
dio = psutil.disk_io_counters()
|
||||
dio_d = {"read": dio.read_bytes, "write": dio.write_bytes} if dio else {}
|
||||
except Exception:
|
||||
dio_d = {}
|
||||
# top io processes
|
||||
items = sorted(cache["procs"], key=lambda x: x["io_r"] + x["io_w"], reverse=True)[:60]
|
||||
return jsonify({"parts": parts, "io": dio_d, "hw": get_disk_hw(),
|
||||
"items": items})
|
||||
|
||||
_disk_hw_static = {}
|
||||
|
||||
def _read(p, default=""):
|
||||
try:
|
||||
with open(p) as f:
|
||||
return f.read().strip()
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
def _sys_block_base():
|
||||
for base in ("/host/sys/block", "/sys/block"):
|
||||
try:
|
||||
if os.path.isdir(base):
|
||||
return base
|
||||
except Exception:
|
||||
continue
|
||||
return "/host/sys/block"
|
||||
|
||||
def _live_sysfs(name):
|
||||
"""实时 sysfs: 容量/转速/型号(覆盖静态快照中的漂移项)"""
|
||||
base = _sys_block_base()
|
||||
d = os.path.join(base, name)
|
||||
out = {}
|
||||
try:
|
||||
sectors = _read(os.path.join(d, "size"))
|
||||
if sectors.isdigit():
|
||||
out["cap_b"] = int(sectors) * 512
|
||||
except Exception:
|
||||
pass
|
||||
rot = _read(os.path.join(d, "queue/rotational"))
|
||||
if rot in ("0", "1"):
|
||||
out["rotational"] = (rot == "1")
|
||||
model = _read(os.path.join(d, "device/model"))
|
||||
if model:
|
||||
out["sys_model"] = model
|
||||
vendor = _read(os.path.join(d, "device/vendor"))
|
||||
if vendor:
|
||||
out["sys_vendor"] = vendor
|
||||
return out
|
||||
|
||||
def _live_mdstat():
|
||||
"""实时 mdstat: 每组阵列状态/同步进度,键为 md 名"""
|
||||
st = {}
|
||||
for p in ("/host/proc/mdstat", "/proc/mdstat"):
|
||||
try:
|
||||
with open(p) as f:
|
||||
txt = f.read()
|
||||
break
|
||||
except Exception:
|
||||
txt = ""
|
||||
else:
|
||||
return st
|
||||
import re
|
||||
cur = None
|
||||
for line in txt.splitlines():
|
||||
m = re.match(r"^(md\d+)\s*:\s*(\w+)\s+(\w+)(.*)$", line)
|
||||
if m:
|
||||
cur = m.group(1)
|
||||
st[cur] = {"status": m.group(2), "level": m.group(3),
|
||||
"devs": m.group(4).strip(), "sync": ""}
|
||||
continue
|
||||
if cur and ("recovery" in line or "resync" in line or "blocks" in line):
|
||||
s = line.strip()
|
||||
if "recovery" in line or "resync" in line:
|
||||
st[cur]["sync"] = s
|
||||
elif "blocks" in line and not st[cur].get("blocks"):
|
||||
st[cur]["blocks"] = s
|
||||
return st
|
||||
|
||||
def _live_perdisk_io():
|
||||
try:
|
||||
d = psutil.disk_io_counters(perdisk=True) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
out = {}
|
||||
for k, v in d.items():
|
||||
try:
|
||||
out[k] = {"read": v.read_bytes, "write": v.write_bytes}
|
||||
except Exception:
|
||||
continue
|
||||
return out
|
||||
|
||||
def get_disk_hw():
|
||||
global _disk_hw_static
|
||||
if not _disk_hw_static:
|
||||
hj = {}
|
||||
for jp in ("hw_disk.json",
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"hw_disk.json")):
|
||||
try:
|
||||
with open(jp) as f:
|
||||
hj = json.load(f)
|
||||
if hj.get("disks"):
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
_disk_hw_static = hj or {"disks": [], "arrays": []}
|
||||
disks = [dict(x) for x in _disk_hw_static.get("disks", [])]
|
||||
arrays = [dict(x) for x in _disk_hw_static.get("arrays", [])]
|
||||
# 合并实时数据
|
||||
pio = _live_perdisk_io()
|
||||
for dk in disks:
|
||||
nm = dk.get("name", "")
|
||||
dk.update(_live_sysfs(nm))
|
||||
if nm in pio:
|
||||
dk["io_read"] = pio[nm]["read"]
|
||||
dk["io_write"] = pio[nm]["write"]
|
||||
# 转速文字
|
||||
if dk.get("rotational") is True and not dk.get("rpm"):
|
||||
dk["rpm"] = 5400
|
||||
md_live = _live_mdstat()
|
||||
for a in arrays:
|
||||
md = a.get("md", "")
|
||||
lv = md_live.get(md, {})
|
||||
if lv:
|
||||
a["live_status"] = lv.get("status", "")
|
||||
a["live_devs"] = lv.get("devs", "")
|
||||
a["live_sync"] = lv.get("sync", "")
|
||||
if md in pio:
|
||||
a["io_read"] = pio[md]["read"]
|
||||
a["io_write"] = pio[md]["write"]
|
||||
return {"disks": disks, "arrays": arrays,
|
||||
"extra": _disk_hw_static.get("extra", {}),
|
||||
"snapshot": _disk_hw_static.get("snapshot", ""),
|
||||
"note": _disk_hw_static.get("note", "")}
|
||||
|
||||
@app.route("/api/net")
|
||||
def api_net():
|
||||
global net_prev, net_rate
|
||||
now = time.time()
|
||||
try:
|
||||
counters = _host_nic_counters()
|
||||
except Exception:
|
||||
counters = {}
|
||||
rates = []
|
||||
for nic, c in counters.items():
|
||||
if nic.startswith(("lo", "docker", "br-", "veth")):
|
||||
continue
|
||||
prev = net_prev.get(nic)
|
||||
if prev:
|
||||
dt = max(now - prev["t"], 0.5)
|
||||
up = (c.bytes_sent - prev["sent"]) / dt
|
||||
down = (c.bytes_recv - prev["recv"]) / dt
|
||||
else:
|
||||
up = down = 0
|
||||
net_prev[nic] = {"sent": c.bytes_sent, "recv": c.bytes_recv, "t": now}
|
||||
rates.append({"nic": nic, "up": max(up, 0), "down": max(down, 0),
|
||||
"sent": c.bytes_sent, "recv": c.bytes_recv})
|
||||
rates.sort(key=lambda x: x["up"] + x["down"], reverse=True)
|
||||
try:
|
||||
_hss = _host_ss()
|
||||
except Exception:
|
||||
_hss = None
|
||||
if _hss is not None:
|
||||
_h_tcp, _h_listen = _hss
|
||||
conns = len(_h_tcp)
|
||||
else:
|
||||
_h_tcp, _h_listen = None, None
|
||||
try:
|
||||
conns = len(psutil.net_connections())
|
||||
except Exception:
|
||||
conns = 0
|
||||
total_recv = 0
|
||||
total_sent = 0
|
||||
for nic, c in counters.items():
|
||||
if nic.startswith(("lo", "docker", "br-", "veth")):
|
||||
continue
|
||||
total_recv += getattr(c, "bytes_recv", 0) or 0
|
||||
total_sent += getattr(c, "bytes_sent", 0) or 0
|
||||
items = sorted(cache["procs"], key=lambda x: x["conns"], reverse=True)[:60]
|
||||
tcp_list = []
|
||||
listen_list = []
|
||||
if _h_tcp is not None:
|
||||
name_by_pid = {p["pid"]: p["name"] for p in cache.get("procs", [])}
|
||||
for c in _h_tcp:
|
||||
if not c.get("name"):
|
||||
c["name"] = name_by_pid.get(c.get("pid"), "")
|
||||
tcp_list, listen_list = _h_tcp[:80], (_h_listen or [])[:80]
|
||||
for c in listen_list:
|
||||
if not c.get("name"):
|
||||
c["name"] = name_by_pid.get(c.get("pid"), "")
|
||||
else:
|
||||
try:
|
||||
name_by_pid = {p["pid"]: p["name"] for p in cache.get("procs", [])}
|
||||
for c in psutil.net_connections(kind="tcp"):
|
||||
laddr = f"{c.laddr.ip}:{c.laddr.port}" if c.laddr else ""
|
||||
raddr = f"{c.raddr.ip}:{c.raddr.port}" if c.raddr else ""
|
||||
family = "ipv6" if ":" in (c.laddr.ip if c.laddr else "") and "." not in (c.laddr.ip if c.laddr else "") else "ipv4"
|
||||
# better family detection
|
||||
import socket
|
||||
family = "ipv6" if (c.family == socket.AF_INET6) else "ipv4"
|
||||
if c.status == "LISTEN":
|
||||
listen_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": c.laddr.ip if c.laddr else "", "port": c.laddr.port if c.laddr else 0, "family": family, "pid": c.pid, "proto": "tcp"})
|
||||
else:
|
||||
tcp_list.append({"name": name_by_pid.get(c.pid, ""), "laddr": laddr, "raddr": raddr, "family": family, "pid": c.pid, "status": c.status})
|
||||
except Exception:
|
||||
pass
|
||||
tcp_list = tcp_list[:80]
|
||||
listen_list = listen_list[:80]
|
||||
return jsonify({"nics": rates, "conns": conns, "items": items,
|
||||
"hw": get_net_hw(),
|
||||
"total_recv": total_recv, "total_sent": total_sent,
|
||||
"tcp": tcp_list, "listen": listen_list})
|
||||
|
||||
_net_hw_static = {}
|
||||
|
||||
def _net_sysfs(name):
|
||||
"""实时 sysfs: 状态/MTU/速率/MAC,键名与 psutil 速率互补"""
|
||||
out = {}
|
||||
for base in ("/host/sys/class/net", "/sys/class/net"):
|
||||
d = os.path.join(base, name)
|
||||
try:
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
for k in ("address", "operstate", "mtu", "speed", "duplex",
|
||||
"carrier"):
|
||||
v = _read(os.path.join(d, k))
|
||||
if v:
|
||||
out[k] = v
|
||||
# 驱动名
|
||||
try:
|
||||
drv = os.path.basename(os.readlink(os.path.join(d, "device/driver")))
|
||||
if drv:
|
||||
out["live_driver"] = drv
|
||||
except Exception:
|
||||
pass
|
||||
if out:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
return out
|
||||
|
||||
def _net_addrs():
|
||||
try:
|
||||
ad = psutil.net_if_addrs() or {}
|
||||
except Exception:
|
||||
return {}
|
||||
out = {}
|
||||
for nic, lst in ad.items():
|
||||
v4, v6, mac = [], [], ""
|
||||
for a in lst:
|
||||
try:
|
||||
fam = a.family.name if hasattr(a.family, "name") else str(a.family)
|
||||
except Exception:
|
||||
fam = ""
|
||||
addr = a.address or ""
|
||||
if "PACKET" in fam:
|
||||
if addr:
|
||||
mac = mac or addr
|
||||
elif "AF_INET6" in fam:
|
||||
if addr and not addr.startswith("fe80"):
|
||||
v6.append(addr.split("%")[0])
|
||||
elif addr:
|
||||
v6.append(addr.split("%")[0] + "(链路)")
|
||||
elif "AF_INET" in fam:
|
||||
if addr and len(addr.split(".")) == 4:
|
||||
v4.append(addr)
|
||||
out[nic] = {"v4": v4, "v6": v6, "mac": mac}
|
||||
return out
|
||||
|
||||
def get_net_hw():
|
||||
global _net_hw_static
|
||||
if not _net_hw_static:
|
||||
hj = {}
|
||||
for jp in ("hw_net.json",
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"hw_net.json")):
|
||||
try:
|
||||
with open(jp) as f:
|
||||
hj = json.load(f)
|
||||
if hj.get("nics"):
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
_net_hw_static = hj or {"nics": []}
|
||||
statics = {x.get("name"): dict(x) for x in _net_hw_static.get("nics", [])}
|
||||
try:
|
||||
st = psutil.net_if_stats() or {}
|
||||
except Exception:
|
||||
st = {}
|
||||
addrs = _parse_ip_addr(_nsenter_run(["ip", "-o", "addr", "show"]))
|
||||
if not addrs:
|
||||
addrs = _net_addrs()
|
||||
# 展示的网卡: 静态档案 + 实际有流量的非虚拟口
|
||||
names = list(statics.keys())
|
||||
try:
|
||||
counters = _host_nic_counters()
|
||||
except Exception:
|
||||
counters = {}
|
||||
for nic in counters:
|
||||
if nic.startswith(("lo", "docker", "br-", "veth")):
|
||||
continue
|
||||
if nic not in statics:
|
||||
names.append(nic)
|
||||
out = []
|
||||
for nic in names:
|
||||
base = dict(statics.get(nic, {"name": nic}))
|
||||
s = st.get(nic)
|
||||
if s is not None:
|
||||
try:
|
||||
base["isup"] = bool(s.isup)
|
||||
base["live_speed"] = s.speed or 0
|
||||
base["live_mtu"] = s.mtu or 0
|
||||
except Exception:
|
||||
pass
|
||||
base.update(_net_sysfs(nic))
|
||||
if base.get("isup") is None and base.get("operstate"):
|
||||
base["isup"] = (str(base.get("operstate")).strip().lower() == "up")
|
||||
a = addrs.get(nic, {})
|
||||
if a:
|
||||
base["ipv4"] = a.get("v4", [])
|
||||
base["ipv6"] = a.get("v6", [])
|
||||
if a.get("mac") and not base.get("mac"):
|
||||
base["mac"] = a["mac"]
|
||||
c = counters.get(nic)
|
||||
if c is not None:
|
||||
try:
|
||||
base["io_sent"] = c.bytes_sent
|
||||
base["io_recv"] = c.bytes_recv
|
||||
except Exception:
|
||||
pass
|
||||
out.append(base)
|
||||
# 默认网关/DNS 实时读
|
||||
gw, dns = _net_hw_static.get("gateway", ""), _net_hw_static.get("dns", "")
|
||||
base_if = ""
|
||||
try:
|
||||
with open("/host/proc/net/route" if os.path.exists("/host/proc/net/route") else "/proc/net/route") as f:
|
||||
for line in f.read().splitlines()[1:]:
|
||||
f_ = line.split()
|
||||
if len(f_) > 2 and f_[1] == "00000000" and f_[7] == "00000000":
|
||||
import socket, struct
|
||||
gw = socket.inet_ntoa(struct.pack("<L", int(f_[2], 16)))
|
||||
base_if = f_[0]
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
rp = "/host/etc/resolv.conf" if os.path.exists("/host/etc/resolv.conf") else "/etc/resolv.conf"
|
||||
with open(rp) as f:
|
||||
for line in f:
|
||||
if line.startswith("nameserver"):
|
||||
dns = line.split()[1]
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return {"nics": out, "gateway": gw, "dns": dns,
|
||||
"egress": base_if,
|
||||
"snapshot": _net_hw_static.get("snapshot", ""),
|
||||
"note": _net_hw_static.get("note", "")}
|
||||
|
||||
@app.route("/api/kill", methods=["POST"])
|
||||
def api_kill():
|
||||
d = request.get_json(force=True, silent=True) or {}
|
||||
try:
|
||||
pid = int(d.get("pid", 0))
|
||||
except Exception:
|
||||
return jsonify({"ok": False, "error": "pid无效"}), 400
|
||||
if pid <= 1:
|
||||
return jsonify({"ok": False, "error": "不能结束该进程"}), 400
|
||||
try:
|
||||
os.kill(pid, signal.SIGTERM)
|
||||
return jsonify({"ok": True})
|
||||
except ProcessLookupError:
|
||||
return jsonify({"ok": False, "error": "进程已不存在"}), 404
|
||||
except PermissionError:
|
||||
return jsonify({"ok": False, "error": "无权限"}), 403
|
||||
except Exception as e:
|
||||
return jsonify({"ok": False, "error": str(e)}), 500
|
||||
|
||||
@app.route("/api/health")
|
||||
def health():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=PORT)
|
||||
@@ -0,0 +1,14 @@
|
||||
services:
|
||||
fnos-resmon:
|
||||
image: jpccr.ccs.tencentyun.com/jinghui/fnos-resmon:latest
|
||||
container_name: fnos-resmon
|
||||
network_mode: host
|
||||
pid: host
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- PORT=7031
|
||||
- PROCFS_PATH=/host/proc
|
||||
privileged: true
|
||||
volumes:
|
||||
- /proc:/host/proc:rw
|
||||
- /sys:/host/sys:ro
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 284 KiB After Width: | Height: | Size: 319 KiB |
@@ -0,0 +1 @@
|
||||
{"arrays":[{"devices":["sdc3"],"level":"raid1","lvm":"trim_43d5e563_4991_48af_89f2_514933c40b28-0","md":"md0","members":"1/1","mount":"/vol1","note":"单成员 RAID1,无冗余"},{"devices":["sda1"],"level":"raid1","lvm":"trim_3f9de466_c96d_406a_a13b_9a3d4bab6b42","md":"md1","members":"1/1","mount":"/vol3","note":"单成员 RAID1,无冗余"},{"devices":["sdb1"],"level":"raid1","lvm":"trim_a03ba591_eb54_4c55_a112_00d2903bd71c-0","md":"md3","members":"1/1","mount":"/vol2","note":"单成员 RAID1,无冗余"}],"disks":[{"cap_b":1024209543168,"form":"2.5英寸","health":"PASSED","hours":18878,"iface":"SATA 6Gb/s","model":"QUANXING S101 1TB","name":"sda","power_cycles":452,"realloc":0,"serial":"AD20221216A0101609","temp_c":40,"type":"SSD","wear":0},{"cap_b":12000138625024,"form":"3.5英寸","health":"PASSED","helium":100,"hours":4396,"iface":"SATA 6Gb/s","model":"WDC WD120EDGZ-11B1PA1","model_family":"Western Digital Ultrastar (He10/12)","name":"sdb","power_cycles":237,"realloc":0,"rpm":7200,"serial":"9MJB45YT","temp_c":37,"type":"HDD 氦气盘"},{"cap_b":512110190592,"form":"2.5英寸","health":"PASSED","hours":16661,"iface":"SATA 6Gb/s","model":"QUANXING S101 512G","name":"sdc","power_cycles":735,"realloc":0,"serial":"AC20221216A0100212","temp_c":40,"type":"SSD","wear":0}],"extra":{"mount":"/","note":"系统盘直挂分区,无 RAID/LVM","part":"sdc2"},"note":"SMART 为构建时快照,温度/通电时间随时间漂移;容量/型号/序列号为静态","snapshot":"2026-11-06"}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"dimms": [
|
||||
{
|
||||
"locator": "DIMM 0",
|
||||
"bank": "P0 CHANNEL A",
|
||||
"size_b": 8589934592,
|
||||
"size_mb": 8192,
|
||||
"type": "DDR4",
|
||||
"speed": 0,
|
||||
"cspeed": 2400,
|
||||
"maker": "A-DATA Technology",
|
||||
"serial": "3E8A0000",
|
||||
"part": ""
|
||||
},
|
||||
{
|
||||
"locator": "DIMM 0",
|
||||
"bank": "P0 CHANNEL B",
|
||||
"size_b": 17179869184,
|
||||
"size_mb": 16384,
|
||||
"type": "DDR4",
|
||||
"speed": 0,
|
||||
"cspeed": 2400,
|
||||
"maker": "Unknown",
|
||||
"serial": "22522642",
|
||||
"part": "QXD016GD4U266600"
|
||||
},
|
||||
{
|
||||
"locator": "DIMM 1",
|
||||
"bank": "P0 CHANNEL B",
|
||||
"size_b": 17179869184,
|
||||
"size_mb": 16384,
|
||||
"type": "DDR4",
|
||||
"speed": 0,
|
||||
"cspeed": 2400,
|
||||
"maker": "Unknown",
|
||||
"serial": "62805591",
|
||||
"part": "EAGET-16GB-3200"
|
||||
}
|
||||
],
|
||||
"installed": 42949672960,
|
||||
"max_cap_b": 137438953472
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"dns":"192.168.68.1","gateway":"192.168.68.1","nics":[{"driver":"r8169","model":"Realtek RTL8125 2.5GbE","name":"enp42s0","pci":"10EC:8125","role":"有线主网口(已接入 OVS,IP 挂在 enp42s0-ovs 上)"},{"driver":"mt7921e","model":"MEDIATEK MT7921K Wi-Fi 6E","name":"wlp41s0","pci":"14C3:0608","role":"无线备用(DHCP,metric 600)","ssid":"css_5G"},{"model":"EasyTier VPN 虚拟网卡","name":"tun0","role":"组网隧道"},{"model":"OVS 内部端口(与 enp42s0 同 MAC)","name":"enp42s0-ovs","role":"宿主实际出口 IP 承载口"},{"model":"Open vSwitch 数据通道","name":"ovs-system","role":"OVS datapath(DOWN 属正常)"}],"note":"型号/驱动/网关/DNS 为构建时快照;地址/状态/速率/流量为实时读取","snapshot":"2026-11-06"}
|
||||
@@ -0,0 +1,195 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>飞牛资源管理器</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
html,body{height:100%;overflow:hidden}
|
||||
body{font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;background:#fff;color:#333;font-size:14px;display:flex;flex-direction:column}
|
||||
.scrollarea{flex:1;overflow:auto;min-height:0}
|
||||
.tabs{display:flex;border-bottom:1px solid #eee;padding:0 16px}
|
||||
.tab{padding:12px 18px;cursor:pointer;color:#333;font-size:15px;position:relative}
|
||||
.tab.active{color:#20a53a}
|
||||
.tab.active:after{content:"";position:absolute;left:10px;right:10px;bottom:-1px;height:2px;background:#20a53a}
|
||||
.card{border:1px solid #eee;border-radius:4px;margin:14px 16px;display:flex;text-align:center}
|
||||
.stat{flex:1;padding:16px 8px}
|
||||
.stat+.stat{border-left:1px solid #f2f2f2}
|
||||
.stat .k{font-weight:700;margin-bottom:8px;font-size:14px}
|
||||
.stat .v{font-size:15px}
|
||||
.v.green{color:#20a53a}
|
||||
table{width:calc(100% - 32px);margin:0 16px 20px;border-collapse:collapse;font-size:13px;table-layout:fixed}
|
||||
thead th{background:#f7f7f7;color:#555;font-weight:400;text-align:left;padding:10px 8px;white-space:nowrap;overflow:hidden}
|
||||
tbody td{padding:9px 8px;border-bottom:1px solid #f2f2f2;vertical-align:top;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
tbody td.desc{max-width:340px}
|
||||
a.proc{color:#20a53a;text-decoration:none;white-space:nowrap}
|
||||
col.c-name{width:150px}col.c-num{width:90px}col.c-pid{width:80px}col.c-user{width:110px}col.c-st{width:60px}col.c-op{width:60px}
|
||||
.st-sleep{color:#ff9900}.st-run{color:#20a53a}
|
||||
.kill{color:#20a53a;cursor:pointer;background:none;border:none;font-size:13px}
|
||||
.kill:hover{text-decoration:underline}
|
||||
.bigbtn{background:linear-gradient(180deg,#1f9d55,#157347);border:none;color:#fff;font-size:18px;font-weight:700;border-radius:10px;padding:14px 28px;cursor:pointer;box-shadow:0 4px 14px rgba(31,157,85,.4);display:inline-block;margin:6px 0}
|
||||
.bigbtn:hover{filter:brightness(1.1)}
|
||||
.bigbtn:active{transform:scale(.97)}
|
||||
.num{font-variant-numeric:tabular-nums}
|
||||
.bar{height:8px;background:#f0f0f0;border-radius:4px;overflow:hidden;margin-top:6px}
|
||||
.bar>i{display:block;height:100%;background:#20a53a;border-radius:4px}
|
||||
.diskrow{margin:14px 16px;border:1px solid #eee;border-radius:4px;padding:14px 16px}
|
||||
.diskrow .t{font-weight:700;margin-bottom:6px}
|
||||
.mut{color:#999;font-size:12px}
|
||||
.toolbar{margin:0 16px 10px;color:#999;font-size:12px;display:flex;justify-content:space-between}
|
||||
button.refresh{background:#20a53a;color:#fff;border:none;border-radius:3px;padding:5px 14px;cursor:pointer}
|
||||
.cpuinfo{margin:0 16px 12px;border:1px solid #eee;border-radius:4px;padding:12px 16px;font-size:13px;line-height:1.9;color:#333}
|
||||
.cpuinfo .model{font-weight:700;font-size:14px;margin-bottom:4px}
|
||||
.cpuinfo .mut{color:#999;font-size:12px}
|
||||
.corebar{display:flex;gap:4px;margin-top:8px;flex-wrap:wrap}
|
||||
.corecell{flex:1;min-width:44px;text-align:center}
|
||||
.corecell .cb{height:8px;background:#f0f0f0;border-radius:4px;overflow:hidden}
|
||||
.corecell .cb>i{display:block;height:100%;background:#20a53a;border-radius:4px}
|
||||
.corecell .ct{font-size:11px;color:#999;margin-top:2px;font-variant-numeric:tabular-nums}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="tabs">
|
||||
<div class="tab active" data-t="cpu">CPU</div>
|
||||
<div class="tab" data-t="mem">内存</div>
|
||||
<div class="tab" data-t="disk">磁盘</div>
|
||||
<div class="tab" data-t="net">网络</div>
|
||||
<div style="margin-left:auto;display:flex;align-items:center;gap:12px;padding-right:16px;font-size:12px">
|
||||
<span style="color:#999">v1.2.8</span>
|
||||
<a href="https://nav.88531.cn" target="_blank" style="color:#20a53a;text-decoration:none">资享导航站</a>
|
||||
<a href="https://gitea.88531.cn/jinghui/fnos-resmon" target="_blank" style="color:#20a53a;text-decoration:none">开源地址</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card" id="summary"></div>
|
||||
<div class="cpuinfo" id="cpuinfo" style="display:none"></div>
|
||||
<div class="cpuinfo" id="meminfo" style="display:none"></div>
|
||||
<div class="cpuinfo" id="diskinfo" style="display:none"></div>
|
||||
<div class="cpuinfo" id="netinfo" style="display:none"></div>
|
||||
<div class="toolbar"><span id="sub"></span><span><span id="ts" style="margin-right:10px"></span><button class="refresh" onclick="load(true)">刷新</button></span></div>
|
||||
<div class="scrollarea"><table>
|
||||
<thead id="thead"></thead>
|
||||
<tbody id="tbody"></tbody>
|
||||
</table>
|
||||
<div id="disks"></div><div id="netextra"></div></div>
|
||||
<script>
|
||||
let cur='cpu';
|
||||
let sortState={key:null,dir:-1};
|
||||
let curData=null;
|
||||
document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>{document.querySelectorAll('.tab').forEach(x=>x.classList.remove('active'));t.classList.add('active');cur=t.dataset.t;document.getElementById('disks').innerHTML='';const ci=document.getElementById('cpuinfo');if(ci)ci.style.display='none';const mi2=document.getElementById('meminfo');if(mi2)mi2.style.display='none';const di=document.getElementById('diskinfo');if(di)di.style.display='none';const ni=document.getElementById('netinfo');if(ni)ni.style.display='none';load(true)});
|
||||
function fmtB(b){if(b==null)return '-';const u=['B','KB','MB','GB','TB'];let i=0;while(b>=1024&&i<4){b/=1024;i++}return b.toFixed(b>=100?0:1)+u[i]}
|
||||
function fmtR(b){return fmtB(b)+'/s'}
|
||||
function esc(s){return String(s==null?'':s).replace(/&/g,'&').replace(/</g,'<')}
|
||||
async function dropMem(){if(!confirm('一键回收未使用的内存(drop caches)?'))return;const r=await fetch('/api/mem/drop',{method:'POST'});const j=await r.json();alert(j.ok?('已回收,可用 '+fmtB(j.available)):('失败: '+j.error));load(true)}
|
||||
async function kill(pid,name){if(!confirm('结束进程 '+name+' (PID '+pid+') ?'))return;const r=await fetch('/api/kill',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({pid})});const j=await r.json();alert(j.ok?'已发送结束信号':('失败: '+j.error));load(true)}
|
||||
function cmpVal(p,key){
|
||||
if(key==='name')return String(p.name||'');
|
||||
if(key==='desc')return String(p.desc||'');
|
||||
if(key==='user')return String(p.user||'');
|
||||
if(key==='status')return String(p.status||'');
|
||||
if(key==='cpu')return Number(p.cpu||0);
|
||||
if(key==='threads')return Number(p.threads||0);
|
||||
if(key==='mem')return Number(p.mem||0);
|
||||
if(key==='rss')return Number(p.rss||0);
|
||||
if(key==='uss')return Number(p.uss||0);
|
||||
if(key==='swap')return Number(p.swap||0);
|
||||
if(key==='pid')return Number(p.pid||0);
|
||||
if(key==='io_r')return Number(p.io_r||0);
|
||||
if(key==='io_w')return Number(p.io_w||0);
|
||||
if(key==='conns')return Number(p.conns||0);
|
||||
return 0;
|
||||
}
|
||||
function renderBody(){
|
||||
const B=document.getElementById('tbody');
|
||||
if(!curData||!curData.items)return;
|
||||
let items=curData.items.slice();
|
||||
if(sortState.key){
|
||||
items.sort((a,b)=>{
|
||||
const va=cmpVal(a,sortState.key),vb=cmpVal(b,sortState.key);
|
||||
if(typeof va==='string')return sortState.dir*va.localeCompare(vb);
|
||||
return sortState.dir*(va-vb);
|
||||
});
|
||||
}
|
||||
if(cur==='cpu') B.innerHTML=items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.cpu}</td><td class="num">${p.threads}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
else if(cur==='mem') B.innerHTML=items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${fmtB(p.rss)}</td><td class="num">${fmtB(p.uss)}</td><td class="num">${fmtB(p.swap)}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
else if(cur==='disk') B.innerHTML=items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${fmtB(p.io_r)}</td><td class="num">${fmtB(p.io_w)}</td><td class="num">${p.pid}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
else if(cur==='net') B.innerHTML=items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.conns}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
}
|
||||
function arrow(k){if(sortState.key!==k)return ' ▼';return sortState.dir>0?' ▲':' ▼'}
|
||||
function renderHeader(){
|
||||
const H=document.getElementById('thead');
|
||||
if(cur==='cpu') H.innerHTML=`<tr><th onclick="sortBy('name')">进程名${arrow('name')}</th><th onclick="sortBy('cpu')">CPU使用率(%)${arrow('cpu')}</th><th onclick="sortBy('threads')">线程数${arrow('threads')}</th><th onclick="sortBy('pid')">PID${arrow('pid')}</th><th onclick="sortBy('desc')">描述${arrow('desc')}</th><th onclick="sortBy('user')">用户${arrow('user')}</th><th onclick="sortBy('status')">状态${arrow('status')}</th><th>操作</th></tr>`;
|
||||
else if(cur==='mem') H.innerHTML=`<tr><th onclick="sortBy('name')">进程名${arrow('name')}</th><th onclick="sortBy('rss')">RSS${arrow('rss')}</th><th onclick="sortBy('uss')">USS${arrow('uss')}</th><th onclick="sortBy('swap')">SWAP${arrow('swap')}</th><th onclick="sortBy('pid')">PID${arrow('pid')}</th><th onclick="sortBy('desc')">描述${arrow('desc')}</th><th onclick="sortBy('user')">用户${arrow('user')}</th><th onclick="sortBy('status')">状态${arrow('status')}</th><th>操作</th></tr>`;
|
||||
else if(cur==='disk') H.innerHTML=`<tr><th onclick="sortBy('name')">进程名${arrow('name')}</th><th onclick="sortBy('io_r')">读累计${arrow('io_r')}</th><th onclick="sortBy('io_w')">写累计${arrow('io_w')}</th><th onclick="sortBy('pid')">PID${arrow('pid')}</th><th onclick="sortBy('user')">用户${arrow('user')}</th><th onclick="sortBy('status')">状态${arrow('status')}</th><th>操作</th></tr>`;
|
||||
else if(cur==='net') H.innerHTML=`<tr><th onclick="sortBy('name')">进程名${arrow('name')}</th><th onclick="sortBy('conns')">连接数${arrow('conns')}</th><th onclick="sortBy('pid')">PID${arrow('pid')}</th><th onclick="sortBy('desc')">描述${arrow('desc')}</th><th onclick="sortBy('user')">用户${arrow('user')}</th><th onclick="sortBy('status')">状态${arrow('status')}</th><th>操作</th></tr>`;
|
||||
}
|
||||
function sortBy(key){
|
||||
if(sortState.key===key) sortState.dir*=-1; else {sortState.key=key;sortState.dir=-1;}
|
||||
renderHeader(); renderBody();
|
||||
}
|
||||
async function load(manual){
|
||||
document.getElementById('disks').innerHTML='';
|
||||
document.getElementById('netextra').innerHTML='';
|
||||
try{
|
||||
const r=await fetch('/api/'+cur,{cache:'no-store'});const j=await r.json();
|
||||
curData=j;
|
||||
document.getElementById('ts').textContent='更新于 '+new Date().toLocaleTimeString();
|
||||
const S=document.getElementById('summary'),H=document.getElementById('thead'),B=document.getElementById('tbody');
|
||||
if(cur==='cpu'){
|
||||
S.innerHTML=`<div class="stat"><div class="k">CPU占用</div><div class="v green">${j.cpu}%</div></div><div class="stat"><div class="k">活跃进程数</div><div class="v green">${j.active}</div></div><div class="stat"><div class="k">负载(1分钟,5分钟,15分钟)</div><div class="v num">${j.load.join(', ')}</div></div>`;
|
||||
const I=j.info||{},P=j.percpu||[];
|
||||
document.getElementById('cpuinfo').style.display='';
|
||||
document.getElementById('cpuinfo').innerHTML=`<div class="model">${esc(I.model||'未知CPU')} <span class="mut">${esc(I.arch||'')}</span></div><div>物理 ${I.physical||'-'} 核 / 逻辑 ${I.logical||'-'} 核 · ${I.sockets?('共 '+I.sockets+' 路 × '+I.cores_per_socket+'核 × '+I.threads_per_core+'线程'):''} · 当前 ${I.freq_cur||'-'} MHz(${I.freq_min||'-'} ~ ${I.freq_max||'-'} MHz)</div><div class="mut">L1d ${esc(I.l1d||'-')} · L1i ${esc(I.l1i||'-')} · L2 ${esc(I.l2||'-')} · L3 ${esc(I.l3||'-')}</div><div class="corebar">${P.map((v,i)=>`<div class="corecell"><div class="cb"><i style="width:${Math.min(v,100)}%"></i></div><div class="ct">#${i} ${v}%</div></div>`).join('')}</div>`;
|
||||
document.getElementById('sub').textContent=`共 ${j.total} 个进程,显示占用最高的前 ${j.items.length} 个(进程CPU为单进程占用,单核满=100%,16核满=1600%,进程之和÷16≈整机占用)`;
|
||||
renderHeader();
|
||||
B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.cpu}</td><td class="num">${p.threads}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
}else if(cur==='mem'){
|
||||
S.innerHTML=`<div class="stat"><div class="k">内存占用</div><div class="v green">${j.percent}%</div></div><div class="stat"><div class="k">已用 / 总共</div><div class="v num">${fmtB(j.used)} / ${fmtB(j.total)}</div></div><div class="stat"><div class="k">可用 / Swap</div><div class="v num">${fmtB(j.available)} / ${fmtB(j.swap_used)}/${fmtB(j.swap_total)} (Swap ${j.swap_percent||0}%)</div></div><div class="stat"><div class="k">操作</div><div class="v"><button class="bigbtn" onclick="dropMem()">🧹 一键回收未使用的内存</button></div></div>`;
|
||||
const D=j.detail||{},H2=j.hw||{},DM=H2.dimms||[];
|
||||
const row=(k,v)=>`<span style="display:inline-block;min-width:230px;margin-right:12px">${k} <b class="num">${v}</b></span>`;
|
||||
document.getElementById('meminfo').style.display='';
|
||||
document.getElementById('meminfo').innerHTML=`<div class="model">物理 ${fmtB(H2.installed||0)}(${DM.length} 条) · 系统可用 ${fmtB(H2.system_total||j.total)} · 预留 ${fmtB(H2.reserved||0)}(核显 ${fmtB(H2.vram||0)} + BIOS/PCI 保留)</div>`
|
||||
+(DM.length?`<div class="mut">槽位:</div><div>${DM.map(d=>row(esc((d.locator||'')+' / '+(d.bank||'')), esc(fmtB(d.size_b)+' '+d.type+' '+(d.cspeed||d.speed||'')+'MT/s '+(d.maker||'')+' '+(d.part||'')))).join('')}</div>`:`<div class="mut">未读到内存槽位表(DMI 不可用)</div>`)
|
||||
+`<div class="mut">占用拆解:</div><div>${row('空闲 MemFree',fmtB(D.MemFree))+row('可用 MemAvailable',fmtB(D.MemAvailable))+row('缓冲 Buffers',fmtB(D.Buffers))+row('缓存 Cached',fmtB(D.Cached))+row('Swap缓存',fmtB(D.SwapCached))+row('匿名页 AnonPages',fmtB(D.AnonPages))+row('映射 Mapped',fmtB(D.Mapped))+row('共享 Shmem',fmtB(D.Shmem))+row('Slab',fmtB(D.Slab))+row('可回收',fmtB(D.SReclaimable))+row('不可回收',fmtB(D.SUnreclaim))+row('页表',fmtB(D.PageTables))+row('内核栈',fmtB(D.KernelStack))+row('已提交',fmtB(D.Committed_AS))+row('提交上限',fmtB(D.CommitLimit))+row('脏页',fmtB(D.Dirty))}</div>`;
|
||||
document.getElementById('sub').textContent=`按内存占用排序,前 ${j.items.length} 个进程`;
|
||||
renderHeader();
|
||||
B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${fmtB(p.rss)}</td><td class="num">${fmtB(p.uss)}</td><td class="num">${fmtB(p.swap)}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
}else if(cur==='disk'){
|
||||
let tot=0,used=0;j.parts.forEach(p=>{tot+=p.total;used+=p.used});
|
||||
const pct=tot?Math.round(used/tot*100):0;
|
||||
S.innerHTML=`<div class="stat"><div class="k">磁盘占用</div><div class="v green">${pct}%</div></div><div class="stat"><div class="k">已用 / 总共</div><div class="v num">${fmtB(used)} / ${fmtB(tot)}</div></div><div class="stat"><div class="k">读 / 写累计</div><div class="v num">${fmtB(j.io.read||0)} / ${fmtB(j.io.write||0)}</div></div>`;
|
||||
document.getElementById('sub').textContent=`${j.parts.length} 个挂载点,下表按 IO 占用排序`;
|
||||
renderHeader();
|
||||
B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${fmtB(p.io_r)}</td><td class="num">${fmtB(p.io_w)}</td><td class="num">${p.pid}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
document.getElementById('disks').innerHTML=j.parts.map(p=>`<div class="diskrow"><div class="t">${esc(p.mount)} <span class="mut">${esc(p.device)} ${esc(p.fstype)}</span></div><div class="num">${fmtB(p.used)} / ${fmtB(p.total)} (${p.percent}%) · 可用 ${fmtB(p.free)}</div><div class="bar"><i style="width:${p.percent}%"></i></div></div>`).join('');
|
||||
const W=j.hw||{},DS=W.disks||[],AR=W.arrays||[],EX=W.extra||{};
|
||||
const drow=(k,v)=>`<span style="display:inline-block;min-width:250px;margin-right:12px">${k} <b class="num">${v}</b></span>`;
|
||||
document.getElementById('diskinfo').style.display='';
|
||||
document.getElementById('diskinfo').innerHTML=`<div class="model">共 ${DS.length} 块物理盘 · ${AR.length} 组阵列 <span class="mut">SMART 快照 ${esc(W.snapshot||'')}(温度/通电时间为快照值)</span></div>`
|
||||
+(DS.length?DS.map(d=>`<div style="margin-top:8px;padding-top:8px;border-top:1px dashed #eee"><div><b>/dev/${esc(d.name||'')}</b> ${esc(d.model||d.sys_model||'')} <span class="mut">${esc(d.type||'')} · ${fmtB(d.cap_b)} · ${esc(d.iface||'')}</span> <span style="color:${String(d.health||'').includes('PASSED')?'#20a53a':'#f00'}">${esc(d.health||'')}</span></div><div>${drow('序列号',esc(d.serial||'-'))+drow('温度',d.temp_c!=null?(d.temp_c+'°C 快照'):'-')+drow('通电',d.hours!=null?(Math.floor(d.hours/24)+' 天('+d.hours+' 小时)'):'-')+drow('通电次数',d.power_cycles!=null?d.power_cycles:'-')+drow('坏道重映射',d.realloc!=null?d.realloc:'-')+(d.wear!=null?drow('磨损',d.wear+'%'):'')+(d.helium!=null?drow('氦气',d.helium+'%'):'')+(d.rpm?drow('转速',d.rpm+' 转'):drow('转速',d.rotational?'机械':'固态'))+drow('尺寸',esc(d.form||'-'))+drow('读写累计',fmtB(d.io_read||0)+' / '+fmtB(d.io_write||0))}</div></div>`).join(''):`<div class="mut">未读到硬盘信息</div>`)
|
||||
+(AR.length?`<div class="mut" style="margin-top:8px">阵列拓扑(单成员 RAID1,无冗余):</div><div>${AR.map(a=>drow(esc(a.md+' → '+(a.mount||'')),esc((a.level||'')+' '+(a.members||'')+' '+(a.live_status||'')+' '+(a.live_devs||'')))).join('')+(AR.some(a=>a.live_sync)?`<div class="mut">${esc((AR.find(a=>a.live_sync)||{}).live_sync||'')}</div>`:''+(EX&&EX.mount?`<div>${drow('系统盘 '+esc(EX.mount||'/'),esc((EX.part||'')+'('+(EX.note||'')+')'))}</div>`:''))}</div>`:'')
|
||||
+((W.note)?`<div class="mut">${esc(W.note)}</div>`:'');
|
||||
}else{
|
||||
const up=j.nics.reduce((a,n)=>a+n.up,0),down=j.nics.reduce((a,n)=>a+n.down,0);
|
||||
S.innerHTML=`<div class="stat"><div class="k">上行速率</div><div class="v green">${fmtR(up)}</div></div><div class="stat"><div class="k">下行速率</div><div class="v green">${fmtR(down)}</div></div><div class="stat"><div class="k">累计接收</div><div class="v num">${fmtB(j.total_recv||0)}</div></div><div class="stat"><div class="k">累计发送</div><div class="v num">${fmtB(j.total_sent||0)}</div></div><div class="stat"><div class="k">连接数</div><div class="v num">${j.conns}</div></div>`;
|
||||
document.getElementById('sub').textContent=j.nics.map(n=>`${n.nic}: ↑${fmtR(n.up)} ↓${fmtR(n.down)}`).join(' · ')||'无网卡数据';
|
||||
renderHeader();
|
||||
B.innerHTML=j.items.map(p=>`<tr><td><a class="proc">${esc(p.name)}</a></td><td class="num">${p.conns}</td><td class="num">${p.pid}</td><td>${esc(p.desc)}</td><td>${esc(p.user)}</td><td class="${p.active?'st-run':'st-sleep'}">${p.status}</td><td><button class="kill" onclick="kill(${p.pid},'${esc(p.name)}')">结束</button></td></tr>`).join('');
|
||||
document.getElementById('netextra').innerHTML=`<h3 style="margin:12px 0 4px">TCP连接</h3><table class="t"><thead><tr><th>进程名</th><th>本地地址</th><th>远程地址</th><th>地址族</th><th>PID</th><th>状态</th></tr></thead><tbody>${(j.tcp||[]).map(c=>`<tr><td>${esc(c.name)}</td><td class="num">${esc(c.laddr)}</td><td class="num">${esc(c.raddr)}</td><td>${esc(c.family)}</td><td class="num">${c.pid||''}</td><td>${esc(c.status)}</td></tr>`).join('')}</tbody></table><h3 style="margin:12px 0 4px">侦听端口</h3><table class="t"><thead><tr><th>进程名</th><th>监听地址</th><th>端口</th><th>地址族</th><th>防火墙</th><th>PID</th><th>协议</th></tr></thead><tbody>${(j.listen||[]).map(c=>`<tr><td>${esc(c.name)}</td><td class="num">${esc(c.laddr)}</td><td class="num">${c.port}</td><td>${esc(c.family)}</td><td>不放行</td><td class="num">${c.pid||''}</td><td>${esc(c.proto)}</td></tr>`).join('')}</tbody></table>`;
|
||||
const NW=j.hw||{},NN=NW.nics||[];
|
||||
const nrow=(k,v)=>`<span style="display:inline-block;min-width:260px;margin-right:12px">${k} <b class="num">${v}</b></span>`;
|
||||
const spd=n=>(n&&+n>0?(+n>=1000?((+n/1000)+' Gb/s'):(n+' Mb/s')):'-');
|
||||
document.getElementById('netinfo').style.display='';
|
||||
document.getElementById('netinfo').innerHTML=`<div class="model">出口 ${esc(NW.egress||'-')} · 网关 ${esc(NW.gateway||'-')} · DNS ${esc(NW.dns||'-')} <span class="mut">共 ${NN.length} 块网卡(档案快照 ${esc(NW.snapshot||'')},地址/状态/速率为实时)</span></div>`
|
||||
+(NN.length?NN.map(n=>`<div style="margin-top:8px;padding-top:8px;border-top:1px dashed #eee"><div><b>${esc(n.name||'')}</b> ${esc(n.model||'')} <span class="mut">${esc(n.role||'')}</span> <span style="color:${(n.isup===false||n.operstate==='down')?'#999':'#20a53a'}">${esc(n.operstate||(n.isup===false?'down':'up'))}</span></div><div>${nrow('IPv4',esc((n.ipv4||[]).join(' / ')||'-'))+nrow('IPv6',esc((n.ipv6||[]).join(' / ')||'-'))+nrow('MAC',esc(n.address||n.mac||'-'))+nrow('协商速率',spd(n.speed||n.live_speed))+nrow('双工',esc(n.duplex||'-'))+nrow('MTU',esc(n.mtu||n.live_mtu||'-'))+nrow('驱动',esc(n.live_driver||n.driver||'-'))+(n.pci?nrow('PCI',esc(n.pci)):'')+(n.ssid?nrow('WiFi',esc(n.ssid)):'')+nrow('收发累计',fmtB(n.io_recv||0)+' / '+fmtB(n.io_sent||0))}</div></div>`).join(''):`<div class="mut">未读到网卡信息</div>`)
|
||||
+((NW.note)?`<div class="mut">${esc(NW.note)}</div>`:'');
|
||||
}
|
||||
}catch(e){if(manual)alert('加载失败: '+e)}
|
||||
}
|
||||
load(true);setInterval(()=>load(false),3000);
|
||||
</script>
|
||||
<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:6px;font-size:12px;color:#999;background:#fff;border-top:1px solid #eee;z-index:999">
|
||||
<a href="https://nav.88531.cn" target="_blank" rel="noopener">资享导航站</a> ·
|
||||
<a href="https://gitea.88531.cn/jinghui/fnos-resmon" target="_blank" rel="noopener">开源地址 (Gitea)</a>
|
||||
</footer>
|
||||
</html>
|
||||
@@ -0,0 +1,2 @@
|
||||
flask
|
||||
psutil
|
||||
Reference in new issue
Block a user