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  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 44 of file xlogrecovery.h.

45 {
46  RECOVERY_NOT_PAUSED, /* pause not requested */
47  RECOVERY_PAUSE_REQUESTED, /* pause requested, but not yet paused */
48  RECOVERY_PAUSED /* recovery is paused */
RecoveryPauseState
Definition: xlogrecovery.h:45
@ RECOVERY_PAUSED
Definition: xlogrecovery.h:48
@ RECOVERY_NOT_PAUSED
Definition: xlogrecovery.h:46
@ RECOVERY_PAUSE_REQUESTED
Definition: xlogrecovery.h:47

◆ RecoveryTargetTimeLineGoal

Enumerator
RECOVERY_TARGET_TIMELINE_CONTROLFILE 
RECOVERY_TARGET_TIMELINE_LATEST 
RECOVERY_TARGET_TIMELINE_NUMERIC 

Definition at line 36 of file xlogrecovery.h.

37 {
RecoveryTargetTimeLineGoal
Definition: xlogrecovery.h:37
@ RECOVERY_TARGET_TIMELINE_NUMERIC
Definition: xlogrecovery.h:40
@ RECOVERY_TARGET_TIMELINE_CONTROLFILE
Definition: xlogrecovery.h:38
@ RECOVERY_TARGET_TIMELINE_LATEST
Definition: xlogrecovery.h:39

◆ 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 4379 of file xlogrecovery.c.

4380 {
4381  struct stat stat_buf;
4382 
4383  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
4384  return true;
4385 
4386  return false;
4387 }
#define stat
Definition: win32_port.h:292
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:298

References PROMOTE_SIGNAL_FILE, and stat.

Referenced by CheckForStandbyTrigger(), and process_pm_pmsignal().

◆ FinishWalRecovery()

EndOfWalRecoveryInfo* FinishWalRecovery ( void  )

Definition at line 1406 of file xlogrecovery.c.

1407 {
1409  XLogRecPtr lastRec;
1410  TimeLineID lastRecTLI;
1411  XLogRecPtr endOfLog;
1412 
1413  /*
1414  * Kill WAL receiver, if it's still running, before we continue to write
1415  * the startup checkpoint and aborted-contrecord records. It will trump
1416  * over these records and subsequent ones if it's still alive when we
1417  * start writing WAL.
1418  */
1420 
1421  /*
1422  * We are now done reading the xlog from stream. Turn off streaming
1423  * recovery to force fetching the files (which would be required at end of
1424  * recovery, e.g., timeline history file) from archive or pg_wal.
1425  *
1426  * Note that standby mode must be turned off after killing WAL receiver,
1427  * i.e., calling XLogShutdownWalRcv().
1428  */
1429  Assert(!WalRcvStreaming());
1430  StandbyMode = false;
1431 
1432  /*
1433  * Determine where to start writing WAL next.
1434  *
1435  * Re-fetch the last valid or last applied record, so we can identify the
1436  * exact endpoint of what we consider the valid portion of WAL. There may
1437  * be an incomplete continuation record after that, in which case
1438  * 'abortedRecPtr' and 'missingContrecPtr' are set and the caller will
1439  * write a special OVERWRITE_CONTRECORD message to mark that the rest of
1440  * it is intentionally missing. See CreateOverwriteContrecordRecord().
1441  *
1442  * An important side-effect of this is to load the last page into
1443  * xlogreader. The caller uses it to initialize the WAL for writing.
1444  */
1445  if (!InRecovery)
1446  {
1447  lastRec = CheckPointLoc;
1448  lastRecTLI = CheckPointTLI;
1449  }
1450  else
1451  {
1453  lastRecTLI = XLogRecoveryCtl->lastReplayedTLI;
1454  }
1456  (void) ReadRecord(xlogprefetcher, PANIC, false, lastRecTLI);
1457  endOfLog = xlogreader->EndRecPtr;
1458 
1459  /*
1460  * Remember the TLI in the filename of the XLOG segment containing the
1461  * end-of-log. It could be different from the timeline that endOfLog
1462  * nominally belongs to, if there was a timeline switch in that segment,
1463  * and we were reading the old WAL from a segment belonging to a higher
1464  * timeline.
1465  */
1466  result->endOfLogTLI = xlogreader->seg.ws_tli;
1467 
1469  {
1470  /*
1471  * We are no longer in archive recovery state.
1472  *
1473  * We are now done reading the old WAL. Turn off archive fetching if
1474  * it was active.
1475  */
1477  InArchiveRecovery = false;
1478 
1479  /*
1480  * If the ending log segment is still open, close it (to avoid
1481  * problems on Windows with trying to rename or delete an open file).
1482  */
1483  if (readFile >= 0)
1484  {
1485  close(readFile);
1486  readFile = -1;
1487  }
1488  }
1489 
1490  /*
1491  * Copy the last partial block to the caller, for initializing the WAL
1492  * buffer for appending new WAL.
1493  */
1494  if (endOfLog % XLOG_BLCKSZ != 0)
1495  {
1496  char *page;
1497  int len;
1498  XLogRecPtr pageBeginPtr;
1499 
1500  pageBeginPtr = endOfLog - (endOfLog % XLOG_BLCKSZ);
1501  Assert(readOff == XLogSegmentOffset(pageBeginPtr, wal_segment_size));
1502 
1503  /* Copy the valid part of the last block */
1504  len = endOfLog % XLOG_BLCKSZ;
1505  page = palloc(len);
1506  memcpy(page, xlogreader->readBuf, len);
1507 
1508  result->lastPageBeginPtr = pageBeginPtr;
1509  result->lastPage = page;
1510  }
1511  else
1512  {
1513  /* There is no partial block to copy. */
1514  result->lastPageBeginPtr = endOfLog;
1515  result->lastPage = NULL;
1516  }
1517 
1518  /*
1519  * Create a comment for the history file to explain why and where timeline
1520  * changed.
1521  */
1523 
1524  result->lastRec = lastRec;
1525  result->lastRecTLI = lastRecTLI;
1526  result->endOfLog = endOfLog;
1527 
1528  result->abortedRecPtr = abortedRecPtr;
1530 
1533 
1534  return result;
1535 }
#define PANIC
Definition: elog.h:42
#define close(a)
Definition: win32.h:12
Assert(fmt[strlen(fmt) - 1] !='\n')
void * palloc(Size size)
Definition: mcxt.c:1226
const void size_t len
XLogRecPtr lastPageBeginPtr
Definition: xlogrecovery.h:111
XLogRecPtr abortedRecPtr
Definition: xlogrecovery.h:120
XLogRecPtr missingContrecPtr
Definition: xlogrecovery.h:121
TimeLineID endOfLogTLI
Definition: xlogrecovery.h:109
TimeLineID ws_tli
Definition: xlogreader.h:49
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
WALOpenSegment seg
Definition: xlogreader.h:272
TimeLineID lastReplayedTLI
Definition: xlogrecovery.c:340
XLogRecPtr lastReplayedReadRecPtr
Definition: xlogrecovery.c:338
bool WalRcvStreaming(void)
int wal_segment_size
Definition: xlog.c:146
void XLogShutdownWalRcv(void)
Definition: xlog.c:8936
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint32 TimeLineID
Definition: xlogdefs.h:59
void XLogPrefetcherBeginRead(XLogPrefetcher *prefetcher, XLogRecPtr recPtr)
static char * getRecoveryStopReason(void)
bool ArchiveRecoveryRequested
Definition: xlogrecovery.c:137
bool InArchiveRecovery
Definition: xlogrecovery.c:138
static XLogRecPtr missingContrecPtr
Definition: xlogrecovery.c:373
static XLogRecoveryCtlData * XLogRecoveryCtl
Definition: xlogrecovery.c:364
static uint32 readOff
Definition: xlogrecovery.c:232
static bool standby_signal_file_found
Definition: xlogrecovery.c:150
bool StandbyMode
Definition: xlogrecovery.c:147
static int readFile
Definition: xlogrecovery.c:230
static XLogRecPtr abortedRecPtr
Definition: xlogrecovery.c:372
static XLogRecord * ReadRecord(XLogPrefetcher *xlogprefetcher, int emode, bool fetching_ckpt, TimeLineID replayTLI)
static XLogRecPtr CheckPointLoc
Definition: xlogrecovery.c:167
static bool recovery_signal_file_found
Definition: xlogrecovery.c:151
static XLogPrefetcher * xlogprefetcher
Definition: xlogrecovery.c:191
static XLogReaderState * xlogreader
Definition: xlogrecovery.c:188
static TimeLineID CheckPointTLI
Definition: xlogrecovery.c:168
bool InRecovery
Definition: xlogutils.c:53

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, 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 4542 of file xlogrecovery.c.

4543 {
4544  TimestampTz xtime;
4545 
4549 
4550  return xtime;
4551 }
int64 TimestampTz
Definition: timestamp.h:39
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz currentChunkStartTime
Definition: xlogrecovery.c:356

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

Referenced by GetReplicationApplyDelay().

◆ GetCurrentReplayRecPtr()

XLogRecPtr GetCurrentReplayRecPtr ( TimeLineID replayEndTLI)

Definition at line 4478 of file xlogrecovery.c.

4479 {
4480  XLogRecPtr recptr;
4481  TimeLineID tli;
4482 
4484  recptr = XLogRecoveryCtl->replayEndRecPtr;
4487 
4488  if (replayEndTLI)
4489  *replayEndTLI = tli;
4490  return recptr;
4491 }
TimeLineID replayEndTLI
Definition: xlogrecovery.c:348
XLogRecPtr replayEndRecPtr
Definition: xlogrecovery.c:347

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

Referenced by UpdateMinRecoveryPoint(), and xlog_redo().

◆ GetLatestXTime()

TimestampTz GetLatestXTime ( void  )

◆ GetRecoveryPauseState()

◆ GetXLogReceiptTime()

void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 4558 of file xlogrecovery.c.

4559 {
4560  /*
4561  * This must be executed in the startup process, since we don't export the
4562  * relevant state to shared memory.
4563  */
4564  Assert(InRecovery);
4565 
4566  *rtime = XLogReceiptTime;
4567  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
4568 }
static XLogSource XLogReceiptSource
Definition: xlogrecovery.c:259
@ XLOG_FROM_STREAM
Definition: xlogrecovery.c:214
static TimestampTz XLogReceiptTime
Definition: xlogrecovery.c:258

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

Referenced by GetStandbyLimitTime().

◆ GetXLogReplayRecPtr()

◆ HotStandbyActive()

bool HotStandbyActive ( void  )

Definition at line 4418 of file xlogrecovery.c.

4419 {
4420  /*
4421  * We check shared state each time only until Hot Standby is active. We
4422  * can't de-activate Hot Standby, so there's no need to keep checking
4423  * after the shared variable has once been seen true.
4424  */
4426  return true;
4427  else
4428  {
4429  /* spinlock is essential on machines with weak memory ordering! */
4433 
4434  return LocalHotStandbyActive;
4435  }
4436 }
static bool LocalHotStandbyActive
Definition: xlogrecovery.c:176

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 512 of file xlogrecovery.c.

514 {
515  XLogPageReadPrivate *private;
516  struct stat st;
517  bool wasShutdown;
518  XLogRecord *record;
519  DBState dbstate_at_startup;
520  bool haveTblspcMap = false;
521  bool haveBackupLabel = false;
522  CheckPoint checkPoint;
523  bool backupFromStandby = false;
524 
525  dbstate_at_startup = ControlFile->state;
526 
527  /*
528  * Initialize on the assumption we want to recover to the latest timeline
529  * that's active according to pg_control.
530  */
534  else
536 
537  /*
538  * Check for signal files, and if so set up state for offline recovery
539  */
542 
544  {
546  ereport(LOG,
547  (errmsg("entering standby mode")));
549  ereport(LOG,
550  (errmsg("starting point-in-time recovery to XID %u",
553  ereport(LOG,
554  (errmsg("starting point-in-time recovery to %s",
557  ereport(LOG,
558  (errmsg("starting point-in-time recovery to \"%s\"",
561  ereport(LOG,
562  (errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%X\"",
565  ereport(LOG,
566  (errmsg("starting point-in-time recovery to earliest consistent point")));
567  else
568  ereport(LOG,
569  (errmsg("starting archive recovery")));
570  }
571 
572  /*
573  * Take ownership of the wakeup latch if we're going to sleep during
574  * recovery.
575  */
578 
579  private = palloc0(sizeof(XLogPageReadPrivate));
580  xlogreader =
582  XL_ROUTINE(.page_read = &XLogPageRead,
583  .segment_open = NULL,
584  .segment_close = wal_segment_close),
585  private);
586  if (!xlogreader)
587  ereport(ERROR,
588  (errcode(ERRCODE_OUT_OF_MEMORY),
589  errmsg("out of memory"),
590  errdetail("Failed while allocating a WAL reading processor.")));
592 
593  /*
594  * Set the WAL decode buffer size. This limits how far ahead we can read
595  * in the WAL.
596  */
598 
599  /* Create a WAL prefetcher. */
601 
602  /*
603  * Allocate two page buffers dedicated to WAL consistency checks. We do
604  * it this way, rather than just making static arrays, for two reasons:
605  * (1) no need to waste the storage in most instantiations of the backend;
606  * (2) a static char array isn't guaranteed to have any particular
607  * alignment, whereas palloc() will provide MAXALIGN'd storage.
608  */
609  replay_image_masked = (char *) palloc(BLCKSZ);
610  primary_image_masked = (char *) palloc(BLCKSZ);
611 
613  &backupFromStandby))
614  {
615  List *tablespaces = NIL;
616 
617  /*
618  * Archive recovery was requested, and thanks to the backup label
619  * file, we know how far we need to replay to reach consistency. Enter
620  * archive recovery directly.
621  */
622  InArchiveRecovery = true;
625 
626  /*
627  * When a backup_label file is present, we want to roll forward from
628  * the checkpoint it identifies, rather than using pg_control.
629  */
631  CheckPointTLI);
632  if (record != NULL)
633  {
634  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
635  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
636  ereport(DEBUG1,
637  (errmsg_internal("checkpoint record is at %X/%X",
639  InRecovery = true; /* force recovery even if SHUTDOWNED */
640 
641  /*
642  * Make sure that REDO location exists. This may not be the case
643  * if there was a crash during an online backup, which left a
644  * backup_label around that references a WAL segment that's
645  * already been archived.
646  */
647  if (checkPoint.redo < CheckPointLoc)
648  {
650  if (!ReadRecord(xlogprefetcher, LOG, false,
651  checkPoint.ThisTimeLineID))
652  ereport(FATAL,
653  (errmsg("could not find redo location referenced by checkpoint record"),
654  errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" and add required recovery options.\n"
655  "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
656  "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
657  DataDir, DataDir, DataDir)));
658  }
659  }
660  else
661  {
662  ereport(FATAL,
663  (errmsg("could not locate required checkpoint record"),
664  errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" and add required recovery options.\n"
665  "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
666  "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
667  DataDir, DataDir, DataDir)));
668  wasShutdown = false; /* keep compiler quiet */
669  }
670 
671  /* Read the tablespace_map file if present and create symlinks. */
672  if (read_tablespace_map(&tablespaces))
673  {
674  ListCell *lc;
675 
676  foreach(lc, tablespaces)
677  {
678  tablespaceinfo *ti = lfirst(lc);
679  char *linkloc;
680 
681  linkloc = psprintf("pg_tblspc/%s", ti->oid);
682 
683  /*
684  * Remove the existing symlink if any and Create the symlink
685  * under PGDATA.
686  */
687  remove_tablespace_symlink(linkloc);
688 
689  if (symlink(ti->path, linkloc) < 0)
690  ereport(ERROR,
692  errmsg("could not create symbolic link \"%s\": %m",
693  linkloc)));
694 
695  pfree(ti->oid);
696  pfree(ti->path);
697  pfree(ti);
698  }
699 
700  /* tell the caller to delete it later */
701  haveTblspcMap = true;
702  }
703 
704  /* tell the caller to delete it later */
705  haveBackupLabel = true;
706  }
707  else
708  {
709  /*
710  * If tablespace_map file is present without backup_label file, there
711  * is no use of such file. There is no harm in retaining it, but it
712  * is better to get rid of the map file so that we don't have any
713  * redundant file in data directory and it will avoid any sort of
714  * confusion. It seems prudent though to just rename the file out of
715  * the way rather than delete it completely, also we ignore any error
716  * that occurs in rename operation as even if map file is present
717  * without backup_label file, it is harmless.
718  */
719  if (stat(TABLESPACE_MAP, &st) == 0)
720  {
721  unlink(TABLESPACE_MAP_OLD);
723  ereport(LOG,
724  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
726  errdetail("File \"%s\" was renamed to \"%s\".",
728  else
729  ereport(LOG,
730  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
732  errdetail("Could not rename file \"%s\" to \"%s\": %m.",
734  }
735 
736  /*
737  * It's possible that archive recovery was requested, but we don't
738  * know how far we need to replay the WAL before we reach consistency.
739  * This can happen for example if a base backup is taken from a
740  * running server using an atomic filesystem snapshot, without calling
741  * pg_backup_start/stop. Or if you just kill a running primary server
742  * and put it into archive recovery by creating a recovery signal
743  * file.
744  *
745  * Our strategy in that case is to perform crash recovery first,
746  * replaying all the WAL present in pg_wal, and only enter archive
747  * recovery after that.
748  *
749  * But usually we already know how far we need to replay the WAL (up
750  * to minRecoveryPoint, up to backupEndPoint, or until we see an
751  * end-of-backup record), and we can enter archive recovery directly.
752  */
758  {
759  InArchiveRecovery = true;
762  }
763 
764  /* Get the last valid checkpoint record. */
770  CheckPointTLI);
771  if (record != NULL)
772  {
773  ereport(DEBUG1,
774  (errmsg_internal("checkpoint record is at %X/%X",
776  }
777  else
778  {
779  /*
780  * We used to attempt to go back to a secondary checkpoint record
781  * here, but only when not in standby mode. We now just fail if we
782  * can't read the last checkpoint because this allows us to
783  * simplify processing around checkpoints.
784  */
785  ereport(PANIC,
786  (errmsg("could not locate a valid checkpoint record")));
787  }
788  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
789  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
790  }
791 
792  /*
793  * If the location of the checkpoint record is not on the expected
794  * timeline in the history of the requested timeline, we cannot proceed:
795  * the backup is not part of the history of the requested timeline.
796  */
797  Assert(expectedTLEs); /* was initialized by reading checkpoint
798  * record */
801  {
802  XLogRecPtr switchpoint;
803 
804  /*
805  * tliSwitchPoint will throw an error if the checkpoint's timeline is
806  * not in expectedTLEs at all.
807  */
809  ereport(FATAL,
810  (errmsg("requested timeline %u is not a child of this server's history",
812  errdetail("Latest checkpoint is at %X/%X on timeline %u, but in the history of the requested timeline, the server forked off from that timeline at %X/%X.",
815  LSN_FORMAT_ARGS(switchpoint))));
816  }
817 
818  /*
819  * The min recovery point should be part of the requested timeline's
820  * history, too.
821  */
825  ereport(FATAL,
826  (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
830 
831  ereport(DEBUG1,
832  (errmsg_internal("redo record is at %X/%X; shutdown %s",
833  LSN_FORMAT_ARGS(checkPoint.redo),
834  wasShutdown ? "true" : "false")));
835  ereport(DEBUG1,
836  (errmsg_internal("next transaction ID: " UINT64_FORMAT "; next OID: %u",
837  U64FromFullTransactionId(checkPoint.nextXid),
838  checkPoint.nextOid)));
839  ereport(DEBUG1,
840  (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %u",
841  checkPoint.nextMulti, checkPoint.nextMultiOffset)));
842  ereport(DEBUG1,
843  (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
844  checkPoint.oldestXid, checkPoint.oldestXidDB)));
845  ereport(DEBUG1,
846  (errmsg_internal("oldest MultiXactId: %u, in database %u",
847  checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
848  ereport(DEBUG1,
849  (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
850  checkPoint.oldestCommitTsXid,
851  checkPoint.newestCommitTsXid)));
853  ereport(PANIC,
854  (errmsg("invalid next transaction ID")));
855 
856  /* sanity check */
857  if (checkPoint.redo > CheckPointLoc)
858  ereport(PANIC,
859  (errmsg("invalid redo in checkpoint record")));
860 
861  /*
862  * Check whether we need to force recovery from WAL. If it appears to
863  * have been a clean shutdown and we did not have a recovery signal file,
864  * then assume no recovery needed.
865  */
866  if (checkPoint.redo < CheckPointLoc)
867  {
868  if (wasShutdown)
869  ereport(PANIC,
870  (errmsg("invalid redo record in shutdown checkpoint")));
871  InRecovery = true;
872  }
873  else if (ControlFile->state != DB_SHUTDOWNED)
874  InRecovery = true;
875  else if (ArchiveRecoveryRequested)
876  {
877  /* force recovery due to presence of recovery signal file */
878  InRecovery = true;
879  }
880 
881  /*
882  * If recovery is needed, update our in-memory copy of pg_control to show
883  * that we are recovering and to show the selected checkpoint as the place
884  * we are starting from. We also mark pg_control with any minimum recovery
885  * stop point obtained from a backup history file.
886  *
887  * We don't write the changes to disk yet, though. Only do that after
888  * initializing various subsystems.
889  */
890  if (InRecovery)
891  {
892  if (InArchiveRecovery)
893  {
895  }
896  else
897  {
898  ereport(LOG,
899  (errmsg("database system was not properly shut down; "
900  "automatic recovery in progress")));
902  ereport(LOG,
903  (errmsg("crash recovery starts in timeline %u "
904  "and has target timeline %u",
908  }
910  ControlFile->checkPointCopy = checkPoint;
911  if (InArchiveRecovery)
912  {
913  /* initialize minRecoveryPoint if not set yet */
914  if (ControlFile->minRecoveryPoint < checkPoint.redo)
915  {
916  ControlFile->minRecoveryPoint = checkPoint.redo;
918  }
919  }
920 
921  /*
922  * Set backupStartPoint if we're starting recovery from a base backup.
923  *
924  * Also set backupEndPoint and use minRecoveryPoint as the backup end
925  * location if we're starting recovery from a base backup which was
926  * taken from a standby. In this case, the database system status in
927  * pg_control must indicate that the database was already in recovery.
928  * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
929  * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
930  * before reaching this point; e.g. because restore_command or
931  * primary_conninfo were faulty.
932  *
933  * Any other state indicates that the backup somehow became corrupted
934  * and we can't sensibly continue with recovery.
935  */
936  if (haveBackupLabel)
937  {
938  ControlFile->backupStartPoint = checkPoint.redo;
940 
941  if (backupFromStandby)
942  {
943  if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
944  dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
945  ereport(FATAL,
946  (errmsg("backup_label contains data inconsistent with control file"),
947  errhint("This means that the backup is corrupted and you will "
948  "have to use another backup for recovery.")));
950  }
951  }
952  }
953 
954  /* remember these, so that we know when we have reached consistency */
958  if (InArchiveRecovery)
959  {
962  }
963  else
964  {
967  }
968 
969  /*
970  * Start recovery assuming that the final record isn't lost.
971  */
974 
975  *wasShutdown_ptr = wasShutdown;
976  *haveBackupLabel_ptr = haveBackupLabel;
977  *haveTblspcMap_ptr = haveTblspcMap;
978 }
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:889
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1782
#define UINT64_FORMAT
Definition: c.h:533
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errcode_for_file_access(void)
Definition: elog.c:881
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#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:149
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:693
char * DataDir
Definition: globals.c:66
void OwnLatch(Latch *latch)
Definition: latch.c:438
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257
DBState
Definition: pg_control.h:88
@ DB_IN_ARCHIVE_RECOVERY
Definition: pg_control.h:94
@ DB_SHUTDOWNED_IN_RECOVERY
Definition: pg_control.h:91
@ DB_SHUTDOWNED
Definition: pg_control.h:90
@ DB_IN_CRASH_RECOVERY
Definition: pg_control.h:93
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Oid oldestMultiDB
Definition: pg_control.h:50
MultiXactId oldestMulti
Definition: pg_control.h:49
MultiXactOffset nextMultiOffset
Definition: pg_control.h:46
TransactionId newestCommitTsXid
Definition: pg_control.h:54
TransactionId oldestXid
Definition: pg_control.h:47
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
Oid nextOid
Definition: pg_control.h:44
MultiXactId nextMulti
Definition: pg_control.h:45
FullTransactionId nextXid
Definition: pg_control.h:43
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
XLogRecPtr redo
Definition: pg_control.h:37
Oid oldestXidDB
Definition: pg_control.h:48
XLogRecPtr backupStartPoint
Definition: pg_control.h:168
bool backupEndRequired
Definition: pg_control.h:170
CheckPoint checkPointCopy
Definition: pg_control.h:133
XLogRecPtr backupEndPoint
Definition: pg_control.h:169
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
XLogRecPtr checkPoint
Definition: pg_control.h:131
uint64 system_identifier
Definition: pg_control.h:108
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
Definition: pg_list.h:54
uint64 system_identifier
Definition: xlogreader.h:191
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:243
int wal_decode_buffer_size
Definition: xlog.c:139
static ControlFileData * ControlFile
Definition: xlog.c:570
#define TABLESPACE_MAP_OLD
Definition: xlog.h:295
#define TABLESPACE_MAP
Definition: xlog.h:294
#define BACKUP_LABEL_FILE
Definition: xlog.h:291
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogPrefetcher * XLogPrefetcherAllocate(XLogReaderState *reader)
void XLogReaderSetDecodeBuffer(XLogReaderState *state, void *buffer, size_t size)
Definition: xlogreader.c:92
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:108
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
static bool backupEndRequired
Definition: xlogrecovery.c:283
const char * recoveryTargetName
Definition: xlogrecovery.c:91
static XLogRecPtr minRecoveryPoint
Definition: xlogrecovery.c:278
static int XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
static XLogRecPtr backupEndPoint
Definition: xlogrecovery.c:282
static void validateRecoveryParameters(void)
static XLogRecord * ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr, TimeLineID replayTLI)
static TimeLineID RedoStartTLI
Definition: xlogrecovery.c:170
static void readRecoverySignalFile(void)
Definition: xlogrecovery.c:988
XLogRecPtr recoveryTargetLSN
Definition: xlogrecovery.c:92
RecoveryTargetType recoveryTarget
Definition: xlogrecovery.c:85
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:123
static char * primary_image_masked
Definition: xlogrecovery.c:298
static TimeLineID minRecoveryPointTLI
Definition: xlogrecovery.c:279
TransactionId recoveryTargetXid
Definition: xlogrecovery.c:88
static char * replay_image_masked
Definition: xlogrecovery.c:297
TimeLineID recoveryTargetTLI
Definition: xlogrecovery.c:122
static XLogRecPtr RedoStartLSN
Definition: xlogrecovery.c:169
static void EnableStandbyMode(void)
Definition: xlogrecovery.c:478
TimestampTz recoveryTargetTime
Definition: xlogrecovery.c:90
static bool StandbyModeRequested
Definition: xlogrecovery.c:146
static XLogRecPtr backupStartPoint
Definition: xlogrecovery.c:281
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:844

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(), 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, XLogRecPtrIsInvalid, and XLR_INFO_MASK.

Referenced by StartupXLOG().

◆ PerformWalRecovery()

void PerformWalRecovery ( void  )

Definition at line 1585 of file xlogrecovery.c.

1586 {
1587  XLogRecord *record;
1588  bool reachedRecoveryTarget = false;
1589  TimeLineID replayTLI;
1590 
1591  /*
1592  * Initialize shared variables for tracking progress of WAL replay, as if
1593  * we had just replayed the record before the REDO location (or the
1594  * checkpoint record itself, if it's a shutdown checkpoint).
1595  */
1598  {
1602  }
1603  else
1604  {
1608  }
1615 
1616  /* Also ensure XLogReceiptTime has a sane value */
1618 
1619  /*
1620  * Let postmaster know we've started redo now, so that it can launch the
1621  * archiver if necessary.
1622  */
1623  if (IsUnderPostmaster)
1625 
1626  /*
1627  * Allow read-only connections immediately if we're consistent already.
1628  */
1630 
1631  /*
1632  * Find the first record that logically follows the checkpoint --- it
1633  * might physically precede it, though.
1634  */
1636  {
1637  /* back up to find the record */
1638  replayTLI = RedoStartTLI;
1640  record = ReadRecord(xlogprefetcher, PANIC, false, replayTLI);
1641  }
1642  else
1643  {
1644  /* just have to read next record after CheckPoint */
1646  replayTLI = CheckPointTLI;
1647  record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1648  }
1649 
1650  if (record != NULL)
1651  {
1652  TimestampTz xtime;
1653  PGRUsage ru0;
1654 
1655  pg_rusage_init(&ru0);
1656 
1657  InRedo = true;
1658 
1659  RmgrStartup();
1660 
1661  ereport(LOG,
1662  (errmsg("redo starts at %X/%X",
1664 
1665  /* Prepare to report progress of the redo phase. */
1666  if (!StandbyMode)
1668 
1669  /*
1670  * main redo apply loop
1671  */
1672  do
1673  {
1674  if (!StandbyMode)
1675  ereport_startup_progress("redo in progress, elapsed time: %ld.%02d s, current LSN: %X/%X",
1677 
1678 #ifdef WAL_DEBUG
1679  if (XLOG_DEBUG ||
1680  (record->xl_rmid == RM_XACT_ID && trace_recovery_messages <= DEBUG2) ||
1681  (record->xl_rmid != RM_XACT_ID && trace_recovery_messages <= DEBUG3))
1682  {
1684 
1685  initStringInfo(&buf);
1686  appendStringInfo(&buf, "REDO @ %X/%X; LSN %X/%X: ",
1689  xlog_outrec(&buf, xlogreader);
1690  appendStringInfoString(&buf, " - ");
1692  elog(LOG, "%s", buf.data);
1693  pfree(buf.data);
1694  }
1695 #endif
1696 
1697  /* Handle interrupt signals of startup process */
1699 
1700  /*
1701  * Pause WAL replay, if requested by a hot-standby session via
1702  * SetRecoveryPause().
1703  *
1704  * Note that we intentionally don't take the info_lck spinlock
1705  * here. We might therefore read a slightly stale value of the
1706  * recoveryPause flag, but it can't be very stale (no worse than
1707  * the last spinlock we did acquire). Since a pause request is a
1708  * pretty asynchronous thing anyway, possibly responding to it one
1709  * WAL record later than we otherwise would is a minor issue, so
1710  * it doesn't seem worth adding another spinlock cycle to prevent
1711  * that.
1712  */
1713  if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1715  recoveryPausesHere(false);
1716 
1717  /*
1718  * Have we reached our recovery target?
1719  */
1721  {
1722  reachedRecoveryTarget = true;
1723  break;
1724  }
1725 
1726  /*
1727  * If we've been asked to lag the primary, wait on latch until
1728  * enough time has passed.
1729  */
1731  {
1732  /*
1733  * We test for paused recovery again here. If user sets
1734  * delayed apply, it may be because they expect to pause
1735  * recovery in case of problems, so we must test again here
1736  * otherwise pausing during the delay-wait wouldn't work.
1737  */
1738  if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
1740  recoveryPausesHere(false);
1741  }
1742 
1743  /*
1744  * Apply the record
1745  */
1746  ApplyWalRecord(xlogreader, record, &replayTLI);
1747 
1748  /* Exit loop if we reached inclusive recovery target */
1750  {
1751  reachedRecoveryTarget = true;
1752  break;
1753  }
1754 
1755  /* Else, try to fetch the next WAL record */
1756  record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
1757  } while (record != NULL);
1758 
1759  /*
1760  * end of main redo apply loop
1761  */
1762 
1763  if (reachedRecoveryTarget)
1764  {
1765  if (!reachedConsistency)
1766  ereport(FATAL,
1767  (errmsg("requested recovery stop point is before consistent recovery point")));
1768 
1769  /*
1770  * This is the last point where we can restart recovery with a new
1771  * recovery target, if we shutdown and begin again. After this,
1772  * Resource Managers may choose to do permanent corrective actions
1773  * at end of recovery.
1774  */
1775  switch (recoveryTargetAction)
1776  {
1778 
1779  /*
1780  * exit with special return code to request shutdown of
1781  * postmaster. Log messages issued from postmaster.
1782  */
1783  proc_exit(3);
1784 
1786  SetRecoveryPause(true);
1787  recoveryPausesHere(true);
1788 
1789  /* drop into promote */
1790 
1792  break;
1793  }
1794  }
1795 
1796  RmgrCleanup();
1797 
1798  ereport(LOG,
1799  (errmsg("redo done at %X/%X system usage: %s",
1801  pg_rusage_show(&ru0))));
1802  xtime = GetLatestXTime();
1803  if (xtime)
1804  ereport(LOG,
1805  (errmsg("last completed transaction was at log time %s",
1806  timestamptz_to_str(xtime))));
1807 
1808  InRedo = false;
1809  }
1810  else
1811  {
1812  /* there are no WAL records following the checkpoint */
1813  ereport(LOG,
1814  (errmsg("redo is not required")));
1815  }
1816 
1817  /*
1818  * This check is intentionally after the above log messages that indicate
1819  * how far recovery went.
1820  */
1823  !reachedRecoveryTarget)
1824  ereport(FATAL,
1825  (errmsg("recovery ended before configured recovery target was reached")));
1826 }
void HandleStartupProcInterrupts(void)
Definition: startup.c:168
void begin_startup_progress_phase(void)
Definition: startup.c:352
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
#define DEBUG3
Definition: elog.h:28
#define DEBUG2
Definition: elog.h:29
bool IsUnderPostmaster
Definition: globals.c:113
int trace_recovery_messages
Definition: guc_tables.c:520
void proc_exit(int code)
Definition: ipc.c:104
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:67
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:181
@ PMSIGNAL_RECOVERY_STARTED
Definition: pmsignal.h:35
void RmgrStartup(void)
Definition: rmgr.c:49
void RmgrCleanup(void)
Definition: rmgr.c:65
#define ereport_startup_progress(msg,...)
Definition: startup.h:18
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:206
RmgrId xl_rmid
Definition: xlogrecord.h:47
@ RECOVERY_TARGET_ACTION_PAUSE
@ RECOVERY_TARGET_ACTION_PROMOTE
@ RECOVERY_TARGET_ACTION_SHUTDOWN
bool reachedConsistency
Definition: xlogrecovery.c:294
static bool recoveryStopsBefore(XLogReaderState *record)
int recoveryTargetAction
Definition: xlogrecovery.c:87
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:203
static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
static void recoveryPausesHere(bool endOfRecovery)
TimestampTz GetLatestXTime(void)

References appendStringInfo(), appendStringInfoString(), ApplyWalRecord(), ArchiveRecoveryRequested, Assert(), begin_startup_progress_phase(), buf, CheckPointLoc, CheckPointTLI, CheckRecoveryConsistency(), XLogRecoveryCtlData::currentChunkStartTime, DEBUG2, DEBUG3, elog(), XLogReaderState::EndRecPtr, ereport, ereport_startup_progress, errmsg(), FATAL, GetCurrentTimestamp(), GetLatestXTime(), HandleStartupProcInterrupts(), XLogRecoveryCtlData::info_lck, initStringInfo(), InRedo, InvalidXLogRecPtr, IsUnderPostmaster, XLogRecoveryCtlData::lastReplayedEndRecPtr, XLogRecoveryCtlData::lastReplayedReadRecPtr, XLogRecoveryCtlData::lastReplayedTLI, LOG, LSN_FORMAT_ARGS, PANIC, pfree(), pg_rusage_init(), pg_rusage_show(), PMSIGNAL_RECOVERY_STARTED, proc_exit(), 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(), trace_recovery_messages, XLogRecord::xl_rmid, xlog_outdesc(), xlogprefetcher, XLogPrefetcherBeginRead(), xlogreader, XLogReceiptTime, and XLogRecoveryCtl.

Referenced by StartupXLOG().

◆ PromoteIsTriggered()

bool PromoteIsTriggered ( void  )

Definition at line 4310 of file xlogrecovery.c.

4311 {
4312  /*
4313  * We check shared state each time only until a standby promotion is
4314  * triggered. We can't trigger a promotion again, so there's no need to
4315  * keep checking after the shared variable has once been seen true.
4316  */
4318  return true;
4319 
4323 
4324  return LocalPromoteIsTriggered;
4325 }
static bool LocalPromoteIsTriggered
Definition: xlogrecovery.c:182

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

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

◆ RecoveryRequiresIntParameter()

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

Definition at line 4575 of file xlogrecovery.c.

4576 {
4577  if (currValue < minValue)
4578  {
4580  {
4581  bool warned_for_promote = false;
4582 
4583  ereport(WARNING,
4584  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4585  errmsg("hot standby is not possible because of insufficient parameter settings"),
4586  errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4587  param_name,
4588  currValue,
4589  minValue)));
4590 
4591  SetRecoveryPause(true);
4592 
4593  ereport(LOG,
4594  (errmsg("recovery has paused"),
4595  errdetail("If recovery is unpaused, the server will shut down."),
4596  errhint("You can then restart the server after making the necessary configuration changes.")));
4597 
4599  {
4601 
4602  if (CheckForStandbyTrigger())
4603  {
4604  if (!warned_for_promote)
4605  ereport(WARNING,
4606  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4607  errmsg("promotion is not possible because of insufficient parameter settings"),
4608 
4609  /*
4610  * Repeat the detail from above so it's easy to find
4611  * in the log.
4612  */
4613  errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4614  param_name,
4615  currValue,
4616  minValue),
4617  errhint("Restart the server after making the necessary configuration changes.")));
4618  warned_for_promote = true;
4619  }
4620 
4621  /*
4622  * If recovery pause is requested then set it paused. While
4623  * we are in the loop, user might resume and pause again so
4624  * set this every time.
4625  */
4627 
4628  /*
4629  * We wait on a condition variable that will wake us as soon
4630  * as the pause ends, but we use a timeout so we can check the
4631  * above conditions periodically too.
4632  */
4635  }
4637  }
4638 
4639  ereport(FATAL,
4640  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4641  errmsg("recovery aborted because of insufficient parameter settings"),
4642  /* Repeat the detail from above so it's easy to find in the log. */
4643  errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
4644  param_name,
4645  currValue,
4646  minValue),
4647  errhint("You can restart the server after making the necessary configuration changes.")));
4648  }
4649 }
bool ConditionVariableTimedSleep(ConditionVariable *cv, long timeout, uint32 wait_event_info)
void ConditionVariableCancelSleep(void)
#define WARNING
Definition: elog.h:36
ConditionVariable recoveryNotPausedCV
Definition: xlogrecovery.c:359
@ WAIT_EVENT_RECOVERY_PAUSE
Definition: wait_event.h:126
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(), HandleStartupProcInterrupts(), HotStandbyActiveInReplay(), LOG, RECOVERY_NOT_PAUSED, XLogRecoveryCtlData::recoveryNotPausedCV, SetRecoveryPause(), WAIT_EVENT_RECOVERY_PAUSE, WARNING, and XLogRecoveryCtl.

Referenced by CheckRequiredParameterValues().

◆ RemovePromoteSignalFiles()

void RemovePromoteSignalFiles ( void  )

Definition at line 4370 of file xlogrecovery.c.

4371 {
4372  unlink(PROMOTE_SIGNAL_FILE);
4373 }

References PROMOTE_SIGNAL_FILE.

Referenced by CheckForStandbyTrigger(), and PostmasterMain().

◆ SetRecoveryPause()

◆ ShutdownWalRecovery()

void ShutdownWalRecovery ( void  )

Definition at line 1541 of file xlogrecovery.c.

1542 {
1543  char recoveryPath[MAXPGPATH];
1544 
1545  /* Final update of pg_stat_recovery_prefetch. */
1547 
1548  /* Shut down xlogreader */
1549  if (readFile >= 0)
1550  {
1551  close(readFile);
1552  readFile = -1;
1553  }
1556 
1558  {
1559  /*
1560  * Since there might be a partial WAL segment named RECOVERYXLOG, get
1561  * rid of it.
1562  */
1563  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
1564  unlink(recoveryPath); /* ignore any error */
1565 
1566  /* Get rid of any remaining recovered timeline-history file, too */
1567  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
1568  unlink(recoveryPath); /* ignore any error */
1569  }
1570 
1571  /*
1572  * We don't need the latch anymore. It's not strictly necessary to disown
1573  * it, but let's do it for the sake of tidiness.
1574  */
1577 }
void DisownLatch(Latch *latch)
Definition: latch.c:464
#define MAXPGPATH
#define snprintf
Definition: port.h:238
#define XLOGDIR
void XLogPrefetcherComputeStats(XLogPrefetcher *prefetcher)
void XLogPrefetcherFree(XLogPrefetcher *prefetcher)
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:170

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

Referenced by StartupXLOG().

◆ StartupRequestWalReceiverRestart()

void StartupRequestWalReceiverRestart ( void  )

Definition at line 4291 of file xlogrecovery.c.

4292 {
4294  {
4295  ereport(LOG,
4296  (errmsg("WAL receiver process shutdown requested")));
4297 
4298  pendingWalRcvRestart = true;
4299  }
4300 }
bool WalRcvRunning(void)
static bool pendingWalRcvRestart
Definition: xlogrecovery.c:248
static XLogSource currentSource
Definition: xlogrecovery.c:246

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 2213 of file xlogrecovery.c.

2214 {
2215  RmgrData rmgr = GetRmgr(XLogRecGetRmid(record));
2216  uint8 info = XLogRecGetInfo(record);
2217  const char *id;
2218 
2220  appendStringInfoChar(buf, '/');
2221 
2222  id = rmgr.rm_identify(info);
2223  if (id == NULL)
2224  appendStringInfo(buf, "UNKNOWN (%X): ", info & ~XLR_INFO_MASK);
2225  else
2226  appendStringInfo(buf, "%s: ", id);
2227 
2228  rmgr.rm_desc(buf, record);
2229 }
unsigned char uint8
Definition: c.h:488
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
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:410
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:411

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 458 of file xlogrecovery.c.

459 {
460  bool found;
461 
463  ShmemInitStruct("XLOG Recovery Ctl", XLogRecoveryShmemSize(), &found);
464  if (found)
465  return;
466  memset(XLogRecoveryCtl, 0, sizeof(XLogRecoveryCtlData));
467 
471 }
void ConditionVariableInit(ConditionVariable *cv)
void InitSharedLatch(Latch *latch)
Definition: latch.c:405
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
#define SpinLockInit(lock)
Definition: spin.h:60
Size XLogRecoveryShmemSize(void)
Definition: xlogrecovery.c:447

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ XLogRecoveryShmemSize()

Size XLogRecoveryShmemSize ( void  )

Definition at line 447 of file xlogrecovery.c.

448 {
449  Size size;
450 
451  /* XLogRecoveryCtl */
452  size = sizeof(XLogRecoveryCtlData);
453 
454  return size;
455 }
size_t Size
Definition: c.h:589
struct XLogRecoveryCtlData XLogRecoveryCtlData

Referenced by CalculateShmemSize(), and XLogRecoveryShmemInit().

◆ XLogRequestWalReceiverReply()

void XLogRequestWalReceiverReply ( void  )

Definition at line 4403 of file xlogrecovery.c.

4404 {
4406 }
static bool doRequestWalReceiverReply
Definition: xlogrecovery.c:185

References doRequestWalReceiverReply.

Referenced by xact_redo_commit().

Variable Documentation

◆ archiveCleanupCommand

PGDLLIMPORT char* archiveCleanupCommand
extern

Definition at line 84 of file xlogrecovery.c.

Referenced by CreateRestartPoint().

◆ PrimaryConnInfo

PGDLLIMPORT char* PrimaryConnInfo
extern

◆ PrimarySlotName

PGDLLIMPORT char* PrimarySlotName
extern

Definition at line 97 of file xlogrecovery.c.

Referenced by StartupRereadConfig(), and WaitForWALToBecomeAvailable().

◆ reachedConsistency

◆ recovery_min_apply_delay

PGDLLIMPORT int recovery_min_apply_delay
extern

Definition at line 93 of file xlogrecovery.c.

Referenced by recoveryApplyDelay().

◆ recovery_target_time_string

PGDLLIMPORT char* recovery_target_time_string
extern

Definition at line 89 of file xlogrecovery.c.

Referenced by validateRecoveryParameters().

◆ recoveryEndCommand

PGDLLIMPORT char* recoveryEndCommand
extern

Definition at line 83 of file xlogrecovery.c.

Referenced by CleanupAfterArchiveRecovery().

◆ recoveryRestoreCommand

PGDLLIMPORT char* recoveryRestoreCommand
extern

Definition at line 82 of file xlogrecovery.c.

Referenced by RestoreArchivedFile(), and validateRecoveryParameters().

◆ recoveryTarget

◆ recoveryTargetAction

PGDLLIMPORT int recoveryTargetAction
extern

Definition at line 87 of file xlogrecovery.c.

Referenced by PerformWalRecovery(), and validateRecoveryParameters().

◆ recoveryTargetInclusive

PGDLLIMPORT bool recoveryTargetInclusive
extern

Definition at line 86 of file xlogrecovery.c.

Referenced by recoveryStopsAfter(), and recoveryStopsBefore().

◆ recoveryTargetLSN

PGDLLIMPORT XLogRecPtr recoveryTargetLSN
extern

◆ recoveryTargetName

PGDLLIMPORT const char* recoveryTargetName
extern

Definition at line 91 of file xlogrecovery.c.

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

◆ recoveryTargetTime

PGDLLIMPORT TimestampTz recoveryTargetTime
extern

Definition at line 90 of file xlogrecovery.c.

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

◆ recoveryTargetTimeLineGoal

◆ recoveryTargetTLI

◆ recoveryTargetTLIRequested

PGDLLIMPORT TimeLineID recoveryTargetTLIRequested
extern

Definition at line 121 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 98 of file xlogrecovery.c.

Referenced by StartupRereadConfig(), and WaitForWALToBecomeAvailable().