1
0
mirror of https://github.com/postgres/postgres.git synced 2025-06-14 18:42:34 +03:00

Handle interleavings between CREATE DATABASE steps and base backup.

Restoring a base backup taken in the middle of CreateDirAndVersionFile()
or write_relmap_file() would lose the function's effects.  The symptom
was absence of the database directory, PG_VERSION file, or
pg_filenode.map.  If missing the directory, recovery would fail.  Either
missing file would not fail recovery but would render the new database
unusable.  Fix CreateDirAndVersionFile() with the transam/README "action
first and then write a WAL entry" strategy.  That has a side benefit of
moving filesystem mutations out of a critical section, reducing the ways
to PANIC.  Fix the write_relmap_file() call with a lock acquisition, so
it interacts with checkpoints like non-CREATE DATABASE calls do.
Back-patch to v15, where commit 9c08aea6a3
introduced STRATEGY=WAL_LOG and made it the default.

Discussion: https://postgr.es/m/20240130195003.0a.nmisch@google.com
This commit is contained in:
Noah Misch
2024-02-01 13:44:19 -08:00
parent 272a7c3034
commit df220714e5
2 changed files with 32 additions and 28 deletions

View File

@ -462,35 +462,12 @@ CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
char buf[16];
/*
* Prepare version data before starting a critical section.
*
* Note that we don't have to copy this from the source database; there's
* only one legal value.
* Note that we don't have to copy version data from the source database;
* there's only one legal value.
*/
sprintf(buf, "%s\n", PG_MAJORVERSION);
nbytes = strlen(PG_MAJORVERSION) + 1;
/* If we are not in WAL replay then write the WAL. */
if (!isRedo)
{
xl_dbase_create_wal_log_rec xlrec;
XLogRecPtr lsn;
START_CRIT_SECTION();
xlrec.db_id = dbid;
xlrec.tablespace_id = tsid;
XLogBeginInsert();
XLogRegisterData((char *) (&xlrec),
sizeof(xl_dbase_create_wal_log_rec));
lsn = XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
/* As always, WAL must hit the disk before the data update does. */
XLogFlush(lsn);
}
/* Create database directory. */
if (MakePGDirectory(dbpath) < 0)
{
@ -534,9 +511,24 @@ CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
/* Close the version file. */
CloseTransientFile(fd);
/* Critical section done. */
/* If we are not in WAL replay then write the WAL. */
if (!isRedo)
{
xl_dbase_create_wal_log_rec xlrec;
START_CRIT_SECTION();
xlrec.db_id = dbid;
xlrec.tablespace_id = tsid;
XLogBeginInsert();
XLogRegisterData((char *) (&xlrec),
sizeof(xl_dbase_create_wal_log_rec));
(void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
END_CRIT_SECTION();
}
}
/*