2
0

mysql-flush.sh.sample 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/bin/sh
  2. # Flush MySQL tables to the disk before the filesystem is frozen.
  3. # At the same time, this keeps a read lock in order to avoid write accesses
  4. # from the other clients until the filesystem is thawed.
  5. MYSQL="/usr/bin/mysql"
  6. MYSQL_OPTS="-uroot" #"-prootpassword"
  7. FIFO=/var/run/mysql-flush.fifo
  8. # Check mysql is installed and the server running
  9. [ -x "$MYSQL" ] && "$MYSQL" $MYSQL_OPTS < /dev/null || exit 0
  10. flush_and_wait() {
  11. printf "FLUSH TABLES WITH READ LOCK \\G\n"
  12. trap 'printf "$(date): $0 is killed\n">&2' HUP INT QUIT ALRM TERM
  13. read < $FIFO
  14. printf "UNLOCK TABLES \\G\n"
  15. rm -f $FIFO
  16. }
  17. case "$1" in
  18. freeze)
  19. mkfifo $FIFO || exit 1
  20. flush_and_wait | "$MYSQL" $MYSQL_OPTS &
  21. # wait until every block is flushed
  22. while [ "$(echo 'SHOW STATUS LIKE "Key_blocks_not_flushed"' |\
  23. "$MYSQL" $MYSQL_OPTS | tail -1 | cut -f 2)" -gt 0 ]; do
  24. sleep 1
  25. done
  26. # for InnoDB, wait until every log is flushed
  27. INNODB_STATUS=$(mktemp /tmp/mysql-flush.XXXXXX)
  28. [ $? -ne 0 ] && exit 2
  29. trap "rm -f $INNODB_STATUS; exit 1" HUP INT QUIT ALRM TERM
  30. while :; do
  31. printf "SHOW ENGINE INNODB STATUS \\G" |\
  32. "$MYSQL" $MYSQL_OPTS > $INNODB_STATUS
  33. LOG_CURRENT=$(grep 'Log sequence number' $INNODB_STATUS |\
  34. tr -s ' ' | cut -d' ' -f4)
  35. LOG_FLUSHED=$(grep 'Log flushed up to' $INNODB_STATUS |\
  36. tr -s ' ' | cut -d' ' -f5)
  37. [ "$LOG_CURRENT" = "$LOG_FLUSHED" ] && break
  38. sleep 1
  39. done
  40. rm -f $INNODB_STATUS
  41. ;;
  42. thaw)
  43. [ ! -p $FIFO ] && exit 1
  44. echo > $FIFO
  45. ;;
  46. *)
  47. exit 1
  48. ;;
  49. esac