欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

线上MYSQL同步报错故障处理方法总结(必看篇)

程序员文章站 2023-11-25 13:08:58
前言 在发生故障切换后,经常遇到的问题就是同步报错,数据库很小的时候,dump完再导入很简单就处理好了,但线上的数据库都150g-200g,如果用单纯的这种方法,成本太高...

前言

在发生故障切换后,经常遇到的问题就是同步报错,数据库很小的时候,dump完再导入很简单就处理好了,但线上的数据库都150g-200g,如果用单纯的这种方法,成本太高,故经过一段时间的摸索,总结了几种处理方法。

生产环境架构图

目前现网的架构,保存着两份数据,通过异步复制做的高可用集群,两台机器提供对外服务。在发生故障时,切换到slave上,并将其变成master,坏掉的机器反向同步新的master,在处理故障时,遇到最多的就是主从报错。下面是我收录下来的报错信息。

常见错误

最常见的3种情况

这3种情况是在ha切换时,由于是异步复制,且sync_binlog=0,会造成一小部分binlog没接收完导致同步报错。

第一种:在master上删除一条记录,而slave上找不到。

last_sql_error: could not execute delete_rows event on table hcy.t1;
can't find record in 't1',
error_code: 1032; handler error ha_err_key_not_found;
the event's master log mysql-bin.000006, end_log_pos 254

第二种:主键重复。在slave已经有该记录,又在master上插入了同一条记录。

last_sql_error: could not execute write_rows event on table hcy.t1;
duplicate entry '2' for key 'primary',
error_code: 1062;
handler error ha_err_found_dupp_key; the event's master log mysql-bin.000006, end_log_pos 924

第三种:在master上更新一条记录,而slave上找不到,丢失了数据。

last_sql_error: could not execute update_rows event on table hcy.t1;
can't find record in 't1',
error_code: 1032;
handler error ha_err_key_not_found; the event's master log mysql-bin.000010, end_log_pos 263

异步半同步区别

异步复制
简单的说就是master把binlog发送过去,不管slave是否接收完,也不管是否执行完,这一动作就结束了.

半同步复制
简单的说就是master把binlog发送过去,slave确认接收完,但不管它是否执行完,给master一个信号我这边收到了,这一动作就结束了。(谷歌写的代码,5.5上正式应用。)

异步的劣势
当master上写操作繁忙时,当前pos点例如是10,而slave上io_thread线程接收过来的是3,此时master宕机,会造成相差7个点未传送到slave上而数据丢失。

特殊的情况

slave的中继日志relay-bin损坏。
last_sql_error: error initializing relay log position: i/o error reading the header from the binary log
last_sql_error: error initializing relay log position: binlog has bad magic number;
it's not a binary log file that can be used by this version of mysql

这种情况slave在宕机,或者非法关机,例如电源故障、主板烧了等,造成中继日志损坏,同步停掉。

人为失误需谨慎:多台slave存在重复server-id
这种情况同步会一直延时,永远也同步不完,error错误日志里一直出现上面两行信息。解决方法就是把server-id改成不一致即可。

slave: received end packet from server, apparent master shutdown:
slave i/o thread: failed reading log event, reconnecting to retry, log 'mysql-bin.000012' at postion 106

问题处理

删除失败

在master上删除一条记录,而slave上找不到。

last_sql_error: could not execute delete_rows event on table hcy.t1;
can't find record in 't1',
error_code: 1032; handler error ha_err_key_not_found;
the event's master log mysql-bin.000006, end_log_pos 254

解决方法:

由于master要删除一条记录,而slave上找不到故报错,这种情况主上都将其删除了,那么从机可以直接跳过。可用命令:

stop slave;
set global sql_slave_skip_counter=1;
start slave;

如果这种情况很多,可用我写的一个脚本skip_error_replcation.sh,默认跳过10个错误(只针对这种情况才跳,其他情况输出错误结果,等待处理),这个脚本是参考maakit工具包的mk-slave-restart原理用shell写的,功能上定义了一些自己的东西,不是无论什么错误都一律跳过。)

主键重复

在slave已经有该记录,又在master上插入了同一条记录。

last_sql_error: could not execute write_rows event on table hcy.t1; 
duplicate entry '2' for key 'primary', 
error_code: 1062; 
handler error ha_err_found_dupp_key; the event's master log mysql-bin.000006, end_log_pos 924

解决方法:

在slave上用desc hcy.t1; 先看下表结构:

mysql> desc hcy.t1;
+-------+---------+------+-----+---------+-------+
| field | type  | null | key | default | extra |
+-------+---------+------+-----+---------+-------+
| id  | int(11) | no  | pri | 0    |    | 
| name | char(4) | yes |   | null  |    | 
+-------+---------+------+-----+---------+-------+

删除重复的主键

mysql> delete from t1 where id=2;
query ok, 1 row affected (0.00 sec)

mysql> start slave;
query ok, 0 rows affected (0.00 sec)

mysql> show slave status\g;
……
slave_io_running: yes
slave_sql_running: yes
……
mysql> select * from t1 where id=2;

在master上和slave上再分别确认一下。

更新丢失

在master上更新一条记录,而slave上找不到,丢失了数据。

last_sql_error: could not execute update_rows event on table hcy.t1; 
can't find record in 't1', 
error_code: 1032; 
handler error ha_err_key_not_found; 
the event's master log mysql-bin.000010, end_log_pos 794

解决方法:

在master上,用mysqlbinlog 分析下出错的binlog日志在干什么。

/usr/local/mysql/bin/mysqlbinlog --no-defaults -v -v --base64-output=decode-rows mysql-bin.000010 | grep -a '10' 794

#120302 12:08:36 server id 22 end_log_pos 794 update_rows: table id 33 flags: stmt_end_f
### update hcy.t1
### where
###  @1=2 /* int meta=0 nullable=0 is_null=0 */
###  @2='bbc' /* string(4) meta=65028 nullable=1 is_null=0 */
### set
###  @1=2 /* int meta=0 nullable=0 is_null=0 */
###  @2='btv' /* string(4) meta=65028 nullable=1 is_null=0 */
# at 794
#120302 12:08:36 server id 22 end_log_pos 821 xid = 60
commit/*!*/;
delimiter ;
# end of log file
rollback /* added by mysqlbinlog */;
/*!50003 set completion_type=@old_completion_type*/;

在slave上,查找下更新后的那条记录,应该是不存在的。

mysql> select * from t1 where id=2;
empty set (0.00 sec)

然后再到master查看

mysql> select * from t1 where id=2;
+----+------+
| id | name |
+----+------+
| 2 | btv | 
+----+------+
1 row in set (0.00 sec)

把丢失的数据在slave上填补,然后跳过报错即可。

mysql> insert into t1 values (2,'btv');
query ok, 1 row affected (0.00 sec)

mysql> select * from t1 where id=2;  
+----+------+
| id | name |
+----+------+
| 2 | btv | 
+----+------+
1 row in set (0.00 sec)

mysql> stop slave ;set global sql_slave_skip_counter=1;start slave;
query ok, 0 rows affected (0.01 sec)
query ok, 0 rows affected (0.00 sec)
query ok, 0 rows affected (0.00 sec)

mysql> show slave status\g;
……
 slave_io_running: yes
 slave_sql_running: yes
……

中继日志损坏

slave的中继日志relay-bin损坏。

last_sql_error: error initializing relay log position: i/o error reading the header from the binary log
last_sql_error: error initializing relay log position: binlog has bad magic number; 
it's not a binary log file that can be used by this version of mysql

手工修复

解决方法:找到同步的binlog和pos点,然后重新做同步,这样就可以有新的中继日值了。

例子:

mysql> show slave status\g;
*************************** 1. row ***************************
       master_log_file: mysql-bin.000010
     read_master_log_pos: 1191
        relay_log_file: vm02-relay-bin.000005
        relay_log_pos: 253
    relay_master_log_file: mysql-bin.000010
       slave_io_running: yes
      slave_sql_running: no
       replicate_do_db: 
     replicate_ignore_db: 
      replicate_do_table: 
    replicate_ignore_table: 
   replicate_wild_do_table: 
 replicate_wild_ignore_table: 
          last_errno: 1593
          last_error: error initializing relay log position: i/o error reading the header from the binary log
         skip_counter: 1
     exec_master_log_pos: 821

slave_io_running :接收master的binlog信息       

master_log_file
                   read_master_log_pos

slave_sql_running:执行写操作

                   relay_master_log_file
                   exec_master_log_pos

以执行写的binlog和pos点为准。

