80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
const express = require('express');
|
||
const router = express.Router();
|
||
const { initializeMonitor, cleanupMonitor } = require('../utils/systemMonitor');
|
||
|
||
// 存储监控服务的状态
|
||
let monitorStatus = {
|
||
isInitialized: false,
|
||
domainId: null,
|
||
lastError: null
|
||
};
|
||
|
||
// 初始化监控服务
|
||
router.post('/initialize', async (req, res) => {
|
||
try {
|
||
const { domainId } = req.body;
|
||
|
||
if (!domainId) {
|
||
return res.status(400).json({ error: '缺少必要的参数' });
|
||
}
|
||
|
||
// 如果已经初始化,检查域ID是否匹配
|
||
if (monitorStatus.isInitialized) {
|
||
if (monitorStatus.domainId !== domainId) {
|
||
return res.status(400).json({ error: 'DDS域ID不匹配' });
|
||
}
|
||
return res.json({
|
||
message: '监控服务已初始化',
|
||
status: monitorStatus
|
||
});
|
||
}
|
||
|
||
// 首次初始化
|
||
const result = initializeMonitor(domainId);
|
||
if (result && result.includes('失败')) {
|
||
monitorStatus.lastError = result;
|
||
return res.status(500).json({ error: result });
|
||
}
|
||
|
||
monitorStatus.isInitialized = true;
|
||
monitorStatus.domainId = domainId;
|
||
monitorStatus.lastError = null;
|
||
|
||
res.json({
|
||
message: '监控服务初始化成功',
|
||
status: monitorStatus
|
||
});
|
||
} catch (error) {
|
||
console.error('初始化监控服务失败:', error);
|
||
monitorStatus.lastError = error.message;
|
||
res.status(500).json({ error: '初始化监控服务失败', message: error.message });
|
||
}
|
||
});
|
||
|
||
// 注销监控器
|
||
router.post('/unregister', async (req, res) => {
|
||
try {
|
||
// 清理资源
|
||
await cleanupMonitor();
|
||
monitorStatus = {
|
||
isInitialized: false,
|
||
domainId: null,
|
||
lastError: null
|
||
};
|
||
|
||
res.json({
|
||
message: '监控服务注销成功',
|
||
status: monitorStatus
|
||
});
|
||
} catch (error) {
|
||
console.error('注销监控服务失败:', error);
|
||
res.status(500).json({ error: '注销监控服务失败', message: error.message });
|
||
}
|
||
});
|
||
|
||
// 获取监控服务状态
|
||
router.get('/status', (req, res) => {
|
||
res.json(monitorStatus);
|
||
});
|
||
|
||
module.exports = router;
|