-
Notifications
You must be signed in to change notification settings - Fork 342
/
Copy pathlocalstore.go
817 lines (727 loc) · 23.2 KB
/
localstore.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// Copyright 2018 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package localstore
import (
"context"
"encoding/binary"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime/pprof"
"sync"
"time"
"github.com/ethersphere/bee/pkg/logging"
"github.com/ethersphere/bee/pkg/pinning"
"github.com/ethersphere/bee/pkg/postage"
"github.com/ethersphere/bee/pkg/postage/batchstore"
"github.com/ethersphere/bee/pkg/sharky"
"github.com/ethersphere/bee/pkg/shed"
"github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/tags"
"github.com/hashicorp/go-multierror"
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/afero"
"github.com/syndtr/goleveldb/leveldb"
)
var _ storage.Storer = &DB{}
var (
// ErrInvalidMode is retuned when an unknown Mode
// is provided to the function.
ErrInvalidMode = errors.New("invalid mode")
)
var (
// Default value for Capacity DB option.
defaultCacheCapacity uint64 = 1000000
// Limit the number of goroutines created by Getters
// that call updateGC function. Value 0 sets no limit.
maxParallelUpdateGC = 1000
// values needed to adjust subscription trigger
// buffer time.
flipFlopBufferDuration = 150 * time.Millisecond
flipFlopWorstCaseDuration = 10 * time.Second
)
const (
sharkyNoOfShards = 32
sharkyDirtyFileName = ".DIRTY"
)
// DB is the local store implementation and holds
// database related objects.
type DB struct {
shed *shed.DB
// sharky instance
sharky *sharky.Store
fdirtyCloser func() error
tags *tags.Tags
// stateStore is needed to access the pinning Service.Pins() method.
stateStore storage.StateStorer
// schema name of loaded data
schemaName shed.StringField
// retrieval indexes
retrievalDataIndex shed.Index
retrievalAccessIndex shed.Index
// push syncing index
pushIndex shed.Index
// push syncing subscriptions triggers
pushTriggers []chan<- struct{}
pushTriggersMu sync.RWMutex
// pull syncing index
pullIndex shed.Index
// pull syncing subscriptions triggers per bin
pullTriggers map[uint8][]chan<- struct{}
pullTriggersMu sync.RWMutex
// binIDs stores the latest chunk serial ID for every
// proximity order bin
binIDs shed.Uint64Vector
// garbage collection index
gcIndex shed.Index
// pin files Index
pinIndex shed.Index
// postage chunks index
postageChunksIndex shed.Index
// postage radius index
postageRadiusIndex shed.Index
// postage index index
postageIndexIndex shed.Index
// field that stores number of items in gc index
gcSize shed.Uint64Field
// field that stores the size of the reserve
reserveSize shed.Uint64Field
// garbage collection is triggered when gcSize exceeds
// the cacheCapacity value
cacheCapacity uint64
// the size of the reserve in chunks
reserveCapacity uint64
unreserveFunc func(postage.UnreserveIteratorFn) error
// triggers garbage collection event loop
collectGarbageTrigger chan struct{}
// triggers reserve eviction event loop
reserveEvictionTrigger chan struct{}
// a buffered channel acting as a semaphore
// to limit the maximal number of goroutines
// created by Getters to call updateGC function
updateGCSem chan struct{}
// a wait group to ensure all updateGC goroutines
// are done before closing the database
updateGCWG sync.WaitGroup
// baseKey is the overlay address
baseKey []byte
batchMu sync.Mutex
// gcRunning is true while GC is running. it is
// used to avoid touching dirty gc index entries
// while garbage collecting.
gcRunning bool
// dirtyAddresses are marked while gc is running
// in order to avoid the removal of dirty entries.
dirtyAddresses []swarm.Address
// this channel is closed when close function is called
// to terminate other goroutines
close chan struct{}
// context
ctx context.Context
// the cancelation function from the context
cancel context.CancelFunc
// protect Close method from exiting before
// garbage collection and gc size write workers
// are done
collectGarbageWorkerDone chan struct{}
reserveEvictionWorkerDone chan struct{}
// wait for all subscriptions to finish before closing
// underlaying leveldb to prevent possible panics from
// iterators
subscriptionsWG sync.WaitGroup
metrics metrics
logger logging.Logger
}
// Options struct holds optional parameters for configuring DB.
type Options struct {
// Capacity is a limit that triggers garbage collection when
// number of items in gcIndex equals or exceeds it.
Capacity uint64
// ReserveCapacity is the capacity of the reserve.
ReserveCapacity uint64
// UnreserveFunc is an iterator needed to facilitate reserve
// eviction once ReserveCapacity is reached.
UnreserveFunc func(postage.UnreserveIteratorFn) error
// OpenFilesLimit defines the upper bound of open files that the
// the localstore should maintain at any point of time. It is
// passed on to the shed constructor.
OpenFilesLimit uint64
// BlockCacheCapacity defines the block cache capacity and is passed
// on to shed.
BlockCacheCapacity uint64
// WriteBuffer defines the size of writer buffer and is passed on to shed.
WriteBufferSize uint64
// DisableSeeksCompaction toggles the seek driven compactions feature on leveldb
// and is passed on to shed.
DisableSeeksCompaction bool
// MetricsPrefix defines a prefix for metrics names.
MetricsPrefix string
Tags *tags.Tags
}
type memFS struct {
afero.Fs
}
func (m *memFS) Open(path string) (fs.File, error) {
return m.Fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
}
type dirFS struct {
basedir string
}
func (d *dirFS) Open(path string) (fs.File, error) {
return os.OpenFile(filepath.Join(d.basedir, path), os.O_RDWR|os.O_CREATE, 0644)
}
func safeInit(rootPath, sharkyBasePath string, db *DB) error {
// create if needed
path := filepath.Join(rootPath, sharkyDirtyFileName)
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
// missing lock file implies a clean exit then create the file and return
return os.WriteFile(path, []byte{}, 0644)
}
locOrErr, err := recovery(db)
if err != nil {
return err
}
recoverySharky, err := sharky.NewRecovery(sharkyBasePath, sharkyNoOfShards, swarm.SocMaxChunkSize)
if err != nil {
return err
}
for l := range locOrErr {
if l.err != nil {
return l.err
}
err = recoverySharky.Add(l.loc)
if err != nil {
return err
}
}
err = recoverySharky.Save()
if err != nil {
return err
}
err = recoverySharky.Close()
if err != nil {
return err
}
return nil
}
// New returns a new DB. All fields and indexes are initialized
// and possible conflicts with schema from existing database is checked.
// One goroutine for writing batches is created.
func New(path string, baseKey []byte, ss storage.StateStorer, o *Options, logger logging.Logger) (db *DB, err error) {
if o == nil {
// default options
o = &Options{
Capacity: defaultCacheCapacity,
ReserveCapacity: uint64(batchstore.Capacity),
}
}
ctx, cancel := context.WithCancel(context.Background())
db = &DB{
stateStore: ss,
cacheCapacity: o.Capacity,
reserveCapacity: o.ReserveCapacity,
unreserveFunc: o.UnreserveFunc,
baseKey: baseKey,
tags: o.Tags,
ctx: ctx,
cancel: cancel,
// channel collectGarbageTrigger
// needs to be buffered with the size of 1
// to signal another event if it
// is triggered during already running function
collectGarbageTrigger: make(chan struct{}, 1),
reserveEvictionTrigger: make(chan struct{}, 1),
close: make(chan struct{}),
collectGarbageWorkerDone: make(chan struct{}),
reserveEvictionWorkerDone: make(chan struct{}),
metrics: newMetrics(),
logger: logger,
}
if db.cacheCapacity == 0 {
db.cacheCapacity = defaultCacheCapacity
}
capacityMB := float64((db.cacheCapacity+uint64(batchstore.Capacity))*swarm.ChunkSize) * 9.5367431640625e-7
if capacityMB <= 1000 {
db.logger.Infof("database capacity: %d chunks (approximately %fMB)", db.cacheCapacity, capacityMB)
} else {
db.logger.Infof("database capacity: %d chunks (approximately %0.1fGB)", db.cacheCapacity, capacityMB/1000)
}
if maxParallelUpdateGC > 0 {
db.updateGCSem = make(chan struct{}, maxParallelUpdateGC)
}
shedOpts := &shed.Options{
OpenFilesLimit: o.OpenFilesLimit,
BlockCacheCapacity: o.BlockCacheCapacity,
WriteBufferSize: o.WriteBufferSize,
DisableSeeksCompaction: o.DisableSeeksCompaction,
}
if withinRadiusFn == nil {
withinRadiusFn = withinRadius
}
db.shed, err = shed.NewDB(path, shedOpts)
if err != nil {
return nil, err
}
// instantiate sharky instance
var sharkyBase fs.FS
if path == "" {
// No need for recovery for in-mem sharky
sharkyBase = &memFS{Fs: afero.NewMemMapFs()}
} else {
sharkyBasePath := filepath.Join(path, "sharky")
if _, err := os.Stat(sharkyBasePath); os.IsNotExist(err) {
err := os.Mkdir(sharkyBasePath, 0775)
if err != nil {
return nil, err
}
}
sharkyBase = &dirFS{basedir: sharkyBasePath}
err = safeInit(path, sharkyBasePath, db)
if err != nil {
return nil, fmt.Errorf("safe sharky initialization failed: %w", err)
}
db.fdirtyCloser = func() error { return os.Remove(filepath.Join(path, sharkyDirtyFileName)) }
}
db.sharky, err = sharky.New(sharkyBase, sharkyNoOfShards, swarm.SocMaxChunkSize)
if err != nil {
return nil, err
}
// Identify current storage schema by arbitrary name.
db.schemaName, err = db.shed.NewStringField("schema-name")
if err != nil {
return nil, err
}
schemaName, err := db.schemaName.Get()
if err != nil && !errors.Is(err, leveldb.ErrNotFound) {
return nil, err
}
if schemaName == "" {
// initial new localstore run
err := db.schemaName.Put(DBSchemaCurrent)
if err != nil {
return nil, err
}
} else {
// Execute possible migrations.
if err := db.migrate(schemaName); err != nil {
return nil, multierror.Append(err, db.sharky.Close(), db.shed.Close(), db.fdirtyCloser())
}
}
// Persist gc size.
db.gcSize, err = db.shed.NewUint64Field("gc-size")
if err != nil {
return nil, err
}
// reserve size
db.reserveSize, err = db.shed.NewUint64Field("reserve-size")
if err != nil {
return nil, err
}
// Index storing actual chunk address, data and bin id.
headerSize := 16 + postage.StampSize
db.retrievalDataIndex, err = db.shed.NewIndex("Address->StoreTimestamp|BinID|BatchID|BatchIndex|Sig|Location", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
return fields.Address, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.Address = key
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
b := make([]byte, headerSize)
binary.BigEndian.PutUint64(b[:8], fields.BinID)
binary.BigEndian.PutUint64(b[8:16], uint64(fields.StoreTimestamp))
stamp, err := postage.NewStamp(fields.BatchID, fields.Index, fields.Timestamp, fields.Sig).MarshalBinary()
if err != nil {
return nil, err
}
copy(b[16:], stamp)
value = append(b, fields.Location...)
return value, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.StoreTimestamp = int64(binary.BigEndian.Uint64(value[8:16]))
e.BinID = binary.BigEndian.Uint64(value[:8])
stamp := new(postage.Stamp)
if err = stamp.UnmarshalBinary(value[16:headerSize]); err != nil {
return e, err
}
e.BatchID = stamp.BatchID()
e.Index = stamp.Index()
e.Timestamp = stamp.Timestamp()
e.Sig = stamp.Sig()
e.Location = value[headerSize:]
return e, nil
},
})
if err != nil {
return nil, err
}
// Index storing access timestamp for a particular address.
// It is needed in order to update gc index keys for iteration order.
db.retrievalAccessIndex, err = db.shed.NewIndex("Address->AccessTimestamp", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
return fields.Address, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.Address = key
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(fields.AccessTimestamp))
return b, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.AccessTimestamp = int64(binary.BigEndian.Uint64(value))
return e, nil
},
})
if err != nil {
return nil, err
}
// pull index allows history and live syncing per po bin
db.pullIndex, err = db.shed.NewIndex("PO|BinID->Hash", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
key = make([]byte, 9)
key[0] = db.po(swarm.NewAddress(fields.Address))
binary.BigEndian.PutUint64(key[1:9], fields.BinID)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.BinID = binary.BigEndian.Uint64(key[1:9])
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
value = make([]byte, 64) // 32 bytes address, 32 bytes batch id
copy(value, fields.Address)
copy(value[32:], fields.BatchID)
return value, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.Address = value[:32]
e.BatchID = value[32:64]
return e, nil
},
})
if err != nil {
return nil, err
}
// create a vector for bin IDs
db.binIDs, err = db.shed.NewUint64Vector("bin-ids")
if err != nil {
return nil, err
}
// create a pull syncing triggers used by SubscribePull function
db.pullTriggers = make(map[uint8][]chan<- struct{})
// push index contains as yet unsynced chunks
db.pushIndex, err = db.shed.NewIndex("StoreTimestamp|Hash->Tags", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
key = make([]byte, 40)
binary.BigEndian.PutUint64(key[:8], uint64(fields.StoreTimestamp))
copy(key[8:], fields.Address)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.Address = key[8:]
e.StoreTimestamp = int64(binary.BigEndian.Uint64(key[:8]))
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
tag := make([]byte, 4)
binary.BigEndian.PutUint32(tag, fields.Tag)
return tag, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
if len(value) == 4 { // only values with tag should be decoded
e.Tag = binary.BigEndian.Uint32(value)
}
return e, nil
},
})
if err != nil {
return nil, err
}
// create a push syncing triggers used by SubscribePush function
db.pushTriggers = make([]chan<- struct{}, 0)
// gc index for removable chunk ordered by ascending last access time
db.gcIndex, err = db.shed.NewIndex("AccessTimestamp|BinID|Hash->BatchID|BatchIndex", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
b := make([]byte, 16, 16+len(fields.Address))
binary.BigEndian.PutUint64(b[:8], uint64(fields.AccessTimestamp))
binary.BigEndian.PutUint64(b[8:16], fields.BinID)
key = append(b, fields.Address...)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.AccessTimestamp = int64(binary.BigEndian.Uint64(key[:8]))
e.BinID = binary.BigEndian.Uint64(key[8:16])
e.Address = key[16:]
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
value = make([]byte, 40)
copy(value, fields.BatchID)
copy(value[32:], fields.Index)
return value, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.BatchID = make([]byte, 32)
copy(e.BatchID, value[:32])
e.Index = make([]byte, postage.IndexSize)
copy(e.Index, value[32:])
return e, nil
},
})
if err != nil {
return nil, err
}
// Create a index structure for storing pinned chunks and their pin counts
db.pinIndex, err = db.shed.NewIndex("Hash->PinCounter", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
return fields.Address, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.Address = key
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b[:8], fields.PinCounter)
return b, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.PinCounter = binary.BigEndian.Uint64(value[:8])
return e, nil
},
})
if err != nil {
return nil, err
}
db.postageChunksIndex, err = db.shed.NewIndex("BatchID|PO|Hash->nil", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
key = make([]byte, 65)
copy(key[:32], fields.BatchID)
key[32] = db.po(swarm.NewAddress(fields.Address))
copy(key[33:], fields.Address)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.BatchID = key[:32]
e.Address = key[33:65]
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
return nil, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
return e, nil
},
})
if err != nil {
return nil, err
}
db.postageRadiusIndex, err = db.shed.NewIndex("BatchID->Radius", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
key = make([]byte, 32)
copy(key[:32], fields.BatchID)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.BatchID = key[:32]
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
return []byte{fields.Radius}, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.Radius = value[0]
return e, nil
},
})
if err != nil {
return nil, err
}
db.postageIndexIndex, err = db.shed.NewIndex("BatchID|BatchIndex->Hash|Timestamp", shed.IndexFuncs{
EncodeKey: func(fields shed.Item) (key []byte, err error) {
key = make([]byte, 40)
copy(key[:32], fields.BatchID)
copy(key[32:40], fields.Index)
return key, nil
},
DecodeKey: func(key []byte) (e shed.Item, err error) {
e.BatchID = key[:32]
e.Index = key[32:40]
return e, nil
},
EncodeValue: func(fields shed.Item) (value []byte, err error) {
value = make([]byte, 40)
copy(value, fields.Address)
copy(value[32:], fields.Timestamp)
return value, nil
},
DecodeValue: func(keyItem shed.Item, value []byte) (e shed.Item, err error) {
e.Address = value[:32]
e.Timestamp = value[32:]
return e, nil
},
})
if err != nil {
return nil, err
}
// start garbage collection worker
go db.collectGarbageWorker()
go db.reserveEvictionWorker()
return db, nil
}
func (db *DB) Size() (uint64, error) {
return db.reserveSize.Get()
}
func (db *DB) Capacity() uint64 {
return db.reserveCapacity
}
// Close closes the underlying database.
func (db *DB) Close() error {
close(db.close)
db.cancel()
// wait for all handlers to finish
done := make(chan struct{})
go func() {
db.updateGCWG.Wait()
// wait for gc worker to
// return before closing the shed
<-db.collectGarbageWorkerDone
<-db.reserveEvictionWorkerDone
close(done)
}()
err := new(multierror.Error)
select {
case <-done:
case <-time.After(5 * time.Second):
db.logger.Error("localstore closed with still active goroutines")
// Print a full goroutine dump to debug blocking.
// TODO: use a logger to write a goroutine profile
prof := pprof.Lookup("goroutine")
err = multierror.Append(err, prof.WriteTo(os.Stdout, 2))
}
err = multierror.Append(err, db.sharky.Close())
err = multierror.Append(err, db.shed.Close())
if db.fdirtyCloser != nil {
err = multierror.Append(err, db.fdirtyCloser())
}
return err.ErrorOrNil()
}
// po computes the proximity order between the address
// and database base key.
func (db *DB) po(addr swarm.Address) (bin uint8) {
return swarm.Proximity(db.baseKey, addr.Bytes())
}
// DebugIndices returns the index sizes for all indexes in localstore
// the returned map keys are the index name, values are the number of elements in the index
func (db *DB) DebugIndices() (indexInfo map[string]int, err error) {
indexInfo = make(map[string]int)
for k, v := range map[string]shed.Index{
"retrievalDataIndex": db.retrievalDataIndex,
"retrievalAccessIndex": db.retrievalAccessIndex,
"pushIndex": db.pushIndex,
"pullIndex": db.pullIndex,
"gcIndex": db.gcIndex,
"pinIndex": db.pinIndex,
"postageChunksIndex": db.postageChunksIndex,
"postageRadiusIndex": db.postageRadiusIndex,
"postageIndexIndex": db.postageIndexIndex,
} {
indexSize, err := v.Count()
if err != nil {
return indexInfo, err
}
indexInfo[k] = indexSize
}
val, err := db.gcSize.Get()
if err != nil {
return indexInfo, err
}
indexInfo["gcSize"] = int(val)
val, err = db.reserveSize.Get()
if err != nil {
return indexInfo, err
}
indexInfo["reserveSize"] = int(val)
return indexInfo, err
}
// stateStoreHasPins returns true if the state-store
// contains any pins, otherwise false is returned.
func (db *DB) stateStoreHasPins() (bool, error) {
pins, err := pinning.NewService(nil, db.stateStore, nil).Pins()
if err != nil {
return false, err
}
return len(pins) > 0, nil
}
// chunkToItem creates new Item with data provided by the Chunk.
func chunkToItem(ch swarm.Chunk) shed.Item {
return shed.Item{
Address: ch.Address().Bytes(),
Data: ch.Data(),
Tag: ch.TagID(),
BatchID: ch.Stamp().BatchID(),
Index: ch.Stamp().Index(),
Timestamp: ch.Stamp().Timestamp(),
Sig: ch.Stamp().Sig(),
Depth: ch.Depth(),
Radius: ch.Radius(),
BucketDepth: ch.BucketDepth(),
Immutable: ch.Immutable(),
}
}
// addressToItem creates new Item with a provided address.
func addressToItem(addr swarm.Address) shed.Item {
return shed.Item{
Address: addr.Bytes(),
}
}
// addressesToItems constructs a slice of Items with only
// addresses set on them.
func addressesToItems(addrs ...swarm.Address) []shed.Item {
items := make([]shed.Item, len(addrs))
for i, addr := range addrs {
items[i] = shed.Item{
Address: addr.Bytes(),
}
}
return items
}
// now is a helper function that returns a current unix timestamp
// in UTC timezone.
// It is set in the init function for usage in production, and
// optionally overridden in tests for data validation.
var now func() int64
func init() {
// set the now function
now = func() (t int64) {
return time.Now().UTC().UnixNano()
}
}
// totalTimeMetric logs a message about time between provided start time
// and the time when the function is called and sends a resetting timer metric
// with provided name appended with ".total-time".
func totalTimeMetric(metric prometheus.Counter, start time.Time) {
totalTime := time.Since(start)
metric.Add(float64(totalTime))
}