2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2015-09-15 00:47:01 +08:00
|
|
|
var _ = require('underscore');
|
|
|
|
var debug = require('debug')('windshaft:stats_client');
|
|
|
|
var StatsD = require('node-statsd').StatsD;
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
/**
|
|
|
|
* Returns an StatsD instance or an stub object that replicates the StatsD public interface so there is no need to
|
|
|
|
* keep checking if the stats_client is instantiated or not.
|
|
|
|
*
|
|
|
|
* The first call to this method implies all future calls will use the config specified in the very first call.
|
|
|
|
*
|
|
|
|
* TODO: It's far from ideal to use make this a singleton, improvement desired.
|
|
|
|
* We proceed this way to be able to use StatsD from several places sharing one single StatsD instance.
|
|
|
|
*
|
|
|
|
* @param config Configuration for StatsD, if undefined it will return an stub
|
|
|
|
* @returns {StatsD|Object}
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
getInstance: function (config) {
|
2015-09-15 00:47:01 +08:00
|
|
|
if (!this.instance) {
|
|
|
|
var instance;
|
|
|
|
|
|
|
|
if (config) {
|
|
|
|
instance = new StatsD(config);
|
|
|
|
instance.last_error = { msg: '', count: 0 };
|
|
|
|
instance.socket.on('error', function (err) {
|
2019-11-14 03:08:04 +08:00
|
|
|
var lastErr = instance.last_error;
|
|
|
|
var lastMsg = lastErr.msg;
|
|
|
|
var thisMsg = '' + err;
|
|
|
|
if (thisMsg !== lastMsg) {
|
2019-10-22 01:07:24 +08:00
|
|
|
debug('statsd client socket error: ' + err);
|
2015-09-15 00:47:01 +08:00
|
|
|
instance.last_error.count = 1;
|
2019-11-14 03:08:04 +08:00
|
|
|
instance.last_error.msg = thisMsg;
|
2015-09-15 00:47:01 +08:00
|
|
|
} else {
|
2019-11-14 03:08:04 +08:00
|
|
|
++lastErr.count;
|
|
|
|
if (!lastErr.interval) {
|
2015-09-15 00:47:01 +08:00
|
|
|
instance.last_error.interval = setInterval(function () {
|
|
|
|
var count = instance.last_error.count;
|
|
|
|
if (count > 1) {
|
2019-10-22 01:07:24 +08:00
|
|
|
debug('last statsd client socket error repeated ' + count + ' times');
|
2015-09-15 00:47:01 +08:00
|
|
|
instance.last_error.count = 1;
|
|
|
|
clearInterval(instance.last_error.interval);
|
|
|
|
instance.last_error.interval = null;
|
|
|
|
}
|
|
|
|
}, 1000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
var stubFunc = function (stat, value, sampleRate, callback) {
|
|
|
|
if (_.isFunction(callback)) {
|
|
|
|
callback(null, 0);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
instance = {
|
|
|
|
timing: stubFunc,
|
|
|
|
increment: stubFunc,
|
|
|
|
decrement: stubFunc,
|
|
|
|
gauge: stubFunc,
|
|
|
|
unique: stubFunc,
|
|
|
|
set: stubFunc,
|
|
|
|
sendAll: stubFunc,
|
|
|
|
send: stubFunc
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
this.instance = instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.instance;
|
|
|
|
}
|
2018-10-23 23:45:42 +08:00
|
|
|
};
|