forked from mongodb/mongo-go-driver
/
logger_verification.go
369 lines (299 loc) · 9.99 KB
/
logger_verification.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
// Copyright (C) MongoDB, Inc. 2023-present.
//
// 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
package unified
import (
"context"
"fmt"
"sync"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/internal/logger"
)
// errLoggerVerification is use to wrap errors associated with validating the
// correctness of logs while testing operations.
var errLoggerVerification = fmt.Errorf("logger verification failed")
// logMessage is a log message that is expected to be observed by the driver.
type logMessage struct {
LevelLiteral string `bson:"level"`
ComponentLiteral string `bson:"component"`
Data bson.Raw `bson:"data"`
FailureIsRedacted bool `bson:"failureIsRedacted"`
}
// newLogMessage will create a "logMessage" from the level and a slice of
// arguments.
func newLogMessage(level int, msg string, args ...interface{}) (*logMessage, error) {
logMessage := new(logMessage)
// Iterate over the literal levels until we get the first
// "LevelLiteral" that matches the level of the "LogMessage". It doesn't
// matter which literal is chose so long as the mapping results in the
// correct level.
for literal, logLevel := range logger.LevelLiteralMap {
if level == int(logLevel) {
logMessage.LevelLiteral = literal
break
}
}
// The argument slice must have an even number of elements, otherwise it
// would not maintain the key-value structure of the document.
if len(args)%2 != 0 {
return nil, fmt.Errorf("%w: invalid arguments: %v", errLoggerVerification, args)
}
// Create a new document from the arguments.
actualD := bson.D{{"message", msg}}
for i := 0; i < len(args); i += 2 {
actualD = append(actualD, bson.E{
Key: args[i].(string),
Value: args[i+1],
})
}
// Marshal the document into a raw value and assign it to the
// logMessage.
bytes, err := bson.Marshal(actualD)
if err != nil {
return nil, fmt.Errorf("%w: failed to marshal: %v", errLoggerVerification, err)
}
logMessage.Data = bson.Raw(bytes)
return logMessage, nil
}
// clientLogMessages is a struct representing the expected "LogMessages" for a
// client.
type clientLogMessages struct {
Client string `bson:"client"`
IgnoreMessages []*logMessage `bson:"ignoreMessages"`
LogMessages []*logMessage `bson:"messages"`
}
// logMessageValidator defines the expectation for log messages across all
// clients.
type logMessageValidator struct {
testCase *TestCase
clientErrs map[string]chan error
}
// newLogMessageValidator will create a new logMessageValidator.
func newLogMessageValidator(testCase *TestCase) *logMessageValidator {
validator := &logMessageValidator{testCase: testCase}
validator.clientErrs = make(map[string]chan error)
// Make the error channels for the clients.
for _, exp := range testCase.ExpectLogMessages {
validator.clientErrs[exp.Client] = make(chan error)
}
return validator
}
func logQueue(ctx context.Context, exp *clientLogMessages) <-chan orderedLogMessage {
clients := entities(ctx).clients()
clientEntity, ok := clients[exp.Client]
if !ok {
return nil
}
return clientEntity.logQueue
}
// verifyLogMatch will verify that the actual log match the expected log.
func verifyLogMatch(ctx context.Context, exp, act *logMessage) error {
if act == nil && exp == nil {
return nil
}
if act == nil || exp == nil {
return fmt.Errorf("%w: document mismatch", errLoggerVerification)
}
levelExp := logger.ParseLevel(exp.LevelLiteral)
levelAct := logger.ParseLevel(act.LevelLiteral)
// The levels of the expected log message and the actual log message
// must match, upto logger.Level.
if levelExp != levelAct {
return fmt.Errorf("%w: level mismatch: want %v, got %v",
errLoggerVerification, levelExp, levelAct)
}
rawExp := documentToRawValue(exp.Data)
rawAct := documentToRawValue(act.Data)
// Top level data does not have to be 1-1 with the expectation, there
// are a number of unrequired fields that may not be present on the
// expected document.
if err := verifyValuesMatch(ctx, rawExp, rawAct, true); err != nil {
return fmt.Errorf("%w: document length mismatch: %v", errLoggerVerification, err)
}
return nil
}
// isUnorderedLog will return true if the log is/should be unordered in the Go
// Driver.
func isUnorderedLog(log *logMessage) bool {
msg, err := log.Data.LookupErr(logger.KeyMessage)
if err != nil {
return false
}
msgStr := msg.StringValue()
// There is a race condition in the connection pool's workflow where it
// is non-deterministic whether the connection pool will fail a checkout
// or close a connection first. Because of this, either log may be
// received in any order. To account for this behavior, we considered
// both logs to be "unordered".
//
// The connection pool must clear before the connection is closed.
// However, either of these conditions are valid:
//
// 1. connection checkout failed > connection pool cleared
// 2. connection pool cleared > connection checkout failed
//
// Therefore, the ConnectionPoolCleared literal is added to the
// unordered list. The check for cleared > closed is made in the
// matching logic.
return msgStr == logger.ConnectionCheckoutFailed ||
msgStr == logger.ConnectionClosed ||
msgStr == logger.ConnectionPoolCleared
}
type logQueues struct {
expected *clientLogMessages
ordered <-chan *logMessage
unordered <-chan *logMessage
}
// partitionLogQueue will partition the expected logs into "unordered" and
// "ordered" log channels.
func partitionLogQueue(ctx context.Context, exp *clientLogMessages) logQueues {
orderedLogCh := make(chan *logMessage, len(exp.LogMessages))
unorderedLogCh := make(chan *logMessage, len(exp.LogMessages))
// Get the unordered indices from the expected log messages.
unorderedIndices := make(map[int]struct{})
for i, log := range exp.LogMessages {
if isUnorderedLog(log) {
unorderedIndices[i] = struct{}{}
}
}
go func() {
defer close(orderedLogCh)
defer close(unorderedLogCh)
for actual := range logQueue(ctx, exp) {
msg := actual.logMessage
if _, ok := unorderedIndices[actual.order-2]; ok {
unorderedLogCh <- msg
} else {
orderedLogCh <- msg
}
}
}()
return logQueues{
expected: exp,
ordered: orderedLogCh,
unordered: unorderedLogCh,
}
}
func matchOrderedLogs(ctx context.Context, logs logQueues) <-chan error {
// Remove all of the unordered log messages from the expected.
expLogMessages := make([]*logMessage, 0, len(logs.expected.LogMessages))
for _, log := range logs.expected.LogMessages {
if !isUnorderedLog(log) {
expLogMessages = append(expLogMessages, log)
}
}
errs := make(chan error, 1)
go func() {
defer close(errs)
for actual := range logs.ordered {
expected := expLogMessages[0]
if expected == nil {
continue
}
err := verifyLogMatch(ctx, expected, actual)
if err != nil {
errs <- err
}
// Remove the first element from the expected log.
expLogMessages = expLogMessages[1:]
}
}()
return errs
}
func matchUnorderedLogs(ctx context.Context, logs logQueues) <-chan error {
unordered := make(map[*logMessage]struct{}, len(logs.expected.LogMessages))
for _, log := range logs.expected.LogMessages {
if isUnorderedLog(log) {
unordered[log] = struct{}{}
}
}
errs := make(chan error, 1)
go func() {
defer close(errs)
// Record the message literals as they occur.
actualMessageSet := map[string]bool{}
for actual := range logs.unordered {
msg, err := actual.Data.LookupErr(logger.KeyMessage)
if err != nil {
errs <- fmt.Errorf("could not lookup message from unordered log: %w", err)
break
}
msgStr := msg.StringValue()
if msgStr == logger.ConnectionPoolCleared && actualMessageSet[logger.ConnectionClosed] {
errs <- fmt.Errorf("connection has been closed before the pool could clear")
}
// Iterate over the unordered log messages and verify
// that at least one of them matches the actual log
// message.
for expected := range unordered {
err = verifyLogMatch(ctx, expected, actual)
if err == nil {
// Remove the matched unordered log
// message from the unordered map.
delete(unordered, expected)
break
}
}
// If there was no match, return an error.
if err != nil {
errs <- err
}
actualMessageSet[msgStr] = true
}
}()
return errs
}
// startLogValidators will start a goroutine for each client's expected log
// messages, listening to the channel of actual log messages and comparing them
// to the expected log messages.
func startLogValidators(ctx context.Context, validator *logMessageValidator) {
for _, expected := range validator.testCase.ExpectLogMessages {
logs := partitionLogQueue(ctx, expected)
wg := &sync.WaitGroup{}
wg.Add(2)
go func(expected *clientLogMessages) {
defer wg.Done()
errCh := matchOrderedLogs(ctx, logs)
if errCh == nil {
return
}
if errs := <-errCh; errs != nil {
validator.clientErrs[expected.Client] <- errs
}
}(expected)
go func(expected *clientLogMessages) {
defer wg.Done()
errCh := matchUnorderedLogs(ctx, logs)
if errCh == nil {
return
}
if errs := <-errCh; errs != nil {
validator.clientErrs[expected.Client] <- errs
}
}(expected)
go func(expected *clientLogMessages) {
wg.Wait()
close(validator.clientErrs[expected.Client])
}(expected)
}
}
func stopLogValidatorsErr(clientName string, err error) error {
return fmt.Errorf("%w: %s: %v", errLoggerVerification, clientName, err)
}
// stopLogValidators will gracefully validate all log messages received by all
// clients and return the first error encountered.
func stopLogValidators(ctx context.Context, validator *logMessageValidator) error {
for clientName, errChan := range validator.clientErrs {
select {
case err := <-errChan:
if err != nil {
return stopLogValidatorsErr(clientName, err)
}
case <-ctx.Done():
return stopLogValidatorsErr(clientName, ctx.Err())
}
}
return nil
}