Skip to content

Instantly share code, notes, and snippets.

@alexbevi
Last active January 27, 2022 07:44
Show Gist options
  • Select an option

  • Save alexbevi/32dc56923b6d37643c622059b5feee31 to your computer and use it in GitHub Desktop.

Select an option

Save alexbevi/32dc56923b6d37643c622059b5feee31 to your computer and use it in GitHub Desktop.
MongoDB Replica Set Sync Source Tree
function printReplicationTree(rs) {
print("\nReplication Sync Source Tree\n============================");
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
var idMapping = rs.members.reduce((acc, el, i) => {
acc[el.name] = i;
return acc;
}, {});
var root = undefined;
rs.members.forEach(function (el) {
// Handle the root element
if (el.syncSourceHost === "") {
root = el;
return;
}
// Use our mapping to locate the parent element in our data array
var parentEl = rs.members[idMapping[el.syncSourceHost]];
// Add our current el to its parent's `children` array
parentEl.children = [].concat(_toConsumableArray(parentEl.children || []), [el]);
});
function pp(node) {
return "[" + node._id + "] " + node.name + " (" + node.stateStr + ")"
}
function walk(tree) {
var indent = 1;
function innerWalk(tree) {
tree.forEach(function (node) {
if (indent == 1 && node.stateStr !== "PRIMARY")
return;
print('--' + Array(indent).join('--'), pp(node));
if (node.children) {
indent++;
innerWalk(node.children);
}
if (tree.indexOf(node) === tree.length - 1) {
indent--;
}
})
}
innerWalk(tree);
}
walk(rs.members);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment