Skip to content

Commit b7d3be6

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 81749aa commit b7d3be6

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
@@ -119,6 +119,14 @@ our ($use_tcp, $test_localhost, $test_pghost, $last_host_assigned,
119119
# list of file reservations made by get_free_port
120120
my @port_reservation_files;
121121

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

@@ -132,7 +140,8 @@ INIT
132140
$ENV{PGDATABASE} = 'postgres';
133141

134142
# Tracking of last port value assigned to accelerate free port lookup.
135-
$last_port_assigned = int(rand() * 16384) + 49152;
143+
my $num_ports = $port_upper_bound - $port_lower_bound;
144+
$last_port_assigned = int(rand() * $num_ports) + $port_lower_bound;
136145

137146
# Set the port lock directory
138147

@@ -1441,7 +1450,7 @@ sub get_free_port
14411450
{
14421451

14431452
# advance $port, wrapping correctly around range end
1444-
$port = 49152 if ++$port >= 65536;
1453+
$port = $port_lower_bound if ++$port > $port_upper_bound;
14451454
print "# Checking port $port\n";
14461455

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

0 commit comments

Comments
 (0)