refactor(mikrotikBackupRoutes, mikrotikBackupScheduler, mikrotikApplyService): replace direct export command with file-based export method for improved reliability and error handling
Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 3m59s
Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 3m59s
This commit is contained in:
@@ -15,7 +15,7 @@ const crypto = require('crypto');
|
||||
const { sendError, sendOk } = require('../middleware/errorHandler');
|
||||
const { writeS3TextObject, readS3TextObject, listS3Objects } = require('../services/s3Service');
|
||||
const { readServersFromS3 } = require('./serversRoutes');
|
||||
const { createRosClient } = require('../services/mikrotikApplyService');
|
||||
const { createRosClient, fetchExportViaFile } = require('../services/mikrotikApplyService');
|
||||
const { decrypt } = require('../utils/encryption');
|
||||
|
||||
const BACKUP_PREFIX = 'backups/mikrotik';
|
||||
@@ -261,29 +261,8 @@ async function runBackupNow(req, res) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
// /rest/execute с командой "/export compact terse", как в планировщике
|
||||
const resp = await client.command('execute', { script: '/export compact terse' });
|
||||
const data = resp && resp.data;
|
||||
let config = '';
|
||||
if (typeof data === 'string') config = data;
|
||||
else if (Array.isArray(data)) {
|
||||
config = data
|
||||
.map((line) => {
|
||||
if (typeof line === 'string') return line;
|
||||
if (line && typeof line === 'object') {
|
||||
if (line.rsc) return String(line.rsc);
|
||||
if (line.config) return String(line.config);
|
||||
return JSON.stringify(line);
|
||||
}
|
||||
return String(line ?? '');
|
||||
})
|
||||
.join('\n');
|
||||
} else if (data && typeof data === 'object') {
|
||||
config = JSON.stringify(data, null, 2);
|
||||
} else {
|
||||
config = String(data || '');
|
||||
}
|
||||
|
||||
// API не возвращает текст /export напрямую — экспортируем в файл, читаем, удаляем
|
||||
const config = await fetchExportViaFile(client);
|
||||
if (!config || !config.trim()) {
|
||||
return sendError(res, 502, 'Empty export result from MikroTik', 'E_EMPTY_EXPORT');
|
||||
}
|
||||
|
||||
@@ -344,6 +344,44 @@ async function applyBlock(client, block, dryRun) {
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить полный экспорт конфигурации MikroTik через REST API.
|
||||
* API не возвращает текст /export напрямую — только при export file=... сохраняется в файл.
|
||||
* Мы экспортируем во временный файл, читаем его, удаляем.
|
||||
*
|
||||
* @param {object} client - ros-rest client (createRosClient)
|
||||
* @returns {Promise<string>} - текст конфигурации (export compact)
|
||||
*/
|
||||
async function fetchExportViaFile(client) {
|
||||
const crypto = require('crypto');
|
||||
const basename = `backup_${Date.now()}_${crypto.randomBytes(4).toString('hex')}.rsc`;
|
||||
|
||||
await client.command('export', { compact: '', file: basename });
|
||||
|
||||
const printRes = await client.command('file/print', {
|
||||
'.proplist': 'contents,.id',
|
||||
'.query': [`name=${basename}`],
|
||||
});
|
||||
const data = printRes?.data;
|
||||
const list = Array.isArray(data) ? data : (data ? [data] : []);
|
||||
const file = list[0];
|
||||
if (!file || file.contents == null) {
|
||||
try {
|
||||
const id = file?.['.id'];
|
||||
if (id) await client.remove(`file/${id}`);
|
||||
} catch (_) {}
|
||||
throw new Error('Failed to read export file from MikroTik');
|
||||
}
|
||||
const config = String(file.contents || '');
|
||||
|
||||
try {
|
||||
const id = file['.id'];
|
||||
if (id) await client.remove(`file/${id}`);
|
||||
} catch (_) {}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createRosClient,
|
||||
rosPrint,
|
||||
@@ -353,4 +391,5 @@ module.exports = {
|
||||
rosRemove,
|
||||
applyOperation,
|
||||
applyBlock,
|
||||
fetchExportViaFile,
|
||||
};
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
*/
|
||||
|
||||
const { readServersFromS3 } = require('../routes/serversRoutes');
|
||||
const { createRosClient } = require('./mikrotikApplyService');
|
||||
const { createRosClient, fetchExportViaFile } = require('./mikrotikApplyService');
|
||||
const { saveBackupForServer } = require('../routes/mikrotikBackupRoutes');
|
||||
const { decrypt } = require('../utils/encryption');
|
||||
const { readS3TextObject } = require('../services/s3Service');
|
||||
@@ -53,32 +53,8 @@ async function getServerIdsFromUiSettings(logger) {
|
||||
}
|
||||
|
||||
async function fetchRouterExport(client) {
|
||||
// Используем /rest/execute с командой "/export compact terse", чтобы гарантированно получить вывод в ответе.
|
||||
const res = await client.command('execute', { script: '/export compact terse' });
|
||||
const data = res && res.data;
|
||||
if (!data) return '';
|
||||
|
||||
if (typeof data === 'string') return data;
|
||||
if (Array.isArray(data)) {
|
||||
// Некоторые версии могут вернуть массив строк/объектов
|
||||
return data
|
||||
.map((line) => {
|
||||
if (typeof line === 'string') return line;
|
||||
if (line && typeof line === 'object') {
|
||||
// Пытаемся собрать строку из полей, если они есть
|
||||
if (line.rsc) return String(line.rsc);
|
||||
if (line.config) return String(line.config);
|
||||
return JSON.stringify(line);
|
||||
}
|
||||
return String(line ?? '');
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
if (typeof data === 'object') {
|
||||
// Fallback: сериализуем объект
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
return String(data);
|
||||
// API не возвращает текст /export напрямую — экспортируем в файл, читаем, удаляем
|
||||
return fetchExportViaFile(client);
|
||||
}
|
||||
|
||||
async function runBackupOnce(logger) {
|
||||
|
||||
Reference in New Issue
Block a user