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