diff --git a/src/bin/pg_rewind/pg_rewind.c b/src/bin/pg_rewind/pg_rewind.c index d1d726ee82d..05f1f4c6ea4 100644 --- a/src/bin/pg_rewind/pg_rewind.c +++ b/src/bin/pg_rewind/pg_rewind.c @@ -46,6 +46,8 @@ static void createBackupLabel(XLogRecPtr startpoint, TimeLineID starttli, static void digestControlFile(ControlFileData *ControlFile, const char *content, size_t size); static void getRestoreCommand(const char *argv0); +static void clear_wal_after_divergence(file_entry_t *entry, + XLogRecPtr divergerec); static void sanityChecks(void); static TimeLineHistoryEntry *getTimelineHistory(TimeLineID tli, bool is_source, int *nentries); @@ -650,7 +652,7 @@ perform_rewind(filemap_t *filemap, rewind_source *source, switch (entry->action) { case FILE_ACTION_NONE: - /* nothing else to do */ + clear_wal_after_divergence(entry, divergerec); break; case FILE_ACTION_COPY: @@ -819,6 +821,48 @@ perform_rewind(filemap_t *filemap, rewind_source *source, update_controlfile(datadir_target, &ControlFile_new, do_sync); } +/* + * A WAL segment that exists only in the target is kept if it has WAL between + * the last common checkpoint and the point of divergence. If the point of + * divergence is in it, the rest of the segment is WAL of the target's old + * timeline. Recovery must not find that: when the source's segment for the + * new timeline is not available, it would read on in this one and replay the + * WAL we are rewinding. Zero it out. + */ +static void +clear_wal_after_divergence(file_entry_t *entry, XLogRecPtr divergerec) +{ + static const PGAlignedXLogBlock zeros = {0}; + const char *fname; + TimeLineID tli; + XLogSegNo segno; + XLogSegNo divergesegno; + off_t off; + + if (entry->source_exists || !entry->target_exists) + return; + if (strncmp(entry->path, XLOGDIR "/", strlen(XLOGDIR "/")) != 0) + return; + fname = entry->path + strlen(XLOGDIR "/"); + if (!IsXLogFileName(fname)) + return; + + XLogFromFileName(fname, &tli, &segno, WalSegSz); + XLByteToSeg(divergerec, divergesegno, WalSegSz); + if (segno != divergesegno) + return; + + pg_log_debug("clearing WAL after %X/%08X in \"%s\"", + LSN_FORMAT_ARGS(divergerec), entry->path); + + open_target_file(entry->path, false); + for (off = XLogSegmentOffset(divergerec, WalSegSz); + off < entry->target_size; + off += XLOG_BLCKSZ) + write_target_range(unconstify(char *, zeros.data), off, + Min(XLOG_BLCKSZ, entry->target_size - off)); +} + static void sanityChecks(void) {