-
Notifications
You must be signed in to change notification settings - Fork 462
/
badger.go
484 lines (414 loc) · 12.3 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
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
package blockstore
import (
"context"
"fmt"
"io"
"sync/atomic"
"github.com/dgraph-io/badger/v2"
"github.com/dgraph-io/badger/v2/options"
blockstore "github.com/ipfs/boxo/blockstore"
dshelp "github.com/ipfs/boxo/datastore/dshelp"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/keytransform"
ipld "github.com/ipfs/go-ipld-format"
"go.uber.org/zap"
)
// ErrBlockstoreClosed is returned from blockstore operations after
// the blockstore has been closed.
var ErrBlockstoreClosed = fmt.Errorf("badger blockstore closed")
// aliases to mask badger dependencies.
const (
// FileIO is equivalent to badger/options.FileIO.
FileIO = options.FileIO
// MemoryMap is equivalent to badger/options.MemoryMap.
MemoryMap = options.MemoryMap
// LoadToRAM is equivalent to badger/options.LoadToRAM.
LoadToRAM = options.LoadToRAM
)
// Options embeds the badger options themselves, and augments them with
// blockstore-specific options.
type Options struct {
badger.Options
// Prefix is an optional prefix to prepend to keys. Default: "".
Prefix string
}
func DefaultOptions(path string) Options {
return Options{
Options: badger.DefaultOptions(path),
Prefix: "",
}
}
// BadgerBlockstoreOptions returns the badger options to apply for the provided
// domain.
func BadgerBlockstoreOptions(path string, readonly bool) (Options, error) {
opts := DefaultOptions(path)
// Due to legacy usage of blockstore.blockstore, over a datastore, all
// blocks are prefixed with this namespace. In the future, this can go away,
// in order to shorten keys, but it'll require a migration.
opts.Prefix = ""
// blockstore values are immutable; therefore we do not expect any
// conflicts to emerge.
opts.DetectConflicts = false
// This is to optimize the database on close so it can be opened
// read-only and efficiently queried. We don't do that and hanging on
// stop isn't nice.
opts.CompactL0OnClose = false
// The alternative is "crash on start and tell the user to fix it". This
// will truncate corrupt and unsynced data, which we don't guarantee to
// persist anyways.
opts.Truncate = true
// We mmap the index and the value logs; this is important to enable
// zero-copy value access.
opts.ValueLogLoadingMode = FileIO
opts.TableLoadingMode = FileIO
// Embed only values < 128 bytes in the LSM tree; larger values are stored
// in value logs.
opts.ValueThreshold = 128
// Default table size is already 64MiB. This is here to make it explicit.
opts.MaxTableSize = 64 << 20
// NOTE: The chain blockstore doesn't require any GC (blocks are never
// deleted). This will change if we move to a tiered blockstore.
opts.ReadOnly = readonly
return opts, nil
}
// badgerLogger is a local wrapper for go-log to make the interface
// compatible with badger.Logger (namely, aliasing Warnf to Warningf)
type badgerLogger struct {
*zap.SugaredLogger // skips 1 caller to get useful line info, skipping over badger.Options.
skip2 *zap.SugaredLogger // skips 2 callers, just like above + this logger.
}
// Warningf is required by the badger logger APIs.
func (b *badgerLogger) Warningf(format string, args ...interface{}) {
b.skip2.Warnf(format, args...)
}
const (
stateOpen int64 = iota
stateClosing
stateClosed
)
// blockstore is a badger-backed IPLD blockstore.
//
// NOTE: once Close() is called, methods will try their best to return
// ErrBlockstoreClosed. This will guaranteed to happen for all subsequent
// operation calls after Close() has returned, but it may not happen for
// operations in progress. Those are likely to fail with a different error.
type BadgerBlockstore struct {
DB *badger.DB
// state is guarded by atomic.
state int64
keyTransform *keytransform.PrefixTransform
cache IBlockCache
}
var (
_ blockstore.Blockstore = (*BadgerBlockstore)(nil)
_ blockstore.Viewer = (*BadgerBlockstore)(nil)
_ io.Closer = (*BadgerBlockstore)(nil)
)
// Open creates a new badger-backed blockstore, with the supplied options.
func Open(opts Options) (*BadgerBlockstore, error) {
opts.Logger = &badgerLogger{
SugaredLogger: log.Desugar().WithOptions(zap.AddCallerSkip(1)).Sugar(),
skip2: log.Desugar().WithOptions(zap.AddCallerSkip(2)).Sugar(),
}
keyTransform := &keytransform.PrefixTransform{
Prefix: datastore.NewKey(opts.Prefix),
}
db, err := badger.Open(opts.Options)
if err != nil {
return nil, fmt.Errorf("failed to open badger blockstore: %w", err)
}
cache := NewLruCache(10 * 10000)
bs := &BadgerBlockstore{
DB: db,
keyTransform: keyTransform,
cache: cache,
}
return bs, nil
}
// Close closes the store. If the store has already been closed, this noops and
// returns an error, even if the first closure resulted in error.
func (b *BadgerBlockstore) Close() error {
if !atomic.CompareAndSwapInt64(&b.state, stateOpen, stateClosing) {
return nil
}
defer atomic.StoreInt64(&b.state, stateClosed)
return b.DB.Close()
}
func (b *BadgerBlockstore) ReadonlyDatastore() *TxBlockstore {
return &TxBlockstore{
cache: b.cache,
tx: b.DB.NewTransaction(false),
keyTransform: b.keyTransform,
}
}
// View implements blockstore.Viewer, which leverages zero-copy read-only
// access to values.
func (b *BadgerBlockstore) View(ctx context.Context, cid cid.Cid, fn func([]byte) error) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
key := b.ConvertKey(cid)
return b.DB.View(func(txn *badger.Txn) error {
switch item, err := txn.Get(key.Bytes()); err {
case nil:
return item.Value(fn)
case badger.ErrKeyNotFound:
return ipld.ErrNotFound{Cid: cid}
default:
return fmt.Errorf("failed to view block from badger blockstore: %w", err)
}
})
}
func (b *BadgerBlockstore) Flush(context.Context) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
return b.DB.Sync()
}
// Has implements blockstore.Has.
func (b *BadgerBlockstore) Has(ctx context.Context, cid cid.Cid) (bool, error) {
if atomic.LoadInt64(&b.state) != stateOpen {
return false, ErrBlockstoreClosed
}
key := b.ConvertKey(cid)
if b.cache != nil {
if _, has := b.cache.Get(key.String()); has {
return true, nil
}
}
err := b.DB.View(func(txn *badger.Txn) error {
_, err := txn.Get(key.Bytes())
return err
})
switch err {
case badger.ErrKeyNotFound:
return false, nil
case nil:
return true, nil
default:
return false, fmt.Errorf("failed to check if block exists in badger blockstore: %w", err)
}
}
// Get implements blockstore.Get.
func (b *BadgerBlockstore) Get(ctx context.Context, cid cid.Cid) (blocks.Block, error) {
if !cid.Defined() {
return nil, ipld.ErrNotFound{Cid: cid}
}
if atomic.LoadInt64(&b.state) != stateOpen {
return nil, ErrBlockstoreClosed
}
key := b.ConvertKey(cid)
if b.cache != nil {
if val, has := b.cache.Get(key.String()); has {
return val.(blocks.Block), nil
}
}
// migrate
// todo just for test
var val []byte
err := b.DB.View(func(txn *badger.Txn) error {
switch item, err := txn.Get(key.Bytes()); err {
case nil:
val, err = item.ValueCopy(nil)
return err
case badger.ErrKeyNotFound:
return ipld.ErrNotFound{Cid: cid}
default:
return fmt.Errorf("failed to get block from badger blockstore: %w", err)
}
})
if err != nil {
return nil, err
}
blk, err := blocks.NewBlockWithCid(val, cid)
if err != nil {
return nil, err
}
b.cache.Add(key.String(), blk)
return blk, nil
}
// GetSize implements blockstore.GetSize.
func (b *BadgerBlockstore) GetSize(ctx context.Context, cid cid.Cid) (int, error) {
if atomic.LoadInt64(&b.state) != stateOpen {
return -1, ErrBlockstoreClosed
}
key := b.ConvertKey(cid)
if b.cache != nil {
if val, has := b.cache.Get(key.String()); has {
return len(val.(blocks.Block).RawData()), nil
}
}
var size int
err := b.DB.View(func(txn *badger.Txn) error {
switch item, err := txn.Get(key.Bytes()); err {
case nil:
size = int(item.ValueSize())
case badger.ErrKeyNotFound:
return ipld.ErrNotFound{Cid: cid}
default:
return fmt.Errorf("failed to get block size from badger blockstore: %w", err)
}
return nil
})
if err != nil {
size = -1
}
return size, err
}
// Put implements blockstore.Put.
func (b *BadgerBlockstore) Put(ctx context.Context, block blocks.Block) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
key := b.ConvertKey(block.Cid())
if _, ok := b.cache.Get(key.String()); ok {
return nil
}
// Check if we have it before writing it.
switch err := b.DB.View(func(txn *badger.Txn) error {
_, err := txn.Get(key.Bytes())
return err
}); err {
case badger.ErrKeyNotFound:
case nil:
b.cache.Add(key.String(), block)
// Already exists, skip the put.
return nil
default:
return err
}
err := b.DB.Update(func(txn *badger.Txn) error {
err := txn.Set(key.Bytes(), block.RawData())
if err == nil {
b.cache.Add(key.String(), block)
}
return err
})
if err != nil {
err = fmt.Errorf("failed to put block in badger blockstore: %w", err)
}
return err
}
// PutMany implements blockstore.PutMany.
func (b *BadgerBlockstore) PutMany(ctx context.Context, blks []blocks.Block) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
batch := b.DB.NewWriteBatch()
defer batch.Cancel()
flushToCache := map[string]blocks.Block{}
for _, block := range blks {
key := b.ConvertKey(block.Cid())
if _, ok := b.cache.Get(key.String()); ok {
continue
}
// Check if we have it before writing it.
switch err := b.DB.View(func(txn *badger.Txn) error {
_, err := txn.Get(key.Bytes())
return err
}); err {
case badger.ErrKeyNotFound:
case nil:
// skipped because we already have it.
continue
default:
// Something is actually wrong
return err
}
if err := batch.Set(key.Bytes(), block.RawData()); err != nil {
return err
}
flushToCache[key.String()] = block
}
err := batch.Flush()
if err != nil {
err = fmt.Errorf("failed to put blocks in badger blockstore: %w", err)
}
// flush to cache
for k, v := range flushToCache {
b.cache.Add(k, v)
}
return err
}
// DeleteBlock implements blockstore.DeleteBlock.
func (b *BadgerBlockstore) DeleteBlock(ctx context.Context, cid cid.Cid) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
key := b.ConvertKey(cid)
return b.DB.Update(func(txn *badger.Txn) error {
err := txn.Delete(key.Bytes())
if err == nil {
b.cache.Remove(key.String())
}
return err
})
}
func (b *BadgerBlockstore) DeleteMany(ctx context.Context, cids []cid.Cid) error {
if atomic.LoadInt64(&b.state) != stateOpen {
return ErrBlockstoreClosed
}
for _, cid := range cids {
key := b.ConvertKey(cid)
if err := b.DB.Update(func(txn *badger.Txn) error {
err := txn.Delete(key.Bytes())
if err == nil {
b.cache.Remove(key.String())
}
return err
}); err != nil {
return err
}
}
return nil
}
// AllKeysChan implements blockstore.AllKeysChan.
func (b *BadgerBlockstore) AllKeysChan(ctx context.Context) (<-chan cid.Cid, error) {
if atomic.LoadInt64(&b.state) != stateOpen {
return nil, ErrBlockstoreClosed
}
txn := b.DB.NewTransaction(false)
opts := badger.IteratorOptions{PrefetchSize: 100}
iter := txn.NewIterator(opts)
ch := make(chan cid.Cid)
go func() {
defer close(ch)
defer iter.Close()
// NewCidV1 makes a copy of the multihash buffer, so we can reuse it to
// contain allocs.
for iter.Rewind(); iter.Valid(); iter.Next() {
if ctx.Err() != nil {
return // context has fired.
}
if atomic.LoadInt64(&b.state) != stateOpen {
// open iterators will run even after the database is closed...
return // closing, yield.
}
k := iter.Item().Key()
// need to convert to key.Key using key.KeyFromDsKey.
bk, err := dshelp.BinaryFromDsKey(datastore.RawKey(string(k)))
if err != nil {
log.Warnf("error parsing key from binary: %s", err)
continue
}
cidKey := cid.NewCidV1(cid.Raw, bk)
select {
case <-ctx.Done():
return
case ch <- cidKey:
}
}
}()
return ch, nil
}
// HashOnRead implements blockstore.HashOnRead. It is not supported by this
// blockstore.
func (b *BadgerBlockstore) HashOnRead(_ bool) {
log.Warnf("called HashOnRead on badger blockstore; function not supported; ignoring")
}
func (b *BadgerBlockstore) ConvertKey(cid cid.Cid) datastore.Key {
key := dshelp.MultihashToDsKey(cid.Hash())
return b.keyTransform.ConvertKey(key)
}