From 2eaa301f054dd3a4d9cd2a236b40693969cbc983 Mon Sep 17 00:00:00 2001 From: Jan Nidzwetzki Date: Fri, 4 Dec 2026 14:32:58 +0100 Subject: [PATCH v1 4/4] Make file copies of databases atomic and keep them during replay CREATE DATABASE with STRATEGY file_copy and ALTER DATABASE SET TABLESPACE log a record that instructs replay to copy a directory, and replay copies whatever is in the source at that moment. It also removes any existing target first, since it cannot distinguish a partial copy from the database itself. If recovery starts before the record on a data directory that is newer, replay replaces the database with a copy of the source in its later state. The database then contains changes that were made to the source after the command. Copy the files into a temporary directory located next to the target, and rename it once the copy is complete. The name begins with pgsql_tmp, so base backups and pg_rewind skip this directory, and it is removed at startup. A database directory is now either absent or complete, so replay can keep an existing directory before consistency is reached, whether the source is still present or not. Two cases remain. If a base backup copied the source after the command but does not include the target, replay still copies the source in its later state. This is the case described in the backup documentation. The same applies if a database directory is dropped and created again with the same OID within the WAL range that is replayed twice. Reported-by: Michael Malis Discussion: https://postgr.es/m/CANVD+MB_JL5ydxD8NUUGJsdEGB1+nW56-PnS8QTfUtW+w_V9+A@mail.gmail.com --- src/backend/commands/dbcommands.c | 125 +++++++++++++++----- src/backend/storage/file/fd.c | 17 +++ src/bin/pg_rewind/t/002_databases.pl | 11 ++ src/include/common/file_utils.h | 1 + src/test/recovery/t/033_replay_tsp_drops.pl | 18 +++ 5 files changed, 141 insertions(+), 31 deletions(-) diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c index 5bfd72b22ec..92c4a4c9f44 100644 --- a/src/backend/commands/dbcommands.c +++ b/src/backend/commands/dbcommands.c @@ -50,6 +50,7 @@ #include "commands/seclabel.h" #include "commands/tablespace.h" #include "common/file_perm.h" +#include "common/file_utils.h" #include "mb/pg_wchar.h" #include "miscadmin.h" #include "pgstat.h" @@ -144,6 +145,10 @@ static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid); static void recovery_create_dbdir(char *path, bool only_tblspc); +static char *database_copy_temp_path(const char *dst_path); +static void copy_database_directory(const char *src_path, + const char *dst_path); +static void remove_database_copy_temp(const char *dst_path); /* * Create a new database using the WAL_LOG strategy. @@ -646,12 +651,8 @@ CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid, dstpath = GetDatabasePath(dst_dboid, dsttablespace); - /* - * Copy this subdirectory to the new location - * - * We don't need to copy subdirectories - */ - copydir(srcpath, dstpath, false); + /* Copy this subdirectory to the new location */ + copy_database_directory(srcpath, dstpath); /* Record the filesystem change in XLOG */ { @@ -2263,7 +2264,7 @@ movedb(const char *dbname, const char *tblspcname) /* * Copy files from the old tablespace to the new one */ - copydir(src_dbpath, dst_dbpath, false); + copy_database_directory(src_dbpath, dst_dbpath); /* * Record the filesystem change in XLOG @@ -2398,6 +2399,7 @@ movedb_failure_callback(int code, Datum arg) /* Get rid of anything we managed to copy to the target directory */ dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid); + remove_database_copy_temp(dstpath); (void) rmtree(dstpath, true); pfree(dstpath); @@ -3095,6 +3097,8 @@ remove_dbtablespaces(Oid db_id) dstpath = GetDatabasePath(db_id, dsttablespace); + remove_database_copy_temp(dstpath); + if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode)) { /* Assume we can ignore it */ @@ -3308,6 +3312,74 @@ database_is_invalid_oid(Oid dboid) } +/* + * Name of the temporary directory used to create database directory dst_path. + * + * It is next to dst_path, so that it can be renamed. The name starts with the + * prefix of temporary files, which base backups and pg_rewind skip. + */ +static char * +database_copy_temp_path(const char *dst_path) +{ + const char *sep = last_dir_separator(dst_path); + + Assert(sep != NULL); + + return psprintf("%.*s/%s%s", (int) (sep - dst_path), dst_path, + PG_TEMP_DBCOPY_PREFIX, sep + 1); +} + +/* + * Copy database directory src_path to dst_path, which must not exist. + * + * The files are copied to a temporary directory, which is renamed when the + * copy is complete. A database directory therefore never has a part of its + * files only, which replay of XLOG_DBASE_CREATE_FILE_COPY relies on. + */ +static void +copy_database_directory(const char *src_path, const char *dst_path) +{ + char *tmp_path = database_copy_temp_path(dst_path); + char *parent_path; + + /* Remove what an earlier attempt has left behind */ + remove_database_copy_temp(dst_path); + + /* We don't need to copy subdirectories */ + copydir(src_path, tmp_path, false); + + if (rename(tmp_path, dst_path) < 0) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not rename file \"%s\" to \"%s\": %m", + tmp_path, dst_path))); + + parent_path = pstrdup(dst_path); + get_parent_directory(parent_path); + fsync_fname(parent_path, true); + + pfree(parent_path); + pfree(tmp_path); +} + +/* + * Remove the temporary directory of copy_database_directory(), if any. + */ +static void +remove_database_copy_temp(const char *dst_path) +{ + char *tmp_path = database_copy_temp_path(dst_path); + struct stat st; + + if (lstat(tmp_path, &st) == 0 && S_ISDIR(st.st_mode) && + !rmtree(tmp_path, true)) + ereport(WARNING, + (errmsg("some useless files may be left behind in old database directory \"%s\"", + tmp_path))); + + pfree(tmp_path); +} + /* * recovery_create_dbdir() * @@ -3377,35 +3449,30 @@ dbase_redo(XLogReaderState *record) * removing the target, as it fails once consistency is reached. */ if (stat(src_path, &st) < 0 && errno == ENOENT) - { recovery_create_dbdir(src_path, false); + if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode)) + { /* - * A target that exists is then the only copy of the database. - * Keep it instead of replacing it with an empty directory. + * Before consistency is reached, the data directory can be newer + * than this record. A target that exists is then the complete + * database, see copy_database_directory(), in a state no older + * than this record. Keep it: the source may have changed or been + * dropped since, so copying it again would not give the same + * database. */ - if (!reachedConsistency && - stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode) && - !directory_is_empty(dst_path)) + if (!reachedConsistency && !directory_is_empty(dst_path)) { - elog(DEBUG1, - "keeping database directory \"%s\" because source directory \"%s\" was missing", - dst_path, src_path); + elog(DEBUG1, "keeping existing database directory \"%s\"", + dst_path); pfree(src_path); pfree(dst_path); return; } - } - /* - * Our theory for replaying a CREATE is to forcibly drop the target - * subdirectory if present, then re-copy the source data. This may be - * more work than needed, but it is simple to implement. - */ - if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode)) - { + /* Otherwise it is a leftover, which is in the way of the copy */ if (!rmtree(dst_path, true)) - /* If this failed, copydir() below is going to error. */ + /* If this failed, the copy below is going to error. */ ereport(WARNING, (errmsg("some useless files may be left behind in old database directory \"%s\"", dst_path))); @@ -3438,12 +3505,8 @@ dbase_redo(XLogReaderState *record) /* Close all smgr fds in all backends. */ WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_SMGRRELEASE)); - /* - * Copy this subdirectory to the new location - * - * We don't need to copy subdirectories - */ - copydir(src_path, dst_path, false); + /* Copy this subdirectory to the new location */ + copy_database_directory(src_path, dst_path); pfree(src_path); pfree(dst_path); diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 443a5dd8f23..6806cb40729 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -3451,6 +3451,23 @@ RemovePgTempRelationFiles(const char *tsdirname) while ((de = ReadDirExtended(ts_dir, tsdirname, LOG)) != NULL) { + /* Remove what an interrupted copy of a database has left behind */ + if (strncmp(de->d_name, + PG_TEMP_DBCOPY_PREFIX, + strlen(PG_TEMP_DBCOPY_PREFIX)) == 0) + { + snprintf(dbspace_path, sizeof(dbspace_path), "%s/%s", + tsdirname, de->d_name); + RemovePgTempFilesInDir(dbspace_path, false, true); + + if (rmdir(dbspace_path) < 0) + ereport(LOG, + (errcode_for_file_access(), + errmsg("could not remove directory \"%s\": %m", + dbspace_path))); + continue; + } + /* * We're only interested in the per-database directories, which have * numeric names. Note that this code will also (properly) ignore "." diff --git a/src/bin/pg_rewind/t/002_databases.pl b/src/bin/pg_rewind/t/002_databases.pl index b25e7621222..34d87dd91b6 100644 --- a/src/bin/pg_rewind/t/002_databases.pl +++ b/src/bin/pg_rewind/t/002_databases.pl @@ -58,6 +58,12 @@ sub run_test standby_psql('DROP DATABASE tmpl'); standby_psql('ALTER DATABASE moved SET TABLESPACE ts'); + # Change the source of a copy afterwards, the copy must not get the change. + standby_psql( + 'CREATE DATABASE copied TEMPLATE inprimary STRATEGY file_copy'); + standby_psql('INSERT INTO inprimary_tab VALUES (1)', 'inprimary'); + standby_psql('CHECKPOINT'); + # The clusters are now diverged. RewindTest::run_pg_rewind($test_mode); @@ -67,6 +73,7 @@ sub run_test 'SELECT datname FROM pg_database ORDER BY 1', qq(beforepromotion cloned +copied inprimary moved postgres @@ -80,6 +87,10 @@ template1 '1', 'cloned database is intact'); is($node_primary->safe_psql('moved', 'SELECT a FROM moved_tab'), '1', 'moved database is intact'); + is( $node_primary->safe_psql( + 'copied', 'SELECT count(*) FROM inprimary_tab'), + '0', + 'copied database has no later changes'); # Permissions on PGDATA should have group permissions SKIP: diff --git a/src/include/common/file_utils.h b/src/include/common/file_utils.h index d6415424b60..94ed57c6a42 100644 --- a/src/include/common/file_utils.h +++ b/src/include/common/file_utils.h @@ -62,5 +62,6 @@ extern ssize_t pg_pwrite_zeros(int fd, size_t size, pgoff_t offset); /* Filename components */ #define PG_TEMP_FILES_DIR "pgsql_tmp" #define PG_TEMP_FILE_PREFIX "pgsql_tmp" +#define PG_TEMP_DBCOPY_PREFIX PG_TEMP_FILE_PREFIX "_dbcopy_" #endif /* FILE_UTILS_H */ diff --git a/src/test/recovery/t/033_replay_tsp_drops.pl b/src/test/recovery/t/033_replay_tsp_drops.pl index 36bc6df3bb7..087eac1aa4b 100644 --- a/src/test/recovery/t/033_replay_tsp_drops.pl +++ b/src/test/recovery/t/033_replay_tsp_drops.pl @@ -27,10 +27,12 @@ sub test_tablespace CREATE TABLESPACE source_ts LOCATION ''; CREATE TABLESPACE target_ts LOCATION ''; CREATE DATABASE template_db IS_TEMPLATE = true; + CREATE DATABASE source_db; SELECT pg_create_physical_replication_slot('slot', true); ]); $node_primary->safe_psql('template_db', 'CREATE TABLE tt AS SELECT 1 AS a'); + $node_primary->safe_psql('source_db', 'CREATE TABLE tt AS SELECT 1 AS a'); my $backup_name = 'my_backup'; $node_primary->backup($backup_name); @@ -65,6 +67,14 @@ sub test_tablespace $query =~ s//$strategy/g; $node_primary->safe_psql('postgres', $query); + + # Copy a database, and change the source afterwards. Replay of the + # second copy writes the change to disk in the standby. + $node_primary->safe_psql('postgres', + "CREATE DATABASE copy_db1 TEMPLATE source_db STRATEGY=$strategy"); + $node_primary->safe_psql('source_db', 'INSERT INTO tt VALUES (2)'); + $node_primary->safe_psql('postgres', + "CREATE DATABASE copy_db2 TEMPLATE source_db STRATEGY=$strategy"); $node_primary->wait_for_catchup($node_standby, 'replay'); # show "create missing directory" log message @@ -81,6 +91,8 @@ sub test_tablespace '1', "copied database is intact for $strategy"); is($node_standby->safe_psql('moveme_db', 'SELECT 1'), '1', "moved database is intact for $strategy"); + is($node_standby->safe_psql('copy_db1', 'SELECT count(*) FROM tt'), + '1', "copied database has no later changes for $strategy"); $node_standby->stop('immediate'); } @@ -113,7 +125,13 @@ $node_standby->init_from_backup($node_primary, $backup_name, has_streaming => 1); $node_standby->append_conf('postgresql.conf', "allow_in_place_tablespaces = on"); + +# A leftover of an interrupted database copy is removed at startup. +my $tmpdir = $node_standby->data_dir . '/base/pgsql_tmp_dbcopy_99999'; +mkdir($tmpdir) or die "could not create directory $tmpdir: $!"; +append_to_file("$tmpdir/1", ''); $node_standby->start; +ok(!-e $tmpdir, 'leftover of a database copy is removed'); # Make sure standby reached consistency and starts accepting connections $node_standby->poll_query_until('postgres', 'SELECT 1', '1'); -- 2.47.3