-
Notifications
You must be signed in to change notification settings - Fork 661
/
db.go
396 lines (349 loc) · 12.6 KB
/
db.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package leveldb
import (
"bytes"
"encoding/json"
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/errors"
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/iterator"
"github.com/syndtr/goleveldb/leveldb/opt"
"github.com/syndtr/goleveldb/leveldb/util"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/logging"
)
const (
// Name is the name of this database for database switches
Name = "leveldb"
// BlockCacheSize is the number of bytes to use for block caching in
// leveldb.
BlockCacheSize = 12 * opt.MiB
// WriteBufferSize is the number of bytes to use for buffers in leveldb.
WriteBufferSize = 12 * opt.MiB
// HandleCap is the number of files descriptors to cap levelDB to use.
HandleCap = 1024
// BitsPerKey is the number of bits to add to the bloom filter per key.
BitsPerKey = 10
// levelDBByteOverhead is the number of bytes of constant overhead that
// should be added to a batch size per operation.
levelDBByteOverhead = 8
)
var (
_ database.Database = &Database{}
_ database.Batch = &batch{}
_ database.Iterator = &iter{}
)
// Database is a persistent key-value store. Apart from basic data storage
// functionality it also supports batch writes and iterating over the keyspace
// in binary-alphabetical order.
type Database struct {
*leveldb.DB
closed utils.AtomicBool
}
type config struct {
// BlockCacheCapacity defines the capacity of the 'sorted table' block caching.
// Use -1 for zero, this has same effect as specifying NoCacher to BlockCacher.
//
// The default value is 12MiB.
BlockCacheCapacity int `json:"blockCacheCapacity"`
// BlockSize is the minimum uncompressed size in bytes of each 'sorted table'
// block.
//
// The default value is 4KiB.
BlockSize int `json:"blockSize"`
// CompactionExpandLimitFactor limits compaction size after expanded.
// This will be multiplied by table size limit at compaction target level.
//
// The default value is 25.
CompactionExpandLimitFactor int `json:"compactionExpandLimitFactor"`
// CompactionGPOverlapsFactor limits overlaps in grandparent (Level + 2)
// that a single 'sorted table' generates. This will be multiplied by
// table size limit at grandparent level.
//
// The default value is 10.
CompactionGPOverlapsFactor int `json:"compactionGPOverlapsFactor"`
// CompactionL0Trigger defines number of 'sorted table' at level-0 that will
// trigger compaction.
//
// The default value is 4.
CompactionL0Trigger int `json:"compactionL0Trigger"`
// CompactionSourceLimitFactor limits compaction source size. This doesn't apply to
// level-0.
// This will be multiplied by table size limit at compaction target level.
//
// The default value is 1.
CompactionSourceLimitFactor int `json:"compactionSourceLimitFactor"`
// CompactionTableSize limits size of 'sorted table' that compaction generates.
// The limits for each level will be calculated as:
// CompactionTableSize * (CompactionTableSizeMultiplier ^ Level)
// The multiplier for each level can also fine-tuned using CompactionTableSizeMultiplierPerLevel.
//
// The default value is 2MiB.
CompactionTableSize int `json:"compactionTableSize"`
// CompactionTableSizeMultiplier defines multiplier for CompactionTableSize.
//
// The default value is 1.
CompactionTableSizeMultiplier float64 `json:"compactionTableSizeMultiplier"`
// CompactionTableSizeMultiplierPerLevel defines per-level multiplier for
// CompactionTableSize.
// Use zero to skip a level.
//
// The default value is nil.
CompactionTableSizeMultiplierPerLevel []float64 `json:"compactionTableSizeMultiplierPerLevel"`
// CompactionTotalSize limits total size of 'sorted table' for each level.
// The limits for each level will be calculated as:
// CompactionTotalSize * (CompactionTotalSizeMultiplier ^ Level)
// The multiplier for each level can also fine-tuned using
// CompactionTotalSizeMultiplierPerLevel.
//
// The default value is 10MiB.
CompactionTotalSize int `json:"compactionTotalSize"`
// CompactionTotalSizeMultiplier defines multiplier for CompactionTotalSize.
//
// The default value is 10.
CompactionTotalSizeMultiplier float64 `json:"compactionTotalSizeMultiplier"`
// DisableSeeksCompaction allows disabling 'seeks triggered compaction'.
// The purpose of 'seeks triggered compaction' is to optimize database so
// that 'level seeks' can be minimized, however this might generate many
// small compaction which may not preferable.
//
// The default is true.
DisableSeeksCompaction bool `json:"disableSeeksCompaction"`
// OpenFilesCacheCapacity defines the capacity of the open files caching.
// Use -1 for zero, this has same effect as specifying NoCacher to OpenFilesCacher.
//
// The default value is 1024.
OpenFilesCacheCapacity int `json:"openFilesCacheCapacity"`
// WriteBuffer defines maximum size of a 'memdb' before flushed to
// 'sorted table'. 'memdb' is an in-memory DB backed by an on-disk
// unsorted journal.
//
// LevelDB may held up to two 'memdb' at the same time.
//
// The default value is 6MiB.
WriteBuffer int `json:"writeBuffer"`
FilterBitsPerKey int `json:"filterBitsPerKey"`
}
// New returns a wrapped LevelDB object.
func New(file string, configBytes []byte, log logging.Logger) (database.Database, error) {
parsedConfig := config{
BlockCacheCapacity: BlockCacheSize,
DisableSeeksCompaction: true,
OpenFilesCacheCapacity: HandleCap,
WriteBuffer: WriteBufferSize / 2,
FilterBitsPerKey: BitsPerKey,
}
if len(configBytes) > 0 {
if err := json.Unmarshal(configBytes, &parsedConfig); err != nil {
return nil, fmt.Errorf("failed to parse db config: %w", err)
}
}
configJSON, err := json.Marshal(&parsedConfig)
if err != nil {
return nil, err
}
log.Info("leveldb config: %s", string(configJSON))
// Open the db and recover any potential corruptions
db, err := leveldb.OpenFile(file, &opt.Options{
BlockCacheCapacity: parsedConfig.BlockCacheCapacity,
BlockSize: parsedConfig.BlockSize,
CompactionExpandLimitFactor: parsedConfig.CompactionExpandLimitFactor,
CompactionGPOverlapsFactor: parsedConfig.CompactionGPOverlapsFactor,
CompactionL0Trigger: parsedConfig.CompactionL0Trigger,
CompactionSourceLimitFactor: parsedConfig.CompactionSourceLimitFactor,
CompactionTableSize: parsedConfig.CompactionTableSize,
CompactionTableSizeMultiplier: parsedConfig.CompactionTableSizeMultiplier,
CompactionTotalSize: parsedConfig.CompactionTotalSize,
CompactionTotalSizeMultiplier: parsedConfig.CompactionTotalSizeMultiplier,
DisableSeeksCompaction: parsedConfig.DisableSeeksCompaction,
OpenFilesCacheCapacity: parsedConfig.OpenFilesCacheCapacity,
WriteBuffer: parsedConfig.WriteBuffer,
Filter: filter.NewBloomFilter(parsedConfig.FilterBitsPerKey),
})
if _, corrupted := err.(*errors.ErrCorrupted); corrupted {
db, err = leveldb.RecoverFile(file, nil)
}
return &Database{
DB: db,
}, err
}
// Has returns if the key is set in the database
func (db *Database) Has(key []byte) (bool, error) {
has, err := db.DB.Has(key, nil)
return has, updateError(err)
}
// Get returns the value the key maps to in the database
func (db *Database) Get(key []byte) ([]byte, error) {
value, err := db.DB.Get(key, nil)
return value, updateError(err)
}
// Put sets the value of the provided key to the provided value
func (db *Database) Put(key []byte, value []byte) error {
return updateError(db.DB.Put(key, value, nil))
}
// Delete removes the key from the database
func (db *Database) Delete(key []byte) error {
return updateError(db.DB.Delete(key, nil))
}
// NewBatch creates a write/delete-only buffer that is atomically committed to
// the database when write is called
func (db *Database) NewBatch() database.Batch { return &batch{db: db} }
// NewIterator creates a lexicographically ordered iterator over the database
func (db *Database) NewIterator() database.Iterator {
return &iter{
db: db,
Iterator: db.DB.NewIterator(new(util.Range), nil),
}
}
// NewIteratorWithStart creates a lexicographically ordered iterator over the
// database starting at the provided key
func (db *Database) NewIteratorWithStart(start []byte) database.Iterator {
return &iter{
db: db,
Iterator: db.DB.NewIterator(&util.Range{Start: start}, nil),
}
}
// NewIteratorWithPrefix creates a lexicographically ordered iterator over the
// database ignoring keys that do not start with the provided prefix
func (db *Database) NewIteratorWithPrefix(prefix []byte) database.Iterator {
return &iter{
db: db,
Iterator: db.DB.NewIterator(util.BytesPrefix(prefix), nil),
}
}
// NewIteratorWithStartAndPrefix creates a lexicographically ordered iterator
// over the database starting at start and ignoring keys that do not start with
// the provided prefix
func (db *Database) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {
iterRange := util.BytesPrefix(prefix)
if bytes.Compare(start, prefix) == 1 {
iterRange.Start = start
}
return &iter{
db: db,
Iterator: db.DB.NewIterator(iterRange, nil),
}
}
// Stat returns a particular internal stat of the database.
func (db *Database) Stat(property string) (string, error) {
stat, err := db.DB.GetProperty(property)
return stat, updateError(err)
}
// This comment is basically copy pasted from the underlying levelDB library:
// Compact the underlying DB for the given key range.
// Specifically, deleted and overwritten versions are discarded,
// and the data is rearranged to reduce the cost of operations
// needed to access the data. This operation should typically only
// be invoked by users who understand the underlying implementation.
//
// A nil start is treated as a key before all keys in the DB.
// And a nil limit is treated as a key after all keys in the DB.
// Therefore if both are nil then it will compact entire DB.
func (db *Database) Compact(start []byte, limit []byte) error {
return updateError(db.DB.CompactRange(util.Range{Start: start, Limit: limit}))
}
func (db *Database) Close() error {
db.closed.SetValue(true)
return updateError(db.DB.Close())
}
// batch is a wrapper around a levelDB batch to contain sizes.
type batch struct {
leveldb.Batch
db *Database
size int
}
// Put the value into the batch for later writing
func (b *batch) Put(key, value []byte) error {
b.Batch.Put(key, value)
b.size += len(key) + len(value) + levelDBByteOverhead
return nil
}
// Delete the key during writing
func (b *batch) Delete(key []byte) error {
b.Batch.Delete(key)
b.size += len(key) + levelDBByteOverhead
return nil
}
// Size retrieves the amount of data queued up for writing.
func (b *batch) Size() int { return b.size }
// Write flushes any accumulated data to disk.
func (b *batch) Write() error {
return updateError(b.db.DB.Write(&b.Batch, nil))
}
// Reset resets the batch for reuse.
func (b *batch) Reset() {
b.Batch.Reset()
b.size = 0
}
// Replay the batch contents.
func (b *batch) Replay(w database.KeyValueWriterDeleter) error {
replay := &replayer{writerDeleter: w}
if err := b.Batch.Replay(replay); err != nil {
// Never actually returns an error, because Replay just returns nil
return err
}
return replay.err
}
// Inner returns itself
func (b *batch) Inner() database.Batch { return b }
type replayer struct {
writerDeleter database.KeyValueWriterDeleter
err error
}
func (r *replayer) Put(key, value []byte) {
if r.err != nil {
return
}
r.err = r.writerDeleter.Put(key, value)
}
func (r *replayer) Delete(key []byte) {
if r.err != nil {
return
}
r.err = r.writerDeleter.Delete(key)
}
type iter struct {
db *Database
iterator.Iterator
key, val []byte
err error
}
func (it *iter) Next() bool {
// Short-circuit and set an error if the underlying database has been closed.
if it.db.closed.GetValue() {
it.key = nil
it.val = nil
it.err = database.ErrClosed
return false
}
hasNext := it.Iterator.Next()
if hasNext {
it.key = utils.CopyBytes(it.Iterator.Key())
it.val = utils.CopyBytes(it.Iterator.Value())
} else {
it.key = nil
it.val = nil
}
return hasNext
}
func (it *iter) Error() error {
if it.err != nil {
return it.err
}
return updateError(it.Iterator.Error())
}
func (it *iter) Key() []byte { return it.key }
func (it *iter) Value() []byte { return it.val }
func updateError(err error) error {
switch err {
case leveldb.ErrClosed:
return database.ErrClosed
case leveldb.ErrNotFound:
return database.ErrNotFound
default:
return err
}
}