当PostgreSQL发生主从切换导致时间线分裂时,可以通过pg_rewind
工具来修复。
触发时间线分裂时,通常会在旧主降级并连接到新主时,日志中出现如下报错并退出:
sql
FATAL: timeline X of the primary does not match recovery target timeline Y
以下是具体的修复操作步骤:
备份配置文件
在执行pg_rewind
之前,首先需要备份新主库和需要rewind
的库的配置文件,以免在rewind
过程中这些配置文件被修改或覆盖。重要的配置文件包括postgresql.conf
、pg_hba.conf
和recovery.conf
(如果存在)。
在需要rewind的库上操作:
登录到数据库服务器:
su - postgres
ssh 172.25.100.1
停止PostgreSQL服务:
arduino
pg_ctl stop -m fast
进入PGDATA目录:
bash
cd /data/postgres/pgdata
备份配置文件:
bash
export BACKUP_DIR=/data/backup
mkdir -p $BACKUP_DIR
cp postgresql.conf $BACKUP_DIR/postgresql.conf.bak
cp pg_hba.conf $BACKUP_DIR/pg_hba.conf.bak
if [ -f recovery.conf ]; then cp recovery.conf $BACKUP_DIR/recovery.conf.bak; fi
使用pg_rewind
pg_rewind
工具用于在主从切换后,将一个之前是主库的PostgreSQL实例同步到新的主库上,以解决时间线分裂的问题。确保新主库正在运行,并且需要rewind的库已经停止。
确保新主库(172.21.100.1)正在运行。
在需要rewind的库上执行pg_rewind
:
ini
# 验证(dry-run)
pg_rewind -n --target-pgdata=/data/postgres/pgdata --source-server='host=172.21.100.1 port=1921 user=postgres password=fake_password dbname=postgres'
# 实际执行
pg_rewind --target-pgdata=/data/postgres/pgdata --source-server='host=172.21.100.1 port=1921 user=postgres password=fake_password dbname=postgres'
确认pg_rewind
执行完成后没有错误。
恢复配置文件
在pg_rewind
操作完成后,需要将之前备份的配置文件恢复到PGDATA目录。
进入PGDATA目录:
bash
cd /data/postgres/pgdata
恢复配置文件:
bash
export BACKUP_DIR=/data/backup
mkdir -p $BACKUP_DIR
cp $BACKUP_DIR/postgresql.conf.bak postgresql.conf
cp $BACKUP_DIR/pg_hba.conf.bak pg_hba.conf
if [ -f $BACKUP_DIR/recovery.conf.bak ]; then cp $BACKUP_DIR/recovery.conf.bak recovery.conf; fi
重启PostgreSQL服务
重启PostgreSQL服务,以应用pg_rewind
操作和恢复的配置文件。
sql
pg_ctl start
验证
登录到PostgreSQL数据库,检查数据是否同步,且配置是否正确。
使用psql
或其他客户端工具连接到数据库:
psql
运行一些基本的SQL命令来检查数据是否同步:
csharp
SELECT pg_current_wal_lsn();
检查时间线是否已经修复:
csharp
SELECT timeline_id FROM pg_control_checkpoint();
注意事项
- 确保在执行这些操作之前,理解每一步的作用和潜在的风险。
- 如果在使用
pg_rewind
时遇到任何问题,参考官方文档或寻求专业帮助。 - 在执行
pg_rewind
之前,确保目标库已经完全停止,以避免数据损坏。 - 在生产环境中操作时,建议先在测试环境进行验证。