Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * xlogrecovery.c
4 : : * Functions for WAL recovery, standby mode
5 : : *
6 : : * This source file contains functions controlling WAL recovery.
7 : : * InitWalRecovery() initializes the system for crash or archive recovery,
8 : : * or standby mode, depending on configuration options and the state of
9 : : * the control file and possible backup label file. PerformWalRecovery()
10 : : * performs the actual WAL replay, calling the rmgr-specific redo routines.
11 : : * FinishWalRecovery() performs end-of-recovery checks and cleanup actions,
12 : : * and prepares information needed to initialize the WAL for writes. In
13 : : * addition to these three main functions, there are a bunch of functions
14 : : * for interrogating recovery state and controlling the recovery process.
15 : : *
16 : : *
17 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
18 : : * Portions Copyright (c) 1994, Regents of the University of California
19 : : *
20 : : * src/backend/access/transam/xlogrecovery.c
21 : : *
22 : : *-------------------------------------------------------------------------
23 : : */
24 : :
25 : : #include "postgres.h"
26 : :
27 : : #include <ctype.h>
28 : : #include <time.h>
29 : : #include <sys/stat.h>
30 : : #include <sys/time.h>
31 : : #include <unistd.h>
32 : :
33 : : #include "access/timeline.h"
34 : : #include "access/transam.h"
35 : : #include "access/xact.h"
36 : : #include "access/xlog_internal.h"
37 : : #include "access/xlogarchive.h"
38 : : #include "access/xlogprefetcher.h"
39 : : #include "access/xlogreader.h"
40 : : #include "access/xlogrecovery.h"
41 : : #include "access/xlogutils.h"
42 : : #include "access/xlogwait.h"
43 : : #include "backup/basebackup.h"
44 : : #include "catalog/pg_control.h"
45 : : #include "commands/tablespace.h"
46 : : #include "common/file_utils.h"
47 : : #include "common/pg_parse_lsn.h"
48 : : #include "miscadmin.h"
49 : : #include "nodes/miscnodes.h"
50 : : #include "pgstat.h"
51 : : #include "postmaster/bgwriter.h"
52 : : #include "postmaster/startup.h"
53 : : #include "replication/slot.h"
54 : : #include "replication/slotsync.h"
55 : : #include "replication/walreceiver.h"
56 : : #include "storage/fd.h"
57 : : #include "storage/ipc.h"
58 : : #include "storage/latch.h"
59 : : #include "storage/pmsignal.h"
60 : : #include "storage/procarray.h"
61 : : #include "storage/spin.h"
62 : : #include "storage/subsystems.h"
63 : : #include "utils/datetime.h"
64 : : #include "utils/fmgrprotos.h"
65 : : #include "utils/guc.h"
66 : : #include "utils/guc_hooks.h"
67 : : #include "utils/pgstat_internal.h"
68 : : #include "utils/pg_lsn.h"
69 : : #include "utils/ps_status.h"
70 : : #include "utils/pg_rusage.h"
71 : : #include "utils/wait_event.h"
72 : :
73 : : /* Unsupported old recovery command file names (relative to $PGDATA) */
74 : : #define RECOVERY_COMMAND_FILE "recovery.conf"
75 : : #define RECOVERY_COMMAND_DONE "recovery.done"
76 : :
77 : : /*
78 : : * GUC support
79 : : */
80 : : const struct config_enum_entry recovery_target_action_options[] = {
81 : : {"pause", RECOVERY_TARGET_ACTION_PAUSE, false},
82 : : {"promote", RECOVERY_TARGET_ACTION_PROMOTE, false},
83 : : {"shutdown", RECOVERY_TARGET_ACTION_SHUTDOWN, false},
84 : : {NULL, 0, false}
85 : : };
86 : :
87 : : /* options formerly taken from recovery.conf for archive recovery */
88 : : char *recoveryRestoreCommand = NULL;
89 : : char *recoveryEndCommand = NULL;
90 : : char *archiveCleanupCommand = NULL;
91 : : RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET;
92 : : bool recoveryTargetInclusive = true;
93 : : int recoveryTargetAction = RECOVERY_TARGET_ACTION_PAUSE;
94 : : TransactionId recoveryTargetXid;
95 : : char *recovery_target_time_string;
96 : : TimestampTz recoveryTargetTime;
97 : : char *recoveryTargetName;
98 : : XLogRecPtr recoveryTargetLSN;
99 : : int recovery_min_apply_delay = 0;
100 : :
101 : : /* options formerly taken from recovery.conf for XLOG streaming */
102 : : char *PrimaryConnInfo = NULL;
103 : : char *PrimarySlotName = NULL;
104 : : bool wal_receiver_create_temp_slot = false;
105 : :
106 : : /*
107 : : * recoveryTargetTimeLineGoal: what the user requested, if any
108 : : *
109 : : * recoveryTargetTLIRequested: numeric value of requested timeline, if constant
110 : : *
111 : : * recoveryTargetTLI: the currently understood target timeline; changes
112 : : *
113 : : * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and
114 : : * the timelines of its known parents, newest first (so recoveryTargetTLI is
115 : : * always the first list member). Only these TLIs are expected to be seen in
116 : : * the WAL segments we read, and indeed only these TLIs will be considered as
117 : : * candidate WAL files to open at all.
118 : : *
119 : : * curFileTLI: the TLI appearing in the name of the current input WAL file.
120 : : * (This is not necessarily the same as the timeline from which we are
121 : : * replaying WAL, which StartupXLOG calls replayTLI, because we could be
122 : : * scanning data that was copied from an ancestor timeline when the current
123 : : * file was created.) During a sequential scan we do not allow this value
124 : : * to decrease.
125 : : */
126 : : RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal = RECOVERY_TARGET_TIMELINE_LATEST;
127 : : TimeLineID recoveryTargetTLIRequested = 0;
128 : : TimeLineID recoveryTargetTLI = 0;
129 : : static List *expectedTLEs;
130 : : static TimeLineID curFileTLI;
131 : :
132 : : /*
133 : : * When ArchiveRecoveryRequested is set, archive recovery was requested,
134 : : * ie. signal files were present. When InArchiveRecovery is set, we are
135 : : * currently recovering using offline XLOG archives. These variables are only
136 : : * valid in the startup process.
137 : : *
138 : : * When ArchiveRecoveryRequested is true, but InArchiveRecovery is false, we're
139 : : * currently performing crash recovery using only XLOG files in pg_wal, but
140 : : * will switch to using offline XLOG archives as soon as we reach the end of
141 : : * WAL in pg_wal.
142 : : */
143 : : bool ArchiveRecoveryRequested = false;
144 : : bool InArchiveRecovery = false;
145 : :
146 : : /*
147 : : * When StandbyModeRequested is set, standby mode was requested, i.e.
148 : : * standby.signal file was present. When StandbyMode is set, we are currently
149 : : * in standby mode. These variables are only valid in the startup process.
150 : : * They work similarly to ArchiveRecoveryRequested and InArchiveRecovery.
151 : : */
152 : : static bool StandbyModeRequested = false;
153 : : bool StandbyMode = false;
154 : :
155 : : /* was a signal file present at startup? */
156 : : static bool standby_signal_file_found = false;
157 : : static bool recovery_signal_file_found = false;
158 : :
159 : : /*
160 : : * CheckPointLoc is the position of the checkpoint record that determines
161 : : * where to start the replay. It comes from the backup label file or the
162 : : * control file.
163 : : *
164 : : * RedoStartLSN is the checkpoint's REDO location, also from the backup label
165 : : * file or the control file. In standby mode, XLOG streaming usually starts
166 : : * from the position where an invalid record was found. But if we fail to
167 : : * read even the initial checkpoint record, we use the REDO location instead
168 : : * of the checkpoint location as the start position of XLOG streaming.
169 : : * Otherwise we would have to jump backwards to the REDO location after
170 : : * reading the checkpoint record, because the REDO record can precede the
171 : : * checkpoint record.
172 : : */
173 : : static XLogRecPtr CheckPointLoc = InvalidXLogRecPtr;
174 : : static TimeLineID CheckPointTLI = 0;
175 : : static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr;
176 : : static TimeLineID RedoStartTLI = 0;
177 : :
178 : : /*
179 : : * Local copy of SharedHotStandbyActive variable. False actually means "not
180 : : * known, need to check the shared state".
181 : : */
182 : : static bool LocalHotStandbyActive = false;
183 : :
184 : : /*
185 : : * Local copy of SharedPromoteIsTriggered variable. False actually means "not
186 : : * known, need to check the shared state".
187 : : */
188 : : static bool LocalPromoteIsTriggered = false;
189 : :
190 : : /* Has the recovery code requested a walreceiver wakeup? */
191 : : static bool doRequestWalReceiverReply;
192 : :
193 : : /* XLogReader object used to parse the WAL records */
194 : : static XLogReaderState *xlogreader = NULL;
195 : :
196 : : /* XLogPrefetcher object used to consume WAL records with read-ahead */
197 : : static XLogPrefetcher *xlogprefetcher = NULL;
198 : :
199 : : /* Parameters passed down from ReadRecord to the XLogPageRead callback. */
200 : : typedef struct XLogPageReadPrivate
201 : : {
202 : : int emode;
203 : : bool fetching_ckpt; /* are we fetching a checkpoint record? */
204 : : bool randAccess;
205 : : TimeLineID replayTLI;
206 : : } XLogPageReadPrivate;
207 : :
208 : : /* flag to tell XLogPageRead that we have started replaying */
209 : : static bool InRedo = false;
210 : :
211 : : /*
212 : : * Codes indicating where we got a WAL file from during recovery, or where
213 : : * to attempt to get one.
214 : : */
215 : : typedef enum
216 : : {
217 : : XLOG_FROM_ANY = 0, /* request to read WAL from any source */
218 : : XLOG_FROM_ARCHIVE, /* restored using restore_command */
219 : : XLOG_FROM_PG_WAL, /* existing file in pg_wal */
220 : : XLOG_FROM_STREAM, /* streamed from primary */
221 : : } XLogSource;
222 : :
223 : : /* human-readable names for XLogSources, for debugging output */
224 : : static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
225 : :
226 : : /*
227 : : * readFile is -1 or a kernel FD for the log file segment that's currently
228 : : * open for reading. readSegNo identifies the segment. readOff is the offset
229 : : * of the page just read, readLen indicates how much of it has been read into
230 : : * readBuf, and readSource indicates where we got the currently open file from.
231 : : *
232 : : * Note: we could use Reserve/ReleaseExternalFD to track consumption of this
233 : : * FD too (like for openLogFile in xlog.c); but it doesn't currently seem
234 : : * worthwhile, since the XLOG is not read by general-purpose sessions.
235 : : */
236 : : static int readFile = -1;
237 : : static XLogSegNo readSegNo = 0;
238 : : static uint32 readOff = 0;
239 : : static uint32 readLen = 0;
240 : : static XLogSource readSource = XLOG_FROM_ANY;
241 : :
242 : : /*
243 : : * Keeps track of which source we're currently reading from. This is
244 : : * different from readSource in that this is always set, even when we don't
245 : : * currently have a WAL file open. If lastSourceFailed is set, our last
246 : : * attempt to read from currentSource failed, and we should try another source
247 : : * next.
248 : : *
249 : : * pendingWalRcvRestart is set when a config change occurs that requires a
250 : : * walreceiver restart. This is only valid in XLOG_FROM_STREAM state.
251 : : */
252 : : static XLogSource currentSource = XLOG_FROM_ANY;
253 : : static bool lastSourceFailed = false;
254 : : static bool pendingWalRcvRestart = false;
255 : :
256 : : /*
257 : : * These variables track when we last obtained some WAL data to process,
258 : : * and where we got it from. (XLogReceiptSource is initially the same as
259 : : * readSource, but readSource gets reset to zero when we don't have data
260 : : * to process right now. It is also different from currentSource, which
261 : : * also changes when we try to read from a source and fail, while
262 : : * XLogReceiptSource tracks where we last successfully read some WAL.)
263 : : */
264 : : static TimestampTz XLogReceiptTime = 0;
265 : : static XLogSource XLogReceiptSource = XLOG_FROM_ANY;
266 : :
267 : : /* Local copy of WalRcv->flushedUpto */
268 : : static XLogRecPtr flushedUpto = InvalidXLogRecPtr;
269 : : static TimeLineID receiveTLI = 0;
270 : :
271 : : /*
272 : : * Copy of minRecoveryPoint and backupEndPoint from the control file.
273 : : *
274 : : * In order to reach consistency, we must replay the WAL up to
275 : : * minRecoveryPoint. If backupEndRequired is true, we must also reach
276 : : * backupEndPoint, or if it's invalid, an end-of-backup record corresponding
277 : : * to backupStartPoint.
278 : : *
279 : : * Note: In archive recovery, after consistency has been reached, the
280 : : * functions in xlog.c will start updating minRecoveryPoint in the control
281 : : * file. But this copy of minRecoveryPoint variable reflects the value at the
282 : : * beginning of recovery, and is *not* updated after consistency is reached.
283 : : */
284 : : static XLogRecPtr minRecoveryPoint;
285 : : static TimeLineID minRecoveryPointTLI;
286 : :
287 : : static XLogRecPtr backupStartPoint;
288 : : static XLogRecPtr backupEndPoint;
289 : : static bool backupEndRequired = false;
290 : :
291 : : /*
292 : : * Have we reached a consistent database state? In crash recovery, we have
293 : : * to replay all the WAL, so reachedConsistency is never set. During archive
294 : : * recovery, the database is consistent once minRecoveryPoint is reached.
295 : : *
296 : : * Consistent state means that the system is internally consistent, all
297 : : * the WAL has been replayed up to a certain point, and importantly, there
298 : : * is no trace of later actions on disk.
299 : : *
300 : : * This flag is used only by the startup process and postmaster. When
301 : : * minRecoveryPoint is reached, the startup process sets it to true and
302 : : * sends a PMSIGNAL_RECOVERY_CONSISTENT signal to the postmaster,
303 : : * which then sets it to true upon receiving the signal.
304 : : */
305 : : bool reachedConsistency = false;
306 : :
307 : : /* Buffers dedicated to consistency checks of size BLCKSZ */
308 : : static char *replay_image_masked = NULL;
309 : : static char *primary_image_masked = NULL;
310 : :
311 : : XLogRecoveryCtlData *XLogRecoveryCtl = NULL;
312 : :
313 : : static void XLogRecoveryShmemRequest(void *arg);
314 : : static void XLogRecoveryShmemInit(void *arg);
315 : :
316 : : const ShmemCallbacks XLogRecoveryShmemCallbacks = {
317 : : .request_fn = XLogRecoveryShmemRequest,
318 : : .init_fn = XLogRecoveryShmemInit,
319 : : };
320 : :
321 : : /*
322 : : * abortedRecPtr is the start pointer of a broken record at end of WAL when
323 : : * recovery completes; missingContrecPtr is the location of the first
324 : : * contrecord that went missing. See CreateOverwriteContrecordRecord for
325 : : * details.
326 : : */
327 : : static XLogRecPtr abortedRecPtr;
328 : : static XLogRecPtr missingContrecPtr;
329 : :
330 : : /*
331 : : * if recoveryStopsBefore/After returns true, it saves information of the stop
332 : : * point here
333 : : */
334 : : static TransactionId recoveryStopXid;
335 : : static TimestampTz recoveryStopTime;
336 : : static XLogRecPtr recoveryStopLSN;
337 : : static char recoveryStopName[MAXFNAMELEN];
338 : : static bool recoveryStopAfter;
339 : :
340 : : /* prototypes for local functions */
341 : : static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI);
342 : :
343 : : static void EnableStandbyMode(void);
344 : : static void readRecoverySignalFile(void);
345 : : static void validateRecoveryParameters(void);
346 : : static bool read_backup_label(XLogRecPtr *checkPointLoc,
347 : : TimeLineID *backupLabelTLI,
348 : : bool *backupEndRequired, bool *backupFromStandby);
349 : : static bool read_tablespace_map(List **tablespaces);
350 : :
351 : : static void xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI);
352 : : static void CheckRecoveryConsistency(void);
353 : : static void rm_redo_error_callback(void *arg);
354 : : #ifdef WAL_DEBUG
355 : : static void xlog_outrec(StringInfo buf, XLogReaderState *record);
356 : : #endif
357 : : static void xlog_block_info(StringInfo buf, XLogReaderState *record);
358 : : static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,
359 : : TimeLineID prevTLI, TimeLineID replayTLI);
360 : : static bool getRecordTimestamp(XLogReaderState *record, TimestampTz *recordXtime);
361 : : static void verifyBackupPageConsistency(XLogReaderState *record);
362 : :
363 : : static bool recoveryStopsBefore(XLogReaderState *record);
364 : : static bool recoveryStopsAfter(XLogReaderState *record);
365 : : static char *getRecoveryStopReason(void);
366 : : static void recoveryPausesHere(bool endOfRecovery);
367 : : static bool recoveryApplyDelay(XLogReaderState *record);
368 : : static void ConfirmRecoveryPaused(void);
369 : :
370 : : static XLogRecord *ReadRecord(XLogPrefetcher *xlogprefetcher,
371 : : int emode, bool fetching_ckpt,
372 : : TimeLineID replayTLI);
373 : :
374 : : static int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
375 : : int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
376 : : static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
377 : : bool randAccess,
378 : : bool fetching_ckpt,
379 : : XLogRecPtr tliRecPtr,
380 : : TimeLineID replayTLI,
381 : : XLogRecPtr replayLSN,
382 : : bool nonblocking);
383 : : static int emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
384 : : static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher,
385 : : XLogRecPtr RecPtr, TimeLineID replayTLI);
386 : : static bool rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN);
387 : : static int XLogFileRead(XLogSegNo segno, TimeLineID tli,
388 : : XLogSource source, bool notfoundOk);
389 : : static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
390 : :
391 : : static bool CheckForStandbyTrigger(void);
392 : : static void SetPromoteIsTriggered(void);
393 : :
394 : : static void SetCurrentChunkStartTime(TimestampTz xtime);
395 : : static void SetLatestXTime(TimestampTz xtime);
396 : : static RecoveryTargetType DetermineRecoveryTargetType(void);
397 : :
398 : : /*
399 : : * Register shared memory for WAL recovery
400 : : */
401 : : static void
402 : 1362 : XLogRecoveryShmemRequest(void *arg)
403 : : {
404 : 1362 : ShmemRequestStruct(.name = "XLOG Recovery Ctl",
405 : : .size = sizeof(XLogRecoveryCtlData),
406 : : .ptr = (void **) &XLogRecoveryCtl,
407 : : );
408 : 1362 : }
409 : :
410 : : static void
411 : 1358 : XLogRecoveryShmemInit(void *arg)
412 : : {
413 : 1358 : memset(XLogRecoveryCtl, 0, sizeof(XLogRecoveryCtlData));
414 : :
415 : 1358 : SpinLockInit(&XLogRecoveryCtl->info_lck);
416 : 1358 : InitSharedLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
417 : 1358 : ConditionVariableInit(&XLogRecoveryCtl->recoveryNotPausedCV);
418 : 1358 : }
419 : :
420 : : /*
421 : : * A thin wrapper to enable StandbyMode and do other preparatory work as
422 : : * needed.
423 : : */
424 : : static void
425 : 136 : EnableStandbyMode(void)
426 : : {
427 : 136 : StandbyMode = true;
428 : :
429 : : /*
430 : : * To avoid server log bloat, we don't report recovery progress in a
431 : : * standby as it will always be in recovery unless promoted. We disable
432 : : * startup progress timeout in standby mode to avoid calling
433 : : * startup_progress_timeout_handler() unnecessarily.
434 : : */
435 : 136 : disable_startup_progress_timeout();
436 : 136 : }
437 : :
438 : : /*
439 : : * Prepare the system for WAL recovery, if needed.
440 : : *
441 : : * This is called by StartupXLOG() which coordinates the server startup
442 : : * sequence. This function analyzes the control file and the backup label
443 : : * file, if any, and figures out whether we need to perform crash recovery or
444 : : * archive recovery, and how far we need to replay the WAL to reach a
445 : : * consistent state.
446 : : *
447 : : * This doesn't yet change the on-disk state, except for creating the symlinks
448 : : * from table space map file if any, and for fetching WAL files needed to find
449 : : * the checkpoint record. On entry, the caller has already read the control
450 : : * file into memory, and passes it as argument. This function updates it to
451 : : * reflect the recovery state, and the caller is expected to write it back to
452 : : * disk after initializing other subsystems, but before calling
453 : : * PerformWalRecovery().
454 : : *
455 : : * This initializes some global variables like ArchiveRecoveryRequested, and
456 : : * StandbyModeRequested and InRecovery.
457 : : */
458 : : void
459 : 1184 : InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
460 : : bool *haveBackupLabel_ptr, bool *haveTblspcMap_ptr)
461 : : {
462 : : XLogPageReadPrivate *private;
463 : : struct stat st;
464 : : bool wasShutdown;
465 : : XLogRecord *record;
466 : : DBState dbstate_at_startup;
467 : 1184 : bool haveTblspcMap = false;
468 : 1184 : bool haveBackupLabel = false;
469 : : CheckPoint checkPoint;
470 : 1184 : bool backupFromStandby = false;
471 : :
472 : 1184 : dbstate_at_startup = ControlFile->state;
473 : :
474 : : /*
475 : : * A startup process always starts with an inconsistent database. Set the
476 : : * flag accordingly, even if it was inherited from a postmaster that had
477 : : * already marked the database as consistent. This keeps the invariant
478 : : * local to the startup process without requiring every fork path to clear
479 : : * the flag.
480 : : */
481 : 1184 : reachedConsistency = false;
482 : :
483 : : /*
484 : : * Initialize on the assumption we want to recover to the latest timeline
485 : : * that's active according to pg_control.
486 : : */
487 : 1184 : if (ControlFile->minRecoveryPointTLI >
488 [ + + ]: 1184 : ControlFile->checkPointCopy.ThisTimeLineID)
489 : 2 : recoveryTargetTLI = ControlFile->minRecoveryPointTLI;
490 : : else
491 : 1182 : recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
492 : :
493 : : /*
494 : : * Check for signal files, and if so set up state for offline recovery
495 : : */
496 : 1184 : readRecoverySignalFile();
497 : 1184 : validateRecoveryParameters();
498 : :
499 : : /*
500 : : * Take ownership of the wakeup latch if we're going to sleep during
501 : : * recovery, if required.
502 : : */
503 [ + + ]: 1181 : if (ArchiveRecoveryRequested)
504 : 142 : OwnLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
505 : :
506 : : /*
507 : : * Set the WAL reading processor now, as it will be needed when reading
508 : : * the checkpoint record required (backup_label or not).
509 : : */
510 : 1181 : private = palloc0_object(XLogPageReadPrivate);
511 : 1181 : xlogreader =
512 : 1181 : XLogReaderAllocate(wal_segment_size, NULL,
513 : 1181 : XL_ROUTINE(.page_read = &XLogPageRead,
514 : : .segment_open = NULL,
515 : : .segment_close = wal_segment_close),
516 : : private);
517 [ - + ]: 1181 : if (!xlogreader)
518 [ # # ]: 0 : ereport(ERROR,
519 : : (errcode(ERRCODE_OUT_OF_MEMORY),
520 : : errmsg("out of memory"),
521 : : errdetail("Failed while allocating a WAL reading processor.")));
522 : 1181 : xlogreader->system_identifier = ControlFile->system_identifier;
523 : :
524 : : /*
525 : : * Set the WAL decode buffer size. This limits how far ahead we can read
526 : : * in the WAL.
527 : : */
528 : 1181 : XLogReaderSetDecodeBuffer(xlogreader, NULL, wal_decode_buffer_size);
529 : :
530 : : /* Create a WAL prefetcher. */
531 : 1181 : xlogprefetcher = XLogPrefetcherAllocate(xlogreader);
532 : :
533 : : /*
534 : : * Allocate two page buffers dedicated to WAL consistency checks. We do
535 : : * it this way, rather than just making static arrays, for two reasons:
536 : : * (1) no need to waste the storage in most instantiations of the backend;
537 : : * (2) a static char array isn't guaranteed to have any particular
538 : : * alignment, whereas palloc() will provide MAXALIGN'd storage.
539 : : */
540 : 1181 : replay_image_masked = (char *) palloc(BLCKSZ);
541 : 1181 : primary_image_masked = (char *) palloc(BLCKSZ);
542 : :
543 : : /*
544 : : * Read the backup_label file. We want to run this part of the recovery
545 : : * process after checking for signal files and after performing validation
546 : : * of the recovery parameters.
547 : : */
548 [ + + ]: 1181 : if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &backupEndRequired,
549 : : &backupFromStandby))
550 : : {
551 : 105 : List *tablespaces = NIL;
552 : :
553 : : /*
554 : : * Archive recovery was requested, and thanks to the backup label
555 : : * file, we know how far we need to replay to reach consistency. Enter
556 : : * archive recovery directly.
557 : : */
558 : 105 : InArchiveRecovery = true;
559 [ + + ]: 105 : if (StandbyModeRequested)
560 : 87 : EnableStandbyMode();
561 : :
562 : : /*
563 : : * Omitting backup_label when creating a new replica, PITR node etc.
564 : : * unfortunately is a common cause of corruption. Logging that
565 : : * backup_label was used makes it a bit easier to exclude that as the
566 : : * cause of observed corruption.
567 : : *
568 : : * Do so before we try to read the checkpoint record (which can fail),
569 : : * as otherwise it can be hard to understand why a checkpoint other
570 : : * than ControlFile->checkPoint is used.
571 : : */
572 [ + - ]: 105 : ereport(LOG,
573 : : errmsg("starting backup recovery with redo LSN %X/%08X, checkpoint LSN %X/%08X, on timeline ID %u",
574 : : LSN_FORMAT_ARGS(RedoStartLSN),
575 : : LSN_FORMAT_ARGS(CheckPointLoc),
576 : : CheckPointTLI));
577 : :
578 : : /*
579 : : * When a backup_label file is present, we want to roll forward from
580 : : * the checkpoint it identifies, rather than using pg_control.
581 : : */
582 : 105 : record = ReadCheckpointRecord(xlogprefetcher, CheckPointLoc,
583 : : CheckPointTLI);
584 [ + + ]: 105 : if (record != NULL)
585 : : {
586 : 104 : memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
587 : 104 : wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
588 [ + + ]: 104 : ereport(DEBUG1,
589 : : errmsg_internal("checkpoint record is at %X/%08X",
590 : : LSN_FORMAT_ARGS(CheckPointLoc)));
591 : 104 : InRecovery = true; /* force recovery even if SHUTDOWNED */
592 : :
593 : : /*
594 : : * Make sure that REDO location exists. This may not be the case
595 : : * if there was a crash during an online backup, which left a
596 : : * backup_label around that references a WAL segment that's
597 : : * already been archived.
598 : : */
599 [ + + ]: 104 : if (checkPoint.redo < CheckPointLoc)
600 : : {
601 : 102 : XLogPrefetcherBeginRead(xlogprefetcher, checkPoint.redo);
602 [ + + ]: 102 : if (!ReadRecord(xlogprefetcher, LOG, false,
603 : : checkPoint.ThisTimeLineID))
604 [ + - ]: 1 : ereport(FATAL,
605 : : errmsg("could not find redo location %X/%08X referenced by checkpoint record at %X/%08X",
606 : : LSN_FORMAT_ARGS(checkPoint.redo), LSN_FORMAT_ARGS(CheckPointLoc)),
607 : : errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
608 : : "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
609 : : "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
610 : : DataDir, DataDir, DataDir, DataDir));
611 : : }
612 : : }
613 : : else
614 : : {
615 [ + - ]: 1 : ereport(FATAL,
616 : : errmsg("could not locate required checkpoint record at %X/%08X",
617 : : LSN_FORMAT_ARGS(CheckPointLoc)),
618 : : errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
619 : : "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
620 : : "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
621 : : DataDir, DataDir, DataDir, DataDir));
622 : : wasShutdown = false; /* keep compiler quiet */
623 : : }
624 : :
625 : : /* Read the tablespace_map file if present and create symlinks. */
626 [ + + ]: 103 : if (read_tablespace_map(&tablespaces))
627 : : {
628 : : ListCell *lc;
629 : :
630 [ + - + + : 4 : foreach(lc, tablespaces)
+ + ]
631 : : {
632 : 2 : tablespaceinfo *ti = lfirst(lc);
633 : : char *linkloc;
634 : :
635 : 2 : linkloc = psprintf("%s/%u", PG_TBLSPC_DIR, ti->oid);
636 : :
637 : : /*
638 : : * Remove the existing symlink if any and Create the symlink
639 : : * under PGDATA.
640 : : */
641 : 2 : remove_tablespace_symlink(linkloc);
642 : :
643 [ - + ]: 2 : if (symlink(ti->path, linkloc) < 0)
644 [ # # ]: 0 : ereport(ERROR,
645 : : (errcode_for_file_access(),
646 : : errmsg("could not create symbolic link \"%s\": %m",
647 : : linkloc)));
648 : :
649 : 2 : pfree(ti->path);
650 : 2 : pfree(ti);
651 : : }
652 : :
653 : : /* tell the caller to delete it later */
654 : 2 : haveTblspcMap = true;
655 : : }
656 : :
657 : : /* tell the caller to delete it later */
658 : 103 : haveBackupLabel = true;
659 : : }
660 : : else
661 : : {
662 : : /* No backup_label file has been found if we are here. */
663 : :
664 : : /*
665 : : * If tablespace_map file is present without backup_label file, there
666 : : * is no use of such file. There is no harm in retaining it, but it
667 : : * is better to get rid of the map file so that we don't have any
668 : : * redundant file in data directory and it will avoid any sort of
669 : : * confusion. It seems prudent though to just rename the file out of
670 : : * the way rather than delete it completely, also we ignore any error
671 : : * that occurs in rename operation as even if map file is present
672 : : * without backup_label file, it is harmless.
673 : : */
674 [ + + ]: 1076 : if (stat(TABLESPACE_MAP, &st) == 0)
675 : : {
676 : 1 : unlink(TABLESPACE_MAP_OLD);
677 [ + - ]: 1 : if (durable_rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD, DEBUG1) == 0)
678 [ + - ]: 1 : ereport(LOG,
679 : : (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
680 : : TABLESPACE_MAP, BACKUP_LABEL_FILE),
681 : : errdetail("File \"%s\" was renamed to \"%s\".",
682 : : TABLESPACE_MAP, TABLESPACE_MAP_OLD)));
683 : : else
684 [ # # ]: 0 : ereport(LOG,
685 : : (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
686 : : TABLESPACE_MAP, BACKUP_LABEL_FILE),
687 : : errdetail("Could not rename file \"%s\" to \"%s\": %m.",
688 : : TABLESPACE_MAP, TABLESPACE_MAP_OLD)));
689 : : }
690 : :
691 : : /*
692 : : * It's possible that archive recovery was requested, but we don't
693 : : * know how far we need to replay the WAL before we reach consistency.
694 : : * This can happen for example if a base backup is taken from a
695 : : * running server using an atomic filesystem snapshot, without calling
696 : : * pg_backup_start/stop. Or if you just kill a running primary server
697 : : * and put it into archive recovery by creating a recovery signal
698 : : * file.
699 : : *
700 : : * Our strategy in that case is to perform crash recovery first,
701 : : * replaying all the WAL present in pg_wal, and only enter archive
702 : : * recovery after that.
703 : : *
704 : : * But usually we already know how far we need to replay the WAL (up
705 : : * to minRecoveryPoint, up to backupEndPoint, or until we see an
706 : : * end-of-backup record), and we can enter archive recovery directly.
707 : : */
708 [ + + ]: 1076 : if (ArchiveRecoveryRequested &&
709 [ + + ]: 49 : (XLogRecPtrIsValid(ControlFile->minRecoveryPoint) ||
710 [ + - ]: 10 : ControlFile->backupEndRequired ||
711 [ + - ]: 10 : XLogRecPtrIsValid(ControlFile->backupEndPoint) ||
712 [ + + ]: 10 : ControlFile->state == DB_SHUTDOWNED))
713 : : {
714 : 48 : InArchiveRecovery = true;
715 [ + - ]: 48 : if (StandbyModeRequested)
716 : 48 : EnableStandbyMode();
717 : : }
718 : :
719 : : /*
720 : : * For the same reason as when starting up with backup_label present,
721 : : * emit a log message when we continue initializing from a base
722 : : * backup.
723 : : */
724 [ - + ]: 1076 : if (XLogRecPtrIsValid(ControlFile->backupStartPoint))
725 [ # # ]: 0 : ereport(LOG,
726 : : errmsg("restarting backup recovery with redo LSN %X/%08X",
727 : : LSN_FORMAT_ARGS(ControlFile->backupStartPoint)));
728 : :
729 : : /* Get the last valid checkpoint record. */
730 : 1076 : CheckPointLoc = ControlFile->checkPoint;
731 : 1076 : CheckPointTLI = ControlFile->checkPointCopy.ThisTimeLineID;
732 : 1076 : RedoStartLSN = ControlFile->checkPointCopy.redo;
733 : 1076 : RedoStartTLI = ControlFile->checkPointCopy.ThisTimeLineID;
734 : 1076 : record = ReadCheckpointRecord(xlogprefetcher, CheckPointLoc,
735 : : CheckPointTLI);
736 [ + + ]: 1076 : if (record != NULL)
737 : : {
738 [ + + ]: 1075 : ereport(DEBUG1,
739 : : errmsg_internal("checkpoint record is at %X/%08X",
740 : : LSN_FORMAT_ARGS(CheckPointLoc)));
741 : : }
742 : : else
743 : : {
744 : : /*
745 : : * We used to attempt to go back to a secondary checkpoint record
746 : : * here, but only when not in standby mode. We now just fail if we
747 : : * can't read the last checkpoint because this allows us to
748 : : * simplify processing around checkpoints.
749 : : */
750 [ + - ]: 1 : ereport(FATAL,
751 : : errmsg("could not locate a valid checkpoint record at %X/%08X",
752 : : LSN_FORMAT_ARGS(CheckPointLoc)));
753 : : }
754 : 1075 : memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
755 : 1075 : wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
756 : :
757 : : /* Make sure that REDO location exists. */
758 [ + + ]: 1075 : if (checkPoint.redo < CheckPointLoc)
759 : : {
760 : 48 : XLogPrefetcherBeginRead(xlogprefetcher, checkPoint.redo);
761 [ + + ]: 48 : if (!ReadRecord(xlogprefetcher, LOG, false, checkPoint.ThisTimeLineID))
762 [ + - ]: 1 : ereport(FATAL,
763 : : errmsg("could not find redo location %X/%08X referenced by checkpoint record at %X/%08X",
764 : : LSN_FORMAT_ARGS(checkPoint.redo), LSN_FORMAT_ARGS(CheckPointLoc)));
765 : : }
766 : : }
767 : :
768 [ + + ]: 1177 : if (ArchiveRecoveryRequested)
769 : : {
770 [ + + ]: 142 : if (StandbyModeRequested)
771 [ + - ]: 136 : ereport(LOG,
772 : : (errmsg("entering standby mode")));
773 [ - + ]: 6 : else if (recoveryTarget == RECOVERY_TARGET_XID)
774 [ # # ]: 0 : ereport(LOG,
775 : : (errmsg("starting point-in-time recovery to XID %u",
776 : : recoveryTargetXid)));
777 [ - + ]: 6 : else if (recoveryTarget == RECOVERY_TARGET_TIME)
778 [ # # ]: 0 : ereport(LOG,
779 : : (errmsg("starting point-in-time recovery to %s",
780 : : timestamptz_to_str(recoveryTargetTime))));
781 [ + + ]: 6 : else if (recoveryTarget == RECOVERY_TARGET_NAME)
782 [ + - ]: 3 : ereport(LOG,
783 : : (errmsg("starting point-in-time recovery to \"%s\"",
784 : : recoveryTargetName)));
785 [ + + ]: 3 : else if (recoveryTarget == RECOVERY_TARGET_LSN)
786 [ + - ]: 1 : ereport(LOG,
787 : : errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%08X\"",
788 : : LSN_FORMAT_ARGS(recoveryTargetLSN)));
789 [ - + ]: 2 : else if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE)
790 [ # # ]: 0 : ereport(LOG,
791 : : (errmsg("starting point-in-time recovery to earliest consistent point")));
792 : : else
793 [ + - ]: 2 : ereport(LOG,
794 : : (errmsg("starting archive recovery")));
795 : : }
796 : :
797 : : /*
798 : : * If the location of the checkpoint record is not on the expected
799 : : * timeline in the history of the requested timeline, we cannot proceed:
800 : : * the backup is not part of the history of the requested timeline.
801 : : */
802 : : Assert(expectedTLEs); /* was initialized by reading checkpoint
803 : : * record */
804 [ - + ]: 1177 : if (tliOfPointInHistory(CheckPointLoc, expectedTLEs) !=
805 : : CheckPointTLI)
806 : : {
807 : : XLogRecPtr switchpoint;
808 : :
809 : : /*
810 : : * tliSwitchPoint will throw an error if the checkpoint's timeline is
811 : : * not in expectedTLEs at all.
812 : : */
813 : 0 : switchpoint = tliSwitchPoint(CheckPointTLI, expectedTLEs, NULL);
814 [ # # # # ]: 0 : ereport(FATAL,
815 : : (errmsg("requested timeline %u is not a child of this server's history",
816 : : recoveryTargetTLI),
817 : : /* translator: %s is a backup_label file or a pg_control file */
818 : : errdetail("Latest checkpoint in file \"%s\" is at %X/%08X on timeline %u, but in the history of the requested timeline, the server forked off from that timeline at %X/%08X.",
819 : : haveBackupLabel ? "backup_label" : "pg_control",
820 : : LSN_FORMAT_ARGS(CheckPointLoc),
821 : : CheckPointTLI,
822 : : LSN_FORMAT_ARGS(switchpoint))));
823 : : }
824 : :
825 : : /*
826 : : * The min recovery point should be part of the requested timeline's
827 : : * history, too.
828 : : */
829 [ + + ]: 1177 : if (XLogRecPtrIsValid(ControlFile->minRecoveryPoint) &&
830 : 51 : tliOfPointInHistory(ControlFile->minRecoveryPoint - 1, expectedTLEs) !=
831 [ - + ]: 51 : ControlFile->minRecoveryPointTLI)
832 [ # # ]: 0 : ereport(FATAL,
833 : : errmsg("requested timeline %u does not contain minimum recovery point %X/%08X on timeline %u",
834 : : recoveryTargetTLI,
835 : : LSN_FORMAT_ARGS(ControlFile->minRecoveryPoint),
836 : : ControlFile->minRecoveryPointTLI));
837 : :
838 [ + + + + ]: 1177 : ereport(DEBUG1,
839 : : errmsg_internal("redo record is at %X/%08X; shutdown %s",
840 : : LSN_FORMAT_ARGS(checkPoint.redo),
841 : : wasShutdown ? "true" : "false"));
842 [ + + ]: 1177 : ereport(DEBUG1,
843 : : (errmsg_internal("next transaction ID: " UINT64_FORMAT "; next OID: %" PRIu64,
844 : : U64FromFullTransactionId(checkPoint.nextXid),
845 : : checkPoint.nextOid)));
846 [ + + ]: 1177 : ereport(DEBUG1,
847 : : (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %" PRIu64,
848 : : checkPoint.nextMulti, checkPoint.nextMultiOffset)));
849 [ + + ]: 1177 : ereport(DEBUG1,
850 : : (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
851 : : checkPoint.oldestXid, checkPoint.oldestXidDB)));
852 [ + + ]: 1177 : ereport(DEBUG1,
853 : : (errmsg_internal("oldest MultiXactId: %u, in database %u",
854 : : checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
855 [ + + ]: 1177 : ereport(DEBUG1,
856 : : (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
857 : : checkPoint.oldestCommitTsXid,
858 : : checkPoint.newestCommitTsXid)));
859 [ - + ]: 1177 : if (!TransactionIdIsNormal(XidFromFullTransactionId(checkPoint.nextXid)))
860 [ # # ]: 0 : ereport(PANIC,
861 : : (errmsg("invalid next transaction ID")));
862 : :
863 : : /* sanity check */
864 [ - + ]: 1177 : if (checkPoint.redo > CheckPointLoc)
865 [ # # ]: 0 : ereport(PANIC,
866 : : (errmsg("invalid redo in checkpoint record")));
867 : :
868 : : /*
869 : : * Check whether we need to force recovery from WAL. If it appears to
870 : : * have been a clean shutdown and we did not have a recovery signal file,
871 : : * then assume no recovery needed.
872 : : */
873 [ + + ]: 1177 : if (checkPoint.redo < CheckPointLoc)
874 : : {
875 [ - + ]: 148 : if (wasShutdown)
876 [ # # ]: 0 : ereport(PANIC,
877 : : (errmsg("invalid redo record in shutdown checkpoint")));
878 : 148 : InRecovery = true;
879 : : }
880 [ + + ]: 1029 : else if (ControlFile->state != DB_SHUTDOWNED)
881 : 103 : InRecovery = true;
882 [ + + ]: 926 : else if (ArchiveRecoveryRequested)
883 : : {
884 : : /* force recovery due to presence of recovery signal file */
885 : 9 : InRecovery = true;
886 : : }
887 : :
888 : : /*
889 : : * If recovery is needed, update our in-memory copy of pg_control to show
890 : : * that we are recovering and to show the selected checkpoint as the place
891 : : * we are starting from. We also mark pg_control with any minimum recovery
892 : : * stop point obtained from a backup history file.
893 : : *
894 : : * We don't write the changes to disk yet, though. Only do that after
895 : : * initializing various subsystems.
896 : : */
897 [ + + ]: 1177 : if (InRecovery)
898 : : {
899 [ + + ]: 260 : if (InArchiveRecovery)
900 : : {
901 : 151 : ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
902 : : }
903 : : else
904 : : {
905 [ + - ]: 109 : ereport(LOG,
906 : : (errmsg("database system was not properly shut down; "
907 : : "automatic recovery in progress")));
908 [ + + ]: 109 : if (recoveryTargetTLI > ControlFile->checkPointCopy.ThisTimeLineID)
909 [ + - ]: 2 : ereport(LOG,
910 : : (errmsg("crash recovery starts in timeline %u "
911 : : "and has target timeline %u",
912 : : ControlFile->checkPointCopy.ThisTimeLineID,
913 : : recoveryTargetTLI)));
914 : 109 : ControlFile->state = DB_IN_CRASH_RECOVERY;
915 : : }
916 : 260 : ControlFile->checkPoint = CheckPointLoc;
917 : 260 : ControlFile->checkPointCopy = checkPoint;
918 [ + + ]: 260 : if (InArchiveRecovery)
919 : : {
920 : : /* initialize minRecoveryPoint if not set yet */
921 [ + + ]: 151 : if (ControlFile->minRecoveryPoint < checkPoint.redo)
922 : : {
923 : 102 : ControlFile->minRecoveryPoint = checkPoint.redo;
924 : 102 : ControlFile->minRecoveryPointTLI = checkPoint.ThisTimeLineID;
925 : : }
926 : : }
927 : :
928 : : /*
929 : : * Set backupStartPoint if we're starting recovery from a base backup.
930 : : *
931 : : * Also set backupEndPoint and use minRecoveryPoint as the backup end
932 : : * location if we're starting recovery from a base backup which was
933 : : * taken from a standby. In this case, the database system status in
934 : : * pg_control must indicate that the database was already in recovery.
935 : : * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
936 : : * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
937 : : * before reaching this point; e.g. because restore_command or
938 : : * primary_conninfo were faulty.
939 : : *
940 : : * Any other state indicates that the backup somehow became corrupted
941 : : * and we can't sensibly continue with recovery.
942 : : */
943 [ + + ]: 260 : if (haveBackupLabel)
944 : : {
945 : 103 : ControlFile->backupStartPoint = checkPoint.redo;
946 : 103 : ControlFile->backupEndRequired = backupEndRequired;
947 : :
948 [ + + ]: 103 : if (backupFromStandby)
949 : : {
950 [ - + - - ]: 10 : if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
951 : : dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
952 [ # # ]: 0 : ereport(FATAL,
953 : : (errmsg("backup_label contains data inconsistent with control file"),
954 : : errhint("This means that the backup is corrupted and you will "
955 : : "have to use another backup for recovery.")));
956 : 10 : ControlFile->backupEndPoint = ControlFile->minRecoveryPoint;
957 : : }
958 : : }
959 : : }
960 : :
961 : : /* remember these, so that we know when we have reached consistency */
962 : 1177 : backupStartPoint = ControlFile->backupStartPoint;
963 : 1177 : backupEndRequired = ControlFile->backupEndRequired;
964 : 1177 : backupEndPoint = ControlFile->backupEndPoint;
965 [ + + ]: 1177 : if (InArchiveRecovery)
966 : : {
967 : 151 : minRecoveryPoint = ControlFile->minRecoveryPoint;
968 : 151 : minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
969 : : }
970 : : else
971 : : {
972 : 1026 : minRecoveryPoint = InvalidXLogRecPtr;
973 : 1026 : minRecoveryPointTLI = 0;
974 : : }
975 : :
976 : : /*
977 : : * Start recovery assuming that the final record isn't lost.
978 : : */
979 : 1177 : abortedRecPtr = InvalidXLogRecPtr;
980 : 1177 : missingContrecPtr = InvalidXLogRecPtr;
981 : :
982 : 1177 : *wasShutdown_ptr = wasShutdown;
983 : 1177 : *haveBackupLabel_ptr = haveBackupLabel;
984 : 1177 : *haveTblspcMap_ptr = haveTblspcMap;
985 : 1177 : }
986 : :
987 : : /*
988 : : * See if there are any recovery signal files and if so, set state for
989 : : * recovery.
990 : : *
991 : : * See if there is a recovery command file (recovery.conf), and if so
992 : : * throw an ERROR since as of PG12 we no longer recognize that.
993 : : */
994 : : static void
995 : 1184 : readRecoverySignalFile(void)
996 : : {
997 : : struct stat stat_buf;
998 : :
999 [ + + ]: 1184 : if (IsBootstrapProcessingMode())
1000 : 1041 : return;
1001 : :
1002 : : /*
1003 : : * Check for old recovery API file: recovery.conf
1004 : : */
1005 [ - + ]: 1123 : if (stat(RECOVERY_COMMAND_FILE, &stat_buf) == 0)
1006 [ # # ]: 0 : ereport(FATAL,
1007 : : (errcode_for_file_access(),
1008 : : errmsg("using recovery command file \"%s\" is not supported",
1009 : : RECOVERY_COMMAND_FILE)));
1010 : :
1011 : : /*
1012 : : * Remove unused .done file, if present. Ignore if absent.
1013 : : */
1014 : 1123 : unlink(RECOVERY_COMMAND_DONE);
1015 : :
1016 : : /*
1017 : : * Check for recovery signal files and if found, fsync them since they
1018 : : * represent server state information. We don't sweat too much about the
1019 : : * possibility of fsync failure, however.
1020 : : */
1021 [ + + ]: 1123 : if (stat(STANDBY_SIGNAL_FILE, &stat_buf) == 0)
1022 : : {
1023 : : int fd;
1024 : :
1025 : 137 : fd = BasicOpenFilePerm(STANDBY_SIGNAL_FILE, O_RDWR | PG_BINARY,
1026 : : S_IRUSR | S_IWUSR);
1027 [ + - ]: 137 : if (fd >= 0)
1028 : : {
1029 : 137 : (void) pg_fsync(fd);
1030 : 137 : close(fd);
1031 : : }
1032 : 137 : standby_signal_file_found = true;
1033 : : }
1034 : :
1035 [ + + ]: 1123 : if (stat(RECOVERY_SIGNAL_FILE, &stat_buf) == 0)
1036 : : {
1037 : : int fd;
1038 : :
1039 : 8 : fd = BasicOpenFilePerm(RECOVERY_SIGNAL_FILE, O_RDWR | PG_BINARY,
1040 : : S_IRUSR | S_IWUSR);
1041 [ + - ]: 8 : if (fd >= 0)
1042 : : {
1043 : 8 : (void) pg_fsync(fd);
1044 : 8 : close(fd);
1045 : : }
1046 : 8 : recovery_signal_file_found = true;
1047 : : }
1048 : :
1049 : : /*
1050 : : * If both signal files are present, standby signal file takes precedence.
1051 : : * If neither is present then we won't enter archive recovery.
1052 : : */
1053 : 1123 : StandbyModeRequested = false;
1054 : 1123 : ArchiveRecoveryRequested = false;
1055 [ + + ]: 1123 : if (standby_signal_file_found)
1056 : : {
1057 : 137 : StandbyModeRequested = true;
1058 : 137 : ArchiveRecoveryRequested = true;
1059 : : }
1060 [ + + ]: 986 : else if (recovery_signal_file_found)
1061 : : {
1062 : 6 : StandbyModeRequested = false;
1063 : 6 : ArchiveRecoveryRequested = true;
1064 : : }
1065 : : else
1066 : 980 : return;
1067 : :
1068 : : /*
1069 : : * We don't support standby mode in standalone backends; that requires
1070 : : * other processes such as the WAL receiver to be alive.
1071 : : */
1072 [ + + - + ]: 143 : if (StandbyModeRequested && !IsUnderPostmaster)
1073 [ # # ]: 0 : ereport(FATAL,
1074 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1075 : : errmsg("standby mode is not supported by single-user servers")));
1076 : : }
1077 : :
1078 : : static void
1079 : 1184 : validateRecoveryParameters(void)
1080 : : {
1081 : : /* Reject conflicting targets even when recovery was not requested */
1082 : 1184 : recoveryTarget = DetermineRecoveryTargetType();
1083 : :
1084 [ + + ]: 1182 : if (!ArchiveRecoveryRequested)
1085 : 1039 : return;
1086 : :
1087 : : /*
1088 : : * Check for compulsory parameters
1089 : : */
1090 [ + + ]: 143 : if (StandbyModeRequested)
1091 : : {
1092 [ + - + + ]: 137 : if ((PrimaryConnInfo == NULL || strcmp(PrimaryConnInfo, "") == 0) &&
1093 [ + - + + ]: 15 : (recoveryRestoreCommand == NULL || strcmp(recoveryRestoreCommand, "") == 0))
1094 [ + - ]: 3 : ereport(WARNING,
1095 : : (errmsg("specified neither \"primary_conninfo\" nor \"restore_command\""),
1096 : : errhint("The database server will regularly poll the pg_wal subdirectory to check for files placed there.")));
1097 : : }
1098 : : else
1099 : : {
1100 [ + - ]: 6 : if (recoveryRestoreCommand == NULL ||
1101 [ - + ]: 6 : strcmp(recoveryRestoreCommand, "") == 0)
1102 [ # # ]: 0 : ereport(FATAL,
1103 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1104 : : errmsg("must specify \"restore_command\" when standby mode is not enabled")));
1105 : : }
1106 : :
1107 : : /*
1108 : : * Override any inconsistent requests. Note that this is a change of
1109 : : * behaviour in 9.5; prior to this we simply ignored a request to pause if
1110 : : * hot_standby = off, which was surprising behaviour.
1111 : : */
1112 [ + + ]: 143 : if (recoveryTargetAction == RECOVERY_TARGET_ACTION_PAUSE &&
1113 [ + + ]: 135 : !EnableHotStandby)
1114 : 3 : recoveryTargetAction = RECOVERY_TARGET_ACTION_SHUTDOWN;
1115 : :
1116 : : /*
1117 : : * Final parsing of recovery_target_time string; see also
1118 : : * check_recovery_target_time().
1119 : : */
1120 [ - + ]: 143 : if (recoveryTarget == RECOVERY_TARGET_TIME)
1121 : : {
1122 : 0 : recoveryTargetTime = DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
1123 : : CStringGetDatum(recovery_target_time_string),
1124 : : ObjectIdGetDatum(InvalidOid),
1125 : : Int32GetDatum(-1)));
1126 : : }
1127 : :
1128 : : /*
1129 : : * If user specified recovery_target_timeline, validate it or compute the
1130 : : * "latest" value. We can't do this until after we've gotten the restore
1131 : : * command and set InArchiveRecovery, because we need to fetch timeline
1132 : : * history files from the archive.
1133 : : */
1134 [ - + ]: 143 : if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_NUMERIC)
1135 : : {
1136 : 0 : TimeLineID rtli = recoveryTargetTLIRequested;
1137 : :
1138 : : /* Timeline 1 does not have a history file, all else should */
1139 [ # # # # ]: 0 : if (rtli != 1 && !existsTimeLineHistory(rtli))
1140 [ # # ]: 0 : ereport(FATAL,
1141 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1142 : : errmsg("recovery target timeline %u does not exist",
1143 : : rtli)));
1144 : 0 : recoveryTargetTLI = rtli;
1145 : : }
1146 [ + - ]: 143 : else if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_LATEST)
1147 : : {
1148 : : /* We start the "latest" search from pg_control's timeline */
1149 : 143 : recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
1150 : : }
1151 : : else
1152 : : {
1153 : : /*
1154 : : * else we just use the recoveryTargetTLI as already read from
1155 : : * ControlFile
1156 : : */
1157 : : Assert(recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_CONTROLFILE);
1158 : : }
1159 : : }
1160 : :
1161 : : /*
1162 : : * read_backup_label: check to see if a backup_label file is present
1163 : : *
1164 : : * If we see a backup_label during recovery, we assume that we are recovering
1165 : : * from a backup dump file, and we therefore roll forward from the checkpoint
1166 : : * identified by the label file, NOT what pg_control says. This avoids the
1167 : : * problem that pg_control might have been archived one or more checkpoints
1168 : : * later than the start of the dump, and so if we rely on it as the start
1169 : : * point, we will fail to restore a consistent database state.
1170 : : *
1171 : : * Returns true if a backup_label was found (and fills the checkpoint
1172 : : * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
1173 : : * returns false if not. If this backup_label came from a streamed backup,
1174 : : * *backupEndRequired is set to true. If this backup_label was created during
1175 : : * recovery, *backupFromStandby is set to true.
1176 : : *
1177 : : * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
1178 : : * and TLI read from the backup file.
1179 : : */
1180 : : static bool
1181 : 1181 : read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
1182 : : bool *backupEndRequired, bool *backupFromStandby)
1183 : : {
1184 : : char startxlogfilename[MAXFNAMELEN];
1185 : : TimeLineID tli_from_walseg,
1186 : : tli_from_file;
1187 : : FILE *lfp;
1188 : : char ch;
1189 : : char backuptype[20];
1190 : : char backupfrom[20];
1191 : : char backuplabel[MAXPGPATH];
1192 : : char backuptime[128];
1193 : : char lsn[MAXPG_LSNLEN + 1];
1194 : :
1195 : : /* suppress possible uninitialized-variable warnings */
1196 : 1181 : *checkPointLoc = InvalidXLogRecPtr;
1197 : 1181 : *backupLabelTLI = 0;
1198 : 1181 : *backupEndRequired = false;
1199 : 1181 : *backupFromStandby = false;
1200 : :
1201 : : /*
1202 : : * See if label file is present
1203 : : */
1204 : 1181 : lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
1205 [ + + ]: 1181 : if (!lfp)
1206 : : {
1207 [ - + ]: 1076 : if (errno != ENOENT)
1208 [ # # ]: 0 : ereport(FATAL,
1209 : : (errcode_for_file_access(),
1210 : : errmsg("could not read file \"%s\": %m",
1211 : : BACKUP_LABEL_FILE)));
1212 : 1076 : return false; /* it's not there, all is fine */
1213 : : }
1214 : :
1215 : : /*
1216 : : * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
1217 : : * is pretty crude, but we are not expecting any variability in the file
1218 : : * format).
1219 : : */
1220 [ + - ]: 105 : if (fscanf(lfp,
1221 : : "START WAL LOCATION: %" CppAsString2(MAXPG_LSNLEN) "[0123456789ABCDEFabcdef/] (file %08X%16s)%c",
1222 : 105 : lsn, &tli_from_walseg, startxlogfilename, &ch) != 4 ||
1223 [ + - ]: 105 : ch != '\n' ||
1224 [ - + ]: 105 : !pg_parse_lsn(lsn, &RedoStartLSN))
1225 [ # # ]: 0 : ereport(FATAL,
1226 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1227 : : errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
1228 : 105 : RedoStartTLI = tli_from_walseg;
1229 [ + - ]: 105 : if (fscanf(lfp,
1230 : : "CHECKPOINT LOCATION: %" CppAsString2(MAXPG_LSNLEN) "[0123456789ABCDEFabcdef/]%c", lsn,
1231 : 105 : &ch) != 2 ||
1232 [ + - ]: 105 : ch != '\n' ||
1233 [ - + ]: 105 : !pg_parse_lsn(lsn, checkPointLoc))
1234 [ # # ]: 0 : ereport(FATAL,
1235 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1236 : : errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
1237 : 105 : *backupLabelTLI = tli_from_walseg;
1238 : :
1239 : : /*
1240 : : * BACKUP METHOD lets us know if this was a typical backup ("streamed",
1241 : : * which could mean either pg_basebackup or the pg_backup_start/stop
1242 : : * method was used) or if this label came from somewhere else (the only
1243 : : * other option today being from pg_rewind). If this was a streamed
1244 : : * backup then we know that we need to play through until we get to the
1245 : : * end of the WAL which was generated during the backup (at which point we
1246 : : * will have reached consistency and backupEndRequired will be reset to be
1247 : : * false).
1248 : : */
1249 [ + - ]: 105 : if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
1250 : : {
1251 [ + + ]: 105 : if (strcmp(backuptype, "streamed") == 0)
1252 : 101 : *backupEndRequired = true;
1253 : : }
1254 : :
1255 : : /*
1256 : : * BACKUP FROM lets us know if this was from a primary or a standby. If
1257 : : * it was from a standby, we'll double-check that the control file state
1258 : : * matches that of a standby.
1259 : : */
1260 [ + - ]: 105 : if (fscanf(lfp, "BACKUP FROM: %19s\n", backupfrom) == 1)
1261 : : {
1262 [ + + ]: 105 : if (strcmp(backupfrom, "standby") == 0)
1263 : 10 : *backupFromStandby = true;
1264 : : }
1265 : :
1266 : : /*
1267 : : * Parse START TIME and LABEL. Those are not mandatory fields for recovery
1268 : : * but checking for their presence is useful for debugging and the next
1269 : : * sanity checks. Cope also with the fact that the result buffers have a
1270 : : * pre-allocated size, hence if the backup_label file has been generated
1271 : : * with strings longer than the maximum assumed here an incorrect parsing
1272 : : * happens. That's fine as only minor consistency checks are done
1273 : : * afterwards.
1274 : : */
1275 [ + + ]: 105 : if (fscanf(lfp, "START TIME: %127[^\n]\n", backuptime) == 1)
1276 [ + + ]: 104 : ereport(DEBUG1,
1277 : : (errmsg_internal("backup time %s in file \"%s\"",
1278 : : backuptime, BACKUP_LABEL_FILE)));
1279 : :
1280 [ + + ]: 105 : if (fscanf(lfp, "LABEL: %1023[^\n]\n", backuplabel) == 1)
1281 [ + + ]: 101 : ereport(DEBUG1,
1282 : : (errmsg_internal("backup label %s in file \"%s\"",
1283 : : backuplabel, BACKUP_LABEL_FILE)));
1284 : :
1285 : : /*
1286 : : * START TIMELINE is new as of 11. Its parsing is not mandatory, still use
1287 : : * it as a sanity check if present.
1288 : : */
1289 [ + + ]: 105 : if (fscanf(lfp, "START TIMELINE: %u\n", &tli_from_file) == 1)
1290 : : {
1291 [ - + ]: 101 : if (tli_from_walseg != tli_from_file)
1292 [ # # ]: 0 : ereport(FATAL,
1293 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1294 : : errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE),
1295 : : errdetail("Timeline ID parsed is %u, but expected %u.",
1296 : : tli_from_file, tli_from_walseg)));
1297 : :
1298 [ + + ]: 101 : ereport(DEBUG1,
1299 : : (errmsg_internal("backup timeline %u in file \"%s\"",
1300 : : tli_from_file, BACKUP_LABEL_FILE)));
1301 : : }
1302 : :
1303 : : /*
1304 : : * INCREMENTAL FROM LSN indicates that this is an incremental backup. The
1305 : : * LSN itself need not be parsed, so reading its first character is
1306 : : * sufficient.
1307 : : */
1308 [ - + ]: 105 : if (fscanf(lfp, "INCREMENTAL FROM LSN: %c", &ch) == 1)
1309 [ # # ]: 0 : ereport(FATAL,
1310 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1311 : : errmsg("this is an incremental backup, not a data directory"),
1312 : : errhint("Use pg_combinebackup to reconstruct a valid data directory.")));
1313 : :
1314 [ + - - + ]: 105 : if (ferror(lfp) || FreeFile(lfp))
1315 [ # # ]: 0 : ereport(FATAL,
1316 : : (errcode_for_file_access(),
1317 : : errmsg("could not read file \"%s\": %m",
1318 : : BACKUP_LABEL_FILE)));
1319 : :
1320 : 105 : return true;
1321 : : }
1322 : :
1323 : : /*
1324 : : * read_tablespace_map: check to see if a tablespace_map file is present
1325 : : *
1326 : : * If we see a tablespace_map file during recovery, we assume that we are
1327 : : * recovering from a backup dump file, and we therefore need to create symlinks
1328 : : * as per the information present in tablespace_map file.
1329 : : *
1330 : : * Returns true if a tablespace_map file was found (and fills *tablespaces
1331 : : * with a tablespaceinfo struct for each tablespace listed in the file);
1332 : : * returns false if not.
1333 : : */
1334 : : static bool
1335 : 103 : read_tablespace_map(List **tablespaces)
1336 : : {
1337 : : tablespaceinfo *ti;
1338 : : FILE *lfp;
1339 : : char str[MAXPGPATH];
1340 : : int ch,
1341 : : i,
1342 : : n;
1343 : : bool was_backslash;
1344 : :
1345 : : /*
1346 : : * See if tablespace_map file is present
1347 : : */
1348 : 103 : lfp = AllocateFile(TABLESPACE_MAP, "r");
1349 [ + + ]: 103 : if (!lfp)
1350 : : {
1351 [ - + ]: 101 : if (errno != ENOENT)
1352 [ # # ]: 0 : ereport(FATAL,
1353 : : (errcode_for_file_access(),
1354 : : errmsg("could not read file \"%s\": %m",
1355 : : TABLESPACE_MAP)));
1356 : 101 : return false; /* it's not there, all is fine */
1357 : : }
1358 : :
1359 : : /*
1360 : : * Read and parse the link name and path lines from tablespace_map file
1361 : : * (this code is pretty crude, but we are not expecting any variability in
1362 : : * the file format). De-escape any backslashes that were inserted.
1363 : : */
1364 : 2 : i = 0;
1365 : 2 : was_backslash = false;
1366 [ + + ]: 77 : while ((ch = fgetc(lfp)) != EOF)
1367 : : {
1368 [ + - + + : 75 : if (!was_backslash && (ch == '\n' || ch == '\r'))
- + ]
1369 : 2 : {
1370 : : char *endp;
1371 : :
1372 [ - + ]: 2 : if (i == 0)
1373 : 0 : continue; /* \r immediately followed by \n */
1374 : :
1375 : : /*
1376 : : * The de-escaped line should contain an OID followed by exactly
1377 : : * one space followed by a path. The path might start with
1378 : : * spaces, so don't be too liberal about parsing.
1379 : : */
1380 : 2 : str[i] = '\0';
1381 : 2 : n = 0;
1382 [ + - + + ]: 12 : while (str[n] && str[n] != ' ')
1383 : 10 : n++;
1384 [ + - - + ]: 2 : if (n < 1 || n >= i - 1)
1385 [ # # ]: 0 : ereport(FATAL,
1386 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1387 : : errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
1388 : 2 : str[n++] = '\0';
1389 : :
1390 : 2 : ti = palloc0_object(tablespaceinfo);
1391 : 2 : errno = 0;
1392 : 2 : ti->oid = strtoul(str, &endp, 10);
1393 [ + - + - : 2 : if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
- + ]
1394 [ # # ]: 0 : ereport(FATAL,
1395 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1396 : : errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
1397 : 2 : ti->path = pstrdup(str + n);
1398 : 2 : *tablespaces = lappend(*tablespaces, ti);
1399 : :
1400 : 2 : i = 0;
1401 : 2 : continue;
1402 : : }
1403 [ + - - + ]: 73 : else if (!was_backslash && ch == '\\')
1404 : 0 : was_backslash = true;
1405 : : else
1406 : : {
1407 [ + - ]: 73 : if (i < sizeof(str) - 1)
1408 : 73 : str[i++] = ch;
1409 : 73 : was_backslash = false;
1410 : : }
1411 : : }
1412 : :
1413 [ + - - + ]: 2 : if (i != 0 || was_backslash) /* last line not terminated? */
1414 [ # # ]: 0 : ereport(FATAL,
1415 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1416 : : errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
1417 : :
1418 [ + - - + ]: 2 : if (ferror(lfp) || FreeFile(lfp))
1419 [ # # ]: 0 : ereport(FATAL,
1420 : : (errcode_for_file_access(),
1421 : : errmsg("could not read file \"%s\": %m",
1422 : : TABLESPACE_MAP)));
1423 : :
1424 : 2 : return true;
1425 : : }
1426 : :
1427 : : /*
1428 : : * Finish WAL recovery.
1429 : : *
1430 : : * This does not close the 'xlogreader' yet, because in some cases the caller
1431 : : * still wants to re-read the last checkpoint record by calling
1432 : : * ReadCheckpointRecord().
1433 : : *
1434 : : * Returns the position of the last valid or applied record, after which new
1435 : : * WAL should be appended, information about why recovery was ended, and some
1436 : : * other things. See the EndOfWalRecoveryInfo struct for details.
1437 : : */
1438 : : EndOfWalRecoveryInfo *
1439 : 1101 : FinishWalRecovery(void)
1440 : : {
1441 : 1101 : EndOfWalRecoveryInfo *result = palloc_object(EndOfWalRecoveryInfo);
1442 : : XLogRecPtr lastRec;
1443 : : TimeLineID lastRecTLI;
1444 : : XLogRecPtr endOfLog;
1445 : :
1446 : : /*
1447 : : * Kill WAL receiver, if it's still running, before we continue to write
1448 : : * the startup checkpoint and aborted-contrecord records. It will trump
1449 : : * over these records and subsequent ones if it's still alive when we
1450 : : * start writing WAL.
1451 : : */
1452 : 1101 : XLogShutdownWalRcv();
1453 : :
1454 : : /*
1455 : : * Shutdown the slot sync worker to drop any temporary slots acquired by
1456 : : * it and to prevent it from keep trying to fetch the failover slots.
1457 : : *
1458 : : * We do not update the 'synced' column in 'pg_replication_slots' system
1459 : : * view from true to false here, as any failed update could leave 'synced'
1460 : : * column false for some slots. This could cause issues during slot sync
1461 : : * after restarting the server as a standby. While updating the 'synced'
1462 : : * column after switching to the new timeline is an option, it does not
1463 : : * simplify the handling for the 'synced' column. Therefore, we retain the
1464 : : * 'synced' column as true after promotion as it may provide useful
1465 : : * information about the slot origin.
1466 : : */
1467 : 1101 : ShutDownSlotSync();
1468 : :
1469 : : /*
1470 : : * We are now done reading the xlog from stream. Turn off streaming
1471 : : * recovery to force fetching the files (which would be required at end of
1472 : : * recovery, e.g., timeline history file) from archive or pg_wal.
1473 : : *
1474 : : * Note that standby mode must be turned off after killing WAL receiver,
1475 : : * i.e., calling XLogShutdownWalRcv().
1476 : : */
1477 : : Assert(!WalRcvStreaming());
1478 : 1101 : StandbyMode = false;
1479 : :
1480 : : /*
1481 : : * Determine where to start writing WAL next.
1482 : : *
1483 : : * Re-fetch the last valid or last applied record, so we can identify the
1484 : : * exact endpoint of what we consider the valid portion of WAL. There may
1485 : : * be an incomplete continuation record after that, in which case
1486 : : * 'abortedRecPtr' and 'missingContrecPtr' are set and the caller will
1487 : : * write a special OVERWRITE_CONTRECORD message to mark that the rest of
1488 : : * it is intentionally missing. See CreateOverwriteContrecordRecord().
1489 : : *
1490 : : * An important side-effect of this is to load the last page into
1491 : : * xlogreader. The caller uses it to initialize the WAL for writing.
1492 : : */
1493 [ + + ]: 1101 : if (!InRecovery)
1494 : : {
1495 : 916 : lastRec = CheckPointLoc;
1496 : 916 : lastRecTLI = CheckPointTLI;
1497 : : }
1498 : : else
1499 : : {
1500 : 185 : lastRec = XLogRecoveryCtl->lastReplayedReadRecPtr;
1501 : 185 : lastRecTLI = XLogRecoveryCtl->lastReplayedTLI;
1502 : : }
1503 : 1101 : XLogPrefetcherBeginRead(xlogprefetcher, lastRec);
1504 : 1101 : (void) ReadRecord(xlogprefetcher, PANIC, false, lastRecTLI);
1505 : 1101 : endOfLog = xlogreader->EndRecPtr;
1506 : :
1507 : : /*
1508 : : * Remember the TLI in the filename of the XLOG segment containing the
1509 : : * end-of-log. It could be different from the timeline that endOfLog
1510 : : * nominally belongs to, if there was a timeline switch in that segment,
1511 : : * and we were reading the old WAL from a segment belonging to a higher
1512 : : * timeline.
1513 : : */
1514 : 1101 : result->endOfLogTLI = xlogreader->seg.ws_tli;
1515 : :
1516 [ + + ]: 1101 : if (ArchiveRecoveryRequested)
1517 : : {
1518 : : /*
1519 : : * We are no longer in archive recovery state.
1520 : : *
1521 : : * We are now done reading the old WAL. Turn off archive fetching if
1522 : : * it was active.
1523 : : */
1524 : : Assert(InArchiveRecovery);
1525 : 67 : InArchiveRecovery = false;
1526 : :
1527 : : /*
1528 : : * If the ending log segment is still open, close it (to avoid
1529 : : * problems on Windows with trying to rename or delete an open file).
1530 : : */
1531 [ + - ]: 67 : if (readFile >= 0)
1532 : : {
1533 : 67 : close(readFile);
1534 : 67 : readFile = -1;
1535 : : }
1536 : : }
1537 : :
1538 : : /*
1539 : : * Copy the last partial block to the caller, for initializing the WAL
1540 : : * buffer for appending new WAL.
1541 : : */
1542 [ + + ]: 1101 : if (endOfLog % XLOG_BLCKSZ != 0)
1543 : : {
1544 : : char *page;
1545 : : int len;
1546 : : XLogRecPtr pageBeginPtr;
1547 : :
1548 : 1081 : pageBeginPtr = endOfLog - (endOfLog % XLOG_BLCKSZ);
1549 : : Assert(readOff == XLogSegmentOffset(pageBeginPtr, wal_segment_size));
1550 : :
1551 : : /* Copy the valid part of the last block */
1552 : 1081 : len = endOfLog % XLOG_BLCKSZ;
1553 : 1081 : page = palloc(len);
1554 : 1081 : memcpy(page, xlogreader->readBuf, len);
1555 : :
1556 : 1081 : result->lastPageBeginPtr = pageBeginPtr;
1557 : 1081 : result->lastPage = page;
1558 : : }
1559 : : else
1560 : : {
1561 : : /* There is no partial block to copy. */
1562 : 20 : result->lastPageBeginPtr = endOfLog;
1563 : 20 : result->lastPage = NULL;
1564 : : }
1565 : :
1566 : : /*
1567 : : * Create a comment for the history file to explain why and where timeline
1568 : : * changed.
1569 : : */
1570 : 1101 : result->recoveryStopReason = getRecoveryStopReason();
1571 : :
1572 : 1101 : result->lastRec = lastRec;
1573 : 1101 : result->lastRecTLI = lastRecTLI;
1574 : 1101 : result->endOfLog = endOfLog;
1575 : :
1576 : 1101 : result->abortedRecPtr = abortedRecPtr;
1577 : 1101 : result->missingContrecPtr = missingContrecPtr;
1578 : :
1579 : 1101 : result->standby_signal_file_found = standby_signal_file_found;
1580 : 1101 : result->recovery_signal_file_found = recovery_signal_file_found;
1581 : :
1582 : 1101 : return result;
1583 : : }
1584 : :
1585 : : /*
1586 : : * Clean up the WAL reader and leftovers from restoring WAL from archive
1587 : : */
1588 : : void
1589 : 1101 : ShutdownWalRecovery(void)
1590 : : {
1591 : : char recoveryPath[MAXPGPATH];
1592 : :
1593 : : /* Final update of pg_stat_recovery_prefetch. */
1594 : 1101 : XLogPrefetcherComputeStats(xlogprefetcher);
1595 : :
1596 : : /* Shut down xlogreader */
1597 [ + + ]: 1101 : if (readFile >= 0)
1598 : : {
1599 : 1034 : close(readFile);
1600 : 1034 : readFile = -1;
1601 : : }
1602 : 1101 : pfree(xlogreader->private_data);
1603 : 1101 : XLogReaderFree(xlogreader);
1604 : 1101 : XLogPrefetcherFree(xlogprefetcher);
1605 : :
1606 [ + + ]: 1101 : if (ArchiveRecoveryRequested)
1607 : : {
1608 : : /*
1609 : : * Since there might be a partial WAL segment named RECOVERYXLOG, get
1610 : : * rid of it.
1611 : : */
1612 : 67 : snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
1613 : 67 : unlink(recoveryPath); /* ignore any error */
1614 : :
1615 : : /* Get rid of any remaining recovered timeline-history file, too */
1616 : 67 : snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
1617 : 67 : unlink(recoveryPath); /* ignore any error */
1618 : : }
1619 : :
1620 : : /*
1621 : : * We don't need the latch anymore. It's not strictly necessary to disown
1622 : : * it, but let's do it for the sake of tidiness.
1623 : : */
1624 [ + + ]: 1101 : if (ArchiveRecoveryRequested)
1625 : 67 : DisownLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
1626 : 1101 : }
1627 : :
1628 : : /*
1629 : : * Perform WAL recovery.
1630 : : *
1631 : : * If the system was shut down cleanly, this is never called.
1632 : : */
1633 : : void
1634 : 259 : PerformWalRecovery(void)
1635 : : {
1636 : : XLogRecord *record;
1637 : 259 : bool reachedRecoveryTarget = false;
1638 : : TimeLineID replayTLI;
1639 : :
1640 : : /*
1641 : : * Initialize shared variables for tracking progress of WAL replay, as if
1642 : : * we had just replayed the record before the REDO location (or the
1643 : : * checkpoint record itself, if it's a shutdown checkpoint).
1644 : : */
1645 : 259 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
1646 [ + + ]: 259 : if (RedoStartLSN < CheckPointLoc)
1647 : : {
1648 : 147 : XLogRecoveryCtl->lastReplayedReadRecPtr = InvalidXLogRecPtr;
1649 : 147 : XLogRecoveryCtl->lastReplayedEndRecPtr = RedoStartLSN;
1650 : 147 : XLogRecoveryCtl->lastReplayedTLI = RedoStartTLI;
1651 : : }
1652 : : else
1653 : : {
1654 : 112 : XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
1655 : 112 : XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
1656 : 112 : XLogRecoveryCtl->lastReplayedTLI = CheckPointTLI;
1657 : : }
1658 : 259 : XLogRecoveryCtl->replayEndRecPtr = XLogRecoveryCtl->lastReplayedEndRecPtr;
1659 : 259 : XLogRecoveryCtl->replayEndTLI = XLogRecoveryCtl->lastReplayedTLI;
1660 : 259 : XLogRecoveryCtl->recoveryLastXTime = 0;
1661 : 259 : XLogRecoveryCtl->currentChunkStartTime = 0;
1662 : 259 : XLogRecoveryCtl->recoveryPauseState = RECOVERY_NOT_PAUSED;
1663 : 259 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
1664 : :
1665 : : /* Also ensure XLogReceiptTime has a sane value */
1666 : 259 : XLogReceiptTime = GetCurrentTimestamp();
1667 : :
1668 : : /*
1669 : : * Let postmaster know we've started redo now, so that it can launch the
1670 : : * archiver if necessary.
1671 : : */
1672 [ + + ]: 259 : if (IsUnderPostmaster)
1673 : 250 : SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
1674 : :
1675 : : /*
1676 : : * Allow read-only connections immediately if we're consistent already.
1677 : : */
1678 : 259 : CheckRecoveryConsistency();
1679 : :
1680 : : /*
1681 : : * Find the first record that logically follows the checkpoint --- it
1682 : : * might physically precede it, though.
1683 : : */
1684 [ + + ]: 259 : if (RedoStartLSN < CheckPointLoc)
1685 : : {
1686 : : /* back up to find the record */
1687 : 147 : replayTLI = RedoStartTLI;
1688 : 147 : XLogPrefetcherBeginRead(xlogprefetcher, RedoStartLSN);
1689 : 147 : record = ReadRecord(xlogprefetcher, PANIC, false, replayTLI);
1690 : :
1691 : : /*
1692 : : * If a checkpoint record's redo pointer points back to an earlier
1693 : : * LSN, the record at that LSN should be an XLOG_CHECKPOINT_REDO
1694 : : * record.
1695 : : */
1696 [ + - ]: 147 : if (record->xl_rmid != RM_XLOG_ID ||
1697 [ - + ]: 147 : (record->xl_info & ~XLR_INFO_MASK) != XLOG_CHECKPOINT_REDO)
1698 [ # # ]: 0 : ereport(FATAL,
1699 : : errmsg("unexpected record type found at redo point %X/%08X",
1700 : : LSN_FORMAT_ARGS(xlogreader->ReadRecPtr)));
1701 : : }
1702 : : else
1703 : : {
1704 : : /* just have to read next record after CheckPoint */
1705 : : Assert(xlogreader->ReadRecPtr == CheckPointLoc);
1706 : 112 : replayTLI = CheckPointTLI;
1707 : 112 : record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1708 : : }
1709 : :
1710 [ + + ]: 259 : if (record != NULL)
1711 : : {
1712 : : TimestampTz xtime;
1713 : : PGRUsage ru0;
1714 : :
1715 : 248 : pg_rusage_init(&ru0);
1716 : :
1717 : 248 : InRedo = true;
1718 : :
1719 : 248 : RmgrStartup();
1720 : :
1721 [ + - ]: 248 : ereport(LOG,
1722 : : errmsg("redo starts at %X/%08X",
1723 : : LSN_FORMAT_ARGS(xlogreader->ReadRecPtr)));
1724 : :
1725 : : /* Prepare to report progress of the redo phase. */
1726 [ + + ]: 248 : if (!StandbyMode)
1727 : 118 : begin_startup_progress_phase();
1728 : :
1729 : : /*
1730 : : * main redo apply loop
1731 : : */
1732 : : do
1733 : : {
1734 [ + + ]: 2972476 : if (!StandbyMode)
1735 [ - + - - ]: 328638 : ereport_startup_progress("redo in progress, elapsed time: %ld.%02d s, current LSN: %X/%08X",
1736 : : LSN_FORMAT_ARGS(xlogreader->ReadRecPtr));
1737 : :
1738 : : #ifdef WAL_DEBUG
1739 : : if (XLOG_DEBUG)
1740 : : {
1741 : : StringInfoData buf;
1742 : :
1743 : : initStringInfo(&buf);
1744 : : appendStringInfo(&buf, "REDO @ %X/%08X; LSN %X/%08X: ",
1745 : : LSN_FORMAT_ARGS(xlogreader->ReadRecPtr),
1746 : : LSN_FORMAT_ARGS(xlogreader->EndRecPtr));
1747 : : xlog_outrec(&buf, xlogreader);
1748 : : appendStringInfoString(&buf, " - ");
1749 : : xlog_outdesc(&buf, xlogreader);
1750 : : elog(LOG, "%s", buf.data);
1751 : : pfree(buf.data);
1752 : : }
1753 : : #endif
1754 : :
1755 : : /* Handle interrupt signals of startup process */
1756 : 2972476 : ProcessStartupProcInterrupts();
1757 : :
1758 : : /*
1759 : : * Pause WAL replay, if requested by a hot-standby session via
1760 : : * SetRecoveryPause().
1761 : : *
1762 : : * Note that we intentionally don't take the info_lck spinlock
1763 : : * here. We might therefore read a slightly stale value of the
1764 : : * recoveryPause flag, but it can't be very stale (no worse than
1765 : : * the last spinlock we did acquire). Since a pause request is a
1766 : : * pretty asynchronous thing anyway, possibly responding to it one
1767 : : * WAL record later than we otherwise would is a minor issue, so
1768 : : * it doesn't seem worth adding another spinlock cycle to prevent
1769 : : * that.
1770 : : */
1771 [ - + ]: 2972476 : if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1772 : : RECOVERY_NOT_PAUSED)
1773 : 0 : recoveryPausesHere(false);
1774 : :
1775 : : /*
1776 : : * Have we reached our recovery target?
1777 : : */
1778 [ + + ]: 2972476 : if (recoveryStopsBefore(xlogreader))
1779 : : {
1780 : 3 : reachedRecoveryTarget = true;
1781 : 3 : break;
1782 : : }
1783 : :
1784 : : /*
1785 : : * If we've been asked to lag the primary, wait on latch until
1786 : : * enough time has passed.
1787 : : */
1788 [ + + ]: 2972473 : if (recoveryApplyDelay(xlogreader))
1789 : : {
1790 : : /*
1791 : : * We test for paused recovery again here. If user sets
1792 : : * delayed apply, it may be because they expect to pause
1793 : : * recovery in case of problems, so we must test again here
1794 : : * otherwise pausing during the delay-wait wouldn't work.
1795 : : */
1796 [ + + ]: 28 : if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1797 : : RECOVERY_NOT_PAUSED)
1798 : 1 : recoveryPausesHere(false);
1799 : : }
1800 : :
1801 : : /*
1802 : : * Apply the record
1803 : : */
1804 : 2972473 : ApplyWalRecord(xlogreader, record, &replayTLI);
1805 : :
1806 : : /*
1807 : : * Wake up processes waiting for standby replay, write, or flush
1808 : : * LSN to reach current replay position. Replay implies that the
1809 : : * WAL was already written and flushed to disk, so write and flush
1810 : : * waiters can be woken at the replay position too.
1811 : : */
1812 : 2972471 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_REPLAY,
1813 : 2972471 : XLogRecoveryCtl->lastReplayedEndRecPtr);
1814 : 2972471 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE,
1815 : 2972471 : XLogRecoveryCtl->lastReplayedEndRecPtr);
1816 : 2972471 : WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH,
1817 : 2972471 : XLogRecoveryCtl->lastReplayedEndRecPtr);
1818 : :
1819 : : /* Exit loop if we reached inclusive recovery target */
1820 [ + + ]: 2972471 : if (recoveryStopsAfter(xlogreader))
1821 : : {
1822 : 5 : reachedRecoveryTarget = true;
1823 : 5 : break;
1824 : : }
1825 : :
1826 : : /* Else, try to fetch the next WAL record */
1827 : 2972466 : record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1828 [ + + ]: 2972395 : } while (record != NULL);
1829 : :
1830 : : /*
1831 : : * end of main redo apply loop
1832 : : */
1833 : :
1834 [ + + ]: 175 : if (reachedRecoveryTarget)
1835 : : {
1836 [ - + ]: 8 : if (!reachedConsistency)
1837 [ # # ]: 0 : ereport(FATAL,
1838 : : (errmsg("requested recovery stop point is before consistent recovery point")));
1839 : :
1840 : : /*
1841 : : * This is the last point where we can restart recovery with a new
1842 : : * recovery target, if we shutdown and begin again. After this,
1843 : : * Resource Managers may choose to do permanent corrective actions
1844 : : * at end of recovery.
1845 : : */
1846 [ - + + - ]: 8 : switch (recoveryTargetAction)
1847 : : {
1848 : 0 : case RECOVERY_TARGET_ACTION_SHUTDOWN:
1849 : :
1850 : : /*
1851 : : * exit with special return code to request shutdown of
1852 : : * postmaster. Log messages issued from postmaster.
1853 : : */
1854 : 0 : proc_exit(3);
1855 : :
1856 : 1 : case RECOVERY_TARGET_ACTION_PAUSE:
1857 : 1 : SetRecoveryPause(true);
1858 : 1 : recoveryPausesHere(true);
1859 : :
1860 : : /* drop into promote */
1861 : : pg_fallthrough;
1862 : :
1863 : 8 : case RECOVERY_TARGET_ACTION_PROMOTE:
1864 : 8 : break;
1865 : : }
1866 : : }
1867 : :
1868 : 175 : RmgrCleanup();
1869 : :
1870 [ + - ]: 175 : ereport(LOG,
1871 : : errmsg("redo done at %X/%08X system usage: %s",
1872 : : LSN_FORMAT_ARGS(xlogreader->ReadRecPtr),
1873 : : pg_rusage_show(&ru0)));
1874 : 175 : xtime = GetLatestXTime();
1875 [ + + ]: 175 : if (xtime)
1876 [ + - ]: 47 : ereport(LOG,
1877 : : (errmsg("last completed transaction was at log time %s",
1878 : : timestamptz_to_str(xtime))));
1879 : :
1880 : 175 : InRedo = false;
1881 : : }
1882 : : else
1883 : : {
1884 : : /* there are no WAL records following the checkpoint */
1885 [ + - ]: 11 : ereport(LOG,
1886 : : (errmsg("redo is not required")));
1887 : : }
1888 : :
1889 : : /*
1890 : : * This check is intentionally after the above log messages that indicate
1891 : : * how far recovery went.
1892 : : */
1893 [ + + ]: 186 : if (ArchiveRecoveryRequested &&
1894 [ + + ]: 68 : recoveryTarget != RECOVERY_TARGET_UNSET &&
1895 [ + + ]: 9 : !reachedRecoveryTarget)
1896 [ + - ]: 1 : ereport(FATAL,
1897 : : (errcode(ERRCODE_CONFIG_FILE_ERROR),
1898 : : errmsg("recovery ended before configured recovery target was reached")));
1899 : 185 : }
1900 : :
1901 : : /*
1902 : : * Subroutine of PerformWalRecovery, to apply one WAL record.
1903 : : */
1904 : : static void
1905 : 2972473 : ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
1906 : : {
1907 : : ErrorContextCallback errcallback;
1908 : 2972473 : bool switchedTLI = false;
1909 : :
1910 : : /* Setup error traceback support for ereport() */
1911 : 2972473 : errcallback.callback = rm_redo_error_callback;
1912 : 2972473 : errcallback.arg = xlogreader;
1913 : 2972473 : errcallback.previous = error_context_stack;
1914 : 2972473 : error_context_stack = &errcallback;
1915 : :
1916 : : /*
1917 : : * TransamVariables->nextXid must be beyond record's xid.
1918 : : */
1919 : 2972473 : AdvanceNextFullTransactionIdPastXid(record->xl_xid);
1920 : :
1921 : : /*
1922 : : * Before replaying this record, check if this record causes the current
1923 : : * timeline to change. The record is already considered to be part of the
1924 : : * new timeline, so we update replayTLI before replaying it. That's
1925 : : * important so that replayEndTLI, which is recorded as the minimum
1926 : : * recovery point's TLI if recovery stops after this record, is set
1927 : : * correctly.
1928 : : */
1929 [ + + ]: 2972473 : if (record->xl_rmid == RM_XLOG_ID)
1930 : : {
1931 : 118428 : TimeLineID newReplayTLI = *replayTLI;
1932 : 118428 : TimeLineID prevReplayTLI = *replayTLI;
1933 : 118428 : uint8 info = record->xl_info & ~XLR_INFO_MASK;
1934 : :
1935 [ + + ]: 118428 : if (info == XLOG_CHECKPOINT_SHUTDOWN)
1936 : : {
1937 : : CheckPoint checkPoint;
1938 : :
1939 : 51 : memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
1940 : 51 : newReplayTLI = checkPoint.ThisTimeLineID;
1941 : 51 : prevReplayTLI = checkPoint.PrevTimeLineID;
1942 : : }
1943 [ + + ]: 118377 : else if (info == XLOG_END_OF_RECOVERY)
1944 : : {
1945 : : xl_end_of_recovery xlrec;
1946 : :
1947 : 15 : memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
1948 : 15 : newReplayTLI = xlrec.ThisTimeLineID;
1949 : 15 : prevReplayTLI = xlrec.PrevTimeLineID;
1950 : : }
1951 : :
1952 [ + + ]: 118428 : if (newReplayTLI != *replayTLI)
1953 : : {
1954 : : /* Check that it's OK to switch to this TLI */
1955 : 16 : checkTimeLineSwitch(xlogreader->EndRecPtr,
1956 : : newReplayTLI, prevReplayTLI, *replayTLI);
1957 : :
1958 : : /* Following WAL records should be run with new TLI */
1959 : 16 : *replayTLI = newReplayTLI;
1960 : 16 : switchedTLI = true;
1961 : : }
1962 : : }
1963 : :
1964 : : /*
1965 : : * Update shared replayEndRecPtr before replaying this record, so that
1966 : : * XLogFlush will update minRecoveryPoint correctly.
1967 : : */
1968 : 2972473 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
1969 : 2972473 : XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
1970 : 2972473 : XLogRecoveryCtl->replayEndTLI = *replayTLI;
1971 : 2972473 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
1972 : :
1973 : : /*
1974 : : * If we are attempting to enter Hot Standby mode, process XIDs we see
1975 : : */
1976 [ + + ]: 2972473 : if (standbyState >= STANDBY_INITIALIZED &&
1977 [ + + ]: 2663793 : TransactionIdIsValid(record->xl_xid))
1978 : 2599214 : RecordKnownAssignedTransactionIds(record->xl_xid);
1979 : :
1980 : : /*
1981 : : * Some XLOG record types that are related to recovery are processed
1982 : : * directly here, rather than in xlog_redo()
1983 : : */
1984 [ + + ]: 2972473 : if (record->xl_rmid == RM_XLOG_ID)
1985 : 118428 : xlogrecovery_redo(xlogreader, *replayTLI);
1986 : :
1987 : : /* Now apply the WAL record itself */
1988 : 2972473 : GetRmgr(record->xl_rmid).rm_redo(xlogreader);
1989 : :
1990 : : /*
1991 : : * After redo, check whether the backup pages associated with the WAL
1992 : : * record are consistent with the existing pages. This check is done only
1993 : : * if consistency check is enabled for this record.
1994 : : */
1995 [ + + ]: 2972471 : if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
1996 : 2275752 : verifyBackupPageConsistency(xlogreader);
1997 : :
1998 : : /* Pop the error context stack */
1999 : 2972471 : error_context_stack = errcallback.previous;
2000 : :
2001 : : /*
2002 : : * Update lastReplayedEndRecPtr after this record has been successfully
2003 : : * replayed.
2004 : : */
2005 : 2972471 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
2006 : 2972471 : XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
2007 : 2972471 : XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
2008 : 2972471 : XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
2009 : 2972471 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
2010 : :
2011 : : /* ------
2012 : : * Wakeup walsenders:
2013 : : *
2014 : : * On the standby, the WAL is flushed first (which will only wake up
2015 : : * physical walsenders) and then applied, which will only wake up logical
2016 : : * walsenders.
2017 : : *
2018 : : * Indeed, logical walsenders on standby can't decode and send data until
2019 : : * it's been applied.
2020 : : *
2021 : : * Physical walsenders don't need to be woken up during replay unless
2022 : : * cascading replication is allowed and time line change occurred (so that
2023 : : * they can notice that they are on a new time line).
2024 : : *
2025 : : * That's why the wake up conditions are for:
2026 : : *
2027 : : * - physical walsenders in case of new time line and cascade
2028 : : * replication is allowed
2029 : : * - logical walsenders in case cascade replication is allowed (could not
2030 : : * be created otherwise)
2031 : : * ------
2032 : : */
2033 [ + + + + ]: 2972471 : if (AllowCascadeReplication())
2034 : 2719980 : WalSndWakeup(switchedTLI, true);
2035 : :
2036 : : /*
2037 : : * If rm_redo called XLogRequestWalReceiverReply, then we wake up the
2038 : : * receiver so that it notices the updated lastReplayedEndRecPtr and sends
2039 : : * a reply to the primary.
2040 : : */
2041 [ + + ]: 2972471 : if (doRequestWalReceiverReply)
2042 : : {
2043 : 3 : doRequestWalReceiverReply = false;
2044 : 3 : WalRcvRequestApplyReply();
2045 : : }
2046 : :
2047 : : /* Allow read-only connections if we're consistent now */
2048 : 2972471 : CheckRecoveryConsistency();
2049 : :
2050 : : /* Is this a timeline switch? */
2051 [ + + ]: 2972471 : if (switchedTLI)
2052 : : {
2053 : : /*
2054 : : * Before we continue on the new timeline, clean up any (possibly
2055 : : * bogus) future WAL segments on the old timeline.
2056 : : */
2057 : 16 : RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
2058 : :
2059 : : /* Reset the prefetcher. */
2060 : 16 : XLogPrefetchReconfigure();
2061 : : }
2062 : 2972471 : }
2063 : :
2064 : : /*
2065 : : * Some XLOG RM record types that are directly related to WAL recovery are
2066 : : * handled here rather than in the xlog_redo()
2067 : : */
2068 : : static void
2069 : 118428 : xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI)
2070 : : {
2071 : 118428 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2072 : 118428 : XLogRecPtr lsn = record->EndRecPtr;
2073 : :
2074 : : Assert(XLogRecGetRmid(record) == RM_XLOG_ID);
2075 : :
2076 [ + + ]: 118428 : if (info == XLOG_OVERWRITE_CONTRECORD)
2077 : : {
2078 : : /* Verify the payload of a XLOG_OVERWRITE_CONTRECORD record. */
2079 : : xl_overwrite_contrecord xlrec;
2080 : :
2081 : 1 : memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_overwrite_contrecord));
2082 [ - + ]: 1 : if (xlrec.overwritten_lsn != record->overwrittenRecPtr)
2083 [ # # ]: 0 : elog(FATAL, "mismatching overwritten LSN %X/%08X -> %X/%08X",
2084 : : LSN_FORMAT_ARGS(xlrec.overwritten_lsn),
2085 : : LSN_FORMAT_ARGS(record->overwrittenRecPtr));
2086 : :
2087 : : /* We have safely skipped the aborted record */
2088 : 1 : abortedRecPtr = InvalidXLogRecPtr;
2089 : 1 : missingContrecPtr = InvalidXLogRecPtr;
2090 : :
2091 [ + - ]: 1 : ereport(LOG,
2092 : : errmsg("successfully skipped missing contrecord at %X/%08X, overwritten at %s",
2093 : : LSN_FORMAT_ARGS(xlrec.overwritten_lsn),
2094 : : timestamptz_to_str(xlrec.overwrite_time)));
2095 : :
2096 : : /* Verifying the record should only happen once */
2097 : 1 : record->overwrittenRecPtr = InvalidXLogRecPtr;
2098 : : }
2099 [ + + ]: 118427 : else if (info == XLOG_BACKUP_END)
2100 : : {
2101 : : XLogRecPtr startpoint;
2102 : :
2103 : 117 : memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));
2104 : :
2105 [ + + ]: 117 : if (backupStartPoint == startpoint)
2106 : : {
2107 : : /*
2108 : : * We have reached the end of base backup, the point where
2109 : : * pg_backup_stop() was done. The data on disk is now consistent
2110 : : * (assuming we have also reached minRecoveryPoint). Set
2111 : : * backupEndPoint to the current LSN, so that the next call to
2112 : : * CheckRecoveryConsistency() will notice it and do the
2113 : : * end-of-backup processing.
2114 : : */
2115 [ + + ]: 98 : elog(DEBUG1, "end of backup record reached");
2116 : :
2117 : 98 : backupEndPoint = lsn;
2118 : : }
2119 : : else
2120 [ + + ]: 19 : elog(DEBUG1, "saw end-of-backup record for backup starting at %X/%08X, waiting for %X/%08X",
2121 : : LSN_FORMAT_ARGS(startpoint), LSN_FORMAT_ARGS(backupStartPoint));
2122 : : }
2123 : 118428 : }
2124 : :
2125 : : /*
2126 : : * Verify that, in non-test mode, ./pg_tblspc doesn't contain any real
2127 : : * directories.
2128 : : *
2129 : : * Replay of database creation XLOG records for databases that were later
2130 : : * dropped can create fake directories in pg_tblspc. By the time consistency
2131 : : * is reached these directories should have been removed; here we verify
2132 : : * that this did indeed happen. This is to be called at the point where
2133 : : * consistent state is reached.
2134 : : *
2135 : : * allow_in_place_tablespaces turns the PANIC into a WARNING, which is
2136 : : * useful for testing purposes, and also allows for an escape hatch in case
2137 : : * things go south.
2138 : : */
2139 : : static void
2140 : 151 : CheckTablespaceDirectory(void)
2141 : : {
2142 : : DIR *dir;
2143 : : struct dirent *de;
2144 : :
2145 : 151 : dir = AllocateDir(PG_TBLSPC_DIR);
2146 [ + + ]: 460 : while ((de = ReadDir(dir, PG_TBLSPC_DIR)) != NULL)
2147 : : {
2148 : : char path[MAXPGPATH + sizeof(PG_TBLSPC_DIR)];
2149 : :
2150 : : /* Skip entries of non-oid names */
2151 [ + + ]: 309 : if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
2152 : 302 : continue;
2153 : :
2154 : 7 : snprintf(path, sizeof(path), "%s/%s", PG_TBLSPC_DIR, de->d_name);
2155 : :
2156 [ + + ]: 7 : if (get_dirent_type(path, de, false, ERROR) != PGFILETYPE_LNK)
2157 [ + - + - ]: 4 : ereport(allow_in_place_tablespaces ? WARNING : PANIC,
2158 : : (errcode(ERRCODE_DATA_CORRUPTED),
2159 : : errmsg("unexpected directory entry \"%s\" found in %s",
2160 : : de->d_name, PG_TBLSPC_DIR),
2161 : : errdetail("All directory entries in %s/ should be symbolic links.",
2162 : : PG_TBLSPC_DIR),
2163 : : errhint("Remove those directories, or set \"allow_in_place_tablespaces\" to ON transiently to let recovery complete.")));
2164 : : }
2165 : 151 : FreeDir(dir);
2166 : 151 : }
2167 : :
2168 : : /*
2169 : : * Checks if recovery has reached a consistent state. When consistency is
2170 : : * reached and we have a valid starting standby snapshot, tell postmaster
2171 : : * that it can start accepting read-only connections.
2172 : : */
2173 : : static void
2174 : 2972731 : CheckRecoveryConsistency(void)
2175 : : {
2176 : : XLogRecPtr lastReplayedEndRecPtr;
2177 : : TimeLineID lastReplayedTLI;
2178 : :
2179 : : /*
2180 : : * During crash recovery, we don't reach a consistent state until we've
2181 : : * replayed all the WAL.
2182 : : */
2183 [ + + ]: 2972731 : if (!XLogRecPtrIsValid(minRecoveryPoint))
2184 : 323411 : return;
2185 : :
2186 : : Assert(InArchiveRecovery);
2187 : :
2188 : : /*
2189 : : * assume that we are called in the startup process, and hence don't need
2190 : : * a lock to read lastReplayedEndRecPtr
2191 : : */
2192 : 2649320 : lastReplayedEndRecPtr = XLogRecoveryCtl->lastReplayedEndRecPtr;
2193 : 2649320 : lastReplayedTLI = XLogRecoveryCtl->lastReplayedTLI;
2194 : :
2195 : : /*
2196 : : * Have we reached the point where our base backup was completed?
2197 : : */
2198 [ + + ]: 2649320 : if (XLogRecPtrIsValid(backupEndPoint) &&
2199 [ + + ]: 5308 : backupEndPoint <= lastReplayedEndRecPtr)
2200 : : {
2201 : 103 : XLogRecPtr saveBackupStartPoint = backupStartPoint;
2202 : 103 : XLogRecPtr saveBackupEndPoint = backupEndPoint;
2203 : :
2204 [ + + ]: 103 : elog(DEBUG1, "end of backup reached");
2205 : :
2206 : : /*
2207 : : * We have reached the end of base backup, as indicated by pg_control.
2208 : : * Update the control file accordingly.
2209 : : */
2210 : 103 : ReachedEndOfBackup(lastReplayedEndRecPtr, lastReplayedTLI);
2211 : 103 : backupStartPoint = InvalidXLogRecPtr;
2212 : 103 : backupEndPoint = InvalidXLogRecPtr;
2213 : 103 : backupEndRequired = false;
2214 : :
2215 [ + - ]: 103 : ereport(LOG,
2216 : : errmsg("completed backup recovery with redo LSN %X/%08X and end LSN %X/%08X",
2217 : : LSN_FORMAT_ARGS(saveBackupStartPoint),
2218 : : LSN_FORMAT_ARGS(saveBackupEndPoint)));
2219 : : }
2220 : :
2221 : : /*
2222 : : * Have we passed our safe starting point? Note that minRecoveryPoint is
2223 : : * known to be incorrectly set if recovering from a backup, until the
2224 : : * XLOG_BACKUP_END arrives to advise us of the correct minRecoveryPoint.
2225 : : * All we know prior to that is that we're not consistent yet.
2226 : : */
2227 [ + + + + ]: 2649320 : if (!reachedConsistency && !backupEndRequired &&
2228 [ + + ]: 14885 : minRecoveryPoint <= lastReplayedEndRecPtr)
2229 : : {
2230 : : /*
2231 : : * Check to see if the XLOG sequence contained any unresolved
2232 : : * references to uninitialized pages.
2233 : : */
2234 : 151 : XLogCheckInvalidPages();
2235 : :
2236 : : /*
2237 : : * Check that pg_tblspc doesn't contain any real directories. Replay
2238 : : * of Database/CREATE_* records may have created fictitious tablespace
2239 : : * directories that should have been removed by the time consistency
2240 : : * was reached.
2241 : : */
2242 : 151 : CheckTablespaceDirectory();
2243 : :
2244 : 151 : reachedConsistency = true;
2245 : 151 : SendPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT);
2246 [ + - ]: 151 : ereport(LOG,
2247 : : errmsg("consistent recovery state reached at %X/%08X",
2248 : : LSN_FORMAT_ARGS(lastReplayedEndRecPtr)));
2249 : : }
2250 : :
2251 : : /*
2252 : : * Have we got a valid starting snapshot that will allow queries to be
2253 : : * run? If so, we can tell postmaster that the database is consistent now,
2254 : : * enabling connections.
2255 : : */
2256 [ + + ]: 2649320 : if (standbyState == STANDBY_SNAPSHOT_READY &&
2257 [ + + + + ]: 2649016 : !LocalHotStandbyActive &&
2258 [ + - ]: 139 : reachedConsistency &&
2259 : : IsUnderPostmaster)
2260 : : {
2261 : 139 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
2262 : 139 : XLogRecoveryCtl->SharedHotStandbyActive = true;
2263 : 139 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
2264 : :
2265 : 139 : LocalHotStandbyActive = true;
2266 : :
2267 : 139 : SendPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY);
2268 : : }
2269 : : }
2270 : :
2271 : : /*
2272 : : * Error context callback for errors occurring during rm_redo().
2273 : : */
2274 : : static void
2275 : 189 : rm_redo_error_callback(void *arg)
2276 : : {
2277 : 189 : XLogReaderState *record = (XLogReaderState *) arg;
2278 : : StringInfoData buf;
2279 : :
2280 : 189 : initStringInfo(&buf);
2281 : 189 : xlog_outdesc(&buf, record);
2282 : 189 : xlog_block_info(&buf, record);
2283 : :
2284 : : /* translator: %s is a WAL record description */
2285 : 189 : errcontext("WAL redo at %X/%08X for %s",
2286 : 189 : LSN_FORMAT_ARGS(record->ReadRecPtr),
2287 : : buf.data);
2288 : :
2289 : 189 : pfree(buf.data);
2290 : 189 : }
2291 : :
2292 : : /*
2293 : : * Returns a string describing an XLogRecord, consisting of its identity
2294 : : * optionally followed by a colon, a space, and a further description.
2295 : : */
2296 : : void
2297 : 189 : xlog_outdesc(StringInfo buf, XLogReaderState *record)
2298 : : {
2299 : 189 : RmgrData rmgr = GetRmgr(XLogRecGetRmid(record));
2300 : 189 : uint8 info = XLogRecGetInfo(record);
2301 : : const char *id;
2302 : :
2303 : 189 : appendStringInfoString(buf, rmgr.rm_name);
2304 : 189 : appendStringInfoChar(buf, '/');
2305 : :
2306 : 189 : id = rmgr.rm_identify(info);
2307 [ - + ]: 189 : if (id == NULL)
2308 : 0 : appendStringInfo(buf, "UNKNOWN (%X): ", info & ~XLR_INFO_MASK);
2309 : : else
2310 : 189 : appendStringInfo(buf, "%s: ", id);
2311 : :
2312 : 189 : rmgr.rm_desc(buf, record);
2313 : 189 : }
2314 : :
2315 : : #ifdef WAL_DEBUG
2316 : :
2317 : : static void
2318 : : xlog_outrec(StringInfo buf, XLogReaderState *record)
2319 : : {
2320 : : appendStringInfo(buf, "prev %X/%08X; xid %u",
2321 : : LSN_FORMAT_ARGS(XLogRecGetPrev(record)),
2322 : : XLogRecGetXid(record));
2323 : :
2324 : : appendStringInfo(buf, "; len %u",
2325 : : XLogRecGetDataLen(record));
2326 : :
2327 : : xlog_block_info(buf, record);
2328 : : }
2329 : : #endif /* WAL_DEBUG */
2330 : :
2331 : : /*
2332 : : * Returns a string giving information about all the blocks in an
2333 : : * XLogRecord.
2334 : : */
2335 : : static void
2336 : 189 : xlog_block_info(StringInfo buf, XLogReaderState *record)
2337 : : {
2338 : : int block_id;
2339 : :
2340 : : /* decode block references */
2341 [ + + ]: 239 : for (block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
2342 : : {
2343 : : RelFileLocator rlocator;
2344 : : ForkNumber forknum;
2345 : : BlockNumber blk;
2346 : :
2347 [ - + ]: 50 : if (!XLogRecGetBlockTagExtended(record, block_id,
2348 : : &rlocator, &forknum, &blk, NULL))
2349 : 0 : continue;
2350 : :
2351 [ + + ]: 50 : if (forknum != MAIN_FORKNUM)
2352 : 8 : appendStringInfo(buf, "; blkref #%d: rel %u/%u/%u, fork %u, blk %u",
2353 : : block_id,
2354 : : rlocator.spcOid, rlocator.dbOid,
2355 : : rlocator.relNumber,
2356 : : forknum,
2357 : : blk);
2358 : : else
2359 : 42 : appendStringInfo(buf, "; blkref #%d: rel %u/%u/%u, blk %u",
2360 : : block_id,
2361 : : rlocator.spcOid, rlocator.dbOid,
2362 : : rlocator.relNumber,
2363 : : blk);
2364 [ + + ]: 50 : if (XLogRecHasBlockImage(record, block_id))
2365 : 29 : appendStringInfoString(buf, " FPW");
2366 : : }
2367 : 189 : }
2368 : :
2369 : :
2370 : : /*
2371 : : * Check that it's OK to switch to new timeline during recovery.
2372 : : *
2373 : : * 'lsn' is the address of the shutdown checkpoint record we're about to
2374 : : * replay. (Currently, timeline can only change at a shutdown checkpoint).
2375 : : */
2376 : : static void
2377 : 16 : checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI, TimeLineID prevTLI,
2378 : : TimeLineID replayTLI)
2379 : : {
2380 : : /* Check that the record agrees on what the current (old) timeline is */
2381 [ - + ]: 16 : if (prevTLI != replayTLI)
2382 [ # # ]: 0 : ereport(PANIC,
2383 : : (errmsg("unexpected previous timeline ID %u (current timeline ID %u) in checkpoint record",
2384 : : prevTLI, replayTLI)));
2385 : :
2386 : : /*
2387 : : * The new timeline better be in the list of timelines we expect to see,
2388 : : * according to the timeline history. It should also not decrease.
2389 : : */
2390 [ + - - + ]: 16 : if (newTLI < replayTLI || !tliInHistory(newTLI, expectedTLEs))
2391 [ # # ]: 0 : ereport(PANIC,
2392 : : (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
2393 : : newTLI, replayTLI)));
2394 : :
2395 : : /*
2396 : : * If we have not yet reached min recovery point, and we're about to
2397 : : * switch to a timeline greater than the timeline of the min recovery
2398 : : * point: trouble. After switching to the new timeline, we could not
2399 : : * possibly visit the min recovery point on the correct timeline anymore.
2400 : : * This can happen if there is a newer timeline in the archive that
2401 : : * branched before the timeline the min recovery point is on, and you
2402 : : * attempt to do PITR to the new timeline.
2403 : : */
2404 [ + + ]: 16 : if (XLogRecPtrIsValid(minRecoveryPoint) &&
2405 [ + + ]: 14 : lsn < minRecoveryPoint &&
2406 [ - + ]: 3 : newTLI > minRecoveryPointTLI)
2407 [ # # ]: 0 : ereport(PANIC,
2408 : : errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%08X on timeline %u",
2409 : : newTLI,
2410 : : LSN_FORMAT_ARGS(minRecoveryPoint),
2411 : : minRecoveryPointTLI));
2412 : :
2413 : : /* Looks good */
2414 : 16 : }
2415 : :
2416 : :
2417 : : /*
2418 : : * Extract timestamp from WAL record.
2419 : : *
2420 : : * If the record contains a timestamp, returns true, and saves the timestamp
2421 : : * in *recordXtime. If the record type has no timestamp, returns false.
2422 : : * Currently, only transaction commit/abort records and restore points contain
2423 : : * timestamps.
2424 : : */
2425 : : static bool
2426 : 49000 : getRecordTimestamp(XLogReaderState *record, TimestampTz *recordXtime)
2427 : : {
2428 : 49000 : uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2429 : 49000 : uint8 xact_info = info & XLOG_XACT_OPMASK;
2430 : 49000 : uint8 rmid = XLogRecGetRmid(record);
2431 : :
2432 [ + + + - ]: 49000 : if (rmid == RM_XLOG_ID && info == XLOG_RESTORE_POINT)
2433 : : {
2434 : 2 : *recordXtime = ((xl_restore_point *) XLogRecGetData(record))->rp_time;
2435 : 2 : return true;
2436 : : }
2437 [ + - + + : 48998 : if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_COMMIT ||
+ + ]
2438 : : xact_info == XLOG_XACT_COMMIT_PREPARED))
2439 : : {
2440 : 44682 : *recordXtime = ((xl_xact_commit *) XLogRecGetData(record))->xact_time;
2441 : 44682 : return true;
2442 : : }
2443 [ + - + + : 4316 : if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_ABORT ||
+ - ]
2444 : : xact_info == XLOG_XACT_ABORT_PREPARED))
2445 : : {
2446 : 4316 : *recordXtime = ((xl_xact_abort *) XLogRecGetData(record))->xact_time;
2447 : 4316 : return true;
2448 : : }
2449 : 0 : return false;
2450 : : }
2451 : :
2452 : : /*
2453 : : * Checks whether the current buffer page and backup page stored in the
2454 : : * WAL record are consistent or not. Before comparing the two pages, a
2455 : : * masking can be applied to the pages to ignore certain areas like hint bits,
2456 : : * unused space between pd_lower and pd_upper among other things. This
2457 : : * function should be called once WAL replay has been completed for a
2458 : : * given record.
2459 : : */
2460 : : static void
2461 : 2275752 : verifyBackupPageConsistency(XLogReaderState *record)
2462 : : {
2463 : 2275752 : RmgrData rmgr = GetRmgr(XLogRecGetRmid(record));
2464 : : RelFileLocator rlocator;
2465 : : ForkNumber forknum;
2466 : : BlockNumber blkno;
2467 : : int block_id;
2468 : :
2469 : : /* Records with no backup blocks have no need for consistency checks. */
2470 [ + + ]: 2275752 : if (!XLogRecHasAnyBlockRefs(record))
2471 : 88 : return;
2472 : :
2473 : : Assert((XLogRecGetInfo(record) & XLR_CHECK_CONSISTENCY) != 0);
2474 : :
2475 [ + + ]: 4721323 : for (block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
2476 : : {
2477 : : Buffer buf;
2478 : : Page page;
2479 : :
2480 [ + + ]: 2445659 : if (!XLogRecGetBlockTagExtended(record, block_id,
2481 : : &rlocator, &forknum, &blkno, NULL))
2482 : : {
2483 : : /*
2484 : : * WAL record doesn't contain a block reference with the given id.
2485 : : * Do nothing.
2486 : : */
2487 : 2521 : continue;
2488 : : }
2489 : :
2490 : : /*
2491 : : * Blocks registered with REGBUF_NO_CHANGE may have no image, see
2492 : : * XLogRecordAssemble(). Nothing to compare for these.
2493 : : */
2494 [ + + ]: 2443138 : if (!XLogRecHasBlockImage(record, block_id))
2495 : 75 : continue;
2496 : :
2497 [ + + ]: 2443063 : if (XLogRecBlockImageApply(record, block_id))
2498 : : {
2499 : : /*
2500 : : * WAL record has already applied the page, so bypass the
2501 : : * consistency check as that would result in comparing the full
2502 : : * page stored in the record with itself.
2503 : : */
2504 : 29141 : continue;
2505 : : }
2506 : :
2507 : : /*
2508 : : * Read the contents from the current buffer and store it in a
2509 : : * temporary page.
2510 : : */
2511 : 2413922 : buf = XLogReadBufferExtended(rlocator, forknum, blkno,
2512 : : RBM_NORMAL_NO_LOG,
2513 : : InvalidBuffer);
2514 [ - + ]: 2413922 : if (!BufferIsValid(buf))
2515 : 0 : continue;
2516 : :
2517 : 2413922 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
2518 : 2413922 : page = BufferGetPage(buf);
2519 : :
2520 : : /*
2521 : : * Take a copy of the local page where WAL has been applied to have a
2522 : : * comparison base before masking it...
2523 : : */
2524 : 2413922 : memcpy(replay_image_masked, page, BLCKSZ);
2525 : :
2526 : : /* No need for this page anymore now that a copy is in. */
2527 : 2413922 : UnlockReleaseBuffer(buf);
2528 : :
2529 : : /*
2530 : : * If the block LSN is already ahead of this WAL record, we can't
2531 : : * expect contents to match. This can happen if recovery is
2532 : : * restarted.
2533 : : */
2534 [ - + ]: 2413922 : if (PageGetLSN(replay_image_masked) > record->EndRecPtr)
2535 : 0 : continue;
2536 : :
2537 : : /*
2538 : : * Read the contents from the backup copy, stored in WAL record and
2539 : : * store it in a temporary page. There is no need to allocate a new
2540 : : * page here, a local buffer is fine to hold its contents and a mask
2541 : : * can be directly applied on it.
2542 : : */
2543 [ - + ]: 2413922 : if (!RestoreBlockImage(record, block_id, primary_image_masked))
2544 [ # # ]: 0 : ereport(ERROR,
2545 : : (errcode(ERRCODE_INTERNAL_ERROR),
2546 : : errmsg_internal("%s", record->errormsg_buf)));
2547 : :
2548 : : /*
2549 : : * If masking function is defined, mask both the primary and replay
2550 : : * images
2551 : : */
2552 [ + - ]: 2413922 : if (rmgr.rm_mask != NULL)
2553 : : {
2554 : 2413922 : rmgr.rm_mask(replay_image_masked, blkno);
2555 : 2413922 : rmgr.rm_mask(primary_image_masked, blkno);
2556 : : }
2557 : :
2558 : : /* Time to compare the primary and replay images. */
2559 [ - + ]: 2413922 : if (memcmp(replay_image_masked, primary_image_masked, BLCKSZ) != 0)
2560 : : {
2561 [ # # ]: 0 : elog(FATAL,
2562 : : "inconsistent page found, rel %u/%u/%u, forknum %u, blkno %u",
2563 : : rlocator.spcOid, rlocator.dbOid, rlocator.relNumber,
2564 : : forknum, blkno);
2565 : : }
2566 : : }
2567 : : }
2568 : :
2569 : : /*
2570 : : * For point-in-time recovery, this function decides whether we want to
2571 : : * stop applying the XLOG before the current record.
2572 : : *
2573 : : * Returns true if we are stopping, false otherwise. If stopping, some
2574 : : * information is saved in recoveryStopXid et al for use in annotating the
2575 : : * new timeline's history file.
2576 : : */
2577 : : static bool
2578 : 2972476 : recoveryStopsBefore(XLogReaderState *record)
2579 : : {
2580 : 2972476 : bool stopsHere = false;
2581 : : uint8 xact_info;
2582 : : bool isCommit;
2583 : 2972476 : TimestampTz recordXtime = 0;
2584 : : TransactionId recordXid;
2585 : :
2586 : : /*
2587 : : * Ignore recovery target settings when not in archive recovery (meaning
2588 : : * we are in crash recovery).
2589 : : */
2590 [ + + ]: 2972476 : if (!ArchiveRecoveryRequested)
2591 : 308666 : return false;
2592 : :
2593 : : /* Check if we should stop as soon as reaching consistency */
2594 [ - + - - ]: 2663810 : if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
2595 : : {
2596 [ # # ]: 0 : ereport(LOG,
2597 : : (errmsg("recovery stopping after reaching consistency")));
2598 : :
2599 : 0 : recoveryStopAfter = false;
2600 : 0 : recoveryStopXid = InvalidTransactionId;
2601 : 0 : recoveryStopLSN = InvalidXLogRecPtr;
2602 : 0 : recoveryStopTime = 0;
2603 : 0 : recoveryStopName[0] = '\0';
2604 : 0 : return true;
2605 : : }
2606 : :
2607 : : /* Check if target LSN has been reached */
2608 [ + + ]: 2663810 : if (recoveryTarget == RECOVERY_TARGET_LSN &&
2609 [ + + ]: 8626 : !recoveryTargetInclusive &&
2610 [ + + ]: 597 : record->ReadRecPtr >= recoveryTargetLSN)
2611 : : {
2612 : 3 : recoveryStopAfter = false;
2613 : 3 : recoveryStopXid = InvalidTransactionId;
2614 : 3 : recoveryStopLSN = record->ReadRecPtr;
2615 : 3 : recoveryStopTime = 0;
2616 : 3 : recoveryStopName[0] = '\0';
2617 [ + - ]: 3 : ereport(LOG,
2618 : : errmsg("recovery stopping before WAL location (LSN) \"%X/%08X\"",
2619 : : LSN_FORMAT_ARGS(recoveryStopLSN)));
2620 : 3 : return true;
2621 : : }
2622 : :
2623 : : /* Otherwise we only consider stopping before COMMIT or ABORT records. */
2624 [ + + ]: 2663807 : if (XLogRecGetRmid(record) != RM_XACT_ID)
2625 : 2638991 : return false;
2626 : :
2627 : 24816 : xact_info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
2628 : :
2629 [ + + ]: 24816 : if (xact_info == XLOG_XACT_COMMIT)
2630 : : {
2631 : 22301 : isCommit = true;
2632 : 22301 : recordXid = XLogRecGetXid(record);
2633 : : }
2634 [ + + ]: 2515 : else if (xact_info == XLOG_XACT_COMMIT_PREPARED)
2635 : : {
2636 : 26 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
2637 : : xl_xact_parsed_commit parsed;
2638 : :
2639 : 26 : isCommit = true;
2640 : 26 : ParseCommitRecord(XLogRecGetInfo(record),
2641 : : xlrec,
2642 : : &parsed);
2643 : 26 : recordXid = parsed.twophase_xid;
2644 : : }
2645 [ + + ]: 2489 : else if (xact_info == XLOG_XACT_ABORT)
2646 : : {
2647 : 2143 : isCommit = false;
2648 : 2143 : recordXid = XLogRecGetXid(record);
2649 : : }
2650 [ + + ]: 346 : else if (xact_info == XLOG_XACT_ABORT_PREPARED)
2651 : : {
2652 : 15 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
2653 : : xl_xact_parsed_abort parsed;
2654 : :
2655 : 15 : isCommit = false;
2656 : 15 : ParseAbortRecord(XLogRecGetInfo(record),
2657 : : xlrec,
2658 : : &parsed);
2659 : 15 : recordXid = parsed.twophase_xid;
2660 : : }
2661 : : else
2662 : 331 : return false;
2663 : :
2664 [ - + - - ]: 24485 : if (recoveryTarget == RECOVERY_TARGET_XID && !recoveryTargetInclusive)
2665 : : {
2666 : : /*
2667 : : * There can be only one transaction end record with this exact
2668 : : * transactionid
2669 : : *
2670 : : * when testing for an xid, we MUST test for equality only, since
2671 : : * transactions are numbered in the order they start, not the order
2672 : : * they complete. A higher numbered xid will complete before you about
2673 : : * 50% of the time...
2674 : : */
2675 : 0 : stopsHere = (recordXid == recoveryTargetXid);
2676 : : }
2677 : :
2678 : : /*
2679 : : * Note: we must fetch recordXtime regardless of recoveryTarget setting.
2680 : : * We don't expect getRecordTimestamp ever to fail, since we already know
2681 : : * this is a commit or abort record; but test its result anyway.
2682 : : */
2683 [ + - ]: 24485 : if (getRecordTimestamp(record, &recordXtime) &&
2684 [ - + ]: 24485 : recoveryTarget == RECOVERY_TARGET_TIME)
2685 : : {
2686 : : /*
2687 : : * There can be many transactions that share the same commit time, so
2688 : : * we stop after the last one, if we are inclusive, or stop at the
2689 : : * first one if we are exclusive
2690 : : */
2691 [ # # ]: 0 : if (recoveryTargetInclusive)
2692 : 0 : stopsHere = (recordXtime > recoveryTargetTime);
2693 : : else
2694 : 0 : stopsHere = (recordXtime >= recoveryTargetTime);
2695 : : }
2696 : :
2697 [ - + ]: 24485 : if (stopsHere)
2698 : : {
2699 : 0 : recoveryStopAfter = false;
2700 : 0 : recoveryStopXid = recordXid;
2701 : 0 : recoveryStopTime = recordXtime;
2702 : 0 : recoveryStopLSN = InvalidXLogRecPtr;
2703 : 0 : recoveryStopName[0] = '\0';
2704 : :
2705 [ # # ]: 0 : if (isCommit)
2706 : : {
2707 [ # # ]: 0 : ereport(LOG,
2708 : : (errmsg("recovery stopping before commit of transaction %u, time %s",
2709 : : recoveryStopXid,
2710 : : timestamptz_to_str(recoveryStopTime))));
2711 : : }
2712 : : else
2713 : : {
2714 [ # # ]: 0 : ereport(LOG,
2715 : : (errmsg("recovery stopping before abort of transaction %u, time %s",
2716 : : recoveryStopXid,
2717 : : timestamptz_to_str(recoveryStopTime))));
2718 : : }
2719 : : }
2720 : :
2721 : 24485 : return stopsHere;
2722 : : }
2723 : :
2724 : : /*
2725 : : * Same as recoveryStopsBefore, but called after applying the record.
2726 : : *
2727 : : * We also track the timestamp of the latest applied COMMIT/ABORT
2728 : : * record in XLogRecoveryCtl->recoveryLastXTime.
2729 : : */
2730 : : static bool
2731 : 2972471 : recoveryStopsAfter(XLogReaderState *record)
2732 : : {
2733 : : uint8 info;
2734 : : uint8 xact_info;
2735 : : uint8 rmid;
2736 : 2972471 : TimestampTz recordXtime = 0;
2737 : :
2738 : : /*
2739 : : * Ignore recovery target settings when not in archive recovery (meaning
2740 : : * we are in crash recovery).
2741 : : */
2742 [ + + ]: 2972471 : if (!ArchiveRecoveryRequested)
2743 : 308666 : return false;
2744 : :
2745 : 2663805 : info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2746 : 2663805 : rmid = XLogRecGetRmid(record);
2747 : :
2748 : : /*
2749 : : * There can be many restore points that share the same name; we stop at
2750 : : * the first one.
2751 : : */
2752 [ + + + + ]: 2663805 : if (recoveryTarget == RECOVERY_TARGET_NAME &&
2753 [ + + ]: 20 : rmid == RM_XLOG_ID && info == XLOG_RESTORE_POINT)
2754 : : {
2755 : : xl_restore_point *recordRestorePointData;
2756 : :
2757 : 3 : recordRestorePointData = (xl_restore_point *) XLogRecGetData(record);
2758 : :
2759 [ + + ]: 3 : if (strcmp(recordRestorePointData->rp_name, recoveryTargetName) == 0)
2760 : : {
2761 : 2 : recoveryStopAfter = true;
2762 : 2 : recoveryStopXid = InvalidTransactionId;
2763 : 2 : recoveryStopLSN = InvalidXLogRecPtr;
2764 : 2 : (void) getRecordTimestamp(record, &recoveryStopTime);
2765 : 2 : strlcpy(recoveryStopName, recordRestorePointData->rp_name, MAXFNAMELEN);
2766 : :
2767 [ + - ]: 2 : ereport(LOG,
2768 : : (errmsg("recovery stopping at restore point \"%s\", time %s",
2769 : : recoveryStopName,
2770 : : timestamptz_to_str(recoveryStopTime))));
2771 : 2 : return true;
2772 : : }
2773 : : }
2774 : :
2775 : : /* Check if the target LSN has been reached */
2776 [ + + + + ]: 2663803 : if (recoveryTarget == RECOVERY_TARGET_LSN &&
2777 : 8029 : recoveryTargetInclusive &&
2778 [ + + ]: 8029 : record->ReadRecPtr >= recoveryTargetLSN)
2779 : : {
2780 : 3 : recoveryStopAfter = true;
2781 : 3 : recoveryStopXid = InvalidTransactionId;
2782 : 3 : recoveryStopLSN = record->ReadRecPtr;
2783 : 3 : recoveryStopTime = 0;
2784 : 3 : recoveryStopName[0] = '\0';
2785 [ + - ]: 3 : ereport(LOG,
2786 : : errmsg("recovery stopping after WAL location (LSN) \"%X/%08X\"",
2787 : : LSN_FORMAT_ARGS(recoveryStopLSN)));
2788 : 3 : return true;
2789 : : }
2790 : :
2791 [ + + ]: 2663800 : if (rmid != RM_XACT_ID)
2792 : 2638986 : return false;
2793 : :
2794 : 24814 : xact_info = info & XLOG_XACT_OPMASK;
2795 : :
2796 [ + + + + ]: 24814 : if (xact_info == XLOG_XACT_COMMIT ||
2797 [ + + ]: 2489 : xact_info == XLOG_XACT_COMMIT_PREPARED ||
2798 [ + + ]: 346 : xact_info == XLOG_XACT_ABORT ||
2799 : : xact_info == XLOG_XACT_ABORT_PREPARED)
2800 : : {
2801 : : TransactionId recordXid;
2802 : :
2803 : : /* Update the last applied transaction timestamp */
2804 [ + - ]: 24483 : if (getRecordTimestamp(record, &recordXtime))
2805 : 24483 : SetLatestXTime(recordXtime);
2806 : :
2807 : : /* Extract the XID of the committed/aborted transaction */
2808 [ + + ]: 24483 : if (xact_info == XLOG_XACT_COMMIT_PREPARED)
2809 : : {
2810 : 26 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
2811 : : xl_xact_parsed_commit parsed;
2812 : :
2813 : 26 : ParseCommitRecord(XLogRecGetInfo(record),
2814 : : xlrec,
2815 : : &parsed);
2816 : 26 : recordXid = parsed.twophase_xid;
2817 : : }
2818 [ + + ]: 24457 : else if (xact_info == XLOG_XACT_ABORT_PREPARED)
2819 : : {
2820 : 15 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
2821 : : xl_xact_parsed_abort parsed;
2822 : :
2823 : 15 : ParseAbortRecord(XLogRecGetInfo(record),
2824 : : xlrec,
2825 : : &parsed);
2826 : 15 : recordXid = parsed.twophase_xid;
2827 : : }
2828 : : else
2829 : 24442 : recordXid = XLogRecGetXid(record);
2830 : :
2831 : : /*
2832 : : * There can be only one transaction end record with this exact
2833 : : * transactionid
2834 : : *
2835 : : * when testing for an xid, we MUST test for equality only, since
2836 : : * transactions are numbered in the order they start, not the order
2837 : : * they complete. A higher numbered xid will complete before you about
2838 : : * 50% of the time...
2839 : : */
2840 [ - + - - ]: 24483 : if (recoveryTarget == RECOVERY_TARGET_XID && recoveryTargetInclusive &&
2841 [ # # ]: 0 : recordXid == recoveryTargetXid)
2842 : : {
2843 : 0 : recoveryStopAfter = true;
2844 : 0 : recoveryStopXid = recordXid;
2845 : 0 : recoveryStopTime = recordXtime;
2846 : 0 : recoveryStopLSN = InvalidXLogRecPtr;
2847 : 0 : recoveryStopName[0] = '\0';
2848 : :
2849 [ # # # # ]: 0 : if (xact_info == XLOG_XACT_COMMIT ||
2850 : : xact_info == XLOG_XACT_COMMIT_PREPARED)
2851 : : {
2852 [ # # ]: 0 : ereport(LOG,
2853 : : (errmsg("recovery stopping after commit of transaction %u, time %s",
2854 : : recoveryStopXid,
2855 : : timestamptz_to_str(recoveryStopTime))));
2856 : : }
2857 [ # # # # ]: 0 : else if (xact_info == XLOG_XACT_ABORT ||
2858 : : xact_info == XLOG_XACT_ABORT_PREPARED)
2859 : : {
2860 [ # # ]: 0 : ereport(LOG,
2861 : : (errmsg("recovery stopping after abort of transaction %u, time %s",
2862 : : recoveryStopXid,
2863 : : timestamptz_to_str(recoveryStopTime))));
2864 : : }
2865 : 0 : return true;
2866 : : }
2867 : : }
2868 : :
2869 : : /* Check if we should stop as soon as reaching consistency */
2870 [ - + - - ]: 24814 : if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
2871 : : {
2872 [ # # ]: 0 : ereport(LOG,
2873 : : (errmsg("recovery stopping after reaching consistency")));
2874 : :
2875 : 0 : recoveryStopAfter = true;
2876 : 0 : recoveryStopXid = InvalidTransactionId;
2877 : 0 : recoveryStopTime = 0;
2878 : 0 : recoveryStopLSN = InvalidXLogRecPtr;
2879 : 0 : recoveryStopName[0] = '\0';
2880 : 0 : return true;
2881 : : }
2882 : :
2883 : 24814 : return false;
2884 : : }
2885 : :
2886 : : /*
2887 : : * Create a comment for the history file to explain why and where
2888 : : * timeline changed.
2889 : : */
2890 : : static char *
2891 : 1101 : getRecoveryStopReason(void)
2892 : : {
2893 : : char reason[200];
2894 : :
2895 [ - + ]: 1101 : if (recoveryTarget == RECOVERY_TARGET_XID)
2896 : 0 : snprintf(reason, sizeof(reason),
2897 : : "%s transaction %u",
2898 [ # # ]: 0 : recoveryStopAfter ? "after" : "before",
2899 : : recoveryStopXid);
2900 [ - + ]: 1101 : else if (recoveryTarget == RECOVERY_TARGET_TIME)
2901 : 0 : snprintf(reason, sizeof(reason),
2902 : : "%s %s\n",
2903 [ # # ]: 0 : recoveryStopAfter ? "after" : "before",
2904 : : timestamptz_to_str(recoveryStopTime));
2905 [ + + ]: 1101 : else if (recoveryTarget == RECOVERY_TARGET_LSN)
2906 : 8 : snprintf(reason, sizeof(reason),
2907 : : "%s LSN %X/%08X\n",
2908 : 8 : recoveryStopAfter ? "after" : "before",
2909 [ + + ]: 8 : LSN_FORMAT_ARGS(recoveryStopLSN));
2910 [ + + ]: 1093 : else if (recoveryTarget == RECOVERY_TARGET_NAME)
2911 : 3 : snprintf(reason, sizeof(reason),
2912 : : "at restore point \"%s\"",
2913 : : recoveryStopName);
2914 [ - + ]: 1090 : else if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE)
2915 : 0 : snprintf(reason, sizeof(reason), "reached consistency");
2916 : : else
2917 : 1090 : snprintf(reason, sizeof(reason), "no recovery target specified");
2918 : :
2919 : 1101 : return pstrdup(reason);
2920 : : }
2921 : :
2922 : : /*
2923 : : * Wait until shared recoveryPauseState is set to RECOVERY_NOT_PAUSED.
2924 : : *
2925 : : * endOfRecovery is true if the recovery target is reached and
2926 : : * the paused state starts at the end of recovery because of
2927 : : * recovery_target_action=pause, and false otherwise.
2928 : : */
2929 : : static void
2930 : 10 : recoveryPausesHere(bool endOfRecovery)
2931 : : {
2932 : : /* Don't pause unless users can connect! */
2933 [ - + ]: 10 : if (!LocalHotStandbyActive)
2934 : 0 : return;
2935 : :
2936 : : /* Don't pause after standby promotion has been triggered */
2937 [ - + ]: 10 : if (LocalPromoteIsTriggered)
2938 : 0 : return;
2939 : :
2940 [ + + ]: 10 : if (endOfRecovery)
2941 [ + - ]: 1 : ereport(LOG,
2942 : : (errmsg("pausing at the end of recovery"),
2943 : : errhint("Execute pg_wal_replay_resume() to promote.")));
2944 : : else
2945 [ + - ]: 9 : ereport(LOG,
2946 : : (errmsg("recovery has paused"),
2947 : : errhint("Execute pg_wal_replay_resume() to continue.")));
2948 : :
2949 : : /* loop until recoveryPauseState is set to RECOVERY_NOT_PAUSED */
2950 [ + + ]: 32 : while (GetRecoveryPauseState() != RECOVERY_NOT_PAUSED)
2951 : : {
2952 : 25 : ProcessStartupProcInterrupts();
2953 [ + + ]: 24 : if (CheckForStandbyTrigger())
2954 : 2 : return;
2955 : :
2956 : : /*
2957 : : * If recovery pause is requested then set it paused. While we are in
2958 : : * the loop, user might resume and pause again so set this every time.
2959 : : */
2960 : 22 : ConfirmRecoveryPaused();
2961 : :
2962 : : /*
2963 : : * We wait on a condition variable that will wake us as soon as the
2964 : : * pause ends, but we use a timeout so we can check the above exit
2965 : : * condition periodically too.
2966 : : */
2967 : 22 : ConditionVariableTimedSleep(&XLogRecoveryCtl->recoveryNotPausedCV, 1000,
2968 : : WAIT_EVENT_RECOVERY_PAUSE);
2969 : : }
2970 : 7 : ConditionVariableCancelSleep();
2971 : : }
2972 : :
2973 : : /*
2974 : : * When recovery_min_apply_delay is set, we wait long enough to make sure
2975 : : * certain record types are applied at least that interval behind the primary.
2976 : : *
2977 : : * Returns true if we waited.
2978 : : *
2979 : : * Note that the delay is calculated between the WAL record log time and
2980 : : * the current time on standby. We would prefer to keep track of when this
2981 : : * standby received each WAL record, which would allow a more consistent
2982 : : * approach and one not affected by time synchronisation issues, but that
2983 : : * is significantly more effort and complexity for little actual gain in
2984 : : * usability.
2985 : : */
2986 : : static bool
2987 : 2972473 : recoveryApplyDelay(XLogReaderState *record)
2988 : : {
2989 : : uint8 xact_info;
2990 : : TimestampTz xtime;
2991 : : TimestampTz delayUntil;
2992 : : long msecs;
2993 : :
2994 : : /* nothing to do if no delay configured */
2995 [ + + ]: 2972473 : if (recovery_min_apply_delay <= 0)
2996 : 2972319 : return false;
2997 : :
2998 : : /* no delay is applied on a database not yet consistent */
2999 [ + + ]: 154 : if (!reachedConsistency)
3000 : 4 : return false;
3001 : :
3002 : : /* nothing to do if crash recovery is requested */
3003 [ - + ]: 150 : if (!ArchiveRecoveryRequested)
3004 : 0 : return false;
3005 : :
3006 : : /*
3007 : : * Is it a COMMIT record?
3008 : : *
3009 : : * We deliberately choose not to delay aborts since they have no effect on
3010 : : * MVCC. We already allow replay of records that don't have a timestamp,
3011 : : * so there is already opportunity for issues caused by early conflicts on
3012 : : * standbys.
3013 : : */
3014 [ + + ]: 150 : if (XLogRecGetRmid(record) != RM_XACT_ID)
3015 : 120 : return false;
3016 : :
3017 : 30 : xact_info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
3018 : :
3019 [ - + - - ]: 30 : if (xact_info != XLOG_XACT_COMMIT &&
3020 : : xact_info != XLOG_XACT_COMMIT_PREPARED)
3021 : 0 : return false;
3022 : :
3023 [ - + ]: 30 : if (!getRecordTimestamp(record, &xtime))
3024 : 0 : return false;
3025 : :
3026 : 30 : delayUntil = TimestampTzPlusMilliseconds(xtime, recovery_min_apply_delay);
3027 : :
3028 : : /*
3029 : : * Exit without arming the latch if it's already past time to apply this
3030 : : * record
3031 : : */
3032 : 30 : msecs = TimestampDifferenceMilliseconds(GetCurrentTimestamp(), delayUntil);
3033 [ + + ]: 30 : if (msecs <= 0)
3034 : 2 : return false;
3035 : :
3036 : : while (true)
3037 : : {
3038 : 89 : ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
3039 : :
3040 : : /* This might change recovery_min_apply_delay. */
3041 : 89 : ProcessStartupProcInterrupts();
3042 : :
3043 [ - + ]: 89 : if (CheckForStandbyTrigger())
3044 : 0 : break;
3045 : :
3046 : : /*
3047 : : * Recalculate delayUntil as recovery_min_apply_delay could have
3048 : : * changed while waiting in this loop.
3049 : : */
3050 : 89 : delayUntil = TimestampTzPlusMilliseconds(xtime, recovery_min_apply_delay);
3051 : :
3052 : : /*
3053 : : * Wait for difference between GetCurrentTimestamp() and delayUntil.
3054 : : */
3055 : 89 : msecs = TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
3056 : : delayUntil);
3057 : :
3058 [ + + ]: 89 : if (msecs <= 0)
3059 : 28 : break;
3060 : :
3061 [ - + ]: 61 : elog(DEBUG2, "recovery apply delay %ld milliseconds", msecs);
3062 : :
3063 : 61 : (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
3064 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
3065 : : msecs,
3066 : : WAIT_EVENT_RECOVERY_APPLY_DELAY);
3067 : : }
3068 : 28 : return true;
3069 : : }
3070 : :
3071 : : /*
3072 : : * Get the current state of the recovery pause request.
3073 : : */
3074 : : RecoveryPauseState
3075 : 42 : GetRecoveryPauseState(void)
3076 : : {
3077 : : RecoveryPauseState state;
3078 : :
3079 : 42 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
3080 : 42 : state = XLogRecoveryCtl->recoveryPauseState;
3081 : 42 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
3082 : :
3083 : 42 : return state;
3084 : : }
3085 : :
3086 : : /*
3087 : : * Set the recovery pause state.
3088 : : *
3089 : : * If recovery pause is requested then sets the recovery pause state to
3090 : : * 'pause requested' if it is not already 'paused'. Otherwise, sets it
3091 : : * to 'not paused' to resume the recovery. The recovery pause will be
3092 : : * confirmed by the ConfirmRecoveryPaused.
3093 : : */
3094 : : void
3095 : 76 : SetRecoveryPause(bool recoveryPause)
3096 : : {
3097 : 76 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
3098 : :
3099 [ + + ]: 76 : if (!recoveryPause)
3100 : 66 : XLogRecoveryCtl->recoveryPauseState = RECOVERY_NOT_PAUSED;
3101 [ + - ]: 10 : else if (XLogRecoveryCtl->recoveryPauseState == RECOVERY_NOT_PAUSED)
3102 : 10 : XLogRecoveryCtl->recoveryPauseState = RECOVERY_PAUSE_REQUESTED;
3103 : :
3104 : 76 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
3105 : :
3106 [ + + ]: 76 : if (!recoveryPause)
3107 : 66 : ConditionVariableBroadcast(&XLogRecoveryCtl->recoveryNotPausedCV);
3108 : 76 : }
3109 : :
3110 : : /*
3111 : : * Confirm the recovery pause by setting the recovery pause state to
3112 : : * RECOVERY_PAUSED.
3113 : : */
3114 : : static void
3115 : 22 : ConfirmRecoveryPaused(void)
3116 : : {
3117 : : /* If recovery pause is requested then set it paused */
3118 : 22 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
3119 [ + + ]: 22 : if (XLogRecoveryCtl->recoveryPauseState == RECOVERY_PAUSE_REQUESTED)
3120 : 10 : XLogRecoveryCtl->recoveryPauseState = RECOVERY_PAUSED;
3121 : 22 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
3122 : 22 : }
3123 : :
3124 : :
3125 : : /*
3126 : : * Attempt to read the next XLOG record.
3127 : : *
3128 : : * Before first call, the reader needs to be positioned to the first record
3129 : : * by calling XLogPrefetcherBeginRead().
3130 : : *
3131 : : * If no valid record is available, returns NULL, or fails if emode is PANIC.
3132 : : * (emode must be either PANIC, LOG). In standby mode, retries until a valid
3133 : : * record is available.
3134 : : */
3135 : : static XLogRecord *
3136 : 2975157 : ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
3137 : : bool fetching_ckpt, TimeLineID replayTLI)
3138 : : {
3139 : : XLogRecord *record;
3140 : 2975157 : XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
3141 : 2975157 : XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
3142 : :
3143 : : Assert(AmStartupProcess() || !IsUnderPostmaster);
3144 : :
3145 : : /* Pass through parameters to XLogPageRead */
3146 : 2975157 : private->fetching_ckpt = fetching_ckpt;
3147 : 2975157 : private->emode = emode;
3148 : 2975157 : private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
3149 : 2975157 : private->replayTLI = replayTLI;
3150 : :
3151 : : /* This is the first attempt to read this page. */
3152 : 2975157 : lastSourceFailed = false;
3153 : :
3154 : : for (;;)
3155 : 176 : {
3156 : : char *errormsg;
3157 : :
3158 : 2975333 : record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
3159 [ + + ]: 2975262 : if (record == NULL)
3160 : : {
3161 : : /*
3162 : : * When we find that WAL ends in an incomplete record, keep track
3163 : : * of that record. After recovery is done, we'll write a record
3164 : : * to indicate to downstream WAL readers that that portion is to
3165 : : * be ignored.
3166 : : *
3167 : : * However, when ArchiveRecoveryRequested = true, we're going to
3168 : : * switch to a new timeline at the end of recovery. We will only
3169 : : * copy WAL over to the new timeline up to the end of the last
3170 : : * complete record, so if we did this, we would later create an
3171 : : * overwrite contrecord in the wrong place, breaking everything.
3172 : : */
3173 [ + + ]: 358 : if (!ArchiveRecoveryRequested &&
3174 [ + + ]: 122 : XLogRecPtrIsValid(xlogreader->abortedRecPtr))
3175 : : {
3176 : 12 : abortedRecPtr = xlogreader->abortedRecPtr;
3177 : 12 : missingContrecPtr = xlogreader->missingContrecPtr;
3178 : : }
3179 : :
3180 [ + + ]: 358 : if (readFile >= 0)
3181 : : {
3182 : 332 : close(readFile);
3183 : 332 : readFile = -1;
3184 : : }
3185 : :
3186 : : /*
3187 : : * We only end up here without a message when XLogPageRead()
3188 : : * failed - in that case we already logged something. In
3189 : : * StandbyMode that only happens if we have been triggered, so we
3190 : : * shouldn't loop anymore in that case.
3191 : : */
3192 [ + + ]: 358 : if (errormsg)
3193 [ + + ]: 332 : ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
3194 : : (errmsg_internal("%s", errormsg) /* already translated */ ));
3195 : : }
3196 : :
3197 : : /*
3198 : : * Check page TLI is one of the expected values.
3199 : : */
3200 [ - + ]: 2974904 : else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
3201 : : {
3202 : : char fname[MAXFNAMELEN];
3203 : : XLogSegNo segno;
3204 : : int32 offset;
3205 : :
3206 : 0 : XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
3207 : 0 : offset = XLogSegmentOffset(xlogreader->latestPagePtr,
3208 : : wal_segment_size);
3209 : 0 : XLogFileName(fname, xlogreader->seg.ws_tli, segno,
3210 : : wal_segment_size);
3211 [ # # ]: 0 : ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
3212 : : errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
3213 : : xlogreader->latestPageTLI,
3214 : : fname,
3215 : : LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
3216 : : offset));
3217 : 0 : record = NULL;
3218 : : }
3219 : :
3220 [ + + ]: 2975262 : if (record)
3221 : : {
3222 : : /* Great, got a record */
3223 : 2975086 : return record;
3224 : : }
3225 : : else
3226 : : {
3227 : : /* No valid record available from this source */
3228 : 358 : lastSourceFailed = true;
3229 : :
3230 : : /*
3231 : : * If archive recovery was requested, but we were still doing
3232 : : * crash recovery, switch to archive recovery and retry using the
3233 : : * offline archive. We have now replayed all the valid WAL in
3234 : : * pg_wal, so we are presumably now consistent.
3235 : : *
3236 : : * We require that there's at least some valid WAL present in
3237 : : * pg_wal, however (!fetching_ckpt). We could recover using the
3238 : : * WAL from the archive, even if pg_wal is completely empty, but
3239 : : * we'd have no idea how far we'd have to replay to reach
3240 : : * consistency. So err on the safe side and give up.
3241 : : */
3242 [ + + + + ]: 358 : if (!InArchiveRecovery && ArchiveRecoveryRequested &&
3243 [ + - ]: 1 : !fetching_ckpt)
3244 : : {
3245 [ - + ]: 1 : ereport(DEBUG1,
3246 : : (errmsg_internal("reached end of WAL in pg_wal, entering archive recovery")));
3247 : 1 : InArchiveRecovery = true;
3248 [ + - ]: 1 : if (StandbyModeRequested)
3249 : 1 : EnableStandbyMode();
3250 : :
3251 : 1 : SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
3252 : 1 : minRecoveryPoint = xlogreader->EndRecPtr;
3253 : 1 : minRecoveryPointTLI = replayTLI;
3254 : :
3255 : 1 : CheckRecoveryConsistency();
3256 : :
3257 : : /*
3258 : : * Before we retry, reset lastSourceFailed and currentSource
3259 : : * so that we will check the archive next.
3260 : : */
3261 : 1 : lastSourceFailed = false;
3262 : 1 : currentSource = XLOG_FROM_ANY;
3263 : :
3264 : 176 : continue;
3265 : : }
3266 : :
3267 : : /* In standby mode, loop back to retry. Otherwise, give up. */
3268 [ + + + + ]: 357 : if (StandbyMode && !CheckForStandbyTrigger())
3269 : 175 : continue;
3270 : : else
3271 : 182 : return NULL;
3272 : : }
3273 : : }
3274 : : }
3275 : :
3276 : : /*
3277 : : * Read the XLOG page containing targetPagePtr into readBuf (if not read
3278 : : * already). Returns number of bytes read, if the page is read successfully,
3279 : : * or XLREAD_FAIL in case of errors. When errors occur, they are ereport'ed,
3280 : : * but only if they have not been previously reported.
3281 : : *
3282 : : * See XLogReaderRoutine.page_read for more details.
3283 : : *
3284 : : * While prefetching, xlogreader->nonblocking may be set. In that case,
3285 : : * returns XLREAD_WOULDBLOCK if we'd otherwise have to wait for more WAL.
3286 : : *
3287 : : * This is responsible for restoring files from archive as needed, as well
3288 : : * as for waiting for the requested WAL record to arrive in standby mode.
3289 : : *
3290 : : * xlogreader->private_data->emode specifies the log level used for reporting
3291 : : * "file not found" or "end of WAL" situations in archive recovery, or in
3292 : : * standby mode when promotion is triggered. If set to WARNING or below,
3293 : : * XLogPageRead() returns XLREAD_FAIL in those situations, on higher log
3294 : : * levels the ereport() won't return.
3295 : : *
3296 : : * In standby mode, if after a successful return of XLogPageRead() the
3297 : : * caller finds the record it's interested in to be broken, it should
3298 : : * ereport the error with the level determined by
3299 : : * emode_for_corrupt_record(), and then set lastSourceFailed
3300 : : * and call XLogPageRead() again with the same arguments. This lets
3301 : : * XLogPageRead() to try fetching the record from another source, or to
3302 : : * sleep and retry.
3303 : : */
3304 : : static int
3305 : 1535170 : XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
3306 : : XLogRecPtr targetRecPtr, char *readBuf)
3307 : : {
3308 : 1535170 : XLogPageReadPrivate *private =
3309 : : (XLogPageReadPrivate *) xlogreader->private_data;
3310 : 1535170 : int emode = private->emode;
3311 : : uint32 targetPageOff;
3312 : : XLogSegNo targetSegNo PG_USED_FOR_ASSERTS_ONLY;
3313 : : ssize_t r;
3314 : : instr_time io_start;
3315 : :
3316 : : Assert(AmStartupProcess() || !IsUnderPostmaster);
3317 : :
3318 : 1535170 : XLByteToSeg(targetPagePtr, targetSegNo, wal_segment_size);
3319 : 1535170 : targetPageOff = XLogSegmentOffset(targetPagePtr, wal_segment_size);
3320 : :
3321 : : /*
3322 : : * See if we need to switch to a new segment because the requested record
3323 : : * is not in the currently open one.
3324 : : */
3325 [ + + ]: 1535170 : if (readFile >= 0 &&
3326 [ + + ]: 1533164 : !XLByteInSeg(targetPagePtr, readSegNo, wal_segment_size))
3327 : : {
3328 : : /*
3329 : : * Request a restartpoint if we've replayed too much xlog since the
3330 : : * last one.
3331 : : */
3332 [ + + + - ]: 1538 : if (ArchiveRecoveryRequested && IsUnderPostmaster)
3333 : : {
3334 [ + + ]: 1517 : if (XLogCheckpointNeeded(readSegNo))
3335 : : {
3336 : 1357 : (void) GetRedoRecPtr();
3337 [ + + ]: 1357 : if (XLogCheckpointNeeded(readSegNo))
3338 : 1349 : RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
3339 : : }
3340 : : }
3341 : :
3342 : 1538 : close(readFile);
3343 : 1538 : readFile = -1;
3344 : 1538 : readSource = XLOG_FROM_ANY;
3345 : : }
3346 : :
3347 : 1535170 : XLByteToSeg(targetPagePtr, readSegNo, wal_segment_size);
3348 : :
3349 : 1535173 : retry:
3350 : : /* See if we need to retrieve more data */
3351 [ + + ]: 1535173 : if (readFile < 0 ||
3352 [ + + ]: 1531626 : (readSource == XLOG_FROM_STREAM &&
3353 [ + + ]: 1513392 : flushedUpto < targetPagePtr + reqLen))
3354 : : {
3355 [ + + ]: 37386 : if (readFile >= 0 &&
3356 [ + + ]: 33839 : xlogreader->nonblocking &&
3357 [ + - ]: 16762 : readSource == XLOG_FROM_STREAM &&
3358 [ + - ]: 16762 : flushedUpto < targetPagePtr + reqLen)
3359 : 16762 : return XLREAD_WOULDBLOCK;
3360 : :
3361 [ + + + - ]: 20553 : switch (WaitForWALToBecomeAvailable(targetPagePtr + reqLen,
3362 : 20624 : private->randAccess,
3363 : 20624 : private->fetching_ckpt,
3364 : : targetRecPtr,
3365 : : private->replayTLI,
3366 : : xlogreader->EndRecPtr,
3367 : 20624 : xlogreader->nonblocking))
3368 : : {
3369 : 448 : case XLREAD_WOULDBLOCK:
3370 : 448 : return XLREAD_WOULDBLOCK;
3371 : 50 : case XLREAD_FAIL:
3372 [ - + ]: 50 : if (readFile >= 0)
3373 : 0 : close(readFile);
3374 : 50 : readFile = -1;
3375 : 50 : readLen = 0;
3376 : 50 : readSource = XLOG_FROM_ANY;
3377 : 50 : return XLREAD_FAIL;
3378 : 20055 : case XLREAD_SUCCESS:
3379 : 20055 : break;
3380 : : }
3381 : : }
3382 : :
3383 : : /*
3384 : : * At this point, we have the right segment open and if we're streaming we
3385 : : * know the requested record is in it.
3386 : : */
3387 : : Assert(readFile != -1);
3388 : :
3389 : : /*
3390 : : * If the current segment is being streamed from the primary, calculate
3391 : : * how much of the current page we have received already. We know the
3392 : : * requested record has been received, but this is for the benefit of
3393 : : * future calls, to allow quick exit at the top of this function.
3394 : : */
3395 [ + + ]: 1517842 : if (readSource == XLOG_FROM_STREAM)
3396 : : {
3397 [ + + ]: 1497711 : if (((targetPagePtr) / XLOG_BLCKSZ) != (flushedUpto / XLOG_BLCKSZ))
3398 : 1485336 : readLen = XLOG_BLCKSZ;
3399 : : else
3400 : 12375 : readLen = XLogSegmentOffset(flushedUpto, wal_segment_size) -
3401 : : targetPageOff;
3402 : : }
3403 : : else
3404 : 20131 : readLen = XLOG_BLCKSZ;
3405 : :
3406 : : /* Read the requested page */
3407 : 1517842 : readOff = targetPageOff;
3408 : :
3409 : : /* Measure I/O timing when reading segment */
3410 : 1517842 : io_start = pgstat_prepare_io_time(track_wal_io_timing);
3411 : :
3412 : 1517842 : pgstat_report_wait_start(WAIT_EVENT_WAL_READ);
3413 : 1517842 : r = pg_pread(readFile, readBuf, XLOG_BLCKSZ, (pgoff_t) readOff);
3414 [ - + ]: 1517842 : if (r != XLOG_BLCKSZ)
3415 : : {
3416 : : char fname[MAXFNAMELEN];
3417 : 0 : int save_errno = errno;
3418 : :
3419 : 0 : pgstat_report_wait_end();
3420 : :
3421 : : /* Count I/O stats only for successful short reads */
3422 [ # # ]: 0 : if (r > 0)
3423 : 0 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_READ,
3424 : : io_start, 1, r);
3425 : :
3426 : 0 : XLogFileName(fname, curFileTLI, readSegNo, wal_segment_size);
3427 [ # # ]: 0 : if (r < 0)
3428 : : {
3429 : 0 : errno = save_errno;
3430 [ # # ]: 0 : ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
3431 : : (errcode_for_file_access(),
3432 : : errmsg("could not read from WAL segment %s, LSN %X/%08X, offset %u: %m",
3433 : : fname, LSN_FORMAT_ARGS(targetPagePtr),
3434 : : readOff)));
3435 : : }
3436 : : else
3437 [ # # ]: 0 : ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
3438 : : (errcode(ERRCODE_DATA_CORRUPTED),
3439 : : errmsg("could not read from WAL segment %s, LSN %X/%08X, offset %u: read %zd of %zu",
3440 : : fname, LSN_FORMAT_ARGS(targetPagePtr),
3441 : : readOff, r, (Size) XLOG_BLCKSZ)));
3442 : 0 : goto next_record_is_invalid;
3443 : : }
3444 : 1517842 : pgstat_report_wait_end();
3445 : :
3446 : 1517842 : pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_READ,
3447 : : io_start, 1, r);
3448 : :
3449 : : Assert(targetSegNo == readSegNo);
3450 : : Assert(targetPageOff == readOff);
3451 : : Assert(reqLen <= readLen);
3452 : :
3453 : 1517842 : xlogreader->seg.ws_tli = curFileTLI;
3454 : :
3455 : : /*
3456 : : * Check the page header immediately, so that we can retry immediately if
3457 : : * it's not valid. This may seem unnecessary, because ReadPageInternal()
3458 : : * validates the page header anyway, and would propagate the failure up to
3459 : : * ReadRecord(), which would retry. However, there's a corner case with
3460 : : * continuation records, if a record is split across two pages such that
3461 : : * we would need to read the two pages from different sources across two
3462 : : * WAL segments.
3463 : : *
3464 : : * The first page is only available locally, in pg_wal, because it's
3465 : : * already been recycled on the primary. The second page, however, is not
3466 : : * present in pg_wal, and we should stream it from the primary. There is a
3467 : : * recycled WAL segment present in pg_wal, with garbage contents, however.
3468 : : * We would read the first page from the local WAL segment, but when
3469 : : * reading the second page, we would read the bogus, recycled, WAL
3470 : : * segment. If we didn't catch that case here, we would never recover,
3471 : : * because ReadRecord() would retry reading the whole record from the
3472 : : * beginning.
3473 : : *
3474 : : * Of course, this only catches errors in the page header, which is what
3475 : : * happens in the case of a recycled WAL segment. Other kinds of errors or
3476 : : * corruption still has the same problem. But this at least fixes the
3477 : : * common case, which can happen as part of normal operation.
3478 : : *
3479 : : * Validating the page header is cheap enough that doing it twice
3480 : : * shouldn't be a big deal from a performance point of view.
3481 : : *
3482 : : * When not in standby mode, an invalid page header should cause recovery
3483 : : * to end, not retry reading the page, so we don't need to validate the
3484 : : * page header here for the retry. Instead, ReadPageInternal() is
3485 : : * responsible for the validation.
3486 : : */
3487 [ + + ]: 1517842 : if (StandbyMode &&
3488 [ + + ]: 1506159 : (targetPagePtr % wal_segment_size) == 0 &&
3489 [ + + ]: 1534 : !XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
3490 : : {
3491 : : /*
3492 : : * Emit this error right now then retry this page immediately. Use
3493 : : * errmsg_internal() because the message was already translated.
3494 : : */
3495 [ + - ]: 4 : if (xlogreader->errormsg_buf[0])
3496 [ + + ]: 4 : ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
3497 : : (errmsg_internal("%s", xlogreader->errormsg_buf)));
3498 : :
3499 : : /* reset any error XLogReaderValidatePageHeader() might have set */
3500 : 4 : XLogReaderResetError(xlogreader);
3501 : 4 : goto next_record_is_invalid;
3502 : : }
3503 : :
3504 : 1517838 : return readLen;
3505 : :
3506 : 4 : next_record_is_invalid:
3507 : :
3508 : : /*
3509 : : * If we're reading ahead, give up fast. Retries and error reporting will
3510 : : * be handled by a later read when recovery catches up to this point.
3511 : : */
3512 [ + + ]: 4 : if (xlogreader->nonblocking)
3513 : 1 : return XLREAD_WOULDBLOCK;
3514 : :
3515 : 3 : lastSourceFailed = true;
3516 : :
3517 [ + - ]: 3 : if (readFile >= 0)
3518 : 3 : close(readFile);
3519 : 3 : readFile = -1;
3520 : 3 : readLen = 0;
3521 : 3 : readSource = XLOG_FROM_ANY;
3522 : :
3523 : : /* In standby-mode, keep trying */
3524 [ + - ]: 3 : if (StandbyMode)
3525 : 3 : goto retry;
3526 : : else
3527 : 0 : return XLREAD_FAIL;
3528 : : }
3529 : :
3530 : : /*
3531 : : * Open the WAL segment containing WAL location 'RecPtr'.
3532 : : *
3533 : : * The segment can be fetched via restore_command, or via walreceiver having
3534 : : * streamed the record, or it can already be present in pg_wal. Checking
3535 : : * pg_wal is mainly for crash recovery, but it will be polled in standby mode
3536 : : * too, in case someone copies a new segment directly to pg_wal. That is not
3537 : : * documented or recommended, though.
3538 : : *
3539 : : * If 'fetching_ckpt' is true, we're fetching a checkpoint record, and should
3540 : : * prepare to read WAL starting from RedoStartLSN after this.
3541 : : *
3542 : : * 'RecPtr' might not point to the beginning of the record we're interested
3543 : : * in, it might also point to the page or segment header. In that case,
3544 : : * 'tliRecPtr' is the position of the WAL record we're interested in. It is
3545 : : * used to decide which timeline to stream the requested WAL from.
3546 : : *
3547 : : * 'replayLSN' is the current replay LSN, so that if we scan for new
3548 : : * timelines, we can reject a switch to a timeline that branched off before
3549 : : * this point.
3550 : : *
3551 : : * If the record is not immediately available, the function returns XLREAD_FAIL
3552 : : * if we're not in standby mode. In standby mode, the function waits for it to
3553 : : * become available.
3554 : : *
3555 : : * When the requested record becomes available, the function opens the file
3556 : : * containing it (if not open already), and returns XLREAD_SUCCESS. When end
3557 : : * of standby mode is triggered by the user, and there is no more WAL
3558 : : * available, returns XLREAD_FAIL.
3559 : : *
3560 : : * If nonblocking is true, then give up immediately if we can't satisfy the
3561 : : * request, returning XLREAD_WOULDBLOCK instead of waiting.
3562 : : */
3563 : : static XLogPageReadResult
3564 : 20624 : WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
3565 : : bool fetching_ckpt, XLogRecPtr tliRecPtr,
3566 : : TimeLineID replayTLI, XLogRecPtr replayLSN,
3567 : : bool nonblocking)
3568 : : {
3569 : : static TimestampTz last_fail_time = 0;
3570 : : TimestampTz now;
3571 : 20624 : bool streaming_reply_sent = false;
3572 : :
3573 : : /*-------
3574 : : * Standby mode is implemented by a state machine:
3575 : : *
3576 : : * 1. Read from either archive or pg_wal (XLOG_FROM_ARCHIVE), or just
3577 : : * pg_wal (XLOG_FROM_PG_WAL)
3578 : : * 2. Check for promotion trigger request
3579 : : * 3. Read from primary server via walreceiver (XLOG_FROM_STREAM)
3580 : : * 4. Rescan timelines
3581 : : * 5. Sleep wal_retrieve_retry_interval milliseconds, and loop back to 1.
3582 : : *
3583 : : * Failure to read from the current source advances the state machine to
3584 : : * the next state.
3585 : : *
3586 : : * 'currentSource' indicates the current state. There are no currentSource
3587 : : * values for "check trigger", "rescan timelines", and "sleep" states,
3588 : : * those actions are taken when reading from the previous source fails, as
3589 : : * part of advancing to the next state.
3590 : : *
3591 : : * If standby mode is turned off while reading WAL from stream, we move
3592 : : * to XLOG_FROM_ARCHIVE and reset lastSourceFailed, to force fetching
3593 : : * the files (which would be required at end of recovery, e.g., timeline
3594 : : * history file) from archive or pg_wal. We don't need to kill WAL receiver
3595 : : * here because it's already stopped when standby mode is turned off at
3596 : : * the end of recovery.
3597 : : *-------
3598 : : */
3599 [ + + ]: 20624 : if (!InArchiveRecovery)
3600 : 1154 : currentSource = XLOG_FROM_PG_WAL;
3601 [ + + ]: 19470 : else if (currentSource == XLOG_FROM_ANY ||
3602 [ + + - + ]: 19316 : (!StandbyMode && currentSource == XLOG_FROM_STREAM))
3603 : : {
3604 : 154 : lastSourceFailed = false;
3605 : 154 : currentSource = XLOG_FROM_ARCHIVE;
3606 : : }
3607 : :
3608 : : for (;;)
3609 : 18166 : {
3610 : 38790 : XLogSource oldSource = currentSource;
3611 : 38790 : bool startWalReceiver = false;
3612 : :
3613 : : /*
3614 : : * First check if we failed to read from the current source, and
3615 : : * advance the state machine if so. The failure to read might've
3616 : : * happened outside this function, e.g when a CRC check fails on a
3617 : : * record, or within this loop.
3618 : : */
3619 [ + + ]: 38790 : if (lastSourceFailed)
3620 : : {
3621 : : /*
3622 : : * Don't allow any retry loops to occur during nonblocking
3623 : : * readahead. Let the caller process everything that has been
3624 : : * decoded already first.
3625 : : */
3626 [ + + ]: 670 : if (nonblocking)
3627 : 98 : return XLREAD_WOULDBLOCK;
3628 : :
3629 [ + + - ]: 572 : switch (currentSource)
3630 : : {
3631 : 338 : case XLOG_FROM_ARCHIVE:
3632 : : case XLOG_FROM_PG_WAL:
3633 : :
3634 : : /*
3635 : : * Check to see if promotion is requested. Note that we do
3636 : : * this only after failure, so when you promote, we still
3637 : : * finish replaying as much as we can from archive and
3638 : : * pg_wal before failover.
3639 : : */
3640 [ + + + + ]: 338 : if (StandbyMode && CheckForStandbyTrigger())
3641 : : {
3642 : 16 : XLogShutdownWalRcv();
3643 : 16 : return XLREAD_FAIL;
3644 : : }
3645 : :
3646 : : /*
3647 : : * Not in standby mode, and we've now tried the archive
3648 : : * and pg_wal.
3649 : : */
3650 [ + + ]: 322 : if (!StandbyMode)
3651 : 34 : return XLREAD_FAIL;
3652 : :
3653 : : /*
3654 : : * Move to XLOG_FROM_STREAM state, and set to start a
3655 : : * walreceiver if necessary.
3656 : : */
3657 : 288 : currentSource = XLOG_FROM_STREAM;
3658 : 288 : startWalReceiver = true;
3659 : 288 : break;
3660 : :
3661 : 234 : case XLOG_FROM_STREAM:
3662 : :
3663 : : /*
3664 : : * Failure while streaming. Most likely, we got here
3665 : : * because streaming replication was terminated, or
3666 : : * promotion was triggered. But we also get here if we
3667 : : * find an invalid record in the WAL streamed from the
3668 : : * primary, in which case something is seriously wrong.
3669 : : * There's little chance that the problem will just go
3670 : : * away, but PANIC is not good for availability either,
3671 : : * especially in hot standby mode. So, we treat that the
3672 : : * same as disconnection, and retry from archive/pg_wal
3673 : : * again. The WAL in the archive should be identical to
3674 : : * what was streamed, so it's unlikely that it helps, but
3675 : : * one can hope...
3676 : : */
3677 : :
3678 : : /*
3679 : : * We should be able to move to XLOG_FROM_STREAM only in
3680 : : * standby mode.
3681 : : */
3682 : : Assert(StandbyMode);
3683 : :
3684 : : /*
3685 : : * Before we leave XLOG_FROM_STREAM state, make sure that
3686 : : * walreceiver is not active, so that it won't overwrite
3687 : : * WAL that we restore from archive.
3688 : : *
3689 : : * If walreceiver is actively streaming (or attempting to
3690 : : * connect), we must shut it down. However, if it's
3691 : : * already in WAITING state (e.g., due to timeline
3692 : : * divergence), we only need to reset the install flag to
3693 : : * allow archive restoration.
3694 : : */
3695 [ + + ]: 234 : if (WalRcvStreaming())
3696 : 40 : XLogShutdownWalRcv();
3697 : : else
3698 : : {
3699 : : /*
3700 : : * WALRCV_STOPPING state is a transient state while
3701 : : * the startup process is in ShutdownWalRcv(). It
3702 : : * should never appear here since we would be waiting
3703 : : * for the walreceiver to reach WALRCV_STOPPED in that
3704 : : * case.
3705 : : */
3706 : : Assert(WalRcvGetState() != WALRCV_STOPPING);
3707 : 194 : ResetInstallXLogFileSegmentActive();
3708 : : }
3709 : :
3710 : : /*
3711 : : * Before we sleep, re-scan for possible new timelines if
3712 : : * we were requested to recover to the latest timeline.
3713 : : */
3714 [ + - ]: 234 : if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_LATEST)
3715 : : {
3716 [ + + ]: 234 : if (rescanLatestTimeLine(replayTLI, replayLSN))
3717 : : {
3718 : 9 : currentSource = XLOG_FROM_ARCHIVE;
3719 : 9 : break;
3720 : : }
3721 : : }
3722 : :
3723 : : /*
3724 : : * XLOG_FROM_STREAM is the last state in our state
3725 : : * machine, so we've exhausted all the options for
3726 : : * obtaining the requested WAL. We're going to loop back
3727 : : * and retry from the archive, but if it hasn't been long
3728 : : * since last attempt, sleep wal_retrieve_retry_interval
3729 : : * milliseconds to avoid busy-waiting.
3730 : : */
3731 : 225 : now = GetCurrentTimestamp();
3732 [ + + ]: 225 : if (!TimestampDifferenceExceeds(last_fail_time, now,
3733 : : wal_retrieve_retry_interval))
3734 : : {
3735 : : long wait_time;
3736 : :
3737 : 248 : wait_time = wal_retrieve_retry_interval -
3738 : 124 : TimestampDifferenceMilliseconds(last_fail_time, now);
3739 : :
3740 [ + - ]: 124 : elog(LOG, "waiting for WAL to become available at %X/%08X",
3741 : : LSN_FORMAT_ARGS(RecPtr));
3742 : :
3743 : : /* Do background tasks that might benefit us later. */
3744 : 124 : KnownAssignedTransactionIdsIdleMaintenance();
3745 : :
3746 : 124 : (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
3747 : : WL_LATCH_SET | WL_TIMEOUT |
3748 : : WL_EXIT_ON_PM_DEATH,
3749 : : wait_time,
3750 : : WAIT_EVENT_RECOVERY_RETRIEVE_RETRY_INTERVAL);
3751 : 124 : ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
3752 : 124 : now = GetCurrentTimestamp();
3753 : :
3754 : : /* Handle interrupt signals of startup process */
3755 : 124 : ProcessStartupProcInterrupts();
3756 : : }
3757 : 208 : last_fail_time = now;
3758 : 208 : currentSource = XLOG_FROM_ARCHIVE;
3759 : 208 : break;
3760 : :
3761 : 0 : default:
3762 [ # # ]: 0 : elog(ERROR, "unexpected WAL source %d", currentSource);
3763 : : }
3764 : : }
3765 [ + + ]: 38120 : else if (currentSource == XLOG_FROM_PG_WAL)
3766 : : {
3767 : : /*
3768 : : * We just successfully read a file in pg_wal. We prefer files in
3769 : : * the archive over ones in pg_wal, so try the next file again
3770 : : * from the archive first.
3771 : : */
3772 [ - + ]: 1150 : if (InArchiveRecovery)
3773 : 0 : currentSource = XLOG_FROM_ARCHIVE;
3774 : : }
3775 : :
3776 [ + + ]: 38625 : if (currentSource != oldSource)
3777 [ + + + - ]: 505 : elog(DEBUG2, "switched WAL source from %s to %s after %s",
3778 : : xlogSourceNames[oldSource], xlogSourceNames[currentSource],
3779 : : lastSourceFailed ? "failure" : "success");
3780 : :
3781 : : /*
3782 : : * We've now handled possible failure. Try to read from the chosen
3783 : : * source.
3784 : : */
3785 : 38625 : lastSourceFailed = false;
3786 : :
3787 [ + + - ]: 38625 : switch (currentSource)
3788 : : {
3789 : 2133 : case XLOG_FROM_ARCHIVE:
3790 : : case XLOG_FROM_PG_WAL:
3791 : :
3792 : : /*
3793 : : * WAL receiver must not be running when reading WAL from
3794 : : * archive or pg_wal.
3795 : : */
3796 : : Assert(!WalRcvStreaming());
3797 : :
3798 : : /* Close any old file we might have open. */
3799 [ + + ]: 2133 : if (readFile >= 0)
3800 : : {
3801 : 114 : close(readFile);
3802 : 114 : readFile = -1;
3803 : : }
3804 : : /* Reset curFileTLI if random fetch. */
3805 [ + + ]: 2133 : if (randAccess)
3806 : 1363 : curFileTLI = 0;
3807 : :
3808 : : /*
3809 : : * Try to restore the file from archive, or read an existing
3810 : : * file from pg_wal.
3811 : : */
3812 : 2133 : readFile = XLogFileReadAnyTLI(readSegNo,
3813 [ + + ]: 2133 : currentSource == XLOG_FROM_ARCHIVE ? XLOG_FROM_ANY :
3814 : : currentSource);
3815 [ + + ]: 2132 : if (readFile >= 0)
3816 : 1897 : return XLREAD_SUCCESS; /* success! */
3817 : :
3818 : : /*
3819 : : * Nope, not found in archive or pg_wal.
3820 : : */
3821 : 235 : lastSourceFailed = true;
3822 : 235 : break;
3823 : :
3824 : 36492 : case XLOG_FROM_STREAM:
3825 : : {
3826 : : bool havedata;
3827 : :
3828 : : /*
3829 : : * We should be able to move to XLOG_FROM_STREAM only in
3830 : : * standby mode.
3831 : : */
3832 : : Assert(StandbyMode);
3833 : :
3834 : : /*
3835 : : * First, shutdown walreceiver if its restart has been
3836 : : * requested -- but no point if we're already slated for
3837 : : * starting it.
3838 : : */
3839 [ + + + - ]: 36492 : if (pendingWalRcvRestart && !startWalReceiver)
3840 : : {
3841 : 10 : XLogShutdownWalRcv();
3842 : :
3843 : : /*
3844 : : * Re-scan for possible new timelines if we were
3845 : : * requested to recover to the latest timeline.
3846 : : */
3847 [ + - ]: 10 : if (recoveryTargetTimeLineGoal ==
3848 : : RECOVERY_TARGET_TIMELINE_LATEST)
3849 : 10 : rescanLatestTimeLine(replayTLI, replayLSN);
3850 : :
3851 : 10 : startWalReceiver = true;
3852 : : }
3853 : 36492 : pendingWalRcvRestart = false;
3854 : :
3855 : : /*
3856 : : * Launch walreceiver if needed.
3857 : : *
3858 : : * If fetching_ckpt is true, RecPtr points to the initial
3859 : : * checkpoint location. In that case, we use RedoStartLSN
3860 : : * as the streaming start position instead of RecPtr, so
3861 : : * that when we later jump backwards to start redo at
3862 : : * RedoStartLSN, we will have the logs streamed already.
3863 : : */
3864 [ + + + - ]: 36492 : if (startWalReceiver &&
3865 [ + + ]: 298 : PrimaryConnInfo && strcmp(PrimaryConnInfo, "") != 0)
3866 : : {
3867 : : XLogRecPtr ptr;
3868 : : TimeLineID tli;
3869 : :
3870 [ - + ]: 233 : if (fetching_ckpt)
3871 : : {
3872 : 0 : ptr = RedoStartLSN;
3873 : 0 : tli = RedoStartTLI;
3874 : : }
3875 : : else
3876 : : {
3877 : 233 : ptr = RecPtr;
3878 : :
3879 : : /*
3880 : : * Use the record begin position to determine the
3881 : : * TLI, rather than the position we're reading.
3882 : : */
3883 : 233 : tli = tliOfPointInHistory(tliRecPtr, expectedTLEs);
3884 : :
3885 [ + - - + ]: 233 : if (curFileTLI > 0 && tli < curFileTLI)
3886 [ # # ]: 0 : elog(ERROR, "according to history file, WAL location %X/%08X belongs to timeline %u, but previous recovered WAL file came from timeline %u",
3887 : : LSN_FORMAT_ARGS(tliRecPtr),
3888 : : tli, curFileTLI);
3889 : : }
3890 : 233 : curFileTLI = tli;
3891 : 233 : SetInstallXLogFileSegmentActive();
3892 : 233 : RequestXLogStreaming(tli, ptr, PrimaryConnInfo,
3893 : : PrimarySlotName,
3894 : : wal_receiver_create_temp_slot);
3895 : 233 : flushedUpto = InvalidXLogRecPtr;
3896 : : }
3897 : :
3898 : : /*
3899 : : * Check if WAL receiver is active or wait to start up.
3900 : : */
3901 [ + + ]: 36492 : if (!WalRcvStreaming())
3902 : : {
3903 : 194 : lastSourceFailed = true;
3904 : 194 : break;
3905 : : }
3906 : :
3907 : : /*
3908 : : * Walreceiver is active, so see if new data has arrived.
3909 : : *
3910 : : * We only advance XLogReceiptTime when we obtain fresh
3911 : : * WAL from walreceiver and observe that we had already
3912 : : * processed everything before the most recent "chunk"
3913 : : * that it flushed to disk. In steady state where we are
3914 : : * keeping up with the incoming data, XLogReceiptTime will
3915 : : * be updated on each cycle. When we are behind,
3916 : : * XLogReceiptTime will not advance, so the grace time
3917 : : * allotted to conflicting queries will decrease.
3918 : : */
3919 [ + + ]: 36298 : if (RecPtr < flushedUpto)
3920 : 1834 : havedata = true;
3921 : : else
3922 : : {
3923 : : XLogRecPtr latestChunkStart;
3924 : :
3925 : 34464 : flushedUpto = GetWalRcvFlushRecPtr(&latestChunkStart, &receiveTLI);
3926 [ + + + - ]: 34464 : if (RecPtr < flushedUpto && receiveTLI == curFileTLI)
3927 : : {
3928 : 17560 : havedata = true;
3929 [ + + ]: 17560 : if (latestChunkStart <= RecPtr)
3930 : : {
3931 : 13658 : XLogReceiptTime = GetCurrentTimestamp();
3932 : 13658 : SetCurrentChunkStartTime(XLogReceiptTime);
3933 : : }
3934 : : }
3935 : : else
3936 : 16904 : havedata = false;
3937 : : }
3938 [ + + ]: 36298 : if (havedata)
3939 : : {
3940 : : /*
3941 : : * Great, streamed far enough. Open the file if it's
3942 : : * not open already. Also read the timeline history
3943 : : * file if we haven't initialized timeline history
3944 : : * yet; it should be streamed over and present in
3945 : : * pg_wal by now. Use XLOG_FROM_STREAM so that source
3946 : : * info is set correctly and XLogReceiptTime isn't
3947 : : * changed.
3948 : : *
3949 : : * NB: We must set readTimeLineHistory based on
3950 : : * recoveryTargetTLI, not receiveTLI. Normally they'll
3951 : : * be the same, but if recovery_target_timeline is
3952 : : * 'latest' and archiving is configured, then it's
3953 : : * possible that we managed to retrieve one or more
3954 : : * new timeline history files from the archive,
3955 : : * updating recoveryTargetTLI.
3956 : : */
3957 [ + + ]: 19394 : if (readFile < 0)
3958 : : {
3959 [ - + ]: 1236 : if (!expectedTLEs)
3960 : 0 : expectedTLEs = readTimeLineHistory(recoveryTargetTLI);
3961 : 1236 : readFile = XLogFileRead(readSegNo, receiveTLI,
3962 : : XLOG_FROM_STREAM, false);
3963 : : Assert(readFile >= 0);
3964 : : }
3965 : : else
3966 : : {
3967 : : /* just make sure source info is correct... */
3968 : 18158 : readSource = XLOG_FROM_STREAM;
3969 : 18158 : XLogReceiptSource = XLOG_FROM_STREAM;
3970 : 18158 : return XLREAD_SUCCESS;
3971 : : }
3972 : 1236 : break;
3973 : : }
3974 : :
3975 : : /* In nonblocking mode, return rather than sleeping. */
3976 [ + + ]: 16904 : if (nonblocking)
3977 : 350 : return XLREAD_WOULDBLOCK;
3978 : :
3979 : : /*
3980 : : * Data not here yet. Check for trigger, then wait for
3981 : : * walreceiver to wake us up when new WAL arrives.
3982 : : */
3983 [ + + ]: 16554 : if (CheckForStandbyTrigger())
3984 : : {
3985 : : /*
3986 : : * Note that we don't return XLREAD_FAIL immediately
3987 : : * here. After being triggered, we still want to
3988 : : * replay all the WAL that was already streamed. It's
3989 : : * in pg_wal now, so we just treat this as a failure,
3990 : : * and the state machine will move on to replay the
3991 : : * streamed WAL from pg_wal, and then recheck the
3992 : : * trigger and exit replay.
3993 : : */
3994 : 40 : lastSourceFailed = true;
3995 : 40 : break;
3996 : : }
3997 : :
3998 : : /*
3999 : : * Since we have replayed everything we have received so
4000 : : * far and are about to start waiting for more WAL, let's
4001 : : * tell the upstream server our replay location now so
4002 : : * that pg_stat_replication doesn't show stale
4003 : : * information.
4004 : : */
4005 [ + + ]: 16514 : if (!streaming_reply_sent)
4006 : : {
4007 : 14224 : WalRcvRequestApplyReply();
4008 : 14224 : streaming_reply_sent = true;
4009 : : }
4010 : :
4011 : : /* Do any background tasks that might benefit us later. */
4012 : 16514 : KnownAssignedTransactionIdsIdleMaintenance();
4013 : :
4014 : : /* Update pg_stat_recovery_prefetch before sleeping. */
4015 : 16514 : XLogPrefetcherComputeStats(xlogprefetcher);
4016 : :
4017 : : /*
4018 : : * Wait for more WAL to arrive, when we will be woken
4019 : : * immediately by the WAL receiver.
4020 : : */
4021 : 16514 : (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
4022 : : WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
4023 : : -1L,
4024 : : WAIT_EVENT_RECOVERY_WAL_STREAM);
4025 : 16514 : ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
4026 : 16514 : break;
4027 : : }
4028 : :
4029 : 0 : default:
4030 [ # # ]: 0 : elog(ERROR, "unexpected WAL source %d", currentSource);
4031 : : }
4032 : :
4033 : : /*
4034 : : * Check for recovery pause here so that we can confirm more quickly
4035 : : * that a requested pause has actually taken effect.
4036 : : */
4037 [ + + ]: 18219 : if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
4038 : : RECOVERY_NOT_PAUSED)
4039 : 8 : recoveryPausesHere(false);
4040 : :
4041 : : /*
4042 : : * This possibly-long loop needs to handle interrupts of startup
4043 : : * process.
4044 : : */
4045 : 18218 : ProcessStartupProcInterrupts();
4046 : : }
4047 : :
4048 : : return XLREAD_FAIL; /* not reached */
4049 : : }
4050 : :
4051 : :
4052 : : /*
4053 : : * Determine what log level should be used to report a corrupt WAL record
4054 : : * in the current WAL page, previously read by XLogPageRead().
4055 : : *
4056 : : * 'emode' is the error mode that would be used to report a file-not-found
4057 : : * or legitimate end-of-WAL situation. Generally, we use it as-is, but if
4058 : : * we're retrying the exact same record that we've tried previously, only
4059 : : * complain the first time to keep the noise down. However, we only do when
4060 : : * reading from pg_wal, because we don't expect any invalid records in archive
4061 : : * or in records streamed from the primary. Files in the archive should be complete,
4062 : : * and we should never hit the end of WAL because we stop and wait for more WAL
4063 : : * to arrive before replaying it.
4064 : : *
4065 : : * NOTE: This function remembers the RecPtr value it was last called with,
4066 : : * to suppress repeated messages about the same record. Only call this when
4067 : : * you are about to ereport(), or you might cause a later message to be
4068 : : * erroneously suppressed.
4069 : : */
4070 : : static int
4071 : 336 : emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
4072 : : {
4073 : : static XLogRecPtr lastComplaint = InvalidXLogRecPtr;
4074 : :
4075 [ + + + - ]: 336 : if (readSource == XLOG_FROM_PG_WAL && emode == LOG)
4076 : : {
4077 [ + + ]: 331 : if (RecPtr == lastComplaint)
4078 : 91 : emode = DEBUG1;
4079 : : else
4080 : 240 : lastComplaint = RecPtr;
4081 : : }
4082 : 336 : return emode;
4083 : : }
4084 : :
4085 : :
4086 : : /*
4087 : : * Subroutine to try to fetch and validate a prior checkpoint record.
4088 : : */
4089 : : static XLogRecord *
4090 : 1181 : ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
4091 : : TimeLineID replayTLI)
4092 : : {
4093 : : XLogRecord *record;
4094 : : uint8 info;
4095 : :
4096 : : Assert(xlogreader != NULL);
4097 : :
4098 [ - + ]: 1181 : if (!XRecOffIsValid(RecPtr))
4099 : : {
4100 [ # # ]: 0 : ereport(LOG,
4101 : : (errmsg("invalid checkpoint location")));
4102 : 0 : return NULL;
4103 : : }
4104 : :
4105 : 1181 : XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
4106 : 1181 : record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
4107 : :
4108 [ + + ]: 1181 : if (record == NULL)
4109 : : {
4110 [ + - ]: 2 : ereport(LOG,
4111 : : (errmsg("invalid checkpoint record")));
4112 : 2 : return NULL;
4113 : : }
4114 [ - + ]: 1179 : if (record->xl_rmid != RM_XLOG_ID)
4115 : : {
4116 [ # # ]: 0 : ereport(LOG,
4117 : : (errmsg("invalid resource manager ID in checkpoint record")));
4118 : 0 : return NULL;
4119 : : }
4120 : 1179 : info = record->xl_info & ~XLR_INFO_MASK;
4121 [ + + - + ]: 1179 : if (info != XLOG_CHECKPOINT_SHUTDOWN &&
4122 : : info != XLOG_CHECKPOINT_ONLINE)
4123 : : {
4124 [ # # ]: 0 : ereport(LOG,
4125 : : (errmsg("invalid xl_info in checkpoint record")));
4126 : 0 : return NULL;
4127 : : }
4128 [ - + ]: 1179 : if (record->xl_tot_len != SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(CheckPoint))
4129 : : {
4130 [ # # ]: 0 : ereport(LOG,
4131 : : (errmsg("invalid length of checkpoint record")));
4132 : 0 : return NULL;
4133 : : }
4134 : 1179 : return record;
4135 : : }
4136 : :
4137 : : /*
4138 : : * Scan for new timelines that might have appeared in the archive since we
4139 : : * started recovery.
4140 : : *
4141 : : * If there are any, the function changes recovery target TLI to the latest
4142 : : * one and returns 'true'.
4143 : : */
4144 : : static bool
4145 : 244 : rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN)
4146 : : {
4147 : : List *newExpectedTLEs;
4148 : : bool found;
4149 : : ListCell *cell;
4150 : : TimeLineID newtarget;
4151 : 244 : TimeLineID oldtarget = recoveryTargetTLI;
4152 : 244 : TimeLineHistoryEntry *currentTle = NULL;
4153 : :
4154 : 244 : newtarget = findNewestTimeLine(recoveryTargetTLI);
4155 [ + + ]: 244 : if (newtarget == recoveryTargetTLI)
4156 : : {
4157 : : /* No new timelines found */
4158 : 235 : return false;
4159 : : }
4160 : :
4161 : : /*
4162 : : * Determine the list of expected TLIs for the new TLI
4163 : : */
4164 : :
4165 : 9 : newExpectedTLEs = readTimeLineHistory(newtarget);
4166 : :
4167 : : /*
4168 : : * If the current timeline is not part of the history of the new timeline,
4169 : : * we cannot proceed to it.
4170 : : */
4171 : 9 : found = false;
4172 [ + - + - : 18 : foreach(cell, newExpectedTLEs)
+ - ]
4173 : : {
4174 : 18 : currentTle = (TimeLineHistoryEntry *) lfirst(cell);
4175 : :
4176 [ + + ]: 18 : if (currentTle->tli == recoveryTargetTLI)
4177 : : {
4178 : 9 : found = true;
4179 : 9 : break;
4180 : : }
4181 : : }
4182 [ - + ]: 9 : if (!found)
4183 : : {
4184 [ # # ]: 0 : ereport(LOG,
4185 : : (errmsg("new timeline %u is not a child of database system timeline %u",
4186 : : newtarget,
4187 : : replayTLI)));
4188 : 0 : return false;
4189 : : }
4190 : :
4191 : : /*
4192 : : * The current timeline was found in the history file, but check that the
4193 : : * next timeline was forked off from it *after* the current recovery
4194 : : * location.
4195 : : */
4196 [ - + ]: 9 : if (currentTle->end < replayLSN)
4197 : : {
4198 [ # # ]: 0 : ereport(LOG,
4199 : : errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%08X",
4200 : : newtarget,
4201 : : replayTLI,
4202 : : LSN_FORMAT_ARGS(replayLSN)));
4203 : 0 : return false;
4204 : : }
4205 : :
4206 : : /* The new timeline history seems valid. Switch target */
4207 : 9 : recoveryTargetTLI = newtarget;
4208 : 9 : list_free_deep(expectedTLEs);
4209 : 9 : expectedTLEs = newExpectedTLEs;
4210 : :
4211 : : /*
4212 : : * As in StartupXLOG(), try to ensure we have all the history files
4213 : : * between the old target and new target in pg_wal.
4214 : : */
4215 : 9 : restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
4216 : :
4217 [ + - ]: 9 : ereport(LOG,
4218 : : (errmsg("new target timeline is %u",
4219 : : recoveryTargetTLI)));
4220 : :
4221 : 9 : return true;
4222 : : }
4223 : :
4224 : :
4225 : : /*
4226 : : * Open a logfile segment for reading (during recovery).
4227 : : *
4228 : : * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
4229 : : * Otherwise, it's assumed to be already available in pg_wal.
4230 : : */
4231 : : static int
4232 : 4006 : XLogFileRead(XLogSegNo segno, TimeLineID tli,
4233 : : XLogSource source, bool notfoundOk)
4234 : : {
4235 : : char xlogfname[MAXFNAMELEN];
4236 : : char activitymsg[MAXFNAMELEN + 16];
4237 : : char path[MAXPGPATH];
4238 : : int fd;
4239 : :
4240 : 4006 : XLogFileName(xlogfname, tli, segno, wal_segment_size);
4241 : :
4242 [ + + - ]: 4006 : switch (source)
4243 : : {
4244 : 996 : case XLOG_FROM_ARCHIVE:
4245 : : /* Report recovery progress in PS display */
4246 : 996 : snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
4247 : : xlogfname);
4248 : 996 : set_ps_display(activitymsg);
4249 : :
4250 [ + + ]: 996 : if (!RestoreArchivedFile(path, xlogfname,
4251 : : "RECOVERYXLOG",
4252 : : wal_segment_size,
4253 : : InRedo))
4254 : 624 : return -1;
4255 : 371 : break;
4256 : :
4257 : 3010 : case XLOG_FROM_PG_WAL:
4258 : : case XLOG_FROM_STREAM:
4259 : 3010 : XLogFilePath(path, tli, segno, wal_segment_size);
4260 : 3010 : break;
4261 : :
4262 : 0 : default:
4263 [ # # ]: 0 : elog(ERROR, "invalid XLogFileRead source %d", source);
4264 : : }
4265 : :
4266 : : /*
4267 : : * If the segment was fetched from archival storage, replace the existing
4268 : : * xlog segment (if any) with the archival version.
4269 : : */
4270 [ + + ]: 3381 : if (source == XLOG_FROM_ARCHIVE)
4271 : : {
4272 : : Assert(!IsInstallXLogFileSegmentActive());
4273 : 371 : KeepFileRestoredFromArchive(path, xlogfname);
4274 : :
4275 : : /*
4276 : : * Set path to point at the new file in pg_wal.
4277 : : */
4278 : 371 : snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
4279 : : }
4280 : :
4281 : 3381 : fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
4282 [ + + ]: 3381 : if (fd >= 0)
4283 : : {
4284 : : /* Success! */
4285 : 3133 : curFileTLI = tli;
4286 : :
4287 : : /* Report recovery progress in PS display */
4288 : 3133 : snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
4289 : : xlogfname);
4290 : 3133 : set_ps_display(activitymsg);
4291 : :
4292 : : /* Track source of data in assorted state variables */
4293 : 3133 : readSource = source;
4294 : 3133 : XLogReceiptSource = source;
4295 : : /* In FROM_STREAM case, caller tracks receipt time, not me */
4296 [ + + ]: 3133 : if (source != XLOG_FROM_STREAM)
4297 : 1897 : XLogReceiptTime = GetCurrentTimestamp();
4298 : :
4299 : 3133 : return fd;
4300 : : }
4301 [ + - - + ]: 248 : if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
4302 [ # # ]: 0 : ereport(PANIC,
4303 : : (errcode_for_file_access(),
4304 : : errmsg("could not open file \"%s\": %m", path)));
4305 : 248 : return -1;
4306 : : }
4307 : :
4308 : : /*
4309 : : * Open a logfile segment for reading (during recovery).
4310 : : *
4311 : : * This version searches for the segment with any TLI listed in expectedTLEs.
4312 : : */
4313 : : static int
4314 : 2133 : XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source)
4315 : : {
4316 : : char path[MAXPGPATH];
4317 : : ListCell *cell;
4318 : : int fd;
4319 : : List *tles;
4320 : :
4321 : : /*
4322 : : * Loop looking for a suitable timeline ID: we might need to read any of
4323 : : * the timelines listed in expectedTLEs.
4324 : : *
4325 : : * We expect curFileTLI on entry to be the TLI of the preceding file in
4326 : : * sequence, or 0 if there was no predecessor. We do not allow curFileTLI
4327 : : * to go backwards; this prevents us from picking up the wrong file when a
4328 : : * parent timeline extends to higher segment numbers than the child we
4329 : : * want to read.
4330 : : *
4331 : : * If we haven't read the timeline history file yet, read it now, so that
4332 : : * we know which TLIs to scan. We don't save the list in expectedTLEs,
4333 : : * however, unless we actually find a valid segment. That way if there is
4334 : : * neither a timeline history file nor a WAL segment in the archive, and
4335 : : * streaming replication is set up, we'll read the timeline history file
4336 : : * streamed from the primary when we start streaming, instead of
4337 : : * recovering with a dummy history generated here.
4338 : : */
4339 [ + + ]: 2133 : if (expectedTLEs)
4340 : 952 : tles = expectedTLEs;
4341 : : else
4342 : 1181 : tles = readTimeLineHistory(recoveryTargetTLI);
4343 : :
4344 [ + - + + : 2388 : foreach(cell, tles)
+ + ]
4345 : : {
4346 : 2161 : TimeLineHistoryEntry *hent = (TimeLineHistoryEntry *) lfirst(cell);
4347 : 2161 : TimeLineID tli = hent->tli;
4348 : :
4349 [ + + ]: 2161 : if (tli < curFileTLI)
4350 : 8 : break; /* don't bother looking at too-old TLIs */
4351 : :
4352 : : /*
4353 : : * Skip scanning the timeline ID that the logfile segment to read
4354 : : * doesn't belong to
4355 : : */
4356 [ + + ]: 2153 : if (XLogRecPtrIsValid(hent->begin))
4357 : : {
4358 : 94 : XLogSegNo beginseg = 0;
4359 : :
4360 : 94 : XLByteToSeg(hent->begin, beginseg, wal_segment_size);
4361 : :
4362 : : /*
4363 : : * The logfile segment that doesn't belong to the timeline is
4364 : : * older or newer than the segment that the timeline started or
4365 : : * ended at, respectively. It's sufficient to check only the
4366 : : * starting segment of the timeline here. Since the timelines are
4367 : : * scanned in descending order in this loop, any segments newer
4368 : : * than the ending segment should belong to newer timeline and
4369 : : * have already been read before. So it's not necessary to check
4370 : : * the ending segment of the timeline here.
4371 : : */
4372 [ + + ]: 94 : if (segno < beginseg)
4373 : 7 : continue;
4374 : : }
4375 : :
4376 [ + + - + ]: 2146 : if (source == XLOG_FROM_ANY || source == XLOG_FROM_ARCHIVE)
4377 : : {
4378 : 996 : fd = XLogFileRead(segno, tli, XLOG_FROM_ARCHIVE, true);
4379 [ + + ]: 995 : if (fd != -1)
4380 : : {
4381 [ - + ]: 371 : elog(DEBUG1, "got WAL segment from archive");
4382 [ + + ]: 371 : if (!expectedTLEs)
4383 : 22 : expectedTLEs = tles;
4384 : 1897 : return fd;
4385 : : }
4386 : : }
4387 : :
4388 [ + + + - ]: 1774 : if (source == XLOG_FROM_ANY || source == XLOG_FROM_PG_WAL)
4389 : : {
4390 : 1774 : fd = XLogFileRead(segno, tli, XLOG_FROM_PG_WAL, true);
4391 [ + + ]: 1774 : if (fd != -1)
4392 : : {
4393 [ + + ]: 1526 : if (!expectedTLEs)
4394 : 1157 : expectedTLEs = tles;
4395 : 1526 : return fd;
4396 : : }
4397 : : }
4398 : : }
4399 : :
4400 : : /* Couldn't find it. For simplicity, complain about front timeline */
4401 : 235 : XLogFilePath(path, recoveryTargetTLI, segno, wal_segment_size);
4402 : 235 : errno = ENOENT;
4403 [ + + ]: 235 : ereport(DEBUG2,
4404 : : (errcode_for_file_access(),
4405 : : errmsg("could not open file \"%s\": %m", path)));
4406 : 235 : return -1;
4407 : : }
4408 : :
4409 : : /*
4410 : : * Set flag to signal the walreceiver to restart. (The startup process calls
4411 : : * this on noticing a relevant configuration change.)
4412 : : */
4413 : : void
4414 : 16 : StartupRequestWalReceiverRestart(void)
4415 : : {
4416 [ + - + + ]: 16 : if (currentSource == XLOG_FROM_STREAM && WalRcvRunning())
4417 : : {
4418 [ + - ]: 10 : ereport(LOG,
4419 : : (errmsg("WAL receiver process shutdown requested")));
4420 : :
4421 : 10 : pendingWalRcvRestart = true;
4422 : : }
4423 : 16 : }
4424 : :
4425 : :
4426 : : /*
4427 : : * Has a standby promotion already been triggered?
4428 : : *
4429 : : * Unlike CheckForStandbyTrigger(), this works in any process
4430 : : * that's connected to shared memory.
4431 : : */
4432 : : bool
4433 : 93 : PromoteIsTriggered(void)
4434 : : {
4435 : : /*
4436 : : * We check shared state each time only until a standby promotion is
4437 : : * triggered. We can't trigger a promotion again, so there's no need to
4438 : : * keep checking after the shared variable has once been seen true.
4439 : : */
4440 [ + + ]: 93 : if (LocalPromoteIsTriggered)
4441 : 62 : return true;
4442 : :
4443 : 31 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4444 : 31 : LocalPromoteIsTriggered = XLogRecoveryCtl->SharedPromoteIsTriggered;
4445 : 31 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4446 : :
4447 : 31 : return LocalPromoteIsTriggered;
4448 : : }
4449 : :
4450 : : static void
4451 : 59 : SetPromoteIsTriggered(void)
4452 : : {
4453 : 59 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4454 : 59 : XLogRecoveryCtl->SharedPromoteIsTriggered = true;
4455 : 59 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4456 : :
4457 : : /*
4458 : : * Mark the recovery pause state as 'not paused' because the paused state
4459 : : * ends and promotion continues if a promotion is triggered while recovery
4460 : : * is paused. Otherwise pg_get_wal_replay_pause_state() can mistakenly
4461 : : * return 'paused' while a promotion is ongoing.
4462 : : */
4463 : 59 : SetRecoveryPause(false);
4464 : :
4465 : 59 : LocalPromoteIsTriggered = true;
4466 : 59 : }
4467 : :
4468 : : /*
4469 : : * Check whether a promote request has arrived.
4470 : : */
4471 : : static bool
4472 : 17204 : CheckForStandbyTrigger(void)
4473 : : {
4474 [ + + ]: 17204 : if (LocalPromoteIsTriggered)
4475 : 57 : return true;
4476 : :
4477 [ + + + - ]: 17147 : if (IsPromoteSignaled() && CheckPromoteSignal())
4478 : : {
4479 [ + - ]: 59 : ereport(LOG, (errmsg("received promote request")));
4480 : 59 : RemovePromoteSignalFiles();
4481 : 59 : ResetPromoteSignaled();
4482 : 59 : SetPromoteIsTriggered();
4483 : 59 : return true;
4484 : : }
4485 : :
4486 : 17088 : return false;
4487 : : }
4488 : :
4489 : : /*
4490 : : * Remove the files signaling a standby promotion request.
4491 : : */
4492 : : void
4493 : 1146 : RemovePromoteSignalFiles(void)
4494 : : {
4495 : 1146 : unlink(PROMOTE_SIGNAL_FILE);
4496 : 1146 : }
4497 : :
4498 : : /*
4499 : : * Check to see if a promote request has arrived.
4500 : : */
4501 : : bool
4502 : 857 : CheckPromoteSignal(void)
4503 : : {
4504 : : struct stat stat_buf;
4505 : :
4506 [ + + ]: 857 : if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
4507 : 118 : return true;
4508 : :
4509 : 739 : return false;
4510 : : }
4511 : :
4512 : : /*
4513 : : * Has hot standby initialization started pg_subtrans?
4514 : : */
4515 : : bool
4516 : 215 : RecoverySubtransInitialized(void)
4517 : : {
4518 : : bool result;
4519 : :
4520 : 215 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4521 : 215 : result = XLogRecoveryCtl->SharedRecoverySubtransInitialized;
4522 : 215 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4523 : :
4524 : 215 : return result;
4525 : : }
4526 : :
4527 : : /*
4528 : : * Remember that hot standby initialization has started pg_subtrans.
4529 : : */
4530 : : void
4531 : 139 : SetRecoverySubtransInitialized(void)
4532 : : {
4533 : 139 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4534 : 139 : XLogRecoveryCtl->SharedRecoverySubtransInitialized = true;
4535 : 139 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4536 : 139 : }
4537 : :
4538 : : /*
4539 : : * Wake up startup process to replay newly arrived WAL, or to notice that
4540 : : * failover has been requested.
4541 : : */
4542 : : void
4543 : 45453 : WakeupRecovery(void)
4544 : : {
4545 : 45453 : SetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
4546 : 45453 : }
4547 : :
4548 : : /*
4549 : : * Schedule a walreceiver wakeup in the main recovery loop.
4550 : : */
4551 : : void
4552 : 3 : XLogRequestWalReceiverReply(void)
4553 : : {
4554 : 3 : doRequestWalReceiverReply = true;
4555 : 3 : }
4556 : :
4557 : : /*
4558 : : * Is HotStandby active yet? This is only important in special backends
4559 : : * since normal backends won't ever be able to connect until this returns
4560 : : * true. Postmaster knows this by way of signal, not via shared memory.
4561 : : *
4562 : : * Unlike testing standbyState, this works in any process that's connected to
4563 : : * shared memory. (And note that standbyState alone doesn't tell the truth
4564 : : * anyway.)
4565 : : */
4566 : : bool
4567 : 197 : HotStandbyActive(void)
4568 : : {
4569 : : /*
4570 : : * We check shared state each time only until Hot Standby is active. We
4571 : : * can't de-activate Hot Standby, so there's no need to keep checking
4572 : : * after the shared variable has once been seen true.
4573 : : */
4574 [ + + ]: 197 : if (LocalHotStandbyActive)
4575 : 25 : return true;
4576 : : else
4577 : : {
4578 : : /* spinlock is essential on machines with weak memory ordering! */
4579 : 172 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4580 : 172 : LocalHotStandbyActive = XLogRecoveryCtl->SharedHotStandbyActive;
4581 : 172 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4582 : :
4583 : 172 : return LocalHotStandbyActive;
4584 : : }
4585 : : }
4586 : :
4587 : : /*
4588 : : * Like HotStandbyActive(), but to be used only in WAL replay code,
4589 : : * where we don't need to ask any other process what the state is.
4590 : : */
4591 : : bool
4592 : 53 : HotStandbyActiveInReplay(void)
4593 : : {
4594 : : Assert(AmStartupProcess() || !IsPostmasterEnvironment);
4595 : 53 : return LocalHotStandbyActive;
4596 : : }
4597 : :
4598 : : /*
4599 : : * Get latest redo apply position.
4600 : : *
4601 : : * Exported to allow WALReceiver to read the pointer directly.
4602 : : */
4603 : : XLogRecPtr
4604 : 124974 : GetXLogReplayRecPtr(TimeLineID *replayTLI)
4605 : : {
4606 : : XLogRecPtr recptr;
4607 : : TimeLineID tli;
4608 : :
4609 : 124974 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4610 : 124974 : recptr = XLogRecoveryCtl->lastReplayedEndRecPtr;
4611 : 124974 : tli = XLogRecoveryCtl->lastReplayedTLI;
4612 : 124974 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4613 : :
4614 [ + + ]: 124974 : if (replayTLI)
4615 : 6990 : *replayTLI = tli;
4616 : 124974 : return recptr;
4617 : : }
4618 : :
4619 : :
4620 : : /*
4621 : : * Get position of last applied, or the record being applied.
4622 : : *
4623 : : * This is different from GetXLogReplayRecPtr() in that if a WAL
4624 : : * record is currently being applied, this includes that record.
4625 : : */
4626 : : XLogRecPtr
4627 : 7067 : GetCurrentReplayRecPtr(TimeLineID *replayEndTLI)
4628 : : {
4629 : : XLogRecPtr recptr;
4630 : : TimeLineID tli;
4631 : :
4632 : 7067 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4633 : 7067 : recptr = XLogRecoveryCtl->replayEndRecPtr;
4634 : 7067 : tli = XLogRecoveryCtl->replayEndTLI;
4635 : 7067 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4636 : :
4637 [ + - ]: 7067 : if (replayEndTLI)
4638 : 7067 : *replayEndTLI = tli;
4639 : 7067 : return recptr;
4640 : : }
4641 : :
4642 : : /*
4643 : : * Save timestamp of latest processed commit/abort record.
4644 : : *
4645 : : * We keep this in XLogRecoveryCtl, not a simple static variable, so that it can be
4646 : : * seen by processes other than the startup process. Note in particular
4647 : : * that CreateRestartPoint is executed in the checkpointer.
4648 : : */
4649 : : static void
4650 : 24483 : SetLatestXTime(TimestampTz xtime)
4651 : : {
4652 : 24483 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4653 : 24483 : XLogRecoveryCtl->recoveryLastXTime = xtime;
4654 : 24483 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4655 : 24483 : }
4656 : :
4657 : : /*
4658 : : * Fetch timestamp of latest processed commit/abort record.
4659 : : */
4660 : : TimestampTz
4661 : 390 : GetLatestXTime(void)
4662 : : {
4663 : : TimestampTz xtime;
4664 : :
4665 : 390 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4666 : 390 : xtime = XLogRecoveryCtl->recoveryLastXTime;
4667 : 390 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4668 : :
4669 : 390 : return xtime;
4670 : : }
4671 : :
4672 : : /*
4673 : : * Save timestamp of the next chunk of WAL records to apply.
4674 : : *
4675 : : * We keep this in XLogRecoveryCtl, not a simple static variable, so that it can be
4676 : : * seen by all backends.
4677 : : */
4678 : : static void
4679 : 13658 : SetCurrentChunkStartTime(TimestampTz xtime)
4680 : : {
4681 : 13658 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4682 : 13658 : XLogRecoveryCtl->currentChunkStartTime = xtime;
4683 : 13658 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4684 : 13658 : }
4685 : :
4686 : : /*
4687 : : * Fetch timestamp of latest processed commit/abort record.
4688 : : * Startup process maintains an accurate local copy in XLogReceiptTime
4689 : : */
4690 : : TimestampTz
4691 : 294 : GetCurrentChunkReplayStartTime(void)
4692 : : {
4693 : : TimestampTz xtime;
4694 : :
4695 : 294 : SpinLockAcquire(&XLogRecoveryCtl->info_lck);
4696 : 294 : xtime = XLogRecoveryCtl->currentChunkStartTime;
4697 : 294 : SpinLockRelease(&XLogRecoveryCtl->info_lck);
4698 : :
4699 : 294 : return xtime;
4700 : : }
4701 : :
4702 : : /*
4703 : : * Returns time of receipt of current chunk of XLOG data, as well as
4704 : : * whether it was received from streaming replication or from archives.
4705 : : */
4706 : : void
4707 : 27 : GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream)
4708 : : {
4709 : : /*
4710 : : * This must be executed in the startup process, since we don't export the
4711 : : * relevant state to shared memory.
4712 : : */
4713 : : Assert(InRecovery);
4714 : :
4715 : 27 : *rtime = XLogReceiptTime;
4716 : 27 : *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
4717 : 27 : }
4718 : :
4719 : : /*
4720 : : * Note that text field supplied is a parameter name and does not require
4721 : : * translation
4722 : : */
4723 : : void
4724 : 815 : RecoveryRequiresIntParameter(const char *param_name, int currValue, int minValue)
4725 : : {
4726 [ - + ]: 815 : if (currValue < minValue)
4727 : : {
4728 [ # # ]: 0 : if (HotStandbyActiveInReplay())
4729 : : {
4730 : 0 : bool warned_for_promote = false;
4731 : :
4732 [ # # ]: 0 : ereport(WARNING,
4733 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4734 : : errmsg("hot standby is not possible because of insufficient parameter settings"),
4735 : : errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4736 : : param_name,
4737 : : currValue,
4738 : : minValue)));
4739 : :
4740 : 0 : SetRecoveryPause(true);
4741 : :
4742 [ # # ]: 0 : ereport(LOG,
4743 : : (errmsg("recovery has paused"),
4744 : : errdetail("If recovery is unpaused, the server will shut down."),
4745 : : errhint("You can then restart the server after making the necessary configuration changes.")));
4746 : :
4747 [ # # ]: 0 : while (GetRecoveryPauseState() != RECOVERY_NOT_PAUSED)
4748 : : {
4749 : 0 : ProcessStartupProcInterrupts();
4750 : :
4751 [ # # ]: 0 : if (CheckForStandbyTrigger())
4752 : : {
4753 [ # # ]: 0 : if (!warned_for_promote)
4754 [ # # ]: 0 : ereport(WARNING,
4755 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4756 : : errmsg("promotion is not possible because of insufficient parameter settings"),
4757 : :
4758 : : /*
4759 : : * Repeat the detail from above so it's easy to find
4760 : : * in the log.
4761 : : */
4762 : : errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4763 : : param_name,
4764 : : currValue,
4765 : : minValue),
4766 : : errhint("Restart the server after making the necessary configuration changes.")));
4767 : 0 : warned_for_promote = true;
4768 : : }
4769 : :
4770 : : /*
4771 : : * If recovery pause is requested then set it paused. While
4772 : : * we are in the loop, user might resume and pause again so
4773 : : * set this every time.
4774 : : */
4775 : 0 : ConfirmRecoveryPaused();
4776 : :
4777 : : /*
4778 : : * We wait on a condition variable that will wake us as soon
4779 : : * as the pause ends, but we use a timeout so we can check the
4780 : : * above conditions periodically too.
4781 : : */
4782 : 0 : ConditionVariableTimedSleep(&XLogRecoveryCtl->recoveryNotPausedCV, 1000,
4783 : : WAIT_EVENT_RECOVERY_PAUSE);
4784 : : }
4785 : 0 : ConditionVariableCancelSleep();
4786 : : }
4787 : :
4788 [ # # ]: 0 : ereport(FATAL,
4789 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4790 : : errmsg("recovery aborted because of insufficient parameter settings"),
4791 : : /* Repeat the detail from above so it's easy to find in the log. */
4792 : : errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4793 : : param_name,
4794 : : currValue,
4795 : : minValue),
4796 : : errhint("You can restart the server after making the necessary configuration changes.")));
4797 : : }
4798 : 815 : }
4799 : :
4800 : :
4801 : : /*
4802 : : * GUC check_hook for primary_slot_name
4803 : : */
4804 : : bool
4805 : 1592 : check_primary_slot_name(char **newval, void **extra, GucSource source)
4806 : : {
4807 : : int err_code;
4808 : 1592 : char *err_msg = NULL;
4809 : 1592 : char *err_hint = NULL;
4810 : :
4811 [ + - + + ]: 1592 : if (*newval && strcmp(*newval, "") != 0 &&
4812 [ - + ]: 188 : !ReplicationSlotValidateNameInternal(*newval, false, &err_code,
4813 : : &err_msg, &err_hint))
4814 : : {
4815 : 0 : GUC_check_errcode(err_code);
4816 : 0 : GUC_check_errdetail("%s", err_msg);
4817 [ # # ]: 0 : if (err_hint != NULL)
4818 : 0 : GUC_check_errhint("%s", err_hint);
4819 : 0 : return false;
4820 : : }
4821 : :
4822 : 1592 : return true;
4823 : : }
4824 : :
4825 : : /*
4826 : : * Return the recovery target derived from the recovery_target* settings,
4827 : : * raising an error if more than one of them is set.
4828 : : */
4829 : : static RecoveryTargetType
4830 : 1184 : DetermineRecoveryTargetType(void)
4831 : : {
4832 : 1184 : int ntargets = 0;
4833 : 1184 : RecoveryTargetType target = RECOVERY_TARGET_UNSET;
4834 : : const char *val;
4835 : : StringInfoData buf;
4836 : :
4837 : 1184 : initStringInfo(&buf);
4838 : :
4839 : : #define ADD_TARGET_IF_SET(gucname, kind) \
4840 : : do { \
4841 : : val = GetConfigOption(gucname, false, false); \
4842 : : if (val[0] != '\0') \
4843 : : { \
4844 : : ntargets++; \
4845 : : target = (kind); \
4846 : : if (buf.len == 0) \
4847 : : appendStringInfo(&buf, _("\"%s\""), gucname); \
4848 : : else \
4849 : : appendStringInfo(&buf, _(", \"%s\""), gucname); \
4850 : : } \
4851 : : } while (0)
4852 : :
4853 [ + + + - ]: 1184 : ADD_TARGET_IF_SET("recovery_target", RECOVERY_TARGET_IMMEDIATE);
4854 [ + + + - ]: 1184 : ADD_TARGET_IF_SET("recovery_target_lsn", RECOVERY_TARGET_LSN);
4855 [ + + + - ]: 1184 : ADD_TARGET_IF_SET("recovery_target_name", RECOVERY_TARGET_NAME);
4856 [ + + - + ]: 1184 : ADD_TARGET_IF_SET("recovery_target_time", RECOVERY_TARGET_TIME);
4857 [ + + - + ]: 1184 : ADD_TARGET_IF_SET("recovery_target_xid", RECOVERY_TARGET_XID);
4858 : : #undef ADD_TARGET_IF_SET
4859 : :
4860 [ + + ]: 1184 : if (ntargets > 1)
4861 [ + - ]: 2 : ereport(FATAL,
4862 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4863 : : errmsg("cannot specify more than one recovery target"),
4864 : : errdetail("Parameters set are: %s.",
4865 : : buf.data));
4866 : :
4867 : 1182 : pfree(buf.data);
4868 : :
4869 : 1182 : return target;
4870 : : }
4871 : :
4872 : : /*
4873 : : * GUC check_hook for recovery_target
4874 : : */
4875 : : bool
4876 : 1406 : check_recovery_target(char **newval, void **extra, GucSource source)
4877 : : {
4878 [ + + - + ]: 1406 : if (strcmp(*newval, "immediate") != 0 && strcmp(*newval, "") != 0)
4879 : : {
4880 : 0 : GUC_check_errdetail("The only allowed value is \"immediate\".");
4881 : 0 : return false;
4882 : : }
4883 : 1406 : return true;
4884 : : }
4885 : :
4886 : : /*
4887 : : * GUC check_hook for recovery_target_lsn
4888 : : */
4889 : : bool
4890 : 1413 : check_recovery_target_lsn(char **newval, void **extra, GucSource source)
4891 : : {
4892 [ + + ]: 1413 : if (strcmp(*newval, "") != 0)
4893 : : {
4894 : : XLogRecPtr lsn;
4895 : : XLogRecPtr *myextra;
4896 : 10 : ErrorSaveContext escontext = {T_ErrorSaveContext};
4897 : :
4898 : 10 : lsn = pg_lsn_in_safe(*newval, (Node *) &escontext);
4899 [ - + ]: 10 : if (escontext.error_occurred)
4900 : 0 : return false;
4901 : :
4902 : 10 : myextra = (XLogRecPtr *) guc_malloc(LOG, sizeof(XLogRecPtr));
4903 [ - + ]: 10 : if (!myextra)
4904 : 0 : return false;
4905 : 10 : *myextra = lsn;
4906 : 10 : *extra = myextra;
4907 : : }
4908 : 1413 : return true;
4909 : : }
4910 : :
4911 : : /*
4912 : : * GUC assign_hook for recovery_target_lsn
4913 : : */
4914 : : void
4915 : 1413 : assign_recovery_target_lsn(const char *newval, void *extra)
4916 : : {
4917 [ + - + + ]: 1413 : if (newval && strcmp(newval, "") != 0)
4918 : 10 : recoveryTargetLSN = *((XLogRecPtr *) extra);
4919 : 1413 : }
4920 : :
4921 : : /*
4922 : : * GUC check_hook for recovery_target_name
4923 : : */
4924 : : bool
4925 : 1413 : check_recovery_target_name(char **newval, void **extra, GucSource source)
4926 : : {
4927 : : /* Use the value of newval directly */
4928 [ - + ]: 1413 : if (strlen(*newval) >= MAXFNAMELEN)
4929 : : {
4930 : 0 : GUC_check_errdetail("\"%s\" is too long (maximum %d characters).",
4931 : : "recovery_target_name", MAXFNAMELEN - 1);
4932 : 0 : return false;
4933 : : }
4934 : 1413 : return true;
4935 : : }
4936 : :
4937 : : /*
4938 : : * GUC check_hook for recovery_target_time
4939 : : *
4940 : : * The interpretation of the recovery_target_time string can depend on the
4941 : : * time zone setting, so we need to wait until after all GUC processing is
4942 : : * done before we can do the final parsing of the string. This check function
4943 : : * only does a parsing pass to catch syntax errors, but we store the string
4944 : : * and parse it again when we need to use it.
4945 : : */
4946 : : bool
4947 : 1408 : check_recovery_target_time(char **newval, void **extra, GucSource source)
4948 : : {
4949 [ + + ]: 1408 : if (strcmp(*newval, "") != 0)
4950 : : {
4951 : : /* reject some special values */
4952 [ + - ]: 3 : if (strcmp(*newval, "now") == 0 ||
4953 [ + - ]: 3 : strcmp(*newval, "today") == 0 ||
4954 [ + - ]: 3 : strcmp(*newval, "tomorrow") == 0 ||
4955 [ - + ]: 3 : strcmp(*newval, "yesterday") == 0)
4956 : : {
4957 : 0 : return false;
4958 : : }
4959 : :
4960 : : /*
4961 : : * parse timestamp value (see also timestamptz_in())
4962 : : */
4963 : : {
4964 : 3 : char *str = *newval;
4965 : : fsec_t fsec;
4966 : : struct pg_tm tt,
4967 : 3 : *tm = &tt;
4968 : : int tz;
4969 : : int dtype;
4970 : : int nf;
4971 : : int dterr;
4972 : : char *field[MAXDATEFIELDS];
4973 : : int ftype[MAXDATEFIELDS];
4974 : : char workbuf[MAXDATELEN + MAXDATEFIELDS];
4975 : : DateTimeErrorExtra dtextra;
4976 : : TimestampTz timestamp;
4977 : :
4978 : 3 : dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
4979 : : field, ftype, MAXDATEFIELDS, &nf);
4980 [ + - ]: 3 : if (dterr == 0)
4981 : 3 : dterr = DecodeDateTime(field, ftype, nf,
4982 : : &dtype, tm, &fsec, &tz, &dtextra);
4983 [ - + ]: 3 : if (dterr != 0)
4984 : 0 : return false;
4985 [ - + ]: 3 : if (dtype != DTK_DATE)
4986 : 0 : return false;
4987 : :
4988 [ - + ]: 3 : if (tm2timestamp(tm, fsec, &tz, ×tamp) != 0)
4989 : : {
4990 : 0 : GUC_check_errdetail("Timestamp out of range: \"%s\".", str);
4991 : 0 : return false;
4992 : : }
4993 : : }
4994 : : }
4995 : 1408 : return true;
4996 : : }
4997 : :
4998 : : /*
4999 : : * GUC check_hook for recovery_target_timeline
5000 : : */
5001 : : bool
5002 : 1408 : check_recovery_target_timeline(char **newval, void **extra, GucSource source)
5003 : : {
5004 : : RecoveryTargetTimeLineGoal rttg;
5005 : : RecoveryTargetTimeLineGoal *myextra;
5006 : :
5007 [ - + ]: 1408 : if (strcmp(*newval, "current") == 0)
5008 : 0 : rttg = RECOVERY_TARGET_TIMELINE_CONTROLFILE;
5009 [ + + ]: 1408 : else if (strcmp(*newval, "latest") == 0)
5010 : 1405 : rttg = RECOVERY_TARGET_TIMELINE_LATEST;
5011 : : else
5012 : : {
5013 : : char *endp;
5014 : : uint64 timeline;
5015 : :
5016 : 3 : rttg = RECOVERY_TARGET_TIMELINE_NUMERIC;
5017 : :
5018 : 3 : errno = 0;
5019 : 3 : timeline = strtou64(*newval, &endp, 0);
5020 : :
5021 [ + + + - : 3 : if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
- + ]
5022 : : {
5023 : 1 : GUC_check_errdetail("\"%s\" is not a valid number.",
5024 : : "recovery_target_timeline");
5025 : 3 : return false;
5026 : : }
5027 : :
5028 [ + + + - ]: 2 : if (timeline < 1 || timeline > PG_UINT32_MAX)
5029 : : {
5030 : 2 : GUC_check_errdetail("\"%s\" must be between %u and %u.",
5031 : : "recovery_target_timeline", 1, PG_UINT32_MAX);
5032 : 2 : return false;
5033 : : }
5034 : : }
5035 : :
5036 : 1405 : myextra = (RecoveryTargetTimeLineGoal *) guc_malloc(LOG, sizeof(RecoveryTargetTimeLineGoal));
5037 [ - + ]: 1405 : if (!myextra)
5038 : 0 : return false;
5039 : 1405 : *myextra = rttg;
5040 : 1405 : *extra = myextra;
5041 : :
5042 : 1405 : return true;
5043 : : }
5044 : :
5045 : : /*
5046 : : * GUC assign_hook for recovery_target_timeline
5047 : : */
5048 : : void
5049 : 1405 : assign_recovery_target_timeline(const char *newval, void *extra)
5050 : : {
5051 : 1405 : recoveryTargetTimeLineGoal = *((RecoveryTargetTimeLineGoal *) extra);
5052 [ - + ]: 1405 : if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_NUMERIC)
5053 : 0 : recoveryTargetTLIRequested = (TimeLineID) strtoul(newval, NULL, 0);
5054 : : else
5055 : 1405 : recoveryTargetTLIRequested = 0;
5056 : 1405 : }
5057 : :
5058 : : /*
5059 : : * GUC check_hook for recovery_target_xid
5060 : : */
5061 : : bool
5062 : 1413 : check_recovery_target_xid(char **newval, void **extra, GucSource source)
5063 : : {
5064 [ + + ]: 1413 : if (strcmp(*newval, "") != 0)
5065 : : {
5066 : : TransactionId xid;
5067 : : TransactionId *myextra;
5068 : : char *endp;
5069 : : char *val;
5070 : :
5071 : 8 : errno = 0;
5072 : :
5073 : : /*
5074 : : * Consume leading whitespace to determine if number is negative
5075 : : */
5076 : 8 : val = *newval;
5077 : :
5078 [ - + ]: 8 : while (isspace((unsigned char) *val))
5079 : 0 : val++;
5080 : :
5081 : : /*
5082 : : * This cast will remove the epoch, if any
5083 : : */
5084 : 8 : xid = (TransactionId) strtou64(val, &endp, 0);
5085 : :
5086 [ + + + - : 8 : if (*endp != '\0' || errno == EINVAL || errno == ERANGE || *val == '-')
+ - + + ]
5087 : : {
5088 : 2 : GUC_check_errdetail("\"%s\" is not a valid number.",
5089 : : "recovery_target_xid");
5090 : 3 : return false;
5091 : : }
5092 : :
5093 [ + + ]: 6 : if (xid < FirstNormalTransactionId)
5094 : : {
5095 : 1 : GUC_check_errdetail("\"%s\" without epoch must be greater than or equal to %u.",
5096 : : "recovery_target_xid",
5097 : : FirstNormalTransactionId);
5098 : 1 : return false;
5099 : : }
5100 : :
5101 : 5 : myextra = (TransactionId *) guc_malloc(LOG, sizeof(TransactionId));
5102 [ - + ]: 5 : if (!myextra)
5103 : 0 : return false;
5104 : 5 : *myextra = xid;
5105 : 5 : *extra = myextra;
5106 : : }
5107 : 1410 : return true;
5108 : : }
5109 : :
5110 : : /*
5111 : : * GUC assign_hook for recovery_target_xid
5112 : : */
5113 : : void
5114 : 1410 : assign_recovery_target_xid(const char *newval, void *extra)
5115 : : {
5116 [ + - + + ]: 1410 : if (newval && strcmp(newval, "") != 0)
5117 : 5 : recoveryTargetXid = *((TransactionId *) extra);
5118 : 1410 : }
|