relay_master_log_file: mysql-bin.000010
exec_master_log_pos: 821
mysql> stop slave;
query ok, 0 rows affected (0.01 sec)

mysql> change master to master_log_file='mysql-bin.000010',master_log_pos=821;
query ok, 0 rows affected (0.01 sec)

mysql> start slave;
query ok, 0 rows affected (0.00 sec)


mysql> show slave status\g;
*************************** 1. row ***************************
        slave_io_state: waiting for master to send event
         master_host: 192.168.8.22
         master_user: repl
         master_port: 3306
        connect_retry: 10
       master_log_file: mysql-bin.000010
     read_master_log_pos: 1191
        relay_log_file: vm02-relay-bin.000002
        relay_log_pos: 623
    relay_master_log_file: mysql-bin.000010
       slave_io_running: yes
      slave_sql_running: yes
       replicate_do_db: 
     replicate_ignore_db: 
      replicate_do_table: 
    replicate_ignore_table: 
   replicate_wild_do_table: 
 replicate_wild_ignore_table: 
          last_errno: 0
          last_error: 
         skip_counter: 0
     exec_master_log_pos: 1191
       relay_log_space: 778
       until_condition: none
        until_log_file: 
        until_log_pos: 0
      master_ssl_allowed: no
      master_ssl_ca_file: 
      master_ssl_ca_path: 
       master_ssl_cert: 
      master_ssl_cipher: 
        master_ssl_key: 
    seconds_behind_master: 0
master_ssl_verify_server_cert: no
        last_io_errno: 0
        last_io_error: 
        last_sql_errno: 0
        last_sql_error: 
ibbackup

各种大招都用上了,无奈slave数据丢失过多,ibbackup(需要银子)该你登场了。

ibbackup热备份工具,是付费的。xtrabackup是免费的,功能上一样。

ibbackup备份期间不锁表,备份时开启一个事务(相当于做一个快照),然后会记录一个点,之后数据的更改保存在ibbackup_logfile文件里,恢复时把ibbackup_logfile 变化的数据再写入到ibdata里。

ibbackup 只备份数据( ibdata、.ibd ),表结构.frm不备份。

下面一个演示例子:

备份:ibbackup /bak/etc/my_local.cnf /bak/etc/my_bak.cnf

恢复:ibbackup --apply-log /bak/etc/my_bak.cnf

[root@vm01 etc]# more my_local.cnf 

datadir =/usr/local/mysql/data
innodb_data_home_dir = /usr/local/mysql/data
innodb_data_file_path = ibdata1:10m:autoextend
innodb_log_group_home_dir = /usr/local/mysql/data
innodb_buffer_pool_size = 100m
innodb_log_file_size = 5m
innodb_log_files_in_group=2


[root@vm01 etc]# ibbackup /bak/etc/my_local.cnf /bak/etc/my_bak.cnf 

innodb hot backup version 3.0.0; copyright 2002-2005 innobase oy
license a21488 is granted to vm01 (chunyang_he@126.com)
(--apply-log works in any computer regardless of the hostname)
licensed for use in a computer whose hostname is 'vm01'
expires 2012-5-1 (year-month-day) at 00:00
see http://www.innodb.com for further information
type ibbackup --license for detailed license terms, --help for help

contents of /bak/etc/my_local.cnf:
innodb_data_home_dir got value /usr/local/mysql/data
innodb_data_file_path got value ibdata1:10m:autoextend
datadir got value /usr/local/mysql/data
innodb_log_group_home_dir got value /usr/local/mysql/data
innodb_log_files_in_group got value 2
innodb_log_file_size got value 5242880

contents of /bak/etc/my_bak.cnf:
innodb_data_home_dir got value /bak/data
innodb_data_file_path got value ibdata1:10m:autoextend

datadir got value /bak/data
innodb_log_group_home_dir got value /bak/data
innodb_log_files_in_group got value 2
innodb_log_file_size got value 5242880

ibbackup: found checkpoint at lsn 0 1636898
ibbackup: starting log scan from lsn 0 1636864
120302 16:47:43 ibbackup: copying log...
120302 16:47:43 ibbackup: log copied, lsn 0 1636898
ibbackup: we wait 1 second before starting copying the data files...
120302 16:47:44 ibbackup: copying /usr/local/mysql/data/ibdata1
ibbackup: a copied database page was modified at 0 1636898
ibbackup: scanned log up to lsn 0 1636898
ibbackup: was able to parse the log up to lsn 0 1636898
ibbackup: maximum page number for a log record 0
120302 16:47:46 ibbackup: full backup completed!
[root@vm01 etc]#
[root@vm01 etc]# cd /bak/data/
[root@vm01 data]# ls
ibbackup_logfile ibdata1

[root@vm01 data]# ibbackup --apply-log /bak/etc/my_bak.cnf 

innodb hot backup version 3.0.0; copyright 2002-2005 innobase oy
license a21488 is granted to vm01 (chunyang_he@126.com)
(--apply-log works in any computer regardless of the hostname)
licensed for use in a computer whose hostname is 'vm01'
expires 2012-5-1 (year-month-day) at 00:00
see http://www.innodb.com for further information
type ibbackup --license for detailed license terms, --help for help

contents of /bak/etc/my_bak.cnf:
innodb_data_home_dir got value /bak/data
innodb_data_file_path got value ibdata1:10m:autoextend
datadir got value /bak/data
innodb_log_group_home_dir got value /bak/data
innodb_log_files_in_group got value 2
innodb_log_file_size got value 5242880

120302 16:48:38 ibbackup: ibbackup_logfile's creation parameters:
ibbackup: start lsn 0 1636864, end lsn 0 1636898,
ibbackup: start checkpoint 0 1636898


ibbackup: start checkpoint 0 1636898
innodb: doing recovery: scanned up to log sequence number 0 1636898
innodb: starting an apply batch of log records to the database...
innodb: progress in percents: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 .....99
setting log file size to 0 5242880
ibbackup: we were able to parse ibbackup_logfile up to
ibbackup: lsn 0 1636898
ibbackup: last mysql binlog file position 0 1191, file name ./mysql-bin.000010
ibbackup: the first data file is '/bak/data/ibdata1'
ibbackup: and the new created log files are at '/bak/data/'
120302 16:48:38 ibbackup: full backup prepared for recovery successfully!

[root@vm01 data]# ls
ibbackup_logfile ibdata1 ib_logfile0 ib_logfile1

把ibdata1 ib_logfile0 ib_logfile1拷贝到从,把.frm也拷贝过去,启动mysql后,做同步,那个点就是上面输出的:

ibbackup: last mysql binlog file position 0 1191, file name ./mysql-bin.000010
change master to master_log_file='mysql-bin.000010',master_log_pos=1191;

maatkit工具包
http://www.maatkit.org/

简介

maatkit是一个开源的工具包,为mysql日常管理提供了帮助。目前,已被percona公司收购并维护。其中:

mk-table-checksum是用来检测master和slave上的表结构和数据是否一致。

mk-table-sync是发生主从数据不一致时,来修复的。

这两个工具包,没有在现网实际操作的经验,这里仅仅是新技术探讨和学术交流,下面展示下如何使用。

http://www.actionsky.com/products/mysql-others/maatkit.jsp

[root@vm02]# mk-table-checksum h=vm01,u=admin,p=123456 h=vm02,u=admin,p=123456 -d hcy -t t1
cannot connect to mysql because the perl dbi module is not installed or not found. 
run 'perl -mdbi' to see the directories that perl searches for dbi.
if dbi is not installed, try:
 debian/ubuntu apt-get install libdbi-perl
 rhel/centos  yum install perl-dbi
 opensolaris  pgk install pkg:/sunwpmdbi

提示缺少perl-dbi模块,那么直接 yum install perl-dbi。

[root@vm02 bin]# mk-table-checksum h=vm01,u=admin,p=123456 h=vm02,u=admin,p=123456 -d hcy -t t1
database table chunk host engine   count     checksum time wait stat lag
hcy   t1    0 vm02 innodb    null    1957752020  0  0 null null
hcy   t1    0 vm01 innodb    null    1957752020  0  0 null null

如果表数据不一致,checksum的值是不相等的。

解释下输出的意思:

database:数据库名
table:表名
chunk:checksum时的近似数值
host:mysql的地址
engine:表引擎
count:表的行数
checksum:校验值
time:所用时间
wait:等待时间
stat:master_pos_wait()返回值
lag:slave的延时时间

如果你想过滤出不相等的都有哪些表,可以用mk-checksum-filter这个工具,只要在后面加个管道符就行了。

[root@vm02 ~]# mk-table-checksum h=vm01,u=admin,p=123456 h=vm02,u=admin,p=123456 -d hcy | mk-checksum-filter    
hcy   t2    0 vm01 innodb    null    1957752020  0  0 null null
hcy   t2    0 vm02 innodb    null    1068689114  0  0 null null

知道有哪些表不一致,可以用mk-table-sync这个工具来处理。

注:在执行mk-table-checksum时会锁表,表的大小取决于执行的快慢。

master上的t2表数据:

slave上的t2表数据:

mysql> select * from t2;         mysql> select * from t2;  
+----+------+               +----+------+
| id | name |               | id | name |
+----+------+               +----+------+
| 1 | a  |               | 1 | a  | 
| 2 | b  |               | 2 | b  | 
| 3 | ss  |               | 3 | ss  | 
| 4 | asd |               | 4 | asd | 
| 5 | ss  |               +----+------+
+----+------+               4 rows in set (0.00 sec)
5 rows in set (0.00 sec) 
                     mysql> \! hostname; 
mysql> \! hostname;            vm02    
vm01 
[root@vm02 ~]# mk-table-sync --execute --print --no-check-slave --transaction --databases hcy h=vm01,u=admin,p=123456 h=vm02,u=admin,p=123456 
insert into `hcy`.`t2`(`id`, `name`) values ('5', 'ss') /*maatkit src_db:hcy src_tbl:t2 src_dsn:h=vm01,p=...,u=admin dst_db:hcy dst_tbl:t2 
dst_dsn:h=vm02,p=...,u=admin lock:0 transaction:1 changing_src:0 replicate:0 bidirectional:0 pid:3246 user:root host:vm02*/;

它的工作原理是:先一行一行检查主从库的表是否一样,如果哪里不一样,就执行删除,更新,插入等操作,使其达到一致。表的大小决定着执行的快慢。

if c<--transaction> is specified, c<lock tables> is not used. instead, lock
and unlock are implemented by beginning and committing transactions.
the exception is if l<"--lock"> is 3.
if c<--no-transaction> is specified, then c<lock tables> is used for any
value of l<"--lock">. see l<"--[no]transaction">.
when enabled, either explicitly or implicitly, the transaction isolation level
is set c<repeatable read> and transactions are started c<with consistent
snapshot>

mysql复制监控

mysql常见错误类型

1005:创建表失败
1006:创建数据库失败
1007:数据库已存在,创建数据库失败
1008:数据库不存在,删除数据库失败
1009:不能删除数据库文件导致删除数据库失败
1010:不能删除数据目录导致删除数据库失败
1011:删除数据库文件失败
1012:不能读取系统表中的记录
1020:记录已被其他用户修改
1021:硬盘剩余空间不足,请加大硬盘可用空间
1022:关键字重复,更改记录失败
1023:关闭时发生错误
1024:读文件错误
1025:更改名字时发生错误
1026:写文件错误
1032:记录不存在
1036:数据表是只读的,不能对它进行修改
1037:系统内存不足,请重启数据库或重启服务器
1038:用于排序的内存不足,请增大排序缓冲区
1040:已到达数据库的最大连接数,请加大数据库可用连接数
1041:系统内存不足
1042:无效的主机名
1043:无效连接
1044:当前用户没有访问数据库的权限
1045:不能连接数据库,用户名或密码错误
1048:字段不能为空
1049:数据库不存在
1050:数据表已存在
1051:数据表不存在
1054:字段不存在
1065:无效的sql语句,sql语句为空
1081:不能建立socket连接
1114:数据表已满,不能容纳任何记录
1116:打开的数据表太多
1129:数据库出现异常,请重启数据库
1130:连接数据库失败,没有连接数据库的权限
1133:数据库用户不存在
1141:当前用户无权访问数据库
1142:当前用户无权访问数据表
1143:当前用户无权访问数据表中的字段
1146:数据表不存在
1147:未定义用户对数据表的访问权限
1149:sql语句语法错误
1158:网络错误,出现读错误,请检查网络连接状况
1159:网络错误,读超时,请检查网络连接状况
1160:网络错误,出现写错误,请检查网络连接状况
1161:网络错误,写超时,请检查网络连接状况
1062:字段值重复,入库失败
1169:字段值重复,更新记录失败
1177:打开数据表失败
1180:提交事务失败
1181:回滚事务失败
1203:当前用户和数据库建立的连接已到达数据库的最大连接数,请增大可用的数据库连接数或重启数据库
1205:加锁超时
1211:当前用户没有创建用户的权限
1216:外键约束检查失败,更新子表记录失败
1217:外键约束检查失败,删除或修改主表记录失败
1226:当前用户使用的资源已超过所允许的资源,请重启数据库或重启服务器
1227:权限不足,您无权进行此操作
1235:mysql版本过低,不具有本功能

复制监控脚本

参考原文修改。

原脚本

#!/bin/bash
#
#check_mysql_slave_replication_status
#
#
#
parasum=2
help_msg(){
 
cat <<
 help
+---------------------+
+error
 cause:
+you
 must input $parasum parameters!
+1st
 : host_ip
+2st
 : host_port
help
exit
}
 
[
 $#
 -ne ${parasum} ] && help_msg #若参数不够打印帮助信息并退出
 
export host_ip=$1
export host_port=$2
myuser="root"     
mypass="123456"
 
mysql_cmd="mysql
 -u$myuser -p$mypass"
mailtitle=""        #邮件主题
mail_address_mysqlstatus="root@localhost.localdomain"  #收件人邮箱  
 
time1=$(date +"%y%m%d%h%m%s")
time2=$(date +"%y-%m-%d
 %h:%m:%s")
 
slavestatusfile=/tmp/salve_status_${host_port}.${time1} 
#邮件内容所在文件
echo "--------------------begin
 at: "$time2
 > $slavestatusfile
echo "" >>
 $slavestatusfile
 
#get
 slave status
${mysql_cmd}
 -e "show
 slave status\g" >>
 $slavestatusfile #取得salve进程的状态
 
#get
 io_thread_status,sql_thread_status,last_errno  取得以下状态值
 
iostatus=$(cat $slavestatusfile|grep slave_io_running|awk '{print
 $2}')
sqlstatus=$(cat $slavestatusfile|grep slave_sql_running
 |awk '{print
 $2}')
  errno=$(cat $slavestatusfile|grep last_errno
 | awk '{print
 $2}')
  behind=$(cat $slavestatusfile|grep seconds_behind_master
 | awk '{print
 $2}')
 
echo "" >>
 $slavestatusfile
 
if [
"$iostatus" ==
"no" ]
 || [ "$sqlstatus" ==
"no" ];then  #判断错误类型
    if [
"$errno" -eq 0
 ];then  #可能是salve线程未启动
      $mysql_cmd
 -e "start
 slave io_thread;start slave sql_thread;"
      echo "cause
 slave threads doesnot's running,trying start slsave io_thread;start slave sql_thread;" >>
 $slavestatusfile
      mailtitle="[warning]
 slave threads stoped on $host_ip $host_port"
    elif [
"$errno" -eq 1007
 ] || [ "$errno" -eq 1053
 ] || [ "$errno" -eq 1062
 ] || [ "$errno" -eq 1213
 ] || [ "$errno" -eq 1032
 ]\
      ||
 [ "errno" -eq 1158
 ] || [ "$errno" -eq 1159
 ] || [ "$errno" -eq 1008
 ];then #忽略此些错误
      $mysql_cmd
 -e "stop
 slave;set global sql_slave_skip_counter=1;start slave;"
      echo "cause
 slave replication catch errors,trying skip counter and restart slave;stop slave ;set global sql_slave_skip_counter=1;slave start;" >>
 $slavestatusfile
      mailtitle="[warning]
 slave error on $host_ip $host_port! errnum: $errno"
    else
      echo "slave
 $host_ip $host_port is down!" >>
 $slavestatusfile
      mailtitle="[error]slave
 replication is down on $host_ip $host_port ! errnum:$errno"
    fi
fi
if [
 -n "$behind" ];then
    behind=0
fi
echo "$behind" >>
 $slavestatusfile
 
#delay
 behind master 判断延时时间
if [
 $behind -gt 300 ];then
  echo `date +"%y-%m%d
 %h:%m:%s"`
"slave
 is behind master $bebind seconds!" >>
 $slavestatusfile
  mailtitle="[warning]slave
 delay $behind seconds,from $host_ip $host_port"
fi
 
if [
 -n "$mailtitle" ];then #若出错或者延时时间大于300s则发送邮件
    cat ${slavestatusfile}
 | /bin/mail -s
"$mailtitle" $mail_address_mysqlstatus
fi
 
#del
 tmpfile:slavestatusfile
>
 $slavestatusfile

修改后脚本

只做了简单的整理,修正了behind为null的判断,但均未测试;

应可考虑增加:

对修复执行结果的判断;多条错误的循环修复、检测、再修复?

取消slavestatusfile临时文件。

errno、behind两种告警分别发邮件,告警正文增加show slave结果原文。

增加path,以便加到crontab中。

考虑crontab中周期执行(加锁避免执行冲突、执行周期选择)

增加执行日志?

#!/bin/sh
#
 check_mysql_slave_replication_status
#
 参考:http://www.tianfeiyu.com/?p=2062
 
usage(){
  echo usage:
  echo "$0
 host port user pass"
}
 
[
 -z "$1" -o
 -z "$2" -o
 -z "$3" -o
 -z "$4" ]
 && usage && exit 1
host=$1
port=$2
user=$3
pass=$4
 
mysql_cmd="mysql
 -h$host -p$port -u$user -p$pass"
 
mailtitle=""        #邮件主题
mail_address_mysqlstatus="root@localhost.localdomain"  #收件人邮箱  
 
time1=$(date +"%y%m%d%h%m%s")
time2=$(date +"%y-%m-%d
 %h:%m:%s")
 
slavestatusfile=/tmp/salve_status_${host_port}.${time1} 
#邮件内容所在文件
echo "--------------------begin
 at: "$time2
 > $slavestatusfile
echo "" >>
 $slavestatusfile
 
#get
 slave status
${mysql_cmd}
 -e "show
 slave status\g" >>
 $slavestatusfile #取得salve进程的状态
 
#get
 io_thread_status,sql_thread_status,last_errno  取得以下状态值
 
 iostatus=$(cat $slavestatusfile|grep slave_io_running|awk '{print
 $2}')
sqlstatus=$(cat $slavestatusfile|grep slave_sql_running
 |awk '{print
 $2}')
  errno=$(cat $slavestatusfile|grep last_errno
 | awk '{print
 $2}')
  behind=$(cat $slavestatusfile|grep seconds_behind_master
 | awk '{print
 $2}')
 
echo "" >>
 $slavestatusfile
 
if [
"$iostatus" =
"no" -o
"$sqlstatus" =
"no" ];then
  case "$errno" in
  0)
    #
 可能是slave未启动
    $mysql_cmd
 -e "start
 slave io_thread;start slave sql_thread;"
    echo "cause
 slave threads doesnot's running,trying start slsave io_thread;start slave sql_thread;" >>
 $slavestatusfile
    ;;
  1007|1053|1062|1213|1032|1158|1159|1008)
    #
 忽略这些错误
    $mysql_cmd
 -e "stop
 slave;set global sql_slave_skip_counter=1;start slave;"
    echo "cause
 slave replication catch errors,trying skip counter and restart slave;stop slave ;set global sql_slave_skip_counter=1;slave start;" >>
 $slavestatusfile
    mailtitle="[warning]
 slave error on $host:$port! errnum: $errno"
    ;;
  *)
    echo "slave
 $host:$port is down!" >>
 $slavestatusfile
    mailtitle="[error]slave
 replication is down on $host:$port! errno:$errno"
    ;;
  esac
fi
 
if [
"$behind" =
"null" -o
 -z "$behind" ];then
  behind=0
fi
echo "behind:$behind" >>
 $slavestatusfile
 
#delay
 behind master 判断延时时间
if [
 $behind -gt 300 ];then
  echo `date +"%y-%m%d
 %h:%m:%s"`
"slave
 is behind master $bebind seconds!" >>
 $slavestatusfile
  mailtitle="[warning]slave
 delay $behind seconds,from $host $port"
fi
 
if [
 -n "$mailtitle" ];then #若出错或者延时时间大于300s则发送邮件
  cat ${slavestatusfile}
 | /bin/mail -s
"$mailtitle" $mail_address_mysqlstatus
fi
 
#del
 tmpfile:slavestatusfile
>
 $slavestatusfile

以上这篇线上mysql同步报错故障处理方法总结(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。