-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
monitor.js
54 lines (43 loc) · 962 Bytes
/
monitor.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
var net = require('net');
var request = require('request');
var sockets = 0;
var timeout;
var noop = function() {};
var gc = function() {
if (sockets) return;
clearTimeout(timeout);
server.close();
};
var server = net.createServer(function(socket) {
sockets++;
var buf = '';
var hosts = {};
socket.setEncoding('utf-8');
socket.on('data', function(message) {
var messages = (buf + message).split('\n');
buf = messages.pop();
messages.forEach(function(message) {
message = JSON.parse(message);
if (message.up) {
hosts[message.up] = 1;
} else {
delete hosts[message.down];
}
});
});
socket.on('error', function() {
socket.destroy();
});
socket.on('end', function() {
socket.destroy();
});
socket.on('close', function() {
sockets--;
Object.keys(hosts).forEach(function(host) {
request.post(host + '/gc', noop);
});
gc();
});
});
timeout = setTimeout(gc, 10000);
server.listen(63567, '127.0.0.1');