-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger.go
72 lines (64 loc) · 1.61 KB
/
badger.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
package storage
import (
"time"
"github.com/MixinNetwork/mixin/config"
"github.com/MixinNetwork/mixin/logger"
"github.com/dgraph-io/badger/v2"
"github.com/dgraph-io/badger/v2/options"
)
type BadgerStore struct {
custom *config.Custom
snapshotsDB *badger.DB
cacheDB *badger.DB
closing bool
}
func NewBadgerStore(custom *config.Custom, dir string) (*BadgerStore, error) {
snapshotsDB, err := openDB(dir+"/snapshots", true, custom.Storage.ValueLogGC, custom.Storage.Truncate)
if err != nil {
return nil, err
}
cacheDB, err := openDB(dir+"/cache", false, custom.Storage.ValueLogGC, true)
if err != nil {
return nil, err
}
return &BadgerStore{
custom: custom,
snapshotsDB: snapshotsDB,
cacheDB: cacheDB,
closing: false,
}, nil
}
func (store *BadgerStore) Close() error {
store.closing = true
err := store.snapshotsDB.Close()
if err != nil {
return err
}
return store.cacheDB.Close()
}
func openDB(dir string, sync, valueLogGC, truncate bool) (*badger.DB, error) {
opts := badger.DefaultOptions(dir)
opts = opts.WithSyncWrites(sync)
opts = opts.WithCompression(options.None)
opts = opts.WithBlockCacheSize(0)
opts = opts.WithIndexCacheSize(0)
opts = opts.WithTruncate(truncate)
db, err := badger.Open(opts)
if err != nil {
return nil, err
}
if valueLogGC {
go func() {
for {
lsm, vlog := db.Size()
logger.Printf("Badger LSM %d VLOG %d\n", lsm, vlog)
if lsm > 1024*1024*8 || vlog > 1024*1024*32 {
err := db.RunValueLogGC(0.5)
logger.Printf("Badger RunValueLogGC %v\n", err)
}
time.Sleep(5 * time.Minute)
}
}()
}
return db, nil
}