继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

pt-online-schema-change你今天滥用了吗?

holdtom
关注TA
已关注
手记 1703
粉丝 240
获赞 991


注:本文来自真实生产案例,感谢网友小豚提供,本人加以故障重现校验。

场景

因想整理一下线上的独立表空间碎片,故使用了pt-online-schema-change在slave从库上执行,目的是怕影响主库的CPU,维护的时候再进行一次主从切换,然后再收缩主库上的表空间碎片。

slave从库上执行的命令如下:

# pt-online-schema-change -S /tmp/mysql.sock --alter="engine=innodb"   --no-check-replication-filters  --recursion-method=none --user=root D=test,t=sbtest --execute

故障

DBA在修改完表结构以后,业务方反馈数据不准确,在排查的过程中发现同步报错1032。

 

分析

1、主库和从库的binlog格式为ROW

wKiom1hGTjSjAMYEAAAKJHbkX34384.png

2、pt-online-schema-change在拷贝原表数据时,原表的数据变更会通过触发器insert/updete/delete到临时表_sbtest_new里,完成之后原表改名为_sbtest_old老表,_sbtest_new临时表改为原表sbtest,最后删除_sbtest_old老表。过程如下:

Altering `test`.`sbtest`... Creating new table... Created new table test._sbtest_new OK. Altering new table... Altered `test`.`_sbtest_new` OK. 2016-12-06T12:15:30 Creating triggers... 2016-12-06T12:15:30 Created triggers OK. 2016-12-06T12:15:30 Copying approximately 1099152 rows... 2016-12-06T12:15:54 Copied rows OK. 2016-12-06T12:15:54 Analyzing new table... 2016-12-06T12:15:54 Swapping tables... 2016-12-06T12:15:54 Swapped original and new tables OK. 2016-12-06T12:15:54 Dropping old table... 2016-12-06T12:15:54 Dropped old table `test`.`_sbtest_old` OK. 2016-12-06T12:15:54 Dropping triggers... 2016-12-06T12:15:54 Dropped triggers OK. Successfully altered `test`.`sbtest`.

3、基于binlog为ROW行的复制,触发器不会在slave从库上工作,这就导致了主从数据不一致。但基于binlog为statement语句的复制,触发器会在slave从库上工作。

With statement-based replication, triggers executed on the master also execute on the slave. With row-based replication, triggers executed on the master do not execute on the slave.

参考文献:http://dev.mysql.com/doc/refman/5.7/en/replication-features-triggers.html

 

注:在二进制日志里,MIXED默认还是采用STATEMENT格式记录的,但在下面这6种情况下会转化为ROW格式。

第一种情况:NDB引擎,表的DML操作增、删、改会以ROW格式记录。

第二种情况:SQL语句里包含了UUID()函数。

第三种情况:自增长字段被更新了。

第四种情况:包含了INSERT DELAYED语句。

第五种情况:使用了用户定义函数(UDF)

第六种情况:使用了临时表。

参考文献:https://dev.mysql.com/doc/refman/5.7/en/binary-log-mixed.html

复现

1、主库创建t1表

 CREATE TABLE `t1` (   `id` int(11) NOT NULL,   PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

2、从库创建t2表并创建触发器

CREATE TABLE `t2` (   `id` int(11) NOT NULL,   PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

触发器

DELIMITER $$   USE `test`$$   DROP TRIGGER IF EXISTS `t1_1`$$   CREATE     TRIGGER `t1_1` AFTER INSERT ON `t1`      FOR EACH ROW BEGIN     INSERT INTO t2(id) VALUES(NEW.id);     END; $$   DELIMITER ;

3、主库插入

insert into t1 values(1),(2),(3); select * from t2;

此时t2表里没有任何数据,触发器没有工作。

结论

如果你使用pt-online-schema-change修改表结构在主库上运行,数据不一致的情况不会发生。但如果在从库上运行,且主库的binlog格式为ROW,那将是危险的。

©著作权归作者所有:来自51CTO博客作者hcymysql的原创作品,如需转载,请注明出处,否则将追究法律责任


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP