Skip to content

Commit 43d4dd8

Browse files
committed
psql: Make cancel test more timing robust
The previous coding relied on the PID file appearing and the query starting "fast enough", which can fail on slow machines. Also, there might have been an undocumented interference between alarm and IPC::Run. This new coding doesn't rely on any of these concurrency mechanisms. Instead, we wait unitl the PID file is complete before proceeding, and then also wait until the sleep query is registered by the server. Discussion: https://www.postgresql.org/message-id/flat/E1mH14Q-0002gh-HS%40gemulon.postgresql.org
1 parent bb9ff46 commit 43d4dd8

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

src/bin/psql/t/020_cancel.pl

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PostgresNode;
88
use TestLib;
99
use Test::More tests => 2;
10+
use Time::HiRes qw(usleep);
1011

1112
my $tempdir = TestLib::tempdir;
1213

@@ -28,19 +29,37 @@
2829
my ($stdin, $stdout, $stderr);
2930

3031
# Test whether shell supports $PPID. It's part of POSIX, but some
31-
# pre-/non-POSIX shells don't support it (e.g., NetBSD, Solaris).
32+
# pre-/non-POSIX shells don't support it (e.g., NetBSD).
3233
$stdin = "\\! echo \$PPID";
3334
IPC::Run::run(['psql', '-X', '-v', 'ON_ERROR_STOP=1'], '<', \$stdin, '>', \$stdout, '2>', \$stderr);
3435
$stdout =~ /^\d+$/ or skip "shell apparently does not support \$PPID", 2;
3536

36-
local $SIG{ALRM} = sub {
37-
my $psql_pid = TestLib::slurp_file("$tempdir/psql.pid");
38-
kill 'INT', $psql_pid;
39-
};
40-
alarm 1;
37+
# Now start the real test
38+
my $h = IPC::Run::start(['psql', '-X', '-v', 'ON_ERROR_STOP=1'], \$stdin, \$stdout, \$stderr);
4139

42-
$stdin = "\\! echo \$PPID >$tempdir/psql.pid\nselect pg_sleep(3);";
43-
my $result = IPC::Run::run(['psql', '-X', '-v', 'ON_ERROR_STOP=1'], '<', \$stdin, '>', \$stdout, '2>', \$stderr);
40+
# Get the PID
41+
$stdout = '';
42+
$stderr = '';
43+
$stdin = "\\! echo \$PPID >$tempdir/psql.pid\n";
44+
pump $h while length $stdin;
45+
my $count;
46+
my $psql_pid;
47+
until (-s "$tempdir/psql.pid" and ($psql_pid = TestLib::slurp_file("$tempdir/psql.pid")) =~ /^\d+\n/s)
48+
{
49+
($count++ < 180 * 100) or die "pid file did not appear";
50+
usleep(10_000)
51+
}
52+
53+
# Send sleep command and wait until the server has registered it
54+
$stdin = "select pg_sleep(180);\n";
55+
pump $h while length $stdin;
56+
$node->poll_query_until('postgres', q{SELECT (SELECT count(*) FROM pg_stat_activity WHERE query ~ 'pg_sleep') > 0;})
57+
or die "timed out";
58+
59+
# Send cancel request
60+
kill 'INT', $psql_pid;
61+
62+
my $result = finish $h;
4463

4564
ok(!$result, 'query failed as expected');
4665
like($stderr, qr/canceling statement due to user request/, 'query was canceled');

0 commit comments

Comments
 (0)