forked from FerretDB/FerretDB
/
commands_diagnostic_test.go
554 lines (452 loc) · 15 KB
/
commands_diagnostic_test.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// 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 integration
import (
"net"
"net/url"
"slices"
"testing"
"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"
"github.com/FerretDB/FerretDB/integration/setup"
"github.com/FerretDB/FerretDB/integration/shareddata"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/must"
"github.com/FerretDB/FerretDB/internal/util/testutil"
"github.com/FerretDB/FerretDB/internal/util/testutil/teststress"
)
func TestCommandsDiagnosticConnectionStatus(t *testing.T) {
t.Parallel()
ctx, collection := setup.Setup(t)
var actual bson.D
err := collection.Database().RunCommand(ctx, bson.D{{"connectionStatus", "*"}}).Decode(&actual)
require.NoError(t, err)
ok := actual.Map()["ok"]
assert.Equal(t, float64(1), ok)
}
func TestCommandsDiagnosticExplain(t *testing.T) {
t.Parallel()
s := setup.SetupWithOpts(t, &setup.SetupOpts{
Providers: []shareddata.Provider{shareddata.Int32s},
})
ctx, collection := s.Ctx, s.Collection
for name, tc := range map[string]struct {
query bson.D
command bson.D
}{
"Count": {
query: bson.D{{"count", collection.Name()}},
command: bson.D{{"count", collection.Name()}, {"$db", collection.Database().Name()}},
},
"Find": {
query: bson.D{
{"find", collection.Name()},
{"filter", bson.D{{"v", bson.D{{"$gt", int32(0)}}}}},
},
command: bson.D{
{"find", collection.Name()},
{"filter", bson.D{{"v", bson.D{{"$gt", int32(0)}}}}},
{"$db", collection.Database().Name()},
},
},
} {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
t.Parallel()
var actual bson.D
err := collection.Database().RunCommand(ctx, bson.D{{"explain", tc.query}}).Decode(&actual)
require.NoError(t, err)
explainResult := actual.Map()
assert.Equal(t, float64(1), explainResult["ok"])
// explainVersion 1 and 2 are in use for different methods on Mongo 7
assert.True(t, explainResult["explainVersion"] == "1" || explainResult["explainVersion"] == "2")
assert.Equal(t, tc.command, explainResult["command"])
serverInfo := ConvertDocument(t, explainResult["serverInfo"].(bson.D))
keys := serverInfo.Keys()
values := serverInfo.Values()
var host string
var gitVersion string
var version string
for i, k := range keys {
switch k {
case "host":
host = values[i].(string)
case "gitVersion":
gitVersion = values[i].(string)
case "version":
version = values[i].(string)
}
}
assert.NotEmpty(t, host)
assert.NotEmpty(t, gitVersion)
assert.Regexp(t, `^7\.0\.`, version)
assert.NotEmpty(t, explainResult["queryPlanner"])
assert.IsType(t, bson.D{}, explainResult["queryPlanner"])
})
}
}
func TestCommandsDiagnosticGetLog(t *testing.T) {
t.Parallel()
res := setup.SetupWithOpts(t, &setup.SetupOpts{
DatabaseName: "admin",
})
ctx, collection := res.Ctx, res.Collection
for name, tc := range map[string]struct {
command bson.D // required, command to run
expected map[string]any // optional, expected keys of response
err *mongo.CommandError // optional, expected error from MongoDB
altMessage string // optional, alternative error message for FerretDB, ignored if empty
skip string // optional, skip test with a specified reason
}{
"Asterisk": {
command: bson.D{{"getLog", "*"}},
expected: map[string]any{
"names": bson.A(bson.A{"global", "startupWarnings"}),
"ok": float64(1),
},
},
"Global": {
command: bson.D{{"getLog", "global"}},
expected: map[string]any{
"totalLinesWritten": int64(1024),
"log": bson.A{},
"ok": float64(1),
},
},
"StartupWarnings": {
command: bson.D{{"getLog", "startupWarnings"}},
expected: map[string]any{
"totalLinesWritten": int64(1024),
"log": bson.A{},
"ok": float64(1),
},
},
"NonExistentName": {
command: bson.D{{"getLog", "nonExistentName"}},
err: &mongo.CommandError{
Code: 96,
Name: "OperationFailed",
Message: `No log named 'nonExistentName'`,
},
altMessage: `no RecentEntries named: nonExistentName`,
},
"Nil": {
command: bson.D{{"getLog", nil}},
err: &mongo.CommandError{
Code: 40414,
Name: "Location40414",
Message: `BSON field 'getLog.getLog' is missing but a required field`,
},
},
"Array": {
command: bson.D{{"getLog", bson.A{}}},
err: &mongo.CommandError{
Code: 14,
Name: "TypeMismatch",
Message: `BSON field 'getLog.getLog' is the wrong type 'array', expected type 'string'`,
},
},
} {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
if tc.skip != "" {
t.Skip(tc.skip)
}
t.Parallel()
require.NotNil(t, tc.command, "command must not be nil")
var res bson.D
err := collection.Database().RunCommand(ctx, tc.command).Decode(&res)
if tc.err != nil {
assert.Nil(t, res)
AssertEqualAltCommandError(t, *tc.err, tc.altMessage, err)
return
}
require.NoError(t, err)
m := res.Map()
k := CollectKeys(t, res)
for key, item := range tc.expected {
assert.Contains(t, k, key)
if key != "log" && key != "totalLinesWritten" {
assert.Equal(t, m[key], item)
}
}
})
}
}
func TestCommandsDiagnosticHostInfo(t *testing.T) {
t.Parallel()
ctx, collection := setup.Setup(t)
var a bson.D
err := collection.Database().RunCommand(ctx, bson.D{{"hostInfo", 42}}).Decode(&a)
require.NoError(t, err)
actual := ConvertDocument(t, a)
assert.Equal(t, float64(1), must.NotFail(actual.Get("ok")))
keys := actual.Keys()
keys = slices.DeleteFunc(keys, func(val string) bool {
return val == "$clusterTime" || val == "operationTime"
})
assert.Equal(t, []string{"system", "os", "extra", "ok"}, keys)
os := must.NotFail(actual.Get("os")).(*types.Document)
assert.Equal(t, []string{"type", "name", "version"}, os.Keys())
system := must.NotFail(actual.Get("system")).(*types.Document)
keys = system.Keys()
assert.Contains(t, keys, "currentTime")
assert.Contains(t, keys, "hostname")
assert.Contains(t, keys, "cpuAddrSize")
assert.Contains(t, keys, "numCores")
assert.Contains(t, keys, "cpuArch")
}
func TestCommandsDiagnosticListCommands(t *testing.T) {
t.Parallel()
ctx, collection := setup.Setup(t)
var a bson.D
err := collection.Database().RunCommand(ctx, bson.D{{"listCommands", 42}}).Decode(&a)
require.NoError(t, err)
actual := ConvertDocument(t, a)
assert.Equal(t, float64(1), must.NotFail(actual.Get("ok")))
keys := actual.Keys()
keys = slices.DeleteFunc(keys, func(val string) bool {
return val == "$clusterTime" || val == "operationTime"
})
assert.Equal(t, []string{"commands", "ok"}, keys)
commands := must.NotFail(actual.Get("commands")).(*types.Document)
listCommands := must.NotFail(commands.Get("listCommands")).(*types.Document)
assert.NotEmpty(t, must.NotFail(listCommands.Get("help")).(string))
}
func TestCommandsDiagnosticValidate(t *testing.T) {
t.Parallel()
t.Run("Basic", func(t *testing.T) {
t.Parallel()
ctx, collection := setup.Setup(t, shareddata.Doubles)
var doc bson.D
command := bson.D{{"validate", collection.Name()}}
err := collection.Database().RunCommand(ctx, command).Decode(&doc)
require.NoError(t, err)
actual := ConvertDocument(t, doc)
expected := must.NotFail(types.NewDocument(
"ns", "TestCommandsDiagnosticValidate-Basic.TestCommandsDiagnosticValidate-Basic",
"nInvalidDocuments", int32(0),
"nNonCompliantDocuments", int32(0),
"nrecords", int32(25),
"nIndexes", int32(1),
"valid", true,
"repaired", false,
"warnings", types.MakeArray(0),
"errors", types.MakeArray(0),
"extraIndexEntries", types.MakeArray(0),
"missingIndexEntries", types.MakeArray(0),
"corruptRecords", types.MakeArray(0),
"ok", float64(1),
))
// TODO https://github.com/FerretDB/FerretDB/issues/3841
actual.Remove("uuid")
actual.Remove("keysPerIndex")
actual.Remove("indexDetails")
actual.Remove("$clusterTime")
actual.Remove("operationTime")
testutil.AssertEqual(t, expected, actual)
})
t.Run("TwoIndexes", func(t *testing.T) {
t.Parallel()
ctx, collection := setup.Setup(t, shareddata.Doubles)
_, err := collection.Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{{"a", 1}}})
require.NoError(t, err)
var doc bson.D
command := bson.D{{"validate", collection.Name()}}
err = collection.Database().RunCommand(ctx, command).Decode(&doc)
require.NoError(t, err)
actual := ConvertDocument(t, doc)
expected := must.NotFail(types.NewDocument(
"ns", "TestCommandsDiagnosticValidate-TwoIndexes.TestCommandsDiagnosticValidate-TwoIndexes",
"nInvalidDocuments", int32(0),
"nNonCompliantDocuments", int32(0),
"nrecords", int32(25),
"nIndexes", int32(2),
"valid", true,
"repaired", false,
"warnings", types.MakeArray(0),
"errors", types.MakeArray(0),
"extraIndexEntries", types.MakeArray(0),
"missingIndexEntries", types.MakeArray(0),
"corruptRecords", types.MakeArray(0),
"ok", float64(1),
))
actual.Remove("uuid")
actual.Remove("keysPerIndex")
actual.Remove("indexDetails")
actual.Remove("$clusterTime")
actual.Remove("operationTime")
testutil.AssertEqual(t, expected, actual)
})
}
func TestCommandsDiagnosticValidateError(t *testing.T) {
t.Skip("https://github.com/FerretDB/FerretDB/issues/2704")
t.Parallel()
for name, tc := range map[string]struct { //nolint:vet // for readability
command bson.D
err *mongo.CommandError
}{
"InvalidTypeDocument": {
command: bson.D{{"validate", bson.D{}}},
err: &mongo.CommandError{
Code: 73,
Name: "InvalidNamespace",
Message: "collection name has invalid type object",
},
},
"NonExistentCollection": {
command: bson.D{{"validate", "nonExistentCollection"}},
err: &mongo.CommandError{
Code: 26,
Name: "NamespaceNotFound",
Message: "Collection 'TestCommandsDiagnosticValidateError-NonExistentCollection.nonExistentCollection' does not exist to validate.",
},
},
} {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
t.Parallel()
require.NotNil(t, tc.command, "command must not be nil")
require.NotNil(t, tc.err, "err must not be nil")
ctx, collection := setup.Setup(t, shareddata.Doubles)
var res bson.D
err := collection.Database().RunCommand(ctx, tc.command).Decode(res)
assert.Nil(t, res)
AssertEqualCommandError(t, *tc.err, err)
})
}
}
func TestCommandsDiagnosticWhatsMyURI(t *testing.T) {
t.Parallel()
s := setup.SetupWithOpts(t, nil)
collection1 := s.Collection
databaseName := s.Collection.Database().Name()
collectionName := s.Collection.Name()
// only check port number on TCP connection, no need to check on Unix domain socket
isUnix := s.IsUnixSocket(t)
// setup second client connection to check that `whatsmyuri` returns different ports
client2, err := mongo.Connect(s.Ctx, options.Client().ApplyURI(s.MongoDBURI))
require.NoError(t, err)
defer client2.Disconnect(s.Ctx)
collection2 := client2.Database(databaseName).Collection(collectionName)
var ports []string
for _, collection := range []*mongo.Collection{collection1, collection2} {
var actual bson.D
command := bson.D{{"whatsmyuri", int32(1)}}
err := collection.Database().RunCommand(s.Ctx, command).Decode(&actual)
require.NoError(t, err)
doc := ConvertDocument(t, actual)
keys := doc.Keys()
values := doc.Values()
var ok float64
var you string
for i, k := range keys {
switch k {
case "ok":
ok = values[i].(float64)
case "you":
you = values[i].(string)
}
}
assert.Equal(t, float64(1), ok)
if !isUnix {
// record ports to compare that they are not equal for two different clients.
_, port, err := net.SplitHostPort(you)
require.NoError(t, err)
assert.NotEmpty(t, port)
ports = append(ports, port)
}
}
if !isUnix {
require.Equal(t, 2, len(ports))
assert.NotEqual(t, ports[0], ports[1])
}
}
// TestCommandWhatsMyURIConnection tests that integration test setup applies
// minPoolSize, maxPoolSize and maxIdleTimeMS correctly to the driver.
// It also tests that the driver behaves like we think it should.
func TestCommandWhatsMyURIConnection(t *testing.T) {
t.Parallel()
// options are applied to create a client that uses single connection pool
s := setup.SetupWithOpts(t, &setup.SetupOpts{
ExtraOptions: url.Values{
"minPoolSize": []string{"1"},
"maxPoolSize": []string{"1"},
"maxIdleTimeMS": []string{"0"},
},
})
collection1 := s.Collection
databaseName := s.Collection.Database().Name()
collectionName := s.Collection.Name()
t.Run("SameClientStress", func(t *testing.T) {
t.Parallel()
ports := make(chan string, 10)
teststress.StressN(t, len(ports), func(ready chan<- struct{}, start <-chan struct{}) {
ready <- struct{}{}
<-start
var res bson.D
err := collection1.Database().RunCommand(s.Ctx, bson.D{{"whatsmyuri", int32(1)}}).Decode(&res)
require.NoError(t, err)
doc := ConvertDocument(t, res)
v, _ := doc.Get("ok")
resOk, ok := v.(float64)
require.True(t, ok)
assert.Equal(t, float64(1), resOk)
v, _ = doc.Get("you")
you, ok := v.(string)
require.True(t, ok)
_, port, err := net.SplitHostPort(you)
require.NoError(t, err)
assert.NotEmpty(t, port)
ports <- port
})
close(ports)
firstPort := <-ports
for port := range ports {
require.Equal(t, firstPort, port, "expected same client to use the same port")
}
})
t.Run("DifferentClient", func(t *testing.T) {
t.Parallel()
u, err := url.Parse(s.MongoDBURI)
require.NoError(t, err)
client2, err := mongo.Connect(s.Ctx, options.Client().ApplyURI(u.String()))
require.NoError(t, err)
defer client2.Disconnect(s.Ctx)
collection2 := client2.Database(databaseName).Collection(collectionName)
var ports []string
for _, collection := range []*mongo.Collection{collection1, collection2} {
var res bson.D
err := collection.Database().RunCommand(s.Ctx, bson.D{{"whatsmyuri", int32(1)}}).Decode(&res)
require.NoError(t, err)
doc := ConvertDocument(t, res)
v, _ := doc.Get("ok")
resOk, ok := v.(float64)
require.True(t, ok)
assert.Equal(t, float64(1), resOk)
v, _ = doc.Get("you")
you, ok := v.(string)
require.True(t, ok)
_, port, err := net.SplitHostPort(you)
require.NoError(t, err)
assert.NotEmpty(t, port)
ports = append(ports, port)
}
require.Equal(t, 2, len(ports))
assert.NotEqual(t, ports[0], ports[1])
})
}