-
Notifications
You must be signed in to change notification settings - Fork 468
/
event_listener_test.go
382 lines (345 loc) · 10.1 KB
/
event_listener_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
// Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"bytes"
"context"
"fmt"
"reflect"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/objstorage/objstorageprovider"
"github.com/cockroachdb/pebble/sstable"
"github.com/cockroachdb/pebble/vfs"
"github.com/cockroachdb/redact"
"github.com/stretchr/testify/require"
)
// Verify event listener actions, as well as expected filesystem operations.
func TestEventListener(t *testing.T) {
if runtime.GOARCH == "386" {
t.Skip("skipped on 32-bit due to slightly varied output")
}
var d *DB
var memLog base.InMemLogger
mem := vfs.NewMem()
require.NoError(t, mem.MkdirAll("ext", 0755))
datadriven.RunTest(t, "testdata/event_listener", func(t *testing.T, td *datadriven.TestData) string {
switch td.Cmd {
case "open":
memLog.Reset()
lel := MakeLoggingEventListener(&memLog)
flushBegin, flushEnd := lel.FlushBegin, lel.FlushEnd
lel.FlushBegin = func(info FlushInfo) {
// Make deterministic.
info.InputBytes = 100
flushBegin(info)
}
lel.FlushEnd = func(info FlushInfo) {
// Make deterministic.
info.InputBytes = 100
flushEnd(info)
}
opts := &Options{
// The table stats collector runs asynchronously and its
// timing is less predictable. It increments nextJobID, which
// can make these tests flaky. The TableStatsLoaded event is
// tested separately in TestTableStats.
DisableTableStats: true,
FS: vfs.WithLogging(mem, memLog.Infof),
FormatMajorVersion: internalFormatNewest,
EventListener: &lel,
MaxManifestFileSize: 1,
L0CompactionThreshold: 10,
WALDir: "wal",
}
opts.Experimental.EnableColumnarBlocks = func() bool { return true }
var err error
d, err = Open("db", opts)
if err != nil {
return err.Error()
}
t := time.Now()
d.timeNow = func() time.Time {
t = t.Add(time.Second)
return t
}
d.opts.private.testingAlwaysWaitForCleanup = true
return memLog.String()
case "close":
memLog.Reset()
if err := d.Close(); err != nil {
return err.Error()
}
return memLog.String()
case "flush":
memLog.Reset()
if err := d.Set([]byte("a"), nil, nil); err != nil {
return err.Error()
}
if err := d.Flush(); err != nil {
return err.Error()
}
return memLog.String()
case "compact":
memLog.Reset()
if err := d.Set([]byte("a"), nil, nil); err != nil {
return err.Error()
}
if err := d.Compact([]byte("a"), []byte("b"), false); err != nil {
return err.Error()
}
return memLog.String()
case "checkpoint":
memLog.Reset()
if err := d.Checkpoint("checkpoint"); err != nil {
return err.Error()
}
return memLog.String()
case "disable-file-deletions":
memLog.Reset()
d.mu.Lock()
d.disableFileDeletions()
d.mu.Unlock()
return memLog.String()
case "enable-file-deletions":
memLog.Reset()
func() {
defer func() {
if r := recover(); r != nil {
memLog.Infof("%v", r)
}
}()
d.mu.Lock()
defer d.mu.Unlock()
d.enableFileDeletions()
}()
d.TestOnlyWaitForCleaning()
return memLog.String()
case "ingest":
memLog.Reset()
f, err := mem.Create("ext/0", vfs.WriteCategoryUnspecified)
if err != nil {
return err.Error()
}
w := sstable.NewWriter(objstorageprovider.NewFileWritable(f), sstable.WriterOptions{
TableFormat: d.TableFormat(),
})
if err := w.Set([]byte("a"), nil); err != nil {
return err.Error()
}
if err := w.Close(); err != nil {
return err.Error()
}
if err := d.Ingest(context.Background(), []string{"ext/0"}); err != nil {
return err.Error()
}
return memLog.String()
case "ingest-flushable":
memLog.Reset()
// Prevent flushes during this test to ensure determinism.
d.mu.Lock()
d.mu.compact.flushing = true
d.mu.Unlock()
b := d.NewBatch()
if err := b.Set([]byte("a"), nil, nil); err != nil {
return err.Error()
}
if err := d.Apply(b, nil); err != nil {
return err.Error()
}
writeTable := func(name string, key byte) error {
f, err := mem.Create(name, vfs.WriteCategoryUnspecified)
if err != nil {
return err
}
w := sstable.NewWriter(objstorageprovider.NewFileWritable(f), sstable.WriterOptions{
TableFormat: d.TableFormat(),
})
if err := w.Set([]byte{key}, nil); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
return nil
}
tableA, tableB := "ext/a", "ext/b"
if err := writeTable(tableA, 'a'); err != nil {
return err.Error()
}
if err := writeTable(tableB, 'b'); err != nil {
return err.Error()
}
if err := d.Ingest(context.Background(), []string{tableA, tableB}); err != nil {
return err.Error()
}
// Re-enable flushes, to allow the subsequent flush to proceed.
d.mu.Lock()
d.mu.compact.flushing = false
d.mu.Unlock()
if err := d.Flush(); err != nil {
return err.Error()
}
return memLog.String()
case "metrics":
// The asynchronous loading of table stats can change metrics, so
// wait for all the tables' stats to be loaded.
d.mu.Lock()
d.waitTableStats()
d.mu.Unlock()
return d.Metrics().StringForTests()
case "sstables":
var buf bytes.Buffer
tableInfos, _ := d.SSTables()
for i, level := range tableInfos {
if len(level) == 0 {
continue
}
fmt.Fprintf(&buf, "%d:\n", i)
for _, m := range level {
fmt.Fprintf(&buf, " %d:[%s-%s]\n",
m.FileNum, m.Smallest.UserKey, m.Largest.UserKey)
}
}
return buf.String()
default:
return fmt.Sprintf("unknown command: %s", td.Cmd)
}
})
}
func TestWriteStallEvents(t *testing.T) {
const flushCount = 10
const writeStallEnd = "write stall ending"
testCases := []struct {
delayFlush bool
expected string
}{
{true, "memtable count limit reached"},
{false, "L0 file count limit exceeded"},
}
for _, c := range testCases {
t.Run("", func(t *testing.T) {
stallEnded := make(chan struct{}, 1)
createReleased := make(chan struct{}, flushCount)
var log base.InMemLogger
var delayOnce sync.Once
listener := &EventListener{
TableCreated: func(info TableCreateInfo) {
if c.delayFlush == (info.Reason == "flushing") {
delayOnce.Do(func() {
<-createReleased
})
}
},
WriteStallBegin: func(info WriteStallBeginInfo) {
log.Infof("%s", info.String())
createReleased <- struct{}{}
},
WriteStallEnd: func() {
log.Infof("%s", writeStallEnd)
select {
case stallEnded <- struct{}{}:
default:
}
},
}
d, err := Open("db", &Options{
EventListener: listener,
FS: vfs.NewMem(),
MemTableSize: initialMemTableSize,
MemTableStopWritesThreshold: 2,
L0CompactionThreshold: 2,
L0StopWritesThreshold: 2,
})
require.NoError(t, err)
defer d.Close()
for i := 0; i < flushCount; i++ {
require.NoError(t, d.Set([]byte("a"), nil, NoSync))
ch, err := d.AsyncFlush()
require.NoError(t, err)
// If we're delaying the flush (because we're testing for memtable
// write stalls), we can't wait for the flush to finish as doing so
// would deadlock. If we're not delaying the flush (because we're
// testing for L0 write stals), we wait for the flush to finish so we
// don't create too many memtables which would trigger a memtable write
// stall.
if !c.delayFlush {
<-ch
}
if strings.Contains(log.String(), c.expected) {
break
}
}
<-stallEnded
events := log.String()
require.Contains(t, events, c.expected)
require.Contains(t, events, writeStallEnd)
if testing.Verbose() {
t.Logf("\n%s", events)
}
})
}
}
type redactLogger struct {
logger Logger
}
// Infof implements the Logger.Infof interface.
func (l redactLogger) Infof(format string, args ...interface{}) {
l.logger.Infof("%s", redact.Sprintf(format, args...).Redact())
}
// Errorf implements the Logger.Errorf interface.
func (l redactLogger) Errorf(format string, args ...interface{}) {
l.logger.Errorf("%s", redact.Sprintf(format, args...).Redact())
}
// Fatalf implements the Logger.Fatalf interface.
func (l redactLogger) Fatalf(format string, args ...interface{}) {
l.logger.Fatalf("%s", redact.Sprintf(format, args...).Redact())
}
func TestEventListenerRedact(t *testing.T) {
// The vast majority of event listener fields logged are safe and do not
// need to be redacted. Verify that the rare, unsafe error does appear in
// the log redacted.
var log base.InMemLogger
l := MakeLoggingEventListener(redactLogger{logger: &log})
l.WALDeleted(WALDeleteInfo{
JobID: 5,
FileNum: base.DiskFileNum(20),
Err: errors.Errorf("unredacted error: %s", "unredacted string"),
})
require.Equal(t, "[JOB 5] WAL delete error: unredacted error: ‹×›\n", log.String())
}
func TestEventListenerEnsureDefaultsBackgroundError(t *testing.T) {
e := EventListener{}
e.EnsureDefaults(nil)
e.BackgroundError(errors.New("an example error"))
}
func TestEventListenerEnsureDefaultsSetsAllCallbacks(t *testing.T) {
e := EventListener{}
e.EnsureDefaults(nil)
testAllCallbacksSetInEventListener(t, e)
}
func TestMakeLoggingEventListenerSetsAllCallbacks(t *testing.T) {
e := MakeLoggingEventListener(nil)
testAllCallbacksSetInEventListener(t, e)
}
func TestTeeEventListenerSetsAllCallbacks(t *testing.T) {
e := TeeEventListener(EventListener{}, EventListener{})
testAllCallbacksSetInEventListener(t, e)
}
func testAllCallbacksSetInEventListener(t *testing.T, e EventListener) {
t.Helper()
v := reflect.ValueOf(e)
for i := 0; i < v.NumField(); i++ {
fType := v.Type().Field(i)
fVal := v.Field(i)
require.Equal(t, reflect.Func, fType.Type.Kind(), "unexpected non-func field: %s", fType.Name)
require.False(t, fVal.IsNil(), "unexpected nil field: %s", fType.Name)
}
}