-
Notifications
You must be signed in to change notification settings - Fork 567
/
postgres.go
280 lines (253 loc) · 8.54 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// package dockertestenv provides test environment where service dependencies are docker containers
package dockertestenv
import (
"context"
"os"
"sync"
"testing"
"time"
"github.com/pachyderm/pachyderm/v2/src/internal/backoff"
"github.com/pachyderm/pachyderm/v2/src/internal/cleanup"
"github.com/pachyderm/pachyderm/v2/src/internal/dbutil"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/log"
"github.com/pachyderm/pachyderm/v2/src/internal/pachconfig"
"github.com/pachyderm/pachyderm/v2/src/internal/pachsql"
"github.com/pachyderm/pachyderm/v2/src/internal/pctx"
"github.com/pachyderm/pachyderm/v2/src/internal/require"
"github.com/pachyderm/pachyderm/v2/src/internal/testutil"
"go.uber.org/zap"
)
const (
postgresPort = 30228
PGBouncerPort = 30229
maxOpenConns = 10
DefaultPostgresPassword = "correcthorsebatterystable"
DefaultPostgresUser = "pachyderm"
DefaultPostgresDatabase = "pachyderm"
)
func postgresHost() string {
return getDockerHost()
}
func PGBouncerHost() string {
return postgresHost()
}
type PostgresConfig struct {
Host string
Port uint16
User string
Password string
DBName string
}
func (pgc PostgresConfig) DBOptions() []dbutil.Option {
return []dbutil.Option{
dbutil.WithMaxOpenConns(10),
dbutil.WithUserPassword(pgc.User, pgc.Password),
dbutil.WithHostPort(pgc.Host, int(pgc.Port)),
dbutil.WithDBName(pgc.DBName),
}
}
type DBConfig struct {
Direct PostgresConfig
PGBouncer PostgresConfig
Identity PostgresConfig
}
func (dbc DBConfig) PachConfigOption(c *pachconfig.Configuration) {
// common
c.PostgresDBName = dbc.PGBouncer.DBName
c.IdentityServerDatabase = dbc.Identity.DBName
c.PostgresUser = dbc.PGBouncer.User
c.PostgresPassword = dbc.PGBouncer.Password
// direct
c.PostgresHost = dbc.Direct.Host
c.PostgresPort = int(dbc.Direct.Port)
// pg_bouncer
c.PGBouncerHost = dbc.PGBouncer.Host
c.PGBouncerPort = int(dbc.PGBouncer.Port)
}
// NewTestDBConfig returns a DBConfig for a test environment
// The environment will be torn down at the end of the test.
func NewTestDBConfig(t testing.TB) DBConfig {
var (
ctx = pctx.TestContext(t)
dbName = testutil.GenerateEphemeralDBName()
dexName = testutil.UniqueString("dex")
)
err := backoff.Retry(func() error {
return EnsureDBEnv(ctx)
}, backoff.NewConstantBackOff(time.Second*3))
require.NoError(t, err, "DB should be created")
db := testutil.OpenDB(t,
dbutil.WithMaxOpenConns(1),
dbutil.WithUserPassword(DefaultPostgresUser, DefaultPostgresPassword),
dbutil.WithHostPort(PGBouncerHost(), PGBouncerPort),
dbutil.WithDBName(DefaultPostgresDatabase),
)
testutil.CreateEphemeralDB(t, db, dbName)
testutil.CreateEphemeralDB(t, db, dexName)
return DBConfig{
Direct: PostgresConfig{
Host: postgresHost(),
Port: postgresPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dbName,
},
PGBouncer: PostgresConfig{
Host: PGBouncerHost(),
Port: PGBouncerPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dbName,
},
Identity: PostgresConfig{
Host: PGBouncerHost(),
Port: PGBouncerPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dexName,
},
}
}
// NewTestDBConfigCtx returns a DBConfig for an environment outside of tests.
func NewTestDBConfigCtx(ctx context.Context) (config DBConfig, cleaner *cleanup.Cleaner, _ error) {
var (
dbName = testutil.GenerateEphemeralDBName()
dexName = testutil.UniqueString("dex")
)
cleaner = new(cleanup.Cleaner)
if err := backoff.Retry(func() error {
return EnsureDBEnv(ctx)
}, backoff.NewConstantBackOff(time.Second*3)); err != nil {
return config, cleaner, errors.Wrap(err, "wait for database to be created")
}
db, err := dbutil.NewDB(
dbutil.WithMaxOpenConns(1),
dbutil.WithUserPassword(DefaultPostgresUser, DefaultPostgresPassword),
dbutil.WithHostPort(PGBouncerHost(), PGBouncerPort),
dbutil.WithDBName(DefaultPostgresDatabase))
if err != nil {
return config, cleaner, errors.Wrap(err, "NewDB")
}
cleaner.AddCleanup("close db connection", db.Close)
if err := testutil.CreateEphemeralDBNontest(ctx, db, dbName); err != nil {
return config, cleaner, errors.Wrapf(err, "CreateEphemeralDB(%v)", dbName)
}
cleaner.AddCleanupCtx("cleanup pach database", func(ctx context.Context) error {
return errors.Wrapf(testutil.CleanupEphemeralDB(ctx, db, dbName), "cleanup database %v", dbName)
})
if err := testutil.CreateEphemeralDBNontest(ctx, db, dexName); err != nil {
return config, cleaner, errors.Wrapf(err, "CreateEphemeralDB(%v)", dexName)
}
cleaner.AddCleanupCtx("cleanup dex database", func(ctx context.Context) error {
return errors.Wrapf(testutil.CleanupEphemeralDB(ctx, db, dexName), "cleanup database %v", dbName)
})
return DBConfig{
Direct: PostgresConfig{
Host: postgresHost(),
Port: postgresPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dbName,
},
PGBouncer: PostgresConfig{
Host: PGBouncerHost(),
Port: PGBouncerPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dbName,
},
Identity: PostgresConfig{
Host: PGBouncerHost(),
Port: PGBouncerPort,
User: DefaultPostgresUser,
Password: DefaultPostgresPassword,
DBName: dexName,
},
}, cleaner, nil
}
// NewTestDB creates a new database connection scoped to the test.
func NewTestDB(t testing.TB) *pachsql.DB {
cfg := NewTestDBConfig(t)
return testutil.OpenDB(t, cfg.PGBouncer.DBOptions()...)
}
func NewTestDirectDB(t testing.TB) *pachsql.DB {
cfg := NewTestDBConfig(t)
return testutil.OpenDB(t, cfg.Direct.DBOptions()...)
}
// NewEphemeralPostgresDB creates a randomly-named new database, returning a
// connection to the new DB and the name itself.
func NewEphemeralPostgresDB(ctx context.Context, t testing.TB) (*pachsql.DB, string) {
c := NewTestDBConfig(t)
return testutil.OpenDB(t, c.Direct.DBOptions()...), c.Direct.DBName
}
var spawnLock sync.Mutex
// TODO: use the docker client, instead of the bash script
// TODO: use the bitnami pg_bouncer image
// TODO: look into https://github.com/ory/dockertest
func EnsureDBEnv(ctx context.Context) error {
// bazel run //src/testing/cmd/dockertestenv creates these for many CI runs.
if got, want := os.Getenv("SKIP_DOCKER_POSTGRES_CREATE"), "1"; got == want {
log.Info(ctx, "not attempting to create docker container; SKIP_DOCKER_POSTGRES_CREATE=1")
return nil
}
spawnLock.Lock()
defer spawnLock.Unlock()
timeout := 120 * time.Second
ctx, cf := context.WithTimeout(ctx, timeout)
defer cf()
dclient := newDockerClient()
defer dclient.Close()
if err := ensureContainer(ctx, dclient, "pach_test_postgres", containerSpec{
Env: map[string]string{
"POSTGRES_DB": "pachyderm",
"POSTGRES_USER": "pachyderm",
"POSTGRES_HOST_AUTH_METHOD": "trust",
},
PortMap: map[uint16]uint16{
30228: 5432,
},
Image: "postgres:13.0-alpine",
Cmd: []string{"postgres", "-c", "max_connections=500", "-c", "fsync=off"},
}); err != nil {
return errors.EnsureStack(err)
}
containerJSON, err := dclient.ContainerInspect(ctx, "pach_test_postgres")
if err != nil {
return errors.EnsureStack(err)
}
postgresIP := containerJSON.NetworkSettings.IPAddress
if err := ensureContainer(ctx, dclient, "pach_test_pgbouncer", containerSpec{
Env: map[string]string{
"PGBOUNCER_AUTH_TYPE": "any",
"POSTGRESQL_USERNAME": "pachyderm",
"POSTGRESQL_PASSWORD": "password",
"POSTGRESQL_HOST": postgresIP,
"POSTGRESQL_PORT": "5432",
"PGBOUNCER_MAX_CLIENT_CONN": "100000",
"PGBOUNCER_POOL_MODE": "transaction",
"PGBOUNCER_IGNORE_STARTUP_PARAMETERS": "extra_float_digits",
},
PortMap: map[uint16]uint16{
30229: 5432,
},
Image: "pachyderm/pgbouncer:1.16.2",
}); err != nil {
return errors.EnsureStack(err)
}
return backoff.RetryUntilCancel(ctx, func() error {
db, err := dbutil.NewDB(
dbutil.WithDBName(DefaultPostgresDatabase),
dbutil.WithHostPort(PGBouncerHost(), PGBouncerPort),
dbutil.WithUserPassword(DefaultPostgresUser, DefaultPostgresPassword),
)
if err != nil {
log.Info(ctx, "failed to connect to database; retrying", zap.Error(err))
return errors.Wrap(err, "connect to db")
}
defer db.Close()
return errors.Wrap(db.PingContext(ctx), "ping db")
}, backoff.RetryEvery(time.Second), func(err error, _ time.Duration) error {
return nil
})
}