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(), pg_fatal, XLogReaderState::ReadRecPtr, SimpleXLogPageRead(), XLogPageReadPrivate::tliIndex, WalSegSz, XLogBeginRead(), 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  XLogBeginRead(xlogreader, startpoint);
72  do
73  {
74  record = XLogReadRecord(xlogreader, &errormsg);
75 
76  if (record == NULL)
77  {
78  XLogRecPtr errptr = xlogreader->EndRecPtr;
79 
80  if (errormsg)
81  pg_fatal("could not read WAL record at %X/%X: %s",
82  (uint32) (errptr >> 32), (uint32) (errptr),
83  errormsg);
84  else
85  pg_fatal("could not read WAL record at %X/%X",
86  (uint32) (errptr >> 32), (uint32) (errptr));
87  }
88 
89  extractPageInfo(xlogreader);
90 
91  } while (xlogreader->ReadRecPtr != endpoint);
92 
93  XLogReaderFree(xlogreader);
94  if (xlogreadfd != -1)
95  {
97  xlogreadfd = -1;
98  }
99 }
#define pg_fatal(...)
Definition: pg_rewind.h:41
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:231
XLogRecPtr EndRecPtr
Definition: xlogreader.h:135
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:261
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:134
char * datadir
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233
unsigned int uint32
Definition: c.h:367
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
static int xlogreadfd
Definition: parsexlog.c:38
static void extractPageInfo(XLogReaderState *record)
Definition: parsexlog.c:324
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 147 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, XLogBeginRead(), XLogReaderAllocate(), XLogReaderFree(), xlogreadfd, XLogReadRecord(), XLogRecGetData, XLogRecGetInfo, XLogRecGetRmid, XLogSegmentOffset, and XLR_INFO_MASK.

Referenced by main().

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

◆ progress_report()

void progress_report ( bool  force)

Definition at line 513 of file pg_rewind.c.

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

Referenced by main().

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

◆ readOneRecord()

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

Definition at line 106 of file parsexlog.c.

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

Referenced by main().

107 {
108  XLogRecord *record;
109  XLogReaderState *xlogreader;
110  char *errormsg;
111  XLogPageReadPrivate private;
112  XLogRecPtr endptr;
113 
114  private.tliIndex = tliIndex;
116  &private);
117  if (xlogreader == NULL)
118  pg_fatal("out of memory");
119 
120  XLogBeginRead(xlogreader, ptr);
121  record = XLogReadRecord(xlogreader, &errormsg);
122  if (record == NULL)
123  {
124  if (errormsg)
125  pg_fatal("could not read WAL record at %X/%X: %s",
126  (uint32) (ptr >> 32), (uint32) (ptr), errormsg);
127  else
128  pg_fatal("could not read WAL record at %X/%X",
129  (uint32) (ptr >> 32), (uint32) (ptr));
130  }
131  endptr = xlogreader->EndRecPtr;
132 
133  XLogReaderFree(xlogreader);
134  if (xlogreadfd != -1)
135  {
136  close(xlogreadfd);
137  xlogreadfd = -1;
138  }
139 
140  return endptr;
141 }
#define pg_fatal(...)
Definition: pg_rewind.h:41
static int SimpleXLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: parsexlog.c:231
XLogRecPtr EndRecPtr
Definition: xlogreader.h:135
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:261
char * datadir
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233
unsigned int uint32
Definition: c.h:367
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:367
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