Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
MongoDB Replica Set Oplog Resize Helper Script
#!/bin/sh
function usage() {
echo
echo "Resizing the local MongoDB RS Oplog"
echo
echo "Usage:"
echo "mongodb_resize_oplog <mongodb local port> <mongodb data path> <new oplog size in gb> <user:group for data dir>"
echo
echo "Example:"
echo "resize-mongodb-oplog.sh 27017 /mongodb/data 8 mongodb:users"
}
ask() {
echo "Continue? (y/n)"
read i
if [ "$i" != "y" ]
then
echo "Aborting, remember to clean up the steps we already did."
exit 1
fi
}
resizeOplog() {
MONGO_INSTANCE_PORT=$1
MONGO_DATA_PATH=$2
MONGO_OPLOG_SIZE=$3
MONGO_USER_GROUP=$4
echo "1. Step down node"
ask
echo "rs.stepDown()" | mongo localhost:${MONGO_INSTANCE_PORT}
echo "2. Shutdown down node"
ask
echo "use admin
db.shutdownServer()" | mongo localhost:${MONGO_INSTANCE_PORT}
sleep 2
echo "3. Restart in local mode"
ask
mongod --port 37017 --dbpath ${MONGO_DATA_PATH} --directoryperdb --fork --logpath /tmp/mongo.log
echo "4. Dump oplog.rs"
ask
mongodump --db local --collection 'oplog.rs' --port 37017
echo "5. Save last seed of oplog.rs in temp"
ask
echo "use local
db = db.getSiblingDB('local')
db.temp.drop()
db.temp.save( db.oplog.rs.find( { }, { ts: 1, h: 1 } ).sort( {\$natural : -1} ).limit(1).next() )
db.temp.find()" | mongo localhost:37017
echo "6. Drop current oplog.rs"
ask
echo "use local
db = db.getSiblingDB('local')
db.oplog.rs.drop()" | mongo localhost:37017
echo "6. Create new empty oplog.rs with ${MONGO_OPLOG_SIZE} GB"
ask
echo "use local
db = db.getSiblingDB('local')
db.runCommand( { create: 'oplog.rs', capped: true, size: (${MONGO_OPLOG_SIZE} * 1024 * 1024 * 1024) } )" | mongo localhost:37017
echo "7. Restore saved seed in new oplog.rs"
ask
echo "use local
db = db.getSiblingDB('local')
db.oplog.rs.save( db.temp.findOne() )
db.temp.drop()
db.oplog.rs.find()" | mongo localhost:37017
echo "8. Shutdown local mode"
ask
echo "use admin
db.shutdownServer()" | mongo localhost:37017
sleep 2
chown -R ${MONGO_USER_GROUP} /mongoDB/node/data
echo "9. Start in normal RS mode"
ask
/etc/init.d/mongod start
echo "Finished resize of oplog.rs, please verify and remove logfile /tmp/mongo.log and dumps of old oplog.rs in working directory"
}
if [ "$#" == 4 ]; then
resizeOplog $1 $2 $3 $4
else
usage
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment