mongo-healthcheck.sh 928 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/bin/bash
  2. mongostart=`stat -c %Z /proc/1`
  3. curtime=`date +%s`
  4. if [[ $(($mongostart-$curtime)) -le "180" ]]; then
  5. echo "0"
  6. exit 0
  7. fi
  8. if [[ -n $1 ]]; then
  9. myhost=$1
  10. else
  11. myhost=localhost:27017
  12. fi
  13. state=`mongo --host $myhost --quiet --eval 'var i=0; rs.status().members.forEach( function(myDoc) { if (myDoc.self==true) { print(myDoc.stateStr); i++;} })' |tail -1`
  14. if [[ $state == "PRIMARY" ]];then
  15. echo "0"
  16. exit 0
  17. fi
  18. if [[ $state == "SECONDARY" ]];then
  19. date=`mongo --host $myhost --eval 'rs.status().date;' |tail -1`
  20. dates=`date -d "$date" "+%s"`
  21. lastHeartbeat=`mongo --host $myhost --quiet --eval 'var i=0; rs.status().members.forEach( function(myDoc) { if (myDoc.stateStr=="PRIMARY") { print(myDoc.lastHeartbeat); i++;} })' |tail -1`
  22. datelh=`date -d "$lastHeartbeat" "+%s"`
  23. if [[ $(($dates-$datelh)) -le "60" ]]; then
  24. echo "0"
  25. exit 0
  26. fi
  27. fi
  28. echo "1"
  29. exit 1