From 7e72eb9ee64e252c44a03f25bdf6d41b99096460 Mon Sep 17 00:00:00 2001 From: Kyle Carberry Date: Tue, 1 Mar 2022 12:36:07 -0600 Subject: [PATCH] test: Add mutex to opening PostgreSQL ports to prevent collision (#389) Closes #388. --- database/postgres/postgres.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/database/postgres/postgres.go b/database/postgres/postgres.go index 78d02de150..1cf5338d73 100644 --- a/database/postgres/postgres.go +++ b/database/postgres/postgres.go @@ -6,6 +6,7 @@ import ( "io/ioutil" "net" "os" + "sync" "time" "github.com/ory/dockertest/v3" @@ -13,6 +14,10 @@ import ( "golang.org/x/xerrors" ) +// Required to prevent port collision during container creation. +// Super unlikely, but it happened. See: https://github.com/coder/coder/runs/5375197003 +var openPortMutex sync.Mutex + // Open creates a new PostgreSQL server using a Docker container. func Open() (string, func(), error) { pool, err := dockertest.NewPool("") @@ -23,10 +28,12 @@ func Open() (string, func(), error) { if err != nil { return "", nil, xerrors.Errorf("create tempdir: %w", err) } + openPortMutex.Lock() // Pick an explicit port on the host to connect to 5432. // This is necessary so we can configure the port to only use ipv4. port, err := getFreePort() if err != nil { + openPortMutex.Unlock() return "", nil, xerrors.Errorf("Unable to get free port: %w", err) } @@ -64,8 +71,11 @@ func Open() (string, func(), error) { config.RestartPolicy = docker.RestartPolicy{Name: "no"} }) if err != nil { + openPortMutex.Unlock() return "", nil, xerrors.Errorf("could not start resource: %w", err) } + openPortMutex.Unlock() + hostAndPort := resource.GetHostPort("5432/tcp") dbURL := fmt.Sprintf("postgres://postgres:postgres@%s/postgres?sslmode=disable", hostAndPort)