embark/lib/core/services_monitor.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-03-29 17:50:05 +00:00
let async = require('../utils/async_extend.js');
// TODO: need to separate colors from states
// i.e use status: /on|off|warn/ not /red|green/
// it's up to the logger or console to determine the color
2017-03-30 11:12:39 +00:00
class ServicesMonitor {
constructor(options) {
this.events = options.events;
this.logger = options.logger;
this.checkList = {};
this.checkTimers = {};
this.checkState = {};
this.working = false;
}
}
2017-03-30 11:12:39 +00:00
ServicesMonitor.prototype.initCheck = function (checkName) {
2017-03-29 17:50:05 +00:00
let self = this;
let check = this.checkList[checkName];
2017-03-30 11:12:39 +00:00
if (!check) {
return false;
}
2017-03-30 11:12:39 +00:00
self.events.on('check:' + checkName, function (obj) {
// TODO: see todo above
if (check && check.status === 'red' && obj.status === 'green') {
self.events.emit('check:backOnline:' + checkName);
}
if (check && check.status === 'green' && obj.status === 'red') {
self.events.emit('check:wentOffline:' + checkName);
}
self.checkState[checkName] = obj.name[obj.status];
check.status = obj.status;
self.events.emit("servicesState", self.checkState);
});
if (check.interval !== 0) {
2017-03-30 11:12:39 +00:00
self.checkTimers[checkName] = setInterval(function () {
check.fn.call(check.fn, function (obj) {
self.events.emit('check:' + checkName, obj);
});
}, check.interval);
}
2017-03-30 11:12:39 +00:00
check.fn.call(check.fn, function (obj) {
self.events.emit('check:' + checkName, obj);
});
};
2017-03-30 11:12:39 +00:00
ServicesMonitor.prototype.addCheck = function (checkName, checkFn, time) {
2017-03-29 17:50:05 +00:00
let self = this;
this.logger.trace('add check: ' + checkName);
this.checkList[checkName] = {fn: checkFn, interval: time || 5000};
if (this.working) {
this.initCheck(checkName);
}
};
2017-03-30 11:12:39 +00:00
ServicesMonitor.prototype.stopCheck = function (name) {
2017-03-11 16:23:42 +00:00
clearInterval(this.checkTimers[name]);
delete this.checkTimers[name];
delete this.checkList[name];
delete this.checkState[name];
};
2017-03-30 11:12:39 +00:00
ServicesMonitor.prototype.startMonitor = function () {
2017-03-29 17:50:05 +00:00
let self = this;
this.working = true;
this.logger.trace('startMonitor');
2017-03-30 11:12:39 +00:00
async.eachObject(this.checkList, function (checkName, check, callback) {
self.initCheck(checkName);
2017-03-11 16:17:52 +00:00
callback();
2017-03-30 11:12:39 +00:00
}, function (err) {
2017-03-11 16:17:52 +00:00
if (err) {
self.logger.error("error running service check");
self.logger.error(err.message);
}
});
};
module.exports = ServicesMonitor;