/
setup.go
422 lines (329 loc) · 12.3 KB
/
setup.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package setup provides integration tests setup helpers.
package setup
import (
"context"
"errors"
"flag"
"fmt"
"net/url"
"runtime/trace"
"slices"
"strings"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.opentelemetry.io/otel"
"go.uber.org/zap"
"github.com/FerretDB/FerretDB/integration/shareddata"
"github.com/FerretDB/FerretDB/internal/handler/handlererrors"
"github.com/FerretDB/FerretDB/internal/util/iterator"
"github.com/FerretDB/FerretDB/internal/util/observability"
"github.com/FerretDB/FerretDB/internal/util/testutil"
"github.com/FerretDB/FerretDB/internal/util/testutil/testtb"
)
// Flags.
var (
targetURLF = flag.String("target-url", "", "target system's URL; if empty, in-process FerretDB is used")
targetBackendF = flag.String("target-backend", "", "target system's backend: '%s'"+strings.Join(allBackends, "', '"))
targetProxyAddrF = flag.String("target-proxy-addr", "", "in-process FerretDB: use given proxy")
targetTLSF = flag.Bool("target-tls", false, "in-process FerretDB: use TLS")
targetUnixSocketF = flag.Bool("target-unix-socket", false, "in-process FerretDB: use Unix domain socket")
postgreSQLURLF = flag.String("postgresql-url", "", "in-process FerretDB: PostgreSQL URL for 'postgresql' handler.")
sqliteURLF = flag.String("sqlite-url", "", "in-process FerretDB: SQLite URI for 'sqlite' handler.")
mysqlURLF = flag.String("mysql-url", "", "in-process FerretDB: MySQL URL for 'mysql' handler.")
hanaURLF = flag.String("hana-url", "", "in-process FerretDB: Hana URL for 'hana' handler.")
batchSizeF = flag.Int("batch-size", 100, "maximum insertion batch size")
compatURLF = flag.String("compat-url", "", "compat system's (MongoDB) URL for compatibility tests; if empty, they are skipped")
benchDocsF = flag.Int("bench-docs", 1000, "benchmarks: number of documents to generate per iteration")
// Disable noisy setup logs by default.
debugSetupF = flag.Bool("debug-setup", false, "enable debug logs for tests setup")
logLevelF = zap.LevelFlag("log-level", zap.DebugLevel, "log level for tests")
disablePushdownF = flag.Bool("disable-pushdown", false, "disable pushdown")
)
// Other globals.
var (
allBackends = []string{"ferretdb-postgresql", "ferretdb-sqlite", "ferretdb-mysql", "ferretdb-hana", "mongodb"}
)
// SetupOpts represents setup options.
//
// Add option to use read-only user.
// TODO https://github.com/FerretDB/FerretDB/issues/1025
type SetupOpts struct {
// Database to use. If empty, temporary test-specific database is created and dropped after test.
DatabaseName string
// Collection to use. If empty, temporary test-specific collection is created and dropped after test.
// Most tests should keep this empty.
CollectionName string
// Data providers. If empty, collection is not created.
Providers []shareddata.Provider
// Benchmark data provider. If empty, collection is not created.
BenchmarkProvider shareddata.BenchmarkProvider
// ExtraOptions sets the options in MongoDB URI, when the option exists it overwrites that option.
ExtraOptions url.Values
// SetupUser true creates a user and returns an authenticated client.
SetupUser bool
// Options to override default backend configuration.
BackendOptions *BackendOpts
}
// BackendOpts represents backend configuration used for test setup.
type BackendOpts struct {
// Capped collections cleanup interval.
CappedCleanupInterval time.Duration
// Percentage of documents to cleanup for capped collections. If not set, defaults to 20.
CappedCleanupPercentage uint8
}
// SetupResult represents setup results.
type SetupResult struct {
Ctx context.Context
Collection *mongo.Collection
MongoDBURI string
}
// NewBackendOpts returns BackendOpts with default values set.
func NewBackendOpts() *BackendOpts {
return &BackendOpts{
CappedCleanupInterval: time.Duration(0),
CappedCleanupPercentage: uint8(20),
}
}
// IsUnixSocket returns true if MongoDB URI is a Unix domain socket.
func (s *SetupResult) IsUnixSocket(tb testtb.TB) bool {
tb.Helper()
// we can't use a regular url.Parse because
// MongoDB really wants Unix domain socket path in the host part of the URI
opts := options.Client().ApplyURI(s.MongoDBURI)
res := slices.ContainsFunc(opts.Hosts, func(host string) bool {
return strings.Contains(host, "/")
})
tb.Logf("IsUnixSocket: %q - %v", s.MongoDBURI, res)
return res
}
// SetupWithOpts setups the test according to given options.
func SetupWithOpts(tb testtb.TB, opts *SetupOpts) *SetupResult {
tb.Helper()
ctx, cancel := context.WithCancel(testutil.Ctx(tb))
setupCtx, span := otel.Tracer("").Start(ctx, "SetupWithOpts")
defer span.End()
defer trace.StartRegion(setupCtx, "SetupWithOpts").End()
if opts == nil {
opts = new(SetupOpts)
}
level := zap.NewAtomicLevelAt(zap.ErrorLevel)
if *debugSetupF {
level = zap.NewAtomicLevelAt(zap.DebugLevel)
}
logger := testutil.LevelLogger(tb, level)
uri := *targetURLF
if uri == "" {
if opts.BackendOptions == nil {
opts.BackendOptions = NewBackendOpts()
}
uri = setupListener(tb, setupCtx, logger, opts.BackendOptions)
} else {
uri = toAbsolutePathURI(tb, *targetURLF)
}
if opts.ExtraOptions != nil {
u, err := url.Parse(uri)
require.NoError(tb, err)
q := u.Query()
for k, vs := range opts.ExtraOptions {
for _, v := range vs {
q.Set(k, v)
}
}
u.RawQuery = q.Encode()
uri = u.String()
tb.Logf("URI with extra options: %s", uri)
}
client := setupClient(tb, setupCtx, uri)
// register cleanup function after setupListener registers its own to preserve full logs
tb.Cleanup(cancel)
if opts.SetupUser {
// user is created before the collection so that user can run collection cleanup
client = setupUser(tb, ctx, client, uri)
}
collection := setupCollection(tb, ctx, client, opts)
level.SetLevel(*logLevelF)
return &SetupResult{
Ctx: ctx,
Collection: collection,
MongoDBURI: uri,
}
}
// Setup setups a single collection for all providers, if they are present.
func Setup(tb testtb.TB, providers ...shareddata.Provider) (context.Context, *mongo.Collection) {
tb.Helper()
s := SetupWithOpts(tb, &SetupOpts{
Providers: providers,
})
return s.Ctx, s.Collection
}
// setupCollection setups a single collection for all providers, if they are present.
func setupCollection(tb testtb.TB, ctx context.Context, client *mongo.Client, opts *SetupOpts) *mongo.Collection {
tb.Helper()
ctx, span := otel.Tracer("").Start(ctx, "setupCollection")
defer span.End()
defer observability.FuncCall(ctx)()
var ownDatabase bool
databaseName := opts.DatabaseName
if databaseName == "" {
databaseName = testutil.DatabaseName(tb)
ownDatabase = true
}
var ownCollection bool
collectionName := opts.CollectionName
if collectionName == "" {
collectionName = testutil.CollectionName(tb)
ownCollection = true
}
database := client.Database(databaseName)
collection := database.Collection(collectionName)
// drop remnants of the previous failed run
_ = collection.Drop(ctx)
if ownDatabase {
_ = database.RunCommand(ctx, bson.D{{"dropAllUsersFromDatabase", 1}})
_ = database.Drop(ctx)
}
var inserted bool
switch {
case len(opts.Providers) > 0:
require.Nil(tb, opts.BenchmarkProvider, "Both Providers and BenchmarkProvider were set")
inserted = insertProviders(tb, ctx, collection, opts.Providers...)
case opts.BenchmarkProvider != nil:
inserted = insertBenchmarkProvider(tb, ctx, collection, opts.BenchmarkProvider)
}
if len(opts.Providers) == 0 && opts.BenchmarkProvider == nil {
tb.Logf("Collection %s.%s wasn't created because no providers were set.", databaseName, collectionName)
} else {
require.True(tb, inserted)
}
if ownCollection {
// delete collection and (possibly) database unless test failed
tb.Cleanup(func() {
if tb.Failed() {
tb.Logf("Keeping %s.%s for debugging.", databaseName, collectionName)
return
}
err := collection.Drop(ctx)
require.NoError(tb, err)
if ownDatabase {
err = database.RunCommand(ctx, bson.D{{"dropAllUsersFromDatabase", 1}}).Err()
require.NoError(tb, err)
err = database.Drop(ctx)
require.NoError(tb, err)
}
})
}
return collection
}
// insertProviders inserts documents from specified Providers into collection. It returns true if any document was inserted.
func insertProviders(tb testtb.TB, ctx context.Context, collection *mongo.Collection, providers ...shareddata.Provider) (inserted bool) {
tb.Helper()
collectionName := collection.Name()
for _, provider := range providers {
spanName := fmt.Sprintf("insertProviders/%s/%s", collectionName, provider.Name())
provCtx, span := otel.Tracer("").Start(ctx, spanName)
region := trace.StartRegion(provCtx, spanName)
docs := shareddata.Docs(provider)
require.NotEmpty(tb, docs)
res, err := collection.InsertMany(provCtx, docs)
require.NoError(tb, err, "provider %q", provider.Name())
require.Len(tb, res.InsertedIDs, len(docs))
inserted = true
region.End()
span.End()
}
return
}
// insertBenchmarkProvider inserts documents from specified BenchmarkProvider into collection.
// It returns true if any document was inserted.
//
// The function calculates the checksum of all inserted documents and compare them with provider's hash.
func insertBenchmarkProvider(tb testtb.TB, ctx context.Context, collection *mongo.Collection, provider shareddata.BenchmarkProvider) (inserted bool) {
tb.Helper()
collectionName := collection.Name()
spanName := fmt.Sprintf("insertBenchmarkProvider/%s/%s", collectionName, provider.Name())
provCtx, span := otel.Tracer("").Start(ctx, spanName)
region := trace.StartRegion(provCtx, spanName)
iter := provider.NewIterator()
defer iter.Close()
for {
docs, err := iterator.ConsumeValuesN(iter, 100)
require.NoError(tb, err)
if len(docs) == 0 {
break
}
insertDocs := make([]any, len(docs))
for i, doc := range docs {
insertDocs[i] = doc
}
res, err := collection.InsertMany(provCtx, insertDocs)
require.NoError(tb, err)
require.Len(tb, res.InsertedIDs, len(docs))
inserted = true
}
region.End()
span.End()
return
}
// setupUser creates a user in admin database with supported mechanisms. It returns an authenticated client.
//
// Without this, once the first user is created, the authentication fails as local exception no longer applies.
func setupUser(tb testtb.TB, ctx context.Context, client *mongo.Client, uri string) *mongo.Client {
tb.Helper()
// username is unique per test so the user is deleted after the test
username, password := "username"+tb.Name(), "password"
err := client.Database("admin").RunCommand(ctx, bson.D{
{"dropUser", username},
}).Err()
var ce mongo.CommandError
if errors.As(err, &ce) && ce.Code == int32(handlererrors.ErrUserNotFound) {
err = nil
}
require.NoError(tb, err)
roles := bson.A{"root"}
if !IsMongoDB(tb) {
// use root role for FerretDB once authorization is implemented
// TODO https://github.com/FerretDB/FerretDB/issues/3974
roles = bson.A{}
}
err = client.Database("admin").RunCommand(ctx, bson.D{
{"createUser", username},
{"roles", roles},
{"pwd", password},
{"mechanisms", bson.A{"SCRAM-SHA-1", "SCRAM-SHA-256"}},
}).Err()
require.NoError(tb, err)
credential := options.Credential{
AuthMechanism: "SCRAM-SHA-256",
AuthSource: "admin",
Username: username,
Password: password,
}
opts := options.Client().ApplyURI(uri).SetAuth(credential)
authenticatedClient, err := mongo.Connect(ctx, opts)
require.NoError(tb, err)
tb.Cleanup(func() {
err = authenticatedClient.Database("admin").RunCommand(ctx, bson.D{
{"dropUser", username},
}).Err()
assert.NoError(tb, err)
require.NoError(tb, authenticatedClient.Disconnect(ctx))
})
return authenticatedClient
}