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

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


场景

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

slave从库上执行的命令以下:sql

# 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在修改完表结构之后,业务方反馈数据不许确,在排查的过程当中发现同步报错1032bash

 

分析

一、主库和从库的binlog格式为ROWapp

wKiom1hGTjSjAMYEAAAKJHbkX34384.png


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

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`.


三、基于binlogROW行的复制,触发器不会在slave从库上工做,这就致使了主从数据不一致。但基于binlogstatement语句的复制,触发器会在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.spa

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

 

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

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

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

第三种状况:自增加字段被更新了。

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

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

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

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


复现

一、主库建立t1

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


二、从库建立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 ;


三、主库插入

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

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


结论

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

相关文章
相关标签/搜索