標籤:shell指令碼 linux培訓 mysql主從同步
企業面試題1:(生產實戰案例):監控MySQL主從同步是否異常,如果異常,則傳送簡訊或者郵件給管理員。提示:如果沒主從同步環境,可以用下面文本放到檔案裡讀取來類比:
階段1:開發一個守護進程指令碼每30秒實現檢測一次。
階段2:如果同步出現如下錯誤號碼(1158,1159,1008,1007,1062),則跳過錯誤。
階段3:請使用數組技術實現上述指令碼(擷取主從判斷及錯誤號碼部分)
此題來自:http://oldboy.blog.51cto.com/2561410/1632876
解答參考1:
#!/bin/sh#oldboy linux training#2015-05-17#說明:本指令碼來自老男孩linux21期學員張耀開發!# Source function library.. /etc/init.d/functions# Defined variablesMysqlUser=rootMysqlPass=oldboy123MysqlPort=3307Mysqlsock=/data/$MysqlPort/mysql.sockErrorNo=(1158 1159 1008 1007 1062)errorlog=/tmp/error_skip.logMysqlCmd="/application/mysql/bin/mysql -u$MysqlUser -p$MysqlPass -S $Mysqlsock"# Judge mysql server is ok?[ -S $Mysqlsock ] ||{echo "Maybe MySQL have someting wrong"exit 1}# Defined skip error Functionsfunction error_skip(){local flagflag=0for num in ${ErrorNo[@]} do if [ "$1" == "$num" ];then $MysqlCmd -e‘stop slave;set global sql_slave_skip_counter=1;start slave;‘ echo "$(date +%F_%R) $1" >>$errorlog else echo "$(date +%F_%R) $1" >>$errorlog ((flag++)) fidone[ "$flag" == "${#ErrorNo[@]}" ] &&{action "MySQL Slave" /bin/falseuniq $errorlog|mail -s "MySQL Slave is error" [email protected]}}# Defined check slave Functionsfunction check_slave(){MyResult=`$MysqlCmd -e‘show slave status\G‘|egrep ‘_Running|Behind_Master|SQL_Errno‘ |awk ‘{print $NF}‘`array=($MyResult)if [ "${array[0]}" == "Yes" -a "${array[1]}" == "Yes" -a "${array[2]}" == "0" ] thenaction "MySQL Slave" /bin/true||error_skip ${array[3]}fi}# Defined main Functionsfunction main(){while true do check_slave sleep 60done}main
解答參考2:
#!/bin/sh#oldboy linux#2015-05-17#說明:本指令碼來自老男孩教育21期學員李新宇!USER=rootPASSWORD=123456PORT=3307error=(1158 1159 1008 1007 1062)MYSQLCMD="mysql -u$USER -p$PASSWORD -S /data/$PORT/mysql.sock"is_run(){ [ `lsof -i:$PORT|wc -l` -lt 2 ]&&{ echo "mysql server is stopped" exit 1 }}status_array(){ status=($($MYSQLCMD -e "show slave status\G"|egrep "_Running|Last_Errno|Behind_Master"|awk ‘{print $NF}‘))}status_error(){for((i=0;i<${#error[*]};i++))do if [ "$1" == "${error[$i]}" ] then $MYSQLCMD -e "stop slave;set global sql_slave_skip_counter=1;start slave;" else echo "MySQL slave is failed, errorno is $1" fidone}judge_slave(){ status_array if [ "${status[0]}" == "Yes" -a "${status[1]}" == "Yes" -a "${status[3]}" = "0" ] then echo "MySQL slave is ok" else status_error ${status[2]} fi}main(){while truedo is_run judge_slave sleep 60done}main
老男孩老師提示:企業實際情境,還可能根據主庫寫時間戳記的方式更嚴格的判斷資料庫是否同步。
本文出自 “老男孩linux營運” 部落格,請務必保留此出處http://oldboy.blog.51cto.com/2561410/1652086
監控MySQL主從同步是否異常並警示企業案例類比