@@ -6,13 +6,18 @@ import (
6
6
"io/ioutil"
7
7
"net"
8
8
"os"
9
+ "sync"
9
10
"time"
10
11
11
12
"github.com/ory/dockertest/v3"
12
13
"github.com/ory/dockertest/v3/docker"
13
14
"golang.org/x/xerrors"
14
15
)
15
16
17
+ // Required to prevent port collision during container creation.
18
+ // Super unlikely, but it happened. See: https://github.com/coder/coder/runs/5375197003
19
+ var openPortMutex sync.Mutex
20
+
16
21
// Open creates a new PostgreSQL server using a Docker container.
17
22
func Open () (string , func (), error ) {
18
23
pool , err := dockertest .NewPool ("" )
@@ -23,10 +28,12 @@ func Open() (string, func(), error) {
23
28
if err != nil {
24
29
return "" , nil , xerrors .Errorf ("create tempdir: %w" , err )
25
30
}
31
+ openPortMutex .Lock ()
26
32
// Pick an explicit port on the host to connect to 5432.
27
33
// This is necessary so we can configure the port to only use ipv4.
28
34
port , err := getFreePort ()
29
35
if err != nil {
36
+ openPortMutex .Unlock ()
30
37
return "" , nil , xerrors .Errorf ("Unable to get free port: %w" , err )
31
38
}
32
39
@@ -64,8 +71,11 @@ func Open() (string, func(), error) {
64
71
config .RestartPolicy = docker.RestartPolicy {Name : "no" }
65
72
})
66
73
if err != nil {
74
+ openPortMutex .Unlock ()
67
75
return "" , nil , xerrors .Errorf ("could not start resource: %w" , err )
68
76
}
77
+ openPortMutex .Unlock ()
78
+
69
79
hostAndPort := resource .GetHostPort ("5432/tcp" )
70
80
dbURL := fmt .Sprintf ("postgres://postgres:postgres@%s/postgres?sslmode=disable" , hostAndPort )
71
81
0 commit comments