PostgreSQL Source Code  git master
pg_rewind.h File Reference
#include "access/timeline.h"
#include "common/logging.h"
#include "datapagemap.h"
#include "libpq-fe.h"
#include "storage/block.h"
#include "storage/relfilenode.h"
Include dependency graph for pg_rewind.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define pg_fatal(...)   do { pg_log_fatal(__VA_ARGS__); exit(1); } while(0)
 

Functions

void extractPageMap (const char *datadir, XLogRecPtr startpoint, int tliIndex, XLogRecPtr endpoint)
 
void findLastCheckpoint (const char *datadir, XLogRecPtr searchptr, int tliIndex, XLogRecPtr *lastchkptrec, TimeLineID *lastchkpttli, XLogRecPtr *lastchkptredo)
 
XLogRecPtr readOneRecord (const char *datadir, XLogRecPtr ptr, int tliIndex)
 
void progress_report (bool force)
 
TimeLineHistoryEntryrewind_parseTimeLineHistory (char *buffer, TimeLineID targetTLI, int *nentries)
 

Variables

char * datadir_target
 
char * datadir_source
 
char * connstr_source
 
bool showprogress
 
bool dry_run
 
int WalSegSz
 
TimeLineHistoryEntrytargetHistory
 
int targetNentries
 
PGconnconn
 
uint64 fetch_size
 
uint64 fetch_done
 

Macro Definition Documentation

◆ pg_fatal

#define pg_fatal (   ...)    do { pg_log_fatal(__VA_ARGS__); exit(1); } while(0)

Definition at line 41 of file pg_rewind.h.

Referenced by adjust_data_dir(), check_cluster_compatibility(), check_cluster_versions(), check_control_data(), check_file_clone(), check_for_data_type_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_hard_link(), check_is_install_user(), check_loadable_libraries(), check_locale_and_encoding(), check_new_cluster_is_empty(), check_pghost_envvar(), check_proper_datallowconn(), check_required_directory(), checkControlFile(), cloneFile(), close_target_file(), copyFile(), create_script_for_cluster_analyze(), create_script_for_old_cluster_deletion(), create_target(), create_target_dir(), create_target_symlink(), createBackupLabel(), digestControlFile(), disable_old_cluster(), ensureCleanShutdown(), exec_prog(), extractPageInfo(), extractPageMap(), fetch_file_range(), findCommonAncestorTimeline(), findLastCheckpoint(), gen_db_file_maps(), get_bin_version(), get_canonical_locale_name(), get_control_data(), get_loadable_libraries(), get_major_server_version(), get_sock_dir(), getTimelineHistory(), init_tablespaces(), libpq_executeFileMap(), libpqConnect(), libpqGetCurrentXlogInsertLocation(), libpqGetFile(), libpqProcessFileList(), linkFile(), main(), new_9_0_populate_pg_largeobject_metadata(), old_11_check_for_sql_identifier_data_type_usage(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), open_target_file(), parallel_exec_prog(), parallel_transfer_all_new_dbs(), parseCommandLine(), pid_lock_file_exists(), process_block_change(), process_source_file(), process_target_file(), readOneRecord(), reap_child(), receiveFileChunks(), recurse_dir(), remove_new_subdir(), remove_target_dir(), remove_target_file(), remove_target_symlink(), rewind_copy_file_range(), rewriteVisibilityMap(), run_simple_command(), run_simple_query(), sanityChecks(), setup(), slurpFile(), start_postmaster(), transfer_all_new_dbs(), transfer_relfile(), truncate_target_file(), validate_exec(), verify_directories(), and write_target_range().

Function Documentation

◆ extractPageMap()

void extractPageMap ( const char *  datadir,
XLogRecPtr  startpoint,
int  tliIndex,
XLogRecPtr  endpoint 
)

Definition at line 57 of file parsexlog.c.

References close, XLogReaderState::EndRecPtr, extractPageInfo(), InvalidXLogRecPtr, pg_fatal, XLogReaderState::ReadRecPtr, SimpleXLogPageRead(), XLogPageReadPrivate::tliIndex, WalSegSz, XLogReaderAllocate(), XLogReaderFree(), xlogreadfd, and XLogReadRecord().

Referenced by main().

59 {
60  XLogRecord *record;
61  XLogReaderState *xlogreader;
62  char *errormsg;
63  XLogPageReadPrivate private;
64 
65  private.tliIndex = tliIndex;
67  &private);
68  if (xlogreader == NULL)
69  pg_fatal("out of memory");
70 
71  do
72  {
73  record = XLogReadRecord(xlogreader, startpoint, &errormsg);
74 
75  if (record == NULL)
76  {
77  XLogRecPtr errptr;
78 
79  errptr = startpoint ? startpoint : xlogreader->EndRecPtr;
80 
81  if (errormsg)
82  pg_fatal("could not read WAL record at %X/%X: %s",
83  (uint32) (errptr >> 32), (uint32) (errptr),
84  errormsg);
85  else
86  pg_fatal("could not read WAL record at %X/%X",
87  (uint32) (errptr >> 32), (uint32) (errptr));
88  }
89 
90  extractPageInfo(xlogreader);
91 
92  startpoint = InvalidXLogRecPtr; /* continue reading at next record */
93 
94  } while (xlogreader->ReadRecPtr != endpoint);
95 
96  XLogReaderFree(xlogreader);
97  if (xlogreadfd != -1)
98  {
100  xlogreadfd = -1;
101  }
102 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define pg_fatal(...)
Definition: pg_rewind.h:41
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:232
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:238
XLogRecPtr EndRecPtr
Definition: xlogreader.h:132
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:131
char * datadir
unsigned int uint32
Definition: c.h:359
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
static int xlogreadfd
Definition: parsexlog.c:38
static void extractPageInfo(XLogReaderState *record)
Definition: parsexlog.c:325
uint64 XLogRecPtr
Definition: xlogdefs.h:21
int WalSegSz
Definition: pg_standby.c:38
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
#define close(a)
Definition: win32.h:12

◆ findLastCheckpoint()

void findLastCheckpoint ( const char *  datadir,
XLogRecPtr  searchptr,
int  tliIndex,
XLogRecPtr lastchkptrec,
TimeLineID lastchkpttli,
XLogRecPtr lastchkptredo 
)

Definition at line 149 of file parsexlog.c.

References close, pg_fatal, CheckPoint::redo, SimpleXLogPageRead(), SizeOfXLogLongPHD, SizeOfXLogShortPHD, CheckPoint::ThisTimeLineID, XLogPageReadPrivate::tliIndex, WalSegSz, XLogRecord::xl_prev, XLOG_CHECKPOINT_ONLINE, XLOG_CHECKPOINT_SHUTDOWN, XLogReaderAllocate(), XLogReaderFree(), xlogreadfd, XLogReadRecord(), XLogRecGetData, XLogRecGetInfo, XLogRecGetRmid, XLogSegmentOffset, and XLR_INFO_MASK.

Referenced by main().

152 {
153  /* Walk backwards, starting from the given record */
154  XLogRecord *record;
155  XLogRecPtr searchptr;
156  XLogReaderState *xlogreader;
157  char *errormsg;
158  XLogPageReadPrivate private;
159 
160  /*
161  * The given fork pointer points to the end of the last common record,
162  * which is not necessarily the beginning of the next record, if the
163  * previous record happens to end at a page boundary. Skip over the page
164  * header in that case to find the next record.
165  */
166  if (forkptr % XLOG_BLCKSZ == 0)
167  {
168  if (XLogSegmentOffset(forkptr, WalSegSz) == 0)
169  forkptr += SizeOfXLogLongPHD;
170  else
171  forkptr += SizeOfXLogShortPHD;
172  }
173 
174  private.tliIndex = tliIndex;
176  &private);
177  if (xlogreader == NULL)
178  pg_fatal("out of memory");
179 
180  searchptr = forkptr;
181  for (;;)
182  {
183  uint8 info;
184 
185  record = XLogReadRecord(xlogreader, searchptr, &errormsg);
186 
187  if (record == NULL)
188  {
189  if (errormsg)
190  pg_fatal("could not find previous WAL record at %X/%X: %s",
191  (uint32) (searchptr >> 32), (uint32) (searchptr),
192  errormsg);
193  else
194  pg_fatal("could not find previous WAL record at %X/%X",
195  (uint32) (searchptr >> 32), (uint32) (searchptr));
196  }
197 
198  /*
199  * Check if it is a checkpoint record. This checkpoint record needs to
200  * be the latest checkpoint before WAL forked and not the checkpoint
201  * where the master has been stopped to be rewinded.
202  */
203  info = XLogRecGetInfo(xlogreader) & ~XLR_INFO_MASK;
204  if (searchptr < forkptr &&
205  XLogRecGetRmid(xlogreader) == RM_XLOG_ID &&
206  (info == XLOG_CHECKPOINT_SHUTDOWN ||
207  info == XLOG_CHECKPOINT_ONLINE))
208  {
209  CheckPoint checkPoint;
210 
211  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
212  *lastchkptrec = searchptr;
213  *lastchkpttli = checkPoint.ThisTimeLineID;
214  *lastchkptredo = checkPoint.redo;
215  break;
216  }
217 
218  /* Walk backwards to previous record. */
219  searchptr = record->xl_prev;
220  }
221 
222  XLogReaderFree(xlogreader);
223  if (xlogreadfd != -1)
224  {
225  close(xlogreadfd);
226  xlogreadfd = -1;
227  }
228 }
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
unsigned char uint8
Definition: c.h:357
#define pg_fatal(...)
Definition: pg_rewind.h:41
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:232
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:238
#define XLogRecGetData(decoder)
Definition: xlogreader.h:283
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
char * datadir
unsigned int uint32
Definition: c.h:359
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:279
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
static int xlogreadfd
Definition: parsexlog.c:38
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:55
int WalSegSz
Definition: pg_standby.c:38
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
#define close(a)
Definition: win32.h:12
XLogRecPtr redo
Definition: pg_control.h:37
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:280
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72

◆ progress_report()

void progress_report ( bool  force)

Definition at line 512 of file pg_rewind.c.

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

Referenced by main().

513 {
514  static pg_time_t last_progress_report = 0;
515  int percent;
516  char fetch_done_str[32];
517  char fetch_size_str[32];
518  pg_time_t now;
519 
520  if (!showprogress)
521  return;
522 
523  now = time(NULL);
524  if (now == last_progress_report && !force)
525  return; /* Max once per second */
526 
527  last_progress_report = now;
528  percent = fetch_size ? (int) ((fetch_done) * 100 / fetch_size) : 0;
529 
530  /*
531  * Avoid overflowing past 100% or the full size. This may make the total
532  * size number change as we approach the end of the backup (the estimate
533  * will always be wrong if WAL is included), but that's better than having
534  * the done column be bigger than the total.
535  */
536  if (percent > 100)
537  percent = 100;
538  if (fetch_done > fetch_size)
540 
541  /*
542  * Separate step to keep platform-dependent format code out of
543  * translatable strings. And we only test for INT64_FORMAT availability
544  * in snprintf, not fprintf.
545  */
546  snprintf(fetch_done_str, sizeof(fetch_done_str), INT64_FORMAT,
547  fetch_done / 1024);
548  snprintf(fetch_size_str, sizeof(fetch_size_str), INT64_FORMAT,
549  fetch_size / 1024);
550 
551  fprintf(stderr, _("%*s/%s kB (%d%%) copied"),
552  (int) strlen(fetch_size_str), fetch_done_str, fetch_size_str,
553  percent);
554  if (isatty(fileno(stderr)))
555  fprintf(stderr, "\r");
556  else
557  fprintf(stderr, "\n");
558 }
int64 pg_time_t
Definition: pgtime.h:23
static pg_time_t last_progress_report
#define fprintf
Definition: port.h:196
bool showprogress
Definition: pg_rewind.c:58
uint64 fetch_size
Definition: pg_rewind.c:67
#define INT64_FORMAT
Definition: c.h:401
uint64 fetch_done
Definition: pg_rewind.c:68
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:87
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547

◆ readOneRecord()

XLogRecPtr readOneRecord ( const char *  datadir,
XLogRecPtr  ptr,
int  tliIndex 
)

Definition at line 109 of file parsexlog.c.

References close, XLogReaderState::EndRecPtr, pg_fatal, SimpleXLogPageRead(), XLogPageReadPrivate::tliIndex, WalSegSz, XLogReaderAllocate(), XLogReaderFree(), xlogreadfd, and XLogReadRecord().

Referenced by main().

110 {
111  XLogRecord *record;
112  XLogReaderState *xlogreader;
113  char *errormsg;
114  XLogPageReadPrivate private;
115  XLogRecPtr endptr;
116 
117  private.tliIndex = tliIndex;
119  &private);
120  if (xlogreader == NULL)
121  pg_fatal("out of memory");
122 
123  record = XLogReadRecord(xlogreader, ptr, &errormsg);
124  if (record == NULL)
125  {
126  if (errormsg)
127  pg_fatal("could not read WAL record at %X/%X: %s",
128  (uint32) (ptr >> 32), (uint32) (ptr), errormsg);
129  else
130  pg_fatal("could not read WAL record at %X/%X",
131  (uint32) (ptr >> 32), (uint32) (ptr));
132  }
133  endptr = xlogreader->EndRecPtr;
134 
135  XLogReaderFree(xlogreader);
136  if (xlogreadfd != -1)
137  {
138  close(xlogreadfd);
139  xlogreadfd = -1;
140  }
141 
142  return endptr;
143 }
#define pg_fatal(...)
Definition: pg_rewind.h:41
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:232
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:238
XLogRecPtr EndRecPtr
Definition: xlogreader.h:132
char * datadir
unsigned int uint32
Definition: c.h:359
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
static int xlogreadfd
Definition: parsexlog.c:38
uint64 XLogRecPtr
Definition: xlogdefs.h:21
int WalSegSz
Definition: pg_standby.c:38
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
#define close(a)
Definition: win32.h:12

◆ rewind_parseTimeLineHistory()

TimeLineHistoryEntry* rewind_parseTimeLineHistory ( char *  buffer,
TimeLineID  targetTLI,
int *  nentries 
)

Definition at line 29 of file timeline.c.

References TimeLineHistoryEntry::begin, TimeLineHistoryEntry::end, InvalidXLogRecPtr, pg_log_error, pg_malloc(), pg_realloc(), and TimeLineHistoryEntry::tli.

Referenced by getTimelineHistory().

30 {
31  char *fline;
32  TimeLineHistoryEntry *entry;
33  TimeLineHistoryEntry *entries = NULL;
34  int nlines = 0;
35  TimeLineID lasttli = 0;
36  XLogRecPtr prevend;
37  char *bufptr;
38  bool lastline = false;
39 
40  /*
41  * Parse the file...
42  */
43  prevend = InvalidXLogRecPtr;
44  bufptr = buffer;
45  while (!lastline)
46  {
47  char *ptr;
48  TimeLineID tli;
49  uint32 switchpoint_hi;
50  uint32 switchpoint_lo;
51  int nfields;
52 
53  fline = bufptr;
54  while (*bufptr && *bufptr != '\n')
55  bufptr++;
56  if (!(*bufptr))
57  lastline = true;
58  else
59  *bufptr++ = '\0';
60 
61  /* skip leading whitespace and check for # comment */
62  for (ptr = fline; *ptr; ptr++)
63  {
64  if (!isspace((unsigned char) *ptr))
65  break;
66  }
67  if (*ptr == '\0' || *ptr == '#')
68  continue;
69 
70  nfields = sscanf(fline, "%u\t%X/%X", &tli, &switchpoint_hi, &switchpoint_lo);
71 
72  if (nfields < 1)
73  {
74  /* expect a numeric timeline ID as first field of line */
75  pg_log_error("syntax error in history file: %s", fline);
76  pg_log_error("Expected a numeric timeline ID.");
77  exit(1);
78  }
79  if (nfields != 3)
80  {
81  pg_log_error("syntax error in history file: %s", fline);
82  pg_log_error("Expected a write-ahead log switchpoint location.");
83  exit(1);
84  }
85  if (entries && tli <= lasttli)
86  {
87  pg_log_error("invalid data in history file: %s", fline);
88  pg_log_error("Timeline IDs must be in increasing sequence.");
89  exit(1);
90  }
91 
92  lasttli = tli;
93 
94  nlines++;
95  entries = pg_realloc(entries, nlines * sizeof(TimeLineHistoryEntry));
96 
97  entry = &entries[nlines - 1];
98  entry->tli = tli;
99  entry->begin = prevend;
100  entry->end = ((uint64) (switchpoint_hi)) << 32 | (uint64) switchpoint_lo;
101  prevend = entry->end;
102 
103  /* we ignore the remainder of each line */
104  }
105 
106  if (entries && targetTLI <= lasttli)
107  {
108  pg_log_error("invalid data in history file");
109  pg_log_error("Timeline IDs must be less than child timeline's ID.");
110  exit(1);
111  }
112 
113  /*
114  * Create one more entry for the "tip" of the timeline, which has no entry
115  * in the history file.
116  */
117  nlines++;
118  if (entries)
119  entries = pg_realloc(entries, nlines * sizeof(TimeLineHistoryEntry));
120  else
121  entries = pg_malloc(1 * sizeof(TimeLineHistoryEntry));
122 
123  entry = &entries[nlines - 1];
124  entry->tli = targetTLI;
125  entry->begin = prevend;
126  entry->end = InvalidXLogRecPtr;
127 
128  *nentries = nlines;
129  return entries;
130 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:52
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
#define pg_log_error(...)
Definition: logging.h:79
TimeLineID tli
Definition: timeline.h:27
unsigned int uint32
Definition: c.h:359
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
XLogRecPtr end
Definition: timeline.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr begin
Definition: timeline.h:28

Variable Documentation

◆ conn

PGconn* conn

Definition at line 54 of file streamutil.c.

Referenced by BaseBackup(), build_client_final_message(), build_client_first_message(), check_for_data_type_usage(), check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_for_tables_with_oids(), check_is_install_user(), check_loadable_libraries(), cluster_all_databases(), cluster_one_database(), connectDatabase(), connectMaintenanceDatabase(), connectToServer(), disconnect_atexit(), doConnect(), dumpBlobs(), dumpDatabase(), dumpDatabaseConfig(), dumpTableData_copy(), ExecuteSqlCommand(), freePGconn(), get_db_conn(), get_db_infos(), get_loadable_libraries(), get_rel_infos(), get_tablespace_paths(), init_slot(), libpqrcv_connect(), main(), makeEmptyPGconn(), new_9_0_populate_pg_largeobject_metadata(), old_9_6_invalidate_hash_indexes(), ParallelSlotsTerminate(), pg_fe_scram_exchange(), pg_fe_scram_init(), pgtls_write(), PQconnectdb(), PQconnectdbParams(), PQconnectStart(), PQconnectStartParams(), PQfireResultCreateEvents(), PQgetResult(), PQping(), PQpingParams(), PQregisterEventProc(), PQreset(), PQresetPoll(), PQsetdbLogin(), read_server_final_message(), read_server_first_message(), reindex_all_databases(), reindex_one_database(), run_permutation(), set_frozenxids(), setKeepalivesCount(), setup_connection(), sql_conn(), start_postmaster(), StartLogStreamer(), StreamLog(), StreamLogicalLog(), try_complete_step(), vacuum_all_databases(), vacuum_one_database(), and vacuumlo().

◆ connstr_source

char* connstr_source

Definition at line 55 of file pg_rewind.c.

Referenced by main().

◆ datadir_source

char* datadir_source

◆ datadir_target

◆ dry_run

◆ fetch_done

uint64 fetch_done

Definition at line 68 of file pg_rewind.c.

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

◆ fetch_size

uint64 fetch_size

Definition at line 67 of file pg_rewind.c.

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

◆ showprogress

bool showprogress

Definition at line 58 of file pg_rewind.c.

Referenced by main(), and progress_report().

◆ targetHistory

TimeLineHistoryEntry* targetHistory

Definition at line 63 of file pg_rewind.c.

Referenced by SimpleXLogPageRead().

◆ targetNentries

int targetNentries

◆ WalSegSz