-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverChecker.js
74 lines (60 loc) · 1.81 KB
/
serverChecker.js
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
const net = require('net');
const async = require('async');
const Server = require('./models/Server');
require('dotenv').config()
const CONCURRENT_LIMIT = 10;
const checkServerStatus = (ip, port) => {
return new Promise((resolve, reject) => {
const client = new net.Socket();
client.setTimeout(5000);
client.connect(port, ip, () => {
resolve('on');
client.end();
});
client.on('timeout', () => {
client.destroy();
resolve('off');
});
client.on('error', () => {
resolve('off');
});
});
};
exports.checkAndRecordAllServers = async () => {
try {
const servers = await Server.find();
const tasks = servers.map(server => {
return async () => {
try {
await checkAndRecordServerStatus(server.ip, server.port);
} catch (err) {
console.error('Error checking/recording server:', err);
}
};
});
async.parallelLimit(tasks, CONCURRENT_LIMIT, (err) => {
if (err) {
console.error('Error:', err);
}
});
} catch (err) {
console.error('Error fetching servers:', err);
}
};
const MAX_CHECKS = 5000;
const checkAndRecordServerStatus = async (ip, port) => {
const status = await checkServerStatus(ip, port);
const update = {
$push: {
checks: {
$each: [{
timestamp: new Date(),
status: status
}],
$slice: -MAX_CHECKS // This keeps only the last 288 checks
}
}
};
await Server.findOneAndUpdate({ ip, port }, update);
};
exports.checkServerStatus = checkServerStatus;