-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathprobe_master.js
69 lines (54 loc) · 1.83 KB
/
probe_master.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
const tls = require('tls');
tls.DEFAULT_ECDH_CURVE = 'auto'; // Fix that should not be needed but is because Node is stupid
const config = require('./config');
const queue = require('./queue');
const Instance = require('./models/instance');
const Probe = require('./models/probe');
const Ping = require('./models/ping');
const io = require('socket.io')();
io.use((socket, next) => {
if(socket.handshake.query.token === config.probe.token) {
if(typeof socket.handshake.query.probe === 'string') {
Probe.findByPk(socket.handshake.query.probe).then((probe) => {
if(probe) {
console.log('probe #' + socket.handshake.query.probe + ':' + probe.name + ' connecting');
next();
} else {
next(new Error('invalid probe'));
}
});
return;
}
}
return next(new Error('unauthorized'));
});
io.on('connection', (socket) => {
console.log('probe #' + socket.handshake.query.probe + ' connected');
socket.on('ping_results', (results) => {
console.log(results.length + ' results received, saving');
Ping.bulkCreate(results.map(r => ({
instance: r.inst,
probeId: socket.handshake.query.probe,
success: !r.err,
error: r.err,
average: r.avg,
jitter: r.jit
}))).catch(console.error);
});
});
io.listen(8738);
process('ping_all', 1, pingAll);
function process(job, n, fn) {
queue.process(job, n, (job, cb) => {
fn(job.data).then(cb).catch(cb);
});
}
async function pingAll() {
console.log('sending ping all');
io.emit('ping', (await Instance.findAll({
where: {
dead: false,
blacklisted: false
}
})).map(i => ({id: i.id, name: i.name})));
}