pt-heartbeat监控mysql主从复制延迟整理

对于MySQL数据库主从复制延迟的监控,可以借助percona的有力武器pt-heartbeat来实现。

pt-heartbeat的工作原理通过使用时间戳方式在主库上更新特定表,然后在从库上读取被更新的时间戳然后与本地系统时间对比来得出其延迟。具体流程:
   1)在主上创建一张heartbeat表,按照一定的时间频率更新该表的字段(把时间更新进去)。监控操作运行后,heartbeat表能促使主从同步!
   2)连接到从库上检查复制的时间记录,和从库的当前系统时间进行比较,得出时间的差异。

使用方法(主从和从库上都可以执行监控操作):
pt-heartbeat [OPTIONS] [DSN] --update|--monitor|--check|--stop

[plain]  view plain  copy
  1. 注意:需要指定的参数至少有 --stop,--update,--monitor,--check。  
  2. 其中--update,--monitor和--check是互斥的,--daemonize和--check也是互斥。  
  3. --ask-pass     隐式输入MySQL密码  
  4. --charset     字符集设置  
  5. --check      检查从的延迟,检查一次就退出,除非指定了--recurse会递归的检查所有的从服务器。  
  6. --check-read-only    如果从服务器开启了只读模式,该工具会跳过任何插入。  
  7. --create-table    在主上创建心跳监控的表,如果该表不存在,可以自己手动建立,建议存储引擎改成memory。通过更新该表知道主从延迟的差距。  
  8. CREATE TABLE heartbeat (  
  9.   ts                    varchar(26) NOT NULL,  
  10.   server_id             int unsigned NOT NULL PRIMARY KEY,  
  11.   file                  varchar(255) DEFAULT NULL,  
  12.   position              bigint unsigned DEFAULT NULL,  
  13.   relay_master_log_file varchar(255) DEFAULT NULL,  
  14.   exec_master_log_pos   bigint unsigned DEFAULT NULL  
  15. );  
  16. heratbeat   表一直在更改ts和position,而ts是我们检查复制延迟的关键。  
  17. --daemonize   执行时,放入到后台执行  
  18. --user=-u,   连接数据库的帐号  
  19. --database=-D,    连接数据库的名称  
  20. --host=-h,     连接的数据库地址  
  21. --password=-p,     连接数据库的密码  
  22. --port=-P,     连接数据库的端口  
  23. --socket=-S,    连接数据库的套接字文件  
  24. --file 【--file=output.txt】   打印--monitor最新的记录到指定的文件,很好的防止满屏幕都是数据的烦恼。  
  25. --frames 【--frames=1m,2m,3m】  在--monitor里输出的[]里的记录段,默认是1m,5m,15m。可以指定1个,如:--frames=1s,多个用逗号隔开。可用单位有秒(s)、分钟(m)、小时(h)、天(d)。  
  26. --interval   检查、更新的间隔时间。默认是见是1s。最小的单位是0.01s,最大精度为小数点后两位,因此0.015将调整至0.02。  
  27. --log    开启daemonized模式的所有日志将会被打印到制定的文件中。  
  28. --monitor    持续监控从的延迟情况。通过--interval指定的间隔时间,打印出从的延迟信息,通过--file则可以把这些信息打印到指定的文件。  
  29. --master-server-id    指定主的server_id,若没有指定则该工具会连到主上查找其server_id。  
  30. --print-master-server-id    在--monitor和--check 模式下,指定该参数则打印出主的server_id。  
  31. --recurse    多级复制的检查深度。模式M-S-S...不是最后的一个从都需要开启log_slave_updates,这样才能检查到。  
  32. --recursion-method     指定复制检查的方式,默认为processlist,hosts。  
  33. --update    更新主上的心跳表。  
  34. --replace     使用--replace代替--update模式更新心跳表里的时间字段,这样的好处是不用管表里是否有行。  
  35. --stop    停止运行该工具(--daemonize),在/tmp/目录下创建一个“pt-heartbeat-sentinel” 文件。后面想重新开启则需要把该临时文件删除,才能开启(--daemonize)。  
  36. --table   指定心跳表名,默认heartbeat。  

实例说明:
master:192.168.1.101
slave:192.168.1.102
同步的库:huanqiu、huanpc
主从库都能使用root账号、密码123456登录

先操作针对huanqiu库的检查,其他同步的库的检查操作类似!

[plain]  view plain  copy
  1. <span style="color:#333333;">mysql> use huanqiu;                     
  2. Database changed  
  3.    
  4. mysql> CREATE TABLE heartbeat (            //主库上的对应库下创建heartbeat表,一般创建后从库会同步这张表(不同步的话,就在从库那边手动也手动创建)  
  5.     ->   ts                    varchar(26) NOT NULL,  
  6.     ->   server_id             int unsigned NOT NULL PRIMARY KEY,  
  7.     ->   file                  varchar(255) DEFAULT NULL,  
  8.     ->   position              bigint unsigned DEFAULT NULL,  
  9.     ->   relay_master_log_file varchar(255) DEFAULT NULL,  
  10.     ->   exec_master_log_pos   bigint unsigned DEFAULT NULL  
  11.     -> );  
  12. Query OK, 0 rows affected (0.02 sec)</span>  

更新主库上的heartbeat,--interval=1表示1秒钟更新一次(注意这个启动操作要在主库服务器上执行)
[root@master-server ~]# pt-heartbeat --user=root --ask-pass --host=192.168.1.101 --create-table -D huanqiu --interval=1 --update --replace --daemonize
Enter password: 
[root@master-server ~]# 
[root@master-server ~]# ps -ef|grep pt-heartbeat
root 15152 1 0 19:49 ? 00:00:00 perl /usr/bin/pt-heartbeat --user=root --ask-pass --host=192.168.1.101 --create-table -D huanqiu --interval=1 --update --replace --daemonize
root 15154 14170 0 19:49 pts/3 00:00:00 grep pt-heartbeat

在主库运行监测同步延迟:
[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --monitor --host=192.168.1.102 --user=root --password=123456
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
........
解释:0表示从没有延迟。 [ 0.00s, 0.00s, 0.00s ] 表示1m,5m,15m的平均值。可以通过--frames去设置。

或者加上--master-server-id参数(主库my.cnf里配置的server-id值)
[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --monitor --host=192.168.1.102 --user=root --password=123456 --master-server-id=101
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
.........
也可以将主库的server-id打印出来(--print-master-server-id)
[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --monit --host=192.168.1.102 --user=root --password=123456 --print-master-server-id
0.00s [ 0.00s, 0.00s, 0.00s ] 101
0.00s [ 0.00s, 0.00s, 0.00s ] 101
0.00s [ 0.00s, 0.00s, 0.00s ] 101
0.00s [ 0.00s, 0.00s, 0.00s ] 101
.........
[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --check --host=192.168.1.102 --user=root --password=123456 --print-master-server-id
0.00 101

上面的监测命令会一直在运行状态中,可以使用--check监测一次就退出
注意:使用了--check,就不能使用--monit
--update,--monitor和--check是互斥的,--daemonize和--check也是互斥。

[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --check --host=192.168.1.102 --user=root --password=123456
0.00
[root@master-server ~]#

注意:
如果想把这个输出结果加入自动化监控,那么可以使用如下命令使监控输出写到文件,然后使用脚本定期过滤文件中的最大值作为预警即可:
注意--log选项必须在有--daemonize参数的时候才会打印到文件中,且这个文件的路径最好在/tmp下,否则可能因为权限问题无法创建
[root@master-server ~]# pt-heartbeat -D huanqiu --table=heartbeat --monitor --host=192.168.1.102 --user=root --password=123456 --log=/opt/master-slave.txt --daemonize
[root@master-server ~]# tail -f /opt/master-slave.txt            //可以测试,在主库上更新数据时,从库上是否及时同步,如不同步,可以在这里看到监控的延迟数据
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
.......

下面是编写的主从同步延迟监控脚本,就是定期过滤--log文件中最大值(此脚本运行的前提是:启动更新主库heartbeat命令以及带上--log的同步延迟检测命令)。如果发生延迟,发送报警邮件。sendemail邮件发送环境部署参考:http://www.cnblogs.com/kevingrace/p/5961861.html
[root@master-server ~]# cat /root/check-slave-monit.sh 

[plain]  view plain  copy
  1. #!/bin/bash  
  2. cat /opt/master-slave.txt > /opt/master_slave.txt  
  3. echo > /opt/master-slave.txt  
  4. max_time=`cat /opt/master_slave.txt |grep -v '^$' |awk '{print $1}' |sort -k1nr |head -1`  
  5. NUM=$(echo "$max_time"|cut -d"s" -f1)  
  6. if [ $NUM == "0.00" ];then  
  7.    echo "Mysql主从数据一致"  
  8. else  
  9.    /usr/local/bin/sendEmail -f ops@huanqiu.cn -t wangshibo@huanqiu.cn -s smtp.huanqiu.cn -u "Mysql主从同步延迟" -o message-content-type=html -o message-charset=utf8 -xu ops@huanqiu.cn -xp WEE78@12l$ -m "Mysql主从数据同步有延迟"  
  10. fi  

[root@master-server ~]# chmod /root/check-slave-monit.sh
[root@master-server ~]# sh /root/check-slave-monit.sh 
Mysql主从数据一致

结合crontab,每隔一分钟检查一次

[plain]  view plain  copy
  1. <span style="color:#333333;">[root@master-server ~]# crontab -e  
  2. #mysql主从同步延迟检查  
  3. * * * * * /bin/bash -x /root/check-slave-monit.sh > /dev/null 2>&1</span>  

在从库上运行监测同步延迟(也可以在命令后加上--master-server-id=101或--print-master-server-id,同上操作)
[root@slave-server src]# pt-heartbeat -D huanqiu --table=heartbeat --monitor --user=root --password=123456
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
........
[root@slave-server src]# pt-heartbeat -D huanqiu --table=heartbeat --user=root --password=123456 --check
0.00
[root@slave-server src]# pt-heartbeat -D huanqiu --table=heartbeat --monitor --user=root --password=123456 --log=/opt/master-slave.txt --daemonize
[root@slave-server src]# tail -f /opt/master-slave.txt 
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]
0.00s [ 0.00s, 0.00s, 0.00s ]

如何关闭上面在主库上执行的heartbeat更新进程呢?
方法一:可以用参数--stop去关闭
[root@master-server ~]# ps -ef|grep heartbeat
root 15152 1 0 19:49 ? 00:00:02 perl /usr/bin/pt-heartbeat --user=root --ask-pass --host=192.168.1.101 --create-table -D huanqiu --interval=1 --update --replace --daemonize
root 15310 1 0 19:59 ? 00:00:01 perl /usr/bin/pt-heartbeat -D huanqiu --table=heartbeat --monitor --host=192.168.1.102 --user=root --password=123456 --log=/opt/master-slave.txt --daemonize
root 15555 31932 0 20:13 pts/2 00:00:00 grep heartbeat
[root@master-server ~]# pt-heartbeat --stop
Successfully created file /tmp/pt-heartbeat-sentinel
[root@master-server ~]# ps -ef|grep heartbeat
root 15558 31932 0 20:14 pts/2 00:00:00 grep heartbeat
[root@master-server ~]#

这样就把在主上开启的进程杀掉了。
但是后续要继续开启后台进行的话,记住一定要先把/tmp/pt-heartbeat-sentinel 文件删除,否则启动不了

方法二:直接kill掉进程pid(推荐这种方法)
[root@master-server ~]# ps -ef|grep heartbeat
root 15152 1 0 19:49 ? 00:00:02 perl /usr/bin/pt-heartbeat --user=root --ask-pass --host=192.168.1.101 --create-table -D huanqiu --interval=1 --update --replace --daemonize
root 15310 1 0 19:59 ? 00:00:01 perl /usr/bin/pt-heartbeat -D huanqiu --table=heartbeat --monitor --host=192.168.1.102 --user=root --password=123456 --log=/opt/master-slave.txt --daemonize
root 15555 31932 0 20:13 pts/2 00:00:00 grep heartbeat
[root@master-server ~]# kill -9 15152
[root@master-server ~]# ps -ef|grep heartbeat
root 15558 31932 0 20:14 pts/2 00:00:00 grep heartbeat

最后总结:
通过pt-heartbeart工具可以很好的弥补默认主从延迟的问题,但需要搞清楚该工具的原理。
默认的Seconds_Behind_Master值是通过将服务器当前的时间戳与二进制日志中的事件时间戳相对比得到的,所以只有在执行事件时才能报告延时。备库复制线程没有运行,也会报延迟null。
还有一种情况:大事务,一个事务更新数据长达一个小时,最后提交。这条更新将比它实际发生时间要晚一个小时才记录到二进制日志中。当备库执行这条语句时,会临时地报告备库延迟为一个小时,执行完后又很快变成0。

---------------------------------------percona-toolkit其他组件命令用法---------------------------------- 

下面这些工具最好不要直接在线上使用,应该作为上线辅助或故障后离线分析的工具,也可以做性能测试的时候配合着使用。

1)pt-online-schema-change
功能介绍:
功能为:在alter操作更改表结构的时候不用锁定表,也就是说执行alter的时候不会阻塞写和读取操作注意执行这个工具的时候必须做好备份,操作之前最好要充分了解它的原理。
工作原理是:创建一个和你要执行alter操作的表一样的空表结构,执行表结构修改,然后从原表中copy原始数据到表结构修改后的表,当数据copy完成以后就会将原表移走,用新表代替原表,默认动作是将原表drop掉。在copy数据的过程中,任何在原表的更新操作都会更新到新表,因为这个工具在会在原表上创建触发器,触发器会将在原表上更新的内容更新到新表。如果表中已经定义了触发器这个工具就不能工作了。

用法介绍:
pt-online-schema-change [OPTIONS] DSN
options可以自行查看help(或加--help查看有哪些选项),DNS为你要操作的数据库和表。
有两个参数需要注意一下:
--dry-run 这个参数不建立触发器,不拷贝数据,也不会替换原表。只是创建和更改新表。
--execute 这个参数的作用和前面工作原理的介绍的一样,会建立触发器,来保证最新变更的数据会影响至新表。注意:如果不加这个参数,这个工具会在执行一些检查后退出。这一举措是为了让使用这充分了解了这个工具的原理。

使用示例:
在线更改表的的引擎,这个尤其在整理innodb表的时候非常有用,如下huanqiu库的haha表默认是Myisam存储引擎,现需要在线修改成Innodb类型。

[plain]  view plain  copy
  1. mysql> show create table huanqiu.haha;  
  2. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  3. | Table | Create Table                                                                                                                                                             |  
  4. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  5. | haha  | CREATE TABLE `haha` (  
  6.   `id` int(10) NOT NULL AUTO_INCREMENT,  
  7.   `name` varchar(50) NOT NULL,  
  8.   PRIMARY KEY (`id`)  
  9. ) ENGINE=MyISAM AUTO_INCREMENT=91 DEFAULT CHARSET=utf8 |  
  10. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  11. 1 row in set (0.00 sec)  

修改操作如下:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-online-schema-change --user=root --password=123456 --host=localhost --alter="ENGINE=InnoDB" D=huanqiu,t=haha --execute --check-replication-filters  
  2. Found 1 slaves:  
  3.   slave-server  
  4. Will check slave lag on:  
  5.   slave-server  
  6. Replication filters are set on these hosts:  
  7.   slave-server  
  8.     slave_skip_errors = ALL  
  9.     replicate_ignore_db = mysql  
  10.     replicate_do_db = huanqiu,huanpc  
  11. Please read the --check-replication-filters documentation to learn how to solve this problem. at /usr/bin/pt-online-schema-change line 8083.  

如上命令就是在主库上操作的,会提示它有从库,需要添加参数--nocheck-replication-filters,即不检查从库。(注意:下面命令中可以将localhost换成主库ip。另外:该命令只能针对某张表进行修改,因为它是针对alter操作的,而alter是针对表的操作命令。所以不能省略命令中"t=表名"的选项)

[plain]  view plain  copy
  1. <span style="color:#333333;">[root@master-server ~]# pt-online-schema-change --user=root --password=123456 --host=localhost --alter="ENGINE=InnoDB" D=huanqiu,t=haha --execute --nocheck-replication-filters         
  2. Found 1 slaves:  
  3.   slave-server  
  4. .......  
  5. 2017-01-16T10:36:33 Dropped old table `huanqiu`.`_haha_old` OK.  
  6. 2017-01-16T10:36:33 Dropping triggers...  
  7. 2017-01-16T10:36:33 Dropped triggers OK.  
  8. Successfully altered `huanqiu`.`haha`.</span>  

然后再次查看huanqiu.haha表的存储引擎,发现已是Innodb类型的了。

[plain]  view plain  copy
  1. mysql> show create table huanqiu.haha;  
  2. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  3. | Table | Create Table                                                                                                                                                             |  
  4. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  5. | haha  | CREATE TABLE `haha` (  
  6.   `id` int(10) NOT NULL AUTO_INCREMENT,  
  7.   `name` varchar(50) NOT NULL,  
  8.   PRIMARY KEY (`id`)  
  9. ) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=utf8 |  
  10. +-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------+  
  11. 1 row in set (0.00 sec)  

若是在从库上,则可以直接执行(也可以将下面从库ip替换成localhost)

[plain]  view plain  copy
  1. [root@slave-server ~]# pt-online-schema-change --user=root --password=123456 --host=192.168.1.102 --alter="ENGINE=InnoDB" D=huanqiu,t=haha --execute  
  2. No slaves found.  See --recursion-method if host slave-server has slaves.  
  3. Not checking slave lag because no slaves were found and --check-slave-lag was not specified.  
  4. Operation, tries, wait:  
  5. .......  
  6. 2017-01-15T21:40:35 Swapped original and new tables OK.  
  7. 2017-01-15T21:40:35 Dropping old table...  
  8. 2017-01-15T21:40:35 Dropped old table `huanqiu`.`_haha_old` OK.  
  9. 2017-01-15T21:40:35 Dropping triggers...  
  10. 2017-01-15T21:40:35 Dropped triggers OK.  
  11. Successfully altered `huanqiu`.`haha`.  

2)pt-duplicate-key-checker
功能介绍:
功能为从mysql表中找出重复的索引和外键,这个工具会将重复的索引和外键都列出来,并生成了删除重复索引的语句,非常方便
用法介绍:
pt-duplicate-key-checker [OPTION...] [DSN]
包含比较多的选项,具体的可以通过命令pt-duplicate-key-checker --help来查看具体支持那些选项,我这里就不一一列举了。DNS为数据库或者表。
使用示例:
查看huanqiu库或huanqiu.haha表的重复索引和外键使用情况使用,如下命令:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-duplicate-key-checker  --host=localhost --user=root --password=123456  --databases=huanqiu  
  2. # ########################################################################  
  3. # Summary of indexes                                                       
  4. # ########################################################################  
  5.    
  6. # Total Indexes  6  

[plain]  view plain  copy
  1. # [root@master-server ~]# pt-duplicate-key-checker  --host=localhost --user=root --password=123456  --databases=huanqiu --table=haha  
  2. # ########################################################################  
  3. # Summary of indexes                                                       
  4. # ########################################################################  
  5.    
  6. # Total Indexes  1  

3)pt-slave-find
功能介绍:
查找和打印mysql所有从服务器复制层级关系
用法介绍:
pt-slave-find [OPTION...] MASTER-HOST
原理:连接mysql主服务器并查找其所有的从,然后打印出所有从服务器的层级关系。
使用示例:
查找主服务器为192.168.1.101的mysql有所有从的层级关系(将下面的192.168.1.101改成localhost,就是查询本机mysql的从关系):

[plain]  view plain  copy
  1. [root@master-server ~]# pt-slave-find --user=root --password=123456 --host=192.168.1.101  
  2. 192.168.1.101  
  3. Version         5.6.33-log  
  4. Server ID       101  
  5. Uptime          5+02:59:42 (started 2017-01-11T10:44:14)  
  6. Replication     Is not a slave, has 1 slaves connected, is not read_only  
  7. Filters          
  8. Binary logging  MIXED  
  9. Slave status     
  10. Slave mode      STRICT  
  11. Auto-increment  increment 1, offset 1  
  12. InnoDB version  5.6.33  
  13. +- 192.168.1.102  
  14.    Version         5.6.34-log  
  15.    Server ID       102  
  16.    Uptime          4+22:22:18 (started 2017-01-11T15:21:38)  
  17.    Replication     Is a slave, has 0 slaves connected, is not read_only  
  18.    Filters         slave_skip_errors=ALL; replicate_ignore_db=mysql; replicate_do_db=huanqiu,huanpc  
  19.    Binary logging  MIXED  
  20.    Slave status    265831 seconds behind, running, no errors  
  21.    Slave mode      STRICT  
  22.    Auto-increment  increment 1, offset 1  
  23.    InnoDB version  5.6.34  

4)pt-show-grants
功能介绍:
规范化和打印mysql权限,让你在复制、比较mysql权限以及进行版本控制的时候更有效率!
用法介绍:
pt-show-grants [OPTION...] [DSN]
选项自行用help查看,DSN选项也请查看help,选项区分大小写。
使用示例:
查看指定mysql的所有用户权限:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-show-grants --host='localhost' --user='root' --password='123456'  
  2. -- Grants dumped by pt-show-grants  
  3. -- Dumped from server Localhost via UNIX socket, MySQL 5.6.33-log at 2017-01-16 11:22:12  
  4. -- Grants for ''@'localhost'  
  5. GRANT USAGE ON *.* TO ''@'localhost';  
  6. -- Grants for 'data_check'@'%'  
  7. .......  

