scheduler.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. const cron = require('node-cron');
  2. const logger = require('../utils/logger');
  3. const SpeedTester = require('./speedTester');
  4. const TelegramNotifier = require('./notifier');
  5. const SubscriptionManager = require('./subscriptionManager');
  6. const { Node, TestResult } = require('../models');
  7. class Scheduler {
  8. constructor() {
  9. this.speedTester = new SpeedTester();
  10. this.notifier = new TelegramNotifier();
  11. this.subscriptionManager = new SubscriptionManager();
  12. this.isRunning = false;
  13. this.testInterval = parseInt(process.env.SPEED_TEST_INTERVAL) || 15; // 分钟
  14. this.failureThreshold = parseInt(process.env.NOTIFICATION_FAILURE_THRESHOLD) || 3;
  15. this.recoveryThreshold = parseInt(process.env.NOTIFICATION_RECOVERY_THRESHOLD) || 2;
  16. }
  17. /**
  18. * 启动调度器
  19. */
  20. start() {
  21. logger.info('启动定时任务调度器 - 定时测速已关闭');
  22. // 暂时关闭定时测速
  23. // const cronExpression = `*/${this.testInterval} * * * *`;
  24. // this.speedTestJob = cron.schedule(cronExpression, async () => {
  25. // await this.runSpeedTest();
  26. // }, {
  27. // scheduled: true,
  28. // timezone: 'Asia/Shanghai'
  29. // });
  30. // 每小时重试失败的通知
  31. this.notificationRetryJob = cron.schedule('0 * * * *', async () => {
  32. await this.notifier.retryFailedNotifications();
  33. }, {
  34. scheduled: true,
  35. timezone: 'Asia/Shanghai'
  36. });
  37. // 每天凌晨2点清理旧数据
  38. this.cleanupJob = cron.schedule('0 2 * * *', async () => {
  39. await this.cleanupOldData();
  40. }, {
  41. scheduled: true,
  42. timezone: 'Asia/Shanghai'
  43. });
  44. // 启动订阅自动更新
  45. this.subscriptionManager.startAutoUpdate();
  46. logger.info('定时任务调度器启动成功');
  47. }
  48. /**
  49. * 停止调度器
  50. */
  51. stop() {
  52. if (this.speedTestJob) {
  53. this.speedTestJob.stop();
  54. }
  55. if (this.notificationRetryJob) {
  56. this.notificationRetryJob.stop();
  57. }
  58. if (this.cleanupJob) {
  59. this.cleanupJob.stop();
  60. }
  61. this.subscriptionManager.stopAutoUpdate();
  62. logger.info('定时任务调度器已停止');
  63. }
  64. /**
  65. * 运行速度测试
  66. */
  67. async runSpeedTest() {
  68. if (this.isRunning) {
  69. logger.warn('上一次测试还在运行中,跳过本次测试');
  70. return;
  71. }
  72. this.isRunning = true;
  73. const startTime = Date.now();
  74. try {
  75. // 获取所有启用的节点
  76. const nodes = await Node.findAll({
  77. where: { isActive: true },
  78. order: [['group', 'ASC'], ['name', 'ASC']]
  79. });
  80. if (nodes.length === 0) {
  81. logger.warn('没有找到启用的节点');
  82. return;
  83. }
  84. logger.info(`找到 ${nodes.length} 个节点,开始测试`);
  85. // 批量测试节点
  86. const testResults = await this.speedTester.testNodes(nodes);
  87. // 处理测试结果
  88. await this.processTestResults(nodes, testResults);
  89. // 生成并发送摘要
  90. await this.sendTestSummary(nodes, testResults);
  91. const duration = Date.now() - startTime;
  92. logger.info(`定时测速完成 - ${nodes.length}个节点,${testResults.filter(r => r.isSuccess).length}个成功,耗时${duration}ms`);
  93. } catch (error) {
  94. logger.error('定时速度测试失败', { error: error.message });
  95. // 发送系统错误通知
  96. await this.notifier.sendSystemNotification(
  97. '⚠️ 系统错误通知',
  98. `定时速度测试过程中发生错误:\n\n${error.message}`,
  99. { error: error.message, timestamp: new Date().toISOString() }
  100. );
  101. } finally {
  102. this.isRunning = false;
  103. }
  104. }
  105. /**
  106. * 处理测试结果
  107. */
  108. async processTestResults(nodes, testResults) {
  109. const nodeMap = new Map(nodes.map(node => [node.id, node]));
  110. const resultMap = new Map(testResults.map(result => [result.nodeId, result]));
  111. for (const node of nodes) {
  112. const testResult = resultMap.get(node.id);
  113. if (!testResult) continue;
  114. const previousStatus = node.status;
  115. const previousFailureCount = node.failureCount;
  116. // 更新节点状态
  117. if (testResult.isSuccess) {
  118. // 测试成功
  119. if (node.status === 'offline') {
  120. // 节点从离线恢复
  121. if (previousFailureCount >= this.recoveryThreshold) {
  122. await this.notifier.sendRecoveryNotification(node, testResult);
  123. }
  124. }
  125. await node.update({
  126. status: 'online',
  127. lastTestTime: testResult.testTime,
  128. lastTestResult: true,
  129. failureCount: 0,
  130. averageLatency: testResult.latency,
  131. averageSpeed: testResult.downloadSpeed
  132. });
  133. } else {
  134. // 测试失败
  135. const newFailureCount = previousFailureCount + 1;
  136. await node.update({
  137. status: 'offline',
  138. lastTestTime: testResult.testTime,
  139. lastTestResult: false,
  140. failureCount: newFailureCount
  141. });
  142. // 检查是否需要发送故障通知
  143. if (newFailureCount === this.failureThreshold && previousStatus === 'online') {
  144. await this.notifier.sendFailureNotification(node, testResult);
  145. }
  146. }
  147. }
  148. }
  149. /**
  150. * 发送测试摘要
  151. */
  152. async sendTestSummary(nodes, testResults) {
  153. const totalNodes = nodes.length;
  154. const onlineNodes = testResults.filter(r => r.isSuccess).length;
  155. const offlineNodes = totalNodes - onlineNodes;
  156. const successRate = totalNodes > 0 ? Math.round((onlineNodes / totalNodes) * 100) : 0;
  157. // 计算平均延迟和速度
  158. const successfulResults = testResults.filter(r => r.isSuccess && r.latency);
  159. const averageLatency = successfulResults.length > 0
  160. ? Math.round(successfulResults.reduce((sum, r) => sum + r.latency, 0) / successfulResults.length)
  161. : null;
  162. const speedResults = testResults.filter(r => r.isSuccess && r.downloadSpeed);
  163. const averageSpeed = speedResults.length > 0
  164. ? Math.round((speedResults.reduce((sum, r) => sum + r.downloadSpeed, 0) / speedResults.length) * 100) / 100
  165. : null;
  166. // 获取故障节点列表
  167. const failedNodes = nodes.filter(node => {
  168. const result = testResults.find(r => r.nodeId === node.id);
  169. return result && !result.isSuccess;
  170. }).slice(0, 10); // 最多显示10个
  171. // 获取最佳节点列表
  172. const bestNodes = testResults
  173. .filter(r => r.isSuccess && r.latency)
  174. .sort((a, b) => a.latency - b.latency)
  175. .slice(0, 5)
  176. .map(result => {
  177. const node = nodes.find(n => n.id === result.nodeId);
  178. return {
  179. name: node ? node.name : 'Unknown',
  180. latency: result.latency,
  181. group: node ? node.group : 'Unknown'
  182. };
  183. });
  184. // 按分组统计
  185. const groupStats = {};
  186. nodes.forEach(node => {
  187. const group = node.group || '默认';
  188. if (!groupStats[group]) {
  189. groupStats[group] = { total: 0, online: 0, offline: 0 };
  190. }
  191. groupStats[group].total++;
  192. const result = testResults.find(r => r.nodeId === node.id);
  193. if (result && result.isSuccess) {
  194. groupStats[group].online++;
  195. } else {
  196. groupStats[group].offline++;
  197. }
  198. });
  199. const summary = {
  200. totalNodes,
  201. onlineNodes,
  202. offlineNodes,
  203. successRate,
  204. averageLatency,
  205. averageSpeed,
  206. failedNodes,
  207. bestNodes,
  208. groupStats,
  209. testTime: new Date().toLocaleString('zh-CN')
  210. };
  211. // 每次测速完成后都发送详细的测试总结报告
  212. await this.notifier.sendSummaryNotification(summary);
  213. logger.info('测试摘要生成完成', summary);
  214. }
  215. /**
  216. * 清理旧数据
  217. */
  218. async cleanupOldData() {
  219. try {
  220. logger.info('开始清理旧数据');
  221. // 删除30天前的测试结果
  222. const thirtyDaysAgo = new Date();
  223. thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  224. const deletedTestResults = await TestResult.destroy({
  225. where: {
  226. testTime: {
  227. [require('sequelize').Op.lt]: thirtyDaysAgo
  228. }
  229. }
  230. });
  231. // 删除7天前的通知记录
  232. const sevenDaysAgo = new Date();
  233. sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
  234. const deletedNotifications = await require('../models').Notification.destroy({
  235. where: {
  236. createdAt: {
  237. [require('sequelize').Op.lt]: sevenDaysAgo
  238. },
  239. isSent: true
  240. }
  241. });
  242. logger.info('旧数据清理完成', {
  243. deletedTestResults,
  244. deletedNotifications
  245. });
  246. } catch (error) {
  247. logger.error('清理旧数据失败', { error: error.message });
  248. }
  249. }
  250. /**
  251. * 手动触发测试
  252. */
  253. async triggerManualTest() {
  254. if (this.isRunning) {
  255. throw new Error('测试正在进行中,请稍后再试');
  256. }
  257. logger.info('手动触发速度测试');
  258. await this.runSpeedTest();
  259. }
  260. /**
  261. * 获取调度器状态
  262. */
  263. getStatus() {
  264. return {
  265. isRunning: this.isRunning,
  266. testInterval: this.testInterval,
  267. failureThreshold: this.failureThreshold,
  268. recoveryThreshold: this.recoveryThreshold,
  269. jobs: {
  270. speedTest: this.speedTestJob ? 'running' : 'stopped',
  271. notificationRetry: this.notificationRetryJob ? 'running' : 'stopped',
  272. cleanup: this.cleanupJob ? 'running' : 'stopped'
  273. }
  274. };
  275. }
  276. }
  277. module.exports = Scheduler;