'use strict';
/* ---------------- 基础 ---------------- */
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
let serverBuild = null;
const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false, traffic: { range: 'today', date: '' }, sel: new Set(), imgSel: new Set(), pendSel: new Set() };
const REFRESH_KEY = 'dc.refreshMs';
const SORT_KEY = 'dc.sortBy';
try { state.sortBy = JSON.parse(localStorage.getItem(SORT_KEY) || '{}') || {}; } catch (e) { state.sortBy = {}; }
state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000));
const PAUSE_KEY = 'dc.paused';
state.paused = localStorage.getItem(PAUSE_KEY) === '1';
state.lastAct = 0;
['pointerdown', 'keydown', 'wheel', 'touchstart'].forEach(ev =>
document.addEventListener(ev, () => { state.lastAct = Date.now(); }, { capture: true, passive: true }));
/* 自动刷新闸门:暂停 / 隐藏 / 正在填表 / 抽屉打开 / 表单页 / 刚有操作 → 都不重绘 */
function canAutoRefresh() {
if (state.paused) return false;
if (document.hidden) return false;
const ae = document.activeElement;
if (ae && /^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName)) return false;
const dr = document.getElementById('drawer');
if (dr && !dr.classList.contains('hidden')) return false;
if (['settings', 'backup', 'registry'].includes(state.view)) return false;
if (Date.now() - state.lastAct < 5000) return false;
return true;
}
function paintPauseBtn() {
const b = document.getElementById('pauseBtn');
if (!b) return;
b.textContent = state.paused ? '▶ 继续' : '⏸ 暂停';
b.classList.toggle('paused', state.paused);
b.title = state.paused ? '已暂停自动刷新,点此继续' : '暂停自动刷新(暂停后数据不再变化)';
}
function togglePause(force) {
state.paused = typeof force === 'boolean' ? force : !state.paused;
localStorage.setItem(PAUSE_KEY, state.paused ? '1' : '0');
paintPauseBtn();
toast(state.paused ? '已暂停自动刷新' : '已恢复自动刷新');
}
const ICONS = {
grid: '',
box: '',
pause: '',
disc: '',
repo: '',
globe: '',
bell: '',
search: '',
refresh: '',
plus: '',
power: '',
restart: '',
link: '',
more: '',
trash: '',
back: '',
};
const icon = (n) => ``;
function paintIcons(root = document) { $$('i[data-ico]', root).forEach(el => { el.outerHTML = icon(el.dataset.ico); }); }
const fmtBytes = (b) => {
if (b === undefined || b === null) return '-';
const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0, n = Math.abs(b);
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
return `${n < 10 && i > 0 ? n.toFixed(2) : Math.round(n * 10) / 10} ${u[i]}`;
};
const fmtRateShort = (b) => {
if (!b) return '0';
const u = ['B/s', 'K/s', 'M/s', 'G/s'];
let i = 0, v = b;
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
const s = v >= 100 ? String(Math.round(v)) : (Math.round(v * 10) / 10).toString();
return s.replace(/\.0$/, '') + u[i];
};
const fmtRate = (b) => (b > 0 ? fmtBytes(b) + '/s' : '0 B/s');
const fmtPct = (n) => (n >= 10 ? n.toFixed(1) : (n || 0).toFixed(2)) + '%';
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const fmtDur = (ms) => {
if (ms === null || ms === undefined || !isFinite(ms) || ms < 0) return '—';
const s = Math.floor(ms / 1000);
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
if (d > 0) return `${d} 天${h ? ' ' + h + ' 小时' : ''}`;
if (h > 0) return `${h} 小时${m ? ' ' + m + ' 分' : ''}`;
if (m > 0) return `${m} 分钟`;
return '不到 1 分钟';
};
const shortImg = (img) => {
const s = String(img || '');
if (/^sha256:/.test(s)) return s.slice(7, 19);
const last = s.split('/').pop();
return last.length > 22 ? last.slice(0, 22) + '…' : last;
};
const fmtDurCompact = (ms) => {
if (ms === null || ms === undefined || !isFinite(ms) || ms < 0) return '—';
const s = Math.floor(ms / 1000), d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
if (d > 0) return `${d}天${h ? h + '小时' : ''}`;
if (h > 0) return `${h}小时${m ? m + '分' : ''}`;
if (m > 0) return `${m}分钟`;
return '1分钟内';
};
const ago = (iso) => {
if (!iso) return '-';
const d = (Date.now() - new Date(iso).getTime()) / 1000;
if (!isFinite(d) || d < 0) return '-';
if (d < 60) return `${Math.round(d)} 秒`;
if (d < 3600) return `${Math.round(d / 60)} 分钟`;
if (d < 86400) return `${(d / 3600).toFixed(1)} 小时`;
return `${Math.floor(d / 86400)} 天`;
};
const timeStr = (t) => new Date(t).toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
async function api(url, opts) {
const r = await fetch(url, opts);
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || r.statusText);
return j;
}
function toast(msg, err) {
const t = $('#toast'); t.textContent = msg; t.className = 'toast' + (err ? ' err' : '');
clearTimeout(t._h); t._h = setTimeout(() => t.classList.add('hidden'), 2600);
}
/* ---------------- 路由 ---------------- */
const TITLES = { apps: '概览', 'apps-all': '全部应用', containers: '运行的容器', stopped: '停止的容器', images: '本地镜像', registry: '镜像仓库', networks: '网络', backup: '备份与恢复', settings: '告警设置' };
const SORTS = {
apps: [['severity', '异常优先'], ['cpu', 'CPU 占用'], ['mem', '内存占用'], ['containers', '容器数'], ['name', '名称']],
containers: [['created', '最新安装'], ['cpu', 'CPU 占用'], ['mem', '内存占用'], ['net', '网络速率'], ['io', '磁盘 IO'], ['pids', '进程数'], ['name', '名称']],
stopped: [['created', '最新安装'], ['name', '名称'], ['mem', '内存占用']],
};
function go(view) {
if (state.view !== view && state.sel) state.sel.clear();
state.view = view;
state.currentApp = null;
const navView = view === 'apps-all' ? 'apps' : view;
$$('#nav a').forEach(a => a.classList.toggle('active', a.dataset.view === navView));
$('#pageTitle').textContent = TITLES[view] || view;
const isList = ['apps', 'apps-all', 'containers', 'stopped'].includes(view);
$('#search').style.display = isList || view === 'images' ? '' : 'none';
$('#sortbox').style.display = isList ? '' : 'none';
const opts = SORTS[view] || SORTS[navView] || SORTS.containers;
const saved = state.sortBy[view] || state.sortBy[navView];
state.sort = (saved && opts.some(o => o[0] === saved)) ? saved : opts[0][0];
$('#sort').innerHTML = opts.map(([v, t]) => ``).join('');
$('#sort').value = state.sort;
$('#addBtn').textContent = view === 'registry' ? '拉取镜像' : view === 'images' ? '清理悬空镜像' : '添加容器';
clearInterval(state.timer);
if ($('#refreshSel')) $('#refreshSel').value = String(state.refreshMs);
const pb = $('#pauseBtn');
if (pb) pb.onclick = () => togglePause();
paintPauseBtn();
render();
state.timer = setInterval(() => {
if (!canAutoRefresh()) return;
if (state.view === view || state.view === 'app-detail') render(true);
}, state.refreshMs);
paintPauseBtn();
}
async function render(silent) {
const scY = window.scrollY || 0;
const viewEl = document.getElementById('view');
const scV = viewEl ? viewEl.scrollTop : 0;
try {
if (state.view === 'app-detail') {
if (state.appTab === 'containers' && state.currentApp) return openApp(state.currentApp);
return;
}
if (state.view === 'apps' || state.view === 'apps-all') return renderApps(silent);
if (state.view === 'containers') return renderContainers(silent, 'running');
if (state.view === 'stopped') return renderContainers(silent, 'stopped');
if (state.view === 'images') return renderImages();
if (state.view === 'registry') return renderRegistry();
if (state.view === 'networks') return renderNetworks();
if (state.view === 'backup') return renderBackup();
if (state.view === 'settings') return renderSettings();
} catch (e) { if (!silent) $('#view').innerHTML = `
加载失败:${esc(e.message)}
`; }
finally {
if (silent) {
window.scrollTo(0, scY);
const v2 = document.getElementById('view');
if (v2) v2.scrollTop = scV;
}
}
}
/* ---------------- 主机信息 ---------------- */
async function refreshHost() {
const h = await api('/api/host');
if (h.build) {
if (serverBuild && serverBuild !== h.build) { location.reload(); return h; }
serverBuild = h.build;
}
const navCl = $('#navContainersLabel'); if (navCl && navCl.textContent !== '运行的容器') navCl.textContent = '运行的容器';
const stamp = $('#buildStamp');
if (stamp && h.build) {
const d = new Date(Number(h.build));
const txt = `构建 ${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
if (stamp.textContent !== txt) stamp.textContent = txt;
}
$('#hostMini').innerHTML = `${esc(h.hostname)}
${h.cpus} 核 · 内存 ${fmtBytes(h.memTotal)}
运行 ${h.running} / 共 ${h.containers} 容器`;
$('#navRunning').textContent = h.running;
const ns = $('#navStopped');
if (ns) {
ns.textContent = (h.stopped || 0) + (h.pending || 0);
ns.title = `已停止容器 ${h.stopped || 0} 个 · 有镜像未启动的应用 ${h.pending || 0} 个`;
}
return h;
}
/* ---------------- 应用看板 ---------------- */
const AVATAR_COLORS = ['#1a73e8', '#7a5af8', '#12b76a', '#f79009', '#e5484d', '#0ba5ec', '#9e77ed', '#099250'];
function avatar(name) {
const s = String(name || '?');
const code = [...s].reduce((a, c) => a + c.codePointAt(0), 0);
const color = AVATAR_COLORS[code % AVATAR_COLORS.length];
const label = /^[a-zA-Z]/.test(s) ? s.slice(0, 2).toUpperCase() : [...s].slice(0, 1).join('');
return `${esc(label)}`;
}
/* ---------------- 趋势图表 ---------------- */
const CHART_META = new Map();
let chartSeq = 0;
function lineChart(points, series, unit, opts) {
opts = opts || {};
const W = 360, H = 118, PL = 4, PR = 4, PT = 12, PB = 17;
const iw = W - PL - PR, ih = H - PT - PB;
const n = Math.max(points.length, 2);
const vals = points.flatMap(p => series.map(sr => p[sr.key] || 0));
const max = opts.max || Math.max(...vals, 1) || 1;
const xAt = (i) => PL + (iw * i) / (n - 1);
const yAt = (v) => PT + ih - (Math.min(v, max) / max) * ih;
const gap = unit === 'hour' ? 4 : unit === 'day' ? 5 : 3;
const ticks = points.map((p, i) => ({ i, l: p.label })).filter(({ i }) => i % gap === 0);
const gridY = [0, 0.5, 1].map(f => PT + ih * f);
const fmtMax = opts.fmt || ((v) => String(Math.round(v)));
const cid = 'cv' + (++chartSeq);
CHART_META.set(cid, { points, series, unit });
return ``;
}
function bindChartTips() {
let tip = document.getElementById('chartTip');
if (!tip) {
tip = document.createElement('div');
tip.id = 'chartTip';
tip.className = 'chart-tip';
document.body.appendChild(tip);
}
const hide = () => { tip.style.display = 'none'; document.querySelectorAll('.ch-guide').forEach(g => g.setAttribute('opacity', '0')); };
$$('#view .tf-chart').forEach(svg => {
const meta = CHART_META.get(svg.dataset.cid);
if (!meta) return;
svg.addEventListener('mousemove', (e) => {
const r = svg.getBoundingClientRect();
const n = meta.points.length;
if (!n) return;
const ratio = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
const idx = Math.round(ratio * (n - 1));
const pt = meta.points[idx];
if (!pt) return;
const vbW = 360, PL = 4, PR = 4, PT = 12, PB = 17;
const xv = PL + ((vbW - PL - PR) * idx) / Math.max(1, n - 1);
const guide = svg.querySelector('.ch-guide');
if (guide) { guide.setAttribute('x1', xv); guide.setAttribute('x2', xv); guide.setAttribute('opacity', '1'); }
tip.innerHTML = `${esc(pt.label)}
${meta.series.map(sr =>
`${esc(sr.name || sr.key)}${sr.fmt ? sr.fmt(pt[sr.key] || 0) : fmtBytes(pt[sr.key] || 0)}
`).join('')}`;
tip.style.display = 'block';
const tw = tip.offsetWidth, th = tip.offsetHeight;
let left = e.clientX + 12, top = e.clientY - th - 10;
if (left + tw > window.innerWidth - 8) left = e.clientX - tw - 12;
if (top < 8) top = e.clientY + 14;
tip.style.left = left + 'px';
tip.style.top = top + 'px';
});
svg.addEventListener('mouseleave', hide);
});
}
async function renderApps(silent) {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
const [data, h, ev, ins, full, tf] = await Promise.all([
api(`/api/apps?filter=${state.filter}&sort=${state.sort}&order=${state.order}${q}`),
refreshHost(),
api('/api/events?limit=8'),
api('/api/insights').catch(() => null),
api('/api/apps?sort=cpu&order=desc').catch(() => null),
(state.view === 'apps' ? api(`/api/traffic?range=${state.traffic.range}${state.traffic.date && state.traffic.range === 'day' ? `&date=${state.traffic.date}` : ''}`).catch(() => null) : Promise.resolve(null)),
]);
const s = data.summary;
const disk = h.disk;
const pill = (a) => `${a.statusText}`;
const chips = [['all', '全部', s.total], ['issues', '有问题', s.critical + s.warning], ['stopped', '已停止', s.stopped], ['high', '高占用', '']];
const cardOf = (a) => `
${avatar(a.name)}
${esc(a.name)}
${a.type === 'compose' ? `Compose · ${a.total} 个容器` : '单容器'} · ${a.running}/${a.total} 运行
${pill(a)}
CPU
${fmtPct(a.cpuPctOfMachine)}
网络
↑${fmtRate(a.txBps)}
↓${fmtRate(a.rxBps)}
${a.issues.length ? `
${a.issues.slice(0, 2).map(i => `
${esc(i.text)}
`).join('')}${a.issues.length > 2 ? `
还有 ${a.issues.length - 2} 条
` : ''}
` : ''}
`;
const cards = data.items.map(cardOf).join('');
const allApps = (full && full.items) || data.items || [];
const topCpu = [...allApps].sort((x, y) => (y.cpuPctOfMachine || 0) - (x.cpuPctOfMachine || 0)).slice(0, 5);
const topMem = [...allApps].sort((x, y) => (y.mem || 0) - (x.mem || 0)).slice(0, 5);
const netOf = (a) => (a.rxBps || 0) + (a.txBps || 0);
const topNet = [...allApps].sort((x, y) => netOf(y) - netOf(x)).slice(0, 5);
const topRun = [...allApps].filter(a => a.runMs !== null && a.runMs !== undefined).sort((x, y) => y.runMs - x.runMs).slice(0, 5);
const memTotal = h.memTotal || 1;
const topRow = (a, i, val, pct, kind) => `
${i + 1}
${esc(a.name)}
${val}
`;
const maxCpu = Math.max(1, ...topCpu.map(a => a.cpuPctOfMachine || 0));
const maxMem = Math.max(1, ...topMem.map(a => a.mem || 0));
const maxNet = Math.max(1, ...topNet.map(netOf));
const maxRun = Math.max(1, ...topRun.map(a => a.runMs));
const topHtml = `
CPU 占用 Top 5占整机 · ${h.cpus} 核
${topCpu.map((a, i) => topRow(a, i, fmtPct(a.cpuPctOfMachine || 0), ((a.cpuPctOfMachine || 0) / maxCpu) * 100, 'cpu')).join('') || '
暂无数据
'}
内存占用 Top 5占整机 ${fmtBytes(memTotal)}
${topMem.map((a, i) => topRow(a, i, `${fmtBytes(a.mem || 0)}
${((a.mem || 0) / memTotal * 100).toFixed(1)}%`, ((a.mem || 0) / maxMem) * 100, 'mem')).join('') || '
暂无数据
'}
网络占用 Top 5上下行合计
${topNet.map((a, i) => topRow(a, i, `↓${fmtRateShort(a.rxBps || 0)}
↑${fmtRateShort(a.txBps || 0)}`, (netOf(a) / maxNet) * 100, 'net')).join('') || '
暂无数据
'}
运行时长 Top 5连续运行
${topRun.map((a, i) => topRow(a, i, `${fmtDurCompact(a.runMs)}
${a.running}/${a.total}`, (a.runMs / maxRun) * 100, 'run')).join('') || '
暂无数据
'}
进度条长度按各榜第一名的值等比缩放,不是占整机比例
`;
const insItems = (ins && ins.items) || [];
const shownIns = state.insightOpen ? insItems : insItems.slice(0, 4);
const insHtml = insItems.length ? `
优化建议根据当前运行状态自动分析
${ins.counts.high ? `高 ${ins.counts.high}` : ''}
${ins.counts.mid ? `中 ${ins.counts.mid}` : ''}
${ins.counts.low ? `低 ${ins.counts.low}` : ''}
${shownIns.map(i => `
${esc(i.title)}${esc(i.appName || '系统')}
${esc(i.detail)}
${i.action
? `
`
: (i.appKey ? `
` : '')}
`).join('')}
${insItems.length > 4 ? `
` : ''}
` : `
`;
const isAll = state.view === 'apps-all';
const attn = allApps.filter(a => a.severity > 0).slice(0, 6);
const totalApps = s.total;
if (isAll) {
$('#view').innerHTML = `
全部应用共 ${totalApps} 个 · 点击卡片查看详情
${chips.map(([k, t2, n]) => ``).join('')}
按状态异常优先、其次资源占用排序
`;
$('#backOverview').onclick = () => go('apps');
} else {
CHART_META.clear(); chartSeq = 0;
const tfPts = (tf && tf.points) || [];
const tfTotal = (tf && tf.total) || { rx: 0, tx: 0 };
const tfNow = (tf && tf.now) || { rx: 0, tx: 0, cpu: 0, mem: 0 };
const tfPeak = (tf && tf.peak) || { mem: 0, cpu: 0 };
const tfAvg = (tf && tf.avg) || { cpu: 0, mem: 0 };
const tfTabs = [['today', '今天'], ['yesterday', '昨天'], ['month', '近 30 天'], ['year', '近 12 个月']];
const noData = '暂无数据
';
const tfHtml = `
流量↓ ${fmtRate(tfNow.rx)} · ↑ ${fmtRate(tfNow.tx)}
${tfPts.length ? lineChart(tfPts, [{ key: 'rx', name: '下行', color: '#1a73e8', area: true, fmt: fmtBytes }, { key: 'tx', name: '上行', color: '#f79009', dash: true, fmt: fmtBytes }], tf.unit, { fmt: fmtBytes }) : noData}
CPU${fmtPct(tfNow.cpu)}
${tfPts.length ? lineChart(tfPts, [{ key: 'cpu', name: 'CPU', color: '#12b76a', area: true, fmt: (v) => v.toFixed(2) + '%' }], tf.unit, { max: Math.min(100, Math.max(2, (tfPeak.cpu || 0) * 1.25)), fmt: (v) => v.toFixed(1) + '%' }) : noData}
内存${fmtBytes(tfNow.mem)}
${tfPts.length ? lineChart(tfPts, [{ key: 'mem', name: '内存', color: '#7a5af8', area: true, fmt: fmtBytes }], tf.unit, { fmt: fmtBytes }) : noData}
`;
$('#view').innerHTML = `
应用总数
${s.total}
${s.containers} 个容器
资源占用
${fmtBytes(s.mem)}
CPU ${fmtPct(s.cpu / h.cpus)} · 磁盘可用 ${disk ? fmtBytes(disk.free) : '-'}
运行容器
${h.running}/${h.containers}
镜像 ${h.images} 个
${tfHtml}
${topHtml}
${insHtml}
需要关注的应用${attn.length ? `${attn.length} 个异常或需要注意` : '全部正常'}
${attn.length ? `${attn.map(cardOf).join('')}
` : '所有应用运行正常,无需处理
'}
最近事件
状态变化与重启记录
${ev.items.length ? ev.items.map(e => `
${timeStr(e.t)}${esc(e.title)}${esc(e.detail || '')}
`).join('') : '
暂无事件
'}
`;
$('#openAllApps').onclick = () => go('apps-all');
}
$$('#view .chip').forEach(b => b.onclick = () => { state.filter = b.dataset.filter; render(); });
$$('#view .tf-tab').forEach(b => b.onclick = () => { state.traffic.range = b.dataset.tr; state.traffic.date = ''; render(); });
const tfDate = $('#tfDate');
if (tfDate) tfDate.onchange = () => {
if (!tfDate.value) return;
state.traffic.range = 'day'; state.traffic.date = tfDate.value; render();
};
bindChartTips();
$$('#view .top-row').forEach(r => r.onclick = () => openApp(r.dataset.top));
const moreBtn = $('#insightMore');
if (moreBtn) moreBtn.onclick = () => { state.insightOpen = !state.insightOpen; render(); };
$$('#view [data-insight]').forEach(b => b.onclick = async (e) => {
e.stopPropagation();
const type = b.dataset.insight, key = b.dataset.key;
if (type === 'openApp') return openApp(key);
b.disabled = true;
try {
if (type === 'startApp') {
const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start' }) });
toast(`启动完成(${r.results.filter(x => x.ok).length}/${r.results.length})`);
} else if (type === 'pruneImages') {
const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'images' }) });
toast(`清理完成,释放 ${fmtBytes(r.reclaimed)}(${r.deleted} 个镜像)`);
} else if (type === 'pruneBuildCache') {
const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'buildCache' }) });
toast(`构建缓存已清理,释放 ${fmtBytes(r.reclaimed)}`);
}
setTimeout(render, 900);
} catch (err) { toast(err.message, true); }
b.disabled = false;
});
$$('#view .app-card').forEach(card => {
card.addEventListener('click', async (e) => {
const port = e.target.closest('.port');
if (port) { e.stopPropagation(); window.open(`http://${location.hostname}:${port.dataset.port}`, '_blank'); return; }
const b = e.target.closest('[data-app-act]');
if (!b) return openApp(card.dataset.app);
e.stopPropagation();
const act = b.dataset.appAct;
if (act === 'detail') return openApp(card.dataset.app);
if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return;
b.disabled = true;
try {
const r = await api(`/api/apps/${encodeURIComponent(card.dataset.app)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) });
const ok = r.results.filter(x => x.ok).length;
toast(`${act === 'start' ? '启动' : act === 'restart' ? '重启' : '停止'}完成(${ok}/${r.results.length})`);
setTimeout(render, 900);
} catch (err) { toast(err.message, true); }
b.disabled = false;
});
});
}
/* ---------------- 应用详情 ---------------- */
async function openApp(key) {
if (state.currentApp !== key) state.appTab = 'containers';
state.currentApp = key;
state.view = 'app-detail';
$$('#nav a').forEach(a => a.classList.remove('active'));
const a = await api(`/api/apps/${encodeURIComponent(key)}`);
$('#pageTitle').textContent = '应用详情';
const disk = null;
const conts = a.containers.map(c => `
| ${esc(c.name)} ${esc(c.service || c.image)} |
${c.state === 'running' ? (c.health === 'unhealthy' ? '异常' : '运行中') : '已停止'} |
${fmtPct(c.stats.cpu)} |
${fmtBytes(c.stats.mem)} |
↑${fmtRate(c.stats.txBps)} ↓${fmtRate(c.stats.rxBps)} |
${c.restarts || 0} |
${c.state === 'running' ? fmtDur(c.runMs !== null && c.runMs !== undefined ? c.runMs : Date.now() - Date.parse(c.startedAt)) : '—'} |
|
`).join('');
$('#view').innerHTML = `
${avatar(a.name)}
${esc(a.name)}
${a.type === 'compose' ? 'Compose 应用' : '单容器'} · ${a.running}/${a.total} 运行 · ${a.key}
${a.statusText}
${a.issues.length ? `${a.issues.map(i => `
${esc(i.text)}
`).join('')}
` : ''}
CPU 占整机
${fmtPct(a.cpuPctOfMachine)}
网络
↑${fmtRate(a.txBps)} ↓${fmtRate(a.rxBps)}
运行时长
${a.runMs === null ? '已停止' : a.runMs < 60000 ? '1 分钟内' : fmtDur(a.runMs)}
可用率
${a.uptime !== null ? a.uptime + '%' : '采样中'}
端口
${a.ports.map(p => `:${p.public}`).join(' ') || '无'}
`;
const applyAppLimits = async (cpus, memMB) => {
const btn = $('#limApply'); if (btn) { btn.disabled = true; btn.textContent = '应用中…'; }
try {
const r = await api(`/api/apps/${encodeURIComponent(key)}/limits`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cpus, memMB }) });
if (r.clearing) toast(r.note || '限制已取消');
else toast(r.applied === r.total ? `已对 ${r.total} 个容器生效` : `${r.applied}/${r.total} 个容器生效(部分不支持热更新)`);
setTimeout(() => openApp(key), 900);
} catch (e) { toast(e.message, true); if (btn) { btn.disabled = false; btn.textContent = '应用限制'; } }
};
if ($('#limApply')) $('#limApply').onclick = () => {
const cpus = Number($('#limCpu').value) || 0;
const memMB = Number($('#limMem').value) || 0;
if (!cpus && !memMB) return toast('CPU 和内存至少填一个,或点「取消限制」', true);
applyAppLimits(cpus, memMB);
};
if ($('#limClear')) $('#limClear').onclick = () => applyAppLimits(0, 0);
$('#backBtn').onclick = () => { $('#pageTitle').textContent = '概览'; go('apps'); };
$$('#view [data-app-act]').forEach(b => b.onclick = async () => {
const act = b.dataset.appAct;
if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return;
b.disabled = true;
try {
const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) });
toast(`完成(${r.results.filter(x => x.ok).length}/${r.results.length})`);
setTimeout(() => openApp(key), 1000);
} catch (e) { toast(e.message, true); b.disabled = false; }
});
$$('#view .port').forEach(p => p.onclick = () => window.open(`http://${location.hostname}:${p.dataset.port}`, '_blank'));
const body = $('#appTabBody');
const drawTab = async () => {
$$('#appTabs button').forEach(b => b.classList.toggle('active', b.dataset.atab === state.appTab));
if (state.appTab === 'containers') {
body.innerHTML = `| 容器 | 状态 | CPU | 内存 | 网络 | 重启 | 运行时长 | 操作 |
${conts}
`;
$$('#appTabBody [data-c-act]').forEach(b => b.onclick = async () => {
const act = b.dataset.cAct, id = b.dataset.id;
if (act === 'detail') return openDrawer(id);
const running = b.textContent.includes('停止');
try {
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) });
toast('已执行'); setTimeout(() => openApp(key), 900);
} catch (e) { toast(e.message, true); }
});
} else if (state.appTab === 'logs') {
body.innerHTML = `
按容器名加前缀合并显示
加载中…
`;
const load = async () => {
const r = await api(`/api/apps/${encodeURIComponent(key)}/logs?tail=${$('#appLogTail').value || 60}`);
$('#appLogBox').textContent = r.logs || '(无日志)';
};
$('#appLogReload').onclick = load;
await load();
} else {
body.innerHTML = `${a.events.length ? a.events.map(e => `
${timeStr(e.t)}${esc(e.title)}${esc(e.detail || '')}
`).join('') : '
该应用暂无事件
'}
`;
}
};
$$('#appTabs button').forEach(b => b.onclick = () => { state.appTab = b.dataset.atab; drawTab(); });
await drawTab();
}
/* ---------------- 容器列表 ---------------- */
async function renderContainers(silent, mode = 'running') {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
const filter = mode === 'stopped' ? '&all=1&state=stopped' : '&all=0';
const [data, h, pend] = await Promise.all([
api(`/api/containers?sort=${state.sort}&order=${state.order}${filter}${q}`),
refreshHost(),
mode === 'stopped' ? api('/api/pending-apps').catch(() => null) : Promise.resolve(null),
]);
const html = data.items.map(c => {
const s = c.stats;
const cpuCls = s.cpu > 80 ? 'hot' : s.cpu > 40 ? 'warn' : '';
const memCls = s.memPct > 80 ? 'hot' : s.memPct > 50 ? 'warn' : '';
const ports = c.ports.filter(p => p.public).slice(0, 2);
const linkBtn = ports.length ? `${icon('link')}` : '';
return `
${mode === 'stopped' ? `
` : ''}
${icon('box')}
${esc(c.name)}${(c.limits && (c.limits.cpus || c.limits.memMB)) ? `限 ${c.limits.cpus ? c.limits.cpus + '核' : ''}${c.limits.cpus && c.limits.memMB ? '/' : ''}${c.limits.memMB ? c.limits.memMB + 'M' : ''}` : ''}
${c.project ? '项目: ' + esc(c.project) : esc(shortImg(c.image))} · ${c.state === 'running' ? (c.runMs === null || c.runMs === undefined ? '运行中' : c.runMs < 60000 ? '刚刚启动' : '已运行 ' + fmtDurCompact(c.runMs)) : '已停止'}${c.restarts ? ` · 重启${c.restarts}` : ''}${c.created ? `` : ''}
内存
${fmtBytes(s.mem)} ${s.memPct ? s.memPct.toFixed(1) + '%' : ''}
网络
↑${fmtRate(s.txBps)} ↓${fmtRate(s.rxBps)}
磁盘 IO
R ${fmtRate(s.rdBps)} / W ${fmtRate(s.wrBps)}
${linkBtn}
${icon('power')}
${c.state === 'running' ? `${icon('restart')}` : ''}
${icon('trash')}
${icon('more')}
`;
}).join('');
const pendHtml = (mode === 'stopped' && pend && pend.items.length) ? `
有镜像但未启动的应用${pend.items.length} 个 · 扫描 ${esc((pend.root || '').replace(/^.*\/docker$/, '.../docker'))}
已选 0 / ${pend.items.length}
删除会移到回收站(compose 目录下 .trash),可恢复;不动镜像
${pend.items.map(p => `
${esc(p.name)}${p.services} 个服务
${esc(p.file.replace((pend.root || '') + '/', ''))}
${p.images.missing.length
? `缺 ${p.images.missing.length} 个镜像 · 自动拉取`
: `镜像就绪 ${p.images.present}/${p.images.total}`}
`).join('')}
已停止的容器${data.total} 个
` : '';
const label = mode === 'stopped' ? '已停止' : '运行中';
const batchHtml = (mode === 'stopped' && data.items.length) ? `
已选 ${[...state.sel].filter(id => data.items.some(c => c.id === id)).length} / ${data.items.length}
只删容器,不删数据卷
` : '';
$('#view').innerHTML = `${pendHtml}${batchHtml}${html || `${mode === 'stopped' ? '没有已停止的容器' : '没有正在运行的容器'}
`}
`;
$$('#view [data-pend-cmd]').forEach(b => b.onclick = () => {
alert(`在宿主机执行:\n\ndocker compose -f ${b.dataset.pendCmd} up -d`);
});
const startPend = async (name, el) => {
if (el) { el.disabled = true; el.dataset.txt = el.textContent; el.textContent = '启动中…'; }
try {
const r = await api('/api/pending-apps/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
toast(r.message || `已启动 ${name}`);
setTimeout(render, 1200);
} catch (e) {
toast(e.message, true);
if (el) { el.disabled = false; el.textContent = el.dataset.txt || '启动'; }
}
};
const pendNames = (pend && pend.items ? pend.items : []).map(x => x.name);
[...state.pendSel].forEach(n => { if (!pendNames.includes(n)) state.pendSel.delete(n); });
const syncPend = () => {
const n = $('#pendSelCount'); if (n) n.textContent = state.pendSel.size;
const s1 = $('#pendStartSel'); if (s1) { s1.disabled = !state.pendSel.size; s1.textContent = state.pendSel.size ? `批量启动 ${state.pendSel.size} 个` : '批量启动'; }
const d1 = $('#pendDelSel'); if (d1) { d1.disabled = !state.pendSel.size; d1.textContent = state.pendSel.size ? `批量删除 ${state.pendSel.size} 个` : '批量删除'; }
const a = $('#pendSelAll'); if (a) a.checked = state.pendSel.size > 0 && state.pendSel.size === pendNames.length;
};
$$('#view .pendsel').forEach(cb => {
cb.checked = state.pendSel.has(cb.dataset.name);
cb.onclick = (e) => { e.stopPropagation(); if (cb.checked) state.pendSel.add(cb.dataset.name); else state.pendSel.delete(cb.dataset.name); syncPend(); };
});
const psa = $('#pendSelAll');
if (psa) psa.onclick = () => {
if (psa.checked) pendNames.forEach(n => state.pendSel.add(n)); else state.pendSel.clear();
$$('#view .pendsel').forEach(cb => { cb.checked = psa.checked; });
syncPend();
};
const psb = $('#pendStartSel');
if (psb) psb.onclick = async () => {
const list = [...state.pendSel];
if (!list.length) return;
psb.disabled = true; psb.textContent = '启动中…';
try {
const r = await api('/api/pending-apps/batch-start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ names: list }) });
const fail = r.results.filter(x => !x.ok);
toast(fail.length ? `已启动 ${r.started} 个,失败 ${fail.length} 个` : `已启动 ${r.started} 个应用`);
state.pendSel.clear();
setTimeout(render, 1200);
} catch (e) { toast(e.message, true); psb.disabled = false; psb.textContent = '批量启动'; }
};
const pdb = $('#pendDelSel');
if (pdb) pdb.onclick = async () => {
const list = [...state.pendSel];
if (!list.length) return;
if (!confirm(`确定删除选中的 ${list.length} 个未启动应用?\n\n目录会移到回收站 .trash(可恢复),不删除镜像。`)) return;
pdb.disabled = true; pdb.textContent = '删除中…';
try {
const r = await api('/api/pending-apps/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ names: list }) });
const fail = r.results.filter(x => !x.ok);
toast(fail.length ? `已删除 ${r.deleted} 个,失败 ${fail.length} 个(${fail[0].error})` : `已删除 ${r.deleted} 个应用(已移入 .trash 回收站)`);
state.pendSel.clear();
setTimeout(render, 900);
} catch (e) { toast(e.message, true); pdb.disabled = false; pdb.textContent = '批量删除'; }
};
syncPend();
$$('#view [data-pend]').forEach(b => b.onclick = (e) => { e.stopPropagation(); startPend(b.dataset.pend, b); });
$$('#view [data-pend-card]').forEach(card => {
card.onclick = (e) => {
if (e.target.closest('[data-pend]') || e.target.closest('[data-pend-cmd]')) return;
startPend(card.dataset.pendCard, card.querySelector('[data-pend]'));
};
});
if (mode === 'stopped') {
const ids = data.items.map(c => c.id);
[...state.sel].forEach(id => { if (!ids.includes(id)) state.sel.delete(id); });
const syncSel = () => {
const n = $('#selCount'); if (n) n.textContent = state.sel.size;
const b = $('#batchDel'); if (b) { b.disabled = state.sel.size === 0; b.textContent = state.sel.size ? `删除选中 ${state.sel.size} 个` : '删除选中'; }
const all = $('#selAll'); if (all) all.checked = state.sel.size > 0 && state.sel.size === ids.length;
};
$$('#view .rowsel').forEach(cb => {
cb.onclick = (e) => { e.stopPropagation(); if (cb.checked) state.sel.add(cb.dataset.id); else state.sel.delete(cb.dataset.id); syncSel(); };
cb.parentElement.onclick = (e) => e.stopPropagation();
});
const selAll = $('#selAll');
if (selAll) selAll.onclick = () => {
if (selAll.checked) ids.forEach(i => state.sel.add(i)); else state.sel.clear();
$$('#view .rowsel').forEach(cb => { cb.checked = selAll.checked; });
syncSel();
};
const bd = $('#batchDel');
if (bd) bd.onclick = async () => {
const list = [...state.sel];
if (!list.length) return;
if (!confirm(`确定删除选中的 ${list.length} 个容器?\n\n只删除容器,不删除数据卷。`)) return;
bd.disabled = true; bd.textContent = '删除中…';
try {
const r = await api('/api/containers/batch-delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: list }) });
const fail = r.results.filter(x => !x.ok);
toast(fail.length ? `已删除 ${r.deleted} 个,失败 ${fail.length} 个` : `已删除 ${r.deleted} 个容器`);
state.sel.clear();
setTimeout(render, 600);
} catch (e) { toast(e.message, true); bd.disabled = false; bd.textContent = '删除选中'; }
};
syncSel();
}
$$('#view .row').forEach(row => {
row.addEventListener('click', async (e) => {
if (e.target.closest('.chk')) return;
const btn = e.target.closest('[data-act]'); const id = row.dataset.id;
if (!btn) return openDrawer(id);
e.stopPropagation();
const act = btn.dataset.act;
if (act === 'detail') return openDrawer(id);
if (act === 'open') { window.open(`http://${location.hostname}:${btn.dataset.ports.split(',')[0]}`, '_blank'); return; }
if (act === 'rm') {
if (!confirm('确定删除这个容器?(不会删除数据卷)')) return;
try { await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); } catch (err) { toast(err.message, true); }
return;
}
const running = row.querySelector('.dot').classList.contains('up');
try {
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) });
toast('已执行'); setTimeout(render, 700);
} catch (err) { toast(err.message, true); }
});
});
}
/* ---------------- 容器详情抽屉 ---------------- */
async function openDrawer(id) {
state.current = id; state.tab = 'stat';
$('#drawer').classList.remove('hidden');
$('#drawerBody').innerHTML = '加载中…
';
const d = await api(`/api/containers/${id}`);
$('#drawerName').textContent = d.info.Name.replace(/^\//, '');
$('#drawerSub').innerHTML = `${esc(d.info.Config.Image)} · ${esc(d.info.State.Status)} · ${esc(d.info.Id.slice(0, 12))}`;
const running = d.info.State.Running;
$('#drawerActions').innerHTML = `
`;
$$('#drawerActions [data-d]').forEach(b => b.onclick = async () => {
const a = b.dataset.d;
try {
if (a === 'rm') { if (!confirm('确定删除该容器?')) return; await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); closeDrawer(); render(); toast('已删除'); return; }
await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: a === 'toggle' ? (running ? 'stop' : 'start') : a }) });
toast('操作成功'); openDrawer(id); render();
} catch (e) { toast(e.message, true); }
});
drawTab(d);
const applyOne = async (cpus, memMB) => {
try {
const r = await api(`/api/containers/${id}/limits`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cpus, memMB }) });
toast(r.clearing ? (r.note || '限制已取消') : '限制已生效');
openDrawer(id); render();
} catch (e) { toast(e.message, true); }
};
if ($('#limApply1')) $('#limApply1').onclick = () => {
const cpus = Number($('#limCpu1').value) || 0;
const memMB = Number($('#limMem1').value) || 0;
if (!cpus && !memMB) return toast('CPU 和内存至少填一个,或点「取消限制」', true);
applyOne(cpus, memMB);
};
if ($('#limClear1')) $('#limClear1').onclick = () => applyOne(0, 0);
}
async function drawTab(d) {
const tab = state.tab;
$$('#drawerTabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
const body = $('#drawerBody');
const s = d.stats || {};
if (tab === 'stat') {
body.innerHTML = `
内存
${fmtBytes(s.mem || 0)}
上限 ${fmtBytes(s.memLimit || 0)} · ${(s.memPct || 0).toFixed(1)}%
网络
↑ ${fmtRate(s.txBps || 0)}
↓ ${fmtRate(s.rxBps || 0)}
累计 ↑${fmtBytes(s.tx || 0)} ↓${fmtBytes(s.rx || 0)}
磁盘 IO
读 ${fmtRate(s.rdBps || 0)}
写 ${fmtRate(s.wrBps || 0)}
累计读 ${fmtBytes(s.rd || 0)} / 写 ${fmtBytes(s.wr || 0)}
重启策略
${esc(d.restartPolicy)}
退出码 ${d.exitCode ?? 0}${d.health ? ' · ' + esc(d.health) : ''}
CPU 曲线(约 12 分钟)
当前 ${fmtPct(s.cpu || 0)}
内存曲线
当前 ${fmtBytes(s.mem || 0)}
网络速率
基本信息
安装时间
${d.info.Created ? esc(new Date(d.info.Created).toLocaleString('zh-CN')) : '-'}
启动时间
${esc(d.startedAt || '-')}
镜像
${esc(d.info.Config.Image)}
命令
${esc([].concat(d.entrypoint || [], d.cmd || []).join(' ') || '-')}
端口
${Object.entries(d.ports || {}).map(([p, b]) => `${p} → ${(b || []).map(x => x.HostPort).join(',') || '-'}`).join('
') || '-'}
容器 ID
${esc(d.info.Id)}
当前限制
${(d.info.HostConfig && (d.info.HostConfig.NanoCpus || d.info.HostConfig.Memory)) ? `${d.info.HostConfig.NanoCpus ? (d.info.HostConfig.NanoCpus / 1e9) + ' 核' : '不限 CPU'} / ${d.info.HostConfig.Memory ? Math.round(d.info.HostConfig.Memory / 1048576) + ' MB' : '不限内存'}` : '未设置'}
`;
const hist = d.history || [];
drawChart(body, 'cpu', hist.map(x => x.c), v => v.toFixed(1) + '%', '#1a73e8');
drawChart(body, 'mem', hist.map(x => x.m / 1048576), v => v.toFixed(0) + ' MB', '#7a5af8');
drawChart(body, 'net', hist.map(x => (x.rx || 0) + (x.tx || 0)), v => fmtRate(v), '#12b76a');
} else if (tab === 'logs') {
body.innerHTML = `
加载中…
`;
let es = null;
const startStream = () => {
if (es) es.close();
es = new EventSource(`/api/containers/${state.current}/logs/stream?tail=${$('#logTail').value || 200}`);
es.onmessage = (ev) => {
const box = $('#logBox'); if (!box) return;
try { box.textContent += JSON.parse(ev.data); } catch (e) {}
box.scrollTop = box.scrollHeight;
};
};
$('#logReload').onclick = async () => {
if (es) { es.close(); es = null; }
const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`);
$('#logBox').textContent = r.logs || '(无日志)';
if ($('#logLive').checked) startStream();
};
$('#logLive').onchange = (e) => { if (e.target.checked) startStream(); else if (es) { es.close(); es = null; } };
const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`);
$('#logBox').textContent = r.logs || '(无日志)';
if ($('#logLive').checked) startStream();
} else if (tab === 'env') {
body.innerHTML = `环境变量
${(d.env || []).map(e => `
${esc(e.split('=')[0])}
${esc(e.split('=').slice(1).join('='))}
`).join('') || '
-
-
'}
`;
} else {
body.innerHTML = `
挂载
| 宿主机路径 / 卷 | 容器路径 | 模式 |
${(d.mounts || []).map(m => `| ${esc(m.Source || m.Name || '')} | ${esc(m.Destination)} | ${m.RW ? '读写' : '只读'} |
`).join('') || '| 无挂载 |
'}
网络
| 网络 | IP | 网关 |
${Object.entries(d.networks || {}).map(([n, v]) => `| ${esc(n)} | ${esc(v.IPAddress || '-')} | ${esc(v.Gateway || '-')} |
`).join('') || '| 无网络 |
'}
`;
}
}
function drawChart(root, which, values, fmt, color) {
const cv = root.querySelector(`canvas[data-chart="${which}"]`);
if (!cv) return;
const dpr = window.devicePixelRatio || 1;
const w = cv.clientWidth || 600, hgt = cv.clientHeight || 90;
cv.width = w * dpr; cv.height = hgt * dpr;
const ctx = cv.getContext('2d'); ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, w, hgt);
if (!values || values.length < 2) { ctx.fillStyle = '#98a2b3'; ctx.font = '12px sans-serif'; ctx.fillText('采集中…', 12, hgt / 2); return; }
const max = Math.max(...values, 1) * 1.15, pad = 8;
const x = i => pad + (w - pad * 2) * i / (values.length - 1);
const y = v => hgt - pad - (hgt - pad * 2) * (v / max);
ctx.beginPath(); ctx.moveTo(x(0), y(values[0]));
values.forEach((v, i) => ctx.lineTo(x(i), y(v)));
ctx.strokeStyle = color; ctx.lineWidth = 1.8; ctx.lineJoin = 'round'; ctx.stroke();
ctx.lineTo(x(values.length - 1), hgt - pad); ctx.lineTo(x(0), hgt - pad); ctx.closePath();
const g = ctx.createLinearGradient(0, 0, 0, hgt); g.addColorStop(0, color + '33'); g.addColorStop(1, color + '05');
ctx.fillStyle = g; ctx.fill();
ctx.fillStyle = '#98a2b3'; ctx.font = '11px sans-serif';
ctx.fillText(fmt(max / 1.15), 10, 14);
ctx.fillText(fmt(values[values.length - 1]), Math.max(10, w - 70), hgt - 10);
}
/* ---------------- 镜像 / 仓库 / 网络 / 设置 ---------------- */
async function renderImages() {
const data = await api('/api/images');
const imgs = data.items || [];
const s = data.summary || { total: imgs.length, totalSize: 0, inUse: 0, deletable: 0, deletableSize: 0 };
const useCell = (i) => {
if (i.running && i.running.length) {
return `运行中 ${i.running.length} 个容器`;
}
if (i.stopped && i.stopped.length) {
return `已停止容器引用 ${i.stopped.length}`;
}
return '未使用';
};
const batchBar = `
已选 ${[...state.imgSel].filter(id => imgs.some(i => i.id === id)).length} / ${imgs.length}
批量导出会打包成一个 tar.gz
`;
$('#view').innerHTML = `${batchBar}
`;
const idsAll = imgs.map(i => i.id);
[...state.imgSel].forEach(id => { if (!idsAll.includes(id)) state.imgSel.delete(id); });
const syncImgSel = () => {
const n = $('#imgSelCount'); if (n) n.textContent = state.imgSel.size;
const b = $('#imgExportSel'); if (b) { b.disabled = state.imgSel.size === 0; b.textContent = state.imgSel.size ? `导出选中 ${state.imgSel.size} 个` : '导出选中'; }
const d = $('#imgDelSel'); if (d) { d.disabled = state.imgSel.size === 0; d.textContent = state.imgSel.size ? `删除选中 ${state.imgSel.size} 个` : '删除选中'; }
const a = $('#imgSelAll'); if (a) a.checked = state.imgSel.size > 0 && state.imgSel.size === idsAll.length;
};
$$('#view .imgsel').forEach(cb => {
cb.onclick = (e) => { e.stopPropagation(); if (cb.checked) state.imgSel.add(cb.dataset.id); else state.imgSel.delete(cb.dataset.id); syncImgSel(); };
});
const sa = $('#imgSelAll');
if (sa) sa.onclick = () => {
if (sa.checked) idsAll.forEach(i => state.imgSel.add(i)); else state.imgSel.clear();
$$('#view .imgsel').forEach(cb => { cb.checked = sa.checked; });
syncImgSel();
};
const imp = $('#imgImport');
if (imp) imp.onclick = () => $('#imgFile').click();
const fileInp = $('#imgFile');
if (fileInp) fileInp.onchange = () => {
const f = fileInp.files && fileInp.files[0];
if (!f) return;
const mb = (f.size / 1048576).toFixed(1);
if (!confirm(`导入镜像文件 ${f.name}(${mb} MB)?\n\n支持 docker save 导出的 .tar / .tar.gz,导入期间请勿关闭页面。`)) { fileInp.value = ''; return; }
const btn = $('#imgImport');
btn.disabled = true;
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/images/import');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) btn.textContent = `上传 ${Math.round((e.loaded / e.total) * 100)}%`;
};
xhr.onload = () => {
btn.disabled = false; btn.textContent = '导入镜像';
fileInp.value = '';
try {
const r = JSON.parse(xhr.responseText);
if (xhr.status === 200 && r.ok) {
toast(r.count ? `已导入 ${r.count} 个镜像:${r.loaded.slice(0, 3).join('、')}` : '导入完成(未识别到镜像名)');
setTimeout(render, 800);
} else toast(r.error || '导入失败', true);
} catch (e) { toast('导入失败:' + xhr.responseText.slice(0, 120), true); }
};
xhr.onerror = () => { btn.disabled = false; btn.textContent = '导入镜像'; toast('导入失败(网络错误)', true); };
xhr.send(f);
};
const bd = $('#imgDelSel');
if (bd) bd.onclick = async () => {
const list = [...state.imgSel];
if (!list.length) return;
if (!confirm(`确定删除选中的 ${list.length} 个镜像?\n\n被容器占用的镜像会自动跳过(不删容器、不删卷)。`)) return;
bd.disabled = true; bd.textContent = '删除中…';
try {
const r = await api('/api/images/batch-delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: list }) });
const fail = r.results.filter(x => !x.ok);
toast(fail.length ? `已删除 ${r.deleted} 个,跳过 ${fail.length} 个(${fail[0].error})` : `已删除 ${r.deleted} 个镜像`);
state.imgSel.clear();
setTimeout(render, 600);
} catch (e) { toast(e.message, true); bd.disabled = false; bd.textContent = '删除选中'; }
};
const be = $('#imgExportSel');
if (be) be.onclick = () => {
let list = [...state.imgSel];
if (!list.length) return;
if (list.length > 40) { list = list.slice(0, 40); toast('一次最多导出 40 个镜像,已取前 40 个'); }
const a = document.createElement('a');
a.href = `/api/images/export?ids=${encodeURIComponent(list.join(','))}`;
document.body.appendChild(a); a.click(); a.remove();
toast(`开始导出 ${list.length} 个镜像(一个 tar.gz),下载中…`);
};
syncImgSel();
$$('#view [data-export]').forEach(b => b.onclick = () => {
const id = b.dataset.export;
const a = document.createElement('a');
a.href = `/api/images/${encodeURIComponent(id)}/export`;
a.download = '';
document.body.appendChild(a); a.click(); a.remove();
toast('开始导出,浏览器下载中…(大镜像可能需要 1-2 分钟)');
});
$$('#view [data-img]').forEach(b => b.onclick = async () => {
if (!confirm('确定删除该镜像?')) return;
try { await api(`/api/images/${encodeURIComponent(b.dataset.img)}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); }
catch (e) { toast(e.message, true); }
});
}
async function renderRegistry() {
$('#view').innerHTML = `
拉取镜像
国内建议用加速前缀:docker.1ms.run/library/nginx:latest
等待操作…
批量 Compose 部署
多段用 --- 分隔,每段一个项目
加载中…
识别到 0 个项目
支持 # 目录: # 项目: # ENV: KEY=VALUE(也认 dir/project/env)
等待操作…
常用镜像
${['nginx:latest', 'redis:7-alpine', 'postgres:17', 'mysql:8', 'mongo:8', 'louislam/uptime-kuma:2', 'jellyfin/jellyfin:latest'].map(t => ``).join('')}
`;
const doPull = (name) => {
const box = $('#pullLog'); box.textContent = '';
fetch('/api/images/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: name }) })
.then(async (resp) => {
const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf = '';
while (true) {
const { done, value } = await reader.read(); if (done) break;
buf += dec.decode(value, { stream: true });
const parts = buf.split('\n\n'); buf = parts.pop();
for (const p of parts) {
const line = p.replace(/^data: /, ''); if (!line) continue;
try {
const j = JSON.parse(line);
if (j.error) box.textContent += `\n❌ ${j.error}`;
else if (j.status) box.textContent += `\n${j.status}${j.progress ? ' ' + j.progress : ''}`;
if (j.done) box.textContent += '\n✅ 完成';
} catch (e) {}
}
box.scrollTop = box.scrollHeight;
}
}).catch(e => box.textContent += `\n❌ ${e.message}`);
};
$('#pullBtn').onclick = () => { const n = $('#pullName').value.trim(); if (n) doPull(n); };
$$('#view [data-pull]').forEach(b => b.onclick = () => { $('#pullName').value = b.dataset.pull; doPull(b.dataset.pull); });
/* 批量 Compose 部署 */
const parseBundle = () => {
const prefix = ($('#depPrefix').value || '').trim().replace(/^\/+|\/+$/g, '');
const text = $('#depText').value || '';
const items = [];
for (const block of text.split(/^\s*---\s*$/m)) {
let dir = '', project = '', env = {};
const body = [];
for (const raw of block.split('\n')) {
const md = raw.match(/^\s*#\s*(?:目录|dir|directory)\s*[::]\s*(.+)$/i);
const mp = raw.match(/^\s*#\s*(?:项目|project|name)\s*[::]\s*(.+)$/i);
const me = raw.match(/^\s*#\s*(?:env|参数|变量)\s*[::]\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/i);
if (md) { dir = md[1].trim(); continue; }
if (mp) { project = mp[1].trim(); continue; }
if (me) { env[me[1]] = me[2].trim(); continue; }
body.push(raw);
}
const compose = body.join('\n').trim();
if (!compose) continue;
const fullDir = [prefix, dir || project].filter(Boolean).join('/').replace(/^\/+/, '');
items.push({ dir: fullDir, project: project || (dir || '').split('/').pop(), env, compose });
}
return items;
};
const refreshPreview = () => {
const items = parseBundle();
$('#depPreview').innerHTML = items.length
? `识别到 ${items.length} 个项目:` + items.map(i => `${esc(i.dir || '(未填目录)')}${i.env && Object.keys(i.env).length ? ` · ${Object.keys(i.env).length} 个参数` : ''}`).join(' ')
: '识别到 0 个项目';
$('#depRun').disabled = items.length === 0;
};
$('#depText').addEventListener('input', refreshPreview);
$('#depPrefix').addEventListener('input', refreshPreview);
$('#depClear').onclick = () => { $('#depLog').textContent = '等待操作…'; };
$('#depRun').onclick = async () => {
const items = parseBundle();
if (!items.length) return toast('没有可部署的项目', true);
const bad = items.filter(i => !i.dir);
if (bad.length) return toast('有项目没填目录(可填安装目录前缀)', true);
if (!confirm(`确定部署 ${items.length} 个 Compose 项目?\n\n目录:${items.map(i => i.dir).slice(0, 4).join('、')}${items.length > 4 ? ' 等' : ''}\n已存在的目录会覆盖其中的 docker-compose.yml 与 .env`)) return;
const btn = $('#depRun'); btn.disabled = true; btn.textContent = '部署中…';
const box = $('#depLog'); box.textContent = '';
try {
const r = await api('/api/compose/deploy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ items }) });
for (const x of r.results) {
box.textContent += `${x.ok ? '✅' : '❌'} ${x.dir}${x.project ? ' (' + x.project + ')' : ''}\n`;
if (x.output) box.textContent += x.output.split('\n').slice(-4).map(l => ' ' + l).join('\n') + '\n';
if (x.error && !x.output) box.textContent += ' ' + x.error + '\n';
}
const fail = r.results.filter(x => !x.ok);
toast(fail.length ? `部署 ${r.deployed} 个,失败 ${fail.length} 个` : `已部署 ${r.deployed} 个项目`);
box.scrollTop = box.scrollHeight;
} catch (e) { box.textContent = '❌ ' + e.message; toast(e.message, true); }
btn.disabled = false; btn.textContent = '批量部署';
refreshPreview();
};
api('/api/host').then(h => { if ($('#depRoot')) $('#depRoot').textContent = h.composeRoot || '(见服务端配置)'; }).catch(() => {});
refreshPreview();
}
async function renderNetworks() {
const nets = await api('/api/networks');
const canDel = nets.filter(n => n.canDelete).length;
$('#view').innerHTML = `
| 网络名 | 驱动 | 子网 | 网关 | 容器数 | 范围 | |
${nets.map(n => `
| ${esc(n.name)}${n.internal ? ' 内部' : ''}${n.builtin ? ' 内置' : ''} |
${esc(n.driver)} |
${n.subnet.map(esc).join(' ') || '-'} |
${n.gateway.map(esc).join(' ') || '-'} |
${n.containers} |
${esc(n.scope)} |
${n.canDelete
? ``
: `${n.builtin ? '内置,不可删除' : `使用中 ${n.containers}`}`} |
`).join('')}
`;
$('#netCreate').onclick = async () => {
const name = $('#netName').value.trim();
if (!name) return toast('请填写网络名', true);
const btn = $('#netCreate');
btn.disabled = true; btn.textContent = '创建中…';
try {
const r = await api('/api/networks', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name, driver: $('#netDriver').value,
subnet: $('#netSubnet').value.trim(), gateway: $('#netGw').value.trim(),
internal: $('#netInternal').checked,
}),
});
toast(`已创建网络 ${r.name}`);
render();
} catch (e) { toast(e.message, true); btn.disabled = false; btn.textContent = '创建'; }
};
$$('#view [data-net]').forEach(b => b.onclick = async () => {
if (!confirm('确定删除该网络?')) return;
try { await api(`/api/networks/${encodeURIComponent(b.dataset.net)}`, { method: 'DELETE' }); toast('已删除'); render(); }
catch (e) { toast(e.message, true); }
});
}
async function renderBackup() {
const data = await api('/api/backup');
const items = data.items || [];
$('#view').innerHTML = `
| 备份文件 | 大小 | 创建时间 | |
${items.map(b => `
| ${esc(b.name)} |
${fmtBytes(b.size)} |
${new Date(b.time).toLocaleString('zh-CN')} |
|
`).join('') || '| 还没有备份 |
'}
`;
$('#bkCreate').onclick = async () => {
const btn = $('#bkCreate');
btn.disabled = true; btn.textContent = '打包中…'; $('#bkHint').textContent = '正在打包,数据多时需要几十秒';
try {
const r = await api('/api/backup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ panel: $('#bkPanel').checked, apps: $('#bkApps').checked }) });
toast(`已生成备份 ${r.name}(${fmtBytes(r.size)}${r.apps ? ` · ${r.apps} 个应用配置` : ''})`);
setTimeout(render, 500);
} catch (e) { toast(e.message, true); btn.disabled = false; btn.textContent = '立即备份'; $('#bkHint').textContent = '备份失败'; }
};
$$('#view [data-bkdl]').forEach(b => b.onclick = () => {
const a = document.createElement('a');
a.href = `/api/backup/${encodeURIComponent(b.dataset.bkdl)}/download`;
document.body.appendChild(a); a.click(); a.remove();
});
$$('#view [data-bkdel]').forEach(b => b.onclick = async () => {
if (!confirm('确定删除该备份文件?')) return;
try { await api(`/api/backup/${encodeURIComponent(b.dataset.bkdel)}`, { method: 'DELETE' }); toast('已删除'); render(); }
catch (e) { toast(e.message, true); }
});
}
async function renderSettings() {
const s = await api('/api/settings');
$('#view').innerHTML = `
`;
$('#saveBtn').onclick = async () => {
try {
await api('/api/settings', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
thresholds: { cpu: Number($('#th_cpu').value), mem: Number($('#th_mem').value) },
debounceMinutes: Number($('#th_debounce').value),
webhook: $('#th_webhook').value,
notify: $('#th_notify').checked,
}),
});
toast('已保存');
} catch (e) { toast(e.message, true); }
};
$('#testBtn').onclick = async () => {
try { await api('/api/settings/test', { method: 'POST' }); $('#setLog').textContent = '测试推送已发送'; toast('已发送'); }
catch (e) { $('#setLog').textContent = '推送失败:' + e.message; toast(e.message, true); }
};
$('#eventBtn').onclick = async () => {
const ev = await api('/api/events?limit=50');
$('#setLog').textContent = ev.items.length ? ev.items.map(e => `${timeStr(e.t)} [${e.level}] ${e.title} — ${e.detail}`).join('\n') : '暂无事件';
};
}
/* ---------------- 添加容器 ---------------- */
function openAddModal() {
if (state.view === 'registry') { go('registry'); return; }
if (state.view === 'images') return pruneImages();
$('#modalTitle').textContent = '添加容器';
$('#modalBody').innerHTML = `
`;
$('#modal').classList.remove('hidden');
$('#modalOk').onclick = async () => {
const image = $('#f_image').value.trim(); if (!image) return toast('请填写镜像', true);
const ports = $('#f_ports').value.split('\n').map(l => l.trim()).filter(Boolean).map(l => {
const [host, cont] = l.split(':');
return { host: Number(host), container: Number(cont || host) };
});
const body = {
image, name: $('#f_name').value.trim() || undefined, ports,
env: $('#f_env').value.split('\n').map(s => s.trim()).filter(Boolean),
volumes: $('#f_vol').value.split('\n').map(s => s.trim()).filter(Boolean),
restart: $('#f_restart').value.trim() || 'always',
};
$('#modalOk').disabled = true; $('#modalOk').textContent = '创建中…';
try { await api('/api/containers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); toast('创建成功'); $('#modal').classList.add('hidden'); render(); }
catch (e) { toast(e.message, true); }
$('#modalOk').disabled = false; $('#modalOk').textContent = '确定';
};
}
async function pruneImages() {
if (!confirm('清理未被使用的悬空镜像?')) return;
try { const r = await api('/api/images/prune', { method: 'POST' }); toast(`已清理,释放 ${fmtBytes(r.SpaceReclaimed || 0)}`); render(); }
catch (e) { toast(e.message, true); }
}
/* ---------------- 事件绑定 ---------------- */
$('#nav').addEventListener('click', e => { const a = e.target.closest('a'); if (a) go(a.dataset.view); });
let qTimer = null;
$('#search').addEventListener('input', e => { state.q = e.target.value; clearTimeout(qTimer); qTimer = setTimeout(() => { if (state.currentApp) return; render(); }, 250); });
$('#sort').addEventListener('change', e => {
state.sort = e.target.value;
state.sortBy[state.view] = state.sort;
localStorage.setItem(SORT_KEY, JSON.stringify(state.sortBy));
render();
});
$('#orderBtn').addEventListener('click', () => { state.order = state.order === 'desc' ? 'asc' : 'desc'; $('#orderBtn').textContent = state.order === 'desc' ? '降序 ↓' : '升序 ↑'; render(); });
$('#refreshBtn').addEventListener('click', () => render());
$('#refreshSel').addEventListener('change', (e) => {
state.refreshMs = Math.min(30000, Math.max(1000, Number(e.target.value) || 3000));
localStorage.setItem(REFRESH_KEY, state.refreshMs);
clearInterval(state.timer);
const view = state.view;
state.timer = setInterval(() => {
if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true);
}, state.refreshMs);
toast(`刷新间隔已设为 ${state.refreshMs / 1000} 秒`);
});
$('#addBtn').addEventListener('click', openAddModal);
$('#drawerClose').onclick = () => $('#drawer').classList.add('hidden');
$('#drawerMask').onclick = () => $('#drawer').classList.add('hidden');
$('#drawerTabs').addEventListener('click', async e => {
const b = e.target.closest('button'); if (!b) return;
state.tab = b.dataset.tab;
if (state.current) drawTab(await api(`/api/containers/${state.current}`));
});
$('#modalCancel').onclick = () => $('#modal').classList.add('hidden');
$('#modalMask').onclick = () => $('#modal').classList.add('hidden');
document.addEventListener('keydown', e => { if (e.key === 'Escape') { $('#modal').classList.add('hidden'); $('#drawer').classList.add('hidden'); } });
paintIcons();
go('apps');