-
Notifications
You must be signed in to change notification settings - Fork 0
/
statecouchdb.go
1216 lines (949 loc) · 37.5 KB
/
statecouchdb.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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package statecouchdb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"unicode/utf8"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric/core/ledger/cceventmgmt"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb"
"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/version"
"github.com/hyperledger/fabric/core/ledger/ledgerconfig"
"github.com/hyperledger/fabric/core/ledger/util/couchdb"
logging "github.com/op/go-logging"
)
var logger = flogging.MustGetLogger("statecouchdb")
const (
binaryWrapper = "valueBytes"
idField = "_id"
revField = "_rev"
versionField = "~version"
deletedField = "_deleted"
)
var reservedFields = []string{idField, revField, versionField, deletedField}
var dbArtifactsDirFilter = map[string]bool{"META-INF/statedb/couchdb/indexes": true}
// querySkip is implemented for future use by query paging
// currently defaulted to 0 and is not used
const querySkip = 0
//BatchableDocument defines a document for a batch
type BatchableDocument struct {
CouchDoc couchdb.CouchDoc
Deleted bool
}
// VersionedDBProvider implements interface VersionedDBProvider
type VersionedDBProvider struct {
couchInstance *couchdb.CouchInstance
databases map[string]*VersionedDB
mux sync.Mutex
openCounts uint64
}
// CommittedVersions contains maps of committedVersions and revisionNumbers.
// Used as a local cache during bulk processing of a block.
// committedVersions - used for state validation of readsets
// revisionNumbers - used during commit phase for couchdb bulk updates
type CommittedVersions struct {
committedVersions map[statedb.CompositeKey]*version.Height
revisionNumbers map[statedb.CompositeKey]string
mux sync.RWMutex
// For now, we use one mutex for both versionNo and revisionNo. Having
// two mutex might be a overkill.
}
// NewVersionedDBProvider instantiates VersionedDBProvider
func NewVersionedDBProvider() (*VersionedDBProvider, error) {
logger.Debugf("constructing CouchDB VersionedDBProvider")
couchDBDef := couchdb.GetCouchDBDefinition()
couchInstance, err := couchdb.CreateCouchInstance(couchDBDef.URL, couchDBDef.Username, couchDBDef.Password,
couchDBDef.MaxRetries, couchDBDef.MaxRetriesOnStartup, couchDBDef.RequestTimeout)
if err != nil {
return nil, err
}
return &VersionedDBProvider{couchInstance, make(map[string]*VersionedDB), sync.Mutex{}, 0}, nil
}
//HandleChaincodeDeploy initializes database artifacts for the database associated with the namespace
// This function delibrately suppresses the errors that occur during the creation of the indexes on couchdb.
// This is because, in the present code, we do not differentiate between the errors because of couchdb interaction
// and the errors because of bad index files - the later being unfixable by the admin. Note that the error suppression
// is acceptable since peer can continue in the committing role without the indexes. However, executing chaincode queries
// may be affected, until a new chaincode with fixed indexes is installed and instantiated
func (vdb *VersionedDB) HandleChaincodeDeploy(chaincodeDefinition *cceventmgmt.ChaincodeDefinition, dbArtifactsTar []byte) error {
logger.Debugf("Entering HandleChaincodeDeploy")
if chaincodeDefinition == nil {
return fmt.Errorf("chaincodeDefinition found nil while creating couchdb index on chain=%s", vdb.chainName)
}
db, err := vdb.getNamespaceDBHandle(chaincodeDefinition.Name)
if err != nil {
return err
}
fileEntries, err := ccprovider.ExtractFileEntries(dbArtifactsTar, dbArtifactsDirFilter)
if err != nil {
logger.Errorf("Error during extracting db artifacts from tar for chaincode=[%s] on chain=[%s]. Error=%s",
chaincodeDefinition, vdb.chainName, err)
return nil
}
for _, fileEntry := range fileEntries {
indexData := fileEntry.FileContent
filename := fileEntry.FileHeader.Name
_, err = db.CreateIndex(string(indexData))
if err != nil {
logger.Errorf("Error during creation of index from file=[%s] for chaincode=[%s] on chain=[%s]. Error=%s",
filename, chaincodeDefinition, vdb.chainName, err)
}
}
return nil
}
// GetDBHandle gets the handle to a named database
func (provider *VersionedDBProvider) GetDBHandle(dbName string) (statedb.VersionedDB, error) {
provider.mux.Lock()
defer provider.mux.Unlock()
vdb := provider.databases[dbName]
if vdb == nil {
var err error
vdb, err = newVersionedDB(provider.couchInstance, dbName)
if err != nil {
return nil, err
}
provider.databases[dbName] = vdb
}
return vdb, nil
}
// Close closes the underlying db instance
func (provider *VersionedDBProvider) Close() {
// No close needed on Couch
}
// VersionedDB implements VersionedDB interface
type VersionedDB struct {
couchInstance *couchdb.CouchInstance
metadataDB *couchdb.CouchDatabase // A database per channel to store metadata such as savepoint.
chainName string // The name of the chain/channel.
namespaceDBs map[string]*couchdb.CouchDatabase // One database per deployed chaincode.
//TODO: Decide whether to split committedDataCache into multiple cahces, i.e., one per namespace.
committedDataCache *CommittedVersions // Used as a local cache during bulk processing of a block.
mux sync.RWMutex
}
// newVersionedDB constructs an instance of VersionedDB
func newVersionedDB(couchInstance *couchdb.CouchInstance, dbName string) (*VersionedDB, error) {
// CreateCouchDatabase creates a CouchDB database object, as well as the underlying database if it does not exist
chainName := dbName
dbName = couchdb.ConstructMetadataDBName(dbName)
metadataDB, err := couchdb.CreateCouchDatabase(*couchInstance, dbName)
if err != nil {
return nil, err
}
versionMap := make(map[statedb.CompositeKey]*version.Height)
revMap := make(map[statedb.CompositeKey]string)
namespaceDBMap := make(map[string]*couchdb.CouchDatabase)
committedDataCache := &CommittedVersions{committedVersions: versionMap, revisionNumbers: revMap}
return &VersionedDB{couchInstance, metadataDB, chainName, namespaceDBMap, committedDataCache, sync.RWMutex{}}, nil
}
// getNamespaceDBHandle gets the handle to a named chaincode database
func (vdb *VersionedDB) getNamespaceDBHandle(namespace string) (*couchdb.CouchDatabase, error) {
vdb.mux.RLock()
db := vdb.namespaceDBs[namespace]
vdb.mux.RUnlock()
if db != nil {
return db, nil
}
namespaceDBName := couchdb.ConstructNamespaceDBName(vdb.chainName, namespace)
vdb.mux.Lock()
defer vdb.mux.Unlock()
db = vdb.namespaceDBs[namespace]
if db == nil {
var err error
db, err = couchdb.CreateCouchDatabase(*vdb.couchInstance, namespaceDBName)
if err != nil {
return nil, err
}
vdb.namespaceDBs[namespace] = db
}
return db, nil
}
// Open implements method in VersionedDB interface
func (vdb *VersionedDB) Open() error {
// no need to open db since a shared couch instance is used
return nil
}
// Close implements method in VersionedDB interface
func (vdb *VersionedDB) Close() {
// no need to close db since a shared couch instance is used
}
// ValidateKeyValue implements method in VersionedDB interface
func (vdb *VersionedDB) ValidateKeyValue(key string, value []byte) error {
if !utf8.ValidString(key) {
return fmt.Errorf("Key should be a valid utf8 string: [%x]", key)
}
var jsonMap map[string]interface{}
err := json.Unmarshal([]byte(value), &jsonMap)
if err == nil {
// the value is a proper json and hence perform a check that this json does not contain reserved field
// if error is not nil then the value will be treated as a binary attachement.
return checkReservedFieldsNotUsed(jsonMap)
}
return nil
}
// BytesKeySuppoted implements method in VersionedDB interface
func (vdb *VersionedDB) BytesKeySuppoted() bool {
return false
}
// GetState implements method in VersionedDB interface
func (vdb *VersionedDB) GetState(namespace string, key string) (*statedb.VersionedValue, error) {
logger.Debugf("GetState(). ns=%s, key=%s", namespace, key)
db, err := vdb.getNamespaceDBHandle(namespace)
if err != nil {
return nil, err
}
couchDoc, _, err := db.ReadDoc(key)
if err != nil {
return nil, err
}
if couchDoc == nil {
return nil, nil
}
// remove the reserved fields from the CouchDB JSON and return the value and version
returnValue, returnVersion, err := getValueAndVersionFromDoc(couchDoc.JSONValue, couchDoc.Attachments)
if err != nil {
return nil, err
}
return &statedb.VersionedValue{Value: returnValue, Version: returnVersion}, nil
}
//GetCachedVersion implements method in VersionedDB interface
func (vdb *VersionedDB) GetCachedVersion(namespace string, key string) (*version.Height, bool) {
logger.Debugf("Retrieving cached version: %s~%s", key, namespace)
compositeKey := statedb.CompositeKey{Namespace: namespace, Key: key}
// Retrieve the version from committed data cache.
// Since the cache was populated based on block readsets,
// checks during validation should find the version here
vdb.committedDataCache.mux.RLock()
version, keyFound := vdb.committedDataCache.committedVersions[compositeKey]
vdb.committedDataCache.mux.RUnlock()
if !keyFound {
return nil, false
}
return version, true
}
// GetVersion implements method in VersionedDB interface
func (vdb *VersionedDB) GetVersion(namespace string, key string) (*version.Height, error) {
returnVersion, keyFound := vdb.GetCachedVersion(namespace, key)
// If the version was not found in the committed data cache, retrieve it from statedb.
if !keyFound {
db, err := vdb.getNamespaceDBHandle(namespace)
if err != nil {
return nil, err
}
couchDoc, _, err := db.ReadDoc(key)
if err != nil {
return nil, err
}
if couchDoc == nil {
return nil, nil
}
docMetadata := &couchdb.DocMetadata{}
err = json.Unmarshal(couchDoc.JSONValue, &docMetadata)
if err != nil {
logger.Errorf("Failed to unmarshal couchdb doc header %s\n", err.Error())
return nil, err
}
if docMetadata.Version == "" {
return nil, nil
}
returnVersion = createVersionHeightFromVersionString(docMetadata.Version)
}
return returnVersion, nil
}
// remove the reserved fields from CouchDB JSON and return the value and version
func getValueAndVersionFromDoc(persistedValue []byte, attachments []*couchdb.AttachmentInfo) ([]byte, *version.Height, error) {
// initialize the return value
returnValue := []byte{}
// create a generic map for the json
jsonResult := make(map[string]interface{})
// unmarshal the selected json into the generic map
decoder := json.NewDecoder(bytes.NewBuffer(persistedValue))
decoder.UseNumber()
err := decoder.Decode(&jsonResult)
if err != nil {
return nil, nil, err
}
// verify the version field exists
if _, fieldFound := jsonResult[versionField]; !fieldFound {
return nil, nil, fmt.Errorf("The version field %s was not found", versionField)
}
// create the return version from the version field in the JSON
returnVersion := createVersionHeightFromVersionString(jsonResult[versionField].(string))
// remove the _id, _rev and version fields
delete(jsonResult, idField)
delete(jsonResult, revField)
delete(jsonResult, versionField)
// handle binary or json data
if attachments != nil { // binary attachment
// get binary data from attachment
for _, attachment := range attachments {
if attachment.Name == binaryWrapper {
returnValue = attachment.AttachmentBytes
}
}
} else {
// marshal the returned JSON data.
returnValue, err = json.Marshal(jsonResult)
if err != nil {
return nil, nil, err
}
}
return returnValue, returnVersion, nil
}
// GetStateMultipleKeys implements method in VersionedDB interface
func (vdb *VersionedDB) GetStateMultipleKeys(namespace string, keys []string) ([]*statedb.VersionedValue, error) {
vals := make([]*statedb.VersionedValue, len(keys))
for i, key := range keys {
val, err := vdb.GetState(namespace, key)
if err != nil {
return nil, err
}
vals[i] = val
}
return vals, nil
}
// GetStateRangeScanIterator implements method in VersionedDB interface
// startKey is inclusive
// endKey is exclusive
func (vdb *VersionedDB) GetStateRangeScanIterator(namespace string, startKey string, endKey string) (statedb.ResultsIterator, error) {
// Get the querylimit from core.yaml
queryLimit := ledgerconfig.GetQueryLimit()
db, err := vdb.getNamespaceDBHandle(namespace)
if err != nil {
return nil, err
}
queryResult, err := db.ReadDocRange(startKey, endKey, queryLimit, querySkip)
if err != nil {
logger.Debugf("Error calling ReadDocRange(): %s\n", err.Error())
return nil, err
}
logger.Debugf("Exiting GetStateRangeScanIterator")
return newKVScanner(namespace, *queryResult), nil
}
// ExecuteQuery implements method in VersionedDB interface
func (vdb *VersionedDB) ExecuteQuery(namespace, query string) (statedb.ResultsIterator, error) {
// Get the querylimit from core.yaml
queryLimit := ledgerconfig.GetQueryLimit()
// Explicit paging not yet supported.
// Use queryLimit from config and 0 skip.
queryString, err := applyAdditionalQueryOptions(query, queryLimit, 0)
if err != nil {
logger.Debugf("Error calling applyAdditionalQueryOptions(): %s\n", err.Error())
return nil, err
}
db, err := vdb.getNamespaceDBHandle(namespace)
if err != nil {
return nil, err
}
queryResult, err := db.QueryDocuments(queryString)
if err != nil {
logger.Debugf("Error calling QueryDocuments(): %s\n", err.Error())
return nil, err
}
logger.Debugf("Exiting ExecuteQuery")
return newQueryScanner(namespace, *queryResult), nil
}
// applyAdditionalQueryOptions will add additional fields to the query required for query processing
func applyAdditionalQueryOptions(queryString string, queryLimit, querySkip int) (string, error) {
const jsonQueryFields = "fields"
const jsonQueryLimit = "limit"
const jsonQuerySkip = "skip"
//create a generic map for the query json
jsonQueryMap := make(map[string]interface{})
//unmarshal the selector json into the generic map
decoder := json.NewDecoder(bytes.NewBuffer([]byte(queryString)))
decoder.UseNumber()
err := decoder.Decode(&jsonQueryMap)
if err != nil {
return "", err
}
if fieldsJSONArray, ok := jsonQueryMap[jsonQueryFields]; ok {
switch fieldsJSONArray.(type) {
case []interface{}:
//Add the "_id", and "version" fields, these are needed by default
jsonQueryMap[jsonQueryFields] = append(fieldsJSONArray.([]interface{}),
idField, versionField)
default:
return "", fmt.Errorf("Fields definition must be an array.")
}
}
// Add limit
// This will override any limit passed in the query.
// Explicit paging not yet supported.
jsonQueryMap[jsonQueryLimit] = queryLimit
// Add skip of 0.
// This will override any skip passed in the query.
// Explicit paging not yet supported.
jsonQueryMap[jsonQuerySkip] = querySkip
//Marshal the updated json query
editedQuery, err := json.Marshal(jsonQueryMap)
if err != nil {
return "", err
}
logger.Debugf("Rewritten query: %s", editedQuery)
return string(editedQuery), nil
}
// ApplyUpdates implements method in VersionedDB interface
func (vdb *VersionedDB) ApplyUpdates(batch *statedb.UpdateBatch, height *version.Height) error {
// STEP 1: GATHER DOCUMENT REVISION NUMBERS REQUIRED FOR THE COUCHDB BULK UPDATE
// ALSO BUILD PROCESS BATCHES OF UPDATE DOCUMENTS PER NAMESPACE BASED ON
// THE MAX BATCH SIZE
namespaces := batch.GetUpdatedNamespaces()
// Create goroutine wait group.
var processBatchGroup sync.WaitGroup
processBatchGroup.Add(len(namespaces))
// Collect error from each goroutine using buffered channel.
errResponses := make(chan error, len(namespaces))
for _, ns := range namespaces {
// each namespace batch is processed and committed parallely.
go func(ns string) {
defer processBatchGroup.Done()
// initialize a missing key list
var missingKeys []*statedb.CompositeKey
//initialize a processBatch for updating bulk documents
processBatch := statedb.NewUpdateBatch()
//get the max size of the batch from core.yaml
maxBatchSize := ledgerconfig.GetMaxBatchUpdateSize()
//initialize a counter to track the batch size
batchSizeCounter := 0
nsUpdates := batch.GetUpdates(ns)
for k, vv := range nsUpdates {
//increment the batch size counter
batchSizeCounter++
compositeKey := statedb.CompositeKey{Namespace: ns, Key: k}
// Revision numbers are needed for couchdb updates.
// vdb.committedDataCache.revisionNumbers is a cache of revision numbers based on ID
// Document IDs and revision numbers will already be in the cache for read/writes,
// but will be missing in the case of blind writes.
// If the key is missing in the cache, then add the key to missingKeys
vdb.committedDataCache.mux.RLock()
_, keyFound := vdb.committedDataCache.revisionNumbers[compositeKey]
vdb.committedDataCache.mux.RUnlock()
if !keyFound {
// Add the key to the missing key list
// As there can be no duplicates in UpdateBatch, no need check for duplicates.
missingKeys = append(missingKeys, &compositeKey)
}
//add the record to the process batch
if vv.Value == nil {
processBatch.Delete(ns, k, vv.Version)
} else {
processBatch.Put(ns, k, vv.Value, vv.Version)
}
//Check to see if the process batch exceeds the max batch size
if batchSizeCounter >= maxBatchSize {
//STEP 2: PROCESS EACH BATCH OF UPDATE DOCUMENTS
err := vdb.processUpdateBatch(processBatch, missingKeys)
if err != nil {
errResponses <- err
return
}
//reset the batch size counter
batchSizeCounter = 0
//create a new process batch
processBatch = statedb.NewUpdateBatch()
// reset the missing key list
missingKeys = []*statedb.CompositeKey{}
}
}
//STEP 3: PROCESS ANY REMAINING DOCUMENTS
err := vdb.processUpdateBatch(processBatch, missingKeys)
if err != nil {
errResponses <- err
return
}
}(ns)
}
// Wait for all goroutines to complete
processBatchGroup.Wait()
// Check if any goroutine resulted in error.
// We can stop all goroutine as soon as any goutine resulted in error rather than
// waiting for all goroutines to complete. As errors are very rare, current sub-optimal
// approach (allowing each subroutine to complete) is adequate for now.
// TODO: Currently, we are returing only one error. We need to create a new error type
// that can encapsulate all the errors and return that type
if len(errResponses) > 0 {
return <-errResponses
}
// Record a savepoint at a given height
err := vdb.recordSavepoint(height, namespaces)
if err != nil {
logger.Errorf("Error during recordSavepoint: %s\n", err.Error())
return err
}
return nil
}
//ProcessUpdateBatch updates a batch
func (vdb *VersionedDB) processUpdateBatch(updateBatch *statedb.UpdateBatch, missingKeys []*statedb.CompositeKey) error {
// An array of missing keys is passed in to the batch processing
// A bulk read will then add the missing revisions to the cache
if len(missingKeys) > 0 {
if logger.IsEnabledFor(logging.DEBUG) {
logger.Debugf("Retrieving keys with unknown revision numbers, keys= %s", printCompositeKeys(missingKeys))
}
err := vdb.LoadCommittedVersions(missingKeys)
if err != nil {
return err
}
}
// STEP 1: CREATE COUCHDB DOCS FROM UPDATE SET THEN DO A BULK UPDATE IN COUCHDB
// Use the batchUpdateMap for tracking couchdb updates by ID
// this will be used in case there are retries required
batchUpdateMap := make(map[string]*BatchableDocument)
//TODO: processUpdateBatch is called with updateBatch of a single namespace/chaincode at a time.
// Hence, retrieving namespaces from updateBatch and looping over it is not required. Need to remove
// only the outer for loop.
namespaces := updateBatch.GetUpdatedNamespaces()
for _, ns := range namespaces {
nsUpdates := updateBatch.GetUpdates(ns)
for key, vv := range nsUpdates {
// Create a document structure
couchDoc := &couchdb.CouchDoc{}
var err error
// retrieve the couchdb revision from the cache
// Documents that do not exist in couchdb will not have revision numbers and will
// exist in the cache with a revision value of nil
vdb.committedDataCache.mux.RLock()
revision := vdb.committedDataCache.revisionNumbers[statedb.CompositeKey{Namespace: ns, Key: key}]
vdb.committedDataCache.mux.RUnlock()
var isDelete bool // initialized to false
if vv.Value == nil {
isDelete = true
}
logger.Debugf("Channel [%s]: namespace=[%s] key=[%#v], prior revision=[%s], isDelete=[%t]",
vdb.chainName, ns, key, revision, isDelete)
if isDelete {
// this is a deleted record. Set the _deleted property to true
couchDoc.JSONValue, err = createCouchdbDocJSON(key, revision, nil, vv.Version, true)
if err != nil {
return err
}
} else {
if couchdb.IsJSON(string(vv.Value)) {
// Handle as json
couchDoc.JSONValue, err = createCouchdbDocJSON(key, revision, vv.Value, vv.Version, false)
if err != nil {
return err
}
} else { // if value is not json, handle as a couchdb attachment
attachment := &couchdb.AttachmentInfo{}
attachment.AttachmentBytes = vv.Value
attachment.ContentType = "application/octet-stream"
attachment.Name = binaryWrapper
attachments := append([]*couchdb.AttachmentInfo{}, attachment)
couchDoc.Attachments = attachments
couchDoc.JSONValue, err = createCouchdbDocJSON(key, revision, nil, vv.Version, false)
if err != nil {
return err
}
}
}
// Add the current docment, revision and delete flag to the update map
batchUpdateMap[key] = &BatchableDocument{CouchDoc: *couchDoc, Deleted: isDelete}
}
if len(batchUpdateMap) > 0 {
//Add the documents to the batch update array
batchUpdateDocs := []*couchdb.CouchDoc{}
for _, updateDocument := range batchUpdateMap {
batchUpdateDocument := updateDocument
batchUpdateDocs = append(batchUpdateDocs, &batchUpdateDocument.CouchDoc)
}
// Do the bulk update into couchdb
// Note that this will do retries if the entire bulk update fails or times out
db, err := vdb.getNamespaceDBHandle(ns)
if err != nil {
return err
}
batchUpdateResp, err := db.BatchUpdateDocuments(batchUpdateDocs)
if err != nil {
return err
}
// STEP 2: IF INDIVIDUAL DOCUMENTS IN THE BULK UPDATE DID NOT SUCCEED, TRY THEM INDIVIDUALLY
// iterate through the response from CouchDB by document
for _, respDoc := range batchUpdateResp {
// If the document returned an error, retry the individual document
if respDoc.Ok != true {
batchUpdateDocument := batchUpdateMap[respDoc.ID]
var err error
//Remove the "_rev" from the JSON before saving
//this will allow the CouchDB retry logic to retry revisions without encountering
//a mismatch between the "If-Match" and the "_rev" tag in the JSON
if batchUpdateDocument.CouchDoc.JSONValue != nil {
err = removeJSONRevision(&batchUpdateDocument.CouchDoc.JSONValue)
if err != nil {
return err
}
}
// Check to see if the document was added to the batch as a delete type document
if batchUpdateDocument.Deleted {
//Log the warning message that a retry is being attempted for batch delete issue
logger.Warningf("CouchDB batch document delete encountered an problem. Retrying delete for document ID:%s", respDoc.ID)
// If this is a deleted document, then retry the delete
// If the delete fails due to a document not being found (404 error),
// the document has already been deleted and the DeleteDoc will not return an error
err = db.DeleteDoc(respDoc.ID, "")
} else {
//Log the warning message that a retry is being attempted for batch update issue
logger.Warningf("CouchDB batch document update encountered an problem. Retrying update for document ID:%s", respDoc.ID)
// Save the individual document to couchdb
// Note that this will do retries as needed
_, err = db.SaveDoc(respDoc.ID, "", &batchUpdateDocument.CouchDoc)
}
// If the single document update or delete returns an error, then throw the error
if err != nil {
errorString := fmt.Sprintf("Error occurred while saving document ID = %v Error: %s Reason: %s\n",
respDoc.ID, respDoc.Error, respDoc.Reason)
logger.Errorf(errorString)
return fmt.Errorf(errorString)
}
}
}
}
}
return nil
}
// printCompositeKeys is a convenience method to print readable log entries for arrays of pointers
// to composite keys
func printCompositeKeys(keys []*statedb.CompositeKey) string {
compositeKeyString := []string{}
for _, key := range keys {
compositeKeyString = append(compositeKeyString, "["+key.Namespace+","+key.Key+"]")
}
return strings.Join(compositeKeyString, ",")
}
// LoadCommittedVersions populates committedVersions and revisionNumbers into cache.
// A bulk retrieve from couchdb is used to populate the cache.
// committedVersions cache will be used for state validation of readsets
// revisionNumbers cache will be used during commit phase for couchdb bulk updates
func (vdb *VersionedDB) LoadCommittedVersions(keys []*statedb.CompositeKey) error {
// initialize version and revision maps
versionMap := vdb.committedDataCache.committedVersions
revMap := vdb.committedDataCache.revisionNumbers
missingKeys := make(map[string][]string) // for each namespace/chaincode, store the missingKeys
vdb.committedDataCache.mux.Lock()
for _, key := range keys {
logger.Debugf("Load into version cache: %s~%s", key.Key, key.Namespace)
// create the compositeKey
compositeKey := statedb.CompositeKey{Namespace: key.Namespace, Key: key.Key}
// initialize an entry for each key. Set the version to nil
_, versionFound := versionMap[compositeKey]
if !versionFound {
versionMap[compositeKey] = nil
}
// initialize empty values for each key (revision numbers will not be in couchdb for new creates)
_, revFound := revMap[compositeKey]
if !revFound {
revMap[compositeKey] = ""
}
// if the compositeKey was not found in the revision or version part of the cache, then add the key to the
// list of keys to be retrieved
if !revFound || !versionFound {
// add the missing key to the list of required keys
missingKeys[key.Namespace] = append(missingKeys[key.Namespace], key.Key)
}
}
vdb.committedDataCache.mux.Unlock()
//get the max size of the batch from core.yaml
maxBatchSize := ledgerconfig.GetMaxBatchUpdateSize()
// Call the batch retrieve if there is one or more keys to retrieve
if len(missingKeys) > 0 {
// Create goroutine wait group.
var batchRetrieveGroup sync.WaitGroup
batchRetrieveGroup.Add(len(missingKeys))
// Collect error from each goroutine using buffered channel.
errResponses := make(chan error, len(missingKeys))
// For each namespace, we parallely load missing keys into the cache using goroutines
for namespace := range missingKeys {
go func(namespace string) {
defer batchRetrieveGroup.Done()
// Initialize the array of keys to be retrieved
keysToRetrieve := []string{}
// Iterate through the missingKeys and build a batch of keys for batch retrieval
for _, key := range missingKeys[namespace] {
keysToRetrieve = append(keysToRetrieve, key)
// check to see if the number of keys is greater than the max batch size
if len(keysToRetrieve) >= maxBatchSize {
err := vdb.batchRetrieveMetaData(namespace, keysToRetrieve)
if err != nil {
errResponses <- err
return
}
// reset the array
keysToRetrieve = []string{}
}
}
// If there are any remaining, retrieve the final batch
if len(keysToRetrieve) > 0 {
err := vdb.batchRetrieveMetaData(namespace, keysToRetrieve)
if err != nil {
errResponses <- err
return
}
}
}(namespace)
}
// Wait for all goroutines to complete
batchRetrieveGroup.Wait()
// Check if any goroutine resulted in error.
// We can stop all goroutine as soon as any goutine resulted in error rather than
// waiting for all goroutines to complete. As errors are very rare, current sub-optimal
// approach (allowing each subroutine to complete) is adequate for now.
// TODO: Currently, we are returing only one error. We need to create a new error type
// that can encapsulate all the errors and return that type.
if len(errResponses) > 0 {
return <-errResponses
}
}
return nil
}
// batchRetrieveMetaData retrieves a batch of keys and loads metadata into cache
func (vdb *VersionedDB) batchRetrieveMetaData(namespace string, keys []string) error {
versionMap := vdb.committedDataCache.committedVersions
revMap := vdb.committedDataCache.revisionNumbers
db, err := vdb.getNamespaceDBHandle(namespace)
if err != nil {
return err
}
documentMetadataArray, err := db.BatchRetrieveDocumentMetadata(keys)
if err != nil {
logger.Errorf("Batch retrieval of document metadata failed %s\n", err.Error())
return err
}
for _, documentMetadata := range documentMetadataArray {
if len(documentMetadata.Version) != 0 {
compositeKey := statedb.CompositeKey{Namespace: namespace, Key: documentMetadata.ID}
vdb.committedDataCache.mux.Lock()
versionMap[compositeKey] = createVersionHeightFromVersionString(documentMetadata.Version)
revMap[compositeKey] = documentMetadata.Rev
vdb.committedDataCache.mux.Unlock()
}
}
return nil
}
func createVersionHeightFromVersionString(encodedVersion string) *version.Height {
versionArray := strings.Split(fmt.Sprintf("%s", encodedVersion), ":")
// convert the blockNum from String to unsigned int
blockNum, _ := strconv.ParseUint(versionArray[0], 10, 64)
// convert the txNum from String to unsigned int
txNum, _ := strconv.ParseUint(versionArray[1], 10, 64)
return version.NewHeight(blockNum, txNum)
}
// ClearCachedVersions clears committedVersions and revisionNumbers
func (vdb *VersionedDB) ClearCachedVersions() {
logger.Debugf("Clear Cache")
versionMap := make(map[statedb.CompositeKey]*version.Height)
revMap := make(map[statedb.CompositeKey]string)
vdb.committedDataCache = &CommittedVersions{committedVersions: versionMap, revisionNumbers: revMap}
}
// createCouchdbDocJSON adds keys to the CouchDoc.JSON value for the following items:
// _id - couchdb document ID, need for all couchdb batch operations
// _rev - couchdb document revision, needed for updating or deleting existing documents
// _deleted - flag used in batch operations for deleting a couchdb document
// version - used for state validation
// The return value is the CouchDoc.JSONValue with the header fields populated
func createCouchdbDocJSON(id, revision string, value []byte, version *version.Height, deleted bool) ([]byte, error) {
// create a new genericMap
jsonMap := map[string]interface{}{}
// if a JSON is provided, then unmarshal the JSON into the return mapping
if value != nil {
// Unmarshal the value into the return map
err := json.Unmarshal(value, &jsonMap)
if err != nil {
return nil, err
}
}
if err := checkReservedFieldsNotUsed(jsonMap); err != nil {
return nil, err
}
// add the version
jsonMap[versionField] = fmt.Sprintf("%v:%v", version.BlockNum, version.TxNum)
// add the ID
jsonMap[idField] = id
// add the revision
if revision != "" {
// add the revision
jsonMap[revField] = revision
}
// If this record is to be deleted, set the "_deleted" property to true
if deleted {
// add the deleted field
jsonMap[deletedField] = true
}