fix(restore): guarantee cleanup of uploaded backup archive
Wrap temp-dir removal in removeTempDir() so a failed rmSync cannot hang the async restore handler and leave the archive on disk, close the peek stream descriptor, and clean wido-up-*/wido-rst-* on response finish and the missing-file path.
This commit is contained in:
@@ -81,6 +81,12 @@ function tarEntryFilter(root) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function removeTempDir(dir) {
|
||||||
|
try {
|
||||||
|
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
function sweepRestoreTempDirs() {
|
function sweepRestoreTempDirs() {
|
||||||
let names = [];
|
let names = [];
|
||||||
try {
|
try {
|
||||||
@@ -111,5 +117,6 @@ module.exports = {
|
|||||||
isDiskFullError,
|
isDiskFullError,
|
||||||
isEntryInside,
|
isEntryInside,
|
||||||
tarEntryFilter,
|
tarEntryFilter,
|
||||||
|
removeTempDir,
|
||||||
sweepRestoreTempDirs,
|
sweepRestoreTempDirs,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ const {
|
|||||||
backupRequestTimeoutMs,
|
backupRequestTimeoutMs,
|
||||||
isDiskFullError,
|
isDiskFullError,
|
||||||
parseBackupLimitMb,
|
parseBackupLimitMb,
|
||||||
|
removeTempDir,
|
||||||
tarEntryFilter,
|
tarEntryFilter,
|
||||||
sweepRestoreTempDirs,
|
sweepRestoreTempDirs,
|
||||||
} = require('./lib/restore');
|
} = require('./lib/restore');
|
||||||
@@ -6078,7 +6079,7 @@ async function buildBackupArchive() {
|
|||||||
const { size } = fs.statSync(outPath);
|
const { size } = fs.statSync(outPath);
|
||||||
return { file: outPath, name: `whatido-backup-${stamp}.tar.gz`, size, counts: payload.counts };
|
return { file: outPath, name: `whatido-backup-${stamp}.tar.gz`, size, counts: payload.counts };
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6155,14 +6156,12 @@ sweepBackupStorage();
|
|||||||
setInterval(() => { pruneBackupTickets(); sweepBackupStorage(); }, 60 * 1000).unref();
|
setInterval(() => { pruneBackupTickets(); sweepBackupStorage(); }, 60 * 1000).unref();
|
||||||
|
|
||||||
function cleanupUpload(req) {
|
function cleanupUpload(req) {
|
||||||
try {
|
removeTempDir(req?.file?.destination || req?._uploadDir);
|
||||||
const dir = req?.file?.destination || req?._uploadDir;
|
|
||||||
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
|
||||||
} catch {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function peekGunzip(filePath, n) {
|
function peekGunzip(filePath, n) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
|
const src = fs.createReadStream(filePath);
|
||||||
const gunz = zlib.createGunzip();
|
const gunz = zlib.createGunzip();
|
||||||
const bufs = [];
|
const bufs = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
@@ -6174,22 +6173,35 @@ function peekGunzip(filePath, n) {
|
|||||||
total += Math.min(c.length, need);
|
total += Math.min(c.length, need);
|
||||||
if (total >= n) {
|
if (total >= n) {
|
||||||
done = true;
|
done = true;
|
||||||
|
src.destroy();
|
||||||
gunz.destroy();
|
gunz.destroy();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
gunz.on('error', () => resolve(null));
|
gunz.on('error', () => resolve(done ? Buffer.concat(bufs) : null));
|
||||||
gunz.on('close', () => resolve(Buffer.concat(bufs)));
|
gunz.on('close', () => resolve(Buffer.concat(bufs)));
|
||||||
fs.createReadStream(filePath).pipe(gunz);
|
src.on('error', () => {
|
||||||
|
gunz.destroy();
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
src.pipe(gunz);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('backup'), async (req, res) => {
|
app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('backup'), async (req, res) => {
|
||||||
if (!req.file) return res.status(400).json({ error: 'backup file required' });
|
if (!req.file) {
|
||||||
|
cleanupUpload(req);
|
||||||
|
return res.status(400).json({ error: 'backup file required' });
|
||||||
|
}
|
||||||
|
res.on('finish', () => {
|
||||||
|
cleanupUpload(req);
|
||||||
|
removeTempDir(req._restoreStaging);
|
||||||
|
});
|
||||||
let data;
|
let data;
|
||||||
let legacyPhotos = [];
|
let legacyPhotos = [];
|
||||||
let staging;
|
let staging;
|
||||||
try {
|
try {
|
||||||
staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-rst-'));
|
staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-rst-'));
|
||||||
|
req._restoreStaging = staging;
|
||||||
const head = await peekGunzip(req.file.path, 8);
|
const head = await peekGunzip(req.file.path, 8);
|
||||||
if (head && head[0] === 0x7b) {
|
if (head && head[0] === 0x7b) {
|
||||||
const buf = await fs.promises.readFile(req.file.path);
|
const buf = await fs.promises.readFile(req.file.path);
|
||||||
@@ -6200,19 +6212,19 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
assertRestoreSpace(staging, req.file.size);
|
assertRestoreSpace(staging, req.file.size);
|
||||||
await tar.x({ file: req.file.path, cwd: staging, filter: tarEntryFilter(staging) });
|
await tar.x({ file: req.file.path, cwd: staging, filter: tarEntryFilter(staging) });
|
||||||
if (!fs.existsSync(path.join(staging, 'data.json')) && fs.existsSync(path.join(staging, 'db.sql.gz'))) {
|
if (!fs.existsSync(path.join(staging, 'data.json')) && fs.existsSync(path.join(staging, 'db.sql.gz'))) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
return res.status(400).json({ error: 'Это архив скрипта scripts/backup.sh (db.sql.gz + _uploads) — восстанавливайте его через scripts/restore.sh. Для веб-восстановления скачайте архив в Настройках админки.' });
|
return res.status(400).json({ error: 'Это архив скрипта scripts/backup.sh (db.sql.gz + _uploads) — восстанавливайте его через scripts/restore.sh. Для веб-восстановления скачайте архив в Настройках админки.' });
|
||||||
}
|
}
|
||||||
if (!fs.existsSync(path.join(staging, 'data.json'))) {
|
if (!fs.existsSync(path.join(staging, 'data.json'))) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
return res.status(400).json({ error: 'В архиве нет data.json — это не архив веб-бэкапа из админки.' });
|
return res.status(400).json({ error: 'В архиве нет data.json — это не архив веб-бэкапа из админки.' });
|
||||||
}
|
}
|
||||||
data = JSON.parse(fs.readFileSync(path.join(staging, 'data.json'), 'utf8'));
|
data = JSON.parse(fs.readFileSync(path.join(staging, 'data.json'), 'utf8'));
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (staging) fs.rmSync(staging, { recursive: true, force: true });
|
if (staging) removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
console.error('Restore unpack failed:', e);
|
console.error('Restore unpack failed:', e);
|
||||||
if (e && e.code === 'RESTORE_NO_SPACE') {
|
if (e && e.code === 'RESTORE_NO_SPACE') {
|
||||||
@@ -6225,7 +6237,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
}
|
}
|
||||||
const formatVersion = Number(data && data.version);
|
const formatVersion = Number(data && data.version);
|
||||||
if (!isSupportedBackupVersion(data)) {
|
if (!isSupportedBackupVersion(data)) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
return res.status(400).json({ error: 'Неверный формат бэкапа' });
|
return res.status(400).json({ error: 'Неверный формат бэкапа' });
|
||||||
}
|
}
|
||||||
@@ -6233,7 +6245,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
try {
|
try {
|
||||||
ndata = normalizeRestoreData(data);
|
ndata = normalizeRestoreData(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
return res.status(400).json({ error: 'Неверный формат бэкапа: ' + e.message });
|
return res.status(400).json({ error: 'Неверный формат бэкапа: ' + e.message });
|
||||||
}
|
}
|
||||||
@@ -6241,7 +6253,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
try {
|
try {
|
||||||
client = await pool.connect();
|
client = await pool.connect();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
console.error('Restore connect failed:', e);
|
console.error('Restore connect failed:', e);
|
||||||
return res.status(503).json({ error: 'Не удалось подключиться к базе данных: ' + e.message });
|
return res.status(503).json({ error: 'Не удалось подключиться к базе данных: ' + e.message });
|
||||||
@@ -6531,7 +6543,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
await client.query('COMMIT');
|
await client.query('COMMIT');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await client.query('ROLLBACK').catch(() => {});
|
await client.query('ROLLBACK').catch(() => {});
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
console.error('Restore failed:', e);
|
console.error('Restore failed:', e);
|
||||||
if (isDiskFullError(e)) {
|
if (isDiskFullError(e)) {
|
||||||
@@ -6552,7 +6564,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
await storage.uploadTree(path.join(staging, 'uploads'));
|
await storage.uploadTree(path.join(staging, 'uploads'));
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
console.error('Restore files failed:', e);
|
console.error('Restore files failed:', e);
|
||||||
const reason = isDiskFullError(e)
|
const reason = isDiskFullError(e)
|
||||||
@@ -6563,7 +6575,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
|||||||
data_restored: true,
|
data_restored: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
fs.rmSync(staging, { recursive: true, force: true });
|
removeTempDir(staging);
|
||||||
cleanupUpload(req);
|
cleanupUpload(req);
|
||||||
try {
|
try {
|
||||||
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||||
|
|||||||
Reference in New Issue
Block a user