-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
store.go
773 lines (684 loc) · 23.7 KB
/
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
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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package pvtdatastorage
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/ledger/rwset"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/ledger/util/leveldbhelper"
"github.com/hyperledger/fabric/core/ledger"
"github.com/hyperledger/fabric/core/ledger/pvtdatapolicy"
"github.com/willf/bitset"
)
var logger = flogging.MustGetLogger("pvtdatastorage")
// Provider provides handle to specific 'Store' that in turn manages
// private write sets for a ledger
type Provider struct {
dbProvider *leveldbhelper.Provider
pvtData *PrivateDataConfig
}
// PrivateDataConfig encapsulates the configuration for private data storage on the ledger
type PrivateDataConfig struct {
// PrivateDataConfig is used to configure a private data storage provider
*ledger.PrivateDataConfig
// StorePath is the filesystem path for private data storage.
// It is internally computed by the ledger component,
// so it is not in ledger.PrivateDataConfig and not exposed to other components.
StorePath string
}
// Store manages the permanent storage of private write sets for a ledger
type Store struct {
db *leveldbhelper.DBHandle
ledgerid string
btlPolicy pvtdatapolicy.BTLPolicy
batchesInterval int
maxBatchSize int
purgeInterval uint64
isEmpty bool
lastCommittedBlock uint64
purgerLock sync.Mutex
collElgProcSync *collElgProcSync
// After committing the pvtdata of old blocks,
// the `isLastUpdatedOldBlocksSet` is set to true.
// Once the stateDB is updated with these pvtdata,
// the `isLastUpdatedOldBlocksSet` is set to false.
// isLastUpdatedOldBlocksSet is mainly used during the
// recovery process. During the peer startup, if the
// isLastUpdatedOldBlocksSet is set to true, the pvtdata
// in the stateDB needs to be updated before finishing the
// recovery operation.
isLastUpdatedOldBlocksSet bool
}
type Initializer struct {
CreatedFromSnapshot bool
LastBlockInSnapshot uint64
}
type blkTranNumKey []byte
type dataEntry struct {
key *dataKey
value *rwset.CollectionPvtReadWriteSet
}
type expiryEntry struct {
key *expiryKey
value *ExpiryData
}
type expiryKey struct {
expiringBlk uint64
committingBlk uint64
}
type nsCollBlk struct {
ns, coll string
blkNum uint64
}
type dataKey struct {
nsCollBlk
txNum uint64
}
type missingDataKey struct {
nsCollBlk
isEligible bool
}
type storeEntries struct {
dataEntries []*dataEntry
expiryEntries []*expiryEntry
missingDataEntries map[missingDataKey]*bitset.BitSet
}
// lastUpdatedOldBlocksList keeps the list of last updated blocks
// and is stored as the value of lastUpdatedOldBlocksKey (defined in kv_encoding.go)
type lastUpdatedOldBlocksList []uint64
//////// Provider functions /////////////
//////////////////////////////////////////
// NewProvider instantiates a StoreProvider
func NewProvider(conf *PrivateDataConfig) (*Provider, error) {
dbProvider, err := leveldbhelper.NewProvider(&leveldbhelper.Conf{DBPath: conf.StorePath})
if err != nil {
return nil, err
}
return &Provider{
dbProvider: dbProvider,
pvtData: conf,
}, nil
}
// OpenStore returns a handle to a store
func (p *Provider) OpenStore(ledgerid string, initializer *Initializer) (*Store, error) {
dbHandle := p.dbProvider.GetDBHandle(ledgerid)
s := &Store{
db: dbHandle,
ledgerid: ledgerid,
batchesInterval: p.pvtData.BatchesInterval,
maxBatchSize: p.pvtData.MaxBatchSize,
purgeInterval: uint64(p.pvtData.PurgeInterval),
collElgProcSync: &collElgProcSync{
notification: make(chan bool, 1),
procComplete: make(chan bool, 1),
},
}
if err := s.initState(); err != nil {
return nil, err
}
// TODO: workaround that will be removed when snapshot import is implemented for pvtdata store
if s.isEmpty && initializer.CreatedFromSnapshot {
s.isEmpty = false
s.lastCommittedBlock = initializer.LastBlockInSnapshot
}
s.launchCollElgProc()
logger.Debugf("Pvtdata store opened. Initial state: isEmpty [%t], lastCommittedBlock [%d]",
s.isEmpty, s.lastCommittedBlock)
return s, nil
}
// Close closes the store
func (p *Provider) Close() {
p.dbProvider.Close()
}
// Drop drops channel-specific data from the pvtdata store
func (p *Provider) Drop(ledgerid string) error {
return p.dbProvider.Drop(ledgerid)
}
//////// store functions ////////////////
//////////////////////////////////////////
func (s *Store) initState() error {
var err error
var blist lastUpdatedOldBlocksList
if s.isEmpty, s.lastCommittedBlock, err = s.getLastCommittedBlockNum(); err != nil {
return err
}
// TODO: FAB-16298 -- the concept of pendingBatch is no longer valid
// for pvtdataStore. We can remove it v2.1. We retain the concept in
// v2.0 to allow rolling upgrade from v142 to v2.0
batchPending, err := s.hasPendingCommit()
if err != nil {
return err
}
if batchPending {
committingBlockNum := s.nextBlockNum()
batch := s.db.NewUpdateBatch()
batch.Put(lastCommittedBlkkey, encodeLastCommittedBlockVal(committingBlockNum))
batch.Delete(pendingCommitKey)
if err := s.db.WriteBatch(batch, true); err != nil {
return err
}
s.isEmpty = false
s.lastCommittedBlock = committingBlockNum
}
if blist, err = s.getLastUpdatedOldBlocksList(); err != nil {
return err
}
if len(blist) > 0 {
s.isLastUpdatedOldBlocksSet = true
} // false if not set
return nil
}
// Init initializes the store. This function is expected to be invoked before using the store
func (s *Store) Init(btlPolicy pvtdatapolicy.BTLPolicy) {
s.btlPolicy = btlPolicy
}
// Commit commits the pvt data as well as both the eligible and ineligible
// missing private data --- `eligible` denotes that the missing private data belongs to a collection
// for which this peer is a member; `ineligible` denotes that the missing private data belong to a
// collection for which this peer is not a member.
func (s *Store) Commit(blockNum uint64, pvtData []*ledger.TxPvtData, missingPvtData ledger.TxMissingPvtData) error {
expectedBlockNum := s.nextBlockNum()
if expectedBlockNum != blockNum {
return &ErrIllegalArgs{fmt.Sprintf("Expected block number=%d, received block number=%d", expectedBlockNum, blockNum)}
}
batch := s.db.NewUpdateBatch()
var err error
var keyBytes, valBytes []byte
storeEntries, err := prepareStoreEntries(blockNum, pvtData, s.btlPolicy, missingPvtData)
if err != nil {
return err
}
for _, dataEntry := range storeEntries.dataEntries {
keyBytes = encodeDataKey(dataEntry.key)
if valBytes, err = encodeDataValue(dataEntry.value); err != nil {
return err
}
batch.Put(keyBytes, valBytes)
}
for _, expiryEntry := range storeEntries.expiryEntries {
keyBytes = encodeExpiryKey(expiryEntry.key)
if valBytes, err = encodeExpiryValue(expiryEntry.value); err != nil {
return err
}
batch.Put(keyBytes, valBytes)
}
for missingDataKey, missingDataValue := range storeEntries.missingDataEntries {
keyBytes = encodeMissingDataKey(&missingDataKey)
if valBytes, err = encodeMissingDataValue(missingDataValue); err != nil {
return err
}
batch.Put(keyBytes, valBytes)
}
committingBlockNum := s.nextBlockNum()
logger.Debugf("Committing private data for block [%d]", committingBlockNum)
batch.Put(lastCommittedBlkkey, encodeLastCommittedBlockVal(committingBlockNum))
if err := s.db.WriteBatch(batch, true); err != nil {
return err
}
s.isEmpty = false
atomic.StoreUint64(&s.lastCommittedBlock, committingBlockNum)
logger.Debugf("Committed private data for block [%d]", committingBlockNum)
s.performPurgeIfScheduled(committingBlockNum)
return nil
}
// GetLastUpdatedOldBlocksPvtData returns the pvtdata of blocks listed in `lastUpdatedOldBlocksList`
// TODO FAB-16293 -- GetLastUpdatedOldBlocksPvtData() can be removed either in v2.0 or in v2.1.
// If we decide to rebuild stateDB in v2.0, by default, the rebuild logic would take
// care of synching stateDB with pvtdataStore without calling GetLastUpdatedOldBlocksPvtData().
// Hence, it can be safely removed. Suppose if we decide not to rebuild stateDB in v2.0,
// we can remove this function in v2.1.
func (s *Store) GetLastUpdatedOldBlocksPvtData() (map[uint64][]*ledger.TxPvtData, error) {
if !s.isLastUpdatedOldBlocksSet {
return nil, nil
}
updatedBlksList, err := s.getLastUpdatedOldBlocksList()
if err != nil {
return nil, err
}
blksPvtData := make(map[uint64][]*ledger.TxPvtData)
for _, blkNum := range updatedBlksList {
if blksPvtData[blkNum], err = s.GetPvtDataByBlockNum(blkNum, nil); err != nil {
return nil, err
}
}
return blksPvtData, nil
}
func (s *Store) getLastUpdatedOldBlocksList() ([]uint64, error) {
var v []byte
var err error
if v, err = s.db.Get(lastUpdatedOldBlocksKey); err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
var updatedBlksList []uint64
buf := proto.NewBuffer(v)
numBlks, err := buf.DecodeVarint()
if err != nil {
return nil, err
}
for i := 0; i < int(numBlks); i++ {
blkNum, err := buf.DecodeVarint()
if err != nil {
return nil, err
}
updatedBlksList = append(updatedBlksList, blkNum)
}
return updatedBlksList, nil
}
// TODO FAB-16294 -- ResetLastUpdatedOldBlocksList() can be removed in v2.1.
// From v2.0 onwards, we do not store the last updatedBlksList. Only to support
// the rolling upgrade from v142 to v2.0, we retain the ResetLastUpdatedOldBlocksList()
// in v2.0.
// ResetLastUpdatedOldBlocksList removes the `lastUpdatedOldBlocksList` entry from the store
func (s *Store) ResetLastUpdatedOldBlocksList() error {
batch := s.db.NewUpdateBatch()
batch.Delete(lastUpdatedOldBlocksKey)
if err := s.db.WriteBatch(batch, true); err != nil {
return err
}
s.isLastUpdatedOldBlocksSet = false
return nil
}
// GetPvtDataByBlockNum returns only the pvt data corresponding to the given block number
// The pvt data is filtered by the list of 'ns/collections' supplied in the filter
// A nil filter does not filter any results
func (s *Store) GetPvtDataByBlockNum(blockNum uint64, filter ledger.PvtNsCollFilter) ([]*ledger.TxPvtData, error) {
logger.Debugf("Get private data for block [%d], filter=%#v", blockNum, filter)
if s.isEmpty {
return nil, &ErrOutOfRange{"The store is empty"}
}
lastCommittedBlock := atomic.LoadUint64(&s.lastCommittedBlock)
if blockNum > lastCommittedBlock {
return nil, &ErrOutOfRange{fmt.Sprintf("Last committed block=%d, block requested=%d", lastCommittedBlock, blockNum)}
}
startKey, endKey := getDataKeysForRangeScanByBlockNum(blockNum)
logger.Debugf("Querying private data storage for write sets using startKey=%#v, endKey=%#v", startKey, endKey)
itr, err := s.db.GetIterator(startKey, endKey)
if err != nil {
return nil, err
}
defer itr.Release()
var blockPvtdata []*ledger.TxPvtData
var currentTxNum uint64
var currentTxWsetAssember *txPvtdataAssembler
firstItr := true
for itr.Next() {
dataKeyBytes := itr.Key()
v11Fmt, err := v11Format(dataKeyBytes)
if err != nil {
return nil, err
}
if v11Fmt {
return v11RetrievePvtdata(itr, filter)
}
dataValueBytes := itr.Value()
dataKey, err := decodeDatakey(dataKeyBytes)
if err != nil {
return nil, err
}
expired, err := isExpired(dataKey.nsCollBlk, s.btlPolicy, lastCommittedBlock)
if err != nil {
return nil, err
}
if expired || !passesFilter(dataKey, filter) {
continue
}
dataValue, err := decodeDataValue(dataValueBytes)
if err != nil {
return nil, err
}
if firstItr {
currentTxNum = dataKey.txNum
currentTxWsetAssember = newTxPvtdataAssembler(blockNum, currentTxNum)
firstItr = false
}
if dataKey.txNum != currentTxNum {
blockPvtdata = append(blockPvtdata, currentTxWsetAssember.getTxPvtdata())
currentTxNum = dataKey.txNum
currentTxWsetAssember = newTxPvtdataAssembler(blockNum, currentTxNum)
}
currentTxWsetAssember.add(dataKey.ns, dataValue)
}
if currentTxWsetAssember != nil {
blockPvtdata = append(blockPvtdata, currentTxWsetAssember.getTxPvtdata())
}
return blockPvtdata, nil
}
// GetMissingPvtDataInfoForMostRecentBlocks returns the missing private data information for the
// most recent `maxBlock` blocks which miss at least a private data of a eligible collection.
func (s *Store) GetMissingPvtDataInfoForMostRecentBlocks(maxBlock int) (ledger.MissingPvtDataInfo, error) {
// we assume that this function would be called by the gossip only after processing the
// last retrieved missing pvtdata info and committing the same.
if maxBlock < 1 {
return nil, nil
}
missingPvtDataInfo := make(ledger.MissingPvtDataInfo)
numberOfBlockProcessed := 0
lastProcessedBlock := uint64(0)
isMaxBlockLimitReached := false
// as we are not acquiring a read lock, new blocks can get committed while we
// construct the MissingPvtDataInfo. As a result, lastCommittedBlock can get
// changed. To ensure consistency, we atomically load the lastCommittedBlock value
lastCommittedBlock := atomic.LoadUint64(&s.lastCommittedBlock)
startKey, endKey := createRangeScanKeysForEligibleMissingDataEntries(lastCommittedBlock)
dbItr, err := s.db.GetIterator(startKey, endKey)
if err != nil {
return nil, err
}
defer dbItr.Release()
for dbItr.Next() {
missingDataKeyBytes := dbItr.Key()
missingDataKey := decodeMissingDataKey(missingDataKeyBytes)
if isMaxBlockLimitReached && (missingDataKey.blkNum != lastProcessedBlock) {
// ensures that exactly maxBlock number
// of blocks' entries are processed
break
}
// check whether the entry is expired. If so, move to the next item.
// As we may use the old lastCommittedBlock value, there is a possibility that
// this missing data is actually expired but we may get the stale information.
// Though it may leads to extra work of pulling the expired data, it will not
// affect the correctness. Further, as we try to fetch the most recent missing
// data (less possibility of expiring now), such scenario would be rare. In the
// best case, we can load the latest lastCommittedBlock value here atomically to
// make this scenario very rare.
lastCommittedBlock = atomic.LoadUint64(&s.lastCommittedBlock)
expired, err := isExpired(missingDataKey.nsCollBlk, s.btlPolicy, lastCommittedBlock)
if err != nil {
return nil, err
}
if expired {
continue
}
// check for an existing entry for the blkNum in the MissingPvtDataInfo.
// If no such entry exists, create one. Also, keep track of the number of
// processed block due to maxBlock limit.
if _, ok := missingPvtDataInfo[missingDataKey.blkNum]; !ok {
numberOfBlockProcessed++
if numberOfBlockProcessed == maxBlock {
isMaxBlockLimitReached = true
// as there can be more than one entry for this block,
// we cannot `break` here
lastProcessedBlock = missingDataKey.blkNum
}
}
valueBytes := dbItr.Value()
bitmap, err := decodeMissingDataValue(valueBytes)
if err != nil {
return nil, err
}
// for each transaction which misses private data, make an entry in missingBlockPvtDataInfo
for index, isSet := bitmap.NextSet(0); isSet; index, isSet = bitmap.NextSet(index + 1) {
txNum := uint64(index)
missingPvtDataInfo.Add(missingDataKey.blkNum, txNum, missingDataKey.ns, missingDataKey.coll)
}
}
return missingPvtDataInfo, nil
}
// ProcessCollsEligibilityEnabled notifies the store when the peer becomes eligible to receive data for an
// existing collection. Parameter 'committingBlk' refers to the block number that contains the corresponding
// collection upgrade transaction and the parameter 'nsCollMap' contains the collections for which the peer
// is now eligible to receive pvt data
func (s *Store) ProcessCollsEligibilityEnabled(committingBlk uint64, nsCollMap map[string][]string) error {
key := encodeCollElgKey(committingBlk)
m := newCollElgInfo(nsCollMap)
val, err := encodeCollElgVal(m)
if err != nil {
return err
}
batch := s.db.NewUpdateBatch()
batch.Put(key, val)
if err = s.db.WriteBatch(batch, true); err != nil {
return err
}
s.collElgProcSync.notify()
return nil
}
func (s *Store) performPurgeIfScheduled(latestCommittedBlk uint64) {
if latestCommittedBlk%s.purgeInterval != 0 {
return
}
go func() {
s.purgerLock.Lock()
logger.Debugf("Purger started: Purging expired private data till block number [%d]", latestCommittedBlk)
defer s.purgerLock.Unlock()
err := s.purgeExpiredData(0, latestCommittedBlk)
if err != nil {
logger.Warningf("Could not purge data from pvtdata store:%s", err)
}
logger.Debug("Purger finished")
}()
}
func (s *Store) purgeExpiredData(minBlkNum, maxBlkNum uint64) error {
batch := s.db.NewUpdateBatch()
expiryEntries, err := s.retrieveExpiryEntries(minBlkNum, maxBlkNum)
if err != nil || len(expiryEntries) == 0 {
return err
}
for _, expiryEntry := range expiryEntries {
// this encoding could have been saved if the function retrieveExpiryEntries also returns the encoded expiry keys.
// However, keeping it for better readability
batch.Delete(encodeExpiryKey(expiryEntry.key))
dataKeys, missingDataKeys := deriveKeys(expiryEntry)
for _, dataKey := range dataKeys {
batch.Delete(encodeDataKey(dataKey))
}
for _, missingDataKey := range missingDataKeys {
batch.Delete(encodeMissingDataKey(missingDataKey))
}
if err := s.db.WriteBatch(batch, false); err != nil {
return err
}
}
logger.Infof("[%s] - [%d] Entries purged from private data storage till block number [%d]", s.ledgerid, len(expiryEntries), maxBlkNum)
return nil
}
func (s *Store) retrieveExpiryEntries(minBlkNum, maxBlkNum uint64) ([]*expiryEntry, error) {
startKey, endKey := getExpiryKeysForRangeScan(minBlkNum, maxBlkNum)
logger.Debugf("retrieveExpiryEntries(): startKey=%#v, endKey=%#v", startKey, endKey)
itr, err := s.db.GetIterator(startKey, endKey)
if err != nil {
return nil, err
}
defer itr.Release()
var expiryEntries []*expiryEntry
for itr.Next() {
expiryKeyBytes := itr.Key()
expiryValueBytes := itr.Value()
expiryKey, err := decodeExpiryKey(expiryKeyBytes)
if err != nil {
return nil, err
}
expiryValue, err := decodeExpiryValue(expiryValueBytes)
if err != nil {
return nil, err
}
expiryEntries = append(expiryEntries, &expiryEntry{key: expiryKey, value: expiryValue})
}
return expiryEntries, nil
}
func (s *Store) launchCollElgProc() {
go func() {
if err := s.processCollElgEvents(); err != nil {
// process collection eligibility events when store is opened -
// in case there is an unprocessed events from previous run
logger.Errorw("failed to process collection eligibility events", "err", err)
}
for {
logger.Debugf("Waiting for collection eligibility event")
s.collElgProcSync.waitForNotification()
if err := s.processCollElgEvents(); err != nil {
logger.Errorw("failed to process collection eligibility events", "err", err)
}
s.collElgProcSync.done()
}
}()
}
func (s *Store) processCollElgEvents() error {
logger.Debugf("Starting to process collection eligibility events")
s.purgerLock.Lock()
defer s.purgerLock.Unlock()
collElgStartKey, collElgEndKey := createRangeScanKeysForCollElg()
eventItr, err := s.db.GetIterator(collElgStartKey, collElgEndKey)
if err != nil {
return err
}
defer eventItr.Release()
batch := s.db.NewUpdateBatch()
totalEntriesConverted := 0
for eventItr.Next() {
collElgKey, collElgVal := eventItr.Key(), eventItr.Value()
blkNum := decodeCollElgKey(collElgKey)
CollElgInfo, err := decodeCollElgVal(collElgVal)
logger.Debugf("Processing collection eligibility event [blkNum=%d], CollElgInfo=%s", blkNum, CollElgInfo)
if err != nil {
logger.Errorf("This error is not expected %s", err)
continue
}
for ns, colls := range CollElgInfo.NsCollMap {
var coll string
for _, coll = range colls.Entries {
logger.Infof("Converting missing data entries from ineligible to eligible for [ns=%s, coll=%s]", ns, coll)
startKey, endKey := createRangeScanKeysForIneligibleMissingData(blkNum, ns, coll)
collItr, err := s.db.GetIterator(startKey, endKey)
if err != nil {
return err
}
collEntriesConverted := 0
for collItr.Next() { // each entry
originalKey, originalVal := collItr.Key(), collItr.Value()
modifiedKey := decodeMissingDataKey(originalKey)
modifiedKey.isEligible = true
batch.Delete(originalKey)
copyVal := make([]byte, len(originalVal))
copy(copyVal, originalVal)
batch.Put(encodeMissingDataKey(modifiedKey), copyVal)
collEntriesConverted++
if batch.Len() > s.maxBatchSize {
s.db.WriteBatch(batch, true)
batch.Reset()
sleepTime := time.Duration(s.batchesInterval)
logger.Infof("Going to sleep for %d milliseconds between batches. Entries for [ns=%s, coll=%s] converted so far = %d",
sleepTime, ns, coll, collEntriesConverted)
s.purgerLock.Unlock()
time.Sleep(sleepTime * time.Millisecond)
s.purgerLock.Lock()
}
} // entry loop
collItr.Release()
logger.Infof("Converted all [%d] entries for [ns=%s, coll=%s]", collEntriesConverted, ns, coll)
totalEntriesConverted += collEntriesConverted
} // coll loop
} // ns loop
batch.Delete(collElgKey) // delete the collection eligibility event key as well
} // event loop
s.db.WriteBatch(batch, true)
logger.Debugf("Converted [%d] ineligible missing data entries to eligible", totalEntriesConverted)
return nil
}
// LastCommittedBlockHeight returns the height of the last committed block
func (s *Store) LastCommittedBlockHeight() (uint64, error) {
if s.isEmpty {
return 0, nil
}
return atomic.LoadUint64(&s.lastCommittedBlock) + 1, nil
}
func (s *Store) nextBlockNum() uint64 {
if s.isEmpty {
return 0
}
return atomic.LoadUint64(&s.lastCommittedBlock) + 1
}
// TODO: FAB-16298 -- the concept of pendingBatch is no longer valid
// for pvtdataStore. We can remove it v2.1. We retain the concept in
// v2.0 to allow rolling upgrade from v142 to v2.0
func (s *Store) hasPendingCommit() (bool, error) {
var v []byte
var err error
if v, err = s.db.Get(pendingCommitKey); err != nil {
return false, err
}
return v != nil, nil
}
func (s *Store) getLastCommittedBlockNum() (bool, uint64, error) {
var v []byte
var err error
if v, err = s.db.Get(lastCommittedBlkkey); v == nil || err != nil {
return true, 0, err
}
return false, decodeLastCommittedBlockVal(v), nil
}
type collElgProcSync struct {
notification, procComplete chan bool
}
func (c *collElgProcSync) notify() {
select {
case c.notification <- true:
logger.Debugf("Signaled to collection eligibility processing routine")
default: //noop
logger.Debugf("Previous signal still pending. Skipping new signal")
}
}
func (c *collElgProcSync) waitForNotification() {
<-c.notification
}
func (c *collElgProcSync) done() {
select {
case c.procComplete <- true:
default:
}
}
func (c *collElgProcSync) waitForDone() {
<-c.procComplete
}
func (s *Store) getBitmapOfMissingDataKey(missingDataKey *missingDataKey) (*bitset.BitSet, error) {
var v []byte
var err error
if v, err = s.db.Get(encodeMissingDataKey(missingDataKey)); err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
return decodeMissingDataValue(v)
}
func (s *Store) getExpiryDataOfExpiryKey(expiryKey *expiryKey) (*ExpiryData, error) {
var v []byte
var err error
if v, err = s.db.Get(encodeExpiryKey(expiryKey)); err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
return decodeExpiryValue(v)
}
// ErrIllegalCall is to be thrown by a store impl if the store does not expect a call to Prepare/Commit/Rollback/InitLastCommittedBlock
type ErrIllegalCall struct {
msg string
}
func (err *ErrIllegalCall) Error() string {
return err.msg
}
// ErrIllegalArgs is to be thrown by a store impl if the args passed are not allowed
type ErrIllegalArgs struct {
msg string
}
func (err *ErrIllegalArgs) Error() string {
return err.msg
}
// ErrOutOfRange is to be thrown for the request for the data that is not yet committed
type ErrOutOfRange struct {
msg string
}
func (err *ErrOutOfRange) Error() string {
return err.msg
}