diff --git a/CHANGELOG.md b/CHANGELOG.md index 4104dd8..c8b5760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # 更新日志 +## 2026-10-26 → ✨ 未启动应用支持批量启动与批量删除 + +- ✨ 「有镜像但未启动的应用」卡片前加复选框,顶部批量条:全选 / 已选 N / 共 M / 「批量启动 N 个」/「批量删除 N 个」 +- ✨ 批量启动逐个执行 `docker compose up -d`,返回每个应用的成功/失败与最后几行输出,完成后自动刷新 +- ✨ 批量删除**移到回收站 `COMPOSE_ROOT/.trash/<名称>-<时间戳>`**,可手动搬回恢复;不动镜像、不动卷 +- 🔧 新增 `POST /api/pending-apps/batch-start`(单批 20 个,串行执行避免打满)、`POST /api/pending-apps/delete`(`purge:true` 可彻底删) +- 🔧 删除前校验:项目仍有容器时拒绝并提示先删容器;目录必须位于扫描根内(防越界删除) +- 🔧 回收站放在 compose 根目录下的 `.trash`:容器内 `/data` 与 `/vol1` 是不同挂载点,跨设备 rename 会报 `EXDEV`;同一文件系统下 rename 即时完成,另有 `cp + rm` 兜底 +- ✅ 实测:批量启动 pbat1/pbat2 → 两个容器 `Up`;批量删除 pbat3 → 目录移入 `.trash`、源目录消失;删除运行中的应用被拒(未找到该项目/有容器);UI 勾选 2 个 → 按钮显示「批量启动 2 个」「批量删除 2 个」→ 启动成功 toast「已启动 2 个应用」、删除成功「已删除 2 个应用(已移入 .trash 回收站)」 + ## 2026-10-26 → ✨ 本地镜像支持批量导出 - ✨ 镜像表每行前加复选框,顶部蓝色批量条:全选 / 已选 N / 共 M / 「导出选中 N 个」 diff --git a/public/app.js b/public/app.js index 31538e3..01e3411 100644 --- a/public/app.js +++ b/public/app.js @@ -4,7 +4,7 @@ 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() }; +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'; state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000)); @@ -627,10 +627,17 @@ async function renderContainers(silent, mode = 'running') { 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.name)}${p.services} 个服务
${esc(p.file.replace((pend.root || '') + '/', ''))}
${p.images.missing.length ? `缺 ${p.images.missing.length} 个镜像 · 自动拉取` @@ -668,6 +675,53 @@ async function renderContainers(silent, mode = 'running') { 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) => { diff --git a/public/style.css b/public/style.css index 01bbaba..65a2a4d 100644 --- a/public/style.css +++ b/public/style.css @@ -360,3 +360,11 @@ table.tb th.num{text-align:right} .img-batch{background:#f4f8ff;border-color:#d6e4f7;color:#4a5a70} .img-batch .bsel{color:#1a5fbf} .img-batch b{color:#1a73e8} + +/* 未启动应用批量条 */ +.pend-batch{margin-bottom:10px;flex-wrap:wrap} +.pend-batch .btn{margin-left:0} +.pend-batch .btn.primary{margin-left:auto} +.pend-chk{display:flex;align-items:center;margin-right:2px} +.pend-chk input{width:14px;height:14px;cursor:pointer;accent-color:#1a73e8} +.pend-top{gap:6px} diff --git a/server/index.js b/server/index.js index 4b9109b..0924a30 100644 --- a/server/index.js +++ b/server/index.js @@ -676,29 +676,104 @@ app.get('/api/pending-apps', async (req, res) => { } 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 projName = target.name.toLowerCase().replace(/[^a-z0-9_-]/g, ''); - const env = { ...process.env }; - if (/^[a-z0-9][a-z0-9_-]*$/.test(projName)) env.COMPOSE_PROJECT_NAME = projName; - const out = await new Promise((resolve) => { - execFile('docker', ['compose', '-f', target.file, 'up', '-d'], { - cwd: target.dir, timeout: 240000, maxBuffer: 2 * 1024 * 1024, env, - }, (err, stdout, stderr) => resolve({ - ok: !err, code: err ? (err.code || 1) : 0, - output: `${stdout || ''}${stderr || ''}`.trim().split('\n').slice(-14).join('\n'), - })); - }); + 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;