feat: 概览实时流量图表(今天/昨天/30天/12个月/查某天)
This commit is contained in:
1 parent
d153dec29d
commit
2eb235c704
5 files changed
+233
-3
No files matched your search
+140
@@ -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);
|
||||
|
||||
|
||||
Reference in new issue
Block a user