2016-10-20 00:42:53 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var request = require('request');
|
2016-10-20 17:12:08 +08:00
|
|
|
var debug = require('../../util/debug')('capacity-http-simple');
|
2016-10-20 00:42:53 +08:00
|
|
|
|
2019-12-24 01:19:08 +08:00
|
|
|
function HttpSimpleCapacity (host, capacityEndpoint) {
|
2016-10-20 00:42:53 +08:00
|
|
|
this.host = host;
|
|
|
|
this.capacityEndpoint = capacityEndpoint;
|
2016-10-20 18:06:51 +08:00
|
|
|
|
|
|
|
this.lastResponse = null;
|
|
|
|
this.lastResponseTime = 0;
|
2016-10-20 00:42:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = HttpSimpleCapacity;
|
|
|
|
|
2019-12-24 01:19:08 +08:00
|
|
|
HttpSimpleCapacity.prototype.getCapacity = function (callback) {
|
|
|
|
this.getResponse(function (err, values) {
|
2016-10-20 00:42:53 +08:00
|
|
|
var capacity = 1;
|
|
|
|
|
2016-10-20 17:12:08 +08:00
|
|
|
if (err) {
|
|
|
|
return callback(null, capacity);
|
|
|
|
}
|
2016-10-20 00:42:53 +08:00
|
|
|
|
2016-10-20 17:12:08 +08:00
|
|
|
var availableCores = parseInt(values.available_cores, 10);
|
2016-10-20 00:42:53 +08:00
|
|
|
|
2016-10-20 17:12:08 +08:00
|
|
|
capacity = Math.max(availableCores, 1);
|
|
|
|
capacity = Number.isFinite(capacity) ? capacity : 1;
|
2016-10-20 00:42:53 +08:00
|
|
|
|
|
|
|
debug('host=%s, capacity=%s', this.host, capacity);
|
|
|
|
return callback(null, capacity);
|
|
|
|
}.bind(this));
|
|
|
|
};
|
2016-10-20 17:12:08 +08:00
|
|
|
|
2019-12-24 01:19:08 +08:00
|
|
|
HttpSimpleCapacity.prototype.getResponse = function (callback) {
|
2016-10-20 17:12:08 +08:00
|
|
|
var requestParams = {
|
|
|
|
method: 'POST',
|
|
|
|
url: this.capacityEndpoint,
|
2016-10-20 18:06:17 +08:00
|
|
|
timeout: 2000,
|
2016-10-20 17:12:08 +08:00
|
|
|
json: true
|
|
|
|
};
|
|
|
|
debug('getCapacity(%s)', this.host);
|
2016-10-20 18:06:51 +08:00
|
|
|
|
|
|
|
// throttle requests for 500 ms
|
|
|
|
var now = Date.now();
|
|
|
|
if (this.lastResponse !== null && ((now - this.lastResponseTime) < 500)) {
|
|
|
|
return callback(null, this.lastResponse);
|
|
|
|
}
|
|
|
|
|
2019-12-24 01:19:08 +08:00
|
|
|
request.post(requestParams, function (err, res, jsonRes) {
|
2016-10-20 17:12:08 +08:00
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
if (jsonRes && jsonRes.retcode === 0) {
|
2016-10-20 18:06:51 +08:00
|
|
|
this.lastResponse = jsonRes.return_values || {};
|
|
|
|
// We could go more aggressive by updating lastResponseTime on failures.
|
|
|
|
this.lastResponseTime = now;
|
|
|
|
|
|
|
|
return callback(null, this.lastResponse);
|
2016-10-20 17:12:08 +08:00
|
|
|
}
|
|
|
|
return callback(new Error('Could not retrieve information from endpoint'));
|
2016-10-20 18:06:51 +08:00
|
|
|
}.bind(this));
|
2016-10-20 17:12:08 +08:00
|
|
|
};
|