-
Notifications
You must be signed in to change notification settings - Fork 171
/
postgres.go
210 lines (170 loc) · 5.3 KB
/
postgres.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package storage
import (
"context"
"fmt"
"io"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/oklog/ulid/v2"
"github.com/openfga/openfga/assets"
"github.com/pressly/goose/v3"
"github.com/stretchr/testify/require"
)
const (
postgresImage = "postgres:14"
)
var (
expireTimeout = 10 * time.Minute //benchmarks take a while to run
)
type postgresTestContainer struct {
addr string
version int64
username string
password string
}
// NewPostgresTestContainer returns an implementation of the DatastoreTestContainer interface
// for Postgres.
func NewPostgresTestContainer() *postgresTestContainer {
return &postgresTestContainer{}
}
func (p *postgresTestContainer) GetDatabaseSchemaVersion() int64 {
return p.version
}
// RunPostgresTestContainer runs a Postgres container, connects to it, and returns a
// bootstrapped implementation of the DatastoreTestContainer interface wired up for the
// Postgres datastore engine.
func (p *postgresTestContainer) RunPostgresTestContainer(t testing.TB) DatastoreTestContainer {
dockerClient, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
require.NoError(t, err)
allImages, err := dockerClient.ImageList(context.Background(), types.ImageListOptions{
All: true,
})
require.NoError(t, err)
foundPostgresImage := false
for _, image := range allImages {
for _, tag := range image.RepoTags {
if strings.Contains(tag, postgresImage) {
foundPostgresImage = true
break
}
}
}
if !foundPostgresImage {
t.Logf("Pulling image %s", postgresImage)
reader, err := dockerClient.ImagePull(context.Background(), postgresImage, types.ImagePullOptions{})
require.NoError(t, err)
_, err = io.Copy(io.Discard, reader) // consume the image pull output to make sure it's done
require.NoError(t, err)
}
containerCfg := container.Config{
Env: []string{
"POSTGRES_DB=defaultdb",
"POSTGRES_PASSWORD=secret",
},
ExposedPorts: nat.PortSet{
nat.Port("5432/tcp"): {},
},
Image: postgresImage,
}
hostCfg := container.HostConfig{
AutoRemove: true,
PublishAllPorts: true,
}
name := fmt.Sprintf("postgres-%s", ulid.Make().String())
cont, err := dockerClient.ContainerCreate(context.Background(), &containerCfg, &hostCfg, nil, nil, name)
require.NoError(t, err, "failed to create postgres docker container")
stopContainer := func() {
t.Logf("stopping container %s", name)
timeoutSec := 5
err := dockerClient.ContainerStop(context.Background(), cont.ID, container.StopOptions{Timeout: &timeoutSec})
if err != nil && !client.IsErrNotFound(err) {
t.Logf("failed to stop postgres container: %v", err)
}
dockerClient.Close()
t.Logf("stopped container %s", name)
}
err = dockerClient.ContainerStart(context.Background(), cont.ID, types.ContainerStartOptions{})
if err != nil {
stopContainer()
t.Fatalf("failed to start postgres container: %v", err)
}
containerJSON, err := dockerClient.ContainerInspect(context.Background(), cont.ID)
require.NoError(t, err)
m, ok := containerJSON.NetworkSettings.Ports["5432/tcp"]
if !ok || len(m) == 0 {
t.Fatalf("failed to get host port mapping from postgres container")
}
// spin up a goroutine to survive any test panics to expire/stop the running container
go func() {
time.Sleep(expireTimeout)
timeoutSec := 0
t.Logf("expiring container %s", name)
err := dockerClient.ContainerStop(context.Background(), cont.ID, container.StopOptions{Timeout: &timeoutSec})
if err != nil && !client.IsErrNotFound(err) {
t.Logf("failed to expire postgres container: %v", err)
}
t.Logf("expired container %s", name)
}()
t.Cleanup(func() {
stopContainer()
})
pgTestContainer := &postgresTestContainer{
addr: fmt.Sprintf("localhost:%s", m[0].HostPort),
username: "postgres",
password: "secret",
}
uri := fmt.Sprintf("postgres://%s:%s@%s/defaultdb?sslmode=disable", pgTestContainer.username, pgTestContainer.password, pgTestContainer.addr)
goose.SetLogger(goose.NopLogger())
db, err := goose.OpenDBWithDriver("pgx", uri)
require.NoError(t, err)
backoffPolicy := backoff.NewExponentialBackOff()
backoffPolicy.MaxElapsedTime = 30 * time.Second
err = backoff.Retry(
func() error {
return db.Ping()
},
backoffPolicy,
)
if err != nil {
stopContainer()
t.Fatalf("failed to connect to postgres container: %v", err)
}
goose.SetBaseFS(assets.EmbedMigrations)
err = goose.Up(db, assets.PostgresMigrationDir)
require.NoError(t, err)
version, err := goose.GetDBVersion(db)
require.NoError(t, err)
pgTestContainer.version = version
err = db.Close()
require.NoError(t, err)
return pgTestContainer
}
// GetConnectionURI returns the postgres connection uri for the running postgres test container.
func (p *postgresTestContainer) GetConnectionURI(includeCredentials bool) string {
creds := ""
if includeCredentials {
creds = fmt.Sprintf("%s:%s@", p.username, p.password)
}
return fmt.Sprintf(
"postgres://%s%s/%s?sslmode=disable",
creds,
p.addr,
"defaultdb",
)
}
func (p *postgresTestContainer) GetUsername() string {
return p.username
}
func (p *postgresTestContainer) GetPassword() string {
return p.password
}