PostgreSQL Source Code git master
xlogrecovery.h File Reference
#include "access/xlogreader.h"
#include "catalog/pg_control.h"
#include "lib/stringinfo.h"
#include "utils/timestamp.h"
Include dependency graph for xlogrecovery.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  EndOfWalRecoveryInfo
 

Typedefs

typedef enum RecoveryPauseState RecoveryPauseState
 

Enumerations

enum  RecoveryTargetType {
  RECOVERY_TARGET_UNSET , RECOVERY_TARGET_XID , RECOVERY_TARGET_TIME , RECOVERY_TARGET_NAME ,
  RECOVERY_TARGET_LSN , RECOVERY_TARGET_IMMEDIATE
}
 
enum  RecoveryTargetTimeLineGoal { RECOVERY_TARGET_TIMELINE_CONTROLFILE , RECOVERY_TARGET_TIMELINE_LATEST , RECOVERY_TARGET_TIMELINE_NUMERIC }
 
enum  RecoveryTargetAction { RECOVERY_TARGET_ACTION_PAUSE , RECOVERY_TARGET_ACTION_PROMOTE , RECOVERY_TARGET_ACTION_SHUTDOWN }
 
enum  RecoveryPauseState { RECOVERY_NOT_PAUSED , RECOVERY_PAUSE_REQUESTED , RECOVERY_PAUSED }
 

Functions

Size XLogRecoveryShmemSize (void)
 
void XLogRecoveryShmemInit (void)
 
void InitWalRecovery (ControlFileData *ControlFile, bool *wasShutdown_ptr, bool *haveBackupLabel_ptr, bool *haveTblspcMap_ptr)
 
void PerformWalRecovery (void)
 
EndOfWalRecoveryInfoFinishWalRecovery (void)
 
void ShutdownWalRecovery (void)
 
void RemovePromoteSignalFiles (void)
 
bool HotStandbyActive (void)
 
XLogRecPtr GetXLogReplayRecPtr (TimeLineID *replayTLI)
 
RecoveryPauseState GetRecoveryPauseState (void)
 
void SetRecoveryPause (bool recoveryPause)
 
void GetXLogReceiptTime (TimestampTz *rtime, bool *fromStream)
 
TimestampTz GetLatestXTime (void)
 
TimestampTz GetCurrentChunkReplayStartTime (void)
 
XLogRecPtr GetCurrentReplayRecPtr (TimeLineID *replayEndTLI)
 
bool PromoteIsTriggered (void)
 
bool CheckPromoteSignal (void)
 
void WakeupRecovery (void)
 
void StartupRequestWalReceiverRestart (void)
 
void XLogRequestWalReceiverReply (void)
 
void RecoveryRequiresIntParameter (const char *param_name, int currValue, int minValue)
 
void xlog_outdesc (StringInfo buf, XLogReaderState *record)
 

Variables

PGDLLIMPORT bool recoveryTargetInclusive
 
PGDLLIMPORT int recoveryTargetAction
 
PGDLLIMPORT int recovery_min_apply_delay
 
PGDLLIMPORT char * PrimaryConnInfo
 
PGDLLIMPORT char * PrimarySlotName
 
PGDLLIMPORT char * recoveryRestoreCommand
 
PGDLLIMPORT char * recoveryEndCommand
 
PGDLLIMPORT char * archiveCleanupCommand
 
PGDLLIMPORT TransactionId recoveryTargetXid
 
PGDLLIMPORT char * recovery_target_time_string
 
PGDLLIMPORT TimestampTz recoveryTargetTime
 
PGDLLIMPORT const char * recoveryTargetName
 
PGDLLIMPORT XLogRecPtr recoveryTargetLSN
 
PGDLLIMPORT RecoveryTargetType recoveryTarget
 
PGDLLIMPORT bool wal_receiver_create_temp_slot
 
PGDLLIMPORT RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal
 
PGDLLIMPORT TimeLineID recoveryTargetTLIRequested
 
PGDLLIMPORT TimeLineID recoveryTargetTLI
 
PGDLLIMPORT bool reachedConsistency
 
PGDLLIMPORT bool StandbyMode
 

Typedef Documentation

◆ RecoveryPauseState

Enumeration Type Documentation

◆ RecoveryPauseState

Enumerator
RECOVERY_NOT_PAUSED 
RECOVERY_PAUSE_REQUESTED 
RECOVERY_PAUSED 

Definition at line 54 of file xlogrecovery.h.

