Advertisement
Guest User

Untitled

a guest
Nov 25th, 2016
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. You can't simply run a backup on a specific node in a cluster, since its role can change to master and lead to an overload for it.
  2. You need some intelligence to choose the right node (slave) and allow multiple nodes to execute the backup; you want to be safe without
  3. designing a specific node to run it.
  4.  
  5. This is my approach:
  6. * schedule the script below in any MongoDB host
  7. * the script will exit if it's running on a master
  8. * if it's a slave, it will wait a random interval, check if there's a lock document on the master and if not present perform the backup.
  9.  
  10. in such a way you are covered from any single node failure
  11.  
  12. #!/bin/bash
  13. #set -x # for debugging
  14. DBUSERNAME=''
  15. DBPASSWORD=''
  16.  
  17. # Please specify a DB!
  18. DB=$1
  19. #check if it's running on the master
  20. MASTER=$(mongo -u ${DBUSERNAME} -p ${DBPASSWORD} --quiet --eval 'rs.isMaster().ismaster' admin)
  21. if [ "$MASTER" == 'true' ];then
  22. echo quitting
  23. else
  24. SLEEP=$(shuf -i 0-5 -n 1)
  25. echo running on a slave, sleeping for $SLEEP seconds
  26. sleep $SLEEP
  27. LOCK=$(echo -e "use $DB\n rs.slaveOk()\n db.lock.find({\"status\":\"bck created\"})\n" |mongo -u ${DBUSERNAME} -p ${DBPASSWORD} --quiet admin)
  28. if [ "$LOCK" == "switched to db $DB" ];then
  29. echo "backing up!"
  30. # find master ip
  31. IP=$(mongo -u ${DBUSERNAME} -p ${DBPASSWORD} --quiet --eval 'db.isMaster().primary' admin)
  32. echo informing master $IP, this node will hold the lock
  33. # all slaves are read-only, so we connect to master to acquire the lock :)
  34. echo -e "use $DB\n db.lock.insert( {\"createdAt\": new Date(),\"host\": hostname(),\"status\":\"bck created\"})\n" | mongo -u ${DBUSERNAME} -p ${DBPASSWORD} --host=${IP} --quiet admin
  35.  
  36. #decide a directory to save
  37. mongodump -u ${DBUSERNAME} -p ${DBPASSWORD} -d ${DB} --authenticationDatabase=admin
  38.  
  39. # connect to master to remove the lock :)
  40. echo -e "use $DB\n db.lock.remove({\"status\":\"bck created\"})" | mongo -u ${DBUSERNAME} -p ${DBPASSWORD} --host=${IP} --quiet admin
  41. else
  42. echo "another node is backing up:"
  43. echo $LOCK
  44. fi
  45.  
  46. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement