'use strict'; /* ---------------- 基础 ---------------- */ const $ = (s, r = document) => r.querySelector(s); const $$ = (s, r = document) => [...r.querySelectorAll(s)]; const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false }; const REFRESH_KEY = 'dc.refreshMs'; state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000)); const ICONS = { grid: '', box: '', pause: '', disc: '', repo: '', globe: '', bell: '', search: '', refresh: '', plus: '', power: '', restart: '', link: '', more: '', trash: '', back: '', }; const icon = (n) => `${ICONS[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 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 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: '概览', containers: '运行的容器', stopped: '停止的容器', images: '本地镜像', registry: '镜像仓库', networks: '网络', settings: '告警设置' }; const SORTS = { apps: [['severity', '异常优先'], ['cpu', 'CPU 占用'], ['mem', '内存占用'], ['containers', '容器数'], ['name', '名称']], containers: [['cpu', 'CPU 占用'], ['mem', '内存占用'], ['net', '网络速率'], ['io', '磁盘 IO'], ['pids', '进程数'], ['name', '名称']], stopped: [['name', '名称'], ['mem', '内存占用']], }; function go(view) { state.view = view; state.currentApp = null; $$('#nav a').forEach(a => a.classList.toggle('active', a.dataset.view === view)); $('#pageTitle').textContent = TITLES[view] || view; const isList = ['apps', 'containers', 'stopped'].includes(view); $('#search').style.display = isList || view === 'images' ? '' : 'none'; $('#sortbox').style.display = isList ? '' : 'none'; const opts = SORTS[view] || SORTS.containers; if (state.sort && !opts.some(o => o[0] === state.sort)) state.sort = 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); render(); state.timer = setInterval(() => { if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true); }, state.refreshMs); } async function render(silent) { try { if (state.view === 'app-detail') { if (state.appTab === 'containers' && state.currentApp) return openApp(state.currentApp); return; } if (state.view === 'apps') 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 === 'settings') return renderSettings(); } catch (e) { if (!silent) $('#view').innerHTML = `
加载失败:${esc(e.message)}
`; } } /* ---------------- 主机信息 ---------------- */ async function refreshHost() { const h = await api('/api/host'); $('#hostMini').innerHTML = `${esc(h.hostname)}
${h.cpus} 核 · 内存 ${fmtBytes(h.memTotal)}
运行 ${h.running} / 共 ${h.containers} 容器`; $('#navRunning').textContent = h.running; $('#navStopped').textContent = (h.stopped || 0) + (h.pending || 0); $('#navStopped').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)}`; } async function renderApps(silent) { const q = state.q ? `&q=${encodeURIComponent(state.q)}` : ''; const [data, h, ev, ins] = 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), ]); const s = data.summary; $('#navIssues').textContent = s.critical + s.warning; $('#navIssues').className = 'nav-badge' + (s.critical ? ' alert' : s.warning ? ' warn' : ''); const disk = h.disk; const pill = (a) => `${a.statusText}`; const chips = [['all', '全部', s.total], ['issues', '有问题', s.critical + s.warning], ['stopped', '已停止', s.stopped], ['high', '高占用', '']]; const cards = data.items.map(a => `
${avatar(a.name)}
${esc(a.name)}
${a.type === 'compose' ? `Compose · ${a.total} 个容器` : '单容器'} · ${a.running}/${a.total} 运行
${pill(a)}
CPU
${fmtPct(a.cpuPctOfMachine)}
内存
${fmtBytes(a.mem)}
网络
↑${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} 条
` : ''}
` : ''}
${a.ports.slice(0, 3).map(p => `:${p.public}`).join('') || '无对外端口'}
${a.runMs === null ? '未运行' : a.runMs < 60000 ? '刚刚启动' : `已运行 ${fmtDur(a.runMs)}`} · ${a.uptime !== null ? `可用率 ${a.uptime}%` : '采样中'}${a.restarts ? ` · 重启 ${a.restarts}` : ''}
`).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 ? `` : ''}
` : `
优化建议当前没有需要优化的项,配置状态良好
`; $('#view').innerHTML = `
应用总数
${s.total}
${s.containers} 个容器
异常
${s.critical}
需要立即处理
注意
${s.warning}
建议关注
资源占用
${fmtBytes(s.mem)}
CPU ${fmtPct(s.cpu / h.cpus)} · 磁盘可用 ${disk ? fmtBytes(disk.free) : '-'}
运行容器
${h.running}/${h.containers}
镜像 ${h.images} 个
${insHtml}
${chips.map(([k, t, n]) => ``).join('')} 按状态异常优先、其次资源占用排序
${cards || '
没有匹配的应用
'}

最近事件

状态变化与重启记录
${ev.items.length ? ev.items.map(e => `
${timeStr(e.t)}
${esc(e.title)}
${esc(e.detail || '')}
`).join('') : '
暂无事件
'}
`; $$('#view .chip').forEach(b => b.onclick = () => { state.filter = b.dataset.filter; render(); }); 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)}
内存合计
${fmtBytes(a.mem)}
网络
↑${fmtRate(a.txBps)} ↓${fmtRate(a.rxBps)}
重启总数
${a.restarts}
运行时长
${a.runMs === null ? '已停止' : a.runMs < 60000 ? '1 分钟内' : fmtDur(a.runMs)}
可用率
${a.uptime !== null ? a.uptime + '%' : '采样中'}
端口
${a.ports.map(p => `:${p.public}`).join(' ') || '无'}
`; $('#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 = `${conts}
容器状态CPU内存网络重启运行时长操作
`; $$('#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 `
${icon('box')}
${esc(c.name)}
${c.project ? '项目: ' + esc(c.project) : esc(c.image.split('/').pop())} · ${esc(c.status)}${c.restarts ? ` · 重启${c.restarts}` : ''}
CPU
${fmtPct(s.cpu)}
内存
${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'))}
${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' ? '已停止' : '运行中'; $('#view').innerHTML = `${pendHtml}${html || `
${mode === 'stopped' ? '没有已停止的容器' : '没有正在运行的容器'}
`}
共 ${data.total} 个${label}容器 · 排序:${({ cpu: 'CPU', mem: '内存', net: '网络', io: '磁盘IO', pids: '进程数', name: '名称' })[state.sort] || state.sort} ${state.order === 'desc' ? '降序' : '升序'} · 每 ${state.refreshMs / 1000} 秒刷新${h.disk ? ` · /vol1 可用 ${fmtBytes(h.disk.free)}` : ''}
`; $$('#view [data-pend-cmd]').forEach(b => b.onclick = () => { alert(`在宿主机执行:\n\ndocker compose -f ${b.dataset.pendCmd} up -d`); }); $$('#view [data-pend]').forEach(b => b.onclick = async () => { const name = b.dataset.pend; if (!confirm(`启动应用「${name}」?\n\n将执行 docker compose up -d,会创建并运行该项目下的容器。`)) return; b.disabled = true; b.textContent = '启动中…'; try { const r = await api('/api/pending-apps/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) }); if (r.ok) { toast(`「${name}」已启动`); setTimeout(() => render(), 1500); } else { alert(`启动失败:\n\n${r.output || '未知错误'}`); b.disabled = false; b.textContent = '启动'; } } catch (e) { toast(e.message, true); b.disabled = false; b.textContent = '启动'; } }); $$('#view .row').forEach(row => { row.addEventListener('click', async (e) => { 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); } 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 = `
CPU
${fmtPct(s.cpu || 0)}
内存
${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)}
进程数
${s.pids || 0}
重启策略
${esc(d.restartPolicy)}
退出码 ${d.exitCode ?? 0}${d.health ? ' · ' + esc(d.health) : ''}

CPU 曲线(约 12 分钟)

当前 ${fmtPct(s.cpu || 0)}

内存曲线

当前 ${fmtBytes(s.mem || 0)}

网络速率

基本信息

启动时间
${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)}
`; 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 => ``).join('') || ''}
宿主机路径 / 卷容器路径模式
${esc(m.Source || m.Name || '')}${esc(m.Destination)}${m.RW ? '读写' : '只读'}
无挂载

网络

${Object.entries(d.networks || {}).map(([n, v]) => ``).join('') || ''}
网络IP网关
${esc(n)}${esc(v.IPAddress || '-')}${esc(v.Gateway || '-')}
无网络
`; } } 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 imgs = await api('/api/images'); const total = imgs.reduce((a, b) => a + b.size, 0); $('#view').innerHTML = ` ${imgs.map(i => ``).join('')}
镜像ID大小创建
${(i.tags.length ? i.tags : [':']).map(t => `${esc(t)}`).join(' ')} ${esc(i.shortId)}${fmtBytes(i.size)} ${new Date(i.created * 1000).toLocaleDateString('zh-CN')}
共 ${imgs.length} 个镜像 · 合计 ${fmtBytes(total)}
`; $$('#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
等待操作…

常用镜像

${['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); }); } async function renderNetworks() { const nets = await api('/api/networks'); $('#view').innerHTML = ` ${nets.map(n => ``).join('')}
网络名驱动子网网关容器数范围
${esc(n.name)}${n.internal ? ' 内部' : ''}${esc(n.driver)} ${n.subnet.map(esc).join('
') || '-'}
${n.gateway.map(esc).join('
') || '-'}
${n.containers}${esc(n.scope)}
共 ${nets.length} 个网络
`; } async function renderSettings() { const s = await api('/api/settings'); $('#view').innerHTML = `

告警规则

%
%
分钟
容器未运行、健康检查失败、重启次数增加、超过资源阈值时产生事件;「异常」级事件按上面的间隔去重后推送到 webhook(POST JSON:title / level / app / detail / time / host)。
—
`; $('#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; 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');