Skip to content

Commit 3347042

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 e288501 commit 3347042

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/test/perl/PostgreSQL/Test/Cluster.pm

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,14 @@ our $min_compat = 12;
127127
# list of file reservations made by get_free_port
128128
my @port_reservation_files;
129129

130+
# We want to choose a server port above the range that servers typically use
131+
# on Unix systems and below the range those systems typically use for ephemeral
132+
# client ports.
133+
# That way we minimize the risk of getting a port collision. These two values
134+
# are chosen to reflect that. We will always choose a port in this range.
135+
my $port_lower_bound = 10200;
136+
my $port_upper_bound = 32767;
137+
130138
INIT
131139
{
132140

@@ -151,7 +159,8 @@ INIT
151159
$ENV{PGDATABASE} = 'postgres';
152160

153161
# Tracking of last port value assigned to accelerate free port lookup.
154-
$last_port_assigned = int(rand() * 16384) + 49152;
162+
my $num_ports = $port_upper_bound - $port_lower_bound;
163+
$last_port_assigned = int(rand() * $num_ports) + $port_lower_bound;
155164

156165
# Set the port lock directory
157166

@@ -1514,7 +1523,7 @@ sub get_free_port
15141523
{
15151524

15161525
# advance $port, wrapping correctly around range end
1517-
$port = 49152 if ++$port >= 65536;
1526+
$port = $port_lower_bound if ++$port > $port_upper_bound;
15181527
print "# Checking port $port\n";
15191528

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

0 commit comments

Comments
 (0)