-
Notifications
You must be signed in to change notification settings - Fork 199
/
pruningStorer.go
914 lines (774 loc) · 23.2 KB
/
pruningStorer.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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
package pruning
import (
"encoding/hex"
"errors"
"fmt"
"math"
"runtime/debug"
"sync"
logger "github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/core"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/data"
"github.com/ElrondNetwork/elrond-go/data/block"
"github.com/ElrondNetwork/elrond-go/epochStart/notifier"
"github.com/ElrondNetwork/elrond-go/storage"
"github.com/ElrondNetwork/elrond-go/storage/storageUnit"
)
var _ storage.Storer = (*PruningStorer)(nil)
var log = logger.GetOrCreate("storage/pruning")
// maxNumEpochsToKeepIfAShardIsStuck represents the maximum number of epochs to be kept active if a shard remains stuck
// and requires data from older epochs
const maxNumEpochsToKeepIfAShardIsStuck = 5
// epochForDefaultEpochPrepareHdr represents the default epoch number for the meta block which is saved on EpochPrepareAction
// it is useful for checking if any metablock of this kind is received
const epochForDefaultEpochPrepareHdr = math.MaxUint32 - 7
// persisterData structure is used so the persister and its path can be kept in the same place
type persisterData struct {
persister storage.Persister
path string
epoch uint32
isClosed bool
mutIsClosed sync.RWMutex
}
func (pd *persisterData) getIsClosed() bool {
pd.mutIsClosed.RLock()
defer pd.mutIsClosed.RUnlock()
return pd.isClosed
}
func (pd *persisterData) setIsClosed(closed bool) {
pd.mutIsClosed.Lock()
pd.isClosed = closed
pd.mutIsClosed.Unlock()
}
// PruningStorer represents a storer which creates a new persister for each epoch and removes older activePersisters
type PruningStorer struct {
lock sync.RWMutex
shardCoordinator storage.ShardCoordinator
activePersisters []*persisterData
persistersMapByEpoch map[uint32]*persisterData
cacher storage.Cacher
bloomFilter storage.BloomFilter
pathManager storage.PathManagerHandler
dbPath string
persisterFactory DbFactoryHandler
mutEpochPrepareHdr sync.RWMutex
epochPrepareHdr *block.MetaBlock
identifier string
numOfEpochsToKeep uint32
numOfActivePersisters uint32
epochForPutOperation uint32
cleanOldEpochsData bool
pruningEnabled bool
}
// NewPruningStorer will return a new instance of PruningStorer without sharded directories' naming scheme
func NewPruningStorer(args *StorerArgs) (*PruningStorer, error) {
return initPruningStorer(args, "")
}
// NewShardedPruningStorer will return a new instance of PruningStorer with sharded directories' naming scheme
func NewShardedPruningStorer(
args *StorerArgs,
shardID uint32,
) (*PruningStorer, error) {
shardIdStr := fmt.Sprintf("%d", shardID)
return initPruningStorer(args, shardIdStr)
}
// initPruningStorer will create a PruningStorer with or without sharded directories' naming scheme
func initPruningStorer(
args *StorerArgs,
shardIDStr string,
) (*PruningStorer, error) {
var cache storage.Cacher
var db storage.Persister
var bf storage.BloomFilter
var err error
defer func() {
if err != nil && db != nil {
_ = db.Destroy()
}
}()
if args.NumOfActivePersisters < 1 {
return nil, storage.ErrInvalidNumberOfPersisters
}
if check.IfNil(args.Notifier) {
return nil, storage.ErrNilEpochStartNotifier
}
if check.IfNil(args.PersisterFactory) {
return nil, storage.ErrNilPersisterFactory
}
if check.IfNil(args.ShardCoordinator) {
return nil, storage.ErrNilShardCoordinator
}
if check.IfNil(args.PathManager) {
return nil, storage.ErrNilPathManager
}
if args.MaxBatchSize > int(args.CacheConf.Capacity) {
return nil, storage.ErrCacheSizeIsLowerThanBatchSize
}
cache, err = storageUnit.NewCache(args.CacheConf)
if err != nil {
return nil, err
}
persisters, persistersMapByEpoch, err := initPersistersInEpoch(args, shardIDStr)
if err != nil {
return nil, err
}
identifier := args.Identifier
if len(shardIDStr) > 0 {
identifier += shardIDStr
}
pdb := &PruningStorer{
pruningEnabled: args.PruningEnabled,
identifier: identifier,
cleanOldEpochsData: args.CleanOldEpochsData,
activePersisters: persisters,
persisterFactory: args.PersisterFactory,
shardCoordinator: args.ShardCoordinator,
persistersMapByEpoch: persistersMapByEpoch,
cacher: cache,
epochPrepareHdr: &block.MetaBlock{Epoch: epochForDefaultEpochPrepareHdr},
bloomFilter: nil,
epochForPutOperation: args.StartingEpoch,
pathManager: args.PathManager,
dbPath: args.DbPath,
numOfEpochsToKeep: args.NumOfEpochsToKeep,
numOfActivePersisters: args.NumOfActivePersisters,
}
if args.BloomFilterConf.Size != 0 { // if size is 0, that means an empty config was used so bloom filter will be nil
bf, err = storageUnit.NewBloomFilter(args.BloomFilterConf)
if err != nil {
return nil, err
}
pdb.bloomFilter = bf
}
pdb.registerHandler(args.Notifier)
return pdb, nil
}
func initPersistersInEpoch(
args *StorerArgs,
shardIDStr string,
) ([]*persisterData, map[uint32]*persisterData, error) {
var persisters []*persisterData
persistersMapByEpoch := make(map[uint32]*persisterData)
if !args.PruningEnabled {
p, err := createPersisterDataForEpoch(args, 0, shardIDStr)
if err != nil {
return nil, nil, err
}
persisters = append(persisters, p)
return persisters, persistersMapByEpoch, nil
}
if args.NumOfEpochsToKeep < args.NumOfActivePersisters {
return nil, nil, fmt.Errorf("invalid epochs configuration")
}
oldestEpochKeep := int64(args.StartingEpoch) - int64(args.NumOfEpochsToKeep) + 1
if oldestEpochKeep < 0 {
oldestEpochKeep = 0
}
oldestEpochActive := int64(args.StartingEpoch) - int64(args.NumOfActivePersisters) + 1
if oldestEpochActive < 0 {
oldestEpochActive = 0
}
for epoch := int64(args.StartingEpoch); epoch >= oldestEpochKeep; epoch-- {
p, err := createPersisterDataForEpoch(args, uint32(epoch), shardIDStr)
if err != nil {
return nil, nil, err
}
persistersMapByEpoch[uint32(epoch)] = p
if epoch < oldestEpochActive {
err = p.persister.Close()
if err != nil {
log.Debug("persister.Close()", "error", err.Error())
}
} else {
persisters = append(persisters, p)
log.Debug("appended a pruning active persister", "epoch", epoch, "identifier", args.Identifier)
}
}
return persisters, persistersMapByEpoch, nil
}
// Put adds data to both cache and persistence medium and updates the bloom filter
func (ps *PruningStorer) Put(key, data []byte) error {
ps.cacher.Put(key, data, len(data))
ps.lock.RLock()
persisterToUse := ps.activePersisters[0]
if ps.pruningEnabled {
persisterInSetEpoch, ok := ps.persistersMapByEpoch[ps.epochForPutOperation]
if ok && !persisterInSetEpoch.getIsClosed() {
persisterToUse = persisterInSetEpoch
} else {
log.Debug("active persister not found",
"epoch", ps.epochForPutOperation,
"used", persisterToUse.epoch)
}
}
ps.lock.RUnlock()
err := persisterToUse.persister.Put(key, data)
if err != nil {
ps.cacher.Remove(key)
return err
}
if ps.bloomFilter != nil {
ps.bloomFilter.Add(key)
}
return nil
}
// Get searches the key in the cache. In case it is not found, it verifies with the bloom filter
// if the key may be in the db. If bloom filter confirms then it further searches in the databases.
func (ps *PruningStorer) Get(key []byte) ([]byte, error) {
v, ok := ps.cacher.Get(key)
var err error
if !ok {
// not found in cache
// search it in active persisters
found := false
ps.lock.RLock()
for idx := uint32(0); (idx < ps.numOfActivePersisters) && (idx < uint32(len(ps.activePersisters))); idx++ {
if ps.bloomFilter == nil || ps.bloomFilter.MayContain(key) {
v, err = ps.activePersisters[idx].persister.Get(key)
if err != nil {
continue
}
buff, ok := v.([]byte)
if !ok {
continue
}
found = true
// if found in persistence unit, add it to cache
ps.cacher.Put(key, v, len(buff))
break
}
}
ps.lock.RUnlock()
if !found {
return nil, fmt.Errorf("key %s not found in %s",
hex.EncodeToString(key), ps.identifier)
}
}
return v.([]byte), nil
}
// Close will close PruningStorer
func (ps *PruningStorer) Close() error {
closedSuccessfully := true
for _, persister := range ps.activePersisters {
err := persister.persister.Close()
if err != nil {
log.Error("cannot close persister", err)
closedSuccessfully = false
}
}
if closedSuccessfully {
return nil
}
return storage.ErrClosingPersisters
}
// GetFromEpoch will search a key only in the persister for the given epoch
func (ps *PruningStorer) GetFromEpoch(key []byte, epoch uint32) ([]byte, error) {
// TODO: this will be used when requesting from resolvers
v, ok := ps.cacher.Get(key)
if ok {
return v.([]byte), nil
}
ps.lock.RLock()
pd, exists := ps.persistersMapByEpoch[epoch]
ps.lock.RUnlock()
if !exists {
return nil, fmt.Errorf("key %s not found in %s",
hex.EncodeToString(key), ps.identifier)
}
if !pd.getIsClosed() {
return pd.persister.Get(key)
}
persister, err := ps.persisterFactory.Create(pd.path)
if err != nil {
log.Debug("open old persister", "error", err.Error())
return nil, err
}
defer func() {
err = persister.Close()
if err != nil {
log.Debug("persister.Close()", "error", err.Error())
}
}()
err = persister.Init()
if err != nil {
log.Debug("init old persister", "error", err.Error())
return nil, err
}
res, err := persister.Get(key)
if err == nil {
return res, nil
}
log.Warn("get from closed persister",
"id", ps.identifier,
"epoch", epoch,
"key", key,
"error", err.Error())
return nil, fmt.Errorf("key %s not found in %s",
hex.EncodeToString(key), ps.identifier)
}
// GetBulkFromEpoch will return a slice of keys only in the persister for the given epoch
func (ps *PruningStorer) GetBulkFromEpoch(keys [][]byte, epoch uint32) (map[string][]byte, error) {
ps.lock.RLock()
pd, exists := ps.persistersMapByEpoch[epoch]
ps.lock.RUnlock()
if !exists {
log.Warn("get from removed persister",
"id", ps.identifier,
"epoch", epoch)
return nil, errors.New("persister does not exits")
}
var persisterToRead storage.Persister
var err error
if pd.getIsClosed() {
// TODO add a mutex when a persisterToRead is created
persisterToRead, err = ps.persisterFactory.Create(pd.path)
if err != nil {
log.Debug("open old persister", "error", err.Error())
return nil, err
}
defer func() {
err = persisterToRead.Close()
if err != nil {
log.Debug("persister.Close()", "error", err.Error())
}
}()
err = persisterToRead.Init()
if err != nil {
log.Debug("init old persister", "error", err.Error())
return nil, err
}
} else {
persisterToRead = pd.persister
}
returnMap := make(map[string][]byte, 0)
for _, key := range keys {
v, ok := ps.cacher.Get(key)
if ok {
returnMap[string(key)] = v.([]byte)
continue
}
res, err := persisterToRead.Get(key)
if err != nil {
log.Warn("cannot get from persister",
"hash", hex.EncodeToString(key),
"error", err.Error(),
)
continue
}
returnMap[string(key)] = res
}
return returnMap, nil
}
// SearchFirst will search a given key in all the active persisters, from the newest to the oldest
func (ps *PruningStorer) SearchFirst(key []byte) ([]byte, error) {
v, ok := ps.cacher.Get(key)
if ok {
return v.([]byte), nil
}
var res []byte
var err error
ps.lock.RLock()
defer ps.lock.RUnlock()
for _, pd := range ps.activePersisters {
res, err = pd.persister.Get(key)
if err == nil {
return res, nil
}
}
return nil, fmt.Errorf("%w - SearchFirst, unit = %s, key = %s, num active persisters = %d",
storage.ErrKeyNotFound,
ps.identifier,
hex.EncodeToString(key),
len(ps.activePersisters),
)
}
// Has checks if the key is in the Unit.
// It first checks the cache. If it is not found, it checks the bloom filter
// and if present it checks the db
func (ps *PruningStorer) Has(key []byte) error {
has := ps.cacher.Has(key)
if has {
return nil
}
ps.lock.RLock()
defer ps.lock.RUnlock()
if ps.bloomFilter == nil || ps.bloomFilter.MayContain(key) {
for _, persister := range ps.activePersisters {
if persister.persister.Has(key) != nil {
continue
}
return nil
}
}
return storage.ErrKeyNotFound
}
// HasInEpoch checks if the key is in the Unit in a given epoch.
// It first checks the cache. If it is not found, it checks the bloom filter
// and if present it checks the db
func (ps *PruningStorer) HasInEpoch(key []byte, epoch uint32) error {
// TODO: this will be used when requesting from resolvers
has := ps.cacher.Has(key)
if has {
return nil
}
if ps.bloomFilter == nil || ps.bloomFilter.MayContain(key) {
ps.lock.RLock()
pd, ok := ps.persistersMapByEpoch[epoch]
ps.lock.RUnlock()
if !ok {
return storage.ErrKeyNotFound
}
if !pd.getIsClosed() {
return pd.persister.Has(key)
}
persister, err := ps.persisterFactory.Create(pd.path)
if err != nil {
log.Debug("open old persister", "error", err.Error())
return err
}
defer func() {
err = persister.Close()
if err != nil {
log.Debug("persister.Close()", "error", err.Error())
}
}()
err = persister.Init()
if err != nil {
log.Debug("init old persister", "error", err.Error())
return err
}
return persister.Has(key)
}
return storage.ErrKeyNotFound
}
// SetEpochForPutOperation will set the epoch to be used when using the put operation
func (ps *PruningStorer) SetEpochForPutOperation(epoch uint32) {
ps.lock.Lock()
ps.epochForPutOperation = epoch
ps.lock.Unlock()
}
// Remove removes the data associated to the given key from both cache and persistence medium
func (ps *PruningStorer) Remove(key []byte) error {
var err error
ps.cacher.Remove(key)
ps.lock.RLock()
defer ps.lock.RUnlock()
for _, pd := range ps.activePersisters {
err = pd.persister.Remove(key)
if err == nil {
return nil
}
}
return err
}
// ClearCache cleans up the entire cache
func (ps *PruningStorer) ClearCache() {
ps.cacher.Clear()
}
// DestroyUnit cleans up the bloom filter, the cache, and the dbs
func (ps *PruningStorer) DestroyUnit() error {
ps.lock.Lock()
defer ps.lock.Unlock()
if ps.bloomFilter != nil {
ps.bloomFilter.Clear()
}
ps.cacher.Clear()
var err error
numOfPersistersRemoved := 0
totalNumOfPersisters := len(ps.persistersMapByEpoch)
for _, pd := range ps.persistersMapByEpoch {
if pd.getIsClosed() {
err = pd.persister.DestroyClosed()
} else {
err = pd.persister.Destroy()
}
if err != nil {
log.Debug("pruning db: destroy",
"error", err.Error())
continue
}
numOfPersistersRemoved++
}
if numOfPersistersRemoved != totalNumOfPersisters {
log.Debug("error destroying pruning db",
"identifier", ps.identifier,
"destroyed", numOfPersistersRemoved,
"total", totalNumOfPersisters)
return storage.ErrDestroyingUnit
}
return nil
}
// registerHandler will register a new function to the epoch start notifier
func (ps *PruningStorer) registerHandler(handler EpochStartNotifier) {
subscribeHandler := notifier.NewHandlerForEpochStart(
func(hdr data.HeaderHandler) {
err := ps.changeEpoch(hdr)
if err != nil {
log.Warn("change epoch in storer", "error", err.Error())
}
},
func(metaHdr data.HeaderHandler) {
err := ps.saveHeaderForEpochStartPrepare(metaHdr)
if err != nil {
log.Warn("prepare epoch change in storer", "error", err.Error())
}
},
core.StorerOrder)
handler.RegisterHandler(subscribeHandler)
}
func (ps *PruningStorer) saveHeaderForEpochStartPrepare(header data.HeaderHandler) error {
ps.mutEpochPrepareHdr.Lock()
defer ps.mutEpochPrepareHdr.Unlock()
var ok bool
ps.epochPrepareHdr, ok = header.(*block.MetaBlock)
if !ok {
return storage.ErrWrongTypeAssertion
}
return nil
}
// changeEpoch will handle creating a new persister and removing of the older ones
func (ps *PruningStorer) changeEpoch(header data.HeaderHandler) error {
epoch := header.GetEpoch()
log.Debug("PruningStorer - change epoch", "unit", ps.identifier, "epoch", epoch)
// if pruning is not enabled, don't create new persisters, but use the same one instead
if !ps.pruningEnabled {
log.Debug("PruningStorer - change epoch - pruning is disabled")
return nil
}
ps.lock.RLock()
_, ok := ps.persistersMapByEpoch[epoch]
ps.lock.RUnlock()
if ok {
err := ps.changeEpochWithExisting(epoch)
if err != nil {
log.Warn("change epoch", "epoch", epoch, "error", err)
return err
}
log.Info("change epoch pruning storer success", "persister", ps.identifier, "epoch", epoch)
return nil
}
shardID := core.GetShardIDString(ps.shardCoordinator.SelfId())
filePath := ps.pathManager.PathForEpoch(shardID, epoch, ps.identifier)
db, err := ps.persisterFactory.Create(filePath)
if err != nil {
log.Warn("change epoch", "persister", ps.identifier, "error", err.Error())
return err
}
newPersister := &persisterData{
persister: db,
epoch: epoch,
path: filePath,
isClosed: false,
}
singleItemPersisters := []*persisterData{newPersister}
ps.lock.Lock()
ps.activePersisters = append(singleItemPersisters, ps.activePersisters...)
ps.persistersMapByEpoch[epoch] = newPersister
err = ps.activePersisters[0].persister.Init()
if err != nil {
ps.lock.Unlock()
return err
}
ps.lock.Unlock()
wasExtended := ps.extendSavedEpochsIfNeeded(header)
if wasExtended {
return nil
}
err = ps.closeAndDestroyPersisters(epoch)
if err != nil {
log.Warn("closing and destroying old persister", "error", err.Error())
return err
}
return nil
}
func (ps *PruningStorer) extendSavedEpochsIfNeeded(header data.HeaderHandler) bool {
epoch := header.GetEpoch()
metaBlock, mbOk := header.(*block.MetaBlock)
if !mbOk {
ps.mutEpochPrepareHdr.RLock()
epochPrepareHdr := ps.epochPrepareHdr
ps.mutEpochPrepareHdr.RUnlock()
if epochPrepareHdr != nil {
metaBlock = epochPrepareHdr
} else {
return false
}
}
shouldExtend := metaBlock.Epoch != epochForDefaultEpochPrepareHdr
if !shouldExtend {
return false
}
ps.lock.RLock()
oldestEpochInCurrentSetting := ps.activePersisters[len(ps.activePersisters)-1].epoch
ps.lock.RUnlock()
oldestEpochToKeep := computeOldestEpoch(metaBlock)
shouldKeepOlderEpochsIfShardIsStuck := epoch-oldestEpochToKeep < maxNumEpochsToKeepIfAShardIsStuck
if oldestEpochToKeep <= oldestEpochInCurrentSetting && shouldKeepOlderEpochsIfShardIsStuck {
err := ps.extendActivePersisters(oldestEpochToKeep, oldestEpochInCurrentSetting)
if err != nil {
log.Warn("PruningStorer - extend epochs", "error", err)
return false
}
return true
}
return false
}
func (ps *PruningStorer) changeEpochWithExisting(epoch uint32) error {
ps.lock.RLock()
numActivePersisters := ps.numOfActivePersisters
var err error
activePersisters := make([]*persisterData, 0, numActivePersisters)
oldestEpochActive := int64(epoch) - int64(numActivePersisters) + 1
if oldestEpochActive < 0 {
oldestEpochActive = 0
}
persisters := make([]*persisterData, 0)
for e := int64(epoch); e >= oldestEpochActive; e-- {
p, ok := ps.persistersMapByEpoch[uint32(e)]
if !ok {
ps.lock.RUnlock()
return nil
}
persisters = append(persisters, p)
}
ps.lock.RUnlock()
for _, p := range persisters {
if p.getIsClosed() {
_, err = ps.persisterFactory.Create(p.path)
if err != nil {
return err
}
}
activePersisters = append(activePersisters, p)
}
ps.lock.Lock()
ps.activePersisters = activePersisters
ps.lock.Unlock()
return nil
}
func (ps *PruningStorer) extendActivePersisters(from uint32, to uint32) error {
count := 0
persisters := make([]*persisterData, 0)
ps.lock.RLock()
for e := int(to); e >= int(from); e-- {
count++
p, ok := ps.persistersMapByEpoch[uint32(e)]
if !ok {
ps.lock.RUnlock()
return nil
}
persisters = append(persisters, p)
}
ps.lock.RUnlock()
reOpenedPersisters := make([]*persisterData, 0)
for _, p := range persisters {
if p.getIsClosed() {
_, err := ps.persisterFactory.Create(p.path)
if err != nil {
return err
}
reOpenedPersisters = append(reOpenedPersisters, p)
p.setIsClosed(false)
}
}
ps.lock.Lock()
ps.activePersisters = append(ps.activePersisters, reOpenedPersisters...)
ps.lock.Unlock()
if count > 0 {
log.Info("PruningStorer - extend stored epochs due to a stuck shard",
"from epoch", from,
"to epoch", to)
}
return nil
}
func (ps *PruningStorer) closeAndDestroyPersisters(epoch uint32) error {
// activePersisters outside the numOfActivePersisters border have to he closed for both scenarios: full archive or not
persistersToClose := make([]*persisterData, 0)
persistersToDestroy := make([]*persisterData, 0)
ps.lock.Lock()
if ps.numOfActivePersisters < uint32(len(ps.activePersisters)) {
for idx := int(ps.numOfActivePersisters); idx < len(ps.activePersisters); idx++ {
persisterToClose := ps.activePersisters[idx]
// remove it from the active persisters slice
ps.activePersisters = ps.activePersisters[:ps.numOfActivePersisters]
epochToClose := epoch - ps.numOfActivePersisters
ps.persistersMapByEpoch[epochToClose] = persisterToClose
persistersToClose = append(persistersToClose, persisterToClose)
}
}
if ps.cleanOldEpochsData && uint32(len(ps.persistersMapByEpoch)) > ps.numOfEpochsToKeep {
idxToRemove := epoch - ps.numOfEpochsToKeep
for {
//epochToRemove := epoch - ps.numOfEpochsToKeep
persisterToDestroy, ok := ps.persistersMapByEpoch[idxToRemove]
if !ok {
break
}
delete(ps.persistersMapByEpoch, idxToRemove)
idxToRemove--
persistersToDestroy = append(persistersToDestroy, persisterToDestroy)
}
}
ps.lock.Unlock()
for _, p := range persistersToClose {
err := p.persister.Close()
if err != nil {
log.Error("error closing persister", "error", err.Error(), "id", ps.identifier)
return err
}
p.setIsClosed(true)
}
for _, p := range persistersToDestroy {
err := p.persister.DestroyClosed()
if err != nil {
return err
}
removeDirectoryIfEmpty(p.path)
}
return nil
}
// RangeKeys does nothing as it is unable to iterate over multiple persisters
// RangeKeys -
func (ps *PruningStorer) RangeKeys(_ func(key []byte, val []byte) bool) {
log.Error("improper use of PruningStorer.RangeKeys()")
debug.PrintStack()
}
// IsInterfaceNil returns true if there is no value under the interface
func (ps *PruningStorer) IsInterfaceNil() bool {
return ps == nil
}
func createPersisterDataForEpoch(args *StorerArgs, epoch uint32, shardIdStr string) (*persisterData, error) {
// TODO: if booting from storage in an epoch > 0, shardId needs to be taken from somewhere else
// e.g. determined from directories in persister path or taken from boot storer
filePath := args.PathManager.PathForEpoch(core.GetShardIDString(args.ShardCoordinator.SelfId()), epoch, args.Identifier)
if len(shardIdStr) > 0 {
filePath += shardIdStr
}
db, err := args.PersisterFactory.Create(filePath)
if err != nil {
log.Warn("persister create error", "error", err.Error())
return nil, err
}
p := &persisterData{
persister: db,
epoch: epoch,
path: filePath,
isClosed: false,
}
err = p.persister.Init()
if err != nil {
log.Warn("init old persister", "error", err.Error())
return nil, err
}
return p, nil
}
func computeOldestEpoch(metaBlock *block.MetaBlock) uint32 {
oldestEpoch := metaBlock.Epoch
for _, lastHdr := range metaBlock.EpochStart.LastFinalizedHeaders {
if lastHdr.Epoch < oldestEpoch {
oldestEpoch = lastHdr.Epoch
}
}
return oldestEpoch
}