Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6d20f8c

Browse files
committed
Fix replay of create database records on standby
Crash recovery on standby may encounter missing directorieswhen replaying database-creation WAL records. Prior to thispatch, the standby would fail to recover in such a case;however, the directories could be legitimately missing.Consider the following sequence of commands: CREATE DATABASE DROP DATABASE DROP TABLESPACEIf, after replaying the last WAL record and removing thetablespace directory, the standby crashes and has to replay thecreate database record again, crash recovery must be able to continue.A fix for this problem was already attempted in49d9cfc, but itwas reverted because of design issues. This new version is basedon Robert Haas' proposal: any missing tablespaces are createdduring recovery before reaching consistency. Tablespacesare created as real directories, and should be deletedby later replay. CheckRecoveryConsistency ensuresthey have disappeared.The problems detected by this new code are reported as PANIC,except when allow_in_place_tablespaces is set to ON, in whichcase they are WARNING. Apart from making tests possible, thisgives users an escape hatch in case things don't go as planned.Author: Kyotaro Horiguchi <horikyota.ntt@gmail.com>Author: Asim R Praveen <apraveen@pivotal.io>Author: Paul Guo <paulguo@gmail.com>Reviewed-by: Anastasia Lubennikova <lubennikovaav@gmail.com> (older versions)Reviewed-by: Fujii Masao <masao.fujii@oss.nttdata.com> (older versions)Reviewed-by: Michaël Paquier <michael@paquier.xyz>Diagnosed-by: Paul Guo <paulguo@gmail.com>Discussion:https://postgr.es/m/CAEET0ZGx9AvioViLf7nbR_8tH9-=27DN5xWJ2P9-ROH16e4JUA@mail.gmail.com
1 parentca347f5 commit6d20f8c

File tree

4 files changed

+302
-31
lines changed

4 files changed

+302
-31
lines changed

‎src/backend/access/transam/xlog.c

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7936,6 +7936,59 @@ StartupXLOG(void)
79367936
RequestCheckpoint(CHECKPOINT_FORCE);
79377937
}
79387938

7939+
/*
7940+
* Verify that, in non-test mode, ./pg_tblspc doesn't contain any real
7941+
* directories.
7942+
*
7943+
* Replay of database creation XLOG records for databases that were later
7944+
* dropped can create fake directories in pg_tblspc. By the time consistency
7945+
* is reached these directories should have been removed; here we verify
7946+
* that this did indeed happen. This is to be called at the point where
7947+
* consistent state is reached.
7948+
*
7949+
* allow_in_place_tablespaces turns the PANIC into a WARNING, which is
7950+
* useful for testing purposes, and also allows for an escape hatch in case
7951+
* things go south.
7952+
*/
7953+
staticvoid
7954+
CheckTablespaceDirectory(void)
7955+
{
7956+
DIR*dir;
7957+
structdirent*de;
7958+
7959+
dir=AllocateDir("pg_tblspc");
7960+
while ((de=ReadDir(dir,"pg_tblspc"))!=NULL)
7961+
{
7962+
charpath[MAXPGPATH+10];
7963+
#ifndefWIN32
7964+
structstatst;
7965+
#endif
7966+
7967+
/* Skip entries of non-oid names */
7968+
if (strspn(de->d_name,"0123456789")!=strlen(de->d_name))
7969+
continue;
7970+
7971+
snprintf(path,sizeof(path),"pg_tblspc/%s",de->d_name);
7972+
7973+
#ifndefWIN32
7974+
if (lstat(path,&st)<0)
7975+
ereport(LOG,
7976+
(errcode_for_file_access(),
7977+
errmsg("could not stat file \"%s\": %m",
7978+
path)));
7979+
elseif (!S_ISLNK(st.st_mode))
7980+
#else/* WIN32 */
7981+
if (!pgwin32_is_junction(path))
7982+
#endif
7983+
ereport(allow_in_place_tablespaces ?WARNING :PANIC,
7984+
(errcode(ERRCODE_DATA_CORRUPTED),
7985+
errmsg("unexpected directory entry \"%s\" found in %s",
7986+
de->d_name,"pg_tblspc/"),
7987+
errdetail("All directory entries in pg_tblspc/ should be symbolic links."),
7988+
errhint("Remove those directories, or set allow_in_place_tablespaces to ON transiently to let recovery complete.")));
7989+
}
7990+
}
7991+
79397992
/*
79407993
* Checks if recovery has reached a consistent state. When consistency is
79417994
* reached and we have a valid starting standby snapshot, tell postmaster
@@ -8006,6 +8059,14 @@ CheckRecoveryConsistency(void)
80068059
*/
80078060
XLogCheckInvalidPages();
80088061

8062+
/*
8063+
* Check that pg_tblspc doesn't contain any real directories. Replay
8064+
* of Database/CREATE_* records may have created ficticious tablespace
8065+
* directories that should have been removed by the time consistency
8066+
* was reached.
8067+
*/
8068+
CheckTablespaceDirectory();
8069+
80098070
reachedConsistency= true;
80108071
ereport(LOG,
80118072
(errmsg("consistent recovery state reached at %X/%X",

‎src/backend/commands/dbcommands.c

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
#include"commands/defrem.h"
4646
#include"commands/seclabel.h"
4747
#include"commands/tablespace.h"
48+
#include"common/file_perm.h"
4849
#include"mb/pg_wchar.h"
4950
#include"miscadmin.h"
5051
#include"pgstat.h"
@@ -2092,6 +2093,45 @@ get_database_name(Oid dbid)
20922093
returnresult;
20932094
}
20942095

2096+
/*
2097+
* recovery_create_dbdir()
2098+
*
2099+
* During recovery, there's a case where we validly need to recover a missing
2100+
* tablespace directory so that recovery can continue. This happens when
2101+
* recovery wants to create a database but the holding tablespace has been
2102+
* removed before the server stopped. Since we expect that the directory will
2103+
* be gone before reaching recovery consistency, and we have no knowledge about
2104+
* the tablespace other than its OID here, we create a real directory under
2105+
* pg_tblspc here instead of restoring the symlink.
2106+
*
2107+
* If only_tblspc is true, then the requested directory must be in pg_tblspc/
2108+
*/
2109+
staticvoid
2110+
recovery_create_dbdir(char*path,boolonly_tblspc)
2111+
{
2112+
structstatst;
2113+
2114+
Assert(RecoveryInProgress());
2115+
2116+
if (stat(path,&st)==0)
2117+
return;
2118+
2119+
if (only_tblspc&&strstr(path,"pg_tblspc/")==NULL)
2120+
elog(PANIC,"requested to created invalid directory: %s",path);
2121+
2122+
if (reachedConsistency&& !allow_in_place_tablespaces)
2123+
ereport(PANIC,
2124+
errmsg("missing directory \"%s\"",path));
2125+
2126+
elog(reachedConsistency ?WARNING :DEBUG1,
2127+
"creating missing directory: %s",path);
2128+
2129+
if (pg_mkdir_p(path,pg_dir_create_mode)!=0)
2130+
ereport(PANIC,
2131+
errmsg("could not create missing directory \"%s\": %m",path));
2132+
}
2133+
2134+
20952135
/*
20962136
* DATABASE resource manager's routines
20972137
*/
@@ -2108,6 +2148,7 @@ dbase_redo(XLogReaderState *record)
21082148
xl_dbase_create_rec*xlrec= (xl_dbase_create_rec*)XLogRecGetData(record);
21092149
char*src_path;
21102150
char*dst_path;
2151+
char*parent_path;
21112152
structstatst;
21122153

21132154
src_path=GetDatabasePath(xlrec->src_db_id,xlrec->src_tablespace_id);
@@ -2127,6 +2168,34 @@ dbase_redo(XLogReaderState *record)
21272168
dst_path)));
21282169
}
21292170

2171+
/*
2172+
* If the parent of the target path doesn't exist, create it now. This
2173+
* enables us to create the target underneath later. Note that if
2174+
* the database dir is not in a tablespace, the parent will always
2175+
* exist, so this never runs in that case.
2176+
*/
2177+
parent_path=pstrdup(dst_path);
2178+
get_parent_directory(parent_path);
2179+
if (stat(parent_path,&st)<0)
2180+
{
2181+
if (errno!=ENOENT)
2182+
ereport(FATAL,
2183+
errmsg("could not stat directory \"%s\": %m",
2184+
dst_path));
2185+
2186+
recovery_create_dbdir(parent_path, true);
2187+
}
2188+
pfree(parent_path);
2189+
2190+
/*
2191+
* There's a case where the copy source directory is missing for the
2192+
* same reason above. Create the emtpy source directory so that
2193+
* copydir below doesn't fail. The directory will be dropped soon by
2194+
* recovery.
2195+
*/
2196+
if (stat(src_path,&st)<0&&errno==ENOENT)
2197+
recovery_create_dbdir(src_path, false);
2198+
21302199
/*
21312200
* Force dirty buffers out to disk, to ensure source database is
21322201
* up-to-date for the copy.

‎src/backend/commands/tablespace.c

Lines changed: 9 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,6 @@ TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
155155
/* Directory creation failed? */
156156
if (MakePGDirectory(dir)<0)
157157
{
158-
char*parentdir;
159-
160158
/* Failure other than not exists or not in WAL replay? */
161159
if (errno!=ENOENT|| !isRedo)
162160
ereport(ERROR,
@@ -165,36 +163,16 @@ TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
165163
dir)));
166164

167165
/*
168-
* Parent directories are missing during WAL replay, so
169-
* continue by creating simple parent directories rather
170-
* than a symlink.
166+
* During WAL replay, it's conceivable that several levels
167+
* of directories are missing if tablespaces are dropped
168+
* further ahead of the WAL stream than we're currently
169+
* replaying. An easy way forward is to create them as
170+
* plain directories and hope they are removed by further
171+
* WAL replay if necessary. If this also fails, there is
172+
* trouble we cannot get out of, so just report that and
173+
* bail out.
171174
*/
172-
173-
/* create two parents up if not exist */
174-
parentdir=pstrdup(dir);
175-
get_parent_directory(parentdir);
176-
get_parent_directory(parentdir);
177-
/* Can't create parent and it doesn't already exist? */
178-
if (MakePGDirectory(parentdir)<0&&errno!=EEXIST)
179-
ereport(ERROR,
180-
(errcode_for_file_access(),
181-
errmsg("could not create directory \"%s\": %m",
182-
parentdir)));
183-
pfree(parentdir);
184-
185-
/* create one parent up if not exist */
186-
parentdir=pstrdup(dir);
187-
get_parent_directory(parentdir);
188-
/* Can't create parent and it doesn't already exist? */
189-
if (MakePGDirectory(parentdir)<0&&errno!=EEXIST)
190-
ereport(ERROR,
191-
(errcode_for_file_access(),
192-
errmsg("could not create directory \"%s\": %m",
193-
parentdir)));
194-
pfree(parentdir);
195-
196-
/* Create database directory */
197-
if (MakePGDirectory(dir)<0)
175+
if (pg_mkdir_p(dir,pg_dir_create_mode)<0)
198176
ereport(ERROR,
199177
(errcode_for_file_access(),
200178
errmsg("could not create directory \"%s\": %m",
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
2+
# Copyright (c) 2021-2022, PostgreSQL Global Development Group
3+
4+
# Test replay of tablespace/database creation/drop
5+
6+
use strict;
7+
use warnings;
8+
9+
use PostgreSQL::Test::Cluster;
10+
use PostgreSQL::Test::Utils;
11+
use Test::More;
12+
13+
subtest_tablespace
14+
{
15+
my$node_primary = PostgreSQL::Test::Cluster->new("primary1");
16+
$node_primary->init(allows_streaming=> 1);
17+
$node_primary->start;
18+
$node_primary->psql(
19+
'postgres',
20+
qq[
21+
SET allow_in_place_tablespaces=on;
22+
CREATE TABLESPACE dropme_ts1 LOCATION '';
23+
CREATE TABLESPACE dropme_ts2 LOCATION '';
24+
CREATE TABLESPACE source_ts LOCATION '';
25+
CREATE TABLESPACE target_ts LOCATION '';
26+
CREATE DATABASE template_db IS_TEMPLATE = true;
27+
]);
28+
my$backup_name ='my_backup';
29+
$node_primary->backup($backup_name);
30+
31+
my$node_standby = PostgreSQL::Test::Cluster->new("standby2");
32+
$node_standby->init_from_backup($node_primary,$backup_name,
33+
has_streaming=> 1);
34+
$node_standby->append_conf('postgresql.conf',
35+
"allow_in_place_tablespaces = on");
36+
$node_standby->start;
37+
38+
# Make sure connection is made
39+
$node_primary->poll_query_until('postgres',
40+
'SELECT count(*) = 1 FROM pg_stat_replication');
41+
42+
$node_standby->safe_psql('postgres','CHECKPOINT');
43+
44+
# Do immediate shutdown just after a sequence of CREAT DATABASE / DROP
45+
# DATABASE / DROP TABLESPACE. This causes CREATE DATABASE WAL records
46+
# to be applied to already-removed directories.
47+
my$query =q[
48+
CREATE DATABASE dropme_db1 WITH TABLESPACE dropme_ts1;
49+
CREATE TABLE t (a int) TABLESPACE dropme_ts2;
50+
CREATE DATABASE dropme_db2 WITH TABLESPACE dropme_ts2;
51+
CREATE DATABASE moveme_db TABLESPACE source_ts;
52+
ALTER DATABASE moveme_db SET TABLESPACE target_ts;
53+
CREATE DATABASE newdb TEMPLATE template_db;
54+
ALTER DATABASE template_db IS_TEMPLATE = false;
55+
DROP DATABASE dropme_db1;
56+
DROP TABLE t;
57+
DROP DATABASE dropme_db2; DROP TABLESPACE dropme_ts2;
58+
DROP TABLESPACE source_ts;
59+
DROP DATABASE template_db;
60+
];
61+
62+
$node_primary->safe_psql('postgres',$query);
63+
$node_primary->wait_for_catchup($node_standby,'replay',
64+
$node_primary->lsn('write'));
65+
66+
# show "create missing directory" log message
67+
$node_standby->safe_psql('postgres',
68+
"ALTER SYSTEM SET log_min_messages TO debug1;");
69+
$node_standby->stop('immediate');
70+
# Should restart ignoring directory creation error.
71+
is($node_standby->start(fail_ok=> 1), 1,"standby node started");
72+
$node_standby->stop('immediate');
73+
}
74+
75+
test_tablespace();
76+
77+
# Ensure that a missing tablespace directory during create database
78+
# replay immediately causes panic if the standby has already reached
79+
# consistent state (archive recovery is in progress).
80+
81+
my$node_primary = PostgreSQL::Test::Cluster->new('primary2');
82+
$node_primary->init(allows_streaming=> 1);
83+
$node_primary->start;
84+
85+
# Create tablespace
86+
$node_primary->safe_psql(
87+
'postgres',q[
88+
SET allow_in_place_tablespaces=on;
89+
CREATE TABLESPACE ts1 LOCATION ''
90+
]);
91+
$node_primary->safe_psql('postgres',
92+
"CREATE DATABASE db1 WITH TABLESPACE ts1");
93+
94+
# Take backup
95+
my$backup_name ='my_backup';
96+
$node_primary->backup($backup_name);
97+
my$node_standby = PostgreSQL::Test::Cluster->new('standby3');
98+
$node_standby->init_from_backup($node_primary,$backup_name,
99+
has_streaming=> 1);
100+
$node_standby->append_conf('postgresql.conf',
101+
"allow_in_place_tablespaces = on");
102+
$node_standby->start;
103+
104+
# Make sure standby reached consistency and starts accepting connections
105+
$node_standby->poll_query_until('postgres','SELECT 1','1');
106+
107+
# Remove standby tablespace directory so it will be missing when
108+
# replay resumes.
109+
my$tspoid =$node_standby->safe_psql('postgres',
110+
"SELECT oid FROM pg_tablespace WHERE spcname = 'ts1';");
111+
my$tspdir =$node_standby->data_dir ."/pg_tblspc/$tspoid";
112+
File::Path::rmtree($tspdir);
113+
114+
my$logstart = get_log_size($node_standby);
115+
116+
# Create a database in the tablespace and a table in default tablespace
117+
$node_primary->safe_psql(
118+
'postgres',
119+
q[
120+
CREATE TABLE should_not_replay_insertion(a int);
121+
CREATE DATABASE db2 WITH TABLESPACE ts1;
122+
INSERT INTO should_not_replay_insertion VALUES (1);
123+
]);
124+
125+
# Standby should fail and should not silently skip replaying the wal
126+
# In this test, PANIC turns into WARNING by allow_in_place_tablespaces.
127+
# Check the log messages instead of confirming standby failure.
128+
my$max_attempts =$PostgreSQL::Test::Utils::timeout_default;
129+
while ($max_attempts-- >= 0)
130+
{
131+
last
132+
if (
133+
find_in_log(
134+
$node_standby,"WARNING: creating missing directory: pg_tblspc/",
135+
$logstart));
136+
sleep 1;
137+
}
138+
ok($max_attempts > 0,"invalid directory creation is detected");
139+
140+
done_testing();
141+
142+
143+
# return the size of logfile of $node in bytes
144+
subget_log_size
145+
{
146+
my ($node) =@_;
147+
148+
return (stat$node->logfile)[7];
149+
}
150+
151+
# find $pat in logfile of $node after $off-th byte
152+
subfind_in_log
153+
{
154+
my ($node,$pat,$off) =@_;
155+
156+
$off = 0unlessdefined$off;
157+
my$log = PostgreSQL::Test::Utils::slurp_file($node->logfile);
158+
return 0if (length($log) <=$off);
159+
160+
$log =substr($log,$off);
161+
162+
return$log =~m/$pat/;
163+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp