forked from dgraph-io/badger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_writer_test.go
580 lines (527 loc) · 15.8 KB
/
stream_writer_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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/*
* Copyright 2019 Dgraph Labs, Inc. and Contributors
*
* 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 badger
import (
"bytes"
"encoding/binary"
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v3/pb"
"github.com/dgraph-io/badger/v3/y"
"github.com/dgraph-io/ristretto/z"
)
func getSortedKVList(valueSize, listSize int) *z.Buffer {
value := make([]byte, valueSize)
y.Check2(rand.Read(value))
buf := z.NewBuffer(10 << 20)
for i := 0; i < listSize; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(i))
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
}
return buf
}
// check if we can read values after writing using stream writer
func TestStreamWriter1(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 10
valueSize := 128
list := getSortedKVList(valueSize, noOfKeys)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(list), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
err := db.View(func(txn *Txn) error {
// read any random key from inserted keys
keybyte := make([]byte, 8)
keyNo := uint64(rand.Int63n(int64(noOfKeys)))
binary.BigEndian.PutUint64(keybyte, keyNo)
_, err := txn.Get(keybyte)
require.Nil(t, err, "key should be found")
// count all keys written using stream writer
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
keysCount++
}
require.True(t, keysCount == noOfKeys, "count of keys should be matched")
return nil
})
require.NoError(t, err, "error while retrieving key")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
// write more keys to db after writing keys using stream writer
func TestStreamWriter2(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 1000
valueSize := 128
list := getSortedKVList(valueSize, noOfKeys)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(list), "sw.Write() failed")
// get max version of sw, will be used in transactions for managed mode
maxVs := sw.maxVersion
require.NoError(t, sw.Flush(), "sw.Flush() failed")
// delete all the inserted keys
val := make([]byte, valueSize)
y.Check2(rand.Read(val))
for i := 0; i < noOfKeys; i++ {
txn := db.newTransaction(true, opts.managedTxns)
if opts.managedTxns {
txn.readTs = math.MaxUint64
txn.commitTs = maxVs
}
keybyte := make([]byte, 8)
keyNo := uint64(i)
binary.BigEndian.PutUint64(keybyte, keyNo)
require.NoError(t, txn.Delete(keybyte), "error while deleting keys")
require.NoError(t, txn.Commit(), "error while commit")
}
// verify while iteration count of keys should be 0
err := db.View(func(txn *Txn) error {
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
keysCount++
}
require.Zero(t, keysCount, "count of keys should be 0")
return nil
})
require.Nil(t, err, "error should be nil while iterating")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
func TestStreamWriter3(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 1000
valueSize := 128
// insert keys which are even
value := make([]byte, valueSize)
y.Check2(rand.Read(value))
counter := 0
buf := z.NewBuffer(10 << 20)
defer buf.Release()
for i := 0; i < noOfKeys; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(counter))
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
counter = counter + 2
}
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
// get max version of sw, will be used in transactions for managed mode
maxVs := sw.maxVersion
require.NoError(t, sw.Flush(), "sw.Flush() failed")
// insert keys which are odd
val := make([]byte, valueSize)
y.Check2(rand.Read(val))
counter = 1
for i := 0; i < noOfKeys; i++ {
txn := db.newTransaction(true, opts.managedTxns)
if opts.managedTxns {
txn.readTs = math.MaxUint64
txn.commitTs = maxVs
}
keybyte := make([]byte, 8)
keyNo := uint64(counter)
binary.BigEndian.PutUint64(keybyte, keyNo)
require.NoError(t, txn.SetEntry(NewEntry(keybyte, val)),
"error while inserting entries")
require.NoError(t, txn.Commit(), "error while commit")
counter = counter + 2
}
// verify while iteration keys are in sorted order
err := db.View(func(txn *Txn) error {
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
prev := uint64(0)
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
key := item.Key()
current := binary.BigEndian.Uint64(key)
if prev != 0 && current != (prev+uint64(1)) {
t.Fatal("keys should be in increasing order")
}
keysCount++
prev = current
}
require.True(t, keysCount == 2*noOfKeys, "count of keys is not matching")
return nil
})
require.Nil(t, err, "error should be nil while iterating")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
// After inserting all data from streams, StreamWriter reinitializes Oracle and updates its nextTs
// to maxVersion found in all entries inserted(if db is running in non managed mode). It also
// updates Oracle's txnMark and readMark. If Oracle is not reinitialized, it might cause issue
// while updating readMark and txnMark when its nextTs is ahead of maxVersion. This tests verifies
// Oracle reinitialization is happening. Try commenting line 171 in stream_writer.go with code
// (sw.db.orc = newOracle(sw.db.opt), this test should fail.
func TestStreamWriter4(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// first insert some entries in db
for i := 0; i < 10; i++ {
err := db.Update(func(txn *Txn) error {
key := []byte(fmt.Sprintf("key-%d", i))
value := []byte(fmt.Sprintf("val-%d", i))
return txn.Set(key, value)
})
require.NoError(t, err, "error while updating db")
}
buf := z.NewBuffer(10 << 20)
defer buf.Release()
KVToBuffer(&pb.KV{
Key: []byte("key-1"),
Value: []byte("value-1"),
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
})
}
func TestStreamWriter5(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
left := make([]byte, 6)
left[0] = 0x00
copy(left[1:], []byte("break"))
right := make([]byte, 6)
right[0] = 0xff
copy(right[1:], []byte("break"))
buf := z.NewBuffer(10 << 20)
defer buf.Release()
KVToBuffer(&pb.KV{
Key: left,
Value: []byte("val"),
Version: 1,
}, buf)
KVToBuffer(&pb.KV{
Key: right,
Value: []byte("val"),
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
require.NoError(t, db.Close())
var err error
db, err = Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
// This test tries to insert multiple equal keys(without version) and verifies
// if those are going to same table.
func TestStreamWriter6(t *testing.T) {
opt := getTestOptions("")
opt.BaseTableSize = 1 << 15
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
str := []string{"a", "b", "c"}
ver := uint64(0)
// The baseTable size is 32 KB (1<<15) and the max table size for level
// 6 table is 1 mb (look at newWrite function). Since all the tables
// will be written to level 6, we need to insert at least 1 mb of data.
// Setting keycount below 32 would cause this test to fail.
keyCount := 40
buf := z.NewBuffer(10 << 20)
defer buf.Release()
for i := range str {
for j := 0; j < keyCount; j++ {
ver++
kv := &pb.KV{
Key: bytes.Repeat([]byte(str[i]), int(db.opt.BaseTableSize)),
Value: []byte("val"),
Version: uint64(keyCount - j),
}
KVToBuffer(kv, buf)
}
}
// list has 3 pairs for equal keys. Since each Key has size equal to MaxTableSize
// we would have 6 tables, if keys are not equal. Here we should have 3 tables.
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
tables := db.Tables()
require.Equal(t, 3, len(tables), "Count of tables not matching")
for _, tab := range tables {
require.Equal(t, keyCount, int(tab.KeyCount),
fmt.Sprintf("failed for level: %d", tab.Level))
}
require.NoError(t, db.Close())
db, err := Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
// This test uses a StreamWriter without calling Flush() at the end.
func TestStreamWriterCancel(t *testing.T) {
opt := getTestOptions("")
opt.BaseTableSize = 1 << 15
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
str := []string{"a", "a", "b", "b", "c", "c"}
ver := 1
buf := z.NewBuffer(10 << 20)
defer buf.Release()
for i := range str {
kv := &pb.KV{
Key: bytes.Repeat([]byte(str[i]), int(db.opt.BaseTableSize)),
Value: []byte("val"),
Version: uint64(ver),
}
KVToBuffer(kv, buf)
ver = (ver + 1) % 2
}
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
sw.Cancel()
// Use the API incorrectly.
sw1 := db.NewStreamWriter()
defer sw1.Cancel()
require.NoError(t, sw1.Prepare())
defer sw1.Cancel()
sw1.Flush()
})
}
func TestStreamDone(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
for i := 0; i < 10; i++ {
buf := z.NewBuffer(10 << 20)
defer buf.Release()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", i)),
Value: val[:],
Version: 1,
StreamId: uint32(i),
}
kv2 := &pb.KV{
StreamId: uint32(i),
StreamDone: true,
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
require.NoError(t, sw.Write(buf), "sw.Write() failed")
}
require.NoError(t, sw.Flush(), "sw.Flush() failed")
require.NoError(t, db.Close())
var err error
db, err = Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
func TestSendOnClosedStream(t *testing.T) {
dir, err := ioutil.TempDir("", "badger-test")
require.NoError(t, err)
defer func() {
require.NoError(t, os.RemoveAll(dir))
}()
opts := getTestOptions(dir)
db, err := Open(opts)
require.NoError(t, err)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
buf := z.NewBuffer(10 << 20)
defer buf.Release()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 1)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
kv2 := &pb.KV{
StreamId: uint32(1),
StreamDone: true,
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
require.NoError(t, sw.Write(buf), "sw.Write() failed")
// Defer for panic.
defer func() {
require.NotNil(t, recover(), "should have paniced")
require.NoError(t, sw.Flush())
require.NoError(t, db.Close())
}()
// Send once stream is closed.
buf1 := z.NewBuffer(10 << 20)
defer buf1.Release()
kv1 = &pb.KV{
Key: []byte(fmt.Sprintf("%d", 2)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
KVToBuffer(kv1, buf1)
sw.Write(buf1)
}
func TestSendOnClosedStream2(t *testing.T) {
dir, err := ioutil.TempDir("", "badger-test")
require.NoError(t, err)
defer func() {
require.NoError(t, os.RemoveAll(dir))
}()
opts := getTestOptions(dir)
db, err := Open(opts)
require.NoError(t, err)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
buf := z.NewBuffer(10 << 20)
defer buf.Release()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 1)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
kv2 := &pb.KV{
StreamId: uint32(1),
StreamDone: true,
}
kv3 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 2)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
KVToBuffer(kv3, buf)
// Defer for panic.
defer func() {
require.NotNil(t, recover(), "should have paniced")
require.NoError(t, sw.Flush())
require.NoError(t, db.Close())
}()
require.NoError(t, sw.Write(buf), "sw.Write() failed")
}
func TestStreamWriterEncrypted(t *testing.T) {
dir, err := ioutil.TempDir("", "badger-test")
require.NoError(t, err)
opts := DefaultOptions(dir)
defer removeDir(dir)
opts = opts.WithEncryptionKey([]byte("badgerkey16bytes"))
opts.BlockCacheSize = 100 << 20
opts.IndexCacheSize = 100 << 20
db, err := Open(opts)
require.NoError(t, err)
key := []byte("mykey")
value := []byte("myvalue")
buf := z.NewBuffer(10 << 20)
defer buf.Release()
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "Prepare failed")
require.NoError(t, sw.Write(buf), "Write failed")
require.NoError(t, sw.Flush(), "Flush failed")
err = db.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.Equal(t, value, val)
require.NoError(t, err)
return nil
})
require.NoError(t, err, "Error while retrieving key")
require.NoError(t, db.Close())
db, err = Open(opts)
require.NoError(t, err)
require.NoError(t, db.Close())
}