一、概述
pg_rewind 是 postgresql 主从数据库之同步数据目录的工具。
pg_rewind 相比 pg_basebackup 和 rsync 这样的工具来说,优势是它不需要从源目录拷贝所有的数据文件,而是会对比时间线发生偏离的点,只拷贝变化过的文件,这样对于数据量很大的情况下速度更快。
pg_rewind 使用前提:需要目标服务器在 postgresql.conf 中允许 wal_log_hints(默认 off),或者在 initdb 初始化数据库时启用数据校验(–data-checksums),full_page_writes 也必须为 on(默认 on)。
二、语法
pg_rewind [option...] { -D | --target-pgdata } directory { --source-pgdata=directory | --source-server=connstr }
参数说明:
三、示例
1. 环境
CentOS 7.8 + HGDB v4.5.7 安全版
192.168.100.11 主
192.168.100.12 备
2. 构建测试数据
--主从(11,12),确保两参数均为 on
show wal_log_hints;
show full_page_writes;
alter system set wal_log_hints = 'on';
pg_ctl restart
--主(11)
create table test(id int,name varchar(20));
insert into test values(1,'aa'),(2,'bb'),(3,'cc');
--主从(11,12)
select * from test;
3.模拟主从时间线偏离
1)提升从库为主库
--从(12)
pg_ctl promote
select pg_is_in_recovery();
--主(11)
select pid,state,client_addr,sync_priority,sync_state from pg_stat_replication;
2)原主库插入数据
--原主(11)
insert into test values(4,'dd');
select * from test;
3)原从库插入数据
--原从(12)
insert into test values(5,'ee');
select * from test;
4)将原主库调为从库
--原主(11)
vi /opt/HighGo4.5.7-see/data/postgresql.auto.conf
standby_mode = 'on' --12之后参数废弃,创建标识文件替代 touch $PGDATA/standby.signal
primary_conninfo = 'user=sysdba password=Hello@123 host=192.168.100.12 port=5866'
--重启数据库后观察原主日志,可发现 wal 时间线已发生偏离(11)
pg_ctl restart
select pg_is_in_recovery();
tail -200f /opt/HighGo4.5.7-see/data/hgdb_log/highgodb_09.csv
streaming: ERROR: requested starting point 0/9000000 on timeline 3 is not in this server's history
DETAIL: This server's history forked from timeline 3 at 0/8034C50.",,,,,,,,,""
2022-03-09 15:42:44.256 CST,,,25847,,62285a74.64f7,5,,2022-03-09 15:42:44 CST,1/0,0,LOG,00000,"new timeline 4 forked off current database system timeline 3 before current recovery point 0/90000A0",,,,,,,,,""
--原备库可查询发生时间线偏离的 wal 文件(12)
select pg_xlogfile_name_offset('0/90000A0'); --10之前
select pg_walfile_name_offset('0/90000A0');
4. 使用 pg_rewind 同步时间线
--原主(11)
pg_ctl stop
pg_rewind --target-pgdata /opt/HighGo4.5.7-see/data/ --source-server='host=192.168.100.12 port=5866 user=sysdba dbname=highgo password=Hello@123'
#若报错缺少 wal 文件,从归档路径或另外节点拷贝 cp /highgo/hgdbbak/archive/000000030000000000000008 /opt/HighGo4.5.7-see/data/pg_wal/
vi /opt/HighGo4.5.7-see/data/postgresql.auto.conf
standby_mode = 'on' --12之后参数废弃,创建标识文件替代 touch $PGDATA/standby.signal
primary_conninfo = 'user=sysdba password=Hello@123 host=192.168.100.12 port=5866'
5. 启动数据库验证同步
--原主(11)
pg_ctl start
select * from test;
--原从(12)
select * from test;
select pid,state,client_addr,sync_priority,sync_state from pg_stat_replication;