-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbadger_store.go
363 lines (317 loc) · 9.12 KB
/
badger_store.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
/*
Copyright 2018-2019 Banco Bilbao Vizcaya Argentaria, S.A.
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 raftbadger
import (
"errors"
"time"
"github.com/dgraph-io/badger/v3"
"github.com/hashicorp/raft"
)
var (
// Prefix names to distingish between logs and conf
prefixLogs = []byte{0x0}
prefixConf = []byte{0x1}
// ErrKeyNotFound is an error indicating a given key does not exist
ErrKeyNotFound = errors.New("not found")
)
// BadgerStore provides access to Badger for Raft to store and retrieve
// log entries. It also provides key/value storage, and can be used as
// a LogStore and StableStore.
type BadgerStore struct {
// conn is the underlying handle to the db.
conn *badger.DB
// The path to the Badger database directory.
path string
vlogTicker *time.Ticker // runs every 1m, check size of vlog and run GC conditionally.
mandatoryVlogTicker *time.Ticker // runs every 10m, we always run vlog GC.
}
// Options contains all the configuration used to open the Badger db
type Options struct {
// Path is the directory path to the Badger db to use.
Path string
// BadgerOptions contains any specific Badger options you might
// want to specify.
BadgerOptions *badger.Options
// NoSync causes the database to skip fsync calls after each
// write to the log. This is unsafe, so it should be used
// with caution.
NoSync bool
// ValueLogGC enables a periodic goroutine that does a garbage
// collection of the value log while the underlying Badger is online.
ValueLogGC bool
// GCInterval is the interval between conditionally running the garbage
// collection process, based on the size of the vlog. By default, runs every 1m.
GCInterval time.Duration
// GCInterval is the interval between mandatory running the garbage
// collection process. By default, runs every 10m.
MandatoryGCInterval time.Duration
// GCThreshold sets threshold in bytes for the vlog size to be included in the
// garbage collection cycle. By default, 1GB.
GCThreshold int64
}
// NewBadgerStore takes a file path and returns a connected Raft backend.
func NewBadgerStore(path string) (*BadgerStore, error) {
return New(Options{Path: path})
}
// func NewDefaultStableStore(path string) (*BadgerStore, error) {
// opts := badger.DefaultOptions
// opts.MaxLevels = 2
// return New(Options{Path: path, BadgerOptions: &opts})
// }
// New uses the supplied options to open the Badger db and prepare it for
// use as a raft backend.
func New(options Options) (*BadgerStore, error) {
// build badger options
if options.BadgerOptions == nil {
defaultOpts := badger.DefaultOptions(options.Path)
options.BadgerOptions = &defaultOpts
}
options.BadgerOptions.SyncWrites = !options.NoSync
// Try to connect
handle, err := badger.Open(*options.BadgerOptions)
if err != nil {
return nil, err
}
// Create the new store
store := &BadgerStore{
conn: handle,
path: options.Path,
}
// Start GC routine
if options.ValueLogGC {
var gcInterval time.Duration
var mandatoryGCInterval time.Duration
var threshold int64
if gcInterval = 1 * time.Minute; options.GCInterval != 0 {
gcInterval = options.GCInterval
}
if mandatoryGCInterval = 10 * time.Minute; options.MandatoryGCInterval != 0 {
mandatoryGCInterval = options.MandatoryGCInterval
}
if threshold = int64(1 << 30); options.GCThreshold != 0 {
threshold = options.GCThreshold
}
store.vlogTicker = time.NewTicker(gcInterval)
store.mandatoryVlogTicker = time.NewTicker(mandatoryGCInterval)
go store.runVlogGC(handle, threshold)
}
return store, nil
}
func (b *BadgerStore) runVlogGC(db *badger.DB, threshold int64) {
// Get initial size on start.
_, lastVlogSize := db.Size()
runGC := func() {
var err error
for err == nil {
// If a GC is successful, immediately run it again.
err = db.RunValueLogGC(0.7)
}
_, lastVlogSize = db.Size()
}
for {
select {
case <-b.vlogTicker.C:
_, currentVlogSize := db.Size()
if currentVlogSize < lastVlogSize+threshold {
continue
}
runGC()
case <-b.mandatoryVlogTicker.C:
runGC()
}
}
}
// Close is used to gracefully close the DB connection.
func (b *BadgerStore) Close() error {
if b.vlogTicker != nil {
b.vlogTicker.Stop()
}
if b.mandatoryVlogTicker != nil {
b.mandatoryVlogTicker.Stop()
}
return b.conn.Close()
}
// FirstIndex returns the first known index from the Raft log.
func (b *BadgerStore) FirstIndex() (uint64, error) {
var value uint64
err := b.conn.View(func(txn *badger.Txn) error {
it := txn.NewIterator(badger.IteratorOptions{
PrefetchValues: false,
Reverse: false,
})
defer it.Close()
it.Seek(prefixLogs)
if it.ValidForPrefix(prefixLogs) {
value = bytesToUint64(it.Item().Key()[1:])
}
return nil
})
if err != nil {
return 0, err
}
return value, nil
}
// LastIndex returns the last known index from the Raft log.
func (b *BadgerStore) LastIndex() (uint64, error) {
var value uint64
err := b.conn.View(func(txn *badger.Txn) error {
it := txn.NewIterator(badger.IteratorOptions{
PrefetchValues: false,
Reverse: true,
})
defer it.Close()
it.Seek(append(prefixLogs, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff))
if it.ValidForPrefix(prefixLogs) {
value = bytesToUint64(it.Item().Key()[1:])
}
return nil
})
if err != nil {
return 0, err
}
return value, nil
}
// GetLog gets a log entry from Badger at a given index.
func (b *BadgerStore) GetLog(index uint64, log *raft.Log) error {
return b.conn.View(func(txn *badger.Txn) error {
item, err := txn.Get(append(prefixLogs, uint64ToBytes(index)...))
if err != nil {
switch err {
case badger.ErrKeyNotFound:
return raft.ErrLogNotFound
default:
return err
}
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
return decodeMsgPack(val, log)
})
}
// StoreLog stores a single raft log.
func (b *BadgerStore) StoreLog(log *raft.Log) error {
val, err := encodeMsgPack(log)
if err != nil {
return err
}
return b.conn.Update(func(txn *badger.Txn) error {
return txn.Set(append(prefixLogs, uint64ToBytes(log.Index)...), val.Bytes())
})
}
// StoreLogs stores a set of raft logs.
func (b *BadgerStore) StoreLogs(logs []*raft.Log) error {
// we manage the transaction manually in order to avoid ErrTxnTooBig errors
txn := b.conn.NewTransaction(true)
for i, log := range logs {
key := append(prefixLogs, uint64ToBytes(log.Index)...)
val, err := encodeMsgPack(log)
if err != nil {
return err
}
if err := txn.Set(key, val.Bytes()); err != nil {
if err == badger.ErrTxnTooBig {
err = txn.Commit()
if err != nil {
return err
}
return b.StoreLogs(logs[i:])
}
return err
}
}
err := txn.Commit()
if err != nil {
return err
}
return nil
}
// DeleteRange deletes logs within a given range inclusively.
func (b *BadgerStore) DeleteRange(min, max uint64) error {
// we manage the transaction manually in order to avoid ErrTxnTooBig errors
txn := b.conn.NewTransaction(true)
it := txn.NewIterator(badger.IteratorOptions{
PrefetchValues: false,
Reverse: false,
})
start := append(prefixLogs, uint64ToBytes(min)...)
for it.Seek(start); it.Valid(); it.Next() {
key := make([]byte, 9)
it.Item().KeyCopy(key)
// Handle out-of-range log index
if bytesToUint64(key[1:]) > max {
break
}
// Delete in-range log index
if err := txn.Delete(key); err != nil {
if err == badger.ErrTxnTooBig {
it.Close()
err = txn.Commit()
if err != nil {
return err
}
return b.DeleteRange(bytesToUint64(key[1:]), max)
}
return err
}
}
it.Close()
err := txn.Commit()
if err != nil {
return err
}
return nil
}
// Set is used to set a key/value set outside of the raft log.
func (b *BadgerStore) Set(key []byte, val []byte) error {
return b.conn.Update(func(txn *badger.Txn) error {
return txn.Set(append(prefixConf, key...), val)
})
}
// Get is used to retrieve a value from the k/v store by key
func (b *BadgerStore) Get(key []byte) ([]byte, error) {
var value []byte
err := b.conn.View(func(txn *badger.Txn) error {
item, err := txn.Get(append(prefixConf, key...))
if err != nil {
switch err {
case badger.ErrKeyNotFound:
return ErrKeyNotFound
default:
return err
}
}
value, err = item.ValueCopy(value)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return value, nil
}
// SetUint64 is like Set, but handles uint64 values
func (b *BadgerStore) SetUint64(key []byte, val uint64) error {
return b.Set(key, uint64ToBytes(val))
}
// GetUint64 is like Get, but handles uint64 values
func (b *BadgerStore) GetUint64(key []byte) (uint64, error) {
val, err := b.Get(key)
if err != nil {
return 0, err
}
return bytesToUint64(val), nil
}