@@ -3,10 +3,8 @@ package postgres
3
3
import (
4
4
"database/sql"
5
5
"fmt"
6
- "net"
7
6
"os"
8
7
"strconv"
9
- "sync"
10
8
"time"
11
9
12
10
"github.com/cenkalti/backoff/v4"
@@ -18,10 +16,6 @@ import (
18
16
"github.com/coder/coder/cryptorand"
19
17
)
20
18
21
- // Required to prevent port collision during container creation.
22
- // Super unlikely, but it happened. See: https://github.com/coder/coder/runs/5375197003
23
- var openPortMutex sync.Mutex
24
-
25
19
// Open creates a new PostgreSQL database instance. With DB_FROM environment variable set, it clones a database
26
20
// from the provided template. With the environment variable unset, it creates a new Docker container running postgres.
27
21
func Open () (string , func (), error ) {
@@ -68,17 +62,6 @@ func OpenContainerized(port int) (string, func(), error) {
68
62
return "" , nil , xerrors .Errorf ("create tempdir: %w" , err )
69
63
}
70
64
71
- openPortMutex .Lock ()
72
- if port == 0 {
73
- // Pick an explicit port on the host to connect to 5432.
74
- // This is necessary so we can configure the port to only use ipv4.
75
- port , err = getFreePort ()
76
- if err != nil {
77
- openPortMutex .Unlock ()
78
- return "" , nil , xerrors .Errorf ("get free port: %w" , err )
79
- }
80
- }
81
-
82
65
resource , err := pool .RunWithOptions (& dockertest.RunOptions {
83
66
Repository : "postgres" ,
84
67
Tag : "13" ,
@@ -114,10 +97,8 @@ func OpenContainerized(port int) (string, func(), error) {
114
97
config .RestartPolicy = docker.RestartPolicy {Name : "no" }
115
98
})
116
99
if err != nil {
117
- openPortMutex .Unlock ()
118
100
return "" , nil , xerrors .Errorf ("could not start resource: %w" , err )
119
101
}
120
- openPortMutex .Unlock ()
121
102
122
103
hostAndPort := resource .GetHostPort ("5432/tcp" )
123
104
dbURL := fmt .Sprintf ("postgres://postgres:postgres@%s/postgres?sslmode=disable" , hostAndPort )
@@ -166,18 +147,3 @@ func OpenContainerized(port int) (string, func(), error) {
166
147
_ = os .RemoveAll (tempDir )
167
148
}, nil
168
149
}
169
-
170
- // getFreePort asks the kernel for a free open port that is ready to use.
171
- func getFreePort () (port int , err error ) {
172
- // Binding to port 0 tells the OS to grab a port for us:
173
- // https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number
174
- listener , err := net .Listen ("tcp" , "localhost:0" )
175
- if err != nil {
176
- return 0 , err
177
- }
178
-
179
- defer listener .Close ()
180
- // This is always a *net.TCPAddr.
181
- // nolint:forcetypeassert
182
- return listener .Addr ().(* net.TCPAddr ).Port , nil
183
- }
0 commit comments