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