Skip to content

Commit

Permalink
feat(sentinel): update sentinels after getting master
Browse files Browse the repository at this point in the history
  • Loading branch information
ddunkin authored and luin committed Jun 8, 2016
1 parent 976c077 commit e3f14b2
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions lib/connectors/sentinel_connector.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,17 @@ SentinelConnector.prototype.connect = function (callback) {
if (typeof this.currentPoint !== 'number') {
this.currentPoint = -1;
}
if (!Array.isArray(this.sentinels)) {
this.sentinels = this.options.sentinels;
}

var _this = this;
var lastError;
connectToNext();

function connectToNext() {
_this.currentPoint += 1;
if (_this.currentPoint === _this.options.sentinels.length) {
if (_this.currentPoint === _this.sentinels.length) {
_this.currentPoint = -1;

var retryDelay;
Expand All @@ -62,7 +65,7 @@ SentinelConnector.prototype.connect = function (callback) {
return;
}

var endpoint = _this.options.sentinels[_this.currentPoint];
var endpoint = _this.sentinels[_this.currentPoint];
_this.resolve(endpoint, function (err, resolved) {
if (!_this.connecting) {
callback(new Error('Connection is closed.'));
Expand All @@ -84,13 +87,48 @@ SentinelConnector.prototype.connect = function (callback) {
}
};

SentinelConnector.prototype.updateSentinels = function (client, callback) {
var _this = this;
client.sentinel('sentinels', this.options.name, function (err, result) {
if (err) {
client.disconnect();
return callback(err);
}
if (Array.isArray(result)) {
for (var i = 0; i < result.length; ++i) {
var sentinel = utils.packObject(result[i]);
var flags = sentinel.flags ? sentinel.flags.split(',') : [];
if (flags.indexOf('disconnected') === -1 && sentinel.ip && sentinel.port) {
var endpoint = { host: sentinel.ip, port: parseInt(sentinel.port) };
var isDuplicate = _this.sentinels.some(function (o) {
return o.host === endpoint.host && o.port === endpoint.port;
});
if (!isDuplicate) {
debug('adding sentinel %s:%s', endpoint.host, endpoint.port);
_this.sentinels.push(endpoint);
}
}
}
debug('sentinels', _this.sentinels);
}
callback(null);
});
};

SentinelConnector.prototype.resolveMaster = function (client, callback) {
var _this = this;
client.sentinel('get-master-addr-by-name', this.options.name, function (err, result) {
client.disconnect();
if (err) {
client.disconnect();
return callback(err);
}
callback(null, Array.isArray(result) ? { host: result[0], port: result[1] } : null);
_this.updateSentinels(client, function (err) {
client.disconnect();
if (err) {
return callback(err);
}
callback(null, Array.isArray(result) ? { host: result[0], port: result[1] } : null);
});
});
};

Expand Down

0 comments on commit e3f14b2

Please sign in to comment.