-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.mjs
180 lines (146 loc) · 6.67 KB
/
monitor.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* Monitor via HeroUnion
*/
import path from 'node:path';
import cron from 'node-cron';
import axios from 'axios';
import common from './lib/common.mjs';
import md5 from 'md5';
class Monitor {
//构造函数,设置默认配置
constructor(configFilename) {
this.config = null;
this.configFile = typeof(configFilename) != 'undefined' && configFilename ? configFilename : 'config.json';
//默认配置
this.systemLogDir = 'log/'; //系统日志保存目录
this.reloadConfigFrequence = 5; //单位:分钟,配置重新加载时间间隔
this.monitFrequence = 10; //单位:分钟,检测时间间隔
this.resultQueryFrequence = 1; //单位:分钟,检测任务结果查询时间间隔
this.tasks = []; //HeroUnion检测任务队列
}
async getConfig(forceReload) {
const _self = this;
if ( !this.config || (typeof(forceReload) != 'undefined' && forceReload) ) {
common.log("Load config from %s", this.configFile);
let config = await common.getConfigFromJsonFile(this.configFile);
//覆盖默认配置
for (const key in config) {
if (typeof(_self[key]) != 'undefined') {
_self[key] = config[key];
}
}
this.config = config;
}
return this.config;
}
//自动重新加载配置文件
autoReloadConfigs() {
const _self = this;
const frequence = typeof(this.config.reloadConfigFrequence) != 'undefined'
&& this.config.reloadConfigFrequence ? this.config.reloadConfigFrequence : 5; //5 分钟重新加载一次
const cronjob = cron.schedule(`*/${frequence} * * * *`, () => {
const forceReload = true;
_self.getConfig(forceReload);
}, {
scheduled: false
});
cronjob.start();
common.log('Cronjob of config auto reload started.');
}
//自动向HeroUnion提交检测任务
autoCreateMonitTask() {
const _self = this;
const frequence = typeof(this.config.monitFrequence) != 'undefined'
&& this.config.monitFrequence ? this.config.monitFrequence : 10; //10 分钟检测一次
const cronjob = cron.schedule(`*/${frequence} * * * *`, async () => {
let configs = await _self.getConfig();
if (configs.monit_urls.length == 0) {
return false;
}
let taskRes;
let total = configs.monit_urls.length;
for (let i=0; i<total; i++) {
if (_self.tasks.find((item) => item.url == configs.monit_urls[i] && item.stats != 'done')) {continue;}
common.log("Checking url %s ...", configs.monit_urls[i]);
taskRes = await common.createHeroUnionTask(configs.monit_urls[i], '', configs);
if (taskRes && taskRes.code == 1) {
_self.tasks.push(taskRes.task);
}else {
common.error("Monit task create failed", taskRes);
}
}
}, {
scheduled: false
});
cronjob.start();
common.log('Cronjob of url monit started.');
}
async queryTasks() {
const _self = this;
let configs = await _self.getConfig();
let task, taskRes;
for(let index = 0; index < _self.tasks.length; index ++) {
task = _self.tasks[index];
if (task.status == 'done' || task.status == 'failed') {continue;}
taskRes = await common.queryHeroUnionTask(task.id, configs);
if (taskRes && taskRes.code == 1) {
_self.tasks[index] = taskRes.task; //更新任务数据
common.log('Task status: %s, url: %s, task id: %s', taskRes.task.status, task.url, task.id);
if (taskRes.task.status == 'done') {
let currentTime = common.getLocalTimeString();
let logFile = path.resolve(_self.systemLogDir) + '/ok.log';
common.saveLog(logFile, `[${currentTime}] Url request success: ${task.url}, task id: ${task.id}\n`);
//写入JSON格式的log
logFile = path.resolve(_self.systemLogDir) + '/json_stats.log';
let logData = {
"timestamp": common.getTimestamp(),
"url": task.url,
"status": taskRes.task.status
};
common.saveLog(logFile, JSON.stringify(logData) + `\n`);
}else if (taskRes.task.status == 'failed') {
//写入错误日志
let currentTime = common.getLocalTimeString();
let logFile = path.resolve(_self.systemLogDir) + '/fail.log';
common.saveLog(logFile, `[${currentTime}] Url request failed: ${task.url}, task id: ${task.id}\n`);
//写入JSON格式的log
logFile = path.resolve(_self.systemLogDir) + '/json_stats.log';
let logData = {
"timestamp": common.getTimestamp(),
"url": task.url,
"status": taskRes.task.status
};
common.saveLog(logFile, JSON.stringify(logData) + `\n`);
}
}else {
common.error('Task query failed, url: %s, task id: %s', task.url, task.id, taskRes);
}
}
//更新tasks,去掉已完成的和失败的
_self.tasks = _self.tasks.filter((item) => item.status != 'done' && item.status != 'failed');
}
//自动查询监控任务结果
autoQueryTaskResult() {
const _self = this;
const frequence = typeof(this.config.resultQueryFrequence) != 'undefined'
&& this.config.resultQueryFrequence ? this.config.resultQueryFrequence : 5; //5 分钟检测一次
const cronjob = cron.schedule(`*/${frequence} * * * *`, async () => {
if (_self.tasks.length == 0) {
return false;
}
await _self.queryTasks();
}, {
scheduled: false
});
cronjob.start();
common.log('Cronjob of monit task result query started.');
}
//初始化
async init() {
await this.getConfig();
this.autoReloadConfigs();
this.autoCreateMonitTask();
this.autoQueryTaskResult();
}
}
export default Monitor;