-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
109 lines (93 loc) · 2.9 KB
/
index.js
File metadata and controls
109 lines (93 loc) · 2.9 KB
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
import os from 'os';
import v8 from 'v8';
import process from 'process';
import pusage from 'pidusage';
export default function (options) {
options = options || {};
const url = options.url || '/health';
const strategy = options.strategy;
if (strategy && typeof strategy !== 'function') {
throw new Error('The parameter of strategy must be a function.');
}
return async function (ctx, next) {
if (url === ctx.url && process.env.NODE_ENV === 'development') {
const monitorData = {
os: getOsInfo(),
process: await getProcessInfo(),
heap: getHeapSpace()
};
monitorData.status = checkHealth(monitorData, strategy) ? 'ok' : 'warn';
ctx.status = monitorData.status === 'ok' ? 200 : 429;
ctx.body = monitorData;
} else if (url === ctx.url && process.env.NODE_ENV === 'production') {
if (strategy) {
const monitorData = {
os: getOsInfo(),
process: await getProcessInfo(),
heap: getHeapSpace()
};
monitorData.status = checkHealth(monitorData, strategy) ? 'ok' : 'warn';
ctx.status = monitorData.status === 'ok' ? 200 : 429;
ctx.body = {status: monitorData.status};
} else {
ctx.body = {status: 'ok'};
}
} else if (`${url}/detail` === ctx.url) {
const monitorData = {
os: getOsInfo(),
process: await getProcessInfo(),
heap: getHeapSpace()
};
monitorData.status = checkHealth(monitorData, strategy) ? 'ok' : 'warn';
ctx.status = monitorData.status === 'ok' ? 200 : 429;
ctx.body = monitorData;
}
return next();
}
};
function checkHealth(monitorData, strategy) {
if (!strategy) {
return true;
}
return strategy(monitorData);
}
function getOsInfo() {
return {
hostname: os.hostname(),
platform: os.platform(),
uptime: os.uptime(),
arch: os.arch(),
cpus: os.cpus(),
avg: os.loadavg(),
memory: {
free: os.freemem(),
total: os.totalmem()
}
}
}
async function getProcessInfo() {
let state = {};
try {
state = await getCpuMemoryPercent();
} catch (ignore) {
}
return {
uptime: process.uptime(),
cpuUsage: process.cpuUsage(),
memoryUsage: process.memoryUsage(),
percent: state
}
}
function getHeapSpace() {
return v8.getHeapSpaceStatistics();
}
function getCpuMemoryPercent() {
return new Promise((resolve, reject) => {
pusage.stat(process.pid, function (err, stat) {
if (err) {
return reject(err);
}
resolve(stat);
})
});
}