PostgreSQL Source Code  git master
parsexlog.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parsexlog.c
4  * Functions for reading Write-Ahead-Log
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *-------------------------------------------------------------------------
10  */
11 
12 #include "postgres_fe.h"
13 
14 #include <unistd.h>
15 
16 #include "access/rmgr.h"
17 #include "access/xact.h"
18 #include "access/xlog_internal.h"
19 #include "access/xlogreader.h"
20 #include "catalog/pg_control.h"
21 #include "catalog/storage_xlog.h"
23 #include "fe_utils/archive.h"
24 #include "filemap.h"
25 #include "pg_rewind.h"
26 
27 /*
28  * RmgrNames is an array of resource manager names, to make error messages
29  * a bit nicer.
30  */
31 #define PG_RMGR(symname,name,redo,desc,identify,startup,cleanup,mask) \
32  name,
33 
34 static const char *RmgrNames[RM_MAX_ID + 1] = {
35 #include "access/rmgrlist.h"
36 };
37 
38 static void extractPageInfo(XLogReaderState *record);
39 
40 static int xlogreadfd = -1;
42 static char xlogfpath[MAXPGPATH];
43 
44 typedef struct XLogPageReadPrivate
45 {
46  const char *restoreCommand;
47  int tliIndex;
49 
51  XLogRecPtr targetPagePtr,
52  int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
53 
54 /*
55  * Read WAL from the datadir/pg_wal, starting from 'startpoint' on timeline
56  * index 'tliIndex' in target timeline history, until 'endpoint'. Make note of
57  * the data blocks touched by the WAL records, and return them in a page map.
58  */
59 void
60 extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex,
61  XLogRecPtr endpoint, const char *restoreCommand)
62 {
63  XLogRecord *record;
65  char *errormsg;
66  XLogPageReadPrivate private;
67 
68  private.tliIndex = tliIndex;
69  private.restoreCommand = restoreCommand;
70  xlogreader = XLogReaderAllocate(WalSegSz, datadir,
71  XL_ROUTINE(.page_read = &SimpleXLogPageRead),
72  &private);
73  if (xlogreader == NULL)
74  pg_fatal("out of memory");
75 
76  XLogBeginRead(xlogreader, startpoint);
77  do
78  {
79  record = XLogReadRecord(xlogreader, &errormsg);
80 
81  if (record == NULL)
82  {
83  XLogRecPtr errptr = xlogreader->EndRecPtr;
84 
85  if (errormsg)
86  pg_fatal("could not read WAL record at %X/%X: %s",
87  (uint32) (errptr >> 32), (uint32) (errptr),
88  errormsg);
89  else
90  pg_fatal("could not read WAL record at %X/%X",
91  (uint32) (errptr >> 32), (uint32) (errptr));
92  }
93 
94  extractPageInfo(xlogreader);
95 
96  } while (xlogreader->ReadRecPtr != endpoint);
97 
98  XLogReaderFree(xlogreader);
99  if (xlogreadfd != -1)
100  {
101  close(xlogreadfd);
102  xlogreadfd = -1;
103  }
104 }
105 
106 /*
107  * Reads one WAL record. Returns the end position of the record, without
108  * doing anything with the record itself.
109  */
111 readOneRecord(const char *datadir, XLogRecPtr ptr, int tliIndex,
112  const char *restoreCommand)
113 {
114  XLogRecord *record;
116  char *errormsg;
117  XLogPageReadPrivate private;
118  XLogRecPtr endptr;
119 
120  private.tliIndex = tliIndex;
121  private.restoreCommand = restoreCommand;
122  xlogreader = XLogReaderAllocate(WalSegSz, datadir,
123  XL_ROUTINE(.page_read = &SimpleXLogPageRead),
124  &private);
125  if (xlogreader == NULL)
126  pg_fatal("out of memory");
127 
128  XLogBeginRead(xlogreader, ptr);
129  record = XLogReadRecord(xlogreader, &errormsg);
130  if (record == NULL)
131  {
132  if (errormsg)
133  pg_fatal("could not read WAL record at %X/%X: %s",
134  (uint32) (ptr >> 32), (uint32) (ptr), errormsg);
135  else
136  pg_fatal("could not read WAL record at %X/%X",
137  (uint32) (ptr >> 32), (uint32) (ptr));
138  }
139  endptr = xlogreader->EndRecPtr;
140 
141  XLogReaderFree(xlogreader);
142  if (xlogreadfd != -1)
143  {
144  close(xlogreadfd);
145  xlogreadfd = -1;
146  }
147 
148  return endptr;
149 }
150 
151 /*
152  * Find the previous checkpoint preceding given WAL location.
153  */
154 void
155 findLastCheckpoint(const char *datadir, XLogRecPtr forkptr, int tliIndex,
156  XLogRecPtr *lastchkptrec, TimeLineID *lastchkpttli,
157  XLogRecPtr *lastchkptredo, const char *restoreCommand)
158 {
159  /* Walk backwards, starting from the given record */
160  XLogRecord *record;
161  XLogRecPtr searchptr;
163  char *errormsg;
164  XLogPageReadPrivate private;
165 
166  /*
167  * The given fork pointer points to the end of the last common record,
168  * which is not necessarily the beginning of the next record, if the
169  * previous record happens to end at a page boundary. Skip over the page
170  * header in that case to find the next record.
171  */
172  if (forkptr % XLOG_BLCKSZ == 0)
173  {
174  if (XLogSegmentOffset(forkptr, WalSegSz) == 0)
175  forkptr += SizeOfXLogLongPHD;
176  else
177  forkptr += SizeOfXLogShortPHD;
178  }
179 
180  private.tliIndex = tliIndex;
181  private.restoreCommand = restoreCommand;
182  xlogreader = XLogReaderAllocate(WalSegSz, datadir,
183  XL_ROUTINE(.page_read = &SimpleXLogPageRead),
184  &private);
185  if (xlogreader == NULL)
186  pg_fatal("out of memory");
187 
188  searchptr = forkptr;
189  for (;;)
190  {
191  uint8 info;
192 
193  XLogBeginRead(xlogreader, searchptr);
194  record = XLogReadRecord(xlogreader, &errormsg);
195 
196  if (record == NULL)
197  {
198  if (errormsg)
199  pg_fatal("could not find previous WAL record at %X/%X: %s",
200  (uint32) (searchptr >> 32), (uint32) (searchptr),
201  errormsg);
202  else
203  pg_fatal("could not find previous WAL record at %X/%X",
204  (uint32) (searchptr >> 32), (uint32) (searchptr));
205  }
206 
207  /*
208  * Check if it is a checkpoint record. This checkpoint record needs to
209  * be the latest checkpoint before WAL forked and not the checkpoint
210  * where the primary has been stopped to be rewound.
211  */
212  info = XLogRecGetInfo(xlogreader) & ~XLR_INFO_MASK;
213  if (searchptr < forkptr &&
214  XLogRecGetRmid(xlogreader) == RM_XLOG_ID &&
215  (info == XLOG_CHECKPOINT_SHUTDOWN ||
216  info == XLOG_CHECKPOINT_ONLINE))
217  {
218  CheckPoint checkPoint;
219 
220  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
221  *lastchkptrec = searchptr;
222  *lastchkpttli = checkPoint.ThisTimeLineID;
223  *lastchkptredo = checkPoint.redo;
224  break;
225  }
226 
227  /* Walk backwards to previous record. */
228  searchptr = record->xl_prev;
229  }
230 
231  XLogReaderFree(xlogreader);
232  if (xlogreadfd != -1)
233  {
234  close(xlogreadfd);
235  xlogreadfd = -1;
236  }
237 }
238 
239 /* XLogReader callback function, to read a WAL page */
240 static int
242  int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
243 {
244  XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
245  uint32 targetPageOff;
246  XLogRecPtr targetSegEnd;
247  XLogSegNo targetSegNo;
248  int r;
249 
250  XLByteToSeg(targetPagePtr, targetSegNo, WalSegSz);
251  XLogSegNoOffsetToRecPtr(targetSegNo + 1, 0, WalSegSz, targetSegEnd);
252  targetPageOff = XLogSegmentOffset(targetPagePtr, WalSegSz);
253 
254  /*
255  * See if we need to switch to a new segment because the requested record
256  * is not in the currently open one.
257  */
258  if (xlogreadfd >= 0 &&
259  !XLByteInSeg(targetPagePtr, xlogreadsegno, WalSegSz))
260  {
261  close(xlogreadfd);
262  xlogreadfd = -1;
263  }
264 
265  XLByteToSeg(targetPagePtr, xlogreadsegno, WalSegSz);
266 
267  if (xlogreadfd < 0)
268  {
269  char xlogfname[MAXFNAMELEN];
270 
271  /*
272  * Since incomplete segments are copied into next timelines, switch to
273  * the timeline holding the required segment. Assuming this scan can
274  * be done both forward and backward, consider also switching timeline
275  * accordingly.
276  */
277  while (private->tliIndex < targetNentries - 1 &&
278  targetHistory[private->tliIndex].end < targetSegEnd)
279  private->tliIndex++;
280  while (private->tliIndex > 0 &&
281  targetHistory[private->tliIndex].begin >= targetSegEnd)
282  private->tliIndex--;
283 
284  XLogFileName(xlogfname, targetHistory[private->tliIndex].tli,
286 
287  snprintf(xlogfpath, MAXPGPATH, "%s/" XLOGDIR "/%s",
288  xlogreader->segcxt.ws_dir, xlogfname);
289 
290  xlogreadfd = open(xlogfpath, O_RDONLY | PG_BINARY, 0);
291 
292  if (xlogreadfd < 0)
293  {
294  /*
295  * If we have no restore_command to execute, then exit.
296  */
297  if (private->restoreCommand == NULL)
298  {
299  pg_log_error("could not open file \"%s\": %m", xlogfpath);
300  return -1;
301  }
302 
303  /*
304  * Since we have restore_command, then try to retrieve missing WAL
305  * file from the archive.
306  */
308  xlogfname,
309  WalSegSz,
310  private->restoreCommand);
311 
312  if (xlogreadfd < 0)
313  return -1;
314  else
315  pg_log_debug("using file \"%s\" restored from archive",
316  xlogfpath);
317  }
318  }
319 
320  /*
321  * At this point, we have the right segment open.
322  */
323  Assert(xlogreadfd != -1);
324 
325  /* Read the requested page */
326  if (lseek(xlogreadfd, (off_t) targetPageOff, SEEK_SET) < 0)
327  {
328  pg_log_error("could not seek in file \"%s\": %m", xlogfpath);
329  return -1;
330  }
331 
332 
333  r = read(xlogreadfd, readBuf, XLOG_BLCKSZ);
334  if (r != XLOG_BLCKSZ)
335  {
336  if (r < 0)
337  pg_log_error("could not read file \"%s\": %m", xlogfpath);
338  else
339  pg_log_error("could not read file \"%s\": read %d of %zu",
340  xlogfpath, r, (Size) XLOG_BLCKSZ);
341 
342  return -1;
343  }
344 
345  Assert(targetSegNo == xlogreadsegno);
346 
347  xlogreader->seg.ws_tli = targetHistory[private->tliIndex].tli;
348  return XLOG_BLCKSZ;
349 }
350 
351 /*
352  * Extract information on which blocks the current record modifies.
353  */
354 static void
356 {
357  int block_id;
358  RmgrId rmid = XLogRecGetRmid(record);
359  uint8 info = XLogRecGetInfo(record);
360  uint8 rminfo = info & ~XLR_INFO_MASK;
361 
362  /* Is this a special record type that I recognize? */
363 
364  if (rmid == RM_DBASE_ID && rminfo == XLOG_DBASE_CREATE)
365  {
366  /*
367  * New databases can be safely ignored. It won't be present in the
368  * source system, so it will be deleted. There's one corner-case,
369  * though: if a new, different, database is also created in the source
370  * system, we'll see that the files already exist and not copy them.
371  * That's OK, though; WAL replay of creating the new database, from
372  * the source systems's WAL, will re-copy the new database,
373  * overwriting the database created in the target system.
374  */
375  }
376  else if (rmid == RM_DBASE_ID && rminfo == XLOG_DBASE_DROP)
377  {
378  /*
379  * An existing database was dropped. We'll see that the files don't
380  * exist in the target data dir, and copy them in toto from the source
381  * system. No need to do anything special here.
382  */
383  }
384  else if (rmid == RM_SMGR_ID && rminfo == XLOG_SMGR_CREATE)
385  {
386  /*
387  * We can safely ignore these. The file will be removed from the
388  * target, if it doesn't exist in source system. If a file with same
389  * name is created in source system, too, there will be WAL records
390  * for all the blocks in it.
391  */
392  }
393  else if (rmid == RM_SMGR_ID && rminfo == XLOG_SMGR_TRUNCATE)
394  {
395  /*
396  * We can safely ignore these. When we compare the sizes later on,
397  * we'll notice that they differ, and copy the missing tail from
398  * source system.
399  */
400  }
401  else if (rmid == RM_XACT_ID &&
402  ((rminfo & XLOG_XACT_OPMASK) == XLOG_XACT_COMMIT ||
403  (rminfo & XLOG_XACT_OPMASK) == XLOG_XACT_COMMIT_PREPARED ||
404  (rminfo & XLOG_XACT_OPMASK) == XLOG_XACT_ABORT ||
405  (rminfo & XLOG_XACT_OPMASK) == XLOG_XACT_ABORT_PREPARED))
406  {
407  /*
408  * These records can include "dropped rels". We can safely ignore
409  * them, we will see that they are missing and copy them from the
410  * source.
411  */
412  }
413  else if (info & XLR_SPECIAL_REL_UPDATE)
414  {
415  /*
416  * This record type modifies a relation file in some special way, but
417  * we don't recognize the type. That's bad - we don't know how to
418  * track that change.
419  */
420  pg_fatal("WAL record modifies a relation, but record type is not recognized: "
421  "lsn: %X/%X, rmgr: %s, info: %02X",
422  (uint32) (record->ReadRecPtr >> 32), (uint32) (record->ReadRecPtr),
423  RmgrNames[rmid], info);
424  }
425 
426  for (block_id = 0; block_id <= record->max_block_id; block_id++)
427  {
428  RelFileNode rnode;
429  ForkNumber forknum;
430  BlockNumber blkno;
431 
432  if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
433  continue;
434 
435  /* We only care about the main fork; others are copied in toto */
436  if (forknum != MAIN_FORKNUM)
437  continue;
438 
439  process_target_wal_block_change(forknum, rnode, blkno);
440  }
441 }
void extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex, XLogRecPtr endpoint, const char *restoreCommand)
Definition: parsexlog.c:60
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
char ws_dir[MAXPGPATH]
Definition: xlogreader.h:54
#define XLOG_XACT_COMMIT
Definition: xact.h:148
uint32 TimeLineID
Definition: xlogdefs.h:52
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
TimeLineHistoryEntry * targetHistory
Definition: pg_rewind.c:71
#define pg_log_error(...)
Definition: logging.h:80
unsigned char uint8
Definition: c.h:427
bool RestoreArchivedFile(char *path, const char *xlogfname, const char *recovername, off_t expectedSize, bool cleanupEnabled)
Definition: xlogarchive.c:53
void findLastCheckpoint(const char *datadir, XLogRecPtr forkptr, int tliIndex, XLogRecPtr *lastchkptrec, TimeLineID *lastchkpttli, XLogRecPtr *lastchkptredo, const char *restoreCommand)
Definition: parsexlog.c:155
#define pg_fatal(...)
Definition: pg_rewind.h:37
static const char * RmgrNames[RM_MAX_ID+1]
Definition: parsexlog.c:34
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:241
uint32 BlockNumber
Definition: block.h:31
TimeLineID tli
Definition: timeline.h:27
void * private_data
Definition: xlogreader.h:168
#define PG_BINARY
Definition: c.h:1267
#define XLOG_SMGR_CREATE
Definition: storage_xlog.h:30
XLogRecPtr EndRecPtr
Definition: xlogreader.h:176
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
WALOpenSegment seg
Definition: xlogreader.h:215
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:268
#define XLogRecGetData(decoder)
Definition: xlogreader.h:310
#define XLOG_DBASE_DROP
#define pg_log_debug(...)
Definition: logging.h:92
#define MAXPGPATH
#define XLOG_XACT_ABORT_PREPARED
Definition: xact.h:152
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
uint64 XLogSegNo
Definition: xlogdefs.h:41
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:175
void process_target_wal_block_change(ForkNumber forknum, RelFileNode rnode, BlockNumber blkno)
Definition: filemap.c:292
char * datadir
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:240
unsigned int uint32
Definition: c.h:429
struct XLogPageReadPrivate XLogPageReadPrivate
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:75
static XLogReaderState * xlogreader
Definition: walsender.c:137
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:305
ForkNumber
Definition: relpath.h:40
#define XL_ROUTINE(...)
Definition: xlogreader.h:116
#define XLOG_SMGR_TRUNCATE
Definition: storage_xlog.h:31
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:139
#define MAXFNAMELEN
#define RM_MAX_ID
Definition: rmgr.h:33
bool XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1498
#define XLOGDIR
int targetNentries
Definition: pg_rewind.c:72
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
static int xlogreadfd
Definition: parsexlog.c:40
const char * restoreCommand
Definition: parsexlog.c:46
static XLogSegNo xlogreadsegno
Definition: parsexlog.c:41
static char xlogfpath[MAXPGPATH]
Definition: parsexlog.c:42
uint8 RmgrId
Definition: rmgr.h:11
static void extractPageInfo(XLogReaderState *record)
Definition: parsexlog.c:355
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
XLogRecPtr end
Definition: timeline.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:800
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLOG_XACT_ABORT
Definition: xact.h:150
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:52
size_t Size
Definition: c.h:528
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
XLogRecPtr readOneRecord(const char *datadir, XLogRecPtr ptr, int tliIndex, const char *restoreCommand)
Definition: parsexlog.c:111
#define XLOG_XACT_OPMASK
Definition: xact.h:158
#define XLOG_DBASE_CREATE
TimeLineID ws_tli
Definition: xlogreader.h:48
int WalSegSz
Definition: pg_standby.c:38
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
XLogRecPtr begin
Definition: timeline.h:28
WALSegmentContext segcxt
Definition: xlogreader.h:214
#define close(a)
Definition: win32.h:12
#define XLOG_XACT_COMMIT_PREPARED
Definition: xact.h:151
#define snprintf
Definition: port.h:215
#define read(a, b, c)
Definition: win32.h:13
XLogRecPtr redo
Definition: pg_control.h:37
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:306
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:69
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)