查看执行数据库的权限:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-show-grants --host='localhost' --user='root' --password='123456' --database='huanqiu'  
  2. -- Grants dumped by pt-show-grants  
  3. -- Dumped from server Localhost via UNIX socket, MySQL 5.6.33-log at 2017-01-16 11:23:16  
  4. -- Grants for ''@'localhost'  
  5. GRANT USAGE ON *.* TO ''@'localhost';  
  6. -- Grants for 'data_check'@'%'  
  7. GRANT SELECT ON *.* TO 'data_check'@'%' IDENTIFIED BY PASSWORD '*36B94ABF70E8D5E025CF9C059E66445CBB05B54F';  
  8. -- Grants for 'mksync'@'%'  
  9. GRANT ALL PRIVILEGES ON *.* TO 'mksync'@'%' IDENTIFIED BY PASSWORD '*B5E7409B1A22D47C6F1D8A693C6146CEB6570475';  
  10. ........  

查看每个用户权限生成revoke收回权限的语句:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-show-grants --host='localhost' --user='root' --password='123456'  --revoke  
  2. -- Grants dumped by pt-show-grants  
  3. -- Dumped from server Localhost via UNIX socket, MySQL 5.6.33-log at 2017-01-16 11:24:58  
  4. -- Revoke statements for ''@'localhost'  
  5. REVOKE USAGE ON *.* FROM ''@'localhost';  
  6. -- Grants for ''@'localhost'  
  7. ..........  

