Created
April 25, 2014 19:19
-
-
Save ankurcha/11300128 to your computer and use it in GitHub Desktop.
This is a set of scripts we use to reliably drop sharded databases on a MongoDB cluster. The reason for doing this is because mongos is very unreliable when it comes to cleanly and reliably dropping stuff.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function removeDB(n) { | |
| flushConfigs(); | |
| var colls = findChunkedCollections(n); | |
| colls.forEach(function(coll) { | |
| if(!db.getSisterDB(n).getCollection(coll).exists()) { | |
| print("collection did not exist for chunk: " + n + "." + coll) | |
| getPrimaries().forEach(function(p){ | |
| p.getDB(n).createCollection(coll); | |
| }); | |
| } | |
| }); | |
| print("Dropping: " + n + " on all shards"); | |
| printjson(db.getSisterDB(n).dropDatabase()) | |
| getPrimaries().forEach( | |
| function(m){ | |
| print("Dropping: " + n + " on " + m) | |
| printjson(m.getDB(n).dropDatabase()); | |
| } | |
| ); | |
| } | |
| function flushConfigs() { | |
| getActiveRouters().forEach(function(mongos) { | |
| print("Flushing: " + mongos); | |
| try { | |
| mongos.getDB('admin').runCommand({flushRouterConfig:true}); | |
| } catch(e) { | |
| print("Error flushing..."); | |
| printjson(e); | |
| } | |
| }); | |
| } | |
| function getActiveRouters() { | |
| var config = db.getSisterDB('config'); | |
| // only return ones that have been alive in the last hour | |
| return config.mongos.find({ping:{$gt:new Date(new Date() - 60000)}}).map(function(mongos) { | |
| try { | |
| return new Mongo(mongos._id); | |
| } catch (e) { | |
| return db.getMongo(); | |
| } | |
| }); | |
| } | |
| function findChunkedCollections(n) { | |
| var m = {} | |
| var colls = []; | |
| var chunks = db.getSisterDB('config').chunks.find({ns: new RegExp("^" + n + "\.")}).forEach(function(c){ | |
| var coll = c.ns.split('.')[1]; | |
| if(!m[coll]) { | |
| colls.push(coll); | |
| } | |
| m[coll] = true | |
| }); | |
| return colls | |
| } | |
| function findShardMembers(shard, state) { | |
| var urls=shard.host.split("/")[1].split(','); | |
| var members=[]; | |
| new Mongo(urls[0]).adminCommand({replSetGetStatus:1}).members.forEach(function(member) { | |
| if(member.state == state || isNaN(state)) { | |
| members.push(new Mongo(member.name)); | |
| } | |
| }); | |
| return members; | |
| } | |
| function findPrimary(shard){ | |
| return findShardMembers(shard, 1)[0] | |
| } | |
| function getPrimaries() { | |
| return db.getSisterDB("config").shards.find().map(findPrimary) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: