joyent-portal/control-tower/lib/index.js

125 lines
2.7 KiB
JavaScript
Raw Normal View History

2017-05-13 00:46:39 +03:00
'use strict';
const CMonClient = require('cmon-client');
const PortalData = require('portal-data');
const VAsync = require('vasync');
module.exports = class {
constructor (options) {
options = options || {};
2017-05-15 21:18:18 +03:00
this._settings = options;
2017-05-13 00:46:39 +03:00
this._data = new PortalData(options.data);
this._cmon = new CMonClient(options.cmon);
this._deployments = {};
}
start (cb) {
this._data.connect((err) => {
if (err) {
return cb(err);
}
this._poll();
this._data.deploymentChanges((err, changes) => {
2017-05-15 21:18:18 +03:00
if (err) {
console.error(err);
}
2017-05-13 00:46:39 +03:00
if (changes) {
this._refreshContainers(changes.id);
}
});
});
}
_refreshContainers (deploymentId) {
this._data.getServices(deploymentId).then((services) => {
2017-05-15 21:18:18 +03:00
this._deployments[deploymentId] = services[0].containers;
2017-05-13 00:46:39 +03:00
});
}
_listContainers () {
let containers = [];
const deploymentIds = Object.keys(this._deployments);
deploymentIds.forEach((deploymentId) => {
containers = containers.concat(this._deployments[deploymentId]);
});
return containers;
}
_poll () {
if (this._isPolling) {
return;
}
const finish = () => {
this._isPolling = false;
2017-05-15 21:18:18 +03:00
setTimeout(() => { this._poll(); }, this._settings.frequency || 5000);
2017-05-13 00:46:39 +03:00
};
2017-05-15 21:18:18 +03:00
const containers = this._listContainers();
if (!containers || !containers.length) {
return finish();
}
2017-05-13 00:46:39 +03:00
this._isPolling = true;
VAsync.forEachParallel({
2017-05-15 21:18:18 +03:00
func: (containerId, next) => {
this._cmon.metrics(containerId, (err, metrics) => {
if (err) {
return next(err);
}
next(null, { containerId, metrics });
});
},
inputs: containers
2017-05-13 00:46:39 +03:00
}, (err, results) => {
if (err) {
console.error(err);
return finish();
}
2017-05-15 21:18:18 +03:00
if (!results.successes || !results.successes.length) {
return finish();
}
this._saveMetrics(results.successes, finish);
});
}
_saveMetrics (successes, cb) {
const metricOperations = successes.map((success) => {
const metrics = this._formatMetrics(success);
return this._data.insertMetrics(success.containerId, metrics);
});
Promise.all(metricOperations).then(() => {
cb();
}).catch((err) => {
cb(err);
2017-05-13 00:46:39 +03:00
});
}
2017-05-15 21:18:18 +03:00
_formatMetrics (success) {
const time = success.metrics.find((metric) => {
if (metric.name === 'time_of_day') {
return metric;
}
});
const formatted = success.metrics.map((metric) => {
return {
name: metric.name,
value: metric.metrics[0].value,
time: time.metrics[0].value
};
});
return formatted;
2017-05-13 00:46:39 +03:00
}
2017-05-15 21:18:18 +03:00
};