From a1ca1f98096b05344e8b2c7025d90885ad6f8b8e Mon Sep 17 00:00:00 2001
From: Ronan Dunklau <ronan.dunklau@aiven.io>
Date: Wed, 1 Sep 2021 15:52:32 +0200
Subject: [PATCH v5 2/3] Use READ_REPLICATION_SLOT command in pg_receivewal.

Prior to this patch, when running pg_receivewal, the start LSN is determined by looking at
the WAL files currently stored on disk, then using the current flush lsn
from the server.

If for some reason the WAL files from pg_receivewal were moved, we want
to restart where we left at, which is the replication slot's restart_lsn
instead of skipping right to the current flush location.

To keep compatibility with prior server versions, we only attempt it if
the version is < 15.
---
 src/bin/pg_basebackup/pg_receivewal.c        |  53 +++++++++-
 src/bin/pg_basebackup/streamutil.c           | 100 +++++++++++++++++++
 src/bin/pg_basebackup/streamutil.h           |  16 +++
 src/bin/pg_basebackup/t/020_pg_receivewal.pl |  51 +++++++++-
 4 files changed, 216 insertions(+), 4 deletions(-)

diff --git a/src/bin/pg_basebackup/pg_receivewal.c b/src/bin/pg_basebackup/pg_receivewal.c
index 9d1843728d..9f63df120b 100644
--- a/src/bin/pg_basebackup/pg_receivewal.c
+++ b/src/bin/pg_basebackup/pg_receivewal.c
@@ -408,10 +408,59 @@ StreamLog(void)
 	stream.startpos = FindStreamingStart(&stream.timeline);
 	if (stream.startpos == InvalidXLogRecPtr)
 	{
-		stream.startpos = serverpos;
-		stream.timeline = servertli;
+		/* Try to get it from the slot if any, and the server supports it */
+		if (replication_slot)
+		{
+			SlotInformation slot_info;
+
+			switch (GetSlotInformation(conn, replication_slot, &slot_info))
+			{
+				case READ_REPLICATION_SLOT_ERROR:
+
+					/*
+					 * Error has been logged by GetSlotInformation, return and
+					 * maybe retry
+					 */
+					return;
+				case READ_REPLICATION_SLOT_NONEXISTENT:
+					pg_log_error("replication slot \"%s\" does not exist", replication_slot);
+					return;
+				case READ_REPLICATION_SLOT_UNSUPPORTED:
+
+					/*
+					 * Server doesn't support the command, so fallback to the
+					 * default case
+					 */
+					pg_log_warning("server does not support fetching the slot's position, "
+								   "resuming from current server position instead");
+					break;
+				default:
+					if (slot_info.is_logical)
+					{
+						/*
+						 * If the slot is not physical we can't expect to
+						 * recover from that
+						 */
+						pg_log_error("cannot use the slot provided, physical slot expected.");
+						exit(1);
+					}
+					stream.startpos = slot_info.restart_lsn;
+					stream.timeline = slot_info.restart_tli;
+			}
+		}
+
+		/*
+		 * If it is still unknown, use the current flush value from the server
+		 */
+		if (stream.startpos == InvalidXLogRecPtr)
+		{
+			stream.startpos = serverpos;
+			stream.timeline = servertli;
+		}
 	}
 
+	Assert(stream.startpos != InvalidXLogRecPtr);
+
 	/*
 	 * Always start streaming at the beginning of a segment
 	 */
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index f5b3b476e5..a4d25552b3 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -479,6 +479,106 @@ RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli,
 	return true;
 }
 
+
+/*
+ * Returns wether a replication slot exists through a given connection,
+ * and fills in the slot_info with the results if passed by the caller.
+ */
+ReadReplicationSlotStatus
+GetSlotInformation(PGconn *conn, const char *slot_name, SlotInformation * slot_info)
+{
+	PGresult   *res;
+	PQExpBuffer query;
+
+	Assert(slot_name != NULL);
+
+	if (PQserverVersion(conn) < 150000)
+		return READ_REPLICATION_SLOT_UNSUPPORTED;
+
+
+	query = createPQExpBuffer();
+	appendPQExpBuffer(query, "READ_REPLICATION_SLOT %s", slot_name);
+	res = PQexec(conn, query->data);
+	destroyPQExpBuffer(query);
+	/* The commpand should always return precisely one tuple */
+	if (PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) != 1)
+	{
+		pg_log_error("could not read replication slot : %s",
+					 PQerrorMessage(conn));
+		PQclear(res);
+		return READ_REPLICATION_SLOT_ERROR;
+	}
+
+	/*
+	 * When the slot doesn't exist, the command returns an all-null tuple. The
+	 * first column (slot_type) will only be null if the slot doesn't exists.
+	 */
+	if (PQgetisnull(res, 0, 0))
+	{
+		PQclear(res);
+		return READ_REPLICATION_SLOT_NONEXISTENT;
+	}
+	if (PQntuples(res) != 1 || PQnfields(res) < 5)
+	{
+		pg_log_error("could not fetch replication slot: got %d rows and %d fields, expected %d rows and %d or more fields",
+					 PQntuples(res), PQnfields(res), 1, 5);
+		PQclear(res);
+		return READ_REPLICATION_SLOT_ERROR;
+	}
+	/* If no slotinformation has been passed, we can return immediately */
+	if (slot_info == NULL)
+	{
+		PQclear(res);
+		return READ_REPLICATION_SLOT_OK;
+	}
+
+	slot_info->is_logical = strcmp(PQgetvalue(res, 0, 0), "logical") == 0;
+	/* Restart LSN */
+	if (PQgetisnull(res, 0, 1))
+		slot_info->restart_lsn = InvalidXLogRecPtr;
+	else
+	{
+		uint32		hi,
+					lo;
+
+		if (sscanf(PQgetvalue(res, 0, 1), "%X/%X", &hi, &lo) != 2)
+		{
+			pg_log_error("could not parse slot's restart_lsn \"%s\"",
+						 PQgetvalue(res, 0, 1));
+			PQclear(res);
+			return READ_REPLICATION_SLOT_ERROR;
+		}
+		slot_info->restart_lsn = ((uint64) hi) << 32 | lo;
+	}
+	if (PQgetisnull(res, 0, 2))
+		slot_info->confirmed_flush_lsn = InvalidXLogRecPtr;
+	else
+	{
+		uint32		hi,
+					lo;
+
+		if (sscanf(PQgetvalue(res, 0, 2), "%X/%X", &hi, &lo) != 2)
+		{
+			pg_log_error("could not parse slot's confirmed_flush_lsn \"%s\"",
+						 PQgetvalue(res, 0, 2));
+			PQclear(res);
+			return READ_REPLICATION_SLOT_ERROR;
+		}
+		slot_info->confirmed_flush_lsn = ((uint64) hi) << 32 | lo;
+	}
+
+	if (PQgetisnull(res, 0, 3))
+		slot_info->restart_tli = 0;
+	else
+		slot_info->restart_tli = atoi(PQgetvalue(res, 0, 3));
+	if (PQgetisnull(res, 0, 4))
+		slot_info->confirmed_flush_tli = 0;
+	else
+		slot_info->confirmed_flush_tli = atoi(PQgetvalue(res, 0, 4));
+	PQclear(res);
+	return READ_REPLICATION_SLOT_OK;
+}
+
 /*
  * Create a replication slot for the given connection. This function
  * returns true in case of success.
diff --git a/src/bin/pg_basebackup/streamutil.h b/src/bin/pg_basebackup/streamutil.h
index 504803b976..cd3bc3229a 100644
--- a/src/bin/pg_basebackup/streamutil.h
+++ b/src/bin/pg_basebackup/streamutil.h
@@ -28,6 +28,14 @@ extern uint32 WalSegSz;
 /* Connection kept global so we can disconnect easily */
 extern PGconn *conn;
 
+typedef struct SlotInformation {
+	bool	   is_logical;
+	XLogRecPtr restart_lsn;
+	XLogRecPtr confirmed_flush_lsn;
+	TimeLineID restart_tli;
+	TimeLineID confirmed_flush_tli;
+} SlotInformation;
+
 extern PGconn *GetConnection(void);
 
 /* Replication commands */
@@ -40,6 +48,14 @@ extern bool RunIdentifySystem(PGconn *conn, char **sysid,
 							  TimeLineID *starttli,
 							  XLogRecPtr *startpos,
 							  char **db_name);
+typedef enum {
+	READ_REPLICATION_SLOT_OK,
+	READ_REPLICATION_SLOT_UNSUPPORTED,
+	READ_REPLICATION_SLOT_ERROR,
+	READ_REPLICATION_SLOT_NONEXISTENT
+} ReadReplicationSlotStatus;
+
+extern ReadReplicationSlotStatus GetSlotInformation(PGconn *conn, const char *slot_name, SlotInformation *slot_info);
 extern bool RetrieveWalSegSize(PGconn *conn);
 extern TimestampTz feGetCurrentTimestamp(void);
 extern void feTimestampDifference(TimestampTz start_time, TimestampTz stop_time,
diff --git a/src/bin/pg_basebackup/t/020_pg_receivewal.pl b/src/bin/pg_basebackup/t/020_pg_receivewal.pl
index 0b33d73900..e79fd9d7f0 100644
--- a/src/bin/pg_basebackup/t/020_pg_receivewal.pl
+++ b/src/bin/pg_basebackup/t/020_pg_receivewal.pl
@@ -5,7 +5,7 @@ use strict;
 use warnings;
 use TestLib;
 use PostgresNode;
-use Test::More tests => 27;
+use Test::More tests => 32;
 
 program_help_ok('pg_receivewal');
 program_version_ok('pg_receivewal');
@@ -49,7 +49,7 @@ is($primary->slot($slot_name)->{'slot_type'},
 
 # Generate some WAL.  Use --synchronous at the same time to add more
 # code coverage.  Switch to the next segment first so that subsequent
-# restarts of pg_receivewal will see this segment as full..
+# restarts of pg_receivewal will see this segment as full
 $primary->psql('postgres', 'CREATE TABLE test_table(x integer);');
 $primary->psql('postgres', 'SELECT pg_switch_wal();');
 my $nextlsn =
@@ -146,6 +146,53 @@ $primary->command_ok(
 $partial_wals[0] =~ s/(\.gz)?.partial//;
 ok(-e $partial_wals[0], "check that previously partial WAL is now complete");
 
+# Verify that if we use a replication slot, we resume where we left even in the
+# absence of WALs
+
+# Setup the slot, and connect to it a first time
+$primary->run_log(
+	[ 'pg_receivewal', '--slot', $slot_name, '--create-slot' ],
+	'creating a replication slot');
+$primary->psql('postgres',
+	'INSERT INTO test_table VALUES (generate_series(1,100));');
+$primary->psql('postgres', 'SELECT pg_switch_wal();');
+$nextlsn =
+  $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn();');
+chomp($nextlsn);
+$primary->run_log(
+	[ 'pg_receivewal', '-D', $stream_dir, '--slot', $slot_name, '--verbose', '--endpos', $nextlsn ],
+	"streaming some WAL");
+
+# Get the slot restart_lsn and make sure we retrieve the associated WAL file
+# even after deletion of the previous stored WAL files.
+$slot = $primary->slot($slot_name);
+my $restart_lsn = $slot->{'restart_lsn'};
+# Add one so that the restart_lsn doesn't correspond to the previous file.
+$restart_lsn =~ s/.$/1/;
+my $walfile_to_be_archived = $primary->safe_psql('postgres',
+	"SELECT pg_walfile_name('$restart_lsn');");
+isnt($restart_lsn, '', 'restart LSN of new slot is not null');
+
+unlink glob "'${stream_dir}/*'";
+
+$primary->psql('postgres',
+	'INSERT INTO test_table VALUES (generate_series(1,100));');
+$primary->psql('postgres', 'SELECT pg_switch_wal();');
+$nextlsn =
+  $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn();');
+chomp($nextlsn);
+# First verify what happens if we try with a non-existing slot.
+$primary->command_fails_like(
+  [ 'pg_receivewal', '-D', $stream_dir, '--slot', 'nonexistentslot', '-n', '--verbose', '--endpos', $nextlsn ],
+  qr/pg_receivewal: error: replication slot "nonexistentslot" does not exist/,
+  'pg_receivewal fails with a non-existing slot');
+$primary->command_ok(
+	[ 'pg_receivewal', '-D', $stream_dir, '--slot', $slot_name, '--verbose', '--endpos', $nextlsn ],
+	"Stream some wal starting from the slot's restart_lsn");
+$slot = $primary->slot($slot_name);
+my @walfiles = glob "${stream_dir}/*";
+ok(-e "$stream_dir/$walfile_to_be_archived", "WAL from the slot's restart_lsn has been archived");
+
 # Permissions on WAL files should be default
 SKIP:
 {
-- 
2.33.0

