-
Notifications
You must be signed in to change notification settings - Fork 4
/
ccperf.js
1321 lines (1132 loc) · 44.9 KB
/
ccperf.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
// Author: Yohei Ueda <[email protected]>
const cluster = require('cluster');
const program = require('commander');
const fs = require('fs');
const path = require('path');
const sdk = require('fabric-client');
const util = require('util');
const sprintf = require('sprintf-js').sprintf;
const yaml = require('js-yaml');
const request = require('request');
const WebSocket = require('ws');
const glob = require('glob');
const prom = require('prom-client');
const TDigest = require('tdigest').TDigest;
const aggregatorRegistry = new prom.AggregatorRegistry();
const logger = require('winston');
if (process.env.FABRIC_CONFIG_LOGLEVEL) {
logger.level = process.env.FABRIC_CONFIG_LOGLEVEL;
}
function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}
function loadConnectionProfile(filePath) {
const baseDir = path.dirname(filePath);
const profile = yaml.safeLoad(loadFile(filePath));
function path2pem(key) {
if (key !== undefined && key.path !== undefined && key.pem === undefined) {
const pem = loadFile(key.path, baseDir);
key.pem = pem;
delete key.path;
}
}
for (const name of Object.keys(profile.organizations)) {
const org = profile.organizations[name];
path2pem(org.signedCert);
path2pem(org.adminPrivateKey);
}
for (const name of Object.keys(profile.orderers)) {
const orderer = profile.orderers[name];
path2pem(orderer.tlsCACerts);
}
for (const name of Object.keys(profile.peers)) {
const peer = profile.peers[name];
path2pem(peer.tlsCACerts);
}
return profile;
}
function loadFile(filePath, baseDir) {
if (!path.isAbsolute(filePath) && baseDir !== undefined) {
filePath = path.join(baseDir, filePath);
}
return fs.readFileSync(filePath, 'utf8');
}
class MemoryKeyValueStore {
constructor(options) {
const self = this;
logger.debug('MemoryKeyValueStore: constructor options=%j', options);
self._store = new Map();
return Promise.resolve(self);
}
initialize() {
}
getValue(name) {
const value = Promise.resolve(this._store.get(name));
logger.debug('MemoryKeyValueStore: getValue name=%j value=%j', name, value);
return value;
}
setValue(name, value) {
this._store.set(name, value);
logger.debug('MemoryKeyValueStore: setValue name=%j value=%j', name, value);
return Promise.resolve(value);
}
}
async function getClient(profile, orgName) {
const cryptoSuite = sdk.newCryptoSuite();
const cryptoKeyStore = sdk.newCryptoKeyStore(MemoryKeyValueStore, {})
cryptoSuite.setCryptoKeyStore(cryptoKeyStore);
const client = await sdk.loadFromConfig(profile);
client.setCryptoSuite(cryptoSuite);
const newStore = await new MemoryKeyValueStore();
client.setStateStore(newStore);
const org = profile.organizations[orgName];
const userOpts = {
username: "admin",
mspid: org.mspid,
cryptoContent: { signedCertPEM: org.signedCert.pem, privateKeyPEM: org.adminPrivateKey.pem },
skipPersistence: false
};
const user = await client.createUser(userOpts);
return client;
}
function doRequest(options) {
return new Promise(function (resolve, reject) {
request(options, function (error, res, body) {
if (!error && res.statusCode < 300) {
resolve(body);
} else {
console.error(body);
reject(error);
}
});
});
}
async function populate(config, channel) {
const client = await getClient(config.profile, config.orgName)
const peer_name = channel.getPeers()[0].getName();
const eventhub = channel.getChannelEventHub(peer_name);
eventhub.connect(false);
const tx_id = client.newTransactionID();
const p = new Promise(resolve => eventhub.registerTxEvent(tx_id.getTransactionID(),
(txId, code, block_bumber) => resolve(txId),
err => console.error('EventHub error ', err),
{ unregister: true }));
const request = {
chaincodeId: 'ccperf',
fcn: 'populate',
args: ['0', String(config.population), String(config.size)],
txId: tx_id
};
const results = await channel.sendTransactionProposal(request);
const proposalResponses = results[0];
const proposal = results[1];
const orderer_request = {
txId: tx_id,
proposalResponses: proposalResponses,
proposal: proposal
};
await channel.sendTransaction(orderer_request);
await p;
eventhub.disconnect();
}
class LocalDriver {
constructor() {
this.txTable = new Map();
this.eventTable = new Map();
this.registry = new prom.Registry()
this.histgramCommit = new prom.Histogram({
name: 'ccperf_commit',
help: 'Commit latency',
labelNames: ['ccperf', 'type', 'tx_validation_code'],
registers: [this.registry]
});
this.histgramE2E = new prom.Histogram({
name: 'ccperf_e2e',
help: 'E2E latency',
labelNames: ['ccperf', 'type', 'tx_validation_code'],
registers: [this.registry]
});
this.quantileEndorsement = new TDigest();
this.quantileSendTransaction = new TDigest();
this.quantileCommit = new TDigest();
this.quantileE2E = new TDigest();
}
daemon(ws) {
const driver = this;
ws.on('message', message => {
const msg = JSON.parse(message);
switch (msg.type) {
case 'init':
driver.init(msg.config).then(() => {
ws.send(JSON.stringify({
type: 'initAck'
}))
});
driver.waitCompletion().then(() => {
ws.send(JSON.stringify({
type: 'completed'
}));
});
break;
case 'start':
driver.start(msg.startTime);
break;
case 'exit':
driver.exit().then(() => {
ws.close();
});
break;
case 'colletMetrics':
driver.collectMetrics().then(metrics => {
ws.send(JSON.stringify({
type: 'metrics',
requestId: msg.requestId,
metrics: metrics
}));
});
break;
case 'feedBlockInfo':
driver.feedBlockInfo(msg.block);
break;
default:
console.error('Daemon receives unknown message %j', msg);
}
});
}
async init(config) {
this.config = config;
const driver = this;
const numProcesses = this.config.processes;
const completionPromises = [];
const exitedPromises = [];
const initAckPromises = [];
for (var i = 0; i < config.asignedProcesses; i++) {
this.config.delay = i * this.config.rampup / numProcesses;
const w = cluster.fork();
w.on('online', () => {
w.send({ type: 'init', config: this.config });
});
initAckPromises.push(new Promise(resolve => {
w.on('message', msg => {
if (msg.type === 'initAck') {
resolve(msg);
}
});
}));
w.on('message', msg => {
if (msg.type === 'tx') {
const tx = msg.tx;
driver.txTable.set(tx.id, tx);
}
});
w.on('message', msg => {
if (msg.type === 'eventRegister') {
const txid = msg.txid;
driver.eventTable.set(txid, {
worker: w
});
w.send({
type: 'eventRegistered',
txid: txid
});
}
});
completionPromises.push(new Promise(resolve => {
w.on('message', msg => {
if (msg.type == 'completed') {
resolve(msg);
}
});
}));
exitedPromises.push(new Promise(resolve => w.on('disconnect', resolve)));
exitedPromises.push(new Promise((resolve, reject) => {
w.on('exit', (code, signal) => {
if (signal) {
reject(`Worker ${w.id} is killed by ${signal}`);
} else if (code != 0) {
reject(`Worker ${w.id} exited with return code ${code}`);
} else {
resolve();
}
});
}));
}
this.completionPromise = Promise.all(completionPromises);
this.exitedPromise = Promise.all(exitedPromises);
console.log('Started %d workers', config.asignedProcesses);
return Promise.all(initAckPromises);;
}
async waitCompletion() {
return this.completionPromise;
}
async start(startTime) {
for (const id in cluster.workers) {
const w = cluster.workers[id];
w.send({
type: 'start',
startTime: startTime
});
}
}
async exit() {
for (const id in cluster.workers) {
const w = cluster.workers[id];
w.send({ type: 'exit' });
}
return this.exitedPromise;
}
async collectMetrics() {
const commitMetricString = this.registry.getSingleMetricAsString('ccperf_commit');
const quantiles = {
'endorsement': this.quantileEndorsement.toArray(),
'sendtransaction': this.quantileSendTransaction.toArray(),
'commit': this.quantileCommit.toArray(),
'e2e': this.quantileE2E.toArray()
};
return new Promise((resolve, reject) => {
aggregatorRegistry.clusterMetrics((err, metricsStr) => {
metricsStr += '\n' + commitMetricString;
if (err) {
reject(err);
} else {
resolve({
promMetrics: decodeMetricsString(metricsStr),
quantiles: quantiles
});
}
});
});
}
async feedBlockInfo(block) {
// Example data structure of a filtered block:
// {
// "channel_id": "mychannel",
// "number": "123",
// "filtered_transactions": [
// {
// "Data": "transaction_actions",
// "txid": "cd1c24b15e19e1923a1cda0fbd1a2db4528eafd6140d563e8ec9abdd5655bcc3",
// "type": "ENDORSER_TRANSACTION",
// "tx_validation_code": "VALID",
// "transaction_actions": {
// "chaincode_actions": []
// }
// }, ...]
// }
const now = Date.now();
for (const commit of block.filtered_transactions) {
const txid = commit.txid;
const tx = this.txTable.get(txid);
if (tx !== undefined) {
this.txTable.delete(txid);
const commitLatency = (now - tx.t3) / 1000;
const e2eLatency = (now - tx.t1) / 1000;
const labels = {
"ccperf": "test",
"type": commit.type,
"tx_validation_code": commit.tx_validation_code
}
this.histgramCommit.observe(labels, commitLatency);
this.histgramE2E.observe(labels, e2eLatency);
this.quantileEndorsement.push((tx.t2 - tx.t1) / 1000);
this.quantileSendTransaction.push((tx.t3 - tx.t2) / 1000);
this.quantileCommit.push(commitLatency);
this.quantileE2E.push(e2eLatency);
}
const event = this.eventTable.get(txid);
if (event !== undefined) {
this.eventTable.delete(txid);
event.worker.send({
type: 'eventOccurred',
tx: commit
});
}
}
}
}
class RemoteDriver {
constructor(hostport) {
this.handlers = {};
const [host, portstr] = hostport.split(':');
const port = Number(portstr);
this.url = `ws://${host}:${port}`;
}
handler(message) {
const msg = JSON.parse(message);
const handler = this.handlers[msg.type];
if (handler === undefined) {
console.error('Daemon process returns unknown message: %j', msg);
return;
}
handler(msg);
}
async init(config) {
this.config = config;
const driver = this;
const ws = new WebSocket(this.url);
this.ws = ws;
this.metricRequests = new Map();
this.metricRequestCount = 0;
ws.on('message', message => {
driver.handler(message);
});
await new Promise(resolve => ws.on('open', resolve));
this.exitedPromise = new Promise(resolve => ws.on('close', resolve));
const initAckPromise = new Promise(resolve => {
driver.handlers['initAck'] = resolve
});
this.completionPromise = new Promise(resolve => {
driver.handlers['completed'] = message => {
resolve(message);
};
});
this.handlers['metrics'] = msg => {
const request = this.metricRequests.get(msg.requestId);
if (request !== undefined) {
this.metricRequests.delete(msg.requestId);
request.done(msg.metrics);
} else {
console.error('Unknown metricRequestId: ', msg.requestId);
}
};
ws.send(JSON.stringify({ type: 'init', config: config }));
return initAckPromise;
}
async waitCompletion() {
return this.completionPromise;
}
async start(startTime) {
this.ws.send(JSON.stringify({
type: 'start',
startTime: startTime
}));
}
async exit() {
this.ws.send(JSON.stringify({
type: 'exit',
}));
return this.exitedPromise;
}
async collectMetrics() {
const driver = this;
const requestId = this.metricRequestCount++;
const promise = new Promise((resolve, reject) => {
const request = {
done: resolve
}
driver.metricRequests.set(requestId, request);
});
driver.ws.send(JSON.stringify({
type: 'colletMetrics',
requestId: requestId
}));
return promise;
}
async feedBlockInfo(block) {
this.ws.send(JSON.stringify({
type: 'feedBlockInfo',
block: block
}));
}
}
function decodeMetricsString(metricsStr) {
const metricsTable = {};
for (const metric of metricsStr.split('\n\n')) {
let name;
for (const line of metric.split('\n')) {
const items = line.split(' ');
if (items[0] === '#') {
name = items[2]
let metricObj = metricsTable[name];
if (metricObj === undefined) {
metricObj = { values: {} }
metricsTable[name] = metricObj;
}
if (items[1] === 'HELP') {
metricObj.help = items.slice(3).join(' ');
} else if (items[1] === 'TYPE') {
metricObj.type = items[3];
}
} else if (items[0] !== '') {
const metricObj = metricsTable[name];
const fullname = items[0];
metricObj.values[fullname] = Number(items[1]);
}
}
}
return metricsTable;
}
function encodeMetricsString(metrics) {
let str = '';
for (const name of Object.keys(metrics)) {
const metric = metrics[name];
str += `# HELP ${name} ${metric.help}\n`
str += `# TYPE ${name} ${metric.type}\n`
const keys = Object.keys(metric.values);
if (keys.length > 0) {
for (const key of keys) {
const value = metric.values[key];
str += `${key} ${value}\n`
}
}
str += '\n';
}
return str;
}
class Master {
constructor(config) {
this.config = config;
}
setupEventHub() {
this.eventhub = this.channel.getChannelEventHub(this.config.committingPeerName);
this.eventhub.connect(false);
if (this.config.logdir) {
const blocksLogPath = config.logdir + '/blocks.json';
this.blocksLog = fs.createWriteStream(blocksLogPath, { flags: 'wx' });
this.blocksLog.write('[\n');
this.blocksLog.firstWriteFlag = true;
}
const master = this;
this.blockRegNum = this.eventhub.registerBlockEvent(
block => {
for (const driver of master.drivers) {
driver.feedBlockInfo(block);
}
if (master.blocksLog) {
if (blocksLog.firstWriteFlag) {
blocksLog.firstWriteFlag = false;
} else {
blocksLog.write(',\n');
}
master.blocksLog.write(JSON.stringify({ timestamp: now, block: block }, undefined, 4));
}
},
err => {
console.error('EventHub error ', err);
}
);
}
shutdownEventHub() {
this.eventhub.unregisterBlockEvent(this.blockRegNum);
this.eventhub.disconnect();
if (this.blocksLog) {
this.blocksLog.close();
}
}
printMetricsHeading() {
//console.log(' elapsed peer.tps orderer.tps commit.tps peer.avg orderer.avg commit.avg peer.pctl orderer.pctl commit.pctl');
console.log(' elapsed peer.tps orderer.tps commit.tps peer.avg orderer.avg commit.avg');
}
printMetrics(interval, elapsed, current, prev) {
function delta(name, key, current, prev) {
const fullname = name + "_" + key;
if (current[name] === undefined || prev[name] === undefined) {
return NaN;
}
return current[name].values[fullname] - prev[name].values[fullname];
}
const data = {
elapsed: elapsed,
peer: {
tps: delta('ccperf_endorsement', 'count{ccperf="test"}', current, prev) / interval,
avg: 1000 * delta('ccperf_endorsement', 'sum{ccperf="test"}', current, prev) / delta('ccperf_endorsement', 'count{ccperf="test"}', current, prev),
pctl: 0
},
orderer: {
tps: delta('ccperf_sendtransaction', 'count{ccperf="test"}', current, prev) / interval,
avg: 1000 * delta('ccperf_sendtransaction', 'sum{ccperf="test"}', current, prev) / delta('ccperf_sendtransaction', 'count{ccperf="test"}', current, prev),
pctl: 0
},
commit: {
tps: delta('ccperf_commit', 'count{ccperf="test",type="ENDORSER_TRANSACTION",tx_validation_code="VALID"}', current, prev) / interval,
avg: 1000 * delta('ccperf_commit', 'sum{ccperf="test",type="ENDORSER_TRANSACTION",tx_validation_code="VALID"}', current, prev) / delta('ccperf_commit', 'count{ccperf="test",type="ENDORSER_TRANSACTION",tx_validation_code="VALID"}', current, prev),
pctl: 0
}
};
//const s = sprintf('%(elapsed)8d %(peer.tps)8.2f %(orderer.tps)11.2f %(commit.tps)10.2f %(peer.avg)8.2f %(orderer.avg)11.2f %(commit.avg)10.2f %(peer.pctl)9.2f %(orderer.pctl)12.2f %(commit.pctl)11.2f', data);
const s = sprintf('%(elapsed)8d %(peer.tps)8.2f %(orderer.tps)11.2f %(commit.tps)10.2f %(peer.avg)8.2f %(orderer.avg)11.2f %(commit.avg)10.2f', data);
console.log('%s', s);
}
aggregateMetrics(metricsArray) {
const metricsTable = {};
const tdigestTable = {
endorsement: new TDigest(),
sendtransaction: new TDigest(),
commit: new TDigest(),
e2e: new TDigest()
};
for (const metrics of metricsArray) {
// Prometheus Histograms
for (const name of Object.keys(metrics.promMetrics)) {
const metric = metrics.promMetrics[name];
let metricObj = metricsTable[name];
if (metricObj === undefined) {
metricObj = {
help: metric.help,
type: metric.type,
values: {}
};
metricsTable[name] = metricObj
};
for (const fullname of Object.keys(metric.values)) {
let oldValue = metricObj.values[fullname];
if (oldValue === undefined) {
oldValue = 0.0;
}
metricObj.values[fullname] = oldValue + metric.values[fullname];
}
}
// TDigest quantiles
for (const name of Object.keys(metrics.quantiles)) {
const quantile = metrics.quantiles[name];
const tdigest = tdigestTable[name];
tdigest.push_centroid(quantile);
}
}
for (const key of Object.keys(tdigestTable)) {
const name = 'ccperf_' + key + '_quantile';
const tdigest = tdigestTable[key];
const metricObj = {
help: key + " latency quantile",
type: "gauge",
values: {}
}
for (const p of [0.5, 0.9, 0.95, 0.99]) {
const percentile = tdigest.percentile(p);
if (percentile !== undefined) {
metricObj.values[name + '{le="' + String(p) + '"}'] = percentile;
}
}
metricsTable[name] = metricObj;
}
return metricsTable;
}
collectMetrics() {
const promises = [];
for (const driver of this.drivers) {
promises.push(driver.collectMetrics());
}
return Promise.all(promises);
}
async postPrometheus(metricString) {
const timestamp = parseInt((this.startTime + this.config.rampup) / 1000);
const url = this.config.prometheus + '/metrics/job/fabric/run_timestamp/' + timestamp + '/duration_seconds/' + this.config.duration / 1000;
const requestOptions = {
url: url,
method: "PUT",
headers: {
"Content-type": "text/plain",
},
body: metricString
}
//console.log(requestOptions);
return doRequest(requestOptions).catch(err => { throw new Error(err) });
}
async start() {
const config = this.config;
this.client = await getClient(config.profile, config.orgName)
this.channel = this.client.getChannel(config.channelID);
if (config.population) {
await populate(config, this.channel);
}
if (config.committingPeerName) {
this.setupEventHub();
}
this.drivers = [];
for (const remote of config.remotes) {
let [hostport, processes] = remote.split('/');
let driver;
if (hostport === "local") {
//console.log('Creating local driver');
driver = new LocalDriver();
} else {
driver = new RemoteDriver(hostport);
}
if (processes === undefined) {
processes = config.processes / config.remotes.length;
}
const driverConfig = Object.assign({}, config);
driverConfig.asignedProcesses = processes;
await driver.init(driverConfig);
this.drivers.push(driver);
}
this.startTime = Date.now() + 1000;
for (const driver of this.drivers) {
driver.start(this.startTime);
}
const interval = 5000.0;
let previousMetrics;
let elapsed = 0.0;
await sleep(this.startTime - Date.now());
this.collectMetrics().then(metricsArray => {
previousMetrics = this.aggregateMetrics(metricsArray);
});
const promInt = setInterval(() => {
this.collectMetrics().then(metricsArray => {
const currentMetrics = this.aggregateMetrics(metricsArray);
//console.log(encodeMetricsString(currentMetrics));
this.printMetrics(interval / 1000, elapsed, currentMetrics, previousMetrics);
if (config.prometheus) {
this.postPrometheus(encodeMetricsString(currentMetrics));
}
previousMetrics = currentMetrics;
elapsed += interval / 1000;
});
}, interval);
console.log('Start: ', this.startTime + config.rampup);
console.log('End: ', this.startTime + config.rampup + config.duration);
this.printMetricsHeading();
for (const driver of this.drivers) {
await driver.waitCompletion();
}
clearInterval(promInt);
if (config.committingPeerName) {
this.shutdownEventHub();
}
for (const driver of this.drivers) {
await driver.exit();
}
}
}
function randomIntArgs(n, min, max) {
const args = [];
for (let i = 0; i < n; i++) {
args.push(String(min + Math.floor(Math.random() * (max - min))))
}
return args
}
class DefaultChaincodeTxPlugin {
constructor() {
this._chaincodeId = 'ccperf';
this._genArgsTable = {
'putstate': context => [String(context.config.num), String(context.config.size), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index)],
'getstate': context => [String(context.config.num), String(context.config.population), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index)],
'rangequery': context => [String(1), String(context.config.population)],
'rangequery_update': context => [String(context.config.num), String(context.config.size), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index), String(context.config.population)],
'mix': context => [String(context.config.num), String(context.config.num2), String(context.config.size), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index), String(context.config.population)],
'json': context => [String(context.config.num), String(context.config.num2), String(context.config.size), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index), String(context.config.population)],
'contended': context => randomIntArgs(context.config.num, 0, context.config.population - 1),
'invoke_chaincode': context => [String(context.config.num), "ccperf2", "putstate", String(1), String(64), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index)],
'hash': context => [String(context.config.num), util.format('key_mychannel_org1_0_%d_%d', context.workerID, context.index)],
}
}
getChaincodeId() {
return this._chaincodeId;
}
getTxTypes() {
return Object.keys(this._genArgsTable);
}
getTxHandler(txType) {
if (txType == "composite") {
if (cluster.worker.id % 2 == 0) {
txType = 'json';
} else {
txType = 'rangequery';
}
}
const handler = {
chaincodeId: this.getChaincodeId(),
isQuery: false,
retry: false,
fcn: txType,
genArgs: this._genArgsTable[txType],
genTransientMap: undefined,
genUserName: undefined,
};
if (txType == 'rangequery') {
handler.isQuery = true;
}
if (txType == 'contended') {
handler.retry = true;
}
return handler;
}
}
class Worker {
constructor(config) {
this.workerID = cluster.worker.id;
this.index = 1;
this.config = config;
let plugin;
if (config.txPluginStr) {
const txPluginClass = eval(config.txPluginStr);
plugin = new txPluginClass();
} else {
plugin = new DefaultChaincodeTxPlugin();
}
const handler = plugin.getTxHandler(config.txType);
this.chaincodeId = handler.chaincodeId;
this.fcn = handler.fcn;
this.genArgs = handler.genArgs;
this.genTransientMap = handler.genTransientMap;
this.genUserName = handler.genUserName;
this.isQuery = handler.isQuery
this.retry = handler.retry
if (this.retry) {
this.eventTable = new Map();
}
if (config.logdir) {
const requestsLogPath = config.logdir + '/requests-' + cluster.worker.id + '.json';
this.requestsLog = fs.createWriteStream(requestsLogPath, { flags: 'wx' });
this.requestsLog.write('[\n');
}
this.registry = new prom.Registry();
prom.AggregatorRegistry.setRegistries([this.registry]);
this.histgramEndorsement = new prom.Histogram({
name: 'ccperf_endorsement',
help: 'Endorsement latency',
labelNames: ['ccperf'],
registers: [this.registry]
});
this.histgramSendTransaction = new prom.Histogram({
name: 'ccperf_sendtransaction',
help: 'SendTransaction latency',
labelNames: ['ccperf'],
registers: [this.registry]
});
this.digestCommits = null;
}
async start() {
const config = this.config;
this.client = await getClient(config.profile, config.orgName);
this.channel = this.client.getChannel(config.channelID);
if (this.config.clientKeystore !== undefined) {
this.cryptoSuite = sdk.newCryptoSuite();
const cryptoKeyStore = sdk.newCryptoKeyStore(undefined, { path: config.clientKeystore });
this.cryptoSuite.setCryptoKeyStore(cryptoKeyStore);
this.stateStore = await sdk.newDefaultKeyValueStore({ path: config.clientKeystore });
}
const orgs = config.endorsingOrgs;
this.peers = []
for (const org of orgs) {
const orgPeers = this.channel.getPeersForOrg(config.profile.organizations[org].mspid).filter(p => p.isInRole("endorsingPeer"));
this.peers.push(orgPeers[cluster.worker.id % orgPeers.length]);
}
if (config.ordererSelection == 'balance') {
const orderers = this.channel.getOrderers();
const orderer = orderers[cluster.worker.id % orderers.length];
this.orderer = orderer.getName();
}
if (this.retry) {
process.on('message', msg => {
if (msg.type === 'eventRegistered') {
const event = this.eventTable.get(msg.txid);
event.registeredResolve(msg);
}
});
process.on('message', msg => {
if (msg.type === 'eventOccurred') {
const txid = msg.tx.txid;
const event = this.eventTable.get(txid);
this.eventTable.delete(txid);
msg.requestArgs = event.requestArgs;
event.occurredResolve(msg);
}
});
}
const promise = new Promise(resolve => {
process.once('message', msg => {
if (msg.type === 'start') {
resolve(msg.startTime);
}
})
});
process.send({ type: 'initAck' });
const startTime = await promise;
const wait = startTime + config.delay - Date.now();
if (wait > 0) {
await sleep(wait);
}
const end = startTime + config.rampup + config.duration + config.rampdown;
let behind = 0;
while (true) {
const before = Date.now();
this.index += 1;
this.execute();
const after = Date.now();
const remaining = config.interval - (after - before) - behind;
if (remaining > 0) {
behind = 0;
await sleep(remaining);
} else {
behind = -remaining;
}
if (Date.now() > end) {
break;
}
}
process.send({ type: 'completed' });
//console.log(info.index/duration*1000);
if (config.logdir) {
requestsLog.write('\n]\n');
requestsLog.close();