5)pt-upgrade
功能介绍:
这个工具用来检查在新版本中运行的SQL是否与老版本一样,返回相同的结果,最好的应用场景就是数据迁移的时候。这在升级服务器的时候非常有用,可以先安装并导数据到新的服务器上,然后使用这个工具跑一下sql看看有什么不同,可以找出不同版本之间的差异。
用法介绍:
pt-upgrade [OPTION...] DSN [DSN...] [FILE]
比较文件中每一个查询语句在每台服务器上执行的结果(主要是针对不同版本的执行结果)。(--help查看选项)
使用示例:
查看某个sql文件在两个服务器的运行结果范例:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-upgrade h=192.168.1.101 h=192.168.1.102 --user=root --password=123456 /root/test.sql  
  2.    
  3. #-----------------------------------------------------------------------  
  4. # Logs  
  5. #-----------------------------------------------------------------------  
  6. .......  
  7. host1:  
  8.   DSN:       h=192.168.1.101  
  9.   hostname:  master-server  
  10.   MySQL:     Source distribution 5.6.33  
  11.    
  12. host2:  
  13.   DSN:       h=192.168.1.102  
  14.   hostname:  slave-server  
  15.   MySQL:     Source distribution 5.6.34  
  16. ......  
  17. queries_read          1  
  18. queries_with_diffs    0  
  19. queries_with_errors   0  

查看慢查询中的对应的查询SQL在两个服务器的运行结果范例:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-upgrade h=192.168.1.101 h=192.168.1.102 --user=root --password=123456 /data/mysql/data/mysql-slow.log  
  2. .......  

6)pt-index-usage
功能介绍:
这个工具主要是用来分析慢查询的索引使用情况。从log文件中读取插叙语句,并用explain分析他们是如何利用索引。完成分析之后会生成一份关于索引没有被查询使用过的报告。
用法介绍:
pt-index-usage [OPTION...] [FILE...]
可以直接从慢查询中获取sql,FILE文件中的sql格式必须和慢查询中个是一致,如果不是一直需要用pt-query-digest转换一下。也可以不生成报告直接保存到数据库中,具体的见后面的示例
注意:使用这个工具需要MySQL必须要有密码,另外运行时可能报找不到/var/lib/mysql/mysql.sock的错,简单的从mysql启动后的sock文件做一个软链接即可。
重点要说明的是pt-index-usage只能分析慢查询日志,所以如果想全面分析所有查询的索引使用情况就得将slow_launch_time设置为0因此请谨慎使用该工具,线上使用的话最好在凌晨进行分析,尤其分析大量日志的时候是很耗CPU的。
整体来说这个工具是不推荐使用的,要想实现类似的分析可以考虑一些其他第三方的工具,比如:mysqlidxchx, userstat和check-unused-keys。网上比较推荐的是userstat,一个Google贡献的patch。
使用示例:
从满查询中的sql查看索引使用情况范例:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-index-usage --host=localhost --user=root --password=123456 /data/mysql/data/mysql-slow.log  

将分析结果保存到数据库范例:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-index-usage --host=localhost --user=root --password=123456 /data/mysql/data/mysql-slow.log  --no-report --create-save-results-database  

7)pt-visual-explain
功能介绍:
格式化explain出来的执行计划按照tree方式输出,方便阅读。
用法介绍:
pt-visual-explain [OPTION...] [FILE...]
通过管道直接查看explain输出结果的范例:

[plain]  view plain  copy
  1. mysql> select * from huanqiu.haha;  
  2. +----+-------------+  
  3. | id | name        |  
  4. +----+-------------+  
  5. |  1 | wangshibo   |  
  6. |  2 | wangshihuan |  
  7. |  3 | 王世博      |  
  8. | 10 | wangshiman  |  
  9. +----+-------------+  
  10. 4 rows in set (0.00 sec)  
  11.    
  12. [root@master-server ~]# mysql -uroot -p123456  -e "explain select * from huanqiu.haha" |pt-visual-explain  
  13. Warning: Using a password on the command line interface can be insecure.  
  14. Table scan  
  15. rows           4  
  16. +- Table  
  17.    table          haha  
  18.       
  19. [root@master-server ~]# mysql -uroot -p123456  -e "explain select * from huanqiu.haha where id=3" |pt-visual-explain  
  20. Warning: Using a password on the command line interface can be insecure.  
  21. Bookmark lookup  
  22. +- Table  
  23. |  table          haha  
  24. |  possible_keys  PRIMARY  
  25. +- Constant index lookup  
  26.    key            haha->PRIMARY  
  27.    possible_keys  PRIMARY  
  28.    key_len        4  
  29.    ref            const  
  30.    rows           1  

查看包含查询语句的test.sql文件的范例:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-visual-explain --connect /root/test.sql --user=root --password=123456  

8)pt-config-diff
功能介绍:
比较mysql配置文件和服务器参数
用法介绍:
pt-config-diff [OPTION...] CONFIG CONFIG [CONFIG...]
CONFIG可以是文件也可以是数据源名称,最少必须指定两个配置文件源,就像unix下面的diff命令一样,如果配置完全一样就不会输出任何东西。
使用示例:
范例1:查看本地和远程服务器的配置文件差异:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-config-diff h=localhost h=192.168.1.102 --user=root --password=123456  
  2. 18 config differences  
  3. Variable                  master-server             slave-server  
  4. ========================= ========================= =========================  
  5. binlog_checksum           NONE                      CRC32  
  6. general_log_file          /data/mysql/data/maste... /data/mysql/data/slave...  
  7. hostname                  master-server             slave-server  
  8. innodb_version            5.6.33                    5.6.34  
  9. log_bin_index             /data/mysql/data/maste... /data/mysql/data/slave...  
  10. log_slave_updates         OFF                       ON  
  11. relay_log_recovery        OFF                       ON  
  12. secure_file_priv                                    NULL  
  13. server_id                 101                       102  
  14. server_uuid               d8497104-d7a7-11e6-911... d8773e51-d7a7-11e6-911...  
  15. slave_net_timeout         3600                      5  
  16. slave_skip_errors         OFF                       ALL  
  17. sync_binlog               1                         0  
  18. sync_master_info          10000                     1  
  19. sync_relay_log            10000                     1  
  20. sync_relay_log_info       10000                     1  
  21. system_time_zone          CST                       EST  
  22. version                   5.6.33-log                5.6.34-log  

