-
Notifications
You must be signed in to change notification settings - Fork 0
/
pte-execRequest.js
1643 lines (1491 loc) · 69.6 KB
/
pte-execRequest.js
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 2016 IBM All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* usage:
* node pte-execRequest.js <pid> <Nid> <uiFile> <tStart> <org> <PTEid>
* - pid: process id
* - Nid: Network id
* - uiFile: user input file
* - tStart: tStart
* - org: organization
* - PTEid: PTE id
*/
// This is an end-to-end test that focuses on exercising all parts of the fabric APIs
// in a happy-path scenario
'use strict';
var fs = require('fs');
var hfc = require('fabric-client');
var path = require('path');
var testUtil = require('./pte-util.js');
var util = require('util');
var PTEid = process.argv[7];
var loggerMsg = 'PTE ' + PTEid + ' exec';
var logger = new testUtil.PTELogger({ "prefix": loggerMsg, "level": "info" });
// local vars
var tCurr;
var tEnd = 0;
var tLocal;
var i = 0;
var inv_m = 0; // counter of invoke move
var inv_q = 0; // counter of invoke query
var n_sd = 0; // counter of service discovery
var evtType = 'FILTEREDBLOCK'; // event type: FILTEREDBLOCK|CHANNEL, default: FILTEREDBLOCK
var evtTimeout = 120000; // event timeout, default: 120000 ms
var evtLastRcvdTime = 0; // last event received time
var evtCode_VALID = 0; // event valid code as defined in TxValidationCode in fabric transaction.pb.go (channel block only)
var lastSentTime = 0; // last transaction sent time
var IDone = 0;
var QDone = 0;
var invokeCheckExec = false;
var invokeCheck = new Boolean(0);
var invokeCheckPeers = 'NONE';
var invokeCheckTx = 'NONE';
var invokeCheckTxNum = 0;
var chaincode_id;
var chaincode_ver;
var tx_id = null;
var eventHubs = [];
var targets = [];
var eventPromises = [];
var txidList = [];
var initFreq = 0; // init discovery freq default = 0
var initDiscTimer;
var serviceDiscovery = false;
var localHost = false;
var ARGS_DIR = path.join(__dirname, 'ccArgumentsGenerators');
var requestQueue = [];
var maxRequestQueueLength = 100;
// transactions status counts
var tx_stats = [];
var tx_sent = 0; // tx_stats idx: total transactions sent
var tx_rcvd = tx_sent + 1; // tx_stats idx: total transactions succeeded (event or query results received)
var tx_pFail = tx_rcvd + 1; // tx_stats idx: total proposal (peer) failure
var tx_txFail = tx_pFail + 1; // tx_stats idx: total transaction (orderer ack) failure
var tx_evtTimeout = tx_txFail + 1; // tx_stats idx: total event timeout
var tx_evtInvalid = tx_evtTimeout + 1; // tx_stats idx: total event received but invalid
var tx_evtUnreceived = tx_evtInvalid + 1; // tx_stats idx: total event unreceived
for (var i = 0; i <= tx_evtUnreceived; i++) {
tx_stats[i] = 0;
}
// need to override the default key size 384 to match the member service backend
// otherwise the client will not be able to decrypt the enrollment challenge
hfc.setConfigSetting('crypto-keysize', 256);
// need to override the default hash algorithm (SHA3) to SHA2 (aka SHA256 when combined
// with the key size 256 above), in order to match what the peer and COP use
hfc.setConfigSetting('crypto-hash-algo', 'SHA2');
//input args
var pid = parseInt(process.argv[2]);
var Nid = parseInt(process.argv[3]);
var uiFile = process.argv[4];
var tStart = parseInt(process.argv[5]);
var org = process.argv[6];
var uiContent;
var txCfgPtr;
var txCfgTmp;
if (fs.existsSync(uiFile)) {
uiContent = testUtil.readConfigFileSubmitter(uiFile);
if (typeof (uiContent.txCfgPtr) === 'undefined') {
txCfgTmp = uiFile;
} else {
txCfgTmp = uiContent.txCfgPtr;
}
txCfgPtr = testUtil.readConfigFileSubmitter(txCfgTmp);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input txCfgPtr[%s]: %j', Nid, channelName, org, pid, txCfgTmp, txCfgPtr);
} else {
uiContent = JSON.parse(uiFile)
txCfgPtr = uiContent
}
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input uiContent[%s]: %j', Nid, channelName, org, pid, uiFile, uiContent);
var channelOpt = uiContent.channelOpt;
var channelOrgName = [];
var channelName = channelOpt.name;
for (i = 0; i < channelOpt.orgName.length; i++) {
channelOrgName.push(channelOpt.orgName[i]);
}
var distOpt;
var ccDfnPtr;
var ccDfntmp;
if (typeof (uiContent.ccDfnPtr) === 'undefined') {
ccDfntmp = uiFile;
} else {
ccDfntmp = uiContent.ccDfnPtr;
}
ccDfnPtr = uiContent;
if (fs.existsSync(uiFile)) {
ccDfnPtr = testUtil.readConfigFileSubmitter(ccDfntmp);
}
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input ccDfnPtr[%s]: %j', Nid, channelName, org, pid, ccDfntmp, ccDfnPtr);
var ccType = ccDfnPtr.ccType;
if (!fs.existsSync(ARGS_DIR + '/' + ccType + '/ccFunctions.js')) {
logger.error('No chaincode payload generation files found: ', ARGS_DIR + '/' + ccType + '/ccFunctions.js');
process.exit(1);
}
var ccFunctions = require(ARGS_DIR + '/' + ccType + '/ccFunctions.js');
var TLS = testUtil.setTLS(txCfgPtr);
var targetPeers = txCfgPtr.targetPeers.toUpperCase();
if (targetPeers == 'DISCOVERY' && TLS != testUtil.TLSCLIENTAUTH) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] invalid configuration: targetPeers (%s) requires TLS (clientauth)', Nid, channelName, org, pid, txCfgPtr.targetPeers);
process.exit(1);
}
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input parameters: uiFile=%s, tStart=%d', Nid, channelName, org, pid, uiFile, tStart);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] TLS: %s', Nid, channelName, org, pid, TLS);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] targetPeers: %s', Nid, channelName, org, pid, targetPeers.toUpperCase());
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] channelOrgName.length: %d, channelOrgName: %s', Nid, channelName, org, pid, channelOrgName.length, channelOrgName);
var client = new hfc();
var channel = client.newChannel(channelName);
if ((typeof (txCfgPtr.eventOpt) !== 'undefined') && (typeof (txCfgPtr.eventOpt.type) !== 'undefined')) {
evtType = txCfgPtr.eventOpt.type.toUpperCase();
if ((evtType != 'FILTEREDBLOCK') && (evtType != 'CHANNEL')) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] unsupported event type: %s', Nid, channelName, org, pid, evtType);
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] supported event types: FilteredBlock and Channel', Nid, channelName, org, pid);
process.exit(1);
}
}
if ((typeof (txCfgPtr.eventOpt) !== 'undefined') && (typeof (txCfgPtr.eventOpt.timeout) !== 'undefined')) {
evtTimeout = txCfgPtr.eventOpt.timeout;
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] event type: %s, timeout: %d', Nid, channel.getName(), org, pid, evtType, evtTimeout);
if (typeof (txCfgPtr.invokeCheck) !== 'undefined') {
if (txCfgPtr.invokeCheck == 'TRUE') {
invokeCheck = true;
} else if (txCfgPtr.invokeCheck == 'FALSE') {
invokeCheck = false;
} else {
invokeCheck = txCfgPtr.invokeCheck;
}
if (invokeCheck) {
if (txCfgPtr.invokeCheckOpt) {
if (txCfgPtr.invokeCheckOpt.peers) {
invokeCheckPeers = txCfgPtr.invokeCheckOpt.peers.toUpperCase();
} else {
invokeCheckPeers = txCfgPtr.targetPeers.toUpperCase();
}
if (txCfgPtr.invokeCheckOpt.transactions) {
invokeCheckTx = txCfgPtr.invokeCheckOpt.transactions.toUpperCase();
} else {
invokeCheckTx = 'LAST';
}
if (txCfgPtr.invokeCheckOpt.txNum) {
invokeCheckTxNum = parseInt(txCfgPtr.invokeCheckOpt.txNum);
} else {
invokeCheckTxNum = 1;
}
} else {
invokeCheckPeers = txCfgPtr.targetPeers.toUpperCase();
invokeCheckTx = 'LAST';
invokeCheckTxNum = 1;
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] invokeCheck: peers=%s, tx=%s, num=%d', Nid, channel.getName(), org, pid, invokeCheckPeers, invokeCheckTx, invokeCheckTxNum);
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] invokeCheck: %j', Nid, channel.getName(), org, pid, invokeCheck);
var channelID = uiContent.channelID;
chaincode_id = uiContent.chaincodeID
if (channelID) {
chaincode_id = uiContent.chaincodeID + channelID;
}
var endorsement_hint = {chaincodes: [{name: chaincode_id}]}
chaincode_ver = uiContent.chaincodeVer;
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] chaincode_id: %s', Nid, channel.getName(), org, pid, chaincode_id);
// find all connection profiles
var cpList = [];
var cpPath = uiContent.ConnProfilePath;
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] connection profile path: ', Nid, channel.getName(), org, pid, cpPath);
cpList = testUtil.getConnProfileListSubmitter(cpPath);
if (cpList.length === 0) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] error: invalid connection profile path or no connection profiles found in the connection profile path: %s', Nid, channel.getName(), org, pid, cpPath);
process.exit(1);
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] cpList: ', Nid, channel.getName(), org, pid, cpList);
// find all org from all connection profiles
var orgList = [];
orgList = testUtil.findAllOrgFromConnProfileSubmitter(cpList);
if (orgList.length === 0) {
logger.error('[Nid=%d pte-main] error: no org contained in connection profiles', Nid);
process.exit(1);
}
logger.info('[Nid=%d pte-main] orgList: ', Nid, orgList);
var orderersCPFList = {};
orderersCPFList = testUtil.getNodetypeFromConnProfilesSubmitter(cpList, 'orderers');
// set org connection profile
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (0 === testUtil.getConnProfilePropCntSubmitter(cpf, 'orderers')) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] no orderer found in the connection profile', Nid, channel.getName(), org, pid);
process.exit(1);
}
if (0 === testUtil.getConnProfilePropCntSubmitter(cpf, 'peers')) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] no peer found in the connection profile', Nid, channel.getName(), org, pid);
process.exit(1);
}
var cpOrgs = cpf['organizations'];
var cpPeers = cpf['peers'];
var users = hfc.getConfigSetting('users');
//user parameters
var transMode = txCfgPtr.transMode.toUpperCase();
var transType = txCfgPtr.transType.toUpperCase();
var invokeType = txCfgPtr.invokeType.toUpperCase();
var nRequest = parseInt(txCfgPtr.nRequest);
if (transType == 'DISCOVERY' && TLS != testUtil.TLSCLIENTAUTH) {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] invalid configuration: transType (%s) requires mutual TLS (clientauth)', Nid, channelName, org, pid, transType);
process.exit(1);
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] transMode: %s, transType: %s, invokeType: %s, nRequest: %d', Nid, channel.getName(), org, pid, transMode, transType, invokeType, nRequest);
// orderer parameters
var ordererMethod = 'USERDEFINED'; // default method
if (typeof (txCfgPtr.ordererOpt) !== 'undefined') {
if (typeof (txCfgPtr.ordererOpt.method) !== 'undefined') {
ordererMethod = txCfgPtr.ordererOpt.method.toUpperCase();
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input parameters: ordererMethod=%s', Nid, channelName, org, pid, ordererMethod);
//failover parameters
var peerList = [];
var currPeerId = 0;
var ordererList = [];
var currOrdererId = 0;
var peerFO = false;
var ordererFO = false;
var peerFOList = 'TARGETPEERS';
var peerFOMethod = 'ROUNDROBIN';
// failover is handled by SDK in discovery mode
if (targetPeers != 'DISCOVERY') {
if (typeof (txCfgPtr.peerFailover) !== 'undefined') {
if (txCfgPtr.peerFailover == 'TRUE') {
peerFO = true;
} else if (txCfgPtr.peerFailover == 'FALSE') {
peerFO = false;
} else {
peerFO = txCfgPtr.peerFailover;
}
}
if (typeof (txCfgPtr.ordererFailover) !== 'undefined') {
if (txCfgPtr.ordererFailover == 'TRUE') {
ordererFO = true;
} else if (txCfgPtr.ordererFailover == 'FALSE') {
ordererFO = false;
} else {
ordererFO = txCfgPtr.ordererFailover;
}
}
}
if (peerFO) {
if (typeof (txCfgPtr.failoverOpt) !== 'undefined') {
if (typeof (txCfgPtr.failoverOpt.list) !== 'undefined') {
peerFOList = txCfgPtr.failoverOpt.list.toUpperCase();
}
if (typeof (txCfgPtr.failoverOpt.method) !== 'undefined') {
peerFOMethod = txCfgPtr.failoverOpt.method.toUpperCase();
}
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] input parameters: peerFO=%s, ordererFO=%s, peerFOList=%s, peerFOMethod=%s', Nid, channelName, org, pid, peerFO, ordererFO, peerFOList, peerFOMethod);
var runDur = 0;
if (nRequest == 0) {
runDur = parseInt(txCfgPtr.runDur);
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] transMode: %s, transType: %s, invokeType: %s, runDur: %d', Nid, channel.getName(), org, pid, transMode, transType, invokeType, runDur);
// convert runDur from second to ms
runDur = 1000 * runDur;
}
var runForever = 0;
if ((nRequest == 0) && (runDur == 0)) {
runForever = 1;
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] runForever: %d', Nid, channel.getName(), org, pid, runForever);
// timeout option
var timeoutOpt;
var reqTimeout = 45000; // default 45 sec
var grpcTimeout = 3000; // default 3 sec
if ((typeof (txCfgPtr.timeoutOpt) !== 'undefined')) {
timeoutOpt = txCfgPtr.timeoutOpt;
logger.info('main - timeoutOpt: %j', timeoutOpt);
if ((typeof (timeoutOpt.request) !== 'undefined')) {
reqTimeout = parseInt(timeoutOpt.request);
}
if ((typeof (timeoutOpt.grpcTimeout) !== 'undefined')) {
grpcTimeout = parseInt(timeoutOpt.grpcTimeout);
hfc.setConfigSetting('grpc-wait-for-ready-timeout', grpcTimeout);
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] reqTimeout: %d, grpcTimeout: %d', Nid, channel.getName(), org, pid, reqTimeout, grpcTimeout);
// init latencies matrix: tx num/avg/min/max
var latency_peer = [0, 0, 99999999, 0];
var latency_orderer = [0, 0, 99999999, 0];
var latency_event = [0, 0, 99999999, 0];
// Create instance of the chaincode function argument generation class
var ccFuncInst = new ccFunctions(ccDfnPtr, logger, Nid, channel.getName(), org, pid);
//set transaction ID: channelName+'_'+org+'_'+Nid+'_'+pid
var txIDVar = channelName + '_' + org + '_' + Nid + '_' + pid;
var bookmark = '';
logger.info('[Nid:chan:org:id=%d:%s:%s:%d pte-execRequest] tx IDVar: ', Nid, channel.getName(), org, pid, txIDVar);
var ccFunctionAccessPolicy = {};
if (ccFuncInst.getAccessControlPolicyMap) { // Load access control policy for chaincode is specified
ccFunctionAccessPolicy = ccFuncInst.getAccessControlPolicyMap();
}
var orgAdmins = {}; // Map org names to client handles
/*
* transactions begin ....
*/
execTransMode();
//construct invoke request
var request_invoke;
function getMoveRequest() {
// Get the invoke arguments from the appropriate payload generation files
ccFuncInst.getInvokeArgs(txIDVar);
// Set the approprate signing identity for this function based on access policy
// If the function has no access control, we can use any signing identity
var orgsForAccess = ccFunctionAccessPolicy[ccDfnPtr.invoke.move.fcn];
if (orgsForAccess && Array.isArray(orgsForAccess) && orgsForAccess.length > 0 && orgAdmins[orgsForAccess[0]]) {
client.setUserContext(orgAdmins[orgsForAccess[0]], false); // Just pick the first organization that satisfies the policy
}
tx_id = client.newTransactionID();
hfc.setConfigSetting('E2E_TX_ID', tx_id.getTransactionID());
//logger.info('[Nid:chan:org:id=%d:%s:%s:%d getMoveRequest] tx id= %s', Nid, channelName, org, pid, tx_id.getTransactionID().toString());
request_invoke = {
chaincodeId: chaincode_id,
endorsement_hint: endorsement_hint,
fcn: ccDfnPtr.invoke.move.fcn,
args: ccFuncInst.testInvokeArgs,
transientMap: ccFuncInst.testInvokeTransientMapEncoded,
txId: tx_id
};
if ((inv_m == nRequest) && (nRequest > 0)) {
if (invokeCheck) {
logger.info('[Nid:chan:org:id=%d:%s:%s:%d getMoveRequest] request_invoke: %j', Nid, channel.getName(), org, pid, request_invoke);
}
}
var ri = Object.assign({}, request_invoke);
return ri;
}
//construct query request
var request_query;
function getQueryRequest() {
// Get the query arguments from the appropriate payload generation files
ccFuncInst.getQueryArgs(txIDVar, bookmark);
// Set the approprate signing identity for this function based on access policy
// If the function has no access control, we can use any signing identity
var orgsForAccess = ccFunctionAccessPolicy[ccDfnPtr.invoke.query.fcn];
if (orgsForAccess && Array.isArray(orgsForAccess) && orgsForAccess.length > 0 && orgAdmins[orgsForAccess[0]]) {
client.setUserContext(orgAdmins[orgsForAccess[0]], false); // Just pick the first organization that satisfies the policy
}
tx_id = client.newTransactionID();
request_query = {
chaincodeId: chaincode_id,
endorsement_hint: endorsement_hint,
txId: tx_id,
fcn: ccDfnPtr.invoke.query.fcn,
args: ccFuncInst.testQueryArgs
};
//logger.info('request_query: %j', request_query);
}
function listenToEventHub() {
// add event if Block listener
if (evtType == 'FILTEREDBLOCK') {
// filteredBlock event
eventRegisterFilteredBlock();
} else {
// channel event
eventRegisterBlock();
}
}
var reConnectEvtHub = 0;
function peerFailover(channel, client) {
// return if no peer failover or using discovery to send transactions
// SDK handles failover when using discovery
if ((!peerFO) || (targetPeers === 'DISCOVERY')) {
return;
}
var currId = currPeerId;
var eh;
channel.removePeer(peerList[currPeerId]);
if (peerFOMethod == 'RANDOM') {
var r = Math.floor(Math.random() * (peerList.length - 1));
if (r >= currPeerId) {
currPeerId = r + 1;
} else {
currPeerId = r;
}
} else if (peerFOMethod == 'ROUNDROBIN') {
currPeerId = currPeerId + 1;
}
currPeerId = currPeerId % peerList.length;
channel.addPeer(peerList[currPeerId]);
//handle channel eventHubs if evtType == CHANNEL
if (invokeType == 'MOVE') {
//delete channel eventHubs
for (var i = 0; i < eventHubs.length; i++) {
var str = peerList[currId]._url.split('//');
if ((eventHubs[i].getPeerAddr()) && (str[1] == eventHubs[i].getPeerAddr())) {
eventHubs[i].disconnect()
delete eventHubs[i];
}
}
//add channel eventHubs
var str = peerList[currPeerId]._url.split('//');
var found = 0;
for (var i = 0; i < eventHubs.length; i++) {
if ((eventHubs[i].getPeerAddr()) && (str[1] == eventHubs[i].getPeerAddr())) {
found = 1;
break;
}
}
if (found == 0) {
eh = channel.newChannelEventHub(peerList[currPeerId]);
eventHubs.push(eh);
if (evtType == 'FILTEREDBLOCK') {
eh.connect();
} else {
eh.connect(true);
}
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d peerFailover] from (%s) to (%s)', Nid, channel.getName(), org, pid, peerList[currId]._url, peerList[currPeerId]._url);
}
// set currPeerId
function setCurrPeerId(channel, client, org) {
var peerUrl = channel.getPeers()[0]._url;
var i;
for (i = 0; i < peerList.length; i++) {
if (peerList[i]._url === peerUrl) {
currPeerId = i;
}
}
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d setCurrPeerId] currPeerId: ', Nid, channelName, org, pid, currPeerId);
}
function removeAllPeers() {
var peers = channel.getPeers();
for (var i = 0; i < peers.length; i++) {
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d setCurrPeerId] removeAllPeers: %s', Nid, channelName, org, pid, peers[i]);
channel.removePeer(peers[i]);
}
}
// assign peer list from all org for peer failover
function assignPeerList(channel, client, org) {
logger.info('[Nid:chan:id=%d:%s:%d assignPeerList]', Nid, channel.getName(), pid);
var peerTmp;
var eh;
var data;
for (let orgtmp in cpOrgs) {
for (let i = 0; i < cpOrgs[orgtmp]['peers'].length; i++) {
var key = cpOrgs[orgtmp]['peers'][i];
if (cpPeers.hasOwnProperty(key)) {
if (cpPeers[key].url) {
if (TLS > testUtil.TLSDISABLED) {
data = testUtil.getTLSCert(orgtmp, key, cpf, cpPath);
if (data !== null) {
peerTmp = client.newPeer(
cpPeers[key].url,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': cpPeers[key]['grpcOptions']['ssl-target-name-override']
}
);
peerList.push(peerTmp);
}
} else {
peerTmp = client.newPeer(cpPeers[key].url);
peerList.push(peerTmp);
}
}
}
}
}
logger.info('[Nid:chan:id=%d:%s:%d assignPeerList] peerList', Nid, channel.getName(), pid, peerList);
}
function channelDiscoveryEvent(channel, client, org) {
logger.info('[Nid:chan:org:id=%d:%s:%s:%d channelDiscoveryEvent]', Nid, channelName, org, pid);
var peerTmp = channel.getPeers();
if (invokeType == 'MOVE') {
for (var u = 0; u < peerTmp.length; u++) {
var eh = channel.newChannelEventHub(peerTmp[u]);
eventHubs.push(eh);
if (evtType == 'FILTEREDBLOCK') {
eh.connect();
} else {
eh.connect(true);
}
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d channelDiscoveryEvent] event length: %d', Nid, channelName, org, pid, eventHubs.length);
}
function clearInitDiscTimeout() {
if (initFreq > 0) {
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d clearInitDiscTimeout] clear discovery timer.', Nid, channelName, org, pid);
clearTimeout(initDiscTimer);
}
}
function initDiscovery() {
var tmpTime = new Date().getTime();
logger.info('[Nid:chan:org:id=%d:%s:%s:%d initDiscovery] discovery timestamp %d, endorsement_hint: %j', Nid, channelName, org, pid, tmpTime, endorsement_hint);
channel.initialize({
discover: serviceDiscovery,
asLocalhost: localHost
})
.then((success) => {
logger.info('[Nid:chan:org:id=%d:%s:%s:%d initDiscovery] discovery results %j', Nid, channelName, org, pid, success);
if (targetPeers === 'DISCOVERY') {
channelDiscoveryEvent(channel, client, org);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d initDiscovery] discovery: completed events ports', Nid, channelName, org, pid);
}
}).catch((err) => {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d initDiscovery] Failed to wait due to error: ', Nid, channelName, org, pid, err.stack ? err.stack : err)
process.exit(1)
});
if (initFreq > 0) {
initDiscTimer = setTimeout(function () {
initDiscovery();
}, initFreq);
}
}
// reconnect orderer
function ordererReconnect(channel, client, org) {
// SDK handles failover when using discovery
if (targetPeers === 'DISCOVERY') {
return;
}
channel.removeOrderer(ordererList[currOrdererId]);
testUtil.assignChannelOrdererSubmitter(channel, client, org, cpPath, TLS)
logger.info('[Nid:chan:org:id=%d:%s:%s:%d ordererReconnect] Orderer reconnect (%s)', Nid, channel.getName(), org, pid, ordererList[currOrdererId]._url);
}
// orderer failover
function ordererFailover(channel, client) {
// return if no orderer failover or using discovery to send transactions
// SDK handles failover when using discovery
if ((!ordererFO) || (targetPeers === 'DISCOVERY')) {
return;
}
var currId = currOrdererId;
channel.removeOrderer(ordererList[currOrdererId]);
currOrdererId = currOrdererId + 1;
currOrdererId = currOrdererId % ordererList.length;
channel.addOrderer(ordererList[currOrdererId]);
logger.info('[Nid:chan:org:id=%d:%s:%s:%d ordererFailover] Orderer failover from (%s) to (%s):', Nid, channel.getName(), org, pid, ordererList[currId]._url, ordererList[currOrdererId]._url);
}
// set currOrdererId
function setCurrOrdererId(channel, client, org) {
// assign ordererID
var ordererID = testUtil.getOrdererID(pid, channelOpt.orgName, org, txCfgPtr, cpf, ordererMethod, cpPath);
logger.info('[Nid:chan:org:id=%d:%s:%s:%d setCurrOrdererId] orderer[%s] is assigned to this thread', Nid, channelName, org, pid, ordererID);
var i;
for (i = 0; i < ordererList.length; i++) {
if (ordererList[i]._url === orderersCPFList[ordererID].url) {
currOrdererId = i;
}
}
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d setCurrOrdererId] currOrdererId:', Nid, channelName, org, pid, currOrdererId);
}
// assign Orderer List for orderer failover
function assignOrdererList(channel, client) {
logger.info('[Nid:chan:org:id=%d:%s:%s:%d assignOrdererList] ', Nid, channelName, org, pid);
var data;
var ordererTmp;
for (let key in orderersCPFList) {
if (orderersCPFList[key].url) {
if (TLS > testUtil.TLSDISABLED) {
data = testUtil.getTLSCert('orderer', key, cpf, cpPath);
if (data !== null) {
let caroots = Buffer.from(data).toString();
ordererTmp = client.newOrderer(
orderersCPFList[key].url,
{
pem: caroots,
'ssl-target-name-override': orderersCPFList[key]['grpcOptions']['ssl-target-name-override']
}
)
ordererList.push(ordererTmp);
}
} else {
ordererTmp = client.newOrderer(orderersCPFList[key].url);
ordererList.push(ordererTmp);
}
}
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d assignOrdererList] orderer list: %s', Nid, channelName, org, pid, ordererList);
}
// add target peers to channel
function setTargetPeers(tPeers) {
var tgtPeers = [];
if (tPeers == 'ORGANCHOR') {
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, channelOrgName, 'ANCHORPEER')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
}
} else if (tPeers == 'ALLANCHORS') {
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, orgList, 'ANCHORPEER')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
}
} else if (tPeers == 'ORGPEERS') {
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, channelOrgName, 'ALLPEERS')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
}
} else if (tPeers == 'ALLPEERS') {
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, orgList, 'ALLPEERS')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
}
} else if (tPeers == 'LIST') {
tgtPeers = txCfgPtr.listOpt;
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
}
} else if (tPeers == 'ROUNDROBIN') {
tgtPeers[org] = [];
tgtPeers[org].push(testUtil.getPeerID(pid, org, txCfgPtr, cpf, tPeers));
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
} else if ((tPeers == 'DISCOVERY') || (transType == 'DISCOVERY')) {
serviceDiscovery = true;
if ((typeof (txCfgPtr.discoveryOpt) !== 'undefined')) {
var discoveryOpt = txCfgPtr.discoveryOpt;
logger.info('[Nid:chan:org:id=%d:%s:%s:%d setTargetPeers] discoveryOpt: %j', Nid, channelName, org, pid, discoveryOpt);
if ((typeof (discoveryOpt.localHost) !== 'undefined')) {
if (discoveryOpt.localHost == 'TRUE') {
localHost = true;
}
}
if (typeof(discoveryOpt.collection) !== 'undefined') {
endorsement_hint['chaincodes'] = [
{name: chaincode_id, collection_names: txCfgPtr.discoveryOpt.collection}
];
}
if ((typeof (discoveryOpt.initFreq) !== 'undefined')) {
initFreq = parseInt(discoveryOpt.initFreq);
}
}
// add one peer to channel to init service discovery
for (var j=0; j<channelOrgName.length; j++) {
var discOrg1 = [];
discOrg1 = channelOrgName.slice(j,j+1);
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, discOrg1, 'ANCHORPEER')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, evtType, invokeType, peerFOList, peerList, eventHubs);
break; // break once one peer is found
}
}
if ((tPeers == 'DISCOVERY') || (transType == 'DISCOVERY')) {
logger.info('[Nid:chan:org:id=%d:%s:%s:%d setTargetPeers] serviceDiscovery=%j, localHost: %j', Nid, channelName, org, pid, serviceDiscovery, localHost);
initDiscovery();
}
} else {
logger.error('[Nid:chan:org:id=%d:%s:%s:%d setTargetPeers] pte-exec:completed:error targetPeers= %s', Nid, channelName, org, pid, tPeers);
process.exit(1);
}
}
function getSubmitterForOrg(username, secret, client, peerOrgAdmin, Nid, org) {
var cpf1 = testUtil.findOrgConnProfileSubmitter(cpList, org);
return testUtil.getSubmitter(username, secret, client, peerOrgAdmin, Nid, org, cpf1);
}
async function execTransMode() {
try {
// init vars
inv_m = 0;
inv_q = 0;
var username = testUtil.getOrgEnrollIdSubmitter(cpf, org);
var secret = testUtil.getOrgEnrollSecretSubmitter(cpf, org);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] user= %s, secret=%s', Nid, channelName, org, pid, username, secret);
//handle client auth
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, org, cpf);
logger.debug('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] got user private key: org=%s', Nid, channelName, org, pid, org);
}
var cryptoSuite = hfc.newCryptoSuite();
var useStore = true;
if (useStore) {
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({ path: testUtil.storePathForOrg(Nid, cpOrgs[org].name) }));
client.setCryptoSuite(cryptoSuite);
}
//enroll user
var promise;
hfc.setConfigSetting('request-timeout', reqTimeout);
if (useStore) {
promise = hfc.newDefaultKeyValueStore({
path: testUtil.storePathForOrg(Nid, cpOrgs[org].name)
});
} else {
promise = Promise.resolve(useStore);
}
return promise.then((store) => {
if (store) {
client.setStateStore(store);
}
client._userContext = null;
var getSubmitterForOrgPromises = [];
channelOrgName.forEach((orgName) => {
getSubmitterForOrgPromises.push(getSubmitterForOrg);
})
return getSubmitterForOrgPromises.reduce(
(promiseChain, currentFunction, currentIndex) =>
promiseChain.then((admin) => {
if (currentIndex > 0) {
orgAdmins[channelOrgName[currentIndex - 1]] = admin;
}
return currentFunction(username, secret, client, true, Nid, channelOrgName[currentIndex], cpf);
}), Promise.resolve()
);
}).then(
function (admin) {
orgAdmins[channelOrgName[channelOrgName.length - 1]] = admin;
logger.info('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] Successfully loaded user \'admin\'', Nid, channelName, org, pid);
if (targetPeers != 'DISCOVERY') {
assignOrdererList(channel, client);
testUtil.assignChannelOrdererSubmitter(channel, client, org, cpPath, TLS)
setCurrOrdererId(channel, client, org);
if (peerFOList == 'ALL') {
assignPeerList(channel, client, org);
}
}
// add target peers to channel
setTargetPeers(targetPeers);
// add event
listenToEventHub();
if (targetPeers != 'DISCOVERY') {
setCurrPeerId(channel, client, org);
logger.info('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] peerList: ', Nid, channelName, org, pid, peerList);
}
// execute transactions
tCurr = new Date().getTime();
var tSynchUp = tStart - tCurr;
if (tSynchUp < 10000) {
tSynchUp = 10000;
}
logger.info('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] execTransMode: tCurr= %d, tStart= %d, time to wait=%d', Nid, channelName, org, pid, tCurr, tStart, tSynchUp);
setTimeout(function () {
//logger.info('[Nid:chan:org:id=%d:%s:%s:%d execTransMode] get peers %j', Nid, channelName, org, pid, channel.getPeers());
if (transType == 'DISCOVERY') {
execModeDiscovery();
} else if (transMode == 'CONSTANT') {
distOpt = txCfgPtr.constantOpt;
execModeConstant();
} else if (transMode == 'POISSON') {
distOpt = txCfgPtr.poissonOpt;
execModePoisson();
} else if (transMode == 'LATENCY') {
execModeLatency();
} else {
// invalid transaction request
logger.error(util.format("[Nid:chan:org:id=%d:%s:%s:%d execTransMode] pte-exec:completed:error Transaction %j and/or mode %s invalid", Nid, channelName, org, pid, transType, transMode));
process.exit(1);
}
}, tSynchUp);
}
).catch((err) => {
logger.error(err);
evtDisconnect();
process.exit(1);
});
} catch (err) {
logger.error(err);
evtDisconnect();
process.exit(1);
}
}
function isExecDone(trType) {
tCurr = new Date().getTime();
if (trType.toUpperCase() == 'MOVE') {
if (nRequest > 0) {
if ((inv_m % (nRequest / 10)) == 0) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, evtTimeoutCnt=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, inv_m, tx_stats[tx_evtTimeout], tCurr - tLocal));
}
if (inv_m >= nRequest) {
IDone = 1;
}
} else {
if ((inv_m % 1000) == 0) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, evtTimeoutCnt=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, inv_m, tx_stats[tx_evtTimeout], tCurr - tLocal));
}
if (runForever == 0) {
if (tCurr > tEnd) {
IDone = 1;
}
}
}
// set a guard timer that extends past the time when all events for all invoke TXs should have been received or timed out.
// If this guard timer times out, then that means at least one invoke TX did not make it,
// and cleanup has not happened so we can finish and clean up now.
if (IDone == 1) {
clearInitDiscTimeout();
lastSentTime = new Date().getTime();
logger.info('[Nid:chan:org:id=%d:%s:%s:%d isExecDone] setup Timeout: %d ms, curr time: %d', Nid, channelName, org, pid, evtTimeout, lastSentTime);
setTimeout(function () {
postEventProc('isExecDone', tx_stats);
if (!invokeCheck) {
process.exit();
}
}, evtTimeout);
}
} else if (trType.toUpperCase() == 'QUERY') {
if (nRequest > 0) {
if ((!invokeCheckExec) && ((inv_q % (nRequest / 10)) == 0)) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, inv_q, tCurr - tLocal));
}
if (inv_q >= nRequest) {
QDone = 1;
clearInitDiscTimeout();
}
} else {
if ((!invokeCheckExec) && ((inv_q % 1000) == 0)) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, inv_q, tCurr - tLocal));
}
if (runForever == 0) {
if (tCurr > tEnd) {
QDone = 1;
clearInitDiscTimeout();
}
}
}
} else if (trType.toUpperCase() == 'DISCOVERY') {
if (nRequest > 0) {
if ((n_sd % (nRequest / 10)) == 0) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, n_sd, tCurr - tLocal));
}
if (n_sd >= nRequest) {
IDone = 1;
clearInitDiscTimeout();
}
} else {
if ((n_sd % 1000) == 0) {
logger.info(util.format("[Nid:chan:org:id=%d:%s:%s:%d isExecDone] invokes(%s) sent: number=%d, elapsed time= %d",
Nid, channelName, org, pid, trType, n_sd, tCurr - tLocal));
}
if (runForever == 0) {
if (tCurr > tEnd) {
IDone = 1;
clearInitDiscTimeout();
}
}
}
}
}
//IDoneMsg()
function IDoneMsg(caller) {
tCurr = new Date().getTime();
var remain = Object.keys(txidList).length;
logger.info('[Nid:chan:org:id=%d:%s:%s:%d %s IDoneMsg] completed %d, evtTimoutCnt %d, unreceived events %d, %s(%s) in %d ms, timestamp: start %d end %d', Nid, channelName, org, pid, caller, inv_m, tx_stats[tx_evtTimeout], remain, transType, invokeType, tCurr - tLocal, tLocal, tCurr);
return;
}
// invoke validation
function invokeValidation(caller) {
if (!invokeCheck) {
logger.info("[Nid:chan:org:id=%d:%s:%s:%d invokeValidation] caller(%s), invokeCheck: %j", Nid, channelName, org, pid, caller, invokeCheck);
return;
}
logger.info("[Nid:chan:org:id=%d:%s:%s:%d invokeValidation] caller(%s) %s, %s, %d", Nid, channelName, org, pid, caller, invokeCheckPeers, invokeCheckTx, invokeCheckTxNum);
// reset transaction index
invokeCheckExec = true;
nRequest = inv_m;
if (invokeCheckTx == 'LAST') {
if (invokeCheckTxNum > inv_m) {
ccFuncInst.arg0 = ccFuncInst.keyStart;
inv_q = 1;
} else {
ccFuncInst.arg0 = ccFuncInst.keyStart + inv_m - invokeCheckTxNum;
inv_q = inv_m - invokeCheckTxNum;
}
} else if (invokeCheckTx == 'ALL') {
ccFuncInst.arg0 = ccFuncInst.keyStart;
inv_q = 0;
} else {
return;