巧用python-mysql-replication寻找pos点

假如线上采用了1主1从,而且没有使用其他的高可用组件,而且也没有开启gtid复制,架构图如下:

巧用python-mysql-replication寻找pos点

在图1是master宕机了,在图2时业务需要切换到slave写入,假如此时你忘记了记录slave的pos点,直接修改域名指向从库,那么在master恢复以后如何接上复制?仔细看我上面的图中标注了server-id,没错,我们可以从binlog中寻找server-id来找寻准确的pos点。

正常情况下slave的binlog里面带入的是master的server-id,也就是4135,当slave开始写入数据时,那么自己的server-id:123就会记录在binlog里面。所以只需要在slave的binlog找到server-id为123开始的pos点时,就是原master恢复的时候需要指向的pos点。那么有两种做法:

1. 自己解析binlog根据server-id寻找pos点。比如需要确认大概什么时候切换的,然后找到具体那个时间段的binlog开始解析。

2. 利用python-mysql-replication这个库来找寻,至于python-mysql-replication是干嘛的,你可以自己度娘。

我这里简单的实现了一下,代码如下:

get_log_pos.py

#!/usr/bin/python
# -*- coding:utf-8 -*-

import sys
import datetime
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent
from pymysqlreplication.event import RotateEvent,QueryEvent

reload(sys)
sys.setdefaultencoding('utf8')

conn_setting = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "xx",
    "passwd": "xx"
}

stream = BinLogStreamReader(
    connection_settings=conn_setting,
    server_id=9999,
    log_file="mysql-bin.000009",
    log_pos=4,
    resume_stream=True,
    blocking=True
)

for binlogevent in stream:
    if isinstance(binlogevent, RotateEvent):
        current_master_log_file=binlogevent.next_binlog
        print "Next binlog file: %s" % (current_master_log_file)
    if isinstance(binlogevent, WriteRowsEvent) or isinstance(binlogevent, DeleteRowsEvent) or isinstance(binlogevent, UpdateRowsEvent) or isinstance(binlogevent, QueryEvent):
        if binlogevent.packet.server_id == 123:
            current_datetime=datetime.datetime.fromtimestamp(binlogevent.packet.timestamp)
            print "数据写入时间: %s" % (current_datetime)
            start_binlog_file=current_master_log_file
            start_binlog_pos=binlogevent.packet.log_pos
            print "开始的binlog文件: %s" % (start_binlog_file)
            print "开始的binlog pos点: %s" % (start_binlog_pos)
            exit(1)

输出结果如下:

Next binlog file: mysql-bin.000001
数据写入时间: 2020-05-11 11:56:09
开始的binlog文件: mysql-bin.000001
开始的binlog pos点: 146147

我们自己动手来解析binlog看看输出的pos点是否准确:

巧用python-mysql-replication寻找pos点

 可以看见是准确无误的。

总结:

线上一般会开启gtid或者使用其他高可用组件进行切换。python-mysql-replication是个好东西,建议同学们都学习使用一下。