-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmyStatsdServer.js
73 lines (56 loc) · 1.76 KB
/
myStatsdServer.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
//custom udp server ip-port
var SERVER_PORT = 1234;
var SERVER_HOST ='127.0.0.1';
//statsd server ip-port
var STATSD_PORT = 8125;
var STATSD_HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
//redis server connection
var redis = require('redis');
var redisClient = redis.createClient(); //creates a new client
//function parses data received from statsd client
//and saves data to redis server
function incrementInRedis(data) {
var pipeIndex = data.lastIndexOf("|");
if(pipeIndex == false)
return false;
//check for the operation type
var operation = data.substring(pipeIndex+1);
if(operation == 'c') {
var counter = data.substring(0,data.indexOf(":"));
var increBy = data.substring(data.indexOf(":")+1,pipeIndex);
redisClient.incrby(counter,increBy,function(err, reply) {
if(err) {
throw err;
}
console.log("Value of counter " + reply);
});
return true;
}
return false;
}
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
//increment counter in redis
if(incrementInRedis(message.toString())) {
//after counter value incremented in redis , pass it on to statsd server
var message = new Buffer(message);
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, STATSD_PORT, STATSD_HOST, function(err, bytes) {
if (err) {
console.log("Error received " + err);
}
console.log( message +' sent to ' + STATSD_HOST +':'+ STATSD_PORT);
client.close();
});
}
else {
console.log("Filed to update in redis");
}
});
//listen to the port on host
server.bind(SERVER_PORT, SERVER_HOST);