feat: 本地镜像支持批量导出

This commit is contained in:
jinghui committed 2026-10-26 22:11:06 +08:00
1 parent 804a681896
commit a1f5c942b9
4 files changed
+90 -2

No files matched your search

+9
View File
@@ -1,5 +1,14 @@
# 更新日志
## 2026-10-26 → ✨ 本地镜像支持批量导出
- ✨ 镜像表每行前加复选框,顶部蓝色批量条:全选 / 已选 N / 共 M / 「导出选中 N 个」
- ✨ 批量导出打包成**一个 `images-<个数>-<日期>.tar.gz`**,内含多镜像 OCI 布局,`docker load < 文件` 一次导入全部
- ✨ 导出优先用镜像 tag 作为引用,**恢复后 RepoTags 保留**(按镜像 ID 导出会丢标签);无 tag 才回退 ID
- 🔧 新增 `GET /api/images/export?ids=a,b,c`:直接走 Docker socket `/images/get`,边读边 gzip,不落临时文件;一次上限 40 个,超出前端提示只取前 40
- 🔧 单张导出(`/api/images/:id/export`)保留,使用与运行状态无关
- ✅ 实测:勾选 3 个 → 按钮变「导出选中 3 个」→ 全选 189 个按钮同步;导出 2 个镜像得到 3.8MB tar.gz,`manifest.json` 内 RepoTags 正确保留(hello-world / alpine)
## 2026-10-26 → ✨ 网络页支持新建/删除网络
- ✨ 网络页顶部新增「新建网络」表单:网络名、驱动(bridge/overlay/macvlan)、子网、网关、内部网络;不填子网则由 Docker 自动分配
+36 -2
View File
@@ -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() };
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 REFRESH_KEY = 'dc.refreshMs';
state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000));
@@ -870,8 +870,15 @@ async function renderImages() {
}
return '<span class="pill stop">未使用</span>';
};
$('#view').innerHTML = `<table class="tb"><thead><tr><th>镜像</th><th>ID</th><th class="num">大小</th><th>使用情况</th><th>创建</th><th></th></tr></thead><tbody>
const batchBar = `<div class="batch-bar img-batch">
<label class="bsel"><input type="checkbox" id="imgSelAll"> 全选</label>
<span class="muted">已选 <b id="imgSelCount">${[...state.imgSel].filter(id => imgs.some(i => i.id === id)).length}</b> / ${imgs.length}</span>
<span class="muted">批量导出会打包成一个 tar.gz</span>
<button class="btn primary" id="imgExportSel" disabled>导出选中</button>
</div>`;
$('#view').innerHTML = `${batchBar}<table class="tb"><thead><tr><th class="chkcell"></th><th>镜像</th><th>ID</th><th class="num">大小</th><th>使用情况</th><th>创建</th><th></th></tr></thead><tbody>
${imgs.map(i => `<tr>
<td class="chkcell"><input type="checkbox" class="imgsel" data-id="${esc(i.id)}"${state.imgSel.has(i.id) ? ' checked' : ''}></td>
<td>${(i.tags.length ? i.tags : ['<none>:<none>']).map(t => `<span class="tag blue">${esc(t)}</span>`).join(' ')}</td>
<td class="muted">${esc(i.shortId)}</td>
<td class="num">${fmtBytes(i.size)}</td>
@@ -884,6 +891,33 @@ async function renderImages() {
</tr>`).join('')}
</tbody></table>
<div class="foot">共 ${s.total} 个镜像 · 合计 ${fmtBytes(s.totalSize)} · 使用中 ${s.inUse} 个 · 可删除 ${s.deletable} 个(可释放 ${fmtBytes(s.deletableSize)})</div>`;
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 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 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');
+7
View File
@@ -353,3 +353,10 @@ table.tb th.num{text-align:right}
.net-form .chkline{display:flex;align-items:center;gap:6px;font-size:12.5px;color:#5a6b82;white-space:nowrap}
.net-form .btn{margin-left:auto}
.tag.gray{background:#f0f3f7;color:#7a8798}
/* 镜像批量导出 */
.chkcell{width:34px;text-align:center;padding-left:10px!important}
.chkcell input{width:15px;height:15px;cursor:pointer;accent-color:#1a73e8}
.img-batch{background:#f4f8ff;border-color:#d6e4f7;color:#4a5a70}
.img-batch .bsel{color:#1a5fbf}
.img-batch b{color:#1a73e8}
+38
View File
@@ -8,6 +8,7 @@ const path = require('path');
const os = require('os');
const { PassThrough } = require('stream');
const zlib = require('zlib');
const http = require('http');
const { execFile } = require('child_process');
const docker = new Docker({ socketPath: process.env.DOCKER_SOCK || '/var/run/docker.sock' });
@@ -1059,6 +1060,43 @@ app.get('/api/images', async (req, res) => {
} catch (e) { res.status(500).json({ error: e.message }); }
});
app.get('/api/images/export', async (req, res) => {
try {
const ids = String(req.query.ids || '').split(',').map(x => x.trim()).filter(Boolean).slice(0, 40);
if (!ids.length) return res.status(400).json({ error: '未选择镜像' });
const stamp = new Date().toISOString().slice(0, 10);
res.setHeader('Content-Type', 'application/gzip');
res.setHeader('Content-Disposition', `attachment; filename="images-${ids.length}-${stamp}.tar.gz"`);
// 有 tag 优先用 tag 导出,否则回退到镜像 ID(按 ID 导出会丢 RepoTags)
const all = await docker.listImages({ all: false });
const tagOf = new Map(all.map(i => [i.Id, (i.RepoTags && i.RepoTags[0]) || '']));
const refs = ids.map(id => tagOf.get(id) || id);
const q = refs.map(r => 'names=' + encodeURIComponent(r)).join('&');
const gz = zlib.createGzip({ level: 3 });
gz.on('error', () => { try { res.end(); } catch (_) {} });
gz.pipe(res);
const up = http.request({ socketPath: process.env.DOCKER_SOCK || '/var/run/docker.sock', path: `/images/get?${q}`, method: 'GET' }, (r) => {
if (r.statusCode !== 200) {
let buf = '';
r.on('data', c => { buf += c; });
r.on('end', () => {
let msg = buf;
try { msg = JSON.parse(buf).message || buf; } catch (_) {}
if (!res.headersSent) res.status(500).json({ error: '导出失败:' + msg }); else res.end();
});
return;
}
r.pipe(gz);
});
up.on('error', (e) => { if (!res.headersSent) res.status(500).json({ error: e.message }); else res.end(); });
res.on('close', () => { try { up.destroy(); } catch (_) {} });
up.end();
} catch (e) {
if (!res.headersSent) res.status(500).json({ error: e.message });
else try { res.end(); } catch (_) {}
}
});
app.get('/api/images/:id/export', async (req, res) => {
try {
const img = await docker.getImage(req.params.id).inspect();