-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-handler.js.original
More file actions
1146 lines (973 loc) · 42.2 KB
/
Copy pathcommand-handler.js.original
File metadata and controls
1146 lines (973 loc) · 42.2 KB
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
const fs = require('fs');
const path = require('path');
const uuid = require('uuid');
const appenv = require('../appenv');
const { exec } = require("./child-proc");
const { ClusterManager, NodeStatus, ClusterOwner, LifePlan } = require('./cluster-manager');
const { CONSTANTS, bundleContract, generateKeys, validateArrayElements, removeDirectorySync, questionSync } = require("./common");
const { EvernodeManager } = require("./evernode-manager");
const { InstanceManager } = require('./instance-manager');
const { error, info, success, log } = require("./logger");
const { TimeTracker } = require("./timetracker");
const NODES_BUNDLE_PATH = `./nodes/`;
const DEFAULT_QUORUM = 0.8;
const MAX_UPLOAD_TRIES = 5;
const DEFAULT_LIFE_GAP = 2; // Number of Moments
const MAX_LIFE_UPPER_BOUND = 48; // Number of Moments
const DEFAULT_OPERATIONAL_TIME_BOUND = 48; // Number of Hours
function version() {
info(`command: version`);
try {
const res = exec(`npm -g list ${CONSTANTS.npmPackageName} --depth=0`);
const splitted = res.toString().split('\n');
if (splitted.length > 1) {
success(`\n${splitted[1].split('@')[1]}\n`);
return;
}
}
catch (e) {
error('Error getting the version info:', e);
}
error(`\n${CONSTANTS.npmPackageName} is not installed.`);
}
async function list(options) {
info(`command: list`);
if (options.desc && !options.orderBy) {
error('orderBy option is required to order in descending manner.');
return;
}
let evernodeMgr;
try {
evernodeMgr = new EvernodeManager();
await evernodeMgr.init();
const hosts = await evernodeMgr.getActiveHostsFromLedger().catch(error);
if (hosts) {
let formatted = hosts.map(h => {
return {
address: h.address,
domain: h.domain,
ram: `${h.ramMb} MB`,
storage: `${h.diskMb} MB`,
cpu: {
model: h.cpuModelName,
time: `${h.cpuMicrosec} us`,
cores: h.cpuCount,
speed: `${h.cpuMHz} MHz`
},
sashimonoVersion: h.version,
countryCode: h.countryCode,
totalInstanceSlots: h.maxInstances,
availableInstanceSlots: h.maxInstances - h.activeInstances,
leaseFee: h.leaseAmount,
reputation: h.hostReputation,
}
});
if (formatted.length > 0 && options.orderBy && !(options.orderBy in formatted[0]))
error(`Host info does not contain a key named ${options.orderBy}.`);
if (options.orderBy)
formatted = formatted.filter(h => h[options.orderBy]).sort((a, b) => ((a[options.orderBy] - b[options.orderBy]) * (options.desc ? -1 : 1)));
log(formatted.slice(0, options.limit).map(h => {
if (!options.props)
return h;
const keys = options.props.split(',').filter(k => k in h);
let obj = {};
for (const key of keys) {
obj[key] = h[key];
}
return obj;
}));
}
}
catch (e) {
error('Error occurred while getting the host list:', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function hostInfo(options) {
info(`command: info`);
let evernodeMgr;
try {
let hostsToSearch = [];
let tempFileName = `hostDetails_${Date.now()}.csv`;
if (!options.filePath && !options.hostAddress)
throw 'Either host address or file path is required to search for host info.';
if (options.filePath) {
if (!fs.existsSync(options.filePath) || !fs.statSync(options.filePath).isFile())
throw `Hosts file ${options.filePath} does not exists.`;
hostsToSearch = options.filePath ? fs.readFileSync(options.filePath, 'UTF-8').split(/\r?\n/).filter(h => h) : [];
}
if (options.hostAddress && (typeof options.hostAddress !== 'string' || options.hostAddress.trim() === ''))
throw 'Host address should be a non-empty string.';
hostsToSearch.push(options.hostAddress);
if (options.output && (!(fs.existsSync(options.output) && fs.statSync(options.output).isDirectory())))
throw `Output path ${options.output} does not exist or is not a directory.`;
evernodeMgr = new EvernodeManager();
await evernodeMgr.init();
// Fetch all host details in parallel
const allHostDetails = await Promise.all(
hostsToSearch.map(async (hostAddress) => {
try {
const host = await evernodeMgr.getHostInfo(hostAddress);
if (host) {
return {
address: host.address,
domain: host.domain,
ram: `${host.ramMb} MB`,
storage: `${host.diskMb} MB`,
cpu: {
model: host.cpuModelName,
time: `${host.cpuMicrosec} us`,
cores: host.cpuCount,
speed: `${host.cpuMHz} MHz`
},
sashimonoVersion: host.version,
countryCode: host.countryCode,
totalInstanceSlots: host.maxInstances,
availableInstanceSlots: host.maxInstances - host.activeInstances,
active: host.active
};
}
} catch (error) {
console.error(`Error fetching details for host ${hostAddress}:`, error);
}
})
);
const validHostDetails = allHostDetails.filter(host => host !== undefined);
// Write them to the CSV file
if (options.output && validHostDetails.length > 0) {
tempFileName = path.join(options.output, tempFileName);
const csvHeader = [
'Address', 'Domain', 'RAM', 'Storage', 'CPU Model', 'CPU Time',
'CPU Cores', 'CPU Speed', 'Sashimono Version', 'Country Code',
'Total Instance Slots', 'Available Instance Slots', 'Active'
];
const csvData = validHostDetails.map(host => [
host.address,
host.domain,
host.ram,
host.storage,
host.cpu.model,
host.cpu.time,
host.cpu.cores,
host.cpu.speed,
host.sashimonoVersion,
host.countryCode,
host.totalInstanceSlots,
host.availableInstanceSlots,
host.active
]);
// Convert header and data into CSV format
const csvContent = [csvHeader, ...csvData].map(row => row.join(',')).join('\n');
// Write the CSV string to the temporary file
fs.writeFile(tempFileName, csvContent, (err) => {
if (err) {
console.error('Error writing to the CSV file:', err.message);
} else {
console.log('CSV file written successfully.');
}
});
}
log(validHostDetails);
}
catch (e) {
error('Error occurred while getting the host info:', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function keygen() {
info(`command: keygen`);
try {
const keys = await generateKeys();
success('New key pair generated', keys);
info('Record these keys and set the private key to the environment variable called EV_USER_PRIVATE_KEY for future operations.');
}
catch (e) {
error('Error occurred while generating key pair:', e);
}
}
async function acquire(host, options) {
info(`command: acquire`);
let evernodeMgr;
try {
evernodeMgr = new EvernodeManager({
tenantSecret: appenv.tenantSecret
});
await evernodeMgr.init();
const userKeys = await generateKeys(appenv.userPrivateKey, 'hex');
const result = await evernodeMgr.acquire(
host,
options.moments || 1,
userKeys.publicKey,
options.contractId,
options.image,
appenv.hpInitCfg || {});
success('Instance created!', result);
}
catch (e) {
error('Error occurred while acquiring the instance:', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function extend(instancesFilePath, options) {
info(`command: extend`);
let evernodeMgr;
try {
if (!instancesFilePath || !fs.existsSync(instancesFilePath))
throw 'Instance file path does not exist.';
evernodeMgr = new EvernodeManager({
tenantSecret: appenv.tenantSecret
});
await evernodeMgr.init();
const moments = options?.moments ? options.moments : 1;
// Read contents of the file
const data = fs.readFileSync(instancesFilePath, 'UTF-8');
// Split the contents by new line
const instances = data.split(/\r?\n/).filter(e => e);
await Promise.all(instances.map(async (line, i) => {
await new Promise(resolve => setTimeout(resolve, 1000 * i));
try {
let [hostAddress, instanceName, life] = line.split(":");
hostAddress = hostAddress.trim();
instanceName = instanceName.trim();
if (life)
life = life.trim();
if (!hostAddress || !instanceName)
throw 'Host address and instance name are required.';
if (life && isNaN(life))
throw 'Moment life should be a integer number.';
else if (life) {
life = Number(life);
if (!Number.isInteger(life))
throw 'Moment life should be a integer number.';
}
else {
life = moments;
}
const result = await evernodeMgr.extend(hostAddress, instanceName, life);
info(`Extending the instance for ${life} ${life === 1 ? 'moment' : 'moments'}.`);
success(`Extension txn Ref: ${result.extendRefId}\nExpiry moment: ${result.expiryMoment}`);
}
catch (e) {
error(e.reason || e);
}
}));
}
catch (e) {
error('Error occurred while extending the instance:.', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function extendInstance(hostAddress, instanceName, options) {
info(`command: extend`);
let evernodeMgr;
try {
evernodeMgr = new EvernodeManager({
tenantSecret: appenv.tenantSecret
});
await evernodeMgr.init();
const moments = options?.moments ? options.moments : 1;
const result = await evernodeMgr.extend(hostAddress, instanceName, moments);
info(`Extending the instance for ${moments} ${moments === 1 ? 'moment' : 'moments'}.`);
success(`Extension txn Ref: ${result.extendRefId}\nExpiry moment: ${result.expiryMoment}`);
}
catch (e) {
error('Error occurred while extending the instance:.', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function audit(options) {
info(`command: audit`);
let hostsToAudit = [];
let auditResults = [];
let totalAmount = 0;
let evernodeMgr, evrBalance;
const errorDescription = {
1: 'Host inactive',
2: 'Host invalid (not registered)',
3: 'No lease offer',
4: 'Timeout during Acquire',
5: 'User Install error during Acquire',
6: 'Transaction failed',
7: 'Insufficient funds during Acquire',
8: 'Connection failed during auditing',
9: 'Transaction failed due to timeout',
100: 'Unknown error',
'N/A': 'Not Applicable'
};
const errorMap = {
'HOST_INACTIVE': 1,
'HOST_INVALID': 2,
'NO_OFFER': 3,
'TIMEOUT': 4,
'user_install_error': 5,
'TRANSACTION_FAILURE': 6,
'TRANSACTION_FAILURE (tecINSUFFICIENT_FUNDS)': 7,
'Connection failed': 8,
'TRANSACTION_FAILURE (TimeoutError)': 9,
'N/A': 'N/A'
};
const expectedOperationalTime = options?.opTime ? options.opTime : DEFAULT_OPERATIONAL_TIME_BOUND;
try {
if (options.filePath) {
if (!fs.existsSync(options.filePath) || !fs.statSync(options.filePath).isFile())
throw `Hosts file ${options.filePath} does not exists.`;
hostsToAudit = options.filePath ? fs.readFileSync(options.filePath, 'UTF-8').split(/\r?\n/).filter(h => h) : [];
}
if (options.hostAddress)
hostsToAudit.push(options.hostAddress);
if (!hostsToAudit || hostsToAudit.length == 0)
throw `No hosts specified to audit.`;
evernodeMgr = new EvernodeManager({
tenantSecret: (options?.aliveness) ? null : appenv.tenantSecret
});
await evernodeMgr.init();
let userKeys;
if (!options?.aliveness)
userKeys = await generateKeys(appenv.userPrivateKey, 'hex');
const defaultValue = 'N/A';
const auditStatus = ['Success', 'Failed', 'Cannot Audit'];
const AuditResult = (hostAddress, status, alivenessData, timeAcquire = defaultValue, timeReadRequestResponse = defaultValue, timeContractResponse = defaultValue, hpVersion = defaultValue, ledgerSeqNo = defaultValue, errorMessage = defaultValue, inactiveStatus = null) => {
return {
"HOST ADDRESS": hostAddress,
"STATUS": inactiveStatus || auditStatus[status],
"CONT_ALIVENESS": alivenessData.aliveness,
"SUSTAINED_UP_TIME (H:m)": alivenessData.uptime,
"ACQUISITION DURATION (s)": timeAcquire,
"READ RES DURATION (s)": timeReadRequestResponse,
"CONTRACT RES DURATION (s)": timeContractResponse,
"HP VER": hpVersion,
"LEDGER SEQ NO": ledgerSeqNo,
"ERROR": errorMap[errorMessage] || '100'
}
}
const AlivenessResult = (hostAddress, alivenessData) => {
return {
"HOST ADDRESS": hostAddress,
"CONT_ALIVENESS": alivenessData.aliveness,
"SUSTAINED_UP_TIME (H:m)": alivenessData.uptime
}
}
if (!options?.aliveness) {
evrBalance = parseFloat(await evernodeMgr.getEVRBalance());
for (let hostIndex in hostsToAudit) {
const hostAddress = hostsToAudit[hostIndex];
const leases = await evernodeMgr.getHostLeases(hostAddress);
if (leases.length === 0) {
totalAmount += 0;
} else {
const amountValue = parseFloat(leases[0].Amount.value);
if (!isNaN(amountValue)) {
totalAmount += amountValue;
} else {
console.error('Invalid amount value in the first lease:', leases[0].Amount.value);
}
}
}
if (evrBalance < totalAmount) {
console.log(`Not enough EVRs to proceed.\nNeed ${totalAmount} EVRs.\nBut you have only ${evrBalance} EVRs.`)
process.exit(1);
}
else {
const answer = await questionSync(`It will cost ${totalAmount} EVRs from your account for the Audit. Do you wish to proceed [Y/n] ? `);
if ((answer.trim().toLowerCase() === 'n')) {
console.log("Exiting...");
process.exit(0);
}
else if (answer.trim().toLowerCase() !== 'y' && answer.trim() !== '') {
console.log('Invalid input. Please enter either "y" or "n".\nExiting...');
process.exit(0);
}
}
}
const currentTimestamp = (Date.now()) / 1000;
const latestXrplLedgerIndex = evernodeMgr.getLatestLedgerIndex();
for (let hostIndex in hostsToAudit) {
const hostAddress = hostsToAudit[hostIndex];
const timeTracker = new TimeTracker();
let timeAcquire, timeContractResponse, timeReadRequestResponse, hpVersion, ledgerSeqNo, status, errorMessage, alivenessData;
let inactiveStatus = null;
let instanceMgr;
try {
info(`Auditing ${hostAddress} ...`);
alivenessData = await evernodeMgr.checkHostRealAliveness(hostAddress, currentTimestamp, latestXrplLedgerIndex, expectedOperationalTime);
if (!options?.aliveness) {
timeTracker.start();
const result = await evernodeMgr.acquire(
hostAddress,
1,
userKeys.publicKey,
uuid.v4(),
options.image || appenv.instanceImage,
appenv.hpInitCfg || {});
success('Instance created!', result);
timeAcquire = timeTracker.end();
const instanceIp = result.domain;
const instanceUserPort = result.user_port;
instanceMgr = new InstanceManager({
ip: instanceIp,
userPort: instanceUserPort,
userPrivateKey: appenv.userPrivateKey
});
await instanceMgr.init();
timeTracker.start();
const readRequestResponse = await instanceMgr.checkReadRequestBootstrapResponse();
if (readRequestResponse == null)
throw 'Read request response check failed'
timeReadRequestResponse = timeTracker.end();
timeTracker.start();
const bootstrapStatusResult = await instanceMgr.checkBootstrapStatus();
if (bootstrapStatusResult == null)
throw 'Bootstrap status response check failed'
timeContractResponse = timeTracker.end();
const statusResult = await instanceMgr.checkStatus();
if (statusResult == null)
throw 'Status check failed'
status = 0;
hpVersion = statusResult.hpVersion;
ledgerSeqNo = statusResult.ledgerSeqNo;
}
}
catch (e) {
status = 1;
errorMessage = e.reason;
if (e.reason == 'HOST_INACTIVE') {
const hostInfo = await evernodeMgr.getHostInfo(hostAddress);
const lastActiveTimestamp = hostInfo?.lastHeartbeatIndex || hostInfo?.registrationTimestamp;
const downtime = Math.floor(Date.now() / 1000) - lastActiveTimestamp;
const days = Math.floor(downtime / (3600 * 24));
const hours = Math.floor((downtime % (3600 * 24)) / 3600);
inactiveStatus = `Inactive(${days}D-${hours}H)`;
}
else if (e.reason == 'NO_OFFER') {
status = 2;
} else if (typeof e === 'string' && e.includes('connection failed')) {
errorMessage = 'Connection failed';
}
error(`Error occurred while auditing ${hostAddress}. Error:`, e);
}
finally {
if (options?.aliveness) {
auditResults.push(AlivenessResult(hostAddress, alivenessData));
} else {
auditResults.push(AuditResult(hostAddress, status, alivenessData, timeAcquire, timeReadRequestResponse, timeContractResponse, hpVersion, ledgerSeqNo, errorMessage, inactiveStatus));
if (instanceMgr)
await instanceMgr.terminate();
}
}
}
}
catch (e) {
error('Error occurred while auditing. Error:', e);
}
finally {
if (auditResults && auditResults.length) {
console.table(auditResults);
info(`NOTE: Considered ${expectedOperationalTime}Hrs. for the Continuous Aliveness check.`)
if (!options?.aliveness) {
info('Error Descriptions:');
for (const key in errorDescription) {
console.log(`${key}: ${errorDescription[key]}`);
}
}
}
else
error("No hosts were audited.");
if (evernodeMgr)
await evernodeMgr.terminate();
}
}
async function bundle(contractDirectoryPath, instancePublicKey, contractBin, options) {
info(`command: bundle`);
try {
contractDirectoryPath = path.normalize(contractDirectoryPath);
const stats = fs.existsSync(contractDirectoryPath) ? fs.statSync(contractDirectoryPath) : null;
if (!stats || !stats.isDirectory())
throw `Contract directory ${contractDirectoryPath} does not exists.`;
const userOverrideCfg = appenv.hpOverrideCfg || {};
const hpOverrideCfg = {
...userOverrideCfg,
contract: {
...(userOverrideCfg.contract || {}),
unl: [
...(userOverrideCfg.contract?.unl || []),
instancePublicKey
],
bin_path: contractBin,
bin_args: options.contractArgs
}
}
const bundlePath = await bundleContract(
contractDirectoryPath,
hpOverrideCfg);
if (bundlePath)
success(`Archive finished. (location: ${bundlePath})`);
} catch (e) {
error('Error occurred while bundling:', e);
}
}
async function deploy(contractBundlePath, instanceIp, instanceUserPort) {
info(`command: deploy`);
let instanceMgr;
try {
instanceMgr = new InstanceManager({
ip: instanceIp,
userPort: instanceUserPort,
userPrivateKey: appenv.userPrivateKey
});
await instanceMgr.init();
await instanceMgr.uploadBundle(contractBundlePath);
success(`Contract bundle uploaded!`);
} catch (e) {
error('Error occurred while uploading the bundle:', e);
}
finally {
if (instanceMgr)
await instanceMgr.terminate();
}
}
async function acquireAndDeploy(contractDirectoryPath, contractBin, host, options) {
info(`command: acquire-and-deploy`);
let evernodeMgr;
let instanceMgr;
try {
evernodeMgr = new EvernodeManager({
tenantSecret: appenv.tenantSecret
});
contractDirectoryPath = path.normalize(contractDirectoryPath);
const stats = fs.existsSync(contractDirectoryPath) ? fs.statSync(contractDirectoryPath) : null;
if (!stats || !stats.isDirectory())
throw `Contract directory ${contractDirectoryPath} does not exists.`;
await evernodeMgr.init();
const hpConfig = appenv.hpInitCfg || {};
const userOverrideCfg = appenv.hpOverrideCfg || {};
const userKeys = await generateKeys(appenv.userPrivateKey, 'hex');
const result = await evernodeMgr.acquire(
host,
options.moments || 1,
userKeys.publicKey,
options.contractId,
options.image,
hpConfig);
const instancePublicKey = result.pubkey;
const instanceIp = result.domain;
const instanceUserPort = result.user_port;
info('Instance created!', result);
const hpOverrideCfg = {
...userOverrideCfg,
contract: {
...(userOverrideCfg.contract || {}),
unl: [
...(userOverrideCfg.contract?.unl || []),
instancePublicKey
],
bin_path: contractBin,
bin_args: options.contractArgs
}
};
const bundlePath = await bundleContract(
contractDirectoryPath,
hpOverrideCfg);
if (!bundlePath)
throw 'Archive failed.';
info(`Archive finished. (location: ${bundlePath})`);
instanceMgr = new InstanceManager({
ip: instanceIp,
userPort: instanceUserPort,
userPrivateKey: appenv.userPrivateKey
});
await instanceMgr.init();
await instanceMgr.uploadBundle(bundlePath);
info(`Contract bundle uploaded!`);
success(`Contract deployed!`);
}
catch (e) {
error('Error occurred while deploying:', e);
}
finally {
if (evernodeMgr)
await evernodeMgr.terminate();
if (instanceMgr)
await instanceMgr.terminate();
}
}
async function clusterCreate(size, contractDirectoryPath, contractBin, hostsFilePath, options) {
info(`command: create-cluster`);
let clusterMgr;
let instanceMgr;
try {
contractDirectoryPath = path.normalize(contractDirectoryPath);
const stats = fs.existsSync(contractDirectoryPath) ? fs.statSync(contractDirectoryPath) : null;
if (!stats || !stats.isDirectory())
throw `Contract directory ${contractDirectoryPath} does not exist.`;
if (!hostsFilePath || !fs.existsSync(hostsFilePath))
throw 'Preferred Host file path does not exist.';
if (options?.signers && !fs.existsSync(options.signers))
throw 'Signer Details file path does not exist.';
if (options?.lifePlan) {
if (!(Object.values(LifePlan).includes(options.lifePlan)))
throw 'Invalid cluster node life plan is provided.';
switch (options.lifePlan) {
case LifePlan.RANDOM: {
info("Randomized node life planning is considered.");
if (options?.signerLife)
throw 'Defining --signer-life is not applicable in Random life plan.';
if (options?.moments)
throw 'Defining --moments is not applicable in Random life plan.';
if (options?.evrLimit)
throw 'Defining --evr-limit is not applicable in Random life plan.';
if (options?.lifeGap)
throw 'Defining --life-gap is not applicable in Random life plan.';
if (!options?.minLife)
throw 'Defining --min-life is not applicable in Random life plan.';
if (!options?.maxLife) {
info(`Default value of --max-life (${MAX_LIFE_UPPER_BOUND} moments) is considered.`)
options.maxLife = MAX_LIFE_UPPER_BOUND;
options.reactivePruning = true;
}
const minLife = parseInt(options.minLife);
const maxLife = parseInt(options.maxLife);
if ((isNaN(minLife) || isNaN(maxLife)) || minLife >= maxLife) {
throw 'Invalid range is provided for node life randomization.';
}
if (minLife <= 0) {
throw 'Moment count for --min-life should be greater than 0.';
} else if (maxLife - minLife <= size)
throw `Provided range does not support for a good node life randomization`;
else {
options.minLife = minLife;
options.maxLife = maxLife;
}
break;
}
case LifePlan.INCREMENTAL: {
info("Incremental node life planning is considered.")
if (options?.maxLife || options?.minLife)
throw 'Defining --min-life or --max-life is not applicable in Incremental life plan.';
if (options?.signerLife)
throw 'Defining --signer-life is not applicable in Incremental life plan.';
if (options?.moments)
throw 'Defining --moments is not applicable in Incremental life plan.';
if (options?.evrLimit)
throw 'Defining --evr-limit is not applicable in Incremental life plan.';
if (!options?.lifeGap) {
info(`Default value of --life-gap (${DEFAULT_LIFE_GAP} moments) is considered.`)
options.lifeGap = DEFAULT_LIFE_GAP
} else {
options.lifeGap = options.lifeGap > 0 ? options.lifeGap : DEFAULT_LIFE_GAP;
}
break;
}
case LifePlan.STATIC:
{
info("Static node life planning is considered.")
if (options?.maxLife || options?.minLife)
throw 'Static life plan does not need the --min-life or --max-life in options.';
if (options?.lifeGap)
throw 'Static life plan does not require the --life-gap in options.';
break;
}
}
}
else {
info("Static node life planning is considered.")
options.lifePlan = LifePlan.STATIC
delete options.maxLife;
delete options.minLife;
delete options.lifeGap;
}
const hpConfig = appenv.hpInitCfg || {};
const userOverrideCfg = appenv.hpOverrideCfg || {};
const clusterSpec = {
size: size,
evrLimit: options.evrLimit,
moments: options?.moments ? parseInt(options.moments) : null,
tenantSecret: appenv.tenantSecret,
ownerPrivateKey: appenv.userPrivateKey,
contractId: options.contractId,
instanceImage: options.image,
config: hpConfig,
lifePlan: options.lifePlan
}
// If the user wants to make a multi-sig enabled cluster
if (options?.signers) {
clusterSpec.multisig = true;
options.signers = JSON.parse(fs.readFileSync(options.signers));
if (validateArrayElements(options.signers, ['account', 'secret', 'weight']))
clusterSpec.signers = options?.signers;
else {
throw 'Invalid Signer list';
}
}
else if (options?.signerCount) {
clusterSpec.multisig = true;
if (options?.signerCount > 0) {
const signerCount = parseInt(options?.signerCount);
if (signerCount <= size)
clusterSpec.signerCount = signerCount
else
throw 'Invalid signer count';
}
else
clusterSpec.signerCount = Math.ceil(size / 2);
}
if (clusterSpec.lifePlan == LifePlan.RANDOM) {
clusterSpec.minLifeMoments = options.minLife;
clusterSpec.maxLifeMoments = options.maxLife;
clusterSpec.reactivePruning = options?.reactivePruning || false;
} else if (clusterSpec.lifePlan == LifePlan.INCREMENTAL)
clusterSpec.lifeGap = options.lifeGap;
if (clusterSpec.multisig) {
// Here we consider quorum as a ratio from total weights.
if (options?.signerQuorum) {
const quorum = parseFloat(options?.signerQuorum);
if (quorum > 0 && quorum <= 1)
clusterSpec.quorum = quorum;
else
throw 'Invalid Quorum';
}
else
clusterSpec.quorum = DEFAULT_QUORUM;
if (clusterSpec.lifePlan == LifePlan.STATIC)
clusterSpec.signerMoments = options?.signerLife ? parseInt(options?.signerLife) : clusterSpec.moments;
}
let preferredHostsArray = [];
try {
const data = fs.readFileSync(hostsFilePath, 'UTF-8');
const hosts = data.split(/\r?\n/).filter(h => h);
preferredHostsArray = hosts.filter((item, index) => hosts.indexOf(item) === index);
} catch (err) {
throw 'Invalid host list file format.';
}
clusterMgr = new ClusterManager(clusterSpec);
await clusterMgr.init(preferredHostsArray);
let result;
try {
result = await clusterMgr.createCluster(preferredHostsArray, options && ('recover' in options));
}
catch (e) {
error('Error occurred while creating the cluster', e);
info(`Partial cluster info saved in ${clusterMgr.getClusterInfoCachePath()}`);
return;
}
instanceMgr = new InstanceManager({
ip: result[0].domain,
userPort: result[0].user_port,
userPrivateKey: result[0].userKeys.privateKey
});
if (clusterMgr.multisig) {
const primaryNode = result[0];
// Regular expression pattern to match the placeholder
const placeholderPattern = /<MASTER_ADDRESS>/g;
// Post Installation Script template with placeholders.
const postInstallScriptTemplate = `#!/bin/bash
# Post install script.
# Check if <MASTER_ADDRESS>.key file exists and move it to outer level.
if [[ -f ./<MASTER_ADDRESS>.key ]]; then
mv ./<MASTER_ADDRESS>.key ../<MASTER_ADDRESS>.key
echo "Moved <MASTER_ADDRESS>.key file in the outer level."
fi
exit 0`;
const tenantMasterAddress = clusterMgr.getTenantAddress();
// Prepare the post installation script.
const postInstallScript = postInstallScriptTemplate.replace(placeholderPattern, tenantMasterAddress);
// Upload a bundle with making UNL as primary node.
let uploadCount = 0;
while (uploadCount < result.length) {
await Promise.all(
result.map(async (node, i) => {
if (node.uploaded) {
return;
}
else if (node.uploadTries >= MAX_UPLOAD_TRIES) {
node.uploaded = false;
uploadCount++;
error(`Max tries for uploading to ${node.host} reached. Abandoning upload`);
return;
}
await new Promise(resolve => {
setTimeout(resolve, i * 500);
});
if (!node.bundlePath) {
const nodeBundlePath = path.resolve(`${NODES_BUNDLE_PATH}${node.pubkey}/contract_path/`);
fs.mkdirSync(nodeBundlePath, { recursive: true });
await clusterMgr.writeSigner(`${nodeBundlePath}/${tenantMasterAddress}.key`, node.pubkey);
const hpOverrideCfg = {
...userOverrideCfg,
contract: {
...(userOverrideCfg.contract || {}),
unl: [
...(userOverrideCfg.contract?.unl || []),
primaryNode.pubkey
],
bin_path: 'bootstrap_contract',
bin_args: node.userKeys.publicKey
}
};
// Replace "exit 0" with "exit 1" in order to add forceful bootstrap upgrade failure in primary node.
// exit 1 => Purposely making a bootstrap upgrade failure.
let nodePostInstallScript = (primaryNode.pubkey === node.pubkey) ?
postInstallScript.replace(/exit 0\b/g, 'exit 1') : postInstallScript;
node.bundlePath = await bundleContract(nodeBundlePath, hpOverrideCfg, nodePostInstallScript);
}
const nodeInstanceMgr = new InstanceManager({
ip: node.domain,
userPort: node.user_port,
userPrivateKey: node.userKeys.privateKey
});
try {
if (!node.uploadTries)
node.uploadTries = 1;
else
node.uploadTries++;
await nodeInstanceMgr.init();
await nodeInstanceMgr.uploadBundle(node.bundlePath, primaryNode.pubkey === node.pubkey);
await nodeInstanceMgr.terminate();
node.uploaded = true;
uploadCount++;
}
catch (e) {
await nodeInstanceMgr.terminate();
error(`Error uploading bundle on node ${node.host}`, e);
}
})
);
}