feat: 新增备份与恢复页(面板数据 + compose 配置,可下载)

This commit is contained in:
jinghui committed 2026-10-26 22:27:53 +08:00
1 parent 4a68439f2c
commit 1791e94028
5 files changed
+178 -1

No files matched your search

+114
View File
@@ -1299,6 +1299,120 @@ app.delete('/api/networks/:id', async (req, res) => {
} catch (e) { res.status(500).json({ error: e.message }); }
});
/* ---------------- 备份 ---------------- */
const DATA_ROOT = path.dirname(SETTINGS_PATH);
const BACKUP_DIR = path.join(DATA_ROOT, 'backups');
const CFG_FILE_RE = /^(docker-compose|compose)\.ya?ml$|^\.env(\..+)?$|\.(ya?ml|json|toml|ini|conf|env|txt|properties)$/i;
async function listBackups() {
try {
const files = await fsp.readdir(BACKUP_DIR);
const out = [];
for (const f of files) {
if (!f.endsWith('.tar.gz')) continue;
const st = await fsp.stat(path.join(BACKUP_DIR, f)).catch(() => null);
if (st) out.push({ name: f, size: st.size, time: st.mtimeMs });
}
return out.sort((a, b) => b.time - a.time);
} catch (e) { return []; }
}
app.get('/api/backup', async (req, res) => {
const items = await listBackups();
res.json({ items, dir: BACKUP_DIR });
});
app.post('/api/backup', async (req, res) => {
const stage = await fsp.mkdtemp(path.join(os.tmpdir(), 'dcbak-')).catch(() => null);
if (!stage) return res.status(500).json({ error: '无法创建临时目录' });
try {
const wantPanel = req.body && req.body.panel !== false;
const wantApps = !!(req.body && req.body.apps);
const ts = new Date();
const stamp = ts.toISOString().replace(/[:.]/g, '-').slice(0, 19);
const name = `docker-center-backup-${stamp}.tar.gz`;
await fsp.mkdir(BACKUP_DIR, { recursive: true });
const manifest = { created: ts.toISOString(), host: hostName(), panel: wantPanel, apps: wantApps, appList: [], files: 0 };
if (wantPanel) {
const pd = path.join(stage, 'panel');
await fsp.mkdir(pd, { recursive: true });
for (const f of ['settings.json', 'events.json']) {
const src = path.join(DATA_ROOT, f);
if (fs.existsSync(src)) { await fsp.copyFile(src, path.join(pd, f)); manifest.files++; }
}
const tf = path.join(DATA_ROOT, 'traffic');
if (fs.existsSync(tf)) {
const dstT = path.join(pd, 'traffic');
await fsp.mkdir(dstT, { recursive: true });
for (const f of await fsp.readdir(tf)) {
if (!f.endsWith('.json')) continue;
await fsp.copyFile(path.join(tf, f), path.join(dstT, f)).catch(() => {});
manifest.files++;
}
}
}
if (wantApps) {
const appsRoot = path.join(stage, 'apps');
await fsp.mkdir(appsRoot, { recursive: true });
let dirs = [];
try { dirs = await fsp.readdir(COMPOSE_ROOT, { withFileTypes: true }); } catch (e) {}
for (const d of dirs) {
if (!d.isDirectory() || d.name.startsWith('.')) continue;
let entries = [];
try { entries = await fsp.readdir(path.join(COMPOSE_ROOT, d.name), { withFileTypes: true }); } catch (e) { continue; }
const picked = [];
for (const e of entries) {
if (!e.isFile() || !CFG_FILE_RE.test(e.name)) continue;
const src = path.join(COMPOSE_ROOT, d.name, e.name);
const st = await fsp.stat(src).catch(() => null);
if (!st || st.size > 2 * 1024 * 1024) continue;
picked.push(e.name);
}
if (!picked.length) continue;
const dst = path.join(appsRoot, d.name);
await fsp.mkdir(dst, { recursive: true });
for (const f of picked) {
await fsp.copyFile(path.join(COMPOSE_ROOT, d.name, f), path.join(dst, f)).catch(() => {});
manifest.files++;
}
manifest.appList.push(d.name);
}
}
await fsp.writeFile(path.join(stage, 'manifest.json'), JSON.stringify(manifest, null, 2));
const out = path.join(BACKUP_DIR, name);
await new Promise((resolve, reject) => {
execFile('tar', ['-czf', out, '-C', stage, '.'], { timeout: 600000, maxBuffer: 8 * 1024 * 1024 }, (err) => err ? reject(err) : resolve());
});
const st = await fsp.stat(out);
pushEvent('info', null, `创建备份 ${name}`, `${(st.size / 1048576).toFixed(1)}MB · ${manifest.appList.length} 个应用配置`);
res.json({ ok: true, name, size: st.size, apps: manifest.appList.length, files: manifest.files });
} catch (e) {
res.status(500).json({ error: e.message });
} finally {
fsp.rm(stage, { recursive: true, force: true }).catch(() => {});
}
});
app.get('/api/backup/:name/download', async (req, res) => {
const name = String(req.params.name || '');
if (!/^[A-Za-z0-9._-]+\.tar\.gz$/.test(name) || name.includes('..')) return res.status(400).json({ error: '文件名不合法' });
const file = path.join(BACKUP_DIR, name);
if (!fs.existsSync(file)) return res.status(404).json({ error: '备份不存在' });
res.download(file, name);
});
app.delete('/api/backup/:name', async (req, res) => {
const name = String(req.params.name || '');
if (!/^[A-Za-z0-9._-]+\.tar\.gz$/.test(name) || name.includes('..')) return res.status(400).json({ error: '文件名不合法' });
const file = path.join(BACKUP_DIR, name);
if (!fs.existsSync(file)) return res.status(404).json({ error: '备份不存在' });
await fsp.rm(file, { force: true });
res.json({ ok: true });
});
/* ---------------- 启动 ---------------- */
setInterval(sampleOnce, SAMPLE_MS);
setInterval(tickApps, SAMPLE_MS);