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