PostgreSQL Source Code  git master
pg_rewind.c File Reference
#include "postgres_fe.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include "access/timeline.h"
#include "access/xlog_internal.h"
#include "catalog/catversion.h"
#include "catalog/pg_control.h"
#include "common/controldata_utils.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/restricted_token.h"
#include "common/string.h"
#include "fe_utils/recovery_gen.h"
#include "fetch.h"
#include "file_ops.h"
#include "filemap.h"
#include "getopt_long.h"
#include "pg_rewind.h"
#include "storage/bufpage.h"
Include dependency graph for pg_rewind.c:

Go to the source code of this file.

Macros

#define MAXCMDLEN   (2 * MAXPGPATH)
 

Functions

static void usage (const char *progname)
 
static void createBackupLabel (XLogRecPtr startpoint, TimeLineID starttli, XLogRecPtr checkpointloc)
 
static void digestControlFile (ControlFileData *ControlFile, char *source, size_t size)
 
static void syncTargetDirectory (void)
 
static void getRestoreCommand (const char *argv0)
 
static void sanityChecks (void)
 
static void findCommonAncestorTimeline (XLogRecPtr *recptr, int *tliIndex)
 
static void ensureCleanShutdown (const char *argv0)
 
static void disconnect_atexit (void)
 
int main (int argc, char **argv)
 
void progress_report (bool finished)
 
static XLogRecPtr MinXLogRecPtr (XLogRecPtr a, XLogRecPtr b)
 
static TimeLineHistoryEntrygetTimelineHistory (ControlFileData *controlFile, int *nentries)
 
static void checkControlFile (ControlFileData *ControlFile)
 

Variables

static ControlFileData ControlFile_target
 
static ControlFileData ControlFile_source
 
const char * progname
 
int WalSegSz
 
char * datadir_target = NULL
 
char * datadir_source = NULL
 
char * connstr_source = NULL
 
char * restore_command = NULL
 
static bool debug = false
 
bool showprogress = false
 
bool dry_run = false
 
bool do_sync = true
 
bool restore_wal = false
 
TimeLineHistoryEntrytargetHistory
 
int targetNentries
 
uint64 fetch_size
 
uint64 fetch_done
 

Macro Definition Documentation

◆ MAXCMDLEN

#define MAXCMDLEN   (2 * MAXPGPATH)

Referenced by ensureCleanShutdown().

Function Documentation

◆ checkControlFile()

static void checkControlFile ( ControlFileData ControlFile)
static

Definition at line 767 of file pg_rewind.c.

References COMP_CRC32C, EQ_CRC32C, FIN_CRC32C, INIT_CRC32C, offsetof, and pg_fatal.

Referenced by digestControlFile().

768 {
769  pg_crc32c crc;
770 
771  /* Calculate CRC */
772  INIT_CRC32C(crc);
773  COMP_CRC32C(crc, (char *) ControlFile, offsetof(ControlFileData, crc));
774  FIN_CRC32C(crc);
775 
776  /* And simply compare it */
777  if (!EQ_CRC32C(crc, ControlFile->crc))
778  pg_fatal("unexpected control file CRC");
779 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define pg_fatal(...)
Definition: pg_rewind.h:41
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
#define offsetof(type, field)
Definition: c.h:668

◆ createBackupLabel()

static void createBackupLabel ( XLogRecPtr  startpoint,
TimeLineID  starttli,
XLogRecPtr  checkpointloc 
)
static

Definition at line 724 of file pg_rewind.c.

References buf, close_target_file(), MAXFNAMELEN, open_target_file(), pg_fatal, snprintf, tm, WalSegSz, write_target_range(), XLByteToSeg, and XLogFileName.

Referenced by main().

725 {
726  XLogSegNo startsegno;
727  time_t stamp_time;
728  char strfbuf[128];
729  char xlogfilename[MAXFNAMELEN];
730  struct tm *tmp;
731  char buf[1000];
732  int len;
733 
734  XLByteToSeg(startpoint, startsegno, WalSegSz);
735  XLogFileName(xlogfilename, starttli, startsegno, WalSegSz);
736 
737  /*
738  * Construct backup label file
739  */
740  stamp_time = time(NULL);
741  tmp = localtime(&stamp_time);
742  strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z", tmp);
743 
744  len = snprintf(buf, sizeof(buf),
745  "START WAL LOCATION: %X/%X (file %s)\n"
746  "CHECKPOINT LOCATION: %X/%X\n"
747  "BACKUP METHOD: pg_rewind\n"
748  "BACKUP FROM: standby\n"
749  "START TIME: %s\n",
750  /* omit LABEL: line */
751  (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename,
752  (uint32) (checkpointloc >> 32), (uint32) checkpointloc,
753  strfbuf);
754  if (len >= sizeof(buf))
755  pg_fatal("backup label buffer too small"); /* shouldn't happen */
756 
757  /* TODO: move old file out of the way, if any. */
758  open_target_file("backup_label", true); /* BACKUP_LABEL_FILE */
759  write_target_range(buf, 0, len);
761 }
void open_target_file(const char *path, bool trunc)
Definition: file_ops.c:42
void write_target_range(char *buf, off_t begin, size_t size)
Definition: file_ops.c:83
#define pg_fatal(...)
Definition: pg_rewind.h:41
static struct pg_tm tm
Definition: localtime.c:102
static char * buf
Definition: pg_test_fsync.c:67
uint64 XLogSegNo
Definition: xlogdefs.h:41
unsigned int uint32
Definition: c.h:374
#define MAXFNAMELEN
int WalSegSz
Definition: pg_rewind.c:52
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
void close_target_file(void)
Definition: file_ops.c:70
#define snprintf
Definition: port.h:193
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ digestControlFile()

static void digestControlFile ( ControlFileData ControlFile,
char *  source,
size_t  size 
)
static

Definition at line 785 of file pg_rewind.c.

References checkControlFile(), IsValidWalSegSize, ngettext, PG_CONTROL_FILE_SIZE, pg_fatal, WalSegSz, and ControlFileData::xlog_seg_size.

Referenced by main().

786 {
787  if (size != PG_CONTROL_FILE_SIZE)
788  pg_fatal("unexpected control file size %d, expected %d",
789  (int) size, PG_CONTROL_FILE_SIZE);
790 
791  memcpy(ControlFile, src, sizeof(ControlFileData));
792 
793  /* set and validate WalSegSz */
794  WalSegSz = ControlFile->xlog_seg_size;
795 
797  pg_fatal(ngettext("WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d byte",
798  "WAL segment size must be a power of two between 1 MB and 1 GB, but the control file specifies %d bytes",
799  WalSegSz),
800  WalSegSz);
801 
802  /* Additional checks on control file */
803  checkControlFile(ControlFile);
804 }
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:94
#define pg_fatal(...)
Definition: pg_rewind.h:41
uint32 xlog_seg_size
Definition: pg_control.h:209
static void checkControlFile(ControlFileData *ControlFile)
Definition: pg_rewind.c:767
int WalSegSz
Definition: pg_rewind.c:52
#define ngettext(s, p, n)
Definition: c.h:1123
#define PG_CONTROL_FILE_SIZE
Definition: pg_control.h:248

◆ disconnect_atexit()

static void disconnect_atexit ( void  )
static

Definition at line 949 of file pg_rewind.c.

References conn, and PQfinish().

Referenced by main().

950 {
951  if (conn != NULL)
952  PQfinish(conn);
953 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4171
PGconn * conn
Definition: streamutil.c:54

◆ ensureCleanShutdown()

static void ensureCleanShutdown ( const char *  argv0)
static

Definition at line 894 of file pg_rewind.c.

References datadir_target, DEVNULL, dry_run, exec_path, find_my_exec(), find_other_exec(), MAXCMDLEN, MAXPGPATH, PG_BACKEND_VERSIONSTR, pg_fatal, pg_log_error, pg_log_info, progname, snprintf, and strlcpy().

Referenced by main().

895 {
896  int ret;
897 #define MAXCMDLEN (2 * MAXPGPATH)
898  char exec_path[MAXPGPATH];
899  char cmd[MAXCMDLEN];
900 
901  /* locate postgres binary */
902  if ((ret = find_other_exec(argv0, "postgres",
904  exec_path)) < 0)
905  {
906  char full_path[MAXPGPATH];
907 
908  if (find_my_exec(argv0, full_path) < 0)
909  strlcpy(full_path, progname, sizeof(full_path));
910 
911  if (ret == -1)
912  pg_fatal("The program \"%s\" is needed by %s but was not found in the\n"
913  "same directory as \"%s\".\n"
914  "Check your installation.",
915  "postgres", progname, full_path);
916  else
917  pg_fatal("The program \"%s\" was found by \"%s\"\n"
918  "but was not the same version as %s.\n"
919  "Check your installation.",
920  "postgres", full_path, progname);
921  }
922 
923  pg_log_info("executing \"%s\" for target server to complete crash recovery",
924  exec_path);
925 
926  /*
927  * Skip processing if requested, but only after ensuring presence of
928  * postgres.
929  */
930  if (dry_run)
931  return;
932 
933  /*
934  * Finally run postgres in single-user mode. There is no need to use
935  * fsync here. This makes the recovery faster, and the target data folder
936  * is synced at the end anyway.
937  */
938  snprintf(cmd, MAXCMDLEN, "\"%s\" --single -F -D \"%s\" template1 < \"%s\"",
939  exec_path, datadir_target, DEVNULL);
940 
941  if (system(cmd) != 0)
942  {
943  pg_log_error("postgres single-user mode in target cluster failed");
944  pg_fatal("Command was: %s", cmd);
945  }
946 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:323
char * datadir_target
Definition: pg_rewind.c:55
static char * argv0
Definition: pg_ctl.c:97
#define MAXCMDLEN
bool dry_run
Definition: pg_rewind.c:62
#define pg_log_error(...)
Definition: logging.h:80
#define pg_fatal(...)
Definition: pg_rewind.h:41
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
#define DEVNULL
Definition: port.h:124
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static char * exec_path
Definition: pg_ctl.c:92
#define snprintf
Definition: port.h:193
#define pg_log_info(...)
Definition: logging.h:88
const char * progname
Definition: pg_rewind.c:51

◆ findCommonAncestorTimeline()

static void findCommonAncestorTimeline ( XLogRecPtr recptr,
int *  tliIndex 
)
static

Definition at line 676 of file pg_rewind.c.

References getTimelineHistory(), i, Min, MinXLogRecPtr(), pg_fatal, pg_free(), and targetNentries.

Referenced by main().

677 {
678  TimeLineHistoryEntry *sourceHistory;
679  int sourceNentries;
680  int i,
681  n;
682 
683  /* Retrieve timelines for both source and target */
684  sourceHistory = getTimelineHistory(&ControlFile_source, &sourceNentries);
686 
687  /*
688  * Trace the history forward, until we hit the timeline diverge. It may
689  * still be possible that the source and target nodes used the same
690  * timeline number in their history but with different start position
691  * depending on the history files that each node has fetched in previous
692  * recovery processes. Hence check the start position of the new timeline
693  * as well and move down by one extra timeline entry if they do not match.
694  */
695  n = Min(sourceNentries, targetNentries);
696  for (i = 0; i < n; i++)
697  {
698  if (sourceHistory[i].tli != targetHistory[i].tli ||
699  sourceHistory[i].begin != targetHistory[i].begin)
700  break;
701  }
702 
703  if (i > 0)
704  {
705  i--;
706  *recptr = MinXLogRecPtr(sourceHistory[i].end, targetHistory[i].end);
707  *tliIndex = i;
708 
709  pg_free(sourceHistory);
710  return;
711  }
712  else
713  {
714  pg_fatal("could not find common ancestor of the source and target cluster's timelines");
715  }
716 }
TimeLineHistoryEntry * targetHistory
Definition: pg_rewind.c:67
#define Min(x, y)
Definition: c.h:927
static XLogRecPtr MinXLogRecPtr(XLogRecPtr a, XLogRecPtr b)
Definition: pg_rewind.c:584
#define pg_fatal(...)
Definition: pg_rewind.h:41
int targetNentries
Definition: pg_rewind.c:68
void pg_free(void *ptr)
Definition: fe_memutils.c:105
static TimeLineHistoryEntry * getTimelineHistory(ControlFileData *controlFile, int *nentries)
Definition: pg_rewind.c:599
int i
static ControlFileData ControlFile_target
Definition: pg_rewind.c:48
static ControlFileData ControlFile_source
Definition: pg_rewind.c:49

◆ getRestoreCommand()

static void getRestoreCommand ( const char *  argv0)
static

Definition at line 831 of file pg_rewind.c.

References datadir_target, find_my_exec(), find_other_exec(), MAXPGPATH, PG_BACKEND_VERSIONSTR, pg_fatal, pg_log_debug, pg_log_error, pg_strdup(), pg_strip_crlf(), pipe_read_line(), progname, restore_command, restore_wal, snprintf, and strlcpy().

Referenced by main().

832 {
833  int rc;
834  char postgres_exec_path[MAXPGPATH],
835  postgres_cmd[MAXPGPATH],
836  cmd_output[MAXPGPATH];
837 
838  if (!restore_wal)
839  return;
840 
841  /* find postgres executable */
842  rc = find_other_exec(argv0, "postgres",
844  postgres_exec_path);
845 
846  if (rc < 0)
847  {
848  char full_path[MAXPGPATH];
849 
850  if (find_my_exec(argv0, full_path) < 0)
851  strlcpy(full_path, progname, sizeof(full_path));
852 
853  if (rc == -1)
854  pg_log_error("The program \"%s\" is needed by %s but was not found in the\n"
855  "same directory as \"%s\".\n"
856  "Check your installation.",
857  "postgres", progname, full_path);
858  else
859  pg_log_error("The program \"%s\" was found by \"%s\"\n"
860  "but was not the same version as %s.\n"
861  "Check your installation.",
862  "postgres", full_path, progname);
863  exit(1);
864  }
865 
866  /*
867  * Build a command able to retrieve the value of GUC parameter
868  * restore_command, if set.
869  */
870  snprintf(postgres_cmd, sizeof(postgres_cmd),
871  "\"%s\" -D \"%s\" -C restore_command",
872  postgres_exec_path, datadir_target);
873 
874  if (!pipe_read_line(postgres_cmd, cmd_output, sizeof(cmd_output)))
875  exit(1);
876 
877  (void) pg_strip_crlf(cmd_output);
878 
879  if (strcmp(cmd_output, "") == 0)
880  pg_fatal("restore_command is not set in the target cluster");
881 
882  restore_command = pg_strdup(cmd_output);
883 
884  pg_log_debug("using for rewind restore_command = \'%s\'",
886 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:323
char * datadir_target
Definition: pg_rewind.c:55
static char * argv0
Definition: pg_ctl.c:97
int pg_strip_crlf(char *str)
Definition: string.c:105
#define pg_log_error(...)
Definition: logging.h:80
#define pg_fatal(...)
Definition: pg_rewind.h:41
bool restore_wal
Definition: pg_rewind.c:64
#define pg_log_debug(...)
Definition: logging.h:92
#define MAXPGPATH
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * restore_command
Definition: pg_rewind.c:58
char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:359
#define snprintf
Definition: port.h:193
const char * progname
Definition: pg_rewind.c:51

◆ getTimelineHistory()

static TimeLineHistoryEntry* getTimelineHistory ( ControlFileData controlFile,
int *  nentries 
)
static

Definition at line 599 of file pg_rewind.c.

References Assert, TimeLineHistoryEntry::begin, ControlFileData::checkPointCopy, datadir_target, debug, TimeLineHistoryEntry::end, fetchFile(), i, InvalidXLogRecPtr, MAXPGPATH, pg_fatal, pg_free(), pg_log_debug, pg_malloc(), rewind_parseTimeLineHistory(), slurpFile(), targetNentries, CheckPoint::ThisTimeLineID, TLHistoryFilePath, and TimeLineHistoryEntry::tli.

Referenced by findCommonAncestorTimeline().

600 {
601  TimeLineHistoryEntry *history;
602  TimeLineID tli;
603 
604  tli = controlFile->checkPointCopy.ThisTimeLineID;
605 
606  /*
607  * Timeline 1 does not have a history file, so there is no need to check
608  * and fake an entry with infinite start and end positions.
609  */
610  if (tli == 1)
611  {
612  history = (TimeLineHistoryEntry *) pg_malloc(sizeof(TimeLineHistoryEntry));
613  history->tli = tli;
614  history->begin = history->end = InvalidXLogRecPtr;
615  *nentries = 1;
616  }
617  else
618  {
619  char path[MAXPGPATH];
620  char *histfile;
621 
622  TLHistoryFilePath(path, tli);
623 
624  /* Get history file from appropriate source */
625  if (controlFile == &ControlFile_source)
626  histfile = fetchFile(path, NULL);
627  else if (controlFile == &ControlFile_target)
628  histfile = slurpFile(datadir_target, path, NULL);
629  else
630  pg_fatal("invalid control file");
631 
632  history = rewind_parseTimeLineHistory(histfile, tli, nentries);
633  pg_free(histfile);
634  }
635 
636  if (debug)
637  {
638  int i;
639 
640  if (controlFile == &ControlFile_source)
641  pg_log_debug("Source timeline history:");
642  else if (controlFile == &ControlFile_target)
643  pg_log_debug("Target timeline history:");
644  else
645  Assert(false);
646 
647  /*
648  * Print the target timeline history.
649  */
650  for (i = 0; i < targetNentries; i++)
651  {
652  TimeLineHistoryEntry *entry;
653 
654  entry = &history[i];
655  pg_log_debug("%d: %X/%X - %X/%X", entry->tli,
656  (uint32) (entry->begin >> 32), (uint32) (entry->begin),
657  (uint32) (entry->end >> 32), (uint32) (entry->end));
658  }
659  }
660 
661  return history;
662 }
char * datadir_target
Definition: pg_rewind.c:55
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:52
static bool debug
Definition: pg_rewind.c:60
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define pg_fatal(...)
Definition: pg_rewind.h:41
TimeLineID tli
Definition: timeline.h:27
CheckPoint checkPointCopy
Definition: pg_control.h:131
char * fetchFile(const char *filename, size_t *filesize)
Definition: fetch.c:54
#define pg_log_debug(...)
Definition: logging.h:92
#define MAXPGPATH
unsigned int uint32
Definition: c.h:374
int targetNentries
Definition: pg_rewind.c:68
XLogRecPtr end
Definition: timeline.h:29
#define Assert(condition)
Definition: c.h:745
void pg_free(void *ptr)
Definition: fe_memutils.c:105
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
XLogRecPtr begin
Definition: timeline.h:28
int i
TimeLineHistoryEntry * rewind_parseTimeLineHistory(char *buffer, TimeLineID targetTLI, int *nentries)
Definition: timeline.c:29
static ControlFileData ControlFile_target
Definition: pg_rewind.c:48
static ControlFileData ControlFile_source
Definition: pg_rewind.c:49
char * slurpFile(const char *datadir, const char *path, size_t *filesize)
Definition: file_ops.c:284
#define TLHistoryFilePath(path, tli)

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 102 of file pg_rewind.c.

References _, calculate_totals(), ControlFileData::checkPoint, ControlFileData::checkPointCopy, conn, connstr_source, createBackupLabel(), datadir_source, datadir_target, DB_IN_ARCHIVE_RECOVERY, DB_SHUTDOWNED, DB_SHUTDOWNED_IN_RECOVERY, debug, digestControlFile(), disconnect_atexit(), do_sync, dry_run, ensureCleanShutdown(), executeFileMap(), extractPageMap(), fetch_done, fetch_size, filemap_t::fetch_size, fetchFile(), fetchSourceFileList(), filemap, filemap_create(), filemap_finalize(), findCommonAncestorTimeline(), findLastCheckpoint(), fprintf, GenerateRecoveryConfig(), get_progname(), get_restricted_token(), GetDataDirectoryCreatePerm(), getopt_long(), getRestoreCommand(), libpqConnect(), libpqGetCurrentXlogInsertLocation(), ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, no_argument, optarg, optind, pg_free(), pg_log_error, pg_log_info, pg_logging_increase_verbosity(), pg_logging_init(), pg_mode_mask, pg_strdup(), PG_TEXTDOMAIN, print_filemap(), process_target_file(), progname, progress_report(), readOneRecord(), required_argument, restore_command, restore_wal, sanityChecks(), set_pglocale_pgservice(), showprogress, slurpFile(), ControlFileData::state, syncTargetDirectory(), targetNentries, CheckPoint::ThisTimeLineID, filemap_t::total_size, traverse_datadir(), update_controlfile(), usage(), writerecoveryconf, and WriteRecoveryConfig().

103 {
104  static struct option long_options[] = {
105  {"help", no_argument, NULL, '?'},
106  {"target-pgdata", required_argument, NULL, 'D'},
107  {"write-recovery-conf", no_argument, NULL, 'R'},
108  {"source-pgdata", required_argument, NULL, 1},
109  {"source-server", required_argument, NULL, 2},
110  {"no-ensure-shutdown", no_argument, NULL, 4},
111  {"version", no_argument, NULL, 'V'},
112  {"restore-target-wal", no_argument, NULL, 'c'},
113  {"dry-run", no_argument, NULL, 'n'},
114  {"no-sync", no_argument, NULL, 'N'},
115  {"progress", no_argument, NULL, 'P'},
116  {"debug", no_argument, NULL, 3},
117  {NULL, 0, NULL, 0}
118  };
119  int option_index;
120  int c;
121  XLogRecPtr divergerec;
122  int lastcommontliIndex;
123  XLogRecPtr chkptrec;
124  TimeLineID chkpttli;
125  XLogRecPtr chkptredo;
126  size_t size;
127  char *buffer;
128  bool no_ensure_shutdown = false;
129  bool rewind_needed;
130  XLogRecPtr endrec;
131  TimeLineID endtli;
132  ControlFileData ControlFile_new;
133  bool writerecoveryconf = false;
134 
135  pg_logging_init(argv[0]);
136  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_rewind"));
137  progname = get_progname(argv[0]);
138 
139  /* Process command-line arguments */
140  if (argc > 1)
141  {
142  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
143  {
144  usage(progname);
145  exit(0);
146  }
147  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
148  {
149  puts("pg_rewind (PostgreSQL) " PG_VERSION);
150  exit(0);
151  }
152  }
153 
154  while ((c = getopt_long(argc, argv, "cD:nNPR", long_options, &option_index)) != -1)
155  {
156  switch (c)
157  {
158  case '?':
159  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
160  exit(1);
161 
162  case 'c':
163  restore_wal = true;
164  break;
165 
166  case 'P':
167  showprogress = true;
168  break;
169 
170  case 'n':
171  dry_run = true;
172  break;
173 
174  case 'N':
175  do_sync = false;
176  break;
177 
178  case 'R':
179  writerecoveryconf = true;
180  break;
181 
182  case 3:
183  debug = true;
185  break;
186 
187  case 'D': /* -D or --target-pgdata */
189  break;
190 
191  case 1: /* --source-pgdata */
193  break;
194 
195  case 2: /* --source-server */
197  break;
198 
199  case 4:
200  no_ensure_shutdown = true;
201  break;
202  }
203  }
204 
205  if (datadir_source == NULL && connstr_source == NULL)
206  {
207  pg_log_error("no source specified (--source-pgdata or --source-server)");
208  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
209  exit(1);
210  }
211 
212  if (datadir_source != NULL && connstr_source != NULL)
213  {
214  pg_log_error("only one of --source-pgdata or --source-server can be specified");
215  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
216  exit(1);
217  }
218 
219  if (datadir_target == NULL)
220  {
221  pg_log_error("no target data directory specified (--target-pgdata)");
222  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
223  exit(1);
224  }
225 
226  if (writerecoveryconf && connstr_source == NULL)
227  {
228  pg_log_error("no source server information (--source-server) specified for --write-recovery-conf");
229  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
230  exit(1);
231  }
232 
233  if (optind < argc)
234  {
235  pg_log_error("too many command-line arguments (first is \"%s\")",
236  argv[optind]);
237  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
238  exit(1);
239  }
240 
241  /*
242  * Don't allow pg_rewind to be run as root, to avoid overwriting the
243  * ownership of files in the data directory. We need only check for root
244  * -- any other user won't have sufficient permissions to modify files in
245  * the data directory.
246  */
247 #ifndef WIN32
248  if (geteuid() == 0)
249  {
250  pg_log_error("cannot be executed by \"root\"");
251  fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
252  progname);
253  exit(1);
254  }
255 #endif
256 
258 
259  /* Set mask based on PGDATA permissions */
261  {
262  pg_log_error("could not read permissions of directory \"%s\": %m",
264  exit(1);
265  }
266 
267  umask(pg_mode_mask);
268 
269  getRestoreCommand(argv[0]);
270 
271  atexit(disconnect_atexit);
272 
273  /* Connect to remote server */
274  if (connstr_source)
276 
277  /*
278  * Ok, we have all the options and we're ready to start. Read in all the
279  * information we need from both clusters.
280  */
281  buffer = slurpFile(datadir_target, "global/pg_control", &size);
282  digestControlFile(&ControlFile_target, buffer, size);
283  pg_free(buffer);
284 
285  /*
286  * If the target instance was not cleanly shut down, start and stop the
287  * target cluster once in single-user mode to enforce recovery to finish,
288  * ensuring that the cluster can be used by pg_rewind. Note that if
289  * no_ensure_shutdown is specified, pg_rewind ignores this step, and users
290  * need to make sure by themselves that the target cluster is in a clean
291  * state.
292  */
293  if (!no_ensure_shutdown &&
296  {
297  ensureCleanShutdown(argv[0]);
298 
299  buffer = slurpFile(datadir_target, "global/pg_control", &size);
300  digestControlFile(&ControlFile_target, buffer, size);
301  pg_free(buffer);
302  }
303 
304  buffer = fetchFile("global/pg_control", &size);
305  digestControlFile(&ControlFile_source, buffer, size);
306  pg_free(buffer);
307 
308  sanityChecks();
309 
310  /*
311  * If both clusters are already on the same timeline, there's nothing to
312  * do.
313  */
315  {
316  pg_log_info("source and target cluster are on the same timeline");
317  rewind_needed = false;
318  }
319  else
320  {
321  findCommonAncestorTimeline(&divergerec, &lastcommontliIndex);
322  pg_log_info("servers diverged at WAL location %X/%X on timeline %u",
323  (uint32) (divergerec >> 32), (uint32) divergerec,
324  targetHistory[lastcommontliIndex].tli);
325 
326  /*
327  * Check for the possibility that the target is in fact a direct
328  * ancestor of the source. In that case, there is no divergent history
329  * in the target that needs rewinding.
330  */
331  if (ControlFile_target.checkPoint >= divergerec)
332  {
333  rewind_needed = true;
334  }
335  else
336  {
337  XLogRecPtr chkptendrec;
338 
339  /* Read the checkpoint record on the target to see where it ends. */
340  chkptendrec = readOneRecord(datadir_target,
342  targetNentries - 1,
344 
345  /*
346  * If the histories diverged exactly at the end of the shutdown
347  * checkpoint record on the target, there are no WAL records in
348  * the target that don't belong in the source's history, and no
349  * rewind is needed.
350  */
351  if (chkptendrec == divergerec)
352  rewind_needed = false;
353  else
354  rewind_needed = true;
355  }
356  }
357 
358  if (!rewind_needed)
359  {
360  pg_log_info("no rewind required");
361  if (writerecoveryconf && !dry_run)
364  exit(0);
365  }
366 
367  findLastCheckpoint(datadir_target, divergerec, lastcommontliIndex,
368  &chkptrec, &chkpttli, &chkptredo, restore_command);
369  pg_log_info("rewinding from last common checkpoint at %X/%X on timeline %u",
370  (uint32) (chkptrec >> 32), (uint32) chkptrec,
371  chkpttli);
372 
373  /*
374  * Build the filemap, by comparing the source and target data directories.
375  */
376  filemap_create();
377  if (showprogress)
378  pg_log_info("reading source file list");
380  if (showprogress)
381  pg_log_info("reading target file list");
383 
384  /*
385  * Read the target WAL from last checkpoint before the point of fork, to
386  * extract all the pages that were modified on the target cluster after
387  * the fork. We can stop reading after reaching the final shutdown record.
388  * XXX: If we supported rewinding a server that was not shut down cleanly,
389  * we would need to replay until the end of WAL here.
390  */
391  if (showprogress)
392  pg_log_info("reading WAL in target");
393  extractPageMap(datadir_target, chkptrec, lastcommontliIndex,
396 
397  if (showprogress)
399 
400  /* this is too verbose even for verbose mode */
401  if (debug)
402  print_filemap();
403 
404  /*
405  * Ok, we're ready to start copying things over.
406  */
407  if (showprogress)
408  {
409  pg_log_info("need to copy %lu MB (total source directory size is %lu MB)",
410  (unsigned long) (filemap->fetch_size / (1024 * 1024)),
411  (unsigned long) (filemap->total_size / (1024 * 1024)));
412 
414  fetch_done = 0;
415  }
416 
417  /*
418  * This is the point of no return. Once we start copying things, we have
419  * modified the target directory and there is no turning back!
420  */
421 
422  executeFileMap();
423 
424  progress_report(true);
425 
426  if (showprogress)
427  pg_log_info("creating backup label and updating control file");
428  createBackupLabel(chkptredo, chkpttli, chkptrec);
429 
430  /*
431  * Update control file of target. Make it ready to perform archive
432  * recovery when restarting.
433  *
434  * minRecoveryPoint is set to the current WAL insert location in the
435  * source server. Like in an online backup, it's important that we recover
436  * all the WAL that was generated while we copied the files over.
437  */
438  memcpy(&ControlFile_new, &ControlFile_source, sizeof(ControlFileData));
439 
440  if (connstr_source)
441  {
444  }
445  else
446  {
449  }
450  ControlFile_new.minRecoveryPoint = endrec;
451  ControlFile_new.minRecoveryPointTLI = endtli;
452  ControlFile_new.state = DB_IN_ARCHIVE_RECOVERY;
453  if (!dry_run)
454  update_controlfile(datadir_target, &ControlFile_new, do_sync);
455 
456  if (showprogress)
457  pg_log_info("syncing target data directory");
459 
460  if (writerecoveryconf && !dry_run)
463 
464  pg_log_info("Done!");
465 
466  return 0;
467 }
void extractPageMap(const char *datadir, XLogRecPtr startpoint, int tliIndex, XLogRecPtr endpoint, const char *restoreCommand)
Definition: parsexlog.c:60
void calculate_totals(void)
Definition: filemap.c:621
static void syncTargetDirectory(void)
Definition: pg_rewind.c:816
char * datadir_target
Definition: pg_rewind.c:55
uint32 TimeLineID
Definition: xlogdefs.h:52
static bool debug
Definition: pg_rewind.c:60
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
TimeLineHistoryEntry * targetHistory
Definition: pg_rewind.c:67
bool dry_run
Definition: pg_rewind.c:62
const char * get_progname(const char *argv0)
Definition: path.c:453
void process_target_file(const char *path, file_type_t type, size_t oldsize, const char *link_target)
Definition: filemap.c:348
#define pg_log_error(...)
Definition: logging.h:80
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
void get_restricted_token(void)
void pg_logging_init(const char *argv0)
Definition: logging.c:81
void WriteRecoveryConfig(PGconn *pgconn, char *target_dir, PQExpBuffer contents)
Definition: recovery_gen.c:117
static void ensureCleanShutdown(const char *argv0)
Definition: pg_rewind.c:894
static bool writerecoveryconf
void findLastCheckpoint(const char *datadir, XLogRecPtr forkptr, int tliIndex, XLogRecPtr *lastchkptrec, TimeLineID *lastchkpttli, XLogRecPtr *lastchkptredo, const char *restoreCommand)
Definition: parsexlog.c:155
CheckPoint checkPointCopy
Definition: pg_control.h:131
void fetchSourceFileList(void)
Definition: fetch.c:28
void filemap_create(void)
Definition: filemap.c:135
#define fprintf
Definition: port.h:197
char * fetchFile(const char *filename, size_t *filesize)
Definition: fetch.c:54
void filemap_finalize(void)
Definition: filemap.c:585
void executeFileMap(void)
Definition: fetch.c:40
uint64 fetch_size
Definition: filemap.h:86
bool showprogress
Definition: pg_rewind.c:61
void update_controlfile(const char *DataDir, ControlFileData *ControlFile, bool do_sync)
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:50
bool restore_wal
Definition: pg_rewind.c:64
uint64 fetch_size
Definition: pg_rewind.c:71
PGconn * conn
Definition: streamutil.c:54
XLogRecPtr libpqGetCurrentXlogInsertLocation(void)
Definition: libpq_fetch.c:147
char * c
static void usage(const char *progname)
Definition: pg_rewind.c:76
filemap_t * filemap
Definition: filemap.c:23
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
uint64 total_size
Definition: filemap.h:85
unsigned int uint32
Definition: c.h:374
void print_filemap(void)
Definition: filemap.c:663
static void findCommonAncestorTimeline(XLogRecPtr *recptr, int *tliIndex)
Definition: pg_rewind.c:676
void traverse_datadir(const char *datadir, process_file_callback_t callback)
Definition: copy_fetch.c:33
PQExpBuffer GenerateRecoveryConfig(PGconn *pgconn, char *replication_slot)
Definition: recovery_gen.c:23
char * connstr_source
Definition: pg_rewind.c:57
#define no_argument
Definition: getopt_long.h:24
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1155
static void disconnect_atexit(void)
Definition: pg_rewind.c:949
int targetNentries
Definition: pg_rewind.c:68
char * datadir_source
Definition: pg_rewind.c:56
bool do_sync
Definition: pg_rewind.c:63
char * restore_command
Definition: pg_rewind.c:58
uint64 XLogRecPtr
Definition: xlogdefs.h:21
void pg_logging_increase_verbosity(void)
Definition: logging.c:174
XLogRecPtr readOneRecord(const char *datadir, XLogRecPtr ptr, int tliIndex, const char *restoreCommand)
Definition: parsexlog.c:111
void progress_report(bool finished)
Definition: pg_rewind.c:528
void pg_free(void *ptr)
Definition: fe_memutils.c:105
static void getRestoreCommand(const char *argv0)
Definition: pg_rewind.c:831
static void sanityChecks(void)
Definition: pg_rewind.c:470
bool GetDataDirectoryCreatePerm(const char *dataDir)
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:434
char * optarg
Definition: getopt.c:52
static ControlFileData ControlFile_target
Definition: pg_rewind.c:48
uint64 fetch_done
Definition: pg_rewind.c:72
static ControlFileData ControlFile_source
Definition: pg_rewind.c:49
static void createBackupLabel(XLogRecPtr startpoint, TimeLineID starttli, XLogRecPtr checkpointloc)
Definition: pg_rewind.c:724
static void digestControlFile(ControlFileData *ControlFile, char *source, size_t size)
Definition: pg_rewind.c:785
#define _(x)
Definition: elog.c:88
int pg_mode_mask
Definition: file_perm.c:25
XLogRecPtr checkPoint
Definition: pg_control.h:129
#define pg_log_info(...)
Definition: logging.h:88
const char * progname
Definition: pg_rewind.c:51
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
void libpqConnect(const char *connstr)
Definition: libpq_fetch.c:43
char * slurpFile(const char *datadir, const char *path, size_t *filesize)
Definition: file_ops.c:284

◆ MinXLogRecPtr()

static XLogRecPtr MinXLogRecPtr ( XLogRecPtr  a,
XLogRecPtr  b 
)
static

Definition at line 584 of file pg_rewind.c.

References Min, and XLogRecPtrIsInvalid.

Referenced by findCommonAncestorTimeline().

585 {
586  if (XLogRecPtrIsInvalid(a))
587  return b;
588  else if (XLogRecPtrIsInvalid(b))
589  return a;
590  else
591  return Min(a, b);
592 }
#define Min(x, y)
Definition: c.h:927
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29

◆ progress_report()

void progress_report ( bool  finished)

Definition at line 528 of file pg_rewind.c.

References _, fetch_done, fetch_size, fprintf, INT64_FORMAT, last_progress_report, now(), showprogress, and snprintf.

Referenced by main().

529 {
530  static pg_time_t last_progress_report = 0;
531  int percent;
532  char fetch_done_str[32];
533  char fetch_size_str[32];
534  pg_time_t now;
535 
536  if (!showprogress)
537  return;
538 
539  now = time(NULL);
540  if (now == last_progress_report && !finished)
541  return; /* Max once per second */
542 
543  last_progress_report = now;
544  percent = fetch_size ? (int) ((fetch_done) * 100 / fetch_size) : 0;
545 
546  /*
547  * Avoid overflowing past 100% or the full size. This may make the total
548  * size number change as we approach the end of the backup (the estimate
549  * will always be wrong if WAL is included), but that's better than having
550  * the done column be bigger than the total.
551  */
552  if (percent > 100)
553  percent = 100;
554  if (fetch_done > fetch_size)
556 
557  /*
558  * Separate step to keep platform-dependent format code out of
559  * translatable strings. And we only test for INT64_FORMAT availability
560  * in snprintf, not fprintf.
561  */
562  snprintf(fetch_done_str, sizeof(fetch_done_str), INT64_FORMAT,
563  fetch_done / 1024);
564  snprintf(fetch_size_str, sizeof(fetch_size_str), INT64_FORMAT,
565  fetch_size / 1024);
566 
567  fprintf(stderr, _("%*s/%s kB (%d%%) copied"),
568  (int) strlen(fetch_size_str), fetch_done_str, fetch_size_str,
569  percent);
570 
571  /*
572  * Stay on the same line if reporting to a terminal and we're not done
573  * yet.
574  */
575  fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
576 }
int64 pg_time_t
Definition: pgtime.h:23
static pg_time_t last_progress_report
#define fprintf
Definition: port.h:197
bool showprogress
Definition: pg_rewind.c:61
uint64 fetch_size
Definition: pg_rewind.c:71
#define INT64_FORMAT
Definition: c.h:416
uint64 fetch_done
Definition: pg_rewind.c:72
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538

◆ sanityChecks()

static void sanityChecks ( void  )
static

Definition at line 470 of file pg_rewind.c.

References CATALOG_VERSION_NO, ControlFileData::catalog_version_no, ControlFileData::data_checksum_version, datadir_source, DB_SHUTDOWNED, DB_SHUTDOWNED_IN_RECOVERY, PG_CONTROL_VERSION, ControlFileData::pg_control_version, PG_DATA_CHECKSUM_VERSION, pg_fatal, ControlFileData::state, ControlFileData::system_identifier, and ControlFileData::wal_log_hints.

Referenced by main().

471 {
472  /* TODO Check that there's no backup_label in either cluster */
473 
474  /* Check system_identifier match */
476  pg_fatal("source and target clusters are from different systems");
477 
478  /* check version */
483  {
484  pg_fatal("clusters are not compatible with this version of pg_rewind");
485  }
486 
487  /*
488  * Target cluster need to use checksums or hint bit wal-logging, this to
489  * prevent from data corruption that could occur because of hint bits.
490  */
493  {
494  pg_fatal("target server needs to use either data checksums or \"wal_log_hints = on\"");
495  }
496 
497  /*
498  * Target cluster better not be running. This doesn't guard against
499  * someone starting the cluster concurrently. Also, this is probably more
500  * strict than necessary; it's OK if the target node was not shut down
501  * cleanly, as long as it isn't running at the moment.
502  */
505  pg_fatal("target server must be shut down cleanly");
506 
507  /*
508  * When the source is a data directory, also require that the source
509  * server is shut down. There isn't any very strong reason for this
510  * limitation, but better safe than sorry.
511  */
512  if (datadir_source &&
515  pg_fatal("source data directory must be shut down cleanly");
516 }
#define pg_fatal(...)
Definition: pg_rewind.h:41
#define CATALOG_VERSION_NO
Definition: catversion.h:56
#define PG_CONTROL_VERSION
Definition: pg_control.h:25
uint32 pg_control_version
Definition: pg_control.h:121
uint64 system_identifier
Definition: pg_control.h:106
uint32 data_checksum_version
Definition: pg_control.h:220
char * datadir_source
Definition: pg_rewind.c:56
uint32 catalog_version_no
Definition: pg_control.h:122
#define PG_DATA_CHECKSUM_VERSION
Definition: bufpage.h:200
static ControlFileData ControlFile_target
Definition: pg_rewind.c:48
static ControlFileData ControlFile_source
Definition: pg_rewind.c:49

◆ syncTargetDirectory()

static void syncTargetDirectory ( void  )
static

Definition at line 816 of file pg_rewind.c.

References datadir_target, do_sync, and dry_run.

Referenced by main().

817 {
818  if (!do_sync || dry_run)
819  return;
820 
821  fsync_pgdata(datadir_target, PG_VERSION_NUM);
822 }
char * datadir_target
Definition: pg_rewind.c:55
bool dry_run
Definition: pg_rewind.c:62
bool do_sync
Definition: pg_rewind.c:63

◆ usage()

static void usage ( const char *  progname)
static

Definition at line 76 of file pg_rewind.c.

References _, and printf.

Referenced by main().

77 {
78  printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
79  printf(_("Usage:\n %s [OPTION]...\n\n"), progname);
80  printf(_("Options:\n"));
81  printf(_(" -c, --restore-target-wal use restore_command in target configuration to\n"
82  " retrieve WAL files from archives\n"));
83  printf(_(" -D, --target-pgdata=DIRECTORY existing data directory to modify\n"));
84  printf(_(" --source-pgdata=DIRECTORY source data directory to synchronize with\n"));
85  printf(_(" --source-server=CONNSTR source server to synchronize with\n"));
86  printf(_(" -n, --dry-run stop before modifying anything\n"));
87  printf(_(" -N, --no-sync do not wait for changes to be written\n"
88  " safely to disk\n"));
89  printf(_(" -P, --progress write progress messages\n"));
90  printf(_(" -R, --write-recovery-conf write configuration for replication\n"
91  " (requires --source-server)\n"));
92  printf(_(" --debug write a lot of debug messages\n"));
93  printf(_(" --no-ensure-shutdown do not automatically fix unclean shutdown\n"));
94  printf(_(" -V, --version output version information, then exit\n"));
95  printf(_(" -?, --help show this help, then exit\n"));
96  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
97  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
98 }
#define printf(...)
Definition: port.h:199
#define _(x)
Definition: elog.c:88
const char * progname
Definition: pg_rewind.c:51

Variable Documentation

◆ connstr_source

char* connstr_source = NULL

Definition at line 57 of file pg_rewind.c.

Referenced by main().

◆ ControlFile_source

ControlFileData ControlFile_source
static

Definition at line 49 of file pg_rewind.c.

◆ ControlFile_target

ControlFileData ControlFile_target
static

Definition at line 48 of file pg_rewind.c.

◆ datadir_source

char* datadir_source = NULL

◆ datadir_target

◆ debug

bool debug = false
static

Definition at line 60 of file pg_rewind.c.

Referenced by getTimelineHistory(), and main().

◆ do_sync

bool do_sync = true

Definition at line 63 of file pg_rewind.c.

Referenced by main(), and syncTargetDirectory().

◆ dry_run

◆ fetch_done

uint64 fetch_done

Definition at line 72 of file pg_rewind.c.

Referenced by main(), progress_report(), and write_target_range().

◆ fetch_size

uint64 fetch_size

Definition at line 71 of file pg_rewind.c.

Referenced by main(), postgres_fdw_validator(), and progress_report().

◆ progname

const char* progname

Definition at line 51 of file pg_rewind.c.

Referenced by ensureCleanShutdown(), getRestoreCommand(), and main().

◆ restore_command

char* restore_command = NULL

Definition at line 58 of file pg_rewind.c.

Referenced by getRestoreCommand(), and main().

◆ restore_wal

bool restore_wal = false

Definition at line 64 of file pg_rewind.c.

Referenced by getRestoreCommand(), and main().

◆ showprogress

bool showprogress = false

Definition at line 61 of file pg_rewind.c.

Referenced by main(), and progress_report().

◆ targetHistory

TimeLineHistoryEntry* targetHistory

Definition at line 67 of file pg_rewind.c.

Referenced by SimpleXLogPageRead().

◆ targetNentries

int targetNentries

◆ WalSegSz

int WalSegSz

Definition at line 52 of file pg_rewind.c.

Referenced by createBackupLabel(), and digestControlFile().