Skip to content

Commit c774d31

Browse files
committed
Choose ports for test servers less likely to result in conflicts
If we choose ports in the range typically used for ephemeral ports there is a danger of encountering a port conflict due to a race condition between the time we choose the port in a range below that typically used to allocate ephemeral ports, but higher than the range typically used by well known services. Author: Jelte Fenema-Nio, with some editing by me. Discussion: https://postgr.es/m/d6ee8761-39d1-0033-1afb-d5a57ee056f2@gmail.com Backpatch to all live branches (12 and up)
1 parent 94c2386 commit c774d31

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/test/perl/PostgresNode.pm

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,14 @@ our ($use_tcp, $test_localhost, $test_pghost, $last_host_assigned,
116116
# list of file reservations made by get_free_port
117117
my @port_reservation_files;
118118

119+
# We want to choose a server port above the range that servers typically use
120+
# on Unix systems and below the range those systems typically use for ephemeral
121+
# client ports.
122+
# That way we minimize the risk of getting a port collision. These two values
123+
# are chosen to reflect that. We will always choose a port in this range.
124+
my $port_lower_bound = 10200;
125+
my $port_upper_bound = 32767;
126+
119127
INIT
120128
{
121129

@@ -129,7 +137,8 @@ INIT
129137
$ENV{PGDATABASE} = 'postgres';
130138

131139
# Tracking of last port value assigned to accelerate free port lookup.
132-
$last_port_assigned = int(rand() * 16384) + 49152;
140+
my $num_ports = $port_upper_bound - $port_lower_bound;
141+
$last_port_assigned = int(rand() * $num_ports) + $port_lower_bound;
133142

134143
# Set the port lock directory
135144

@@ -1242,7 +1251,7 @@ sub get_free_port
12421251
{
12431252

12441253
# advance $port, wrapping correctly around range end
1245-
$port = 49152 if ++$port >= 65536;
1254+
$port = $port_lower_bound if ++$port > $port_upper_bound;
12461255
print "# Checking port $port\n";
12471256

12481257
# Check first that candidate port number is not included in

0 commit comments

Comments
 (0)