mirror of
https://github.com/coder/coder.git
synced 2025-07-21 01:28:49 +00:00
test: Add mutex to opening PostgreSQL ports to prevent collision (#389)
Closes #388.
This commit is contained in:
@ -6,6 +6,7 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/ory/dockertest/v3"
|
"github.com/ory/dockertest/v3"
|
||||||
@ -13,6 +14,10 @@ import (
|
|||||||
"golang.org/x/xerrors"
|
"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.
|
// Open creates a new PostgreSQL server using a Docker container.
|
||||||
func Open() (string, func(), error) {
|
func Open() (string, func(), error) {
|
||||||
pool, err := dockertest.NewPool("")
|
pool, err := dockertest.NewPool("")
|
||||||
@ -23,10 +28,12 @@ func Open() (string, func(), error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", nil, xerrors.Errorf("create tempdir: %w", err)
|
return "", nil, xerrors.Errorf("create tempdir: %w", err)
|
||||||
}
|
}
|
||||||
|
openPortMutex.Lock()
|
||||||
// Pick an explicit port on the host to connect to 5432.
|
// Pick an explicit port on the host to connect to 5432.
|
||||||
// This is necessary so we can configure the port to only use ipv4.
|
// This is necessary so we can configure the port to only use ipv4.
|
||||||
port, err := getFreePort()
|
port, err := getFreePort()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
openPortMutex.Unlock()
|
||||||
return "", nil, xerrors.Errorf("Unable to get free port: %w", err)
|
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"}
|
config.RestartPolicy = docker.RestartPolicy{Name: "no"}
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
openPortMutex.Unlock()
|
||||||
return "", nil, xerrors.Errorf("could not start resource: %w", err)
|
return "", nil, xerrors.Errorf("could not start resource: %w", err)
|
||||||
}
|
}
|
||||||
|
openPortMutex.Unlock()
|
||||||
|
|
||||||
hostAndPort := resource.GetHostPort("5432/tcp")
|
hostAndPort := resource.GetHostPort("5432/tcp")
|
||||||
dbURL := fmt.Sprintf("postgres://postgres:postgres@%s/postgres?sslmode=disable", hostAndPort)
|
dbURL := fmt.Sprintf("postgres://postgres:postgres@%s/postgres?sslmode=disable", hostAndPort)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user