From 00b1b245f74a0496a4d60cfafff92735dbe73d22 Mon Sep 17 00:00:00 2001
From: Michael Banck <michael.banck@credativ.de>
Date: Mon, 22 Aug 2022 16:20:14 +0200
Subject: [PATCH] Allow usage of archive .backup files as backup_label.

This lets the backup_label parser not bail if STOP WAL LOCATION is encountered,
which is the only meaningful difference between an archive .backup file and a
backup_label file, thus allowing to just copy the corresponding .backup file
from the archive as backup_label, in case the backup_label file got lost or was
never recorded.
---
 src/backend/access/transam/xlogrecovery.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index a59a0e826b..a95946e391 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1149,6 +1149,7 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 				  bool *backupEndRequired, bool *backupFromStandby)
 {
 	char		startxlogfilename[MAXFNAMELEN];
+	char		stopxlogfilename[MAXFNAMELEN];
 	TimeLineID	tli_from_walseg,
 				tli_from_file;
 	FILE	   *lfp;
@@ -1183,7 +1184,10 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 	/*
 	 * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
 	 * is pretty crude, but we are not expecting any variability in the file
-	 * format).
+	 * format). Also allow STOP WAL LOCATION to be in the file. This line does
+	 * not appear in backup_label, but it is written to the corresponding
+	 * .backup file and allows users to rename or copy that file to
+	 * backup_label without further editing.
 	 */
 	if (fscanf(lfp, "START WAL LOCATION: %X/%X (file %08X%16s)%c",
 			   &hi, &lo, &tli_from_walseg, startxlogfilename, &ch) != 5 || ch != '\n')
@@ -1192,6 +1196,11 @@ read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
 				 errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
 	RedoStartLSN = ((uint64) hi) << 32 | lo;
 	RedoStartTLI = tli_from_walseg;
+	if (fscanf(lfp, "STOP WAL LOCATION: %X/%X (file %*08X%16s)%c",
+				&hi, &lo, stopxlogfilename, &ch) == 4)
+		ereport(DEBUG1,
+				(errmsg_internal("stop wal location %X/%X in file \"%s\"",
+								 hi, lo, BACKUP_LABEL_FILE)));
 	if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%X%c",
 			   &hi, &lo, &ch) != 3 || ch != '\n')
 		ereport(FATAL,
-- 
2.30.2