范例2:比较本地配置文件和远程服务器的差异:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-config-diff /usr/local/mysql/my.cnf h=localhost h=192.168.1.102 --user=root --password=123456  
  2. 6 config differences  
  3. Variable                  /usr/local/mysql/my.cnf master-server      slave-ser  
  4. ========================= ================= ================== ===============  
  5. binlog_checksum           none              NONE               CRC32  
  6. innodb_read_io_threads    1000              64                 64  
  7. innodb_write_io_threads   1000              64                 64  
  8. log_bin_index             master-bin.index  /data/mysql/dat... /data/mysql/...  
  9. server_id                 101               101                102  
  10. sync_binlog               1                 1                  0  

9)pt-mysql-summary
功能介绍:
精细地对mysql的配置和sataus信息进行汇总,汇总后你直接看一眼就能看明白。
工作原理:连接mysql后查询出status和配置信息保存到临时目录中,然后用awk和其他的脚本工具进行格式化。OPTIONS可以查阅官网的相关页面。
用法介绍:
pt-mysql-summary [OPTIONS] [-- MYSQL OPTIONS]
使用示例:
汇总本地mysql服务器的status和配置信息:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-mysql-summary -- --user=root --password=123456 --host=localhost  

10)pt-deadlock-logger
功能介绍:
提取和记录mysql死锁的相关信息
用法介绍:
pt-deadlock-logger [OPTION...] SOURCE_DSN
收集和保存mysql上最近的死锁信息,可以直接打印死锁信息和存储死锁信息到数据库中,死锁信息包括发生死锁的服务器、最近发生死锁的时间、死锁线程id、死锁的事务id、发生死锁时事务执行了多长时间等等非常多的信息。
使用示例:
查看本地mysql的死锁信息

[plain]  view plain  copy
  1. [root@master-server ~]# pt-deadlock-logger  --user=root --password=123456 h=localhost D=test,t=deadlocks  
  2. server ts thread txn_id txn_time user hostname ip db tbl idx lock_type lock_mode wait_hold victim query  
  3. localhost 2017-01-11T11:00:33 188 0 0 root  192.168.1.101 huanpc checksums PRIMARY RECORD X w 1 REPLACE INTO `huanpc`.`checksums` (db, tbl, chunk, chunk_index, lower_boundary, upper_boundary, this_cnt, this_crc) SELECT 'huanpc', 'heihei', '1', NULL, NULL, NULL, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `member`, `city`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `huanpc`.`heihei` /*checksum table*/  
  4. localhost 2017-01-11T11:00:33 198 0 0 root  192.168.1.101 huanpc checksums PRIMARY RECORD X w 0 REPLACE INTO `huanpc`.`checksums` (db, tbl, chunk, chunk_index, lower_boundary, upper_boundary, this_cnt, this_crc) SELECT 'huanpc', 'heihei', '1', NULL, NULL, NULL, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `member`, `city`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `huanpc`.`heihei` /*checksum table*/  

11)pt-mext
功能介绍:
并行查看SHOW GLOBAL STATUS的多个样本的信息。
用法介绍:
pt-mext [OPTIONS] -- COMMAND
原理:pt-mext执行你指定的COMMAND,并每次读取一行结果,把空行分割的内容保存到一个一个的临时文件中,最后结合这些临时文件并行查看结果。
使用示例:
每隔10s执行一次SHOW GLOBAL STATUS,并将结果合并到一起查看

[plain]  view plain  copy
  1. [root@master-server ~]# pt-mext  -- mysqladmin ext -uroot -p123456  -i10 -c3  

12)pt-query-digest
功能介绍:
分析查询执行日志,并产生一个查询报告,为MySQL、PostgreSQL、 memcached过滤、重放或者转换语句。
pt-query-digest可以从普通MySQL日志,慢查询日志以及二进制日志中分析查询,甚至可以从SHOW PROCESSLIST和MySQL协议的tcpdump中进行分析,如果没有指定文件,它从标准输入流(STDIN)中读取数据。
用法介绍:
pt-query-digest [OPTION...] [FILE]
解析和分析mysql日志文件
使用示例:(建议:当log很大的时候最好还是将日志文件移到其他机器上进行分析,以免过多耗费本机性能)
范例1:分析本地的慢查询日志文件(本例是慢查询日志,也可以是mysql的其他日志)

[plain]  view plain  copy
  1. [root@master-server ~]# pt-query-digest --user=root --password=123456 /data/mysql/data/mysql-slow.log  
  2.    
  3. # 260ms user time, 30ms system time, 24.85M rss, 204.71M vsz  
  4. # Current date: Mon Jan 16 13:20:39 2017  
  5. # Hostname: master-server  
  6. # Files: /data/mysql/data/mysql-slow.log  
  7. # Overall: 18 total, 2 unique, 0 QPS, 0x concurrency _____________________  
  8. # Time range: all events occurred at 2017-01-11 11:00:33  
  9. # Attribute          total     min     max     avg     95%  stddev  median  
  10. # ============     ======= ======= ======= ======= ======= ======= =======  
  11. # Exec time           812s      2s     92s     45s     80s     27s     52s  
  12. # Lock time              0       0       0       0       0       0       0  
  13. # Rows sent              0       0       0       0       0       0       0  
  14. # Rows examine           0       0       0       0       0       0       0  
  15. # Query size         1.10k      62      63   62.56   62.76    0.50   62.76  
  16.    
  17. # Profile  
  18. # Rank Query ID           Response time  Calls R/Call  V/M   Item  
  19. # ==== ================== ============== ===== ======= ===== =============  
  20. #    1 0x50B84661D4CCF34B 467.9075 57.6%    10 46.7907 16.48 CREATE DATABASE `huanqiu`  
  21. #    2 0x9CC34439A4FB17E3 344.2984 42.4%     8 43.0373 16.22 CREATE DATABASE `huanpc`  
  22.    
  23. # Query 1: 0 QPS, 0x concurrency, ID 0x50B84661D4CCF34B at byte 2642 _____  
  24. # This item is included in the report because it matches --limit.  
  25. # Scores: V/M = 16.48  
  26. # Time range: all events occurred at 2017-01-11 11:00:33  
  27. # Attribute    pct   total     min     max     avg     95%  stddev  median  
  28. # ============ === ======= ======= ======= ======= ======= ======= =======  
  29. # Count         55      10  
  30. # Exec time     57    468s      2s     92s     47s     80s     28s     52s  
  31. # Lock time      0       0       0       0       0       0       0       0  
  32. # Rows sent      0       0       0       0       0       0       0       0  
  33. # Rows examine   0       0       0       0       0       0       0       0  
  34. # Query size    55     630      63      63      63      63       0      63  
  35. # String:  
  36. # Hosts  
  37. # Users        root  
  38. # Query_time distribution  
  39. #   1us  
  40. #  10us  
  41. # 100us  
  42. #   1ms  
  43. #  10ms  
  44. # 100ms  
  45. #    1s  #######  
  46. #  10s+  ################################################################  
  47. CREATE DATABASE IF NOT EXISTS `huanqiu` /* pt-table-checksum */\G  
  48.    
  49. # Query 2: 0 QPS, 0x concurrency, ID 0x9CC34439A4FB17E3 at byte 3083 _____  
  50. # This item is included in the report because it matches --limit.  
  51. # Scores: V/M = 16.22  
  52. # Time range: all events occurred at 2017-01-11 11:00:33  
  53. # Attribute    pct   total     min     max     avg     95%  stddev  median  
  54. # ============ === ======= ======= ======= ======= ======= ======= =======  
  55. # Count         44       8  
  56. # Exec time     42    344s      2s     82s     43s     80s     26s     56s  
  57. # Lock time      0       0       0       0       0       0       0       0  
  58. # Rows sent      0       0       0       0       0       0       0       0  
  59. # Rows examine   0       0       0       0       0       0       0       0  
  60. # Query size    44     496      62      62      62      62       0      62  
  61. # String:  
  62. # Hosts  
  63. # Users        root  
  64. # Query_time distribution  
  65. #   1us  
  66. #  10us  
  67. # 100us  
  68. #   1ms  
  69. #  10ms  
  70. # 100ms  
  71. #    1s  #########  
  72. #  10s+  ################################################################  
  73. CREATE DATABASE IF NOT EXISTS `huanpc` /* pt-table-checksum */\G  
  74.    
  75. 整个输出分为三大部分:  
  76. 1)整体概要(Overall)  
  77. 这个部分是一个大致的概要信息(类似loadrunner给出的概要信息),通过它可以对当前MySQL的查询性能做一个初步的评估,比如各个指标的最大值(max),平均值(min),95%分布值,中位数(median),标准偏差(stddev)。  
  78. 这些指标有查询的执行时间(Exec time),锁占用的时间(Lock time),MySQL执行器需要检查的行数(Rows examine),最后返回给客户端的行数(Rows sent),查询的大小。  
  79.    
  80. 2)查询的汇总信息(Profile)  
  81. 这个部分对所有“重要”的查询(通常是比较慢的查询)做了个一览表。  
  82. 每个查询都有一个Query ID,这个ID通过Hash计算出来的。pt-query-digest是根据这个所谓的Fingerprint来group by的。  
  83. Rank整个分析中该“语句”的排名,一般也就是性能最常的。  
  84. Response time  “语句”的响应时间以及整体占比情况。  
  85. Calls 该“语句”的执行次数。  
  86. R/Call 每次执行的平均响应时间。  
  87. V/M 响应时间的差异平均对比率。  
  88. 在尾部有一行输出,显示了其他2个占比较低而不值得单独显示的查询的统计数据。  
  89.    
  90. 3)详细信息  
  91. 这个部分会列出Profile表中每个查询的详细信息:  
  92. 包括Overall中有的信息、查询响应时间的分布情况以及该查询”入榜”的理由。  
  93. pt-query-digest还有很多复杂的操作,这里就不一一介绍了。比如:从PROCESSLIST中查询某个MySQL中最慢的查询:  

范例2:重新回顾满查询日志,并将结果保存到query_review中,注意query_review表的表结构必须先建好,表结构如下:

[plain]  view plain  copy
  1. mysql> use test;  
  2. Database changed  
  3.    
  4. mysql> CREATE TABLE query_review (  
  5.     ->    checksum     BIGINT UNSIGNED NOT NULL PRIMARY KEY,  
  6.     ->    fingerprint  TEXT NOT NULL,  
  7.     ->    sample       TEXT NOT NULL,  
  8.     ->    first_seen   DATETIME,  
  9.     ->    last_seen    DATETIME,  
  10.     ->    reviewed_by  VARCHAR(20),  
  11.     ->    reviewed_on  DATETIME,  
  12.     ->    comments     TEXT  
  13.     -> );  
  14. Query OK, 0 rows affected (0.02 sec)  
  15.     
  16. mysql> select * from query_review;  
  17. Empty set (0.00 sec)  
  18.     
  19. [root@master-server ~]# pt-query-digest --user=root --password=123456 --review h=localhost,D=test,t=query_review /data/mysql/data/mysql-slow.log  
  20.    
  21. mysql> select * from query_review;  
  22. +----------------------+------------------------------------------+-----------------------------------------------------------------+----------  
  23. | checksum | fingerprint | sample | first_see  
  24. +----------------------+------------------------------------------+-----------------------------------------------------------------+----------  
  25. | 5816476304744969035 | create database if not exists `huanqiu` | CREATE DATABASE IF NOT EXISTS `huanqiu` /* pt-table-checksum */ | 2017-01-1  
  26. | 11295947304747079651 | create database if not exists `huanpc` | CREATE DATABASE IF NOT EXISTS `huanpc` /* pt-table-checksum */ | 2017-01-1  
  27. +----------------------+------------------------------------------+-----------------------------------------------------------------+----------  
  28. 2 rows in set (0.00 sec)  

从tcpdump中分析:

[plain]  view plain  copy
  1. [root@master-server ~]# tcpdump -s 65535 -x -nn -q -tttt -i any -c 1000 port 3306 > mysql.tcp.txt  
  2. tcpdump: verbose output suppressed, use -v or -vv for full protocol decode  
  3. listening on any, link-type LINUX_SLL (Linux cooked), capture size 65535 bytes  
  4.    
  5. 然后打开另一个终端窗口:  
  6. [root@master-server ~]# pt-query-digest --type tcpdump mysql.tcp.txt  
  7. Pipeline process 3 (TcpdumpParser) caused an error: substr outside of string at /usr/bin/pt-query-digest line 3628, <> chunk 93.  
  8. Will retry pipeline process 2 (TcpdumpParser) 100 more times.  
  9.    
  10. # 320ms user time, 20ms system time, 24.93M rss, 204.84M vsz  
  11. # Current date: Mon Jan 16 13:24:50 2017  
  12. # Hostname: master-server  
  13. # Files: mysql.tcp.txt  
  14. # Overall: 31 total, 4 unique, 4.43 QPS, 0.00x concurrency _______________  
  15. # Time range: 2017-01-16 13:24:43.000380 to 13:24:50.001205  
  16. # Attribute          total     min     max     avg     95%  stddev  median  
  17. # ============     ======= ======= ======= ======= ======= ======= =======  
  18. # Exec time           30ms    79us     5ms   967us     4ms     1ms   159us  
  19. # Rows affecte          14       0       2    0.45    1.96    0.82       0  
  20. # Query size         1.85k      17     200   61.16  192.76   72.25   17.65  
  21. .........  

13)pt-slave-delay
功能介绍:
设置从服务器落后于主服务器指定时间。
用法介绍:
pt-slave-delay [OPTION...] SLAVE-HOST [MASTER-HOST]
原理:通过启动和停止复制sql线程来设置从落后于主指定时间。默认是基于从上relay日志的二进制日志的位置来判断,因此不需要连接到主服务器,如果IO进程不落后主服务器太多的话,这个检查方式工作很好,如果网络通畅的话,一般IO线程落后主通常都是毫秒级别。一般是通过--delay and --delay"+"--interval来控制。--interval是指定检查是否启动或者停止从上sql线程的频繁度,默认的是1分钟检查一次。
使用示例:
范例1:使从落后主1分钟,并每隔1分钟检测一次,运行10分钟

[plain]  view plain  copy
  1. [root@master-server ~]# pt-slave-delay --user=root --password=123456 --delay 1m --run-time 10m --host=192.168.1.102  
  2. 2017-01-16T13:32:31 slave running 0 seconds behind  
  3. 2017-01-16T13:32:31 STOP SLAVE until 2017-01-16T13:33:31 at master position mysql-bin.000005/102554361  

范例2:使从落后主1分钟,并每隔15秒钟检测一次,运行10分钟:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-slave-delay --user=root --password=123456 --delay 1m --interval 15s --run-time 10m --host=192.168.1.102  
  2. 2017-01-16T13:38:22 slave running 0 seconds behind  
  3. 2017-01-16T13:38:22 STOP SLAVE until 2017-01-16T13:39:22 at master position mysql-bin.000005/102689359  

14)pt-slave-restart
功能介绍:
监视mysql复制错误,并尝试重启mysql复制当复制停止的时候
用法介绍:
pt-slave-restart [OPTION...] [DSN]
监视一个或者多个mysql复制错误,当从停止的时候尝试重新启动复制。你可以指定跳过的错误并运行从到指定的日志位置。
使用示例:
范例1:监视192.168.1.101的从,跳过1个错误

[plain]  view plain  copy
  1. [root@master-server ~]# pt-slave-restart --user=root --password=123456 --host=192.168.1.101 --skip-count=1  

范例2:监视192.168.1.101的从,跳过错误代码为1062的错误。

[plain]  view plain  copy
  1. [root@master-server ~]# pt-slave-restart --user=root --password=123456 --host=192.168.1.101 --error-numbers=1062  

15)pt-diskstats
功能介绍:
是一个对GUN/LINUX的交互式监控工具
用法介绍:
pt-diskstats [OPTION...] [FILES]
为GUN/LINUX打印磁盘io统计信息,和iostat有点像,但是这个工具是交互式并且比iostat更详细。可以分析从远程机器收集的数据。
使用示例:
范例1:查看本机所有的磁盘的状态情况:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-diskstats  

范例2:只查看本机sdc1磁盘的状态情况:
[plain]  view plain  copy
  1. [root@master-server ~]# pt-diskstats  --devices-regex vdc1  
  2.   #ts device    rd_s rd_avkb rd_mb_s rd_mrg rd_cnc   rd_rt    wr_s wr_avkb wr_mb_s wr_mrg wr_cnc   wr_rt busy in_prg    io_s  qtime stime  
  3.   0.9 vdc1       0.0     0.0     0.0     0%    0.0     0.0     5.9     4.0     0.0     0%    0.0     1.0   0%      0     5.9    0.6   0.4  
  4.   1.0 vdc1       0.0     0.0     0.0     0%    0.0     0.0     2.0     6.0     0.0    33%    0.0     0.7   0%      0     2.0    0.0   0.7  

16)pt-summary
功能介绍:
友好地收集和显示系统信息概况,此工具并不是一个调优或者诊断工具,这个工具会产生一个很容易进行比较和发送邮件的报告。
用法介绍:
pt-summary
原理:此工具会运行和多命令去收集系统状态和配置信息,先保存到临时目录的文件中去,然后运行一些unix命令对这些结果做格式化,最好是用root用户或者有权限的用户运行此命令。
使用示例:
查看本地系统信息概况

[plain]  view plain  copy
  1. [root@master-server ~]# pt-summary  

17)pt-stalk
功能介绍:
出现问题的时候收集mysql的用于诊断的数据
用法介绍:
pt-stalk [OPTIONS] [-- MYSQL OPTIONS]
pt-stalk等待触发条件触发,然后收集数据帮助错误诊断,它被设计成使用root权限运行的守护进程,因此你可以诊断那些你不能直接观察的间歇性问题。默认的诊断触发条件为SHOW GLOBAL STATUS。也可以指定processlist为诊断触发条件 ,使用--function参数指定。
使用示例:
范例1:指定诊断触发条件为status,同时运行语句超过20的时候触发,收集的数据存放在目标目录/tmp/test下:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-stalk  --function status --variable Threads_running --threshold 20 --dest /tmp/test  -- -uroot -p123456  -h192.168.1.101  

范例2:指定诊断触发条件为processlist,超过20个状态为statistics触发,收集的数据存放在/tmp/test目录下:

[plain]  view plain  copy
  1. [root@master-server ~]# pt-stalk  --function processlist --variable State --match statistics --threshold 20 --dest /tmp/test -- -uroot -p123456  -h192.168.1.101  
  2. .......  
  3. 2017_01_15_17_31_49-hostname  
  4. 2017_01_15_17_31_49-innodbstatus1  
  5. 2017_01_15_17_31_49-innodbstatus2  
  6. 2017_01_15_17_31_49-interrupts  
  7. 2017_01_15_17_31_49-log_error  
  8. 2017_01_15_17_31_49-lsof  
  9. 2017_01_15_17_31_49-meminfo  

18)pt-archiver
功能介绍:
将mysql数据库中表的记录归档到另外一个表或者文件
用法介绍:
pt-archiver [OPTION...] --source DSN --where WHERE
这个工具只是归档旧的数据,不会对线上数据的OLTP查询造成太大影响,你可以将数据插入另外一台服务器的其他表中,也可以写入到一个文件中,方便使用source命令导入数据。另外你还可以用它来执行delete操作。特别注意:这个工具默认的会删除源中的数据!!
使用示例:
范例1:将192.168.1.101上的huanqiu库的haha表id小于10的记录转移到192.168.1.102上的wangshibo库下的wang_test表内,并归档到/var/log/haha_archive_20170115.log文件中(注意:转移前后,两张表对应转移字段要相同,字段属性最好也要相同;)

[plain]  view plain  copy
  1. <span style="color:#333333;">源数据库机器192.168.1.101的huanqiu库下的haha表在转移前的信息:  
  2. mysql> select * from huanqiu.haha;                                                                                                              
  3. +----+---------------+  
  4. | id | name          |  
  5. +----+---------------+  
  6. |  1 | changbo       |  
  7. |  2 | wangpengde    |  
  8. |  4 | guocongcong   |  
  9. |  5 | kevin         |  
  10. |  8 | mamin         |  
  11. |  9 | shihonge      |  
  12. | 11 | zhanglei      |  
  13. | 15 | zhanghongmiao |  
  14. +----+---------------+  
  15. 8 rows in set (0.01 sec)  
  16.    
  17. 目标数据库机器192.168.1.102的wangshibo库下的wang_test表在转移前的信息:  
  18. mysql> select * from wangshibo.wang_test;  
  19. +------+-----------+  
  20. | id   | name      |  
  21. +------+-----------+  
  22. |   20 | guominmin |  
  23. |   21 | gaofei    |  
  24. |   22 | 李梦楠    |  
  25. +------+-----------+  
  26. 3 rows in set (0.00 sec)  
  27.    
  28. 接着在192.168.1.101机器上执行转移命令:  
  29. [root@master-server ~]# pt-archiver --source h=192.168.1.101,D=huanqiu,t=haha --user=root --password=123456 --dest h=192.168.1.102,D=wangshibo,t=wang_test --file '/var/log/haha_archive_20170115.log' --where "id<=10"  --commit-each  
  30.    
  31. 上面命令执行成功后,再次观察转移前后信息  
  32. 发现源数据库机器192.168.1.101的huanqiu.haha表数据在转移后,源数据也删除了!  
  33. mysql> select * from huanqiu.haha;  
  34. +----+---------------+  
  35. | id | name          |  
  36. +----+---------------+  
  37. | 11 | zhanglei      |  
  38. | 15 | zhanghongmiao |  
  39. +----+---------------+  
  40. 2 rows in set (0.00 sec)  
  41.    
  42. 查看归档日志:  
  43. [root@master-server ~]# tail -f /var/log/haha_archive_20170115.log  
  44. 1   changbo  
  45. 2   wangpengde  
  46. 4   guocongcong  
  47. 5   kevin  
  48. 8   mamin  
  49. 9   shihonge  
  50.    
  51. 目标数据库192.168.1.102的wangshibo.wang_test表内已经移转到了新数据  
  52. mysql> select * from wangshibo.wang_test;  
  53. +------+-------------+  
  54. | id   | name        |  
  55. +------+-------------+  
  56. |   20 | guominmin   |  
  57. |   21 | gaofei      |  
  58. |   22 | 李梦楠       |  
  59. |    1 | changbo     |  
  60. |    2 | wangpengde  |  
  61. |    4 | guocongcong |  
  62. |    5 | kevin       |  
  63. |    8 | mamin       |  
  64. |    9 | shihonge    |  
  65. +------+-------------+  
  66. 9 rows in set (0.00 sec)</span>  

范例2:将192.168.1.101上的huanqiu库的haha表里id小于10的记录归档到haha_log_archive_2017.10.10.log文件中:

[plain]  view plain  copy
  1. mysql> select * from huanqiu.haha;  
  2. +----+---------------+  
  3. | id | name          |  
  4. +----+---------------+  
  5. |  1 | changbo       |  
  6. |  2 | wangpengde    |  
  7. |  4 | guocongcong   |  
  8. |  5 | kevin         |  
  9. |  8 | mamin         |  
  10. |  9 | shihonge      |  
  11. | 11 | zhanglei      |  
  12. | 15 | zhanghongmiao |  
  13. +----+---------------+  
  14. 8 rows in set (0.00 sec)  
  15.    
  16. [root@master-server ~]# pt-archiver --source h=192.168.1.101,D=huanqiu,t=haha --user=root --password=123456 --file 'haha_log_archive_2017.10.10.log' --where "id<=10" --commit-each  
  17.    
  18. 转移后的源数据已被删除  
  19. mysql> select * from huanqiu.haha;  
  20. +----+---------------+  
  21. | id | name          |  
  22. +----+---------------+  
  23. | 11 | zhanglei      |  
  24. | 15 | zhanghongmiao |  
  25. +----+---------------+  
  26. 2 rows in set (0.00 sec)  
  27.    
  28. 查看归档文件  
  29. [root@master-server ~]# cat haha_log_archive_2017.10.10.log  
  30. 1   changbo  
  31. 2   wangpengde  
  32. 4   guocongcong  
  33. 5   kevin  
  34. 8   mamin  
  35. 9   shihonge  

范例3:删除192.168.1.101上的huanqiu库的haha表中id小于10的记录:

[plain]  view plain  copy
  1. mysql> select * from huanqiu.haha;  
  2. +----+---------------+  
  3. | id | name          |  
  4. +----+---------------+  
  5. |  1 | changbo       |  
  6. |  2 | wangpengde    |  
  7. |  4 | guocongcong   |  
  8. |  5 | kevin         |  
  9. |  8 | mamin         |  
  10. |  9 | shihonge      |  
  11. | 11 | zhanglei      |  
  12. | 15 | zhanghongmiao |  
  13. +----+---------------+  
  14. 8 rows in set (0.00 sec)  
  15.    
  16. [root@master-server ~]# pt-archiver --source h=192.168.1.101,D=huanqiu,t=haha --user=root --password=123456 --purge --where 'id<=10' --no-check-charset  
  17. <br>再次查看,发现数据已成功删除!  
  18. mysql> select * from huanqiu.haha;  
  19. +----+---------------+  
  20. | id | name          |  
  21. +----+---------------+  
  22. | 11 | zhanglei      |  
  23. | 15 | zhanghongmiao |  
  24. +----+---------------+  
  25. 2 rows in set (0.00 sec)  

19)pt-find
功能介绍:
查找mysql表并执行指定的命令,和gnu的find命令类似。
用法介绍:
pt-find [OPTION...] [DATABASE...]
默认动作是打印数据库名和表名
使用示例:
查找192.168.1.101中1天以前创建的InnoDB的表 ,并打印。

[plain]  view plain  copy
  1. [root@master-server ~]# pt-find --ctime +1  --host=192.168.1.101 --engine InnoDB --user=root --password=123456  
  2. `huanpc`.`_heihei_new`  
  3. `huanpc`.`checksums`  
  4. `huanqiu`.`_haha_new`  
  5. `huanqiu`.`checksums`  
  6. `huanqiu`.`heartbeat`  
  7. `mysql`.`innodb_index_stats`  
  8. `mysql`.`innodb_table_stats`  
  9. `mysql`.`slave_master_info`  
  10. `mysql`.`slave_relay_log_info`  
  11. `mysql`.`slave_worker_info`  

范例2:查找192.168.1.101中1天以前更改过的数据库名字匹配%huanqiu%的并且引擎为Myisam的表,并将表的引擎更改为Innodb引擎。

[plain]  view plain  copy
  1. 先查找出192.168.1.101上1天以前更改过的数据库名字匹配%huanqiu%的并且引擎为Myisam的表  
  2. [root@master-server ~]# pt-find --ctime +2 --dblike huanqiu --host=192.168.1.101 --engine Myisam --user=root --password=123456  
  3. `huanqiu`.`_haha_new`  
  4. `huanqiu`.`checksums`  
  5. `huanqiu`.`heartbeat`  
  6. [root@master-server ~]# pt-find --ctime +2 --dblike huanpc --host=192.168.1.101 --engine Myisam --user=root --password=123456  
  7. `huanpc`.`_heihei_new`  
  8. `huanpc`.`checksums`  
  9.    
  10. 再将查找出的表的引擎改为Innodb  
  11. [root@master-server ~]# pt-find --ctime +2 --dblike huanqiu --host=192.168.1.101 --engine Myisam --user=root --password=123456 --exec "ALTER TABLE %D.%N ENGINE=InnoDB"  
  12. [root@master-server ~]# pt-find --ctime +2 --dblike huanpc --host=192.168.1.101 --engine Myisam --user=root --password=123456 --exec "ALTER TABLE %D.%N ENGINE=InnoDB"  
  13.    
  14. 最后再检查对应数据表的引擎  

范例3:查找192.168.1.101中huanqiu库和huanpc库中的空表,并删除。

[plain]  view plain  copy
  1. [root@master-server ~]# pt-find --empty huanqiu huanpc --host=192.168.1.101 --user=root --password=123456  --exec-plus "DROP TABLE %s"  


范例4:查找192.168.1.101中超过100M的表

[plain]  view plain  copy
  1. [root@master-server ~]# pt-find --tablesize +100M --host=192.168.1.101 --user=root --password=123456  

20)pt-kill
功能介绍:
Kill掉符合指定条件mysql语句
用法介绍:
pt-kill [OPTIONS]
加入没有指定文件的话pt-kill连接到mysql并通过SHOW PROCESSLIST找到指定的语句,反之pt-kill从包含SHOW PROCESSLIST结果的文件中读取mysql语句
使用示例:
范例1:查找192.168.1.101数据库服务器运行时间超过60s的语句,并打印

[plain]  view plain  copy
  1. [root@master-server ~]# pt-kill --busy-time 60 --print --host=192.168.1.101 --user=root --password=123456  

范例2:查找192.168.1.101数据库服务器运行时间超过60s的语句,并kill

[plain]  view plain  copy
  1. [root@master-server ~]# pt-kill --busy-time 60 --kill --host=192.168.3.135 --user=root --password=123456  

范例3:从proccesslist文件中查找执行时间超过60s的语句

[plain]  view plain  copy
  1. [root@master-server ~]# mysql -uroot -p123456 -h192.168.1.101 -e "show processlist" > processlist.txt  
  2. Warning: Using a password on the command line interface can be insecure.  
  3. [root@master-server ~]# pt-kill --test-matching processlist.txt --busy-time 60 --print  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值