Skip to content

Commit 63e316f

Browse files
committed
Fix pg_rewind bugs when rewinding a standby server.
If the target is a standby server, its WAL doesn't end at the last checkpoint record, but at minRecoveryPoint. We must scan all the WAL from the last common checkpoint all the way up to minRecoveryPoint for modified pages, and also consider that portion when determining whether the server needs rewinding. Backpatch to all supported versions. Author: Ian Barwick and me Discussion: https://www.postgresql.org/message-id/CABvVfJU-LDWvoz4-Yow3Ay5LZYTuPD7eSjjE4kGyNZpXC6FrVQ%40mail.gmail.com
1 parent 28bb8c4 commit 63e316f

File tree

3 files changed

+205
-23
lines changed

3 files changed

+205
-23
lines changed

src/bin/pg_rewind/parsexlog.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ static int SimpleXLogPageRead(XLogReaderState *xlogreader,
5757
* Read WAL from the datadir/pg_wal, starting from 'startpoint' on timeline
5858
* index 'tliIndex' in target timeline history, until 'endpoint'. Make note of
5959
* the data blocks touched by the WAL records, and return them in a page map.
60+
*
61+
* 'endpoint' is the end of the last record to read. The record starting at
62+
* 'endpoint' is the first one that is not read.
6063
*/
6164
void
6265
extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex,
@@ -97,7 +100,13 @@ extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex,
97100

98101
startpoint = InvalidXLogRecPtr; /* continue reading at next record */
99102

100-
} while (xlogreader->ReadRecPtr != endpoint);
103+
} while (xlogreader->EndRecPtr < endpoint);
104+
105+
/*
106+
* If 'endpoint' didn't point exactly at a record boundary, the caller
107+
* messed up.
108+
*/
109+
Assert(xlogreader->EndRecPtr == endpoint);
101110

102111
XLogReaderFree(xlogreader);
103112
if (xlogreadfd != -1)

src/bin/pg_rewind/pg_rewind.c

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ main(int argc, char **argv)
9999
XLogRecPtr chkptrec;
100100
TimeLineID chkpttli;
101101
XLogRecPtr chkptredo;
102+
XLogRecPtr target_wal_endrec;
102103
size_t size;
103104
char *buffer;
104105
bool rewind_needed;
@@ -240,42 +241,55 @@ main(int argc, char **argv)
240241
{
241242
printf(_("source and target cluster are on the same timeline\n"));
242243
rewind_needed = false;
244+
target_wal_endrec = 0;
243245
}
244246
else
245247
{
248+
XLogRecPtr chkptendrec;
249+
246250
findCommonAncestorTimeline(&divergerec, &lastcommontliIndex);
247251
printf(_("servers diverged at WAL location %X/%X on timeline %u\n"),
248252
(uint32) (divergerec >> 32), (uint32) divergerec,
249253
targetHistory[lastcommontliIndex].tli);
250254

255+
/*
256+
* Determine the end-of-WAL on the target.
257+
*
258+
* The WAL ends at the last shutdown checkpoint, or at
259+
* minRecoveryPoint if it was a standby. (If we supported rewinding a
260+
* server that was not shut down cleanly, we would need to replay
261+
* until we reach the first invalid record, like crash recovery does.)
262+
*/
263+
264+
/* read the checkpoint record on the target to see where it ends. */
265+
chkptendrec = readOneRecord(datadir_target,
266+
ControlFile_target.checkPoint,
267+
targetNentries - 1);
268+
269+
if (ControlFile_target.minRecoveryPoint > chkptendrec)
270+
{
271+
target_wal_endrec = ControlFile_target.minRecoveryPoint;
272+
}
273+
else
274+
{
275+
target_wal_endrec = chkptendrec;
276+
}
277+
251278
/*
252279
* Check for the possibility that the target is in fact a direct
253280
* ancestor of the source. In that case, there is no divergent history
254281
* in the target that needs rewinding.
255282
*/
256-
if (ControlFile_target.checkPoint >= divergerec)
283+
if (target_wal_endrec > divergerec)
257284
{
258285
rewind_needed = true;
259286
}
260287
else
261288
{
262-
XLogRecPtr chkptendrec;
263-
264-
/* Read the checkpoint record on the target to see where it ends. */
265-
chkptendrec = readOneRecord(datadir_target,
266-
ControlFile_target.checkPoint,
267-
targetNentries - 1);
268-
269-
/*
270-
* If the histories diverged exactly at the end of the shutdown
271-
* checkpoint record on the target, there are no WAL records in
272-
* the target that don't belong in the source's history, and no
273-
* rewind is needed.
274-
*/
275-
if (chkptendrec == divergerec)
276-
rewind_needed = false;
277-
else
278-
rewind_needed = true;
289+
/* the last common checkpoint record must be part of target WAL */
290+
Assert(target_wal_endrec == divergerec);
291+
292+
rewind_needed = false;
279293
}
280294
}
281295

@@ -304,13 +318,11 @@ main(int argc, char **argv)
304318
/*
305319
* Read the target WAL from last checkpoint before the point of fork, to
306320
* extract all the pages that were modified on the target cluster after
307-
* the fork. We can stop reading after reaching the final shutdown record.
308-
* XXX: If we supported rewinding a server that was not shut down cleanly,
309-
* we would need to replay until the end of WAL here.
321+
* the fork.
310322
*/
311323
pg_log(PG_PROGRESS, "reading WAL in target\n");
312324
extractPageMap(datadir_target, chkptrec, lastcommontliIndex,
313-
ControlFile_target.checkPoint);
325+
target_wal_endrec);
314326
filemap_finalize();
315327

316328
if (showprogress)
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
#
2+
# Test situation where a target data directory contains
3+
# WAL records beyond both the last checkpoint and the divergence
4+
# point:
5+
#
6+
# Target WAL (TLI 2):
7+
#
8+
# backup ... Checkpoint A ... INSERT 'rewind this'
9+
# (TLI 1 -> 2)
10+
#
11+
# ^ last common ^ minRecoveryPoint
12+
# checkpoint
13+
#
14+
# Source WAL (TLI 3):
15+
#
16+
# backup ... Checkpoint A ... Checkpoint B ... INSERT 'keep this'
17+
# (TLI 1 -> 2) (TLI 2 -> 3)
18+
#
19+
#
20+
# The last common checkpoint is Checkpoint A. But there is WAL on TLI 2
21+
# after the last common checkpoint that needs to be rewound. We used to
22+
# have a bug where minRecoveryPoint was ignored, and pg_rewind concluded
23+
# that the target doesn't need rewinding in this scenario, because the
24+
# last checkpoint on the target TLI was an ancestor of the source TLI.
25+
#
26+
#
27+
# This test does not make use of RewindTest as it requires three
28+
# nodes.
29+
30+
use strict;
31+
use warnings;
32+
use PostgresNode;
33+
use TestLib;
34+
use Test::More tests => 3;
35+
36+
use File::Copy;
37+
38+
my $tmp_folder = TestLib::tempdir;
39+
40+
my $node_1 = get_new_node('node_1');
41+
$node_1->init(allows_streaming => 1);
42+
$node_1->append_conf('postgresql.conf', qq(
43+
wal_keep_segments='5'
44+
));
45+
46+
$node_1->start;
47+
48+
# Create a couple of test tables
49+
$node_1->safe_psql('postgres', 'CREATE TABLE public.foo (t TEXT)');
50+
$node_1->safe_psql('postgres', 'CREATE TABLE public.bar (t TEXT)');
51+
$node_1->safe_psql('postgres', "INSERT INTO public.bar VALUES ('in both')");
52+
53+
54+
# Take backup
55+
my $backup_name = 'my_backup';
56+
$node_1->backup($backup_name);
57+
58+
# Create streaming standby from backup
59+
my $node_2 = get_new_node('node_2');
60+
$node_2->init_from_backup($node_1, $backup_name,
61+
has_streaming => 1);
62+
$node_2->start;
63+
64+
# Create streaming standby from backup
65+
my $node_3 = get_new_node('node_3');
66+
$node_3->init_from_backup($node_1, $backup_name,
67+
has_streaming => 1);
68+
$node_3->start;
69+
70+
# Stop node_1
71+
72+
$node_1->stop('fast');
73+
74+
# Promote node_3
75+
$node_3->promote;
76+
77+
# node_1 rejoins node_3
78+
79+
my $node_3_connstr = $node_3->connstr;
80+
81+
unlink($node_2->data_dir . '/recovery.conf');
82+
$node_1->append_conf('recovery.conf', qq(
83+
standby_mode=on
84+
primary_conninfo='$node_3_connstr'
85+
recovery_target_timeline='latest'
86+
));
87+
$node_1->start();
88+
89+
# node_2 follows node_3
90+
91+
unlink($node_2->data_dir . '/recovery.conf');
92+
$node_2->append_conf('recovery.conf', qq(
93+
standby_mode=on
94+
primary_conninfo='$node_3_connstr'
95+
recovery_target_timeline='latest'
96+
));
97+
$node_2->restart();
98+
99+
# Promote node_1
100+
101+
$node_1->promote;
102+
103+
# We now have a split-brain with two primaries. Insert a row on both to
104+
# demonstratively create a split brain. After the rewind, we should only
105+
# see the insert on 1, as the insert on node 3 is rewound away.
106+
$node_1->safe_psql('postgres', "INSERT INTO public.foo (t) VALUES ('keep this')");
107+
108+
# Insert more rows in node 1, to bump up the XID counter. Otherwise, if
109+
# rewind doesn't correctly rewind the changes made on the other node,
110+
# we might fail to notice if the inserts are invisible because the XIDs
111+
# are not marked as committed.
112+
$node_1->safe_psql('postgres', "INSERT INTO public.foo (t) VALUES ('and this')");
113+
$node_1->safe_psql('postgres', "INSERT INTO public.foo (t) VALUES ('and this too')");
114+
115+
# Also insert a row in 'bar' on node 3. It is unmodified in node 1, so it won't get
116+
# overwritten by replaying the WAL from node 1.
117+
$node_3->safe_psql('postgres', "INSERT INTO public.bar (t) VALUES ('rewind this')");
118+
119+
# Wait for node 2 to catch up
120+
$node_2->poll_query_until('postgres',
121+
q|SELECT COUNT(*) > 1 FROM public.bar|, 't');
122+
123+
# At this point node_2 will shut down without a shutdown checkpoint,
124+
# but with WAL entries beyond the preceding shutdown checkpoint.
125+
$node_2->stop('fast');
126+
$node_3->stop('fast');
127+
128+
my $node_2_pgdata = $node_2->data_dir;
129+
my $node_1_connstr = $node_1->connstr;
130+
131+
# Keep a temporary postgresql.conf or it would be overwritten during the rewind.
132+
copy(
133+
"$node_2_pgdata/postgresql.conf",
134+
"$tmp_folder/node_2-postgresql.conf.tmp");
135+
136+
command_ok(
137+
[
138+
'pg_rewind',
139+
"--source-server=$node_1_connstr",
140+
"--target-pgdata=$node_2_pgdata"
141+
],
142+
'pg_rewind detects rewind needed');
143+
144+
# Now move back postgresql.conf with old settings
145+
move(
146+
"$tmp_folder/node_2-postgresql.conf.tmp",
147+
"$node_2_pgdata/postgresql.conf");
148+
149+
$node_2->start;
150+
151+
# Check contents of the test tables after rewind. The rows inserted in node 3
152+
# before rewind should've been overwritten with the data from node 1.
153+
my $result;
154+
$result = $node_2->safe_psql('postgres', 'checkpoint');
155+
$result = $node_2->safe_psql('postgres', 'SELECT * FROM public.foo');
156+
is($result, qq(keep this
157+
and this
158+
and this too), 'table foo after rewind');
159+
160+
$result = $node_2->safe_psql('postgres', 'SELECT * FROM public.bar');
161+
is($result, qq(in both), 'table bar after rewind');

0 commit comments

Comments
 (0)