Skip to content

Commit

Permalink
addNewMembers: Check for an available _id value instead of incrementing
Browse files Browse the repository at this point in the history
If the members of the replica set are iterated quickly, it is possible
to exceed the maximum value of _id (255). Instead of incrementing, check
for the first value that isn't being used by an existing member.
  • Loading branch information
bekriebel committed Mar 20, 2018
1 parent 19bdd13 commit becab8b
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/lib/mongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,18 +130,26 @@ var addNewReplSetMembers = function(db, addrToAdd, addrToRemove, shouldForce, do
var addNewMembers = function(rsConfig, addrsToAdd) {
if (!addrsToAdd || !addrsToAdd.length) return;

//Follows what is basically in mongo's rs.add function
var max = 0;
var memberIds = [];
var newMemberId = 0;

// Build a list of existing rs member IDs
for (var i in rsConfig.members) {
if (rsConfig.members[i]._id > max) {
max = rsConfig.members[i]._id;
}
memberIds.push(rsConfig.members[i]._id);
}

for (var i in addrsToAdd) {
var addrToAdd = addrsToAdd[i];

// Search for the next available member ID (max 255)
for (var i = newMemberId; i <= 255; i++) {
if (!memberIds.includes(i)) {
newMemberId = i;
memberIds.push(newMemberId);
break;
}
}

// Somehow we can get a race condition where the member config has been updated since we created the list of
// addresses to add (addrsToAdd) ... so do another loop to make sure we're not adding duplicates
var exists = false;
Expand All @@ -159,7 +167,7 @@ var addNewMembers = function(rsConfig, addrsToAdd) {
}

var cfg = {
_id: ++max,
_id: newMemberId,
host: addrToAdd
};

Expand Down

0 comments on commit becab8b

Please sign in to comment.