Re: standby recovery fails (tablespace related) (tentative patch and discussion)

Поиск
Список
Период
Сортировка
От Kyotaro Horiguchi
Тема Re: standby recovery fails (tablespace related) (tentative patch and discussion)
Дата
Msg-id 20211108.175516.1349628366169685520.horikyota.ntt@gmail.com
обсуждение исходный текст
Ответ на Re: standby recovery fails (tablespace related) (tentative patch and discussion)  (Daniel Gustafsson <daniel@yesql.se>)
Список pgsql-hackers
At Thu, 4 Nov 2021 13:34:33 +0100, Daniel Gustafsson <daniel@yesql.se> wrote in 
> This patch again fails to apply (seemingly from the Perl namespace work on the
> testcode), and needs a few updates as per the above review.

Rebased the latest patch removing some of the chages.

0001: (I don't remember about this, though) I don't see how to make it
work on Windows.  Anyway the next step would be to write comments.

0002: I didin't see it in details and didn't check if it finds the
issue but it actually scceeds with the fix.  The change to
poll_query_until is removed since it doesn't seem actually used.

0003: The fix. I didn't touch this.

0004: Removed at all. I agree to Tom. (And I faintly remember that I
said something like that.)

regards.

-- 
Kyotaro Horiguchi
NTT Open Source Software Center
From aa6b0b94e42550f23c4cecfa23ea1face7d71bc6 Mon Sep 17 00:00:00 2001
From: Asim R P <apraveen@pivotal.io>
Date: Mon, 8 Nov 2021 17:32:30 +0900
Subject: [PATCH v13 1/3] Support node initialization from backup with
 tablespaces

User defined tablespaces appear as symlinks in in the backup.  This
commit tweaks recursive copy subroutine to allow for symlinks specific
to tablespaces.
---
 src/test/perl/PostgreSQL/Test/Cluster.pm      | 29 +++++++++++-
 .../perl/PostgreSQL/Test/RecursiveCopy.pm     | 45 ++++++++++++++++---
 2 files changed, 66 insertions(+), 8 deletions(-)

diff --git a/src/test/perl/PostgreSQL/Test/Cluster.pm b/src/test/perl/PostgreSQL/Test/Cluster.pm
index 9467a199c8..19a667ebe4 100644
--- a/src/test/perl/PostgreSQL/Test/Cluster.pm
+++ b/src/test/perl/PostgreSQL/Test/Cluster.pm
@@ -634,6 +634,32 @@ sub backup_fs_cold
     return;
 }
 
+sub _srcsymlink
+{
+    my ($srcpath, $destpath) = @_;
+
+    croak "Cannot operate on symlink \"$srcpath\""
+        if ($srcpath !~ qr{/(pg_tblspc/[0-9]+)$});
+
+    # We have mapped tablespaces. Copy them individually
+    my $tmpdir = PostgreSQL::Test::Utils::tempdir();
+    my $dstrealdir = PostgreSQL::Test::Utils::perl2host($tmpdir);
+    my $srcrealdir = readlink($srcpath);
+
+    opendir(my $dh, $srcrealdir);
+    while (my $entry = (readdir $dh))
+    {
+        next if ($entry eq '.' or $entry eq '..');
+        my $spath = "$srcrealdir/$entry";
+        my $dpath = "$dstrealdir/$entry";
+        PostgreSQL::Test::RecursiveCopy::copypath($spath, $dpath);
+    }
+    closedir $dh;
+
+    symlink $dstrealdir, $destpath;
+
+    return 1;
+}
 
 # Common sub of backup_fs_hot and backup_fs_cold
 sub _backup_fs
@@ -743,7 +769,8 @@ sub init_from_backup
     else
     {
         rmdir($data_path);
-        PostgreSQL::Test::RecursiveCopy::copypath($backup_path, $data_path);
+        PostgreSQL::Test::RecursiveCopy::copypath($backup_path, $data_path,
+                                srcsymlinkfn => \&_srcsymlink);
     }
     chmod(0700, $data_path);
 
diff --git a/src/test/perl/PostgreSQL/Test/RecursiveCopy.pm b/src/test/perl/PostgreSQL/Test/RecursiveCopy.pm
index dd320a605e..2a636cef84 100644
--- a/src/test/perl/PostgreSQL/Test/RecursiveCopy.pm
+++ b/src/test/perl/PostgreSQL/Test/RecursiveCopy.pm
@@ -49,6 +49,11 @@ This subroutine will be called for each entry in the source directory with its
 relative path as only parameter; if the subroutine returns true the entry is
 copied, otherwise the file is skipped.
 
+If the B<srcsymlinkfn> parameter is given, it must be a subroutine reference.
+This subroutine will be called when the source directory is a symlink. It
+determines the mechanism that copies files from the source directory to the
+destination directory.
+
 On failure the target directory may be in some incomplete state; no cleanup is
 attempted.
 
@@ -68,6 +73,7 @@ sub copypath
 {
     my ($base_src_dir, $base_dest_dir, %params) = @_;
     my $filterfn;
+    my $srcsymlinkfn;
 
     if (defined $params{filterfn})
     {
@@ -82,31 +88,55 @@ sub copypath
         $filterfn = sub { return 1; };
     }
 
+    if (defined $params{srcsymlinkfn})
+    {
+        croak "if specified, srcsymlinkfn must be a subroutine reference"
+            unless defined(ref $params{srcsymlinkfn})
+            and (ref $params{srcsymlinkfn} eq 'CODE');
+
+        $srcsymlinkfn = $params{srcsymlinkfn};
+    }
+    else
+    {
+        $srcsymlinkfn = undef;
+    }
+
     # Complain if original path is bogus, because _copypath_recurse won't.
     croak "\"$base_src_dir\" does not exist" if !-e $base_src_dir;
 
     # Start recursive copy from current directory
-    return _copypath_recurse($base_src_dir, $base_dest_dir, "", $filterfn);
+    return _copypath_recurse($base_src_dir, $base_dest_dir, "", $filterfn, $srcsymlinkfn);
 }
 
 # Recursive private guts of copypath
 sub _copypath_recurse
 {
-    my ($base_src_dir, $base_dest_dir, $curr_path, $filterfn) = @_;
+    my ($base_src_dir, $base_dest_dir, $curr_path, $filterfn,
+        $srcsymlinkfn) = @_;
     my $srcpath  = "$base_src_dir/$curr_path";
     my $destpath = "$base_dest_dir/$curr_path";
 
     # invoke the filter and skip all further operation if it returns false
     return 1 unless &$filterfn($curr_path);
 
-    # Check for symlink -- needed only on source dir
-    # (note: this will fall through quietly if file is already gone)
-    croak "Cannot operate on symlink \"$srcpath\"" if -l $srcpath;
-
     # Abort if destination path already exists.  Should we allow directories
     # to exist already?
     croak "Destination path \"$destpath\" already exists" if -e $destpath;
 
+    # Check for symlink -- needed only on source dir
+    # If caller provided us with a callback, call it; otherwise we're out.
+    if (-l $srcpath)
+    {
+        if (defined $srcsymlinkfn)
+        {
+            return &$srcsymlinkfn($srcpath, $destpath);
+        }
+        else
+        {
+            croak "Cannot operate on symlink \"$srcpath\"";
+        }
+    }
+
     # If this source path is a file, simply copy it to destination with the
     # same name and we're done.
     if (-f $srcpath)
@@ -139,7 +169,8 @@ sub _copypath_recurse
         {
             next if ($entry eq '.' or $entry eq '..');
             _copypath_recurse($base_src_dir, $base_dest_dir,
-                $curr_path eq '' ? $entry : "$curr_path/$entry", $filterfn)
+                $curr_path eq '' ? $entry : "$curr_path/$entry", $filterfn,
+                $srcsymlinkfn)
               or die "copypath $srcpath/$entry -> $destpath/$entry failed";
         }
 
-- 
2.27.0

From 030f30d330dba3a6c3ff3f9561348375d30a1486 Mon Sep 17 00:00:00 2001
From: Asim R P <apraveen@pivotal.io>
Date: Fri, 20 Sep 2019 17:31:25 +0530
Subject: [PATCH v13 2/3] Tests to replay create database operation on standby

The tests demonstrate that standby fails to replay a create database
WAL record during crash recovery, if one or more of underlying
directories are missing from the file system.  This can happen if a
drop tablespace or drop database WAL record has been replayed in
archive recovery, before a crash.  And then the create database record
happens to be replayed again during crash recovery.  The failures
indicate bugs that need to be fixed.

The first test, TEST 4, performs several DDL operations resulting in a
database directory being removed, along with a few create database
operations.  It expects crash recovery to succeed because for each
missing directory encountered during create database replay, a matching
drop tablespace or drop database WAL record is found later.

Second test, TEST 5, validates that a standby rightfully aborts replay
during archive recovery, if a missing directory is encountered when
replaying create database WAL record.

These tests have been proposed and implemented in various ways by
Alexandra Wang, Anastasia Lubennikova, Kyotaro Horiguchi, Paul Guo and me.
---
 src/test/recovery/t/011_crash_recovery.pl | 162 +++++++++++++++++++++-
 1 file changed, 161 insertions(+), 1 deletion(-)

diff --git a/src/test/recovery/t/011_crash_recovery.pl b/src/test/recovery/t/011_crash_recovery.pl
index d7806e6671..a4e1fcb5dc 100644
--- a/src/test/recovery/t/011_crash_recovery.pl
+++ b/src/test/recovery/t/011_crash_recovery.pl
@@ -9,9 +9,10 @@ use warnings;
 use PostgreSQL::Test::Cluster;
 use PostgreSQL::Test::Utils;
 use Test::More;
+use File::Path qw(rmtree);
 use Config;
 
-plan tests => 3;
+plan tests => 5;
 
 my $node = PostgreSQL::Test::Cluster->new('primary');
 $node->init(allows_streaming => 1);
@@ -62,3 +63,162 @@ is($node->safe_psql('postgres', qq[SELECT pg_xact_status('$xid');]),
 
 $stdin .= "\\q\n";
 $tx->finish;    # wait for psql to quit gracefully
+
+# TEST 4
+#
+# Ensure that a missing tablespace directory during crash recovery on
+# a standby is handled correctly.  The standby should finish crash
+# recovery successfully because a matching drop database record is
+# found in the WAL.  The following scnearios are covered:
+#
+# 1. Create a database against a user-defined tablespace then drop the
+#    database.
+#
+# 2. Create a database against a user-defined tablespace then drop the
+#    database and the tablespace.
+#
+# 3. Move a database from source tablespace to target tablespace then
+#    drop the source tablespace.
+#
+# 4. Create a database from another database as template then drop the
+#    template database.
+#
+#
+
+my $node_master = PostgreSQL::Test::Cluster->new('master2');
+$node_master->init(allows_streaming => 1);
+$node_master->start;
+
+# Create tablespace
+my $dropme_ts_master1 = PostgreSQL::Test::Utils::tempdir();
+$dropme_ts_master1 = PostgreSQL::Test::Utils::perl2host($dropme_ts_master1);
+my $dropme_ts_master2 = PostgreSQL::Test::Utils::tempdir();
+$dropme_ts_master2 = PostgreSQL::Test::Utils::perl2host($dropme_ts_master2);
+my $source_ts_master = PostgreSQL::Test::Utils::tempdir();
+$source_ts_master = PostgreSQL::Test::Utils::perl2host($source_ts_master);
+my $target_ts_master = PostgreSQL::Test::Utils::tempdir();
+$target_ts_master = PostgreSQL::Test::Utils::perl2host($target_ts_master);
+
+$node_master->safe_psql('postgres',
+                        qq[CREATE TABLESPACE dropme_ts1 location '$dropme_ts_master1';
+                           CREATE TABLESPACE dropme_ts2 location '$dropme_ts_master2';
+                           CREATE TABLESPACE source_ts location '$source_ts_master';
+                           CREATE TABLESPACE target_ts location '$target_ts_master';
+                           CREATE DATABASE template_db IS_TEMPLATE = true;]);
+
+my $dropme_ts_standby1 = PostgreSQL::Test::Utils::tempdir();
+$dropme_ts_standby1 = PostgreSQL::Test::Utils::perl2host($dropme_ts_standby1);
+my $dropme_ts_standby2 = PostgreSQL::Test::Utils::tempdir();
+$dropme_ts_standby2 = PostgreSQL::Test::Utils::perl2host($dropme_ts_standby2);
+my $source_ts_standby = PostgreSQL::Test::Utils::tempdir();
+$source_ts_standby = PostgreSQL::Test::Utils::perl2host($source_ts_standby);
+my $target_ts_standby = PostgreSQL::Test::Utils::tempdir();
+$target_ts_standby = PostgreSQL::Test::Utils::perl2host($target_ts_standby);
+
+# Take backup
+my $backup_name = 'my_backup';
+my $ts_mapping = [ "--tablespace-mapping=$dropme_ts_master1=$dropme_ts_standby1",
+  "--tablespace-mapping=$dropme_ts_master2=$dropme_ts_standby2",
+  "--tablespace-mapping=$source_ts_master=$source_ts_standby",
+  "--tablespace-mapping=$target_ts_master=$target_ts_standby" ];
+$node_master->backup($backup_name, backup_options => $ts_mapping);
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby2');
+$node_standby->init_from_backup($node_master, $backup_name, has_streaming => 1);
+$node_standby->start;
+
+# Make sure connection is made
+$node_master->poll_query_until(
+    'postgres', 'SELECT count(*) = 1 FROM pg_stat_replication');
+
+# Make sure to perform restartpoint after tablespace creation
+$node_master->wait_for_catchup($node_standby, 'replay',
+                               $node_master->lsn('replay'));
+$node_standby->safe_psql('postgres', 'CHECKPOINT');
+
+# Do immediate shutdown just after a sequence of CREAT DATABASE / DROP
+# DATABASE / DROP TABLESPACE. This causes CREATE DATABASE WAL records
+# to be applied to already-removed directories.
+$node_master->safe_psql('postgres',
+                        q[CREATE DATABASE dropme_db1 WITH TABLESPACE dropme_ts1;
+                          CREATE DATABASE dropme_db2 WITH TABLESPACE dropme_ts2;
+                          CREATE DATABASE moveme_db TABLESPACE source_ts;
+                          ALTER DATABASE moveme_db SET TABLESPACE target_ts;
+                          CREATE DATABASE newdb TEMPLATE template_db;
+                          ALTER DATABASE template_db IS_TEMPLATE = false;
+                          DROP DATABASE dropme_db1;
+                          DROP DATABASE dropme_db2; DROP TABLESPACE dropme_ts2;
+                          DROP TABLESPACE source_ts;
+                          DROP DATABASE template_db;]);
+$node_master->wait_for_catchup($node_standby, 'replay',
+                               $node_master->lsn('replay'));
+$node_standby->stop('immediate');
+
+# Should restart ignoring directory creation error.
+is($node_standby->start(fail_ok => 1), 1);
+
+# TEST 5
+#
+# Ensure that a missing tablespace directory during create database
+# replay immediately causes panic if the standby has already reached
+# consistent state (archive recovery is in progress).
+
+$node_master = PostgreSQL::Test::Cluster->new('master3');
+$node_master->init(allows_streaming => 1);
+$node_master->start;
+
+# Create tablespace
+my $ts_master = PostgreSQL::Test::Utils::tempdir();
+$ts_master = PostgreSQL::Test::Utils::perl2host($ts_master);
+$node_master->safe_psql('postgres', "CREATE TABLESPACE ts1 LOCATION '$ts_master'");
+$node_master->safe_psql('postgres', "CREATE DATABASE db1 TABLESPACE ts1");
+
+my $ts_standby = PostgreSQL::Test::Utils::tempdir("standby");
+$ts_standby = PostgreSQL::Test::Utils::perl2host($ts_standby);
+
+# Take backup
+$backup_name = 'my_backup';
+$node_master->backup($backup_name,
+                     backup_options =>
+                       [ "--tablespace-mapping=$ts_master=$ts_standby" ]);
+$node_standby = PostgreSQL::Test::Cluster->new('standby3');
+$node_standby->init_from_backup($node_master, $backup_name, has_streaming => 1);
+$node_standby->start;
+
+# Make sure standby reached consistency and starts accepting connections
+$node_standby->poll_query_until('postgres', 'SELECT 1', '1');
+
+# Remove standby tablespace directory so it will be missing when
+# replay resumes.
+#
+# The tablespace mapping is lost when the standby node is initialized
+# from basebackup because RecursiveCopy::copypath creates a new temp
+# directory for each tablspace symlink found in backup.  We must
+# obtain the correct tablespace directory by querying standby.
+$ts_standby = $node_standby->safe_psql(
+    'postgres',
+    "select pg_tablespace_location(oid) from pg_tablespace where spcname = 'ts1'");
+rmtree($ts_standby);
+
+# Create a database in the tablespace and a table in default tablespace
+$node_master->safe_psql('postgres',
+                        q[CREATE TABLE should_not_replay_insertion(a int);
+                          CREATE DATABASE db2 WITH TABLESPACE ts1;
+                          INSERT INTO should_not_replay_insertion VALUES (1);]);
+
+# Standby should fail and should not silently skip replaying the wal
+if ($node_master->poll_query_until(
+        'postgres',
+        'SELECT count(*) = 0 FROM pg_stat_replication',
+        't') == 1)
+{
+    pass('standby failed as expected');
+    # We know that the standby has failed.  Setting its pid to
+    # undefined avoids error when PostgreNode module tries to stop the
+    # standby node as part of tear_down sequence.
+    $node_standby->{_pid} = undef;
+}
+else
+{
+    fail('standby did not fail within 5 seconds');
+}
-- 
2.27.0

From 42d379e23f99b91565c24e23073a6da14bf98f19 Mon Sep 17 00:00:00 2001
From: Alvaro Herrera <alvherre@alvh.no-ip.org>
Date: Thu, 9 Jan 2020 17:54:40 -0300
Subject: [PATCH v13 3/3] Fix replay of create database records on standby

Crash recovery on standby may encounter missing directories when
replaying create database WAL records.  Prior to this patch, the
standby would fail to recover in such a case.  However, the
directories could be legitimately missing.  Consider a sequence of WAL
records as follows:

    CREATE DATABASE
    DROP DATABASE
    DROP TABLESPACE

If, after replaying the last WAL record and removing the tablespace
directory, the standby crashes and has to replay the create database
record again, the crash recovery must be able to move on.

This patch adds mechanism similar to invalid page hash table, to track
missing directories during crash recovery.  If all the missing
directory references are matched with corresponding drop records at
the end of crash recovery, the standby can safely enter archive
recovery.

Bug identified by Paul Guo.

Authored by Paul Guo, Kyotaro Horiguchi and Asim R P.
---
 src/backend/access/transam/xlog.c      |   6 +
 src/backend/access/transam/xlogutils.c | 145 +++++++++++++++++++++++++
 src/backend/commands/dbcommands.c      |  55 ++++++++++
 src/backend/commands/tablespace.c      |   5 +
 src/include/access/xlogutils.h         |   4 +
 5 files changed, 215 insertions(+)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 5cda30836f..c6d5fc782f 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -8313,6 +8313,12 @@ CheckRecoveryConsistency(void)
          */
         XLogCheckInvalidPages();
 
+        /*
+         * Check if the XLOG sequence contained any unresolved references to
+         * missing directories.
+         */
+        XLogCheckMissingDirs();
+
         reachedConsistency = true;
         ereport(LOG,
                 (errmsg("consistent recovery state reached at %X/%X",
diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index b33e0531ed..99abf8b2f4 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -79,6 +79,151 @@ typedef struct xl_invalid_page
 
 static HTAB *invalid_page_tab = NULL;
 
+/*
+ * If a create database WAL record is being replayed more than once during
+ * crash recovery on a standby, it is possible that either the tablespace
+ * directory or the template database directory is missing.  This happens when
+ * the directories are removed by replay of subsequent drop records.  Note
+ * that this problem happens only on standby and not on master.  On master, a
+ * checkpoint is created at the end of create database operation. On standby,
+ * however, such a strategy (creating restart points during replay) is not
+ * viable because it will slow down WAL replay.
+ *
+ * The alternative is to track references to each missing directory
+ * encountered when performing crash recovery in the following hash table.
+ * Similar to invalid page table above, the expectation is that each missing
+ * directory entry should be matched with a drop database or drop tablespace
+ * WAL record by the end of crash recovery.
+ */
+typedef struct xl_missing_dir_key
+{
+    Oid spcNode;
+    Oid dbNode;
+} xl_missing_dir_key;
+
+typedef struct xl_missing_dir
+{
+    xl_missing_dir_key key;
+    char path[MAXPGPATH];
+} xl_missing_dir;
+
+static HTAB *missing_dir_tab = NULL;
+
+void
+XLogReportMissingDir(Oid spcNode, Oid dbNode, char *path)
+{
+    xl_missing_dir_key key;
+    bool found;
+    xl_missing_dir *entry;
+
+    /*
+     * Database OID may be invalid but tablespace OID must be valid.  If
+     * dbNode is InvalidOid, we are logging a missing tablespace directory,
+     * otherwise we are logging a missing database directory.
+     */
+    Assert(OidIsValid(spcNode));
+
+    if (missing_dir_tab == NULL)
+    {
+        /* create hash table when first needed */
+        HASHCTL        ctl;
+
+        memset(&ctl, 0, sizeof(ctl));
+        ctl.keysize = sizeof(xl_missing_dir_key);
+        ctl.entrysize = sizeof(xl_missing_dir);
+
+        missing_dir_tab = hash_create("XLOG missing directory table",
+                                       100,
+                                       &ctl,
+                                       HASH_ELEM | HASH_BLOBS);
+    }
+
+    key.spcNode = spcNode;
+    key.dbNode = dbNode;
+
+    entry = hash_search(missing_dir_tab, &key, HASH_ENTER, &found);
+
+    if (found)
+    {
+        if (dbNode == InvalidOid)
+            elog(DEBUG2, "missing directory %s (tablespace %d) already exists: %s",
+                 path, spcNode, entry->path);
+        else
+            elog(DEBUG2, "missing directory %s (tablespace %d database %d) already exists: %s",
+                 path, spcNode, dbNode, entry->path);
+    }
+    else
+    {
+        strlcpy(entry->path, path, sizeof(entry->path));
+        if (dbNode == InvalidOid)
+            elog(DEBUG2, "logged missing dir %s (tablespace %d)",
+                 path, spcNode);
+        else
+            elog(DEBUG2, "logged missing dir %s (tablespace %d database %d)",
+                 path, spcNode, dbNode);
+    }
+}
+
+void
+XLogForgetMissingDir(Oid spcNode, Oid dbNode)
+{
+    xl_missing_dir_key key;
+
+    key.spcNode = spcNode;
+    key.dbNode = dbNode;
+
+    /* Database OID may be invalid but tablespace OID must be valid. */
+    Assert(OidIsValid(spcNode));
+
+    if (missing_dir_tab == NULL)
+        return;
+
+    if (hash_search(missing_dir_tab, &key, HASH_REMOVE, NULL) != NULL)
+    {
+        if (dbNode == InvalidOid)
+        {
+            elog(DEBUG2, "forgot missing dir (tablespace %d)", spcNode);
+        }
+        else
+        {
+            char *path = GetDatabasePath(dbNode, spcNode);
+
+            elog(DEBUG2, "forgot missing dir %s (tablespace %d database %d)",
+                 path, spcNode, dbNode);
+            pfree(path);
+        }
+    }
+}
+
+/*
+ * This is called at the end of crash recovery, before entering archive
+ * recovery on a standby.  PANIC if the hash table is not empty.
+ */
+void
+XLogCheckMissingDirs(void)
+{
+    HASH_SEQ_STATUS status;
+    xl_missing_dir *hentry;
+    bool        foundone = false;
+
+    if (missing_dir_tab == NULL)
+        return;                    /* nothing to do */
+
+    hash_seq_init(&status, missing_dir_tab);
+
+    while ((hentry = (xl_missing_dir *) hash_seq_search(&status)) != NULL)
+    {
+        elog(WARNING, "missing directory \"%s\" tablespace %d database %d",
+             hentry->path, hentry->key.spcNode, hentry->key.dbNode);
+        foundone = true;
+    }
+
+    if (foundone)
+        elog(PANIC, "WAL contains references to missing directories");
+
+    hash_destroy(missing_dir_tab);
+    missing_dir_tab = NULL;
+}
 
 /* Report a reference to an invalid page */
 static void
diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c
index 029fab48df..0f483edb71 100644
--- a/src/backend/commands/dbcommands.c
+++ b/src/backend/commands/dbcommands.c
@@ -2143,7 +2143,9 @@ dbase_redo(XLogReaderState *record)
         xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
         char       *src_path;
         char       *dst_path;
+        char       *parent_path;
         struct stat st;
+        bool        skip = false;
 
         src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
         dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
@@ -2161,6 +2163,55 @@ dbase_redo(XLogReaderState *record)
                         (errmsg("some useless files may be left behind in old database directory \"%s\"",
                                 dst_path)));
         }
+        else if (!reachedConsistency)
+        {
+            /*
+             * It is possible that drop tablespace record appearing later in
+             * the WAL as already been replayed.  That means we are replaying
+             * the create database record second time, as part of crash
+             * recovery.  In that case, the tablespace directory has already
+             * been removed and the create database operation cannot be
+             * replayed.  We should skip the replay but remember the missing
+             * tablespace directory, to be matched with a drop tablespace
+             * record later.
+             */
+            parent_path = pstrdup(dst_path);
+            get_parent_directory(parent_path);
+            if (!(stat(parent_path, &st) == 0 && S_ISDIR(st.st_mode)))
+            {
+                XLogReportMissingDir(xlrec->tablespace_id, InvalidOid, parent_path);
+                skip = true;
+                ereport(WARNING,
+                        (errmsg("skipping create database WAL record"),
+                         errdetail("Target tablespace \"%s\" not found. We "
+                                   "expect to encounter a WAL record that "
+                                   "removes this directory before reaching "
+                                   "consistent state.", parent_path)));
+            }
+            pfree(parent_path);
+        }
+
+        /*
+         * Source directory may be missing.  E.g. the template database used
+         * for creating this database may have been dropped, due to reasons
+         * noted above.  Moving a database from one tablespace may also be a
+         * partner in the crime.
+         */
+        if (!(stat(src_path, &st) == 0 && S_ISDIR(st.st_mode)) &&
+            !reachedConsistency)
+        {
+            XLogReportMissingDir(xlrec->src_tablespace_id, xlrec->src_db_id, src_path);
+            skip = true;
+            ereport(WARNING,
+                    (errmsg("skipping create database WAL record"),
+                     errdetail("Source database \"%s\" not found. We expect "
+                               "to encounter a WAL record that removes this "
+                               "directory before reaching consistent state.",
+                               src_path)));
+        }
+
+        if (skip)
+            return;
 
         /*
          * Force dirty buffers out to disk, to ensure source database is
@@ -2218,6 +2269,10 @@ dbase_redo(XLogReaderState *record)
                 ereport(WARNING,
                         (errmsg("some useless files may be left behind in old database directory \"%s\"",
                                 dst_path)));
+
+            if (!reachedConsistency)
+                XLogForgetMissingDir(xlrec->tablespace_ids[i], xlrec->db_id);
+
             pfree(dst_path);
         }
 
diff --git a/src/backend/commands/tablespace.c b/src/backend/commands/tablespace.c
index 4b96eec9df..0d5dfe007f 100644
--- a/src/backend/commands/tablespace.c
+++ b/src/backend/commands/tablespace.c
@@ -1527,6 +1527,11 @@ tblspc_redo(XLogReaderState *record)
     {
         xl_tblspc_drop_rec *xlrec = (xl_tblspc_drop_rec *) XLogRecGetData(record);
 
+        if (!reachedConsistency)
+            XLogForgetMissingDir(xlrec->ts_id, InvalidOid);
+
+        XLogFlush(record->EndRecPtr);
+
         /*
          * If we issued a WAL record for a drop tablespace it implies that
          * there were no files in it at all when the DROP was done. That means
diff --git a/src/include/access/xlogutils.h b/src/include/access/xlogutils.h
index eebc91f3a5..3341efc052 100644
--- a/src/include/access/xlogutils.h
+++ b/src/include/access/xlogutils.h
@@ -65,6 +65,10 @@ extern void XLogDropDatabase(Oid dbid);
 extern void XLogTruncateRelation(RelFileNode rnode, ForkNumber forkNum,
                                  BlockNumber nblocks);
 
+extern void XLogReportMissingDir(Oid spcNode, Oid dbNode, char *path);
+extern void XLogForgetMissingDir(Oid spcNode, Oid dbNode);
+extern void XLogCheckMissingDirs(void);
+
 /* Result codes for XLogReadBufferForRedo[Extended] */
 typedef enum
 {
-- 
2.27.0


В списке pgsql-hackers по дате отправления:

Предыдущее
От: Abhijit Menon-Sen
Дата:
Сообщение: Re: SSL compression
Следующее
От: Dinesh Chemuduru
Дата:
Сообщение: Re: [PROPOSAL] new diagnostic items for the dynamic sql