'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 zlib = require('zlib'); const http = require('http'); 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'; const TRAFFIC_DIR = process.env.TRAFFIC_DIR || '/data/traffic'; // 每次进程启动生成新版本号:前端发现版本变化会自动刷新页面 const BUILD_ID = process.env.BUILD_ID || String(Date.now()); app.use(express.json({ limit: '1mb' })); app.use(express.static(path.join(__dirname, '..', 'public'), { etag: false, lastModified: false, setHeaders: (res) => res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate'), })); /* ---------------- 设置 ---------------- */ 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])}`; }; /* ---------------- 采样 ---------------- */ /* ---------------- 流量账本(按小时落盘) ---------------- */ 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 emptyHour = () => ({ rx: 0, tx: 0, cpuSum: 0, cpuN: 0, memSum: 0, memMax: 0, memN: 0 }); const emptyHours = () => Array.from({ length: 24 }, () => emptyHour()); 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++) { const h = j.hours[i] || {}; data.hours[i] = { rx: h.rx || 0, tx: h.tx || 0, cpuSum: h.cpuSum || 0, cpuN: h.cpuN || 0, memSum: h.memSum || 0, memMax: h.memMax || 0, memN: h.memN || 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, cpuPct, memBytes) { 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); if (Number.isFinite(cpuPct)) { b.cpuSum += cpuPct; b.cpuN += 1; } if (Number.isFinite(memBytes)) { b.memSum += memBytes; b.memMax = Math.max(b.memMax, memBytes); b.memN += 1; } 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); 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, // 字节差量:用于流量账本,避免用「速率×间隔」累加带来的抖动 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); } 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) {} })); // 汇总所有运行中容器的流量增量,记入小时账本 await trafficToday(); let sumRx = 0, sumTx = 0; for (const st of stats.values()) { sumRx += st.dRx || 0; sumTx += st.dTx || 0; } const coresAll = os.cpus().length || 1; let sumCpu = 0, sumMem = 0; for (const st of stats.values()) { sumCpu += st.cpu || 0; sumMem += st.mem || 0; } addTraffic(sumRx, sumTx, sumCpu / coresAll, sumMem); 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; } } /* 重启次数 / 健康状态: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, nanoCpus: old.nanoCpus || 0, pidsLimit: old.pidsLimit || 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.nanoCpus = d.HostConfig?.NanoCpus || 0; next.pidsLimit = d.HostConfig?.PidsLimit || 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, nanoCpus: m.nanoCpus || 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, build: BUILD_ID, images: info.Images, driver: info.Driver, lastError, composeRoot: COMPOSE_ROOT, }); } 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 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 agg = (rows) => rows.reduce((a, h) => ({ rx: a.rx + (h.rx || 0), tx: a.tx + (h.tx || 0), cpuSum: a.cpuSum + (h.cpuSum || 0), cpuN: a.cpuN + (h.cpuN || 0), memSum: a.memSum + (h.memSum || 0), memN: a.memN + (h.memN || 0), memMax: Math.max(a.memMax, h.memMax || 0), }), { rx: 0, tx: 0, cpuSum: 0, cpuN: 0, memSum: 0, memN: 0, memMax: 0 }); const shape = (a) => ({ rx: a.rx, tx: a.tx, cpu: a.cpuN ? a.cpuSum / a.cpuN : 0, mem: a.memN ? a.memSum / a.memN : 0, memMax: a.memMax, }); const sumOf = (pts, k) => pts.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((h, i) => ({ label: `${String(i).padStart(2, '0')}:00`, ...shape(h) })); 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, ...shape(agg(day.hours)) }); } label = '近 30 天'; unit = 'day'; from = localYmd(new Date(), -29); } else if (range === 'year') { const base = new Date(Date.now() + 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(); const rows = []; 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); rows.push(...day.hours); } points.push({ label: `${String(mo).padStart(2, '0')}月`, month: `${y}-${String(mo).padStart(2, '0')}`, ...shape(agg(rows)) }); } 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 cores = os.cpus().length || 1; let nowCpu = 0, nowMem = 0, nowRx = 0, nowTx = 0; for (const st of stats.values()) { nowCpu += st.cpu || 0; nowMem += st.mem || 0; nowRx += st.rxBps || 0; nowTx += st.txBps || 0; } res.json({ range, label, unit, from, to, points, total: { rx: sumOf(points, 'rx'), tx: sumOf(points, 'tx') }, avg: { cpu: points.length ? sumOf(points, 'cpu') / points.filter(p => p.cpu).length || 0 : 0, mem: sumOf(points, 'mem') / Math.max(1, points.filter(p => p.mem).length) }, peak: { mem: Math.max(0, ...points.map(p => p.memMax || 0)), cpu: Math.max(0, ...points.map(p => p.cpu || 0)) }, now: { rx: nowRx, tx: nowTx, cpu: nowCpu / cores, mem: nowMem }, cores, 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) => { 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 }); } }); const TRASH_DIR = path.join(COMPOSE_ROOT, '.trash'); // 与 compose 目录同一文件系统,rename 即时完成 async function startPendingProject(target) { const projName = String(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'), })); }); return out; } 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 out = await startPendingProject(target); pendingCache.at = 0; inspectAll().catch(() => {}); res.json(out); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/pending-apps/batch-start', async (req, res) => { try { const names = Array.isArray(req.body && req.body.names) ? req.body.names.filter(n => typeof n === 'string').slice(0, 20) : []; if (!names.length) return res.status(400).json({ error: '未选择应用' }); const items = await scanPending(true); const results = []; for (const name of names) { const target = items.find(i => i.name === name); if (!target) { results.push({ name, ok: false, error: '未找到该项目(可能已经有容器在内)' }); continue; } try { const out = await startPendingProject(target); results.push({ name, ok: out.ok, output: out.output, error: out.ok ? '' : '启动失败,见输出' }); } catch (e) { results.push({ name, ok: false, error: e.message }); } } pendingCache.at = 0; inspectAll().catch(() => {}); const ok = results.filter(r => r.ok).length; pushEvent('info', null, `批量启动应用 ${ok} 个`, `失败 ${results.length - ok} 个`); res.json({ ok: true, started: ok, results }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/pending-apps/delete', async (req, res) => { try { const names = Array.isArray(req.body && req.body.names) ? req.body.names.filter(n => typeof n === 'string').slice(0, 20) : []; const purge = !!(req.body && req.body.purge); if (!names.length) return res.status(400).json({ error: '未选择应用' }); const items = await scanPending(true); const results = []; for (const name of names) { const target = items.find(i => i.name === name); if (!target) { results.push({ name, ok: false, error: '未找到该项目(可能已经有容器在内)' }); continue; } try { const conts = await docker.listContainers({ all: true }); const holders = conts.filter(c => (c.Labels || {})['com.docker.compose.project'] === String(name).toLowerCase() || (c.Labels || {})['com.docker.compose.project'] === name); if (holders.length) { results.push({ name, ok: false, error: `该项目还有 ${holders.length} 个容器,请先删除容器` }); continue; } if (!target.dir.startsWith(COMPOSE_ROOT + path.sep)) { results.push({ name, ok: false, error: '目录不在扫描根内,已跳过' }); continue; } if (purge) { await fsp.rm(target.dir, { recursive: true, force: true }); results.push({ name, ok: true, moved: '' }); } else { await fsp.mkdir(TRASH_DIR, { recursive: true }); const dest = path.join(TRASH_DIR, `${name}-${new Date().toISOString().replace(/[:.]/g, '-')}`); try { await fsp.rename(target.dir, dest); } catch (err) { if (err.code !== 'EXDEV') throw err; await fsp.cp(target.dir, dest, { recursive: true }); await fsp.rm(target.dir, { recursive: true, force: true }); } results.push({ name, ok: true, moved: dest }); } } catch (e) { results.push({ name, ok: false, error: e.message }); } } pendingCache.at = 0; const ok = results.filter(r => r.ok).length; pushEvent('warn', null, `${purge ? '彻底删除' : '删除(移入回收站)'}应用 ${ok} 个`, ''); res.json({ ok: true, deleted: ok, results }); } 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, created: (a, b) => (b.created || 0) - (a.created || 0), }; app.post('/api/containers/batch-delete', async (req, res) => { try { const ids = Array.isArray(req.body && req.body.ids) ? req.body.ids.filter(x => typeof x === 'string') : []; if (!ids.length) return res.status(400).json({ error: '未提供要删除的容器' }); const results = []; for (const id of ids.slice(0, 200)) { try { const c = docker.getContainer(id); const info = await c.inspect(); const name = strip((info.Name || '')); if (info.State && info.State.Running) { results.push({ id, name, ok: false, error: '运行中,已跳过' }); continue; } await c.remove({ v: false, force: false }); results.push({ id, name, ok: true }); } catch (e) { results.push({ id, name: '', ok: false, error: e.message }); } } const deleted = results.filter(r => r.ok).length; pushEvent('info', null, `批量删除容器 ${deleted} 个`, `失败 ${results.length - deleted} 个`); res.json({ ok: true, deleted, results }); } catch (e) { res.status(500).json({ error: e.message }); } }); 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, limits: { cpus: (m.nanoCpus || 0) / 1e9, memMB: Math.round((m.memLimitCfg || 0) / 1048576), pids: m.pidsLimit || 0 }, startedAt: m.startedAt || '', runMs: c.State === 'running' && m.startedAt ? Math.max(0, Date.now() - Date.parse(m.startedAt)) : null, 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 : 'created'; 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, conts] = await Promise.all([ docker.listImages({ all: false }), docker.listContainers({ all: true }), ]); const use = new Map(); for (const c of conts) { const k = c.ImageID; if (!use.has(k)) use.set(k, { running: [], stopped: [] }); const b = use.get(k); (c.State === 'running' ? b.running : b.stopped).push(strip((c.Names || [])[0])); } const list = imgs.map(i => { const u = use.get(i.Id) || { running: [], stopped: [] }; return { id: i.Id, shortId: i.Id.replace('sha256:', '').slice(0, 12), tags: i.RepoTags || [], size: i.Size, created: i.Created, containers: i.Containers || 0, running: u.running, stopped: u.stopped, inUse: u.running.length > 0, canDelete: u.running.length === 0 && u.stopped.length === 0, }; }).sort((a, b) => b.size - a.size); res.json({ items: list, summary: { total: list.length, totalSize: list.reduce((a, b) => a + b.size, 0), inUse: list.filter(i => i.inUse).length, deletable: list.filter(i => i.canDelete).length, deletableSize: list.filter(i => i.canDelete).reduce((a, b) => a + b.size, 0), }, }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/images/batch-delete', async (req, res) => { try { const ids = Array.isArray(req.body && req.body.ids) ? req.body.ids.filter(x => typeof x === 'string').slice(0, 100) : []; if (!ids.length) return res.status(400).json({ error: '未选择镜像' }); const conts = await docker.listContainers({ all: true }); const results = []; for (const id of ids) { try { const img = await docker.getImage(id).inspect(); const holders = conts.filter(c => c.ImageID === img.Id); if (holders.length) { const running = holders.filter(c => c.State === 'running').length; results.push({ id, tag: (img.RepoTags || [])[0] || img.Id.slice(7, 19), ok: false, error: running ? `被 ${running} 个运行中容器占用` : `被 ${holders.length} 个已停止容器引用` }); continue; } await docker.getImage(id).remove({ force: false }); results.push({ id, tag: (img.RepoTags || [])[0] || img.Id.slice(7, 19), ok: true }); } catch (e) { results.push({ id, tag: '', ok: false, error: e.message }); } } const ok = results.filter(r => r.ok).length; pushEvent('info', null, `批量删除镜像 ${ok} 个`, `跳过/失败 ${results.length - ok} 个`); res.json({ ok: true, deleted: ok, results }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/images/import', (req, res) => { const sock = process.env.DOCKER_SOCK || '/var/run/docker.sock'; const up = http.request({ socketPath: sock, path: '/images/load?quiet=0', method: 'POST', headers: { 'Content-Type': 'application/x-tar', 'Transfer-Encoding': 'chunked' }, }, (r) => { let buf = ''; r.on('data', (c) => { buf += c.toString('utf8'); }); r.on('end', () => { const errLine = buf.split(/\r?\n/).map(l => { try { return JSON.parse(l); } catch (_) { return null; } }).find(o => o && (o.error || o.errorDetail)); if (r.statusCode !== 200 || errLine) { const msg = errLine ? ((errLine.errorDetail && errLine.errorDetail.message) || errLine.error) : buf.slice(-300); return res.status(400).json({ error: /invalid tar header|unexpected EOF/i.test(String(msg)) ? '文件不是有效的镜像包(需要 docker save 导出的 tar 或 tar.gz)' : '导入失败:' + msg }); } const loaded = [...buf.matchAll(/Loaded image:?\s*([^\s"\\]+)/g)].map(m => m[1]); pushEvent('info', null, `导入镜像 ${loaded.length} 个`, loaded.slice(0, 3).join('、')); res.json({ ok: true, loaded, count: loaded.length, raw: buf.slice(-800) }); }); }); up.on('error', (e) => { if (!res.headersSent) res.status(500).json({ error: e.message }); else res.end(); }); req.on('aborted', () => up.destroy()); req.pipe(up); }); app.get('/api/images/export', async (req, res) => { try { const ids = String(req.query.ids || '').split(',').map(x => x.trim()).filter(Boolean).slice(0, 40); if (!ids.length) return res.status(400).json({ error: '未选择镜像' }); const stamp = new Date().toISOString().slice(0, 10); res.setHeader('Content-Type', 'application/gzip'); res.setHeader('Content-Disposition', `attachment; filename="images-${ids.length}-${stamp}.tar.gz"`); // 有 tag 优先用 tag 导出,否则回退到镜像 ID(按 ID 导出会丢 RepoTags) const all = await docker.listImages({ all: false }); const tagOf = new Map(all.map(i => [i.Id, (i.RepoTags && i.RepoTags[0]) || ''])); const refs = ids.map(id => tagOf.get(id) || id); const q = refs.map(r => 'names=' + encodeURIComponent(r)).join('&'); const gz = zlib.createGzip({ level: 3 }); gz.on('error', () => { try { res.end(); } catch (_) {} }); gz.pipe(res); const up = http.request({ socketPath: process.env.DOCKER_SOCK || '/var/run/docker.sock', path: `/images/get?${q}`, method: 'GET' }, (r) => { if (r.statusCode !== 200) { let buf = ''; r.on('data', c => { buf += c; }); r.on('end', () => { let msg = buf; try { msg = JSON.parse(buf).message || buf; } catch (_) {} if (!res.headersSent) res.status(500).json({ error: '导出失败:' + msg }); else res.end(); }); return; } r.pipe(gz); }); up.on('error', (e) => { if (!res.headersSent) res.status(500).json({ error: e.message }); else res.end(); }); res.on('close', () => { try { up.destroy(); } catch (_) {} }); up.end(); } catch (e) { if (!res.headersSent) res.status(500).json({ error: e.message }); else try { res.end(); } catch (_) {} } }); app.get('/api/images/:id/export', async (req, res) => { try { const img = await docker.getImage(req.params.id).inspect(); const tag = (img.RepoTags && img.RepoTags[0]) || ''; const base = tag ? tag.replace(/[^a-zA-Z0-9._-]+/g, '_').replace(/^_+|_+$/g, '') : img.Id.replace('sha256:', '').slice(0, 12); const name = `${base || 'image'}.tar.gz`; res.setHeader('Content-Type', 'application/gzip'); res.setHeader('Content-Disposition', `attachment; filename="${name}"`); res.setHeader('X-Image-Name', name); const stream = await docker.getImage(img.Id).get(); const gz = zlib.createGzip({ level: 3 }); stream.on('error', (e) => { try { res.end(); } catch (_) {} }); gz.on('error', () => { try { res.end(); } catch (_) {} }); res.on('close', () => { try { stream.destroy(); gz.destroy(); } catch (_) {} }); stream.pipe(gz).pipe(res); } catch (e) { if (!res.headersSent) res.status(500).json({ error: e.message }); else try { res.end(); } catch (_) {} } }); app.delete('/api/images/:id', async (req, res) => { try { const id = req.params.id; const img = await docker.getImage(id).inspect(); const conts = await docker.listContainers({ all: true }); const running = conts.filter(c => c.ImageID === img.Id && c.State === 'running').map(c => strip((c.Names || [])[0])); if (running.length) return res.status(409).json({ error: `该镜像正被运行中的容器使用(${running.slice(0, 3).join('、')}${running.length > 3 ? ' 等' : ''}),不能删除` }); const stopped = conts.filter(c => c.ImageID === img.Id).map(c => strip((c.Names || [])[0])); if (stopped.length) return res.status(409).json({ error: `该镜像被已停止的容器引用(${stopped.slice(0, 3).join('、')}),请先删除容器` }); await docker.getImage(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`); } }); }); }); const BUILTIN_NETS = ['bridge', 'host', 'none']; /* ---------------- 性能限制 ---------------- */ const LIMITS_PATH = path.join(path.dirname(SETTINGS_PATH), 'limits.json'); let limitsStore = { apps: {}, containers: {} }; try { limitsStore = JSON.parse(fs.readFileSync(LIMITS_PATH, 'utf8')); } catch (e) {} function saveLimits() { try { fs.mkdirSync(path.dirname(LIMITS_PATH), { recursive: true }); fs.writeFileSync(LIMITS_PATH, JSON.stringify(limitsStore, null, 2)); } catch (e) {} } function limitPayload(cpus, memMB) { const c = Number(cpus) || 0; const m = Number(memMB) || 0; if (c < 0 || m < 0) throw new Error('限制值不能为负'); const opt = { NanoCpus: c > 0 ? Math.round(c * 1e9) : 0 }; if (m > 0) { opt.Memory = Math.round(m * 1048576); opt.MemorySwap = -1; } else { opt.Memory = 0; opt.MemorySwap = 0; } return opt; } app.get('/api/limits', (req, res) => res.json(limitsStore)); app.post('/api/containers/:id/limits', async (req, res) => { try { const rawCpus = Number(req.body && req.body.cpus) || 0; const rawMem = Number(req.body && req.body.memMB) || 0; const clearing = rawCpus <= 0 && rawMem <= 0; const opt = clearing ? { CpuQuota: -1 } : limitPayload(rawCpus, rawMem); const c = docker.getContainer(req.params.id); const info = await c.inspect(); await c.update(opt); const name = strip(info.Name || ''); if (clearing) delete limitsStore.containers[name]; else limitsStore.containers[name] = { cpus: rawCpus, memMB: rawMem }; saveLimits(); const st = meta.get(info.Id) || {}; st.nanoCpus = clearing ? 0 : opt.NanoCpus; st.memLimitCfg = clearing ? 0 : (opt.Memory || 0); meta.set(info.Id, st); pushEvent('info', null, clearing ? `取消容器限制 ${name}` : `设置容器限制 ${name}`, clearing ? 'CPU 已解除;内存上限需重建容器才彻底移除' : `${opt.NanoCpus ? (opt.NanoCpus / 1e9).toFixed(2) + ' 核' : '不限 CPU'} · ${opt.Memory ? (opt.Memory / 1048576).toFixed(0) + ' MB' : '不限内存'}`); res.json({ ok: true, clearing, applied: opt, note: clearing ? 'CPU 限制已解除;内存上限需重建容器(docker compose up -d --force-recreate)才能完全移除' : '' }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/apps/:key/limits', async (req, res) => { try { const rawCpus = Number(req.body && req.body.cpus) || 0; const rawMem = Number(req.body && req.body.memMB) || 0; const clearing = rawCpus <= 0 && rawMem <= 0; const opt = clearing ? { CpuQuota: -1 } : limitPayload(rawCpus, rawMem); const key = String(req.params.key); const conts = await docker.listContainers({ all: true }); const mine = conts.filter(c => appKeyOf(c) === key); if (!mine.length) return res.status(404).json({ error: '该应用下没有容器' }); const results = []; for (const c of mine) { try { await docker.getContainer(c.Id).update(opt); const st = meta.get(c.Id) || {}; st.nanoCpus = clearing ? 0 : opt.NanoCpus; st.memLimitCfg = clearing ? 0 : (opt.Memory || 0); meta.set(c.Id, st); results.push({ name: strip((c.Names || [])[0]), ok: true }); } catch (e) { results.push({ name: strip((c.Names || [])[0]), ok: false, error: e.message }); } } if (clearing) delete limitsStore.apps[key]; else limitsStore.apps[key] = { cpus: rawCpus, memMB: rawMem }; saveLimits(); const ok = results.filter(r => r.ok).length; pushEvent('info', null, clearing ? `取消应用限制 ${key}` : `设置应用限制 ${key}`, `${ok}/${results.length} 个容器生效 · ${clearing ? '已解除 CPU;内存需重建容器' : `${opt.NanoCpus ? (opt.NanoCpus / 1e9).toFixed(2) + ' 核' : '不限 CPU'} / ${opt.Memory ? (opt.Memory / 1048576).toFixed(0) + ' MB' : '不限内存'}`}`); res.json({ ok: true, clearing, applied: ok, total: results.length, results, note: clearing ? 'CPU 限制已解除;内存上限需重建容器才能完全移除' : '' }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/limits/reapply', async (req, res) => { try { const conts = await docker.listContainers({ all: true }); let applied = 0, failed = 0; for (const c of conts) { const key = appKeyOf(c); const name = strip((c.Names || [])[0]); const lim = limitsStore.apps[key] || limitsStore.containers[name]; if (!lim) continue; try { const opt = limitPayload(lim.cpus, lim.memMB); await docker.getContainer(c.Id).update(opt); const st = meta.get(c.Id) || {}; st.nanoCpus = opt.NanoCpus; st.memLimitCfg = opt.Memory || 0; meta.set(c.Id, st); applied++; } catch (e) { failed++; } } res.json({ ok: true, applied, failed }); } catch (e) { res.status(500).json({ error: e.message }); } }); /* ---------------- Compose 批量部署 ---------------- */ function safeSubdir(dir) { const d = String(dir || '').trim().replace(/^\/+|\/+$/g, ''); if (!d) return null; if (d.includes('..') || d.includes('//')) return null; // 明确拒绝,不做静默改写 if (!/^[A-Za-z0-9._\-\/]+$/.test(d)) return null; return d; } app.post('/api/compose/deploy', async (req, res) => { try { const items = Array.isArray(req.body && req.body.items) ? req.body.items.slice(0, 20) : []; if (!items.length) return res.status(400).json({ error: '没有可部署的 Compose 项目' }); const results = []; for (const it of items) { const dir = safeSubdir(it.dir); if (!dir) { results.push({ dir: it.dir, ok: false, error: '目录名不合法(只允许字母数字 . _ - 和子路径)' }); continue; } const compose = String(it.compose || ''); if (!/^\s*(services|version)\s*:/m.test(compose)) { results.push({ dir, ok: false, error: '内容不像 Compose 文件(缺少 services:)' }); continue; } const target = path.join(COMPOSE_ROOT, dir); const projName = String(it.project || path.basename(dir)).toLowerCase().replace(/[^a-z0-9_-]/g, ''); try { await fsp.mkdir(target, { recursive: true }); await fsp.writeFile(path.join(target, 'docker-compose.yml'), compose.endsWith('\n') ? compose : compose + '\n'); const envLines = Object.entries(it.env || {}).filter(([k]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k)).map(([k, v]) => `${k}=${String(v)}`); if (projName) envLines.push(`COMPOSE_PROJECT_NAME=${projName}`); if (envLines.length) await fsp.writeFile(path.join(target, '.env'), envLines.join('\n') + '\n'); 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', path.join(target, 'docker-compose.yml'), 'up', '-d'], { cwd: target, timeout: 300000, maxBuffer: 4 * 1024 * 1024, env, }, (err, stdout, stderr) => resolve({ ok: !err, output: `${stdout || ''}${stderr || ''}`.trim().split('\n').slice(-10).join('\n'), })); }); results.push({ dir, project: projName, ok: out.ok, output: out.output, error: out.ok ? '' : '启动失败,见输出' }); } catch (e) { results.push({ dir, ok: false, error: e.message }); } } const ok = results.filter(r => r.ok).length; pendingCache.at = 0; inspectAll().catch(() => {}); pushEvent('info', null, `批量部署 Compose 项目 ${ok} 个`, `失败 ${results.length - ok} 个`); res.json({ ok: true, deployed: ok, results }); } catch (e) { res.status(500).json({ error: e.message }); } }); app.get('/api/networks', async (req, res) => { try { const nets = await docker.listNetworks(); res.json(nets.map(n => { const used = Object.keys(n.Containers || {}).length; const builtin = BUILTIN_NETS.includes(n.Name); return { 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: used, internal: !!n.Internal, builtin, canDelete: !builtin && used === 0, }; }).sort((a, b) => (a.builtin === b.builtin ? a.name.localeCompare(b.name) : a.builtin ? -1 : 1))); } catch (e) { res.status(500).json({ error: e.message }); } }); app.post('/api/networks', async (req, res) => { try { const b = req.body || {}; const name = String(b.name || '').trim(); if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$/.test(name)) { return res.status(400).json({ error: '网络名只能用字母、数字、下划线、点、短横线,且以字母或数字开头' }); } const driver = ['bridge', 'overlay', 'macvlan'].includes(b.driver) ? b.driver : 'bridge'; const subnet = String(b.subnet || '').trim(); const gateway = String(b.gateway || '').trim(); if (subnet && !/^\d{1,3}(\.\d{1,3}){3}\/\d{1,2}$/.test(subnet)) { return res.status(400).json({ error: '子网格式应为 172.28.0.0/16 这种形式' }); } if (gateway && !/^\d{1,3}(\.\d{1,3}){3}$/.test(gateway)) { return res.status(400).json({ error: '网关格式应为 172.28.0.1 这种形式' }); } const exists = (await docker.listNetworks()).find(n => n.Name === name); if (exists) return res.status(409).json({ error: `网络 ${name} 已存在` }); const ipam = subnet ? { Driver: 'default', Config: [gateway ? { Subnet: subnet, Gateway: gateway } : { Subnet: subnet }] } : undefined; const net = await docker.createNetwork({ Name: name, Driver: driver, CheckDuplicate: true, Internal: !!b.internal, Attachable: driver === 'overlay', ...(ipam ? { IPAM: ipam } : {}), }); pushEvent('info', null, `创建网络 ${name}`, `${driver}${subnet ? ' · ' + subnet : ''}`); res.json({ ok: true, id: net.id, name, driver, subnet: subnet || null }); } catch (e) { const m = String(e.message || ''); let msg = m; if (/Pool overlaps/i.test(m)) msg = '该子网与现有网络冲突,请换一个网段(如 10.99.0.0/16)'; else if (/invalid sub allocations|failed to allocate gateway/i.test(m)) msg = '子网或网关不合法,请检查格式与网段范围'; else if (/not support/i.test(m)) msg = '当前 Docker 不支持该驱动(overlay 需要 Swarm,macvlan 需要网卡参数)'; res.status(500).json({ error: msg }); } }); app.delete('/api/networks/:id', async (req, res) => { try { const id = req.params.id; const net = await docker.getNetwork(id).inspect(); if (BUILTIN_NETS.includes(net.Name)) return res.status(409).json({ error: `内置网络 ${net.Name} 不能删除` }); const used = Object.keys(net.Containers || {}).length; if (used) { const names = Object.values(net.Containers || {}).map(c => c.Name).slice(0, 3); return res.status(409).json({ error: `该网络还有 ${used} 个容器在用(${names.join('、')}),请先断开` }); } await docker.getNetwork(id).remove(); pushEvent('info', null, `删除网络 ${net.Name}`, ''); res.json({ ok: true }); } catch (e) { res.status(500).json({ error: e.message }); } }); /* ---------------- 备份 ---------------- */ const DATA_ROOT = path.dirname(SETTINGS_PATH); const BACKUP_DIR = path.join(DATA_ROOT, 'backups'); const CFG_FILE_RE = /^(docker-compose|compose)\.ya?ml$|^\.env(\..+)?$|\.(ya?ml|json|toml|ini|conf|env|txt|properties)$/i; async function listBackups() { try { const files = await fsp.readdir(BACKUP_DIR); const out = []; for (const f of files) { if (!f.endsWith('.tar.gz')) continue; const st = await fsp.stat(path.join(BACKUP_DIR, f)).catch(() => null); if (st) out.push({ name: f, size: st.size, time: st.mtimeMs }); } return out.sort((a, b) => b.time - a.time); } catch (e) { return []; } } app.get('/api/backup', async (req, res) => { const items = await listBackups(); res.json({ items, dir: BACKUP_DIR }); }); app.post('/api/backup', async (req, res) => { const stage = await fsp.mkdtemp(path.join(os.tmpdir(), 'dcbak-')).catch(() => null); if (!stage) return res.status(500).json({ error: '无法创建临时目录' }); try { const wantPanel = req.body && req.body.panel !== false; const wantApps = !!(req.body && req.body.apps); const ts = new Date(); const stamp = ts.toISOString().replace(/[:.]/g, '-').slice(0, 19); const name = `docker-center-backup-${stamp}.tar.gz`; await fsp.mkdir(BACKUP_DIR, { recursive: true }); const manifest = { created: ts.toISOString(), host: hostName(), panel: wantPanel, apps: wantApps, appList: [], files: 0 }; if (wantPanel) { const pd = path.join(stage, 'panel'); await fsp.mkdir(pd, { recursive: true }); for (const f of ['settings.json', 'events.json']) { const src = path.join(DATA_ROOT, f); if (fs.existsSync(src)) { await fsp.copyFile(src, path.join(pd, f)); manifest.files++; } } const tf = path.join(DATA_ROOT, 'traffic'); if (fs.existsSync(tf)) { const dstT = path.join(pd, 'traffic'); await fsp.mkdir(dstT, { recursive: true }); for (const f of await fsp.readdir(tf)) { if (!f.endsWith('.json')) continue; await fsp.copyFile(path.join(tf, f), path.join(dstT, f)).catch(() => {}); manifest.files++; } } } if (wantApps) { const appsRoot = path.join(stage, 'apps'); await fsp.mkdir(appsRoot, { recursive: true }); let dirs = []; try { dirs = await fsp.readdir(COMPOSE_ROOT, { withFileTypes: true }); } catch (e) {} for (const d of dirs) { if (!d.isDirectory() || d.name.startsWith('.')) continue; let entries = []; try { entries = await fsp.readdir(path.join(COMPOSE_ROOT, d.name), { withFileTypes: true }); } catch (e) { continue; } const picked = []; for (const e of entries) { if (!e.isFile() || !CFG_FILE_RE.test(e.name)) continue; const src = path.join(COMPOSE_ROOT, d.name, e.name); const st = await fsp.stat(src).catch(() => null); if (!st || st.size > 2 * 1024 * 1024) continue; picked.push(e.name); } if (!picked.length) continue; const dst = path.join(appsRoot, d.name); await fsp.mkdir(dst, { recursive: true }); for (const f of picked) { await fsp.copyFile(path.join(COMPOSE_ROOT, d.name, f), path.join(dst, f)).catch(() => {}); manifest.files++; } manifest.appList.push(d.name); } } await fsp.writeFile(path.join(stage, 'manifest.json'), JSON.stringify(manifest, null, 2)); const out = path.join(BACKUP_DIR, name); await new Promise((resolve, reject) => { execFile('tar', ['-czf', out, '-C', stage, '.'], { timeout: 600000, maxBuffer: 8 * 1024 * 1024 }, (err) => err ? reject(err) : resolve()); }); const st = await fsp.stat(out); pushEvent('info', null, `创建备份 ${name}`, `${(st.size / 1048576).toFixed(1)}MB · ${manifest.appList.length} 个应用配置`); res.json({ ok: true, name, size: st.size, apps: manifest.appList.length, files: manifest.files }); } catch (e) { res.status(500).json({ error: e.message }); } finally { fsp.rm(stage, { recursive: true, force: true }).catch(() => {}); } }); app.get('/api/backup/:name/download', async (req, res) => { const name = String(req.params.name || ''); if (!/^[A-Za-z0-9._-]+\.tar\.gz$/.test(name) || name.includes('..')) return res.status(400).json({ error: '文件名不合法' }); const file = path.join(BACKUP_DIR, name); if (!fs.existsSync(file)) return res.status(404).json({ error: '备份不存在' }); res.download(file, name); }); app.delete('/api/backup/:name', async (req, res) => { const name = String(req.params.name || ''); if (!/^[A-Za-z0-9._-]+\.tar\.gz$/.test(name) || name.includes('..')) return res.status(400).json({ error: '文件名不合法' }); const file = path.join(BACKUP_DIR, name); if (!fs.existsSync(file)) return res.status(404).json({ error: '备份不存在' }); await fsp.rm(file, { force: true }); res.json({ ok: true }); }); /* ---------------- 启动 ---------------- */ 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); 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`));