飞牛docker容器管理增强版 v3:应用看板 / 优化建议 / 未启动应用 / 一键安装

This commit is contained in:
jinghui committed 2026-10-26 17:46:32 +08:00
commit aeb7f91502
11 files changed
+2404

No files matched your search

+882
View File
@@ -0,0 +1,882 @@
'use strict';
/* 飞牛docker容器管理增强版 — 面向多应用用户的管理与监控 */
const express = require('express');
const Docker = require('dockerode');
const fs = require('fs');
const fsp = require('fs/promises');
const path = require('path');
const os = require('os');
const { PassThrough } = require('stream');
const { execFile } = require('child_process');
const docker = new Docker({ socketPath: process.env.DOCKER_SOCK || '/var/run/docker.sock' });
const app = express();
const PORT = Number(process.env.PORT || 7030);
const SAMPLE_MS = Number(process.env.SAMPLE_MS || 3000);
const INSPECT_MS = Number(process.env.INSPECT_MS || 15000);
const UPTIME_MS = Number(process.env.UPTIME_MS || 60000);
const HISTORY_MAX = 240;
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';
app.use(express.json({ limit: '1mb' }));
app.use(express.static(path.join(__dirname, '..', 'public')));
/* ---------------- 设置 ---------------- */
const DEFAULT_SETTINGS = {
thresholds: { cpu: 85, mem: 90, diskFreePct: 10 }, // cpu 为占整机核数比(%), mem 为容器内存上限占比(%)
webhook: '',
notify: true,
debounceMinutes: 10,
};
let settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
try {
if (fs.existsSync(SETTINGS_PATH)) {
const saved = JSON.parse(fs.readFileSync(SETTINGS_PATH, 'utf8'));
settings = { ...settings, ...saved, thresholds: { ...settings.thresholds, ...(saved.thresholds || {}) } };
}
} catch (e) { console.error('[settings] 读取失败', e.message); }
function saveSettings() {
try {
fs.mkdirSync(path.dirname(SETTINGS_PATH), { recursive: true });
fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
} catch (e) { console.error('[settings] 写入失败', e.message); }
}
/* ---------------- 内存状态 ---------------- */
const stats = new Map(); // containerId -> 采样
const history = new Map(); // containerId -> [{t,c,m,rx,tx}]
const meta = new Map(); // containerId -> {state,health,restarts,startedAt,exitCode,restartPolicy,memLimitCfg,privileged,user,healthcheck,dockerSock,inspected}
const events = []; // {t,level,appKey,title,detail}
const appState = new Map(); // appKey -> {severity,uptime[],lastNotifyAt,since}
const restartsSeen = new Map();
let lastError = '';
let dfCache = { at: 0, data: null };
/* ---------------- 工具 ---------------- */
const strip = (n) => (n || '').replace(/^\//, '');
// 容器内的 os.hostname() 是容器 ID,推送里要用真实宿主机名
function hostName() {
try {
const h = fs.readFileSync('/host/etc/hostname', 'utf8').trim();
if (h) return h;
} catch (e) {}
return os.hostname();
}
function demuxLogs(buf) {
if (!Buffer.isBuffer(buf)) return String(buf || '');
const mux = buf.length > 8 && buf[0] <= 2 && buf[1] === 0 && buf[2] === 0 && buf[3] === 0;
if (!mux) return buf.toString('utf8');
const parts = [];
let i = 0;
while (i + 8 <= buf.length) {
const size = buf.readUInt32BE(i + 4);
const start = i + 8;
if (start + size > buf.length) { parts.push(buf.slice(start)); break; }
parts.push(buf.slice(start, start + size));
i = start + size;
}
return Buffer.concat(parts).toString('utf8');
}
const projectOf = (labels) => (labels && labels['com.docker.compose.project']) || '';
const svcOf = (labels) => (labels && labels['com.docker.compose.service']) || '';
const appKeyOf = (c) => {
const p = projectOf(c.Labels);
return p ? `compose:${p}` : `solo:${strip((c.Names || [])[0])}`;
};
/* ---------------- 采样 ---------------- */
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);
const cores = c.online_cpus || os.cpus().length || 1;
let cpu = 0;
if (cpuDelta > 0 && sysDelta > 0) cpu = (cpuDelta / sysDelta) * cores * 100;
const ms = s.memory_stats || {};
const cache = ms.stats?.inactive_file ?? ms.stats?.cache ?? 0;
const mem = Math.max(0, (ms.usage || 0) - cache);
const memLimit = ms.limit && ms.limit < 9e15 ? ms.limit : os.totalmem();
let rx = 0, tx = 0;
for (const n of Object.values(s.networks || {})) { rx += n.rx_bytes || 0; tx += n.tx_bytes || 0; }
let rd = 0, wr = 0;
for (const b of (s.blkio_stats?.io_service_bytes_recursive || [])) {
if (b.op === 'read') rd += b.value; else if (b.op === 'write') wr += b.value;
}
const dt = prev ? Math.max(0.5, (now - prev.ts) / 1000) : 0;
const rate = (cur, old) => (prev && dt > 0 ? Math.max(0, (cur - (old || 0)) / dt) : 0);
const out = {
ts: now, cpu: +cpu.toFixed(2), mem, memLimit, memPct: memLimit ? +(mem / memLimit * 100).toFixed(2) : 0,
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,
};
stats.set(id, out);
let h = history.get(id); if (!h) { h = []; history.set(id, h); }
h.push({ t: out.ts, c: out.cpu, m: out.mem, rx: out.rxBps, tx: out.txBps });
if (h.length > HISTORY_MAX) h.shift();
return out;
}
async function sampleOnce() {
try {
const list = await docker.listContainers({ all: false });
const alive = new Set(list.map(c => c.Id));
for (const id of [...stats.keys()]) if (!alive.has(id)) { stats.delete(id); history.delete(id); }
await Promise.all(list.map(async c => {
try { computeUsage(c.Id, await docker.getContainer(c.Id).stats({ stream: false })); } catch (e) {}
}));
lastError = '';
} catch (e) { lastError = e.message; }
}
/* 重启次数 / 健康状态:15 秒刷一次,避免每次采样都 inspect */
async function inspectAll() {
try {
const list = await docker.listContainers({ all: true });
for (const c of list) {
const old = meta.get(c.Id) || {};
const next = {
state: c.State, restarts: old.restarts || 0, health: old.health || '',
startedAt: old.startedAt || '', exitCode: old.exitCode ?? 0,
restartPolicy: old.restartPolicy || '', memLimitCfg: old.memLimitCfg || 0,
privileged: !!old.privileged, user: old.user || '', healthcheck: !!old.healthcheck,
dockerSock: !!old.dockerSock, inspected: !!old.inspected,
};
meta.set(c.Id, next);
const changed = old.state !== c.State;
if (c.State === 'running' || changed || !old.inspected) {
try {
const d = await docker.getContainer(c.Id).inspect();
next.restarts = d.RestartCount || 0;
next.health = d.State?.Health?.Status || '';
next.startedAt = d.State?.StartedAt || '';
next.exitCode = d.State?.ExitCode ?? 0;
next.restartPolicy = d.HostConfig?.RestartPolicy?.Name || 'no';
next.memLimitCfg = d.HostConfig?.Memory || 0;
next.privileged = !!d.HostConfig?.Privileged;
next.user = d.Config?.User || '';
next.healthcheck = !!(d.Config?.Healthcheck && (d.Config.Healthcheck.Test || []).length);
next.dockerSock = (d.Mounts || []).some(m => String(m.Source || '').includes('docker.sock'));
next.inspected = true;
const seen = restartsSeen.get(c.Id);
if (seen !== undefined && next.restarts > seen) {
pushEvent('warning', appKeyOf(c), `${strip((c.Names || [])[0])} 发生重启`, `重启次数 ${seen} → ${next.restarts}`);
}
restartsSeen.set(c.Id, next.restarts);
} catch (e) {}
}
}
} catch (e) { lastError = e.message; }
}
/* ---------------- 应用聚合与健康 ---------------- */
function buildApps(containers) {
const map = new Map();
for (const c of containers) {
const key = appKeyOf(c);
if (!map.has(key)) {
map.set(key, {
key, name: projectOf(c.Labels) || strip((c.Names || [])[0]),
type: projectOf(c.Labels) ? 'compose' : 'solo',
containers: [], cpu: 0, mem: 0, rxBps: 0, txBps: 0, memPctMax: 0,
running: 0, total: 0, ports: [], issues: [], restarts: 0, startedAt: null,
});
}
const a = map.get(key);
const st = stats.get(c.Id) || {};
const m = meta.get(c.Id) || {};
a.containers.push({
id: c.Id, name: strip((c.Names || [])[0]), service: svcOf(c.Labels),
image: c.Image, state: c.State, status: c.Status,
health: m.health || '', restarts: m.restarts || 0, startedAt: m.startedAt || '', exitCode: m.exitCode ?? 0,
restartPolicy: m.restartPolicy || '', memLimitCfg: m.memLimitCfg || 0,
privileged: !!m.privileged, healthcheck: !!m.healthcheck, dockerSock: !!m.dockerSock,
ports: (c.Ports || []).filter(pp => pp.PublicPort).length,
runMs: c.State === 'running' && m.startedAt ? Math.max(0, Date.now() - Date.parse(m.startedAt)) : null,
stats: {
cpu: st.cpu ?? 0, mem: st.mem ?? 0, memPct: st.memPct ?? 0,
rxBps: st.rxBps ?? 0, txBps: st.txBps ?? 0, rdBps: st.rdBps ?? 0, wrBps: st.wrBps ?? 0, pids: st.pids ?? 0,
},
});
a.total++;
if (c.State === 'running') a.running++;
a.cpu += st.cpu || 0;
a.mem += st.mem || 0;
a.rxBps += st.rxBps || 0;
a.txBps += st.txBps || 0;
a.memPctMax = Math.max(a.memPctMax, st.memPct || 0);
a.restarts += m.restarts || 0;
for (const p of (c.Ports || [])) if (p.PublicPort) a.ports.push({ public: p.PublicPort, private: p.PrivatePort, type: p.Type });
if (c.State === 'running' && m.startedAt && (!a.startedAt || m.startedAt < a.startedAt)) a.startedAt = m.startedAt;
}
const cores = os.cpus().length || 1;
const cpuLimit = settings.thresholds.cpu || 85;
const memLimit = settings.thresholds.mem || 90;
for (const a of map.values()) {
a.ports = [...new Map(a.ports.map(p => [p.public, p])).values()].sort((x, y) => x.public - y.public);
const down = a.containers.filter(c => c.state !== 'running');
if (down.length && a.running > 0) {
a.issues.push({ level: 'critical', code: 'partial_down', text: `${down.length} 个容器未运行(${down.map(c => c.name).join('、')})` });
} else if (down.length && a.running === 0) {
a.issues.push({ level: 'warning', code: 'stopped', text: '应用已停止' });
}
for (const c of a.containers) {
if (c.health === 'unhealthy') a.issues.push({ level: 'critical', code: 'unhealthy', text: `${c.name} 健康检查失败` });
else if (c.health === 'starting') a.issues.push({ level: 'warning', code: 'health_starting', text: `${c.name} 健康检查中` });
}
const cpuPctOfMachine = a.cpu / cores;
if (cpuPctOfMachine > cpuLimit) a.issues.push({ level: 'warning', code: 'cpu', text: `CPU 占整机 ${cpuPctOfMachine.toFixed(1)}%(阈值 ${cpuLimit}%)` });
if (a.memPctMax > memLimit) a.issues.push({ level: 'warning', code: 'mem', text: `内存占上限 ${a.memPctMax.toFixed(1)}%(阈值 ${memLimit}%)` });
a.cpuPctOfMachine = +cpuPctOfMachine.toFixed(2);
a.severity = a.issues.some(i => i.level === 'critical') ? 2 : (a.issues.length ? 1 : 0);
a.statusText = a.severity === 2 ? '异常' : a.severity === 1 ? '注意' : '正常';
const st = appState.get(a.key);
a.uptime = computeUptime(st?.uptime);
a.runMs = a.running > 0 && a.startedAt ? Math.max(0, Date.now() - Date.parse(a.startedAt)) : null;
a.since = st?.since || null;
delete a.containers_meta;
}
return [...map.values()];
}
function computeUptime(points) {
if (!points || !points.length) return null;
const ok = points.filter(p => p.ok).length;
return +(ok / points.length * 100).toFixed(2);
}
function pushEvent(level, appKey, title, detail) {
const ev = { t: Date.now(), level, appKey, title, detail };
events.unshift(ev);
if (events.length > EVENT_MAX) events.pop();
return ev;
}
async function tickApps() {
try {
const apps = buildApps(await docker.listContainers({ all: true }));
for (const a of apps) {
let st = appState.get(a.key);
if (!st) {
st = { severity: a.severity, uptime: [], since: Date.now(), lastNotifyAt: 0 };
appState.set(a.key, st);
// 首次发现就已异常,也要留一条事件,否则「一上线就坏」的应用没有任何记录
if (a.severity > 0) {
const ev = pushEvent(a.severity === 2 ? 'critical' : 'warning', a.key,
`${a.name} ${a.severity === 2 ? '异常' : '注意'}`, a.issues.map(i => i.text).join(';'));
notify(ev, a, st).catch(() => {});
}
}
const prev = st.severity;
if (a.severity > prev) {
const ev = pushEvent(a.severity === 2 ? 'critical' : 'warning', a.key,
`${a.name} ${a.severity === 2 ? '异常' : '注意'}`, a.issues.map(i => i.text).join(';'));
notify(ev, a, st).catch(() => {});
} else if (a.severity < prev && prev > 0) {
pushEvent('info', a.key, `${a.name} 已恢复`, '所有容器恢复正常');
}
st.severity = a.severity;
}
const keys = new Set(apps.map(a => a.key));
for (const k of [...appState.keys()]) if (!keys.has(k)) appState.delete(k);
} catch (e) { lastError = e.message; }
}
function tickUptime() {
const now = Date.now();
for (const [, st] of appState) {
st.uptime.push({ t: now, ok: st.severity === 0 });
if (st.uptime.length > UPTIME_MAX) st.uptime.shift();
}
}
async function notify(ev, appInfo, st) {
if (!settings.notify || !settings.webhook) return;
const now = Date.now();
if (st && now - (st.lastNotifyAt || 0) < (settings.debounceMinutes || 10) * 60000) return;
if (st) st.lastNotifyAt = now;
try {
await fetch(settings.webhook, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: `[${appInfo.statusText}] ${appInfo.name}`, level: ev.level, app: appInfo.name,
detail: ev.detail, time: new Date(ev.t).toLocaleString('zh-CN', { hour12: false }), host: hostName(),
}),
signal: AbortSignal.timeout(8000),
});
} catch (e) { console.error('[notify] 推送失败', e.message); }
}
/* ---------------- 接口:主机 ---------------- */
app.get('/api/health', (req, res) => res.json({ ok: true, lastError }));
app.get('/api/host', async (req, res) => {
try {
const info = await docker.info();
const ver = await docker.version();
let memTotal = os.totalmem(), memFree = os.freemem(), swapTotal = 0, swapFree = 0;
try {
const mi = fs.readFileSync('/proc/meminfo', 'utf8');
const g = (k) => Number((mi.match(new RegExp(k + ':\\s+(\\d+)')) || [])[1] || 0) * 1024;
memTotal = g('MemTotal'); memFree = g('MemAvailable'); swapTotal = g('SwapTotal'); swapFree = g('SwapFree');
} catch (e) {}
let disk = null;
try {
const st = fs.statfsSync(process.env.DISK_PATH || '/host/vol1');
disk = { total: st.blocks * st.bsize, free: st.bavail * st.bsize };
} catch (e) {}
let pending = 0;
try { pending = (await scanPending()).length; } catch (e) {}
res.json({
hostname: info.Name, os: info.OperatingSystem, kernel: info.KernelVersion,
dockerVersion: ver.Version, cpus: info.NCPU, cpuModel: os.cpus()[0]?.model,
loadavg: os.loadavg(), memTotal, memFree, swapTotal, swapFree, disk,
containers: info.Containers, running: info.ContainersRunning,
paused: info.ContainersPaused, stopped: info.ContainersStopped, pending,
images: info.Images, driver: info.Driver, lastError,
});
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 接口:应用 ---------------- */
app.get('/api/apps', async (req, res) => {
try {
let apps = buildApps(await docker.listContainers({ all: true }));
const q = (req.query.q || '').trim().toLowerCase();
if (q) apps = apps.filter(a => a.name.toLowerCase().includes(q) || a.containers.some(c => c.name.toLowerCase().includes(q)));
const f = req.query.filter;
if (f === 'issues') apps = apps.filter(a => a.severity > 0);
else if (f === 'stopped') apps = apps.filter(a => a.running === 0);
else if (f === 'high') apps = apps.filter(a => a.cpuPctOfMachine > 20 || a.memPctMax > 50);
const cmp = {
severity: (a, b) => (b.severity - a.severity) || (b.cpu - a.cpu),
cpu: (a, b) => b.cpu - a.cpu,
mem: (a, b) => b.mem - a.mem,
name: (a, b) => b.name.localeCompare(a.name, 'zh'),
containers: (a, b) => b.total - a.total,
}[req.query.sort] || ((a, b) => (b.severity - a.severity) || (b.cpu - a.cpu));
const dir = req.query.order === 'asc' ? -1 : 1;
apps.sort((a, b) => dir * cmp(a, b));
res.json({
summary: {
total: apps.length,
critical: apps.filter(a => a.severity === 2).length,
warning: apps.filter(a => a.severity === 1).length,
stopped: apps.filter(a => a.running === 0).length,
running: apps.filter(a => a.running > 0).length,
cpu: +apps.reduce((s, a) => s + a.cpu, 0).toFixed(2),
mem: apps.reduce((s, a) => s + a.mem, 0),
containers: apps.reduce((s, a) => s + a.total, 0),
},
items: apps,
});
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/apps/:key', async (req, res) => {
try {
const key = decodeURIComponent(req.params.key);
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
if (!a) return res.status(404).json({ error: '应用不存在' });
const st = appState.get(key);
a.uptimeHistory = (st?.uptime || []).slice(-120);
a.events = events.filter(e => e.appKey === key).slice(0, 15);
a.cpuPctOfMachine = a.cpuPctOfMachine || 0;
res.json(a);
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/apps/:key/action', async (req, res) => {
const { action } = req.body || {};
try {
const key = decodeURIComponent(req.params.key);
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
if (!a) return res.status(404).json({ error: '应用不存在' });
if (!['start', 'stop', 'restart'].includes(action)) return res.status(400).json({ error: '未知操作' });
const results = [];
for (const c of a.containers) {
try {
const ct = docker.getContainer(c.id);
if (action === 'start') { if (c.state !== 'running') await ct.start(); }
else if (action === 'stop') { if (c.state === 'running') await ct.stop({ t: 10 }); }
else { if (c.state === 'running') await ct.restart({ t: 10 }); else await ct.start(); }
results.push({ name: c.name, ok: true });
} catch (e) { results.push({ name: c.name, ok: false, error: e.message }); }
}
res.json({ ok: true, results });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/apps/:key/logs', async (req, res) => {
try {
const key = decodeURIComponent(req.params.key);
const a = buildApps(await docker.listContainers({ all: true })).find(x => x.key === key);
if (!a) return res.status(404).json({ error: '应用不存在' });
const tail = Math.min(Number(req.query.tail || 120), 2000);
const parts = [];
for (const c of a.containers) {
try {
const text = demuxLogs(await docker.getContainer(c.id).logs({ stdout: true, stderr: true, timestamps: true, tail, follow: false }));
if (text.trim()) parts.push(text.split('\n').filter(Boolean).map(l => `[${c.name}] ${l}`).join('\n'));
} catch (e) { parts.push(`[${c.name}] 日志读取失败:${e.message}`); }
}
res.json({ logs: parts.join('\n') });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/events', (req, res) => {
const limit = Math.min(Number(req.query.limit || 30), 200);
res.json({ items: events.slice(0, limit) });
});
/* ---------------- 接口:有镜像但未启动的应用 ---------------- */
let pendingCache = { at: 0, items: [] };
const normRef = (r) => {
const s = String(r).split('@')[0];
return s.split('/').pop().includes(':') ? s : `${s}:latest`;
};
const shortRef = (r) => normRef(r).split('/').pop();
async function scanPending(force) {
if (!force && pendingCache.items.length && Date.now() - pendingCache.at < 20000) return pendingCache.items;
const [conts, imgs] = await Promise.all([
docker.listContainers({ all: true }),
docker.listImages(),
]);
const busy = new Set();
for (const c of conts) {
const p = (c.Labels || {})['com.docker.compose.project'];
if (p) busy.add(String(p).toLowerCase());
// 单容器也可能是这目录起的,用容器名兜底
for (const n of (c.Names || [])) busy.add(strip(n).toLowerCase());
}
const local = new Set();
for (const im of imgs) for (const t of (im.RepoTags || [])) { local.add(normRef(t)); local.add(shortRef(t)); }
const CAND = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
let dirs = [];
try { dirs = await fsp.readdir(COMPOSE_ROOT, { withFileTypes: true }); } catch (e) { return []; }
const items = [];
for (const d of dirs) {
if (!d.isDirectory() || d.name.startsWith('.')) continue;
let file = null;
for (const fn of CAND) {
const p = path.join(COMPOSE_ROOT, d.name, fn);
try { await fsp.access(p); file = p; break; } catch (e) {}
}
if (!file) continue;
if (busy.has(d.name.toLowerCase())) continue;
let txt = '';
try { txt = await fsp.readFile(file, 'utf8'); } catch (e) { continue; }
const refs = [...new Set([...txt.matchAll(/^\s*image:\s*["']?([^\s"'#]+)/gm)].map(m => m[1]))];
const svcBlock = txt.split(/^services:\s*$/m)[1] || '';
const services = [...new Set([...svcBlock.matchAll(/^ ([A-Za-z0-9._-]+):\s*$/gm)].map(m => m[1]))];
const hasBuild = /^\s*build:/m.test(txt);
const present = refs.filter(r => local.has(normRef(r)) || local.has(shortRef(r)));
const missing = refs.filter(r => !(local.has(normRef(r)) || local.has(shortRef(r))));
if (!present.length) continue; // 只要“有镜像”的
items.push({
key: `dir:${d.name}`, name: d.name, dir: path.join(COMPOSE_ROOT, d.name), file,
services: services.length || refs.length, hasBuild,
images: { total: refs.length, present: present.length, missing: missing.slice(0, 4) },
mtime: (await fsp.stat(file).catch(() => ({ mtimeMs: 0 }))).mtimeMs,
});
}
items.sort((a, b) => b.mtime - a.mtime || a.name.localeCompare(b.name));
pendingCache = { at: Date.now(), items };
return items;
}
app.get('/api/pending-apps', async (req, res) => {
try {
const items = await scanPending(req.query.refresh === '1');
res.json({ items, total: items.length, root: COMPOSE_ROOT });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/pending-apps/start', async (req, res) => {
const name = String((req.body && req.body.name) || '');
try {
const items = await scanPending(true);
const target = items.find(i => i.name === name);
if (!target) return res.status(404).json({ error: '未找到该项目(可能已经有容器在内)' });
const projName = target.name.toLowerCase().replace(/[^a-z0-9_-]/g, '');
const env = { ...process.env };
if (/^[a-z0-9][a-z0-9_-]*$/.test(projName)) env.COMPOSE_PROJECT_NAME = projName;
const out = await new Promise((resolve) => {
execFile('docker', ['compose', '-f', target.file, 'up', '-d'], {
cwd: target.dir, timeout: 240000, maxBuffer: 2 * 1024 * 1024, env,
}, (err, stdout, stderr) => resolve({
ok: !err, code: err ? (err.code || 1) : 0,
output: `${stdout || ''}${stderr || ''}`.trim().split('\n').slice(-14).join('\n'),
}));
});
pendingCache.at = 0;
inspectAll().catch(() => {});
res.json(out);
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 接口:优化建议 ---------------- */
async function getDf(force) {
if (!force && dfCache.data && Date.now() - dfCache.at < 60000) return dfCache.data;
const d = await docker.df();
dfCache = { at: Date.now(), data: d };
return d;
}
app.get('/api/insights', async (req, res) => {
try {
const apps = buildApps(await docker.listContainers({ all: true }));
const items = [];
const add = (sev, app, title, detail, action) => items.push({
sev, appKey: app ? app.key : null, appName: app ? app.name : null, title, detail, action: action || null,
});
const mb = (n) => `${(n / 1048576).toFixed(0)} MB`;
const gb = (n) => `${(n / 1073741824).toFixed(1)} GB`;
const agg = { latest: [], solo: [], noHealth: [], noLimit: [] };
for (const a of apps) {
const c = a.containers;
const running = c.filter(x => x.state === 'running');
// 停止的应用:确认不用就删,要用就起来
if (a.running === 0) {
add('mid', a, '应用已停止', '确认不再需要就删掉,需要就启动;停着的应用仍占镜像和磁盘',
{ type: 'startApp', label: '启动应用' });
continue;
}
const flappy = c.filter(x => (x.restarts || 0) >= 3).sort((x, y) => y.restarts - x.restarts);
if (flappy.length) {
add('high', a, `${flappy.slice(0, 2).map(x => x.name).join('、')} 反复重启(${flappy[0].restarts} 次)`,
'连续重启通常是配置错误、依赖服务不可用或健康检查失败,先看该容器日志',
{ type: 'openApp', label: '查看日志' });
}
const near = running.filter(x => (x.stats.memPct || 0) > 85);
if (near.length) {
add('mid', a, `${near[0].name} 内存接近上限(${(near[0].stats.memPct || 0).toFixed(0)}%)`,
'持续贴近上限会频繁 GC 或被杀,建议提高上限或排查内存泄漏',
{ type: 'openApp', label: '查看应用' });
}
const hot = running.filter(x => (x.stats.cpu || 0) > 60);
if (hot.length) {
add('mid', a, `${hot[0].name} CPU 偏高(${(hot[0].stats.cpu || 0).toFixed(0)}%)`,
'持续高 CPU 会挤压其他应用,建议限流(cpus)或排查死循环/高频任务',
{ type: 'openApp', label: '查看应用' });
}
if (c.some(x => x.privileged)) {
add('high', a, '存在特权容器(privileged)', '特权容器几乎等同宿主 root,非必要请去掉 privileged', null);
}
if (c.some(x => x.dockerSock)) {
add('mid', a, '容器挂载了 docker.sock', '挂载 Docker socket 的容器可以控制整台机器的容器(等同 root),确认是本人设计再用', null);
}
// 汇总类问题
const latest = c.filter(x => /:latest$/.test(x.image) || !x.image.split('/').pop().includes(':'));
if (latest.length) agg.latest.push(a.name);
if (a.type === 'solo') agg.solo.push(a.name);
for (const x of running) {
if (!x.healthcheck && (x.ports || 0) > 0) agg.noHealth.push(a.name);
if (!x.memLimitCfg && (x.stats.mem || 0) > 0) agg.noLimit.push([a.name, x.name, x.stats.mem]);
}
}
const list = (arr, n = 3) => {
const uniq = [...new Set(arr)];
return uniq.slice(0, n).join('、') + (uniq.length > n ? ` 等 ${uniq.length} 个` : '');
};
if (agg.noLimit.length) {
const total = agg.noLimit.reduce((s, x) => s + x[2], 0);
const top = agg.noLimit.sort((a, b) => b[2] - a[2])[0];
if (total > 1073741824) {
add('mid', null, `${agg.noLimit.length} 个容器未设内存上限(合计 ${gb(total)})`,
`占用最高的是 ${top[1]}(${mb(top[2])})。没有 mem_limit 时单个容器可能吃满整机内存并触发 OOM,建议在 compose 里加 mem_limit(例:512m)`, null);
}
}
if (agg.noHealth.length) {
add('low', null, `${agg.noHealth.length} 个对外容器没有健康检查`,
`涉及 ${list(agg.noHealth)}。没有 HEALTHCHECK 时「进程还在但服务已挂」无法被发现,建议补上健康检查`, null);
}
if (agg.latest.length) {
add('low', null, `${agg.latest.length} 个应用使用 latest 镜像`,
`涉及 ${list(agg.latest)}。latest 随上游变动,更新不可控也不便回滚,建议固定版本号`, null);
}
if (agg.solo.length) {
add('low', null, `${agg.solo.length} 个应用未纳入 Compose`,
`涉及 ${list(agg.solo)}。手工 docker run 的容器不便备份、迁移和版本化,建议写成 compose 文件`, null);
}
let disk = null;
try {
const df = await getDf();
const imgs = df.Images || [];
const dangling = imgs.filter(i => !i.RepoTags || !i.RepoTags.length);
const danglingSize = dangling.reduce((s, i) => s + (i.Size || 0), 0);
const buildCache = (df.BuildCache || []).reduce((s, b) => s + (b.Size || 0), 0);
disk = { danglingCount: dangling.length, danglingSize, buildCache, layersSize: df.LayersSize || 0 };
if (danglingSize > 1073741824) {
add('mid', null, `悬空镜像占用 ${gb(danglingSize)}`,
`${dangling.length} 个无标签镜像没有任何容器在用,可以安全清理`, { type: 'pruneImages', label: '清理悬空镜像' });
}
if (buildCache > 5 * 1073741824) {
add('mid', null, `构建缓存占用 ${gb(buildCache)}`,
'docker build 留下的中间层,清理后下次构建会重新生成(不影响已在运行的容器)', { type: 'pruneBuildCache', label: '清理构建缓存' });
}
} catch (e) {}
try {
const st = await fsp.statfs(process.env.DISK_PATH || '/host/vol1');
const free = st.bavail * st.bsize, size = st.blocks * st.bsize;
const pct = size ? (free / size) * 100 : 100;
disk = { ...(disk || {}), free, size };
if (pct < 10) {
add('high', null, `磁盘可用仅剩 ${gb(free)}(${pct.toFixed(0)}%)`,
'磁盘写满会导致容器崩溃、数据库损坏,建议先清理悬空镜像与构建缓存,再处理大日志', null);
}
} catch (e) {}
const order = { high: 0, mid: 1, low: 2 };
items.sort((x, y) => order[x.sev] - order[y.sev]);
const counts = { high: 0, mid: 0, low: 0 };
for (const i of items) counts[i.sev]++;
res.json({ items, counts, total: items.length, disk });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/maintenance/prune', async (req, res) => {
const what = (req.body && req.body.what) || 'images';
try {
let out = { ok: true, what };
if (what === 'buildCache') {
const r = await docker.pruneBuilder({}).catch(async () => ({ SpaceReclaimed: 0 }));
out.reclaimed = r.SpaceReclaimed || 0;
} else {
const r = await docker.pruneImages({ filters: { dangling: ['true'] } });
out.reclaimed = r.SpaceReclaimed || 0;
out.deleted = (r.ImagesDeleted || []).length;
}
await getDf(true);
res.json(out);
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 接口:设置 ---------------- */
app.get('/api/settings', (req, res) => res.json(settings));
app.post('/api/settings', (req, res) => {
const b = req.body || {};
settings = {
...settings,
thresholds: { ...settings.thresholds, ...(b.thresholds || {}) },
webhook: b.webhook !== undefined ? String(b.webhook).trim() : settings.webhook,
notify: b.notify !== undefined ? !!b.notify : settings.notify,
debounceMinutes: b.debounceMinutes !== undefined ? (Number(b.debounceMinutes) || 10) : settings.debounceMinutes,
};
saveSettings();
res.json(settings);
});
app.post('/api/settings/test', async (req, res) => {
if (!settings.webhook) return res.status(400).json({ error: '未配置 webhook' });
try {
await fetch(settings.webhook, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: '[测试] 飞牛docker容器管理增强版', level: 'info', app: '-', detail: '这是一条测试推送', time: new Date().toLocaleString('zh-CN', { hour12: false }), host: hostName() }),
signal: AbortSignal.timeout(8000),
});
res.json({ ok: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 接口:容器 ---------------- */
const SORTERS = {
cpu: (a, b) => b.stats.cpu - a.stats.cpu,
mem: (a, b) => b.stats.mem - a.stats.mem,
net: (a, b) => (b.stats.rxBps + b.stats.txBps) - (a.stats.rxBps + a.stats.txBps),
io: (a, b) => (b.stats.rdBps + b.stats.wrBps) - (a.stats.rdBps + a.stats.wrBps),
name: (a, b) => b.name.localeCompare(a.name, 'zh'),
pids: (a, b) => b.stats.pids - a.stats.pids,
};
app.get('/api/containers', async (req, res) => {
try {
const all = req.query.all !== '0';
const raw = await docker.listContainers({ all });
let list = raw.map(c => {
const st = stats.get(c.Id) || {};
const m = meta.get(c.Id) || {};
return {
id: c.Id, shortId: c.Id.slice(0, 12), name: strip((c.Names || [])[0]),
image: c.Image, state: c.State, status: c.Status, created: c.Created,
project: projectOf(c.Labels), service: svcOf(c.Labels),
health: m.health || '', restarts: m.restarts || 0,
ports: (c.Ports || []).map(p => ({ ip: p.IP, private: p.PrivatePort, public: p.PublicPort, type: p.Type })),
stats: {
cpu: st.cpu ?? 0, mem: st.mem ?? 0, memLimit: st.memLimit ?? 0, memPct: st.memPct ?? 0,
rxBps: st.rxBps ?? 0, txBps: st.txBps ?? 0, rdBps: st.rdBps ?? 0, wrBps: st.wrBps ?? 0,
pids: st.pids ?? 0, hasData: !!st.ts,
},
};
});
const q = (req.query.q || '').trim().toLowerCase();
if (q) list = list.filter(c => c.name.toLowerCase().includes(q) || c.image.toLowerCase().includes(q) || c.project.toLowerCase().includes(q));
if (req.query.state === 'running') list = list.filter(c => c.state === 'running');
else if (req.query.state === 'stopped') list = list.filter(c => c.state !== 'running');
const sort = SORTERS[req.query.sort] ? req.query.sort : 'cpu';
const dir = req.query.order === 'asc' ? -1 : 1;
list.sort((a, b) => dir * SORTERS[sort](a, b));
res.json({ total: list.length, sort, order: dir === 1 ? 'desc' : 'asc', items: list });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/containers/:id', async (req, res) => {
try {
const info = await docker.getContainer(req.params.id).inspect();
res.json({
info, stats: stats.get(info.Id) || null, history: history.get(info.Id) || [],
cmd: info.Config?.Cmd, entrypoint: info.Config?.Entrypoint,
env: info.Config?.Env || [], mounts: info.Mounts || [],
networks: info.NetworkSettings?.Networks || {}, ports: info.NetworkSettings?.Ports || {},
restartPolicy: info.HostConfig?.RestartPolicy?.Name || 'no',
startedAt: info.State?.StartedAt, finishedAt: info.State?.FinishedAt,
exitCode: info.State?.ExitCode, health: info.State?.Health?.Status || '',
});
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/containers/:id/logs', async (req, res) => {
try {
const tail = Math.min(Number(req.query.tail || 300), 5000);
const buf = await docker.getContainer(req.params.id).logs({ stdout: true, stderr: true, timestamps: true, tail, follow: false });
res.json({ logs: demuxLogs(buf) });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/containers/:id/logs/stream', async (req, res) => {
try {
const ct = docker.getContainer(req.params.id);
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const stream = await ct.logs({ stdout: true, stderr: true, timestamps: true, tail: Number(req.query.tail || 100), follow: true });
const out = new PassThrough();
docker.modem.demuxStream(stream, out, out);
out.on('data', d => res.write(`data: ${JSON.stringify(d.toString('utf8'))}\n\n`));
req.on('close', () => { try { stream.destroy(); } catch (e) {} });
} catch (e) { res.status(500).end(); }
});
app.post('/api/containers/:id/action', async (req, res) => {
const { action } = req.body || {};
try {
const ct = docker.getContainer(req.params.id);
if (action === 'start') await ct.start();
else if (action === 'stop') await ct.stop({ t: 10 });
else if (action === 'restart') await ct.restart({ t: 10 });
else if (action === 'pause') await ct.pause();
else if (action === 'unpause') await ct.unpause();
else if (action === 'kill') await ct.kill();
else return res.status(400).json({ error: '未知操作' });
res.json({ ok: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.delete('/api/containers/:id', async (req, res) => {
try {
await docker.getContainer(req.params.id).remove({ force: req.query.force === '1', v: req.query.volumes === '1' });
res.json({ ok: true });
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/containers', async (req, res) => {
const { image, name, ports = [], env = [], volumes = [], restart = 'always', cmd } = req.body || {};
if (!image) return res.status(400).json({ error: '缺少镜像名' });
try {
await new Promise((resolve, reject) => {
docker.pull(image, (err, stream) => {
if (err) return reject(err);
docker.modem.followProgress(stream, (e) => (e ? reject(e) : resolve()), () => {});
});
});
const ExposedPorts = {}, PortBindings = {};
for (const p of ports) {
if (!p.container) continue;
const proto = p.protocol || 'tcp';
ExposedPorts[`${p.container}/${proto}`] = {};
PortBindings[`${p.container}/${proto}`] = [{ HostPort: String(p.host || p.container) }];
}
const c = await docker.createContainer({
Image: image, name: name || undefined, Cmd: cmd ? cmd.split(' ') : undefined,
Env: env.filter(Boolean), ExposedPorts,
HostConfig: { PortBindings, Binds: volumes.filter(Boolean), RestartPolicy: { Name: restart } },
});
await c.start();
res.json({ ok: true, id: c.id });
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 接口:镜像 / 网络 ---------------- */
app.get('/api/images', async (req, res) => {
try {
const imgs = await docker.listImages({ all: false });
res.json(imgs.map(i => ({
id: i.Id, shortId: i.Id.replace('sha256:', '').slice(0, 12), tags: i.RepoTags || [],
size: i.Size, created: i.Created, containers: i.Containers || 0,
})).sort((a, b) => b.size - a.size));
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.delete('/api/images/:id', async (req, res) => {
try { await docker.getImage(req.params.id).remove({ force: req.query.force === '1' }); res.json({ ok: true }); }
catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/images/prune', async (req, res) => {
try { const r = await docker.pruneImages(); res.json({ ok: true, ...r }); }
catch (e) { res.status(500).json({ error: e.message }); }
});
app.post('/api/images/pull', async (req, res) => {
const { image } = req.body || {};
if (!image) return res.status(400).json({ error: '缺少镜像名' });
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
docker.pull(image, (err, stream) => {
if (err) { res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`); return res.end(); }
let last = '';
docker.modem.followProgress(stream,
(e) => { res.write(`data: ${JSON.stringify({ done: !e, error: e ? String(e) : null })}\n\n`); res.end(); },
(ev) => {
const line = ev.status + (ev.progress ? ' ' + ev.progress : '');
if (line !== last) { last = line; res.write(`data: ${JSON.stringify({ status: ev.status, progress: ev.progress })}\n\n`); }
});
});
});
app.get('/api/networks', async (req, res) => {
try {
const nets = await docker.listNetworks();
res.json(nets.map(n => ({
id: n.Id, name: n.Name, driver: n.Driver, scope: n.Scope,
subnet: (n.IPAM?.Config || []).map(c => c.Subnet).filter(Boolean),
gateway: (n.IPAM?.Config || []).map(c => c.Gateway).filter(Boolean),
containers: Object.keys(n.Containers || {}).length, internal: !!n.Internal,
})));
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 启动 ---------------- */
setInterval(sampleOnce, SAMPLE_MS);
setInterval(tickApps, SAMPLE_MS);
setInterval(inspectAll, INSPECT_MS);
setInterval(tickUptime, UPTIME_MS);
setTimeout(() => { sampleOnce(); inspectAll(); tickApps(); }, 300);
app.listen(PORT, '0.0.0.0', () => console.log(`[docker-center] http://0.0.0.0:${PORT} sample=${SAMPLE_MS}ms inspect=${INSPECT_MS}ms`));