55{
56 RECOVERY_NOT_PAUSED, /* pause not requested */
57 RECOVERY_PAUSE_REQUESTED, /* pause requested, but not yet paused */
58 RECOVERY_PAUSED, /* recovery is paused */
RecoveryPauseState
Definition: xlogrecovery.h:55
@ RECOVERY_PAUSED
Definition: xlogrecovery.h:58
@ RECOVERY_NOT_PAUSED
Definition: xlogrecovery.h:56
@ RECOVERY_PAUSE_REQUESTED
Definition: xlogrecovery.h:57

◆ RecoveryTargetAction

Enumerator
RECOVERY_TARGET_ACTION_PAUSE 
RECOVERY_TARGET_ACTION_PROMOTE 
RECOVERY_TARGET_ACTION_SHUTDOWN 

Definition at line 46 of file xlogrecovery.h.

47{
RecoveryTargetAction
Definition: xlogrecovery.h:47
@ RECOVERY_TARGET_ACTION_PAUSE
Definition: xlogrecovery.h:48
@ RECOVERY_TARGET_ACTION_PROMOTE
Definition: xlogrecovery.h:49
@ RECOVERY_TARGET_ACTION_SHUTDOWN
Definition: xlogrecovery.h:50

◆ RecoveryTargetTimeLineGoal

Enumerator
RECOVERY_TARGET_TIMELINE_CONTROLFILE 
RECOVERY_TARGET_TIMELINE_LATEST 
RECOVERY_TARGET_TIMELINE_NUMERIC 

Definition at line 36 of file xlogrecovery.h.

◆ RecoveryTargetType

Enumerator
RECOVERY_TARGET_UNSET 
RECOVERY_TARGET_XID 
RECOVERY_TARGET_TIME 
RECOVERY_TARGET_NAME 
RECOVERY_TARGET_LSN 
RECOVERY_TARGET_IMMEDIATE 

Definition at line 23 of file xlogrecovery.h.

24{
RecoveryTargetType
Definition: xlogrecovery.h:24
@ RECOVERY_TARGET_IMMEDIATE
Definition: xlogrecovery.h:30
@ RECOVERY_TARGET_TIME
Definition: xlogrecovery.h:27
@ RECOVERY_TARGET_UNSET
Definition: xlogrecovery.h:25
@ RECOVERY_TARGET_XID
Definition: xlogrecovery.h:26
@ RECOVERY_TARGET_LSN
Definition: xlogrecovery.h:29
@ RECOVERY_TARGET_NAME
Definition: xlogrecovery.h:28

Function Documentation

◆ CheckPromoteSignal()

bool CheckPromoteSignal ( void  )

Definition at line 4519 of file xlogrecovery.c.

4520{
4521 struct stat stat_buf;
4522
4523 if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
4524 return true;
4525
4526 return false;
4527}
#define stat
Definition: win32_port.h:274
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:312

References PROMOTE_SIGNAL_FILE, and stat.

Referenced by CheckForStandbyTrigger(), and process_pm_pmsignal().

◆ FinishWalRecovery()

EndOfWalRecoveryInfo * FinishWalRecovery ( void  )

Definition at line 1468 of file xlogrecovery.c.

1469{
1471 XLogRecPtr lastRec;
1472 TimeLineID lastRecTLI;
1473 XLogRecPtr endOfLog;
1474
1475 /*
1476 * Kill WAL receiver, if it's still running, before we continue to write
1477 * the startup checkpoint and aborted-contrecord records. It will trump
1478 * over these records and subsequent ones if it's still alive when we
1479 * start writing WAL.
1480 */
1482
1483 /*
1484 * Shutdown the slot sync worker to drop any temporary slots acquired by
1485 * it and to prevent it from keep trying to fetch the failover slots.
1486 *
1487 * We do not update the 'synced' column in 'pg_replication_slots' system
1488 * view from true to false here, as any failed update could leave 'synced'
1489 * column false for some slots. This could cause issues during slot sync
1490 * after restarting the server as a standby. While updating the 'synced'
1491 * column after switching to the new timeline is an option, it does not
1492 * simplify the handling for the 'synced' column. Therefore, we retain the
1493 * 'synced' column as true after promotion as it may provide useful
1494 * information about the slot origin.
1495 */
1497
1498 /*
1499 * We are now done reading the xlog from stream. Turn off streaming
1500 * recovery to force fetching the files (which would be required at end of
1501 * recovery, e.g., timeline history file) from archive or pg_wal.
1502 *
1503 * Note that standby mode must be turned off after killing WAL receiver,
1504 * i.e., calling XLogShutdownWalRcv().
1505 */
1507 StandbyMode = false;
1508
1509 /*
1510 * Determine where to start writing WAL next.
1511 *
1512 * Re-fetch the last valid or last applied record, so we can identify the
1513 * exact endpoint of what we consider the valid portion of WAL. There may
1514 * be an incomplete continuation record after that, in which case
1515 * 'abortedRecPtr' and 'missingContrecPtr' are set and the caller will
1516 * write a special OVERWRITE_CONTRECORD message to mark that the rest of
1517 * it is intentionally missing. See CreateOverwriteContrecordRecord().
1518 *
1519 * An important side-effect of this is to load the last page into
1520 * xlogreader. The caller uses it to initialize the WAL for writing.
1521 */
1522 if (!InRecovery)
1523 {
1524 lastRec = CheckPointLoc;
1525 lastRecTLI = CheckPointTLI;
1526 }
1527 else
1528 {
1530 lastRecTLI = XLogRecoveryCtl->lastReplayedTLI;
1531 }
1533 (void) ReadRecord(xlogprefetcher, PANIC, false, lastRecTLI);
1534 endOfLog = xlogreader->EndRecPtr;
1535
1536 /*
1537 * Remember the TLI in the filename of the XLOG segment containing the
1538 * end-of-log. It could be different from the timeline that endOfLog
1539 * nominally belongs to, if there was a timeline switch in that segment,
1540 * and we were reading the old WAL from a segment belonging to a higher
1541 * timeline.
1542 */
1543 result->endOfLogTLI = xlogreader->seg.ws_tli;
1544
1546 {
1547 /*
1548 * We are no longer in archive recovery state.
1549 *
1550 * We are now done reading the old WAL. Turn off archive fetching if
1551 * it was active.
1552 */
1554 InArchiveRecovery = false;
1555
1556 /*
1557 * If the ending log segment is still open, close it (to avoid
1558 * problems on Windows with trying to rename or delete an open file).
1559 */
1560 if (readFile >= 0)
1561 {
1562 close(readFile);
1563 readFile = -1;
1564 }
1565 }
1566
1567 /*
1568 * Copy the last partial block to the caller, for initializing the WAL
1569 * buffer for appending new WAL.
1570 */
1571 if (endOfLog % XLOG_BLCKSZ != 0)
1572 {
1573 char *page;
1574 int len;
1575 XLogRecPtr pageBeginPtr;
1576
1577 pageBeginPtr = endOfLog - (endOfLog % XLOG_BLCKSZ);
1579
1580 /* Copy the valid part of the last block */
1581 len = endOfLog % XLOG_BLCKSZ;
1582 page = palloc(len);
1583 memcpy(page, xlogreader->readBuf, len);
1584
1585 result->lastPageBeginPtr = pageBeginPtr;
1586 result->lastPage = page;
1587 }
1588 else
1589 {
1590 /* There is no partial block to copy. */
1591 result->lastPageBeginPtr = endOfLog;
1592 result->lastPage = NULL;
1593 }
1594
1595 /*
1596 * Create a comment for the history file to explain why and where timeline
1597 * changed.
1598 */
1600
1601 result->lastRec = lastRec;
1602 result->lastRecTLI = lastRecTLI;
1603 result->endOfLog = endOfLog;
1604
1605 result->abortedRecPtr = abortedRecPtr;
1607
1610
1611 return result;
1612}
#define PANIC
Definition: elog.h:42
Assert(PointerIsAligned(start, uint64))
#define close(a)
Definition: win32.h:12
void * palloc(Size size)
Definition: mcxt.c:1365
const void size_t len
void ShutDownSlotSync(void)
Definition: slotsync.c:1660
XLogRecPtr lastPageBeginPtr
Definition: xlogrecovery.h:121
XLogRecPtr abortedRecPtr
Definition: xlogrecovery.h:130
XLogRecPtr missingContrecPtr
Definition: xlogrecovery.h:131
TimeLineID endOfLogTLI
Definition: xlogrecovery.h:119
TimeLineID ws_tli
Definition: xlogreader.h:49
XLogRecPtr EndRecPtr
Definition: xlogreader.h:206
WALOpenSegment seg
Definition: xlogreader.h:271
TimeLineID lastReplayedTLI
Definition: xlogrecovery.c:348
XLogRecPtr lastReplayedReadRecPtr
Definition: xlogrecovery.c:346
bool WalRcvStreaming(void)
int wal_segment_size
Definition: xlog.c:145
void XLogShutdownWalRcv(void)
Definition: xlog.c:9537
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint32 TimeLineID
Definition: xlogdefs.h:63
void XLogPrefetcherBeginRead(XLogPrefetcher *prefetcher, XLogRecPtr recPtr)
static char * getRecoveryStopReason(void)
bool ArchiveRecoveryRequested
Definition: xlogrecovery.c:140
bool InArchiveRecovery
Definition: xlogrecovery.c:141
static XLogRecPtr missingContrecPtr
Definition: xlogrecovery.c:381
static XLogRecoveryCtlData * XLogRecoveryCtl
Definition: xlogrecovery.c:372
static uint32 readOff
Definition: xlogrecovery.c:235
static bool standby_signal_file_found
Definition: xlogrecovery.c:153
bool StandbyMode
Definition: xlogrecovery.c:150
static int readFile
Definition: xlogrecovery.c:233
static XLogRecPtr abortedRecPtr
Definition: xlogrecovery.c:380
static XLogRecord * ReadRecord(XLogPrefetcher *xlogprefetcher, int emode, bool fetching_ckpt, TimeLineID replayTLI)
static XLogRecPtr CheckPointLoc
Definition: xlogrecovery.c:170
static bool recovery_signal_file_found
Definition: xlogrecovery.c:154
static XLogPrefetcher * xlogprefetcher
Definition: xlogrecovery.c:194
static XLogReaderState * xlogreader
Definition: xlogrecovery.c:191
static TimeLineID CheckPointTLI
Definition: xlogrecovery.c:171
bool InRecovery
Definition: xlogutils.c:50

References abortedRecPtr, EndOfWalRecoveryInfo::abortedRecPtr, ArchiveRecoveryRequested, Assert(), CheckPointLoc, CheckPointTLI, close, EndOfWalRecoveryInfo::endOfLog, EndOfWalRecoveryInfo::endOfLogTLI, XLogReaderState::EndRecPtr, getRecoveryStopReason(), InArchiveRecovery, InRecovery, EndOfWalRecoveryInfo::lastPage, EndOfWalRecoveryInfo::lastPageBeginPtr, EndOfWalRecoveryInfo::lastRec, EndOfWalRecoveryInfo::lastRecTLI, XLogRecoveryCtlData::lastReplayedReadRecPtr, XLogRecoveryCtlData::lastReplayedTLI, len, missingContrecPtr, EndOfWalRecoveryInfo::missingContrecPtr, palloc(), PANIC, XLogReaderState::readBuf, readFile, readOff, ReadRecord(), recovery_signal_file_found, EndOfWalRecoveryInfo::recovery_signal_file_found, EndOfWalRecoveryInfo::recoveryStopReason, XLogReaderState::seg, ShutDownSlotSync(), standby_signal_file_found, EndOfWalRecoveryInfo::standby_signal_file_found, StandbyMode, wal_segment_size, WalRcvStreaming(), WALOpenSegment::ws_tli, xlogprefetcher, XLogPrefetcherBeginRead(), xlogreader, XLogRecoveryCtl, XLogSegmentOffset, and XLogShutdownWalRcv().

Referenced by StartupXLOG().

◆ GetCurrentChunkReplayStartTime()

TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 4682 of file xlogrecovery.c.

4683{
4684 TimestampTz xtime;
4685
4689
4690 return xtime;
4691}
int64 TimestampTz
Definition: timestamp.h:39
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
TimestampTz currentChunkStartTime
Definition: xlogrecovery.c:364

References XLogRecoveryCtlData::currentChunkStartTime, XLogRecoveryCtlData::info_lck, SpinLockAcquire, SpinLockRelease, and XLogRecoveryCtl.

Referenced by GetReplicationApplyDelay().

◆ GetCurrentReplayRecPtr()

XLogRecPtr GetCurrentReplayRecPtr ( TimeLineID replayEndTLI)

Definition at line 4618 of file xlogrecovery.c.

4619{
4620 XLogRecPtr recptr;
4621 TimeLineID tli;
4622
4627
4628 if (replayEndTLI)
4629 *replayEndTLI = tli;
4630 return recptr;
4631}
TimeLineID replayEndTLI
Definition: xlogrecovery.c:356
XLogRecPtr replayEndRecPtr
Definition: xlogrecovery.c:355

References XLogRecoveryCtlData::info_lck, XLogRecoveryCtlData::replayEndRecPtr, XLogRecoveryCtlData::replayEndTLI, SpinLockAcquire, SpinLockRelease, and XLogRecoveryCtl.

Referenced by UpdateMinRecoveryPoint(), and xlog_redo().

◆ GetLatestXTime()

◆ GetRecoveryPauseState()

◆ GetXLogReceiptTime()

void GetXLogReceiptTime ( TimestampTz rtime,
bool *  fromStream 
)

Definition at line 4698 of file xlogrecovery.c.

4699{
4700 /*
4701 * This must be executed in the startup process, since we don't export the
4702 * relevant state to shared memory.
4703 */
4705
4706 *rtime = XLogReceiptTime;
4707 *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
4708}
static XLogSource XLogReceiptSource
Definition: xlogrecovery.c:262
@ XLOG_FROM_STREAM
Definition: xlogrecovery.c:217
static TimestampTz XLogReceiptTime
Definition: xlogrecovery.c:261

References Assert(), InRecovery, XLOG_FROM_STREAM, XLogReceiptSource, and XLogReceiptTime.

Referenced by GetStandbyLimitTime().

◆ GetXLogReplayRecPtr()

◆ HotStandbyActive()

bool HotStandbyActive ( void  )

Definition at line 4558 of file xlogrecovery.c.

4559{
4560 /*
4561 * We check shared state each time only until Hot Standby is active. We
4562 * can't de-activate Hot Standby, so there's no need to keep checking
4563 * after the shared variable has once been seen true.
4564 */
4566 return true;
4567 else
4568 {
4569 /* spinlock is essential on machines with weak memory ordering! */
4573
4574 return LocalHotStandbyActive;
4575 }
4576}
static bool LocalHotStandbyActive
Definition: xlogrecovery.c:179

References XLogRecoveryCtlData::info_lck, LocalHotStandbyActive, XLogRecoveryCtlData::SharedHotStandbyActive, SpinLockAcquire, SpinLockRelease, and XLogRecoveryCtl.

Referenced by XLogWalRcvSendHSFeedback().

◆ InitWalRecovery()

void InitWalRecovery ( ControlFileData ControlFile,
bool *  wasShutdown_ptr,
bool *  haveBackupLabel_ptr,
bool *  haveTblspcMap_ptr 
)

Definition at line 520 of file xlogrecovery.c.

522{
523 XLogPageReadPrivate *private;
524 struct stat st;
525 bool wasShutdown;
526 XLogRecord *record;
527 DBState dbstate_at_startup;
528 bool haveTblspcMap = false;
529 bool haveBackupLabel = false;
530 CheckPoint checkPoint;
531 bool backupFromStandby = false;
532
533 dbstate_at_startup = ControlFile->state;
534
535 /*
536 * Initialize on the assumption we want to recover to the latest timeline
537 * that's active according to pg_control.
538 */
542 else
544
545 /*
546 * Check for signal files, and if so set up state for offline recovery
547 */
550
551 /*
552 * Take ownership of the wakeup latch if we're going to sleep during
553 * recovery, if required.
554 */
557
558 /*
559 * Set the WAL reading processor now, as it will be needed when reading
560 * the checkpoint record required (backup_label or not).
561 */
562 private = palloc0(sizeof(XLogPageReadPrivate));
563 xlogreader =
565 XL_ROUTINE(.page_read = &XLogPageRead,
566 .segment_open = NULL,
567 .segment_close = wal_segment_close),
568 private);
569 if (!xlogreader)
571 (errcode(ERRCODE_OUT_OF_MEMORY),
572 errmsg("out of memory"),
573 errdetail("Failed while allocating a WAL reading processor.")));
575
576 /*
577 * Set the WAL decode buffer size. This limits how far ahead we can read
578 * in the WAL.
579 */
581
582 /* Create a WAL prefetcher. */
584
585 /*
586 * Allocate two page buffers dedicated to WAL consistency checks. We do
587 * it this way, rather than just making static arrays, for two reasons:
588 * (1) no need to waste the storage in most instantiations of the backend;
589 * (2) a static char array isn't guaranteed to have any particular
590 * alignment, whereas palloc() will provide MAXALIGN'd storage.
591 */
592 replay_image_masked = (char *) palloc(BLCKSZ);
593 primary_image_masked = (char *) palloc(BLCKSZ);
594
595 /*
596 * Read the backup_label file. We want to run this part of the recovery
597 * process after checking for signal files and after performing validation
598 * of the recovery parameters.
599 */
601 &backupFromStandby))
602 {
603 List *tablespaces = NIL;
604
605 /*
606 * Archive recovery was requested, and thanks to the backup label
607 * file, we know how far we need to replay to reach consistency. Enter
608 * archive recovery directly.
609 */
610 InArchiveRecovery = true;
613
614 /*
615 * Omitting backup_label when creating a new replica, PITR node etc.
616 * unfortunately is a common cause of corruption. Logging that
617 * backup_label was used makes it a bit easier to exclude that as the
618 * cause of observed corruption.
619 *
620 * Do so before we try to read the checkpoint record (which can fail),
621 * as otherwise it can be hard to understand why a checkpoint other
622 * than ControlFile->checkPoint is used.
623 */
624 ereport(LOG,
625 errmsg("starting backup recovery with redo LSN %X/%08X, checkpoint LSN %X/%08X, on timeline ID %u",
629
630 /*
631 * When a backup_label file is present, we want to roll forward from
632 * the checkpoint it identifies, rather than using pg_control.
633 */
636 if (record != NULL)
637 {
638 memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
639 wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
641 errmsg_internal("checkpoint record is at %X/%08X",
643 InRecovery = true; /* force recovery even if SHUTDOWNED */
644
645 /*
646 * Make sure that REDO location exists. This may not be the case
647 * if there was a crash during an online backup, which left a
648 * backup_label around that references a WAL segment that's
649 * already been archived.
650 */
651 if (checkPoint.redo < CheckPointLoc)
652 {
654 if (!ReadRecord(xlogprefetcher, LOG, false,
655 checkPoint.ThisTimeLineID))
657 errmsg("could not find redo location %X/%08X referenced by checkpoint record at %X/%08X",
659 errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
660 "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
661 "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
663 }
664 }
665 else
666 {
668 errmsg("could not locate required checkpoint record at %X/%08X",
670 errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
671 "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
672 "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
674 wasShutdown = false; /* keep compiler quiet */
675 }
676
677 /* Read the tablespace_map file if present and create symlinks. */
678 if (read_tablespace_map(&tablespaces))
679 {
680 ListCell *lc;
681
682 foreach(lc, tablespaces)
683 {
684 tablespaceinfo *ti = lfirst(lc);
685 char *linkloc;
686
687 linkloc = psprintf("%s/%u", PG_TBLSPC_DIR, ti->oid);
688
689 /*
690 * Remove the existing symlink if any and Create the symlink
691 * under PGDATA.
692 */
694
695 if (symlink(ti->path, linkloc) < 0)
698 errmsg("could not create symbolic link \"%s\": %m",
699 linkloc)));
700
701 pfree(ti->path);
702 pfree(ti);
703 }
704
705 /* tell the caller to delete it later */
706 haveTblspcMap = true;
707 }
708
709 /* tell the caller to delete it later */
710 haveBackupLabel = true;
711 }
712 else
713 {
714 /* No backup_label file has been found if we are here. */
715
716 /*
717 * If tablespace_map file is present without backup_label file, there
718 * is no use of such file. There is no harm in retaining it, but it
719 * is better to get rid of the map file so that we don't have any
720 * redundant file in data directory and it will avoid any sort of
721 * confusion. It seems prudent though to just rename the file out of
722 * the way rather than delete it completely, also we ignore any error
723 * that occurs in rename operation as even if map file is present
724 * without backup_label file, it is harmless.
725 */
726 if (stat(TABLESPACE_MAP, &st) == 0)
727 {
728 unlink(TABLESPACE_MAP_OLD);
730 ereport(LOG,
731 (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
733 errdetail("File \"%s\" was renamed to \"%s\".",
735 else
736 ereport(LOG,
737 (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
739 errdetail("Could not rename file \"%s\" to \"%s\": %m.",
741 }
742
743 /*
744 * It's possible that archive recovery was requested, but we don't
745 * know how far we need to replay the WAL before we reach consistency.
746 * This can happen for example if a base backup is taken from a
747 * running server using an atomic filesystem snapshot, without calling
748 * pg_backup_start/stop. Or if you just kill a running primary server
749 * and put it into archive recovery by creating a recovery signal
750 * file.
751 *
752 * Our strategy in that case is to perform crash recovery first,
753 * replaying all the WAL present in pg_wal, and only enter archive
754 * recovery after that.
755 *
756 * But usually we already know how far we need to replay the WAL (up
757 * to minRecoveryPoint, up to backupEndPoint, or until we see an
758 * end-of-backup record), and we can enter archive recovery directly.
759 */
765 {
766 InArchiveRecovery = true;
769 }
770
771 /*
772 * For the same reason as when starting up with backup_label present,
773 * emit a log message when we continue initializing from a base
774 * backup.
775 */
777 ereport(LOG,
778 errmsg("restarting backup recovery with redo LSN %X/%08X",
780
781 /* Get the last valid checkpoint record. */
788 if (record != NULL)
789 {
791 errmsg_internal("checkpoint record is at %X/%08X",
793 }
794 else
795 {
796 /*
797 * We used to attempt to go back to a secondary checkpoint record
798 * here, but only when not in standby mode. We now just fail if we
799 * can't read the last checkpoint because this allows us to
800 * simplify processing around checkpoints.
801 */
803 errmsg("could not locate a valid checkpoint record at %X/%08X",
805 }
806 memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
807 wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
808 }
809
811 {
813 ereport(LOG,
814 (errmsg("entering standby mode")));
816 ereport(LOG,
817 (errmsg("starting point-in-time recovery to XID %u",
820 ereport(LOG,
821 (errmsg("starting point-in-time recovery to %s",
824 ereport(LOG,
825 (errmsg("starting point-in-time recovery to \"%s\"",
828 ereport(LOG,
829 errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%08X\"",
832 ereport(LOG,
833 (errmsg("starting point-in-time recovery to earliest consistent point")));
834 else
835 ereport(LOG,
836 (errmsg("starting archive recovery")));
837 }
838
839 /*
840 * If the location of the checkpoint record is not on the expected
841 * timeline in the history of the requested timeline, we cannot proceed:
842 * the backup is not part of the history of the requested timeline.
843 */
844 Assert(expectedTLEs); /* was initialized by reading checkpoint
845 * record */
848 {
849 XLogRecPtr switchpoint;
850
851 /*
852 * tliSwitchPoint will throw an error if the checkpoint's timeline is
853 * not in expectedTLEs at all.
854 */
855 switchpoint = tliSwitchPoint(CheckPointTLI, expectedTLEs, NULL);
857 (errmsg("requested timeline %u is not a child of this server's history",
859 /* translator: %s is a backup_label file or a pg_control file */
860 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.",
861 haveBackupLabel ? "backup_label" : "pg_control",
864 LSN_FORMAT_ARGS(switchpoint))));
865 }
866
867 /*
868 * The min recovery point should be part of the requested timeline's
869 * history, too.
870 */
875 errmsg("requested timeline %u does not contain minimum recovery point %X/%08X on timeline %u",
879
881 errmsg_internal("redo record is at %X/%08X; shutdown %s",
882 LSN_FORMAT_ARGS(checkPoint.redo),
883 wasShutdown ? "true" : "false"));
885 (errmsg_internal("next transaction ID: " UINT64_FORMAT "; next OID: %u",
887 checkPoint.nextOid)));
889 (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %u",
890 checkPoint.nextMulti, checkPoint.nextMultiOffset)));
892 (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
893 checkPoint.oldestXid, checkPoint.oldestXidDB)));
895 (errmsg_internal("oldest MultiXactId: %u, in database %u",
896 checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
898 (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
899 checkPoint.oldestCommitTsXid,
900 checkPoint.newestCommitTsXid)));
903 (errmsg("invalid next transaction ID")));
904
905 /* sanity check */
906 if (checkPoint.redo > CheckPointLoc)
908 (errmsg("invalid redo in checkpoint record")));
909
910 /*
911 * Check whether we need to force recovery from WAL. If it appears to
912 * have been a clean shutdown and we did not have a recovery signal file,
913 * then assume no recovery needed.
914 */
915 if (checkPoint.redo < CheckPointLoc)
916 {
917 if (wasShutdown)
919 (errmsg("invalid redo record in shutdown checkpoint")));
920 InRecovery = true;
921 }
922 else if (ControlFile->state != DB_SHUTDOWNED)
923 InRecovery = true;
925 {
926 /* force recovery due to presence of recovery signal file */
927 InRecovery = true;
928 }
929
930 /*
931 * If recovery is needed, update our in-memory copy of pg_control to show
932 * that we are recovering and to show the selected checkpoint as the place
933 * we are starting from. We also mark pg_control with any minimum recovery
934 * stop point obtained from a backup history file.
935 *
936 * We don't write the changes to disk yet, though. Only do that after
937 * initializing various subsystems.
938 */
939 if (InRecovery)
940 {
942 {
944 }
945 else
946 {
947 ereport(LOG,
948 (errmsg("database system was not properly shut down; "
949 "automatic recovery in progress")));
951 ereport(LOG,
952 (errmsg("crash recovery starts in timeline %u "
953 "and has target timeline %u",
957 }
959 ControlFile->checkPointCopy = checkPoint;
961 {
962 /* initialize minRecoveryPoint if not set yet */
963 if (ControlFile->minRecoveryPoint < checkPoint.redo)
964 {
965 ControlFile->minRecoveryPoint = checkPoint.redo;
967 }
968 }
969
970 /*
971 * Set backupStartPoint if we're starting recovery from a base backup.
972 *
973 * Also set backupEndPoint and use minRecoveryPoint as the backup end
974 * location if we're starting recovery from a base backup which was
975 * taken from a standby. In this case, the database system status in
976 * pg_control must indicate that the database was already in recovery.
977 * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
978 * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
979 * before reaching this point; e.g. because restore_command or
980 * primary_conninfo were faulty.
981 *
982 * Any other state indicates that the backup somehow became corrupted
983 * and we can't sensibly continue with recovery.
984 */
985 if (haveBackupLabel)
986 {
987 ControlFile->backupStartPoint = checkPoint.redo;
989
990 if (backupFromStandby)
991 {
992 if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
993 dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
995 (errmsg("backup_label contains data inconsistent with control file"),
996 errhint("This means that the backup is corrupted and you will "
997 "have to use another backup for recovery.")));
999 }
1000 }
1001 }
1002
1003 /* remember these, so that we know when we have reached consistency */
1008 {
1011 }
1012 else
1013 {
1016 }
1017
1018 /*
1019 * Start recovery assuming that the final record isn't lost.
1020 */
1023
1024 *wasShutdown_ptr = wasShutdown;
1025 *haveBackupLabel_ptr = haveBackupLabel;
1026 *haveTblspcMap_ptr = haveTblspcMap;
1027}
TimeLineID tliOfPointInHistory(XLogRecPtr ptr, List *history)
Definition: timeline.c:544
XLogRecPtr tliSwitchPoint(TimeLineID tli, List *history, TimeLineID *nextTLI)
Definition: timeline.c:572
void remove_tablespace_symlink(const char *linkloc)
Definition: tablespace.c:883
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1862
#define UINT64_FORMAT
Definition: c.h:560
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errcode_for_file_access(void)
Definition: elog.c:886
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errhint(const char *fmt,...)
Definition: elog.c:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:779
char * DataDir
Definition: globals.c:71
void OwnLatch(Latch *latch)
Definition: latch.c:126
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
DBState
Definition: pg_control.h:90
@ DB_IN_ARCHIVE_RECOVERY
Definition: pg_control.h:96
@ DB_SHUTDOWNED_IN_RECOVERY
Definition: pg_control.h:93
@ DB_SHUTDOWNED
Definition: pg_control.h:92
@ DB_IN_CRASH_RECOVERY
Definition: pg_control.h:95
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:68
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
#define PG_TBLSPC_DIR
Definition: relpath.h:41
Oid oldestMultiDB
Definition: pg_control.h:51
MultiXactId oldestMulti
Definition: pg_control.h:50
MultiXactOffset nextMultiOffset
Definition: pg_control.h:47
TransactionId newestCommitTsXid
Definition: pg_control.h:55
TransactionId oldestXid
Definition: pg_control.h:48
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
Oid nextOid
Definition: pg_control.h:45
MultiXactId nextMulti
Definition: pg_control.h:46
FullTransactionId nextXid
Definition: pg_control.h:44
TransactionId oldestCommitTsXid
Definition: pg_control.h:53
XLogRecPtr redo
Definition: pg_control.h:37
Oid oldestXidDB
Definition: pg_control.h:49
XLogRecPtr backupStartPoint
Definition: pg_control.h:170
bool backupEndRequired
Definition: pg_control.h:172
CheckPoint checkPointCopy
Definition: pg_control.h:135
XLogRecPtr backupEndPoint
Definition: pg_control.h:171
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:168
XLogRecPtr checkPoint
Definition: pg_control.h:133
uint64 system_identifier
Definition: pg_control.h:110
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:169
Definition: pg_list.h:54
uint64 system_identifier
Definition: xlogreader.h:190
uint8 xl_info
Definition: xlogrecord.h:46
#define U64FromFullTransactionId(x)
Definition: transam.h:49
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define symlink(oldpath, newpath)
Definition: win32_port.h:225
int wal_decode_buffer_size
Definition: xlog.c:138
static ControlFileData * ControlFile
Definition: xlog.c:575
#define TABLESPACE_MAP_OLD
Definition: xlog.h:309
#define TABLESPACE_MAP
Definition: xlog.h:308
#define BACKUP_LABEL_FILE
Definition: xlog.h:305
#define XLogRecPtrIsValid(r)
Definition: xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:47
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogPrefetcher * XLogPrefetcherAllocate(XLogReaderState *reader)
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:107
void XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
Definition: xlogreader.c:91
#define XLogRecGetData(decoder)
Definition: xlogreader.h:414
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
static bool backupEndRequired
Definition: xlogrecovery.c:286
const char * recoveryTargetName
Definition: xlogrecovery.c:94
static XLogRecPtr minRecoveryPoint
Definition: xlogrecovery.c:281
static int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
static XLogRecPtr backupEndPoint
Definition: xlogrecovery.c:285
static void validateRecoveryParameters(void)
static XLogRecord * ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr, TimeLineID replayTLI)
static TimeLineID RedoStartTLI
Definition: xlogrecovery.c:173
static void readRecoverySignalFile(void)
XLogRecPtr recoveryTargetLSN
Definition: xlogrecovery.c:95
RecoveryTargetType recoveryTarget
Definition: xlogrecovery.c:88
static bool read_tablespace_map(List **tablespaces)
static bool read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI, bool *backupEndRequired, bool *backupFromStandby)
static List * expectedTLEs
Definition: xlogrecovery.c:126
static char * primary_image_masked
Definition: xlogrecovery.c:306
static TimeLineID minRecoveryPointTLI
Definition: xlogrecovery.c:282
TransactionId recoveryTargetXid
Definition: xlogrecovery.c:91
static char * replay_image_masked
Definition: xlogrecovery.c:305
TimeLineID recoveryTargetTLI
Definition: xlogrecovery.c:125
static XLogRecPtr RedoStartLSN
Definition: xlogrecovery.c:172
static void EnableStandbyMode(void)
Definition: xlogrecovery.c:486
TimestampTz recoveryTargetTime
Definition: xlogrecovery.c:93
static bool StandbyModeRequested
Definition: xlogrecovery.c:149
static XLogRecPtr backupStartPoint
Definition: xlogrecovery.c:284
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:831

References abortedRecPtr, ArchiveRecoveryRequested, Assert(), BACKUP_LABEL_FILE, backupEndPoint, ControlFileData::backupEndPoint, backupEndRequired, ControlFileData::backupEndRequired, backupStartPoint, ControlFileData::backupStartPoint, ControlFileData::checkPoint, ControlFileData::checkPointCopy, CheckPointLoc, CheckPointTLI, ControlFile, DataDir, DB_IN_ARCHIVE_RECOVERY, DB_IN_CRASH_RECOVERY, DB_SHUTDOWNED, DB_SHUTDOWNED_IN_RECOVERY, DEBUG1, durable_rename(), EnableStandbyMode(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), errmsg_internal(), ERROR, expectedTLEs, FATAL, InArchiveRecovery, InRecovery, InvalidXLogRecPtr, lfirst, LOG, LSN_FORMAT_ARGS, minRecoveryPoint, ControlFileData::minRecoveryPoint, minRecoveryPointTLI, ControlFileData::minRecoveryPointTLI, missingContrecPtr, CheckPoint::newestCommitTsXid, CheckPoint::nextMulti, CheckPoint::nextMultiOffset, CheckPoint::nextOid, CheckPoint::nextXid, NIL, tablespaceinfo::oid, CheckPoint::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, CheckPoint::oldestXidDB, OwnLatch(), palloc(), palloc0(), PANIC, tablespaceinfo::path, pfree(), PG_TBLSPC_DIR, primary_image_masked, psprintf(), read_backup_label(), read_tablespace_map(), ReadCheckpointRecord(), ReadRecord(), readRecoverySignalFile(), RECOVERY_TARGET_IMMEDIATE, RECOVERY_TARGET_LSN, RECOVERY_TARGET_NAME, RECOVERY_TARGET_TIME, RECOVERY_TARGET_XID, recoveryTarget, recoveryTargetLSN, recoveryTargetName, recoveryTargetTime, recoveryTargetTLI, recoveryTargetXid, XLogRecoveryCtlData::recoveryWakeupLatch, CheckPoint::redo, RedoStartLSN, RedoStartTLI, remove_tablespace_symlink(), replay_image_masked, StandbyModeRequested, stat, ControlFileData::state, symlink, XLogReaderState::system_identifier, ControlFileData::system_identifier, TABLESPACE_MAP, TABLESPACE_MAP_OLD, CheckPoint::ThisTimeLineID, timestamptz_to_str(), tliOfPointInHistory(), tliSwitchPoint(), TransactionIdIsNormal, U64FromFullTransactionId, UINT64_FORMAT, validateRecoveryParameters(), wal_decode_buffer_size, wal_segment_close(), wal_segment_size, XidFromFullTransactionId, XLogRecord::xl_info, XL_ROUTINE, XLOG_CHECKPOINT_SHUTDOWN, XLogPageRead(), xlogprefetcher, XLogPrefetcherAllocate(), XLogPrefetcherBeginRead(), xlogreader, XLogReaderAllocate(), XLogReaderSetDecodeBuffer(), XLogRecGetData, XLogRecoveryCtl, and XLogRecPtrIsValid.

Referenced by StartupXLOG().

◆ PerformWalRecovery()

void PerformWalRecovery ( void  )

Definition at line 1663 of file xlogrecovery.c.

1664{
1665 XLogRecord *record;
1666 bool reachedRecoveryTarget = false;
1667 TimeLineID replayTLI;
1668
1669 /*
1670 * Initialize shared variables for tracking progress of WAL replay, as if
1671 * we had just replayed the record before the REDO location (or the
1672 * checkpoint record itself, if it's a shutdown checkpoint).
1673 */
1676 {
1680 }
1681 else
1682 {
1686 }
1693
1694 /* Also ensure XLogReceiptTime has a sane value */
1696
1697 /*
1698 * Let postmaster know we've started redo now, so that it can launch the
1699 * archiver if necessary.
1700 */
1703
1704 /*
1705 * Allow read-only connections immediately if we're consistent already.
1706 */
1708
1709 /*
1710 * Find the first record that logically follows the checkpoint --- it
1711 * might physically precede it, though.
1712 */
1714 {
1715 /* back up to find the record */
1716 replayTLI = RedoStartTLI;
1718 record = ReadRecord(xlogprefetcher, PANIC, false, replayTLI);
1719
1720 /*
1721 * If a checkpoint record's redo pointer points back to an earlier
1722 * LSN, the record at that LSN should be an XLOG_CHECKPOINT_REDO
1723 * record.
1724 */
1725 if (record->xl_rmid != RM_XLOG_ID ||
1727 ereport(FATAL,
1728 errmsg("unexpected record type found at redo point %X/%08X",
1730 }
1731 else
1732 {
1733 /* just have to read next record after CheckPoint */
1735 replayTLI = CheckPointTLI;
1736 record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1737 }
1738
1739 if (record != NULL)
1740 {
1741 TimestampTz xtime;
1742 PGRUsage ru0;
1743
1744 pg_rusage_init(&ru0);
1745
1746 InRedo = true;
1747
1748 RmgrStartup();
1749
1750 ereport(LOG,
1751 errmsg("redo starts at %X/%08X",
1753
1754 /* Prepare to report progress of the redo phase. */
1755 if (!StandbyMode)
1757
1758 /*
1759 * main redo apply loop
1760 */
1761 do
1762 {
1763 if (!StandbyMode)
1764 ereport_startup_progress("redo in progress, elapsed time: %ld.%02d s, current LSN: %X/%08X",
1766
1767#ifdef WAL_DEBUG
1768 if (XLOG_DEBUG)
1769 {
1771
1773 appendStringInfo(&buf, "REDO @ %X/%08X; LSN %X/%08X: ",
1776 xlog_outrec(&buf, xlogreader);
1777 appendStringInfoString(&buf, " - ");
1779 elog(LOG, "%s", buf.data);
1780 pfree(buf.data);
1781 }
1782#endif
1783
1784 /* Handle interrupt signals of startup process */
1786
1787 /*
1788 * Pause WAL replay, if requested by a hot-standby session via
1789 * SetRecoveryPause().
1790 *
1791 * Note that we intentionally don't take the info_lck spinlock
1792 * here. We might therefore read a slightly stale value of the
1793 * recoveryPause flag, but it can't be very stale (no worse than
1794 * the last spinlock we did acquire). Since a pause request is a
1795 * pretty asynchronous thing anyway, possibly responding to it one
1796 * WAL record later than we otherwise would is a minor issue, so
1797 * it doesn't seem worth adding another spinlock cycle to prevent
1798 * that.
1799 */
1800 if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1802 recoveryPausesHere(false);
1803
1804 /*
1805 * Have we reached our recovery target?
1806 */
1808 {
1809 reachedRecoveryTarget = true;
1810 break;
1811 }
1812
1813 /*
1814 * If we've been asked to lag the primary, wait on latch until
1815 * enough time has passed.
1816 */
1818 {
1819 /*
1820 * We test for paused recovery again here. If user sets
1821 * delayed apply, it may be because they expect to pause
1822 * recovery in case of problems, so we must test again here
1823 * otherwise pausing during the delay-wait wouldn't work.
1824 */
1825 if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1827 recoveryPausesHere(false);
1828 }
1829
1830 /*
1831 * Apply the record
1832 */
1833 ApplyWalRecord(xlogreader, record, &replayTLI);
1834
1835 /* Exit loop if we reached inclusive recovery target */
1837 {
1838 reachedRecoveryTarget = true;
1839 break;
1840 }
1841
1842 /*
1843 * If we replayed an LSN that someone was waiting for then walk
1844 * over the shared memory array and set latches to notify the
1845 * waiters.
1846 */
1847 if (waitLSNState &&
1851
1852 /* Else, try to fetch the next WAL record */
1853 record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1854 } while (record != NULL);
1855
1856 /*
1857 * end of main redo apply loop
1858 */
1859
1860 if (reachedRecoveryTarget)
1861 {
1862 if (!reachedConsistency)
1863 ereport(FATAL,
1864 (errmsg("requested recovery stop point is before consistent recovery point")));
1865
1866 /*
1867 * This is the last point where we can restart recovery with a new
1868 * recovery target, if we shutdown and begin again. After this,
1869 * Resource Managers may choose to do permanent corrective actions
1870 * at end of recovery.
1871 */
1872 switch (recoveryTargetAction)
1873 {
1875
1876 /*
1877 * exit with special return code to request shutdown of
1878 * postmaster. Log messages issued from postmaster.
1879 */
1880 proc_exit(3);
1881
1883 SetRecoveryPause(true);
1884 recoveryPausesHere(true);
1885
1886 /* drop into promote */
1887
1889 break;
1890 }
1891 }
1892
1893 RmgrCleanup();
1894
1895 ereport(LOG,
1896 errmsg("redo done at %X/%08X system usage: %s",
1898 pg_rusage_show(&ru0)));
1899 xtime = GetLatestXTime();
1900 if (xtime)
1901 ereport(LOG,
1902 (errmsg("last completed transaction was at log time %s",
1903 timestamptz_to_str(xtime))));
1904
1905 InRedo = false;
1906 }
1907 else
1908 {
1909 /* there are no WAL records following the checkpoint */
1910 ereport(LOG,
1911 (errmsg("redo is not required")));
1912 }
1913
1914 /*
1915 * This check is intentionally after the above log messages that indicate
1916 * how far recovery went.
1917 */
1920 !reachedRecoveryTarget)
1921 ereport(FATAL,
1922 (errcode(ERRCODE_CONFIG_FILE_ERROR),
1923 errmsg("recovery ended before configured recovery target was reached")));
1924}
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:465
void begin_startup_progress_phase(void)
Definition: startup.c:343
void ProcessStartupProcInterrupts(void)
Definition: startup.c:154
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
#define elog(elevel,...)
Definition: elog.h:226
bool IsUnderPostmaster
Definition: globals.c:120
void proc_exit(int code)
Definition: ipc.c:104
#define XLOG_CHECKPOINT_REDO
Definition: pg_control.h:82
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
static char * buf
Definition: pg_test_fsync.c:72
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:165
@ PMSIGNAL_RECOVERY_STARTED
Definition: pmsignal.h:35
void RmgrStartup(void)
Definition: rmgr.c:58
void RmgrCleanup(void)
Definition: rmgr.c:74
#define ereport_startup_progress(msg,...)
Definition: startup.h:18
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
pg_atomic_uint64 minWaitedLSN[WAIT_LSN_TYPE_COUNT]
Definition: xlogwait.h:79
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:205
RmgrId xl_rmid
Definition: xlogrecord.h:47
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
bool reachedConsistency
Definition: xlogrecovery.c:302
static bool recoveryStopsBefore(XLogReaderState *record)
int recoveryTargetAction
Definition: xlogrecovery.c:90
static bool recoveryApplyDelay(XLogReaderState *record)
static bool recoveryStopsAfter(XLogReaderState *record)
static void CheckRecoveryConsistency(void)
void SetRecoveryPause(bool recoveryPause)
void xlog_outdesc(StringInfo buf, XLogReaderState *record)
static bool InRedo
Definition: xlogrecovery.c:206
static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
static void recoveryPausesHere(bool endOfRecovery)
TimestampTz GetLatestXTime(void)
struct WaitLSNState * waitLSNState
Definition: xlogwait.c:63
void WaitLSNWakeup(WaitLSNType lsnType, XLogRecPtr currentLSN)
Definition: xlogwait.c:269
@ WAIT_LSN_TYPE_REPLAY
Definition: xlogwait.h:38

References appendStringInfo(), appendStringInfoString(), ApplyWalRecord(), ArchiveRecoveryRequested, Assert(), begin_startup_progress_phase(), buf, CheckPointLoc, CheckPointTLI, CheckRecoveryConsistency(), XLogRecoveryCtlData::currentChunkStartTime, elog, XLogReaderState::EndRecPtr, ereport, ereport_startup_progress, errcode(), errmsg(), FATAL, GetCurrentTimestamp(), GetLatestXTime(), XLogRecoveryCtlData::info_lck, initStringInfo(), InRedo, InvalidXLogRecPtr, IsUnderPostmaster, XLogRecoveryCtlData::lastReplayedEndRecPtr, XLogRecoveryCtlData::lastReplayedReadRecPtr, XLogRecoveryCtlData::lastReplayedTLI, LOG, LSN_FORMAT_ARGS, WaitLSNState::minWaitedLSN, PANIC, pfree(), pg_atomic_read_u64(), pg_rusage_init(), pg_rusage_show(), PMSIGNAL_RECOVERY_STARTED, proc_exit(), ProcessStartupProcInterrupts(), reachedConsistency, ReadRecord(), XLogReaderState::ReadRecPtr, RECOVERY_NOT_PAUSED, RECOVERY_TARGET_ACTION_PAUSE, RECOVERY_TARGET_ACTION_PROMOTE, RECOVERY_TARGET_ACTION_SHUTDOWN, RECOVERY_TARGET_UNSET, recoveryApplyDelay(), XLogRecoveryCtlData::recoveryLastXTime, recoveryPausesHere(), XLogRecoveryCtlData::recoveryPauseState, recoveryStopsAfter(), recoveryStopsBefore(), recoveryTarget, recoveryTargetAction, RedoStartLSN, RedoStartTLI, XLogRecoveryCtlData::replayEndRecPtr, XLogRecoveryCtlData::replayEndTLI, RmgrCleanup(), RmgrStartup(), SendPostmasterSignal(), SetRecoveryPause(), SpinLockAcquire, SpinLockRelease, StandbyMode, timestamptz_to_str(), WAIT_LSN_TYPE_REPLAY, waitLSNState, WaitLSNWakeup(), XLogRecord::xl_info, XLogRecord::xl_rmid, XLOG_CHECKPOINT_REDO, xlog_outdesc(), xlogprefetcher, XLogPrefetcherBeginRead(), xlogreader, XLogReceiptTime, XLogRecoveryCtl, and XLR_INFO_MASK.

Referenced by StartupXLOG().

◆ PromoteIsTriggered()

bool PromoteIsTriggered ( void  )

Definition at line 4450 of file xlogrecovery.c.

4451{
4452 /*
4453 * We check shared state each time only until a standby promotion is
4454 * triggered. We can't trigger a promotion again, so there's no need to
4455 * keep checking after the shared variable has once been seen true.
4456 */
4458 return true;
4459
4463
4465}
static bool LocalPromoteIsTriggered
Definition: xlogrecovery.c:185

References XLogRecoveryCtlData::info_lck, LocalPromoteIsTriggered, XLogRecoveryCtlData::SharedPromoteIsTriggered, SpinLockAcquire, SpinLockRelease, and XLogRecoveryCtl.

Referenced by ExecWaitStmt(), PerformRecoveryXLogAction(), pg_wal_replay_pause(), pg_wal_replay_resume(), and WaitForLSN().

◆ RecoveryRequiresIntParameter()

void RecoveryRequiresIntParameter ( const char *  param_name,
int  currValue,
int  minValue 
)

Definition at line 4715 of file xlogrecovery.c.

4716{
4717 if (currValue < minValue)
4718 {
4720 {
4721 bool warned_for_promote = false;
4722
4724 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4725 errmsg("hot standby is not possible because of insufficient parameter settings"),
4726 errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4727 param_name,
4728 currValue,
4729 minValue)));
4730
4731 SetRecoveryPause(true);
4732
4733 ereport(LOG,
4734 (errmsg("recovery has paused"),
4735 errdetail("If recovery is unpaused, the server will shut down."),
4736 errhint("You can then restart the server after making the necessary configuration changes.")));
4737
4739 {
4741
4743 {
4744 if (!warned_for_promote)
4746 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4747 errmsg("promotion is not possible because of insufficient parameter settings"),
4748
4749 /*
4750 * Repeat the detail from above so it's easy to find
4751 * in the log.
4752 */
4753 errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4754 param_name,
4755 currValue,
4756 minValue),
4757 errhint("Restart the server after making the necessary configuration changes.")));
4758 warned_for_promote = true;
4759 }
4760
4761 /*
4762 * If recovery pause is requested then set it paused. While
4763 * we are in the loop, user might resume and pause again so
4764 * set this every time.
4765 */
4767
4768 /*
4769 * We wait on a condition variable that will wake us as soon
4770 * as the pause ends, but we use a timeout so we can check the
4771 * above conditions periodically too.
4772 */
4774 WAIT_EVENT_RECOVERY_PAUSE);
4775 }
4777 }
4778
4779 ereport(FATAL,
4780 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4781 errmsg("recovery aborted because of insufficient parameter settings"),
4782 /* Repeat the detail from above so it's easy to find in the log. */
4783 errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4784 param_name,
4785 currValue,
4786 minValue),
4787 errhint("You can restart the server after making the necessary configuration changes.")));
4788 }
4789}
bool ConditionVariableCancelSleep(void)
bool ConditionVariableTimedSleep(ConditionVariable *cv, long timeout, uint32 wait_event_info)
#define WARNING
Definition: elog.h:36
ConditionVariable recoveryNotPausedCV
Definition: xlogrecovery.c:367
static bool CheckForStandbyTrigger(void)
static void ConfirmRecoveryPaused(void)
static bool HotStandbyActiveInReplay(void)
RecoveryPauseState GetRecoveryPauseState(void)

References CheckForStandbyTrigger(), ConditionVariableCancelSleep(), ConditionVariableTimedSleep(), ConfirmRecoveryPaused(), ereport, errcode(), errdetail(), errhint(), errmsg(), FATAL, GetRecoveryPauseState(), HotStandbyActiveInReplay(), LOG, ProcessStartupProcInterrupts(), RECOVERY_NOT_PAUSED, XLogRecoveryCtlData::recoveryNotPausedCV, SetRecoveryPause(), WARNING, and XLogRecoveryCtl.

Referenced by CheckRequiredParameterValues().

◆ RemovePromoteSignalFiles()

void RemovePromoteSignalFiles ( void  )

Definition at line 4510 of file xlogrecovery.c.

4511{
4512 unlink(PROMOTE_SIGNAL_FILE);
4513}

References PROMOTE_SIGNAL_FILE.

Referenced by CheckForStandbyTrigger(), and PostmasterMain().

◆ SetRecoveryPause()

◆ ShutdownWalRecovery()

void ShutdownWalRecovery ( void  )

Definition at line 1618 of file xlogrecovery.c.

1619{
1620 char recoveryPath[MAXPGPATH];
1621
1622 /* Final update of pg_stat_recovery_prefetch. */
1624
1625 /* Shut down xlogreader */
1626 if (readFile >= 0)
1627 {
1628 close(readFile);
1629 readFile = -1;
1630 }
1634
1636 {
1637 /*
1638 * Since there might be a partial WAL segment named RECOVERYXLOG, get
1639 * rid of it.
1640 */
1641 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
1642 unlink(recoveryPath); /* ignore any error */
1643
1644 /* Get rid of any remaining recovered timeline-history file, too */
1645 snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
1646 unlink(recoveryPath); /* ignore any error */
1647 }
1648
1649 /*
1650 * We don't need the latch anymore. It's not strictly necessary to disown
1651 * it, but let's do it for the sake of tidiness.
1652 */
1655}
void DisownLatch(Latch *latch)
Definition: latch.c:144
#define MAXPGPATH
#define snprintf
Definition: port.h:260
void * private_data
Definition: xlogreader.h:195
#define XLOGDIR
void XLogPrefetcherComputeStats(XLogPrefetcher *prefetcher)
void XLogPrefetcherFree(XLogPrefetcher *prefetcher)
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:162

References ArchiveRecoveryRequested, close, DisownLatch(), MAXPGPATH, pfree(), XLogReaderState::private_data, readFile, XLogRecoveryCtlData::recoveryWakeupLatch, snprintf, XLOGDIR, xlogprefetcher, XLogPrefetcherComputeStats(), XLogPrefetcherFree(), xlogreader, XLogReaderFree(), and XLogRecoveryCtl.

Referenced by StartupXLOG().

◆ StartupRequestWalReceiverRestart()

void StartupRequestWalReceiverRestart ( void  )

Definition at line 4431 of file xlogrecovery.c.

4432{
4434 {
4435 ereport(LOG,
4436 (errmsg("WAL receiver process shutdown requested")));
4437
4438 pendingWalRcvRestart = true;
4439 }
4440}
bool WalRcvRunning(void)
static bool pendingWalRcvRestart
Definition: xlogrecovery.c:251
static XLogSource currentSource
Definition: xlogrecovery.c:249

References currentSource, ereport, errmsg(), LOG, pendingWalRcvRestart, WalRcvRunning(), and XLOG_FROM_STREAM.

Referenced by StartupRereadConfig().

◆ WakeupRecovery()

◆ xlog_outdesc()

void xlog_outdesc ( StringInfo  buf,
XLogReaderState record 
)

Definition at line 2321 of file xlogrecovery.c.

2322{
2323 RmgrData rmgr = GetRmgr(XLogRecGetRmid(record));
2324 uint8 info = XLogRecGetInfo(record);
2325 const char *id;
2326
2329
2330 id = rmgr.rm_identify(info);
2331 if (id == NULL)
2332 appendStringInfo(buf, "UNKNOWN (%X): ", info & ~XLR_INFO_MASK);
2333 else
2334 appendStringInfo(buf, "%s: ", id);
2335
2336 rmgr.rm_desc(buf, record);
2337}
uint8_t uint8
Definition: c.h:539
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
const char *(* rm_identify)(uint8 info)
const char * rm_name
void(* rm_desc)(StringInfo buf, XLogReaderState *record)
static RmgrData GetRmgr(RmgrId rmid)
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:409
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:410

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), buf, GetRmgr(), RmgrData::rm_desc, RmgrData::rm_identify, RmgrData::rm_name, XLogRecGetInfo, XLogRecGetRmid, and XLR_INFO_MASK.

Referenced by PerformWalRecovery(), rm_redo_error_callback(), and XLogInsertRecord().

◆ XLogRecoveryShmemInit()

void XLogRecoveryShmemInit ( void  )

Definition at line 466 of file xlogrecovery.c.

467{
468 bool found;
469
471 ShmemInitStruct("XLOG Recovery Ctl", XLogRecoveryShmemSize(), &found);
472 if (found)
473 return;
474 memset(XLogRecoveryCtl, 0, sizeof(XLogRecoveryCtlData));
475
479}
void ConditionVariableInit(ConditionVariable *cv)
void InitSharedLatch(Latch *latch)
Definition: latch.c:93
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:389
#define SpinLockInit(lock)
Definition: spin.h:57
Size XLogRecoveryShmemSize(void)
Definition: xlogrecovery.c:455

References ConditionVariableInit(), XLogRecoveryCtlData::info_lck, InitSharedLatch(), XLogRecoveryCtlData::recoveryNotPausedCV, XLogRecoveryCtlData::recoveryWakeupLatch, ShmemInitStruct(), SpinLockInit, XLogRecoveryCtl, and XLogRecoveryShmemSize().

Referenced by CreateOrAttachShmemStructs().

◆ XLogRecoveryShmemSize()

Size XLogRecoveryShmemSize ( void  )

Definition at line 455 of file xlogrecovery.c.

456{
457 Size size;
458
459 /* XLogRecoveryCtl */
460 size = sizeof(XLogRecoveryCtlData);
461
462 return size;
463}
size_t Size
Definition: c.h:613
struct XLogRecoveryCtlData XLogRecoveryCtlData

Referenced by CalculateShmemSize(), and XLogRecoveryShmemInit().

◆ XLogRequestWalReceiverReply()

void XLogRequestWalReceiverReply ( void  )

Definition at line 4543 of file xlogrecovery.c.

4544{
4546}
static bool doRequestWalReceiverReply
Definition: xlogrecovery.c:188

References doRequestWalReceiverReply.

Referenced by xact_redo_commit().

Variable Documentation

◆ archiveCleanupCommand

PGDLLIMPORT char* archiveCleanupCommand
extern

Definition at line 87 of file xlogrecovery.c.

Referenced by CreateRestartPoint().

◆ PrimaryConnInfo

PGDLLIMPORT char* PrimaryConnInfo
extern

Definition at line 99 of file xlogrecovery.c.

◆ PrimarySlotName

PGDLLIMPORT char* PrimarySlotName
extern

Definition at line 100 of file xlogrecovery.c.

◆ reachedConsistency

◆ recovery_min_apply_delay

PGDLLIMPORT int recovery_min_apply_delay
extern

Definition at line 96 of file xlogrecovery.c.

Referenced by recoveryApplyDelay().

◆ recovery_target_time_string

PGDLLIMPORT char* recovery_target_time_string
extern

Definition at line 92 of file xlogrecovery.c.

Referenced by validateRecoveryParameters().

◆ recoveryEndCommand

PGDLLIMPORT char* recoveryEndCommand
extern

Definition at line 86 of file xlogrecovery.c.

Referenced by CleanupAfterArchiveRecovery().

◆ recoveryRestoreCommand

PGDLLIMPORT char* recoveryRestoreCommand
extern

Definition at line 85 of file xlogrecovery.c.

Referenced by RestoreArchivedFile(), and validateRecoveryParameters().

◆ recoveryTarget

◆ recoveryTargetAction

PGDLLIMPORT int recoveryTargetAction
extern

Definition at line 90 of file xlogrecovery.c.

Referenced by PerformWalRecovery(), and validateRecoveryParameters().

◆ recoveryTargetInclusive

PGDLLIMPORT bool recoveryTargetInclusive
extern

Definition at line 89 of file xlogrecovery.c.

Referenced by recoveryStopsAfter(), and recoveryStopsBefore().

◆ recoveryTargetLSN

PGDLLIMPORT XLogRecPtr recoveryTargetLSN
extern

◆ recoveryTargetName

PGDLLIMPORT const char* recoveryTargetName
extern

Definition at line 94 of file xlogrecovery.c.

Referenced by assign_recovery_target_name(), InitWalRecovery(), and recoveryStopsAfter().

◆ recoveryTargetTime

PGDLLIMPORT TimestampTz recoveryTargetTime
extern

Definition at line 93 of file xlogrecovery.c.

Referenced by InitWalRecovery(), recoveryStopsBefore(), and validateRecoveryParameters().

◆ recoveryTargetTimeLineGoal

◆ recoveryTargetTLI

◆ recoveryTargetTLIRequested

PGDLLIMPORT TimeLineID recoveryTargetTLIRequested
extern

Definition at line 124 of file xlogrecovery.c.

Referenced by assign_recovery_target_timeline(), and validateRecoveryParameters().

◆ recoveryTargetXid

PGDLLIMPORT TransactionId recoveryTargetXid
extern

◆ StandbyMode

◆ wal_receiver_create_temp_slot

PGDLLIMPORT bool wal_receiver_create_temp_slot
extern

Definition at line 101 of file xlogrecovery.c.

Referenced by StartupRereadConfig(), and WaitForWALToBecomeAvailable().