feat: 概览实时流量图表(今天/昨天/30天/12个月/查某天)

This commit is contained in:
jinghui committed 2026-10-26 18:26:52 +08:00
1 parent d153dec29d
commit 2eb235c704
5 files changed
+233 -3

No files matched your search

+10
View File
@@ -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 个)、最近事件
+1 -1
View File
@@ -52,7 +52,7 @@ bash install.sh
| 页面 | 内容 |
|---|---|
| 概览(默认) | 纯仪表盘:应用总数/异常/注意/资源/运行容器统计条、**CPU 与内存占用 Top 5**、优化建议、**需要关注的应用**(仅异常/注意,最多 6 个,卡片可直接启停)、最近事件;右上「查看全部应用」进入完整列表 |
| 概览(默认) | 纯仪表盘:应用总数/异常/注意/资源/运行容器统计条、**实时流量图表**(今天/昨天/近30天/近12个月 + 查某一天,按小时记账落盘)、**CPU 与内存占用 Top 5**、优化建议、**需要关注的应用**(仅异常/注意,最多 6 个,卡片可直接启停)、最近事件;右上「查看全部应用」进入完整列表 |
| 全部应用 | 完整应用卡片列表(50 个):筛选(全部·有问题·已停止·高占用)、排序、状态胶囊、CPU/内存/网络、端口、已运行时长、可用率、重启次数、卡片内启停与详情;顶部可返回概览 |
| 应用详情 | 应用级指标 + 全部容器表格(状态/健康/CPU/内存/网络/重启/运行时长/单容器操作)+ 三个标签页:容器、聚合日志(多容器合并、按容器名加前缀)、事件;顶部可整应用启停重启 |
| 容器 | 只列运行中容器,可排序(CPU/内存/网络/磁盘IO/进程数/名称)、搜索;行内启停/重启/删除/详情/打开端口 |
+62 -2
View File
@@ -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 `<span class="avatar" style="background:${color}">${esc(label)}</span>`;
}
/* ---------------- 流量图表 ---------------- */
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 `<svg class="tf-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none">
<defs><linearGradient id="tfGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#1a73e8" stop-opacity=".28"/><stop offset="100%" stop-color="#1a73e8" stop-opacity="0"/>
</linearGradient></defs>
${gridY.map(y => `<line x1="${PL}" y1="${y.toFixed(1)}" x2="${PL + iw}" y2="${y.toFixed(1)}" stroke="#eef2f7" stroke-width="1"/>`).join('')}
<polygon points="${areaRx}" fill="url(#tfGrad)"/>
<polyline points="${line('rx')}" fill="none" stroke="#1a73e8" stroke-width="1.8" stroke-linejoin="round"/>
<polyline points="${line('tx')}" fill="none" stroke="#f79009" stroke-width="1.5" stroke-dasharray="3 3" stroke-linejoin="round"/>
${ticks.map(({ i, l }) => `<text x="${xAt(i).toFixed(1)}" y="${H - 6}" font-size="9" fill="#93a0b4" text-anchor="middle">${esc(l)}</text>`).join('')}
<text x="${PL}" y="${PT - 2}" font-size="9" fill="#93a0b4">峰值 ${fmtBytes(max)}</text>
</svg>`;
}
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) {
<div class="app-grid">${cards || '<div class="empty">没有匹配的应用</div>'}</div>`;
$('#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 = `
<div class="traffic-box">
<div class="traffic-head">
<b>实时流量</b>
<span class="tf-now">↓ ${fmtRate(tfNow.rx)} · ↑ ${fmtRate(tfNow.tx)}</span>
<div class="tf-tabs">
${tfTabs.map(([k, l]) => `<button class="tf-tab ${state.traffic.range === k ? 'on' : ''}" data-tr="${k}">${l}</button>`).join('')}
<input type="date" id="tfDate" class="tf-date" value="${state.traffic.range === 'day' ? esc(state.traffic.date) : ''}" title="查某一天的流量">
</div>
</div>
<div class="tf-sum">
<span>总流量 <b>${fmtBytes(tfTotal.rx + tfTotal.tx)}</b></span>
<span>下行 <b class="down">${fmtBytes(tfTotal.rx)}</b></span>
<span>上行 <b class="up">${fmtBytes(tfTotal.tx)}</b></span>
<span class="muted">${tf ? esc(tf.label) : ''}${tf && tf.coverage && tf.coverage.from ? ` · 自 ${esc(tf.coverage.from)} 开始记录` : ''}</span>
</div>
${tfPts.length ? tfChart(tfPts, tf.unit) : '<div class="empty sm">暂无流量数据</div>'}
<div class="tf-legend"><span class="lg down"></span>下行(蓝实线)<span class="lg up"></span>上行(橙虚线)</div>
</div>`;
$('#view').innerHTML = `
<div class="stat-strip">
<div class="s-card"><div class="k">应用总数</div><div class="v">${s.total}</div><div class="s">${s.containers} 个容器</div></div>
@@ -270,6 +323,7 @@ async function renderApps(silent) {
<div class="s-card"><div class="k">运行容器</div><div class="v">${h.running}<span class="muted" style="font-size:12px">/${h.containers}</span></div><div class="s">镜像 ${h.images} 个</div></div>
</div>
${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(); };
+20
View File
@@ -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}
+140
View File
@@ -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);