Skip to content

Commit

Permalink
test: Add mutex to opening PostgreSQL ports to prevent collision (#389)
Browse files Browse the repository at this point in the history
Closes #388.
  • Loading branch information
kylecarbs committed Mar 1, 2022
1 parent 6c2371e commit 7e72eb9
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions database/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@ import (
"io/ioutil"
"net"
"os"
"sync"
"time"

"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
"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("")
Expand All @@ -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)
}

Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit 7e72eb9

Please sign in to comment.