mysql_repl_repair修復(fù) MySQL?主從復(fù)制錯誤
mysql_repl_repair.py是一款用于修復(fù)mysql主從復(fù)制錯誤的python小工具,該工具可以修復(fù)由于主從數(shù)據(jù)不一致導(dǎo)致的1062(duplicate key), 1032(key not found)錯誤。當(dāng)遇到復(fù)制出錯,mysql_repl_repair.py會流式讀取relay log中的數(shù)據(jù),并構(gòu)造成修復(fù)sql,在從庫上執(zhí)行,解決sql線程apply時遇到的問題。mysql_repl_repair.py非常輕巧,即使在遇到大事務(wù)時也不會對服務(wù)器造成性能影響,mysql_repl_repair.py支持以daemon方式后臺運行,支持單機(jī)多實例下同時修復(fù)多個實例
目前網(wǎng)易內(nèi)部的使用方法:監(jiān)控服務(wù)定期監(jiān)控mysql主從復(fù)制狀態(tài),如遇1062,1032 則執(zhí)行mysql_repl_repair.py進(jìn)行修復(fù)
原理
1. 當(dāng)從庫sql apply線程遇到1062錯誤時,說明slave上已經(jīng)存在需要insert的數(shù)據(jù),并且需要insert的數(shù)據(jù)上有唯一約束,從而導(dǎo)致插入失敗,那么需要按照 唯一約束建們 來刪除該事務(wù)中相關(guān)insert語句(對應(yīng)WRITE_ROWS_EVENT)。最終構(gòu)造的sql是
delete from table where (pk_col = xxx ) or (uk1_col1 = xxx and uk1_col2=yyy)
如果事務(wù)中存在多條insert, 那么對應(yīng)多條delete語句,而事務(wù)中有delete或者update的話,將忽略
2. 當(dāng)從庫sql apply線程遇到1032錯誤時,說明slave sql線程在執(zhí)行update或者delete時找不到對應(yīng)需要變更的數(shù)據(jù),那么需要先寫入這條數(shù)據(jù)才行,因為binlog為row模式時變更語句(對應(yīng)DELETE_ROWS_EVENT或UPDATE_ROWS_EVENT)中包含變更前數(shù)據(jù),因此可以構(gòu)造出這條數(shù)據(jù)。最終構(gòu)造的sql是
insert ignore into table set a=xxx,b=xxx,c=xxx
如果事務(wù)中包含多條delete/update語句,那么最終需要執(zhí)行多次 insert操作,而事務(wù)中有insert的話,將忽略
限制
-
支持5.1 ~ 5.7,
-
目前只支持ROW格式binlog且為FULL row image格式
-
json,空間數(shù)據(jù)類型的表造成的復(fù)制異常目前版本暫不支持,如有強(qiáng)烈需求,我們將考慮支持一下
USAGE
python mysql_repl_repair.py -h Usage: python mysql_repl_repair.py [options] this script is used to repair mysql replication errors(1062, 1032) example: python mysql_repl_repair.py -u mysql -p mysql -S /tmp/mysql.sock -d -v python mysql_repl_repair.py -u mysql -p mysql -S /tmp/mysql3306.sock,/tmp/mysql3307.sock -l /tmp Options: -h, --help show this help message and exit -u USER, --user=USER username for login mysql -p PASSWORD, --password=PASSWORD Password to use when connecting to server -l LOGDIR, --logdir=LOGDIR log will output to screen by default,if run with daemon mode, default logdir is /tmp, logfile is $logdir/mysql_repl_repair.$port.log -S SOCKETS, --socket=SOCKETS mysql sockets for connecting to server, you can input multi socket to repair multi mysql instance, each socket separate by ',' -d, --daemon run as a daemon -t TIME, --time=TIME unit is second, default is 0 mean run forever -v, --verbose debug log mode
