From 2eb235c704e15dba9b4f73d69efad485a0382349 Mon Sep 17 00:00:00 2001
From: jinghui <181050043@qq.com>
Date: Mon, 26 Oct 2026 18:26:52 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A6=82=E8=A7=88=E5=AE=9E=E6=97=B6?=
=?UTF-8?q?=E6=B5=81=E9=87=8F=E5=9B=BE=E8=A1=A8=EF=BC=88=E4=BB=8A=E5=A4=A9?=
=?UTF-8?q?/=E6=98=A8=E5=A4=A9/30=E5=A4=A9/12=E4=B8=AA=E6=9C=88/=E6=9F=A5?=
=?UTF-8?q?=E6=9F=90=E5=A4=A9=EF=BC=89?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
CHANGELOG.md | 10 ++++
README.md | 2 +-
public/app.js | 64 +++++++++++++++++++++-
public/style.css | 20 +++++++
server/index.js | 140 +++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 233 insertions(+), 3 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f53b7b..a29a6b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# 更新日志
+## 2026-10-26 → ✨ 概览新增实时流量图表(今天/昨天/30 天/12 个月/查某天)
+
+- ✨ 按小时记账:每 3 秒采样把各容器网络计数器差量累加到当天小时桶,15 秒落盘 `data/traffic/YYYY-MM-DD.json`,重启不丢
+- ✨ 概览页新增「实时流量」卡片:当前上下行速率、总流量(下行/上行)、折线面积图(蓝实线=下行,橙虚线=上行)
+- ✨ 四个口径 + 日期查询:今天 / 昨天 / 近 30 天 / 近 12 个月,另可用日期选择器查任意一天
+- ✨ 图表纯 SVG 手写(无第三方库),自适应宽度、按峰值缩放、x 轴自适应刻度
+- 🔧 流量统计用**累计计数器差值**(`rx/tx` 差量),不用「速率×间隔」,避免采样抖动放大总量;容器重启计数器归零时自动跳过
+- 🔧 `/api/host` 增加 build、`/api/traffic` 返回 coverage(从哪天开始记录),前端标注「自 YYYY-MM-DD 开始记录」
+- ✅ 核对:本机 API 增量 3.37MB / docker stats 增量 3.10MB(比值 1.09)
+
## 2026-10-26 → 🔧 概览页改为纯仪表盘,不再铺全部应用
- 🔧 概览页只保留:统计条、CPU/内存 Top 5、优化建议、**需要关注的应用**(仅异常/注意,最多 6 个)、最近事件
diff --git a/README.md b/README.md
index 65446a0..7f50279 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ bash install.sh
| 页面 | 内容 |
|---|---|
-| 概览(默认) | 纯仪表盘:应用总数/异常/注意/资源/运行容器统计条、**CPU 与内存占用 Top 5**、优化建议、**需要关注的应用**(仅异常/注意,最多 6 个,卡片可直接启停)、最近事件;右上「查看全部应用」进入完整列表 |
+| 概览(默认) | 纯仪表盘:应用总数/异常/注意/资源/运行容器统计条、**实时流量图表**(今天/昨天/近30天/近12个月 + 查某一天,按小时记账落盘)、**CPU 与内存占用 Top 5**、优化建议、**需要关注的应用**(仅异常/注意,最多 6 个,卡片可直接启停)、最近事件;右上「查看全部应用」进入完整列表 |
| 全部应用 | 完整应用卡片列表(50 个):筛选(全部·有问题·已停止·高占用)、排序、状态胶囊、CPU/内存/网络、端口、已运行时长、可用率、重启次数、卡片内启停与详情;顶部可返回概览 |
| 应用详情 | 应用级指标 + 全部容器表格(状态/健康/CPU/内存/网络/重启/运行时长/单容器操作)+ 三个标签页:容器、聚合日志(多容器合并、按容器名加前缀)、事件;顶部可整应用启停重启 |
| 容器 | 只列运行中容器,可排序(CPU/内存/网络/磁盘IO/进程数/名称)、搜索;行内启停/重启/删除/详情/打开端口 |
diff --git a/public/app.js b/public/app.js
index a4b6d19..838ad9f 100644
--- a/public/app.js
+++ b/public/app.js
@@ -4,7 +4,7 @@
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
let serverBuild = null;
-const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false };
+const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false, traffic: { range: 'today', date: '' } };
const REFRESH_KEY = 'dc.refreshMs';
state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000));
@@ -145,14 +145,44 @@ function avatar(name) {
return `${esc(label)}`;
}
+/* ---------------- 流量图表 ---------------- */
+function tfChart(points, unit) {
+ const W = 640, H = 150, PL = 6, PR = 6, PT = 12, PB = 22;
+ const iw = W - PL - PR, ih = H - PT - PB;
+ const n = Math.max(points.length, 2);
+ const maxRx = Math.max(...points.map(p => p.rx || 0), 1);
+ const maxTx = Math.max(...points.map(p => p.tx || 0), 1);
+ const max = Math.max(maxRx, maxTx);
+ const xAt = (i) => PL + (iw * i) / (n - 1);
+ const yAt = (v) => PT + ih - (v / max) * ih;
+ const line = (key) => points.map((p, i) => `${xAt(i).toFixed(1)},${yAt(p[key] || 0).toFixed(1)}`).join(' ');
+ const areaRx = `${PL},${PT + ih} ${line('rx')} ${PL + iw},${PT + ih}`;
+ const step = unit === 'hour' ? 4 : unit === 'day' ? 5 : 1;
+ const ticks = points.map((p, i) => ({ i, l: p.label }))
+ .filter(({ i }) => unit === 'hour' ? i % 4 === 0 : unit === 'day' ? i % 5 === 0 : true);
+ const gridY = [0, 0.5, 1].map(f => PT + ih * f);
+ return ``;
+}
+
async function renderApps(silent) {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
- const [data, h, ev, ins, full] = await Promise.all([
+ const [data, h, ev, ins, full, tf] = await Promise.all([
api(`/api/apps?filter=${state.filter}&sort=${state.sort}&order=${state.order}${q}`),
refreshHost(),
api('/api/events?limit=8'),
api('/api/insights').catch(() => null),
api('/api/apps?sort=cpu&order=desc').catch(() => null),
+ (state.view === 'apps' ? api(`/api/traffic?range=${state.traffic.range}${state.traffic.date && state.traffic.range === 'day' ? `&date=${state.traffic.date}` : ''}`).catch(() => null) : Promise.resolve(null)),
]);
const s = data.summary;
const disk = h.disk;
@@ -261,6 +291,29 @@ async function renderApps(silent) {
`;
$('#backOverview').onclick = () => go('apps');
} else {
+ const tfPts = (tf && tf.points) || [];
+ const tfTotal = (tf && tf.total) || { rx: 0, tx: 0 };
+ const tfNow = (tf && tf.now) || { rx: 0, tx: 0 };
+ const tfTabs = [['today', '今天'], ['yesterday', '昨天'], ['month', '近 30 天'], ['year', '近 12 个月']];
+ const tfHtml = `
+
+
+
实时流量
+
↓ ${fmtRate(tfNow.rx)} · ↑ ${fmtRate(tfNow.tx)}
+
+ ${tfTabs.map(([k, l]) => ``).join('')}
+
+
+
+
+ 总流量 ${fmtBytes(tfTotal.rx + tfTotal.tx)}
+ 下行 ${fmtBytes(tfTotal.rx)}
+ 上行 ${fmtBytes(tfTotal.tx)}
+ ${tf ? esc(tf.label) : ''}${tf && tf.coverage && tf.coverage.from ? ` · 自 ${esc(tf.coverage.from)} 开始记录` : ''}
+
+ ${tfPts.length ? tfChart(tfPts, tf.unit) : '
暂无流量数据
'}
+
下行(蓝实线)上行(橙虚线)
+
`;
$('#view').innerHTML = `
应用总数
${s.total}
${s.containers} 个容器
@@ -270,6 +323,7 @@ async function renderApps(silent) {
运行容器
${h.running}/${h.containers}
镜像 ${h.images} 个
+ ${tfHtml}
${topHtml}
${insHtml}
@@ -285,6 +339,12 @@ async function renderApps(silent) {
}
$$('#view .chip').forEach(b => b.onclick = () => { state.filter = b.dataset.filter; render(); });
+ $$('#view .tf-tab').forEach(b => b.onclick = () => { state.traffic.range = b.dataset.tr; state.traffic.date = ''; render(); });
+ const tfDate = $('#tfDate');
+ if (tfDate) tfDate.onchange = () => {
+ if (!tfDate.value) return;
+ state.traffic.range = 'day'; state.traffic.date = tfDate.value; render();
+ };
$$('#view .top-row').forEach(r => r.onclick = () => openApp(r.dataset.top));
const moreBtn = $('#insightMore');
if (moreBtn) moreBtn.onclick = () => { state.insightOpen = !state.insightOpen; render(); };
diff --git a/public/style.css b/public/style.css
index 1f51f00..b329d55 100644
--- a/public/style.css
+++ b/public/style.css
@@ -288,3 +288,23 @@ table.tb th.num{text-align:right}
.tbar.mem i{background:#7a5af8}
.empty.sm{padding:16px;font-size:12px;text-align:center;color:#8b95a5}
.empty.ok-empty{padding:22px;text-align:center;color:#12a15f;background:#f3fbf6;border:1px dashed #cdebd9;border-radius:12px;font-size:13px}
+
+/* 流量卡片 */
+.traffic-box{background:var(--panel);border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow);margin-bottom:14px;padding:12px 14px 8px}
+.traffic-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
+.traffic-head b{font-size:13.5px;color:#26303f}
+.tf-now{font-size:12px;color:#3d4859;font-weight:600;font-variant-numeric:tabular-nums}
+.tf-tabs{margin-left:auto;display:flex;align-items:center;gap:5px;flex-wrap:wrap}
+.tf-tab{font:inherit;font-size:12px;padding:3px 9px;border-radius:7px;border:1px solid var(--line);background:#fbfcfe;color:#5b6a85;cursor:pointer}
+.tf-tab:hover{background:#f2f6fd}
+.tf-tab.on{background:#eaf1fd;border-color:#bcd4f7;color:#1a5fd0;font-weight:600}
+.tf-date{font:inherit;font-size:12px;padding:2px 6px;border:1px solid var(--line);border-radius:7px;color:#5b6a85;background:#fbfcfe}
+.tf-sum{display:flex;gap:16px;flex-wrap:wrap;align-items:baseline;margin:8px 0 2px;font-size:12px;color:#78839a}
+.tf-sum b{color:#26303f;font-size:13px}
+.tf-sum b.down{color:#1a73e8}
+.tf-sum b.up{color:#f79009}
+.tf-chart{width:100%;height:150px;display:block;margin-top:4px}
+.tf-legend{display:flex;align-items:center;gap:6px;font-size:11.5px;color:#78839a;margin:2px 0 4px}
+.tf-legend .lg{width:14px;height:3px;border-radius:2px;display:inline-block}
+.tf-legend .lg.down{background:#1a73e8}
+.tf-legend .lg.up{background:#f79009}
diff --git a/server/index.js b/server/index.js
index d0c6ad3..66175af 100644
--- a/server/index.js
+++ b/server/index.js
@@ -20,6 +20,7 @@ const UPTIME_MAX = 1440;
const EVENT_MAX = 400;
const SETTINGS_PATH = process.env.SETTINGS_PATH || '/data/settings.json';
const COMPOSE_ROOT = process.env.COMPOSE_ROOT || '/host/vol1/1000/HD1/docker';
+const TRAFFIC_DIR = process.env.TRAFFIC_DIR || '/data/traffic';
// 每次进程启动生成新版本号:前端发现版本变化会自动刷新页面
const BUILD_ID = process.env.BUILD_ID || String(Date.now());
@@ -94,9 +95,62 @@ const appKeyOf = (c) => {
};
/* ---------------- 采样 ---------------- */
+/* ---------------- 流量账本(按小时落盘) ---------------- */
+const trafficDays = new Map(); // 'YYYY-MM-DD' -> { date, hours:[{rx,tx}] }
+let trafficDay = null; // 当天(可变)
+let trafficDirty = false;
+const rtTraffic = []; // 实时序列(最近 120 个采样)
+
+const localYmd = (d = new Date(), offsetDays = 0) => {
+ const t = new Date(d.getTime() + 8 * 3600e3 + offsetDays * 86400e3);
+ return t.toISOString().slice(0, 10);
+};
+const emptyHours = () => Array.from({ length: 24 }, () => ({ rx: 0, tx: 0 }));
+
+async function loadTrafficDay(date) {
+ if (trafficDays.has(date)) return trafficDays.get(date);
+ let data = { date, hours: emptyHours() };
+ try {
+ const raw = await fsp.readFile(path.join(TRAFFIC_DIR, `${date}.json`), 'utf8');
+ const j = JSON.parse(raw);
+ if (j && Array.isArray(j.hours)) {
+ for (let i = 0; i < 24; i++) data.hours[i] = { rx: j.hours[i]?.rx || 0, tx: j.hours[i]?.tx || 0 };
+ }
+ } catch (e) {}
+ if (date !== localYmd()) trafficDays.set(date, data); // 历史天可长缓存
+ return data;
+}
+
+async function trafficToday() {
+ const key = localYmd();
+ if (!trafficDay || trafficDay.date !== key) {
+ trafficDay = await loadTrafficDay(key);
+ trafficDay.date = key;
+ }
+ return trafficDay;
+}
+
+function addTraffic(rxBytes, txBytes) {
+ if (!trafficDay) return;
+ const h = new Date().getHours();
+ const b = trafficDay.hours[h];
+ b.rx += Math.max(0, rxBytes); b.tx += Math.max(0, txBytes);
+ trafficDirty = true;
+}
+
+async function flushTraffic() {
+ if (!trafficDirty || !trafficDay) return;
+ try {
+ await fsp.mkdir(TRAFFIC_DIR, { recursive: true });
+ await fsp.writeFile(path.join(TRAFFIC_DIR, `${trafficDay.date}.json`), JSON.stringify(trafficDay));
+ trafficDirty = false;
+ } catch (e) {}
+}
+
function computeUsage(id, s) {
const prev = stats.get(id);
const now = Date.now();
+
const c = s.cpu_stats || {}, pc = s.precpu_stats || {};
const cpuDelta = (c.cpu_usage?.total_usage || 0) - (pc.cpu_usage?.total_usage || 0);
const sysDelta = (c.system_cpu_usage || 0) - (pc.system_cpu_usage || 0);
@@ -120,6 +174,9 @@ function computeUsage(id, s) {
rx, tx, rxBps: rate(rx, prev?.rx), txBps: rate(tx, prev?.tx),
rd, wr, rdBps: rate(rd, prev?.rd), wrBps: rate(wr, prev?.wr),
pids: s.pids_stats?.current || 0,
+ // 字节差量:用于流量账本,避免用「速率×间隔」累加带来的抖动
+ dRx: prev && rx >= (prev.rx || 0) ? rx - prev.rx : 0,
+ dTx: prev && tx >= (prev.tx || 0) ? tx - prev.tx : 0,
};
stats.set(id, out);
let h = history.get(id); if (!h) { h = []; history.set(id, h); }
@@ -136,6 +193,18 @@ async function sampleOnce() {
await Promise.all(list.map(async c => {
try { computeUsage(c.Id, await docker.getContainer(c.Id).stats({ stream: false })); } catch (e) {}
}));
+ // 汇总所有运行中容器的流量增量,记入小时账本
+ await trafficToday();
+ let sumRx = 0, sumTx = 0;
+ for (const st of stats.values()) {
+ sumRx += st.dRx || 0;
+ sumTx += st.dTx || 0;
+ }
+ addTraffic(sumRx, sumTx);
+ const rxNow = [...stats.values()].reduce((a, x) => a + (x.rxBps || 0), 0);
+ const txNow = [...stats.values()].reduce((a, x) => a + (x.txBps || 0), 0);
+ rtTraffic.push({ t: Date.now(), rx: rxNow, tx: txNow });
+ if (rtTraffic.length > 120) rtTraffic.shift();
lastError = '';
} catch (e) { lastError = e.message; }
}
@@ -442,6 +511,75 @@ app.get('/api/events', (req, res) => {
res.json({ items: events.slice(0, limit) });
});
+/* ---------------- 接口:流量统计 ---------------- */
+let coverageCache = { at: 0, from: null, days: 0 };
+
+async function trafficCoverage() {
+ if (Date.now() - coverageCache.at < 120000) return coverageCache;
+ let files = [];
+ try { files = await fsp.readdir(TRAFFIC_DIR); } catch (e) {}
+ const days = files.filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).map(f => f.slice(0, 10)).sort();
+ coverageCache = { at: Date.now(), from: days[0] || null, days: days.length };
+ return coverageCache;
+}
+
+app.get('/api/traffic', async (req, res) => {
+ try {
+ const range = String(req.query.range || 'today');
+ const today = localYmd();
+ const sum = (arr, k) => arr.reduce((s, x) => s + (x[k] || 0), 0);
+ let points = [], label = '', unit = 'hour', from = today, to = today;
+
+ if (range === 'today' || range === 'yesterday' || range === 'day') {
+ const date = range === 'day'
+ ? String(req.query.date || today)
+ : range === 'yesterday' ? localYmd(new Date(), -1) : today;
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return res.status(400).json({ error: '日期格式应为 YYYY-MM-DD' });
+ const day = date === today ? await trafficToday() : await loadTrafficDay(date);
+ points = day.hours.map((b, i) => ({ label: `${String(i).padStart(2, '0')}:00`, rx: b.rx, tx: b.tx }));
+ label = range === 'today' ? '今天' : range === 'yesterday' ? '昨天' : date;
+ from = to = date;
+ } else if (range === 'month') {
+ for (let i = 29; i >= 0; i--) {
+ const d = localYmd(new Date(), -i);
+ const day = d === today ? await trafficToday() : await loadTrafficDay(d);
+ points.push({ label: d.slice(5), date: d, rx: sum(day.hours, 'rx'), tx: sum(day.hours, 'tx') });
+ }
+ label = '近 30 天'; unit = 'day'; from = localYmd(new Date(), -29);
+ } else if (range === 'year') {
+ const now = new Date();
+ const base = new Date(now.getTime() + 8 * 3600e3);
+ for (let i = 11; i >= 0; i--) {
+ const m = new Date(Date.UTC(base.getUTCFullYear(), base.getUTCMonth() - i, 1));
+ const y = m.getUTCFullYear(), mo = m.getUTCMonth() + 1;
+ const daysInMonth = new Date(Date.UTC(y, mo, 0)).getUTCDate();
+ let rx = 0, tx = 0;
+ for (let d = 1; d <= daysInMonth; d++) {
+ const key = `${y}-${String(mo).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
+ if (key > today) break;
+ const day = key === today ? await trafficToday() : await loadTrafficDay(key);
+ rx += sum(day.hours, 'rx'); tx += sum(day.hours, 'tx');
+ }
+ points.push({ label: `${String(mo).padStart(2, '0')}月`, month: `${y}-${String(mo).padStart(2, '0')}`, rx, tx });
+ }
+ label = '近 12 个月'; unit = 'month'; from = localYmd(new Date(), -364);
+ } else {
+ return res.status(400).json({ error: 'range 只能是 today / yesterday / day / month / year' });
+ }
+
+ const cov = await trafficCoverage();
+ const nowRx = rtTraffic.length ? rtTraffic[rtTraffic.length - 1].rx : 0;
+ const nowTx = rtTraffic.length ? rtTraffic[rtTraffic.length - 1].tx : 0;
+ res.json({
+ range, label, unit, from, to, points,
+ total: { rx: sum(points, 'rx'), tx: sum(points, 'tx') },
+ now: { rx: nowRx, tx: nowTx },
+ realtime: rtTraffic.slice(-120),
+ coverage: { from: cov.from, days: cov.days, today },
+ });
+ } catch (e) { res.status(500).json({ error: e.message }); }
+});
+
/* ---------------- 接口:有镜像但未启动的应用 ---------------- */
let pendingCache = { at: 0, items: [] };
const normRef = (r) => {
@@ -882,6 +1020,8 @@ app.get('/api/networks', async (req, res) => {
setInterval(sampleOnce, SAMPLE_MS);
setInterval(tickApps, SAMPLE_MS);
setInterval(inspectAll, INSPECT_MS);
+setInterval(flushTraffic, 15000);
+process.on('SIGTERM', () => { flushTraffic().finally(() => process.exit(0)); });
setInterval(tickUptime, UPTIME_MS);
setTimeout(() => { sampleOnce(); inspectAll(); tickApps(); }, 300);