Skip to content

Commit 7e72eb9

Browse files
authored
test: Add mutex to opening PostgreSQL ports to prevent collision (#389)
Closes #388.
1 parent 6c2371e commit 7e72eb9

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

database/postgres/postgres.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,18 @@ import (
66
"io/ioutil"
77
"net"
88
"os"
9+
"sync"
910
"time"
1011

1112
"github.com/ory/dockertest/v3"
1213
"github.com/ory/dockertest/v3/docker"
1314
"golang.org/x/xerrors"
1415
)
1516

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+
1621
// Open creates a new PostgreSQL server using a Docker container.
1722
func Open() (string, func(), error) {
1823
pool, err := dockertest.NewPool("")
@@ -23,10 +28,12 @@ func Open() (string, func(), error) {
2328
if err != nil {
2429
return "", nil, xerrors.Errorf("create tempdir: %w", err)
2530
}
31+
openPortMutex.Lock()
2632
// Pick an explicit port on the host to connect to 5432.
2733
// This is necessary so we can configure the port to only use ipv4.
2834
port, err := getFreePort()
2935
if err != nil {
36+
openPortMutex.Unlock()
3037
return "", nil, xerrors.Errorf("Unable to get free port: %w", err)
3138
}
3239

@@ -64,8 +71,11 @@ func Open() (string, func(), error) {
6471
config.RestartPolicy = docker.RestartPolicy{Name: "no"}
6572
})
6673
if err != nil {
74+
openPortMutex.Unlock()
6775
return "", nil, xerrors.Errorf("could not start resource: %w", err)
6876
}
77+
openPortMutex.Unlock()
78+
6979
hostAndPort := resource.GetHostPort("5432/tcp")
7080
dbURL := fmt.Sprintf("postgres://postgres:postgres@%s/postgres?sslmode=disable", hostAndPort)
7181

0 commit comments

Comments
 (0)