-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCluster.py
1721 lines (1451 loc) · 75.2 KB
/
Cluster.py
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
import copy
import subprocess
import time
import glob
import shutil
import os
import re
import string
import signal
import datetime
import sys
import random
import json
from core_symbol import CORE_SYMBOL
from testUtils import Utils
from testUtils import Account
from Node import BlockType
from Node import Node
from WalletMgr import WalletMgr
# Protocol Feature Setup Policy
class PFSetupPolicy:
NONE = 0
PREACTIVATE_FEATURE_ONLY = 1
FULL = 2 # This will only happen if the cluster is bootstrapped (i.e. dontBootstrap == False)
@staticmethod
def hasPreactivateFeature(policy):
return policy == PFSetupPolicy.PREACTIVATE_FEATURE_ONLY or \
policy == PFSetupPolicy.FULL
@staticmethod
def isValid(policy):
return policy == PFSetupPolicy.NONE or \
policy == PFSetupPolicy.PREACTIVATE_FEATURE_ONLY or \
policy == PFSetupPolicy.FULL
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-public-methods
class Cluster(object):
__chainSyncStrategies=Utils.getChainStrategies()
__chainSyncStrategy=None
__WalletName="MyWallet"
__localHost="localhost"
__BiosHost="localhost"
__BiosPort=8788
__LauncherCmdArr=[]
__bootlog="eosio-ignition-wd/bootlog.txt"
# pylint: disable=too-many-arguments
# walletd [True|False] Is keosd running. If not load the wallet plugin
def __init__(self, walletd=False, localCluster=True, host="localhost", port=8888, walletHost="localhost", walletPort=9899, enableMongo=False
, mongoHost="localhost", mongoPort=27017, mongoDb="EOStest", defproduceraPrvtKey=None, defproducerbPrvtKey=None, staging=False):
"""Cluster container.
walletd [True|False] Is wallet keosd running. If not load the wallet plugin
localCluster [True|False] Is cluster local to host.
host: eos server host
port: eos server port
walletHost: eos wallet host
walletPort: wos wallet port
enableMongo: Include mongoDb support, configures eos mongo plugin
mongoHost: MongoDB host
mongoPort: MongoDB port
defproduceraPrvtKey: Defproducera account private key
defproducerbPrvtKey: Defproducerb account private key
"""
self.accounts={}
self.nodes={}
self.unstartedNodes=[]
self.localCluster=localCluster
self.wallet=None
self.walletd=walletd
self.enableMongo=enableMongo
self.mongoHost=mongoHost
self.mongoPort=mongoPort
self.mongoDb=mongoDb
self.walletMgr=None
self.host=host
self.port=port
self.walletHost=walletHost
self.walletPort=walletPort
self.mongoEndpointArgs=""
self.mongoUri=""
if self.enableMongo:
self.mongoUri="mongodb://%s:%d/%s" % (mongoHost, mongoPort, mongoDb)
self.mongoEndpointArgs += "--host %s --port %d %s" % (mongoHost, mongoPort, mongoDb)
self.staging=staging
# init accounts
self.defProducerAccounts={}
self.defproduceraAccount=self.defProducerAccounts["defproducera"]= Account("defproducera")
self.defproducerbAccount=self.defProducerAccounts["defproducerb"]= Account("defproducerb")
self.eosioAccount=self.defProducerAccounts["eosio"]= Account("eosio")
self.defproduceraAccount.ownerPrivateKey=defproduceraPrvtKey
self.defproduceraAccount.activePrivateKey=defproduceraPrvtKey
self.defproducerbAccount.ownerPrivateKey=defproducerbPrvtKey
self.defproducerbAccount.activePrivateKey=defproducerbPrvtKey
self.useBiosBootFile=False
self.filesToCleanup=[]
self.alternateVersionLabels=Cluster.__defaultAlternateVersionLabels()
def setChainStrategy(self, chainSyncStrategy=Utils.SyncReplayTag):
self.__chainSyncStrategy=self.__chainSyncStrategies.get(chainSyncStrategy)
if self.__chainSyncStrategy is None:
self.__chainSyncStrategy=self.__chainSyncStrategies.get("none")
def setWalletMgr(self, walletMgr):
self.walletMgr=walletMgr
@staticmethod
def __defaultAlternateVersionLabels():
"""Return a labels dictionary with just the "current" label to path set."""
labels={}
labels["current"]="./"
return labels
def setAlternateVersionLabels(self, file):
"""From the provided file return a dictionary of labels to paths."""
Utils.Print("alternate file=%s" % (file))
self.alternateVersionLabels=Cluster.__defaultAlternateVersionLabels()
if file is None:
# only have "current"
return
if not os.path.exists(file):
Utils.errorExit("Alternate Version Labels file \"%s\" does not exist" % (file))
with open(file, 'r') as f:
content=f.read()
p=re.compile(r'^\s*(\w+)\s*=\s*([^\s](?:.*[^\s])?)\s*$', re.MULTILINE)
all=p.findall(content)
for match in all:
label=match[0]
path=match[1]
if label=="current":
Utils.Print("ERROR: cannot overwrite default label %s with path=%s" % (label, path))
continue
self.alternateVersionLabels[label]=path
if Utils.Debug: Utils.Print("Version label \"%s\" maps to \"%s\"" % (label, path))
# launch local nodes and set self.nodes
# pylint: disable=too-many-locals
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
def launch(self, pnodes=1, unstartedNodes=0, totalNodes=1, prodCount=1, topo="mesh", delay=1, onlyBios=False, dontBootstrap=False,
totalProducers=None, sharedProducers=0, extraNodeosArgs=None, useBiosBootFile=True, specificExtraNodeosArgs=None, onlySetProds=False,
pfSetupPolicy=PFSetupPolicy.FULL, alternateVersionLabelsFile=None, associatedNodeLabels=None, loadSystemContract=True):
"""Launch cluster.
pnodes: producer nodes count
unstartedNodes: non-producer nodes that are configured into the launch, but not started. Should be included in totalNodes.
totalNodes: producer + non-producer nodes + unstarted non-producer nodes count
prodCount: producers per producer node count
topo: cluster topology (as defined by launcher, and "bridge" shape that is specific to this launch method)
delay: delay between individual nodes launch (as defined by launcher)
delay 0 exposes a bootstrap bug where producer handover may have a large gap confusing nodes and bringing system to a halt.
onlyBios: When true, only loads the bios contract (and not more full bootstrapping).
dontBootstrap: When true, don't do any bootstrapping at all. (even bios is not uploaded)
extraNodeosArgs: string of arguments to pass through to each nodoes instance (via --nodeos flag on launcher)
useBiosBootFile: determines which of two bootstrap methods is used (when both dontBootstrap and onlyBios are false).
The default value of true uses the bios_boot.sh file generated by the launcher.
A value of false uses manual bootstrapping in this script, which does not do things like stake votes for producers.
specificExtraNodeosArgs: dictionary of arguments to pass to a specific node (via --specific-num and
--specific-nodeos flags on launcher), example: { "5" : "--plugin eosio::test_control_api_plugin" }
onlySetProds: Stop the bootstrap process after setting the producers (only if useBiosBootFile is false)
pfSetupPolicy: determine the protocol feature setup policy (none, preactivate_feature_only, or full)
alternateVersionLabelsFile: Supply an alternate version labels file to use with associatedNodeLabels.
associatedNodeLabels: Supply a dictionary of node numbers to use an alternate label for a specific node.
loadSystemContract: indicate whether the eosio.system contract should be loaded (setting this to False causes useBiosBootFile to be treated as False)
"""
assert(isinstance(topo, str))
assert PFSetupPolicy.isValid(pfSetupPolicy)
if alternateVersionLabelsFile is not None:
assert(isinstance(alternateVersionLabelsFile, str))
elif associatedNodeLabels is not None:
associatedNodeLabels=None # need to supply alternateVersionLabelsFile to use labels
if associatedNodeLabels is not None:
assert(isinstance(associatedNodeLabels, dict))
Utils.Print("associatedNodeLabels size=%s" % (len(associatedNodeLabels)))
Utils.Print("alternateVersionLabelsFile=%s" % (alternateVersionLabelsFile))
if not self.localCluster:
Utils.Print("WARNING: Cluster not local, not launching %s." % (Utils.EosServerName))
return True
if len(self.nodes) > 0:
raise RuntimeError("Cluster already running.")
if pnodes > totalNodes:
raise RuntimeError("totalNodes (%d) must be equal to or greater than pnodes(%d)." % (totalNodes, pnodes))
if pnodes + unstartedNodes > totalNodes:
raise RuntimeError("totalNodes (%d) must be equal to or greater than pnodes(%d) + unstartedNodes(%d)." % (totalNodes, pnodes, unstartedNodes))
if self.walletMgr is None:
self.walletMgr=WalletMgr(True)
producerFlag=""
if totalProducers:
assert(isinstance(totalProducers, (str,int)))
producerFlag="--producers %s" % (totalProducers)
if sharedProducers > 0:
producerFlag += (" --shared-producers %d" % (sharedProducers))
self.setAlternateVersionLabels(alternateVersionLabelsFile)
tries = 30
while not Utils.arePortsAvailable(set(range(self.port, self.port+totalNodes+1))):
Utils.Print("ERROR: Another process is listening on nodeos default port. wait...")
if tries == 0:
return False
tries = tries - 1
time.sleep(2)
cmd="%s -p %s -n %s -d %s -i %s -f %s --unstarted-nodes %s" % (
Utils.EosLauncherPath, pnodes, totalNodes, delay, datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
producerFlag, unstartedNodes)
cmdArr=cmd.split()
if self.staging:
cmdArr.append("--nogen")
nodeosArgs="--max-transaction-time -1 --abi-serializer-max-time-ms 990000 --filter-on \"*\" --p2p-max-nodes-per-host %d" % (totalNodes)
if not self.walletd:
nodeosArgs += " --plugin eosio::wallet_api_plugin"
if self.enableMongo:
nodeosArgs += " --plugin eosio::mongo_db_plugin --mongodb-wipe --delete-all-blocks --mongodb-uri %s" % self.mongoUri
if extraNodeosArgs is not None:
assert(isinstance(extraNodeosArgs, str))
nodeosArgs += extraNodeosArgs
if Utils.Debug:
nodeosArgs += " --contracts-console"
if PFSetupPolicy.hasPreactivateFeature(pfSetupPolicy):
nodeosArgs += " --plugin eosio::producer_api_plugin"
if nodeosArgs:
cmdArr.append("--nodeos")
cmdArr.append(nodeosArgs)
if specificExtraNodeosArgs is not None:
assert(isinstance(specificExtraNodeosArgs, dict))
for nodeNum,arg in specificExtraNodeosArgs.items():
assert(isinstance(nodeNum, (str,int)))
assert(isinstance(arg, str))
cmdArr.append("--specific-num")
cmdArr.append(str(nodeNum))
cmdArr.append("--specific-nodeos")
cmdArr.append(arg)
cmdArr.append("--max-block-cpu-usage")
cmdArr.append(str(160000000))
cmdArr.append("--max-transaction-cpu-usage")
cmdArr.append(str(150000000))
if associatedNodeLabels is not None:
for nodeNum,label in associatedNodeLabels.items():
assert(isinstance(nodeNum, (str,int)))
assert(isinstance(label, str))
path=self.alternateVersionLabels.get(label)
if path is None:
Utils.errorExit("associatedNodeLabels passed in indicates label %s for node num %s, but it was not identified in %s" % (label, nodeNum, alternateVersionLabelsFile))
cmdArr.append("--spcfc-inst-num")
cmdArr.append(str(nodeNum))
cmdArr.append("--spcfc-inst-nodeos")
cmdArr.append(path)
# must be last cmdArr.append before subprocess.call, so that everything is on the command line
# before constructing the shape.json file for "bridge"
if topo=="bridge":
shapeFilePrefix="shape_bridge"
shapeFile=shapeFilePrefix+".json"
cmdArrForOutput=copy.deepcopy(cmdArr)
cmdArrForOutput.append("--output")
cmdArrForOutput.append(shapeFile)
s=" ".join(cmdArrForOutput)
if Utils.Debug: Utils.Print("cmd: %s" % (s))
if 0 != subprocess.call(cmdArrForOutput):
Utils.Print("ERROR: Launcher failed to create shape file \"%s\"." % (shapeFile))
return False
f = open(shapeFile, "r")
shapeFileJsonStr = f.read()
f.close()
shapeFileObject = json.loads(shapeFileJsonStr)
Utils.Print("shapeFileObject=%s" % (shapeFileObject))
# retrieve the nodes, which as a map of node name to node definition, which the fc library prints out as
# an array of array, the first level of arrays is the pair entries of the map, the second is an array
# of two entries - [ <first>, <second> ] with first being the name and second being the node definition
shapeFileNodes = shapeFileObject["nodes"]
numProducers=totalProducers if totalProducers is not None else (totalNodes - unstartedNodes)
maxProducers=ord('z')-ord('a')+1
assert numProducers<maxProducers, \
"ERROR: topo of %s assumes names of \"defproducera\" to \"defproducerz\", so must have at most %d producers" % \
(topo,maxProducers)
# will make a map to node object to make identification easier
biosNodeObject=None
bridgeNodes={}
producerNodes={}
producers=[]
for append in range(ord('a'),ord('a')+numProducers):
name="defproducer" + chr(append)
producers.append(name)
# first group starts at 0
secondGroupStart=int((numProducers+1)/2)
producerGroup1=[]
producerGroup2=[]
Utils.Print("producers=%s" % (producers))
shapeFileNodeMap = {}
def getNodeNum(nodeName):
p=re.compile(r'^testnet_(\d+)$')
m=p.match(nodeName)
return int(m.group(1))
for shapeFileNodePair in shapeFileNodes:
assert(len(shapeFileNodePair)==2)
nodeName=shapeFileNodePair[0]
shapeFileNode=shapeFileNodePair[1]
shapeFileNodeMap[nodeName]=shapeFileNode
Utils.Print("name=%s, shapeFileNode=%s" % (nodeName, shapeFileNodeMap[shapeFileNodePair[0]]))
if nodeName=="bios":
biosNodeObject=shapeFileNode
continue
nodeNum=getNodeNum(nodeName)
Utils.Print("nodeNum=%d, shapeFileNode=%s" % (nodeNum, shapeFileNode))
assert("producers" in shapeFileNode)
shapeFileNodeProds=shapeFileNode["producers"]
numNodeProducers=len(shapeFileNodeProds)
if (numNodeProducers==0):
bridgeNodes[nodeName]=shapeFileNode
else:
producerNodes[nodeName]=shapeFileNode
group=None
# go through all the producers for this node and determine which group on the bridged network they are in
for shapeFileNodeProd in shapeFileNodeProds:
producerIndex=0
for prod in producers:
if prod==shapeFileNodeProd:
break
producerIndex+=1
prodGroup=None
if producerIndex<secondGroupStart:
prodGroup=1
if group is None:
group=prodGroup
producerGroup1.append(nodeName)
Utils.Print("Group1 grouping producerIndex=%s, secondGroupStart=%s" % (producerIndex,secondGroupStart))
else:
prodGroup=2
if group is None:
group=prodGroup
producerGroup2.append(nodeName)
Utils.Print("Group2 grouping producerIndex=%s, secondGroupStart=%s" % (producerIndex,secondGroupStart))
if group!=prodGroup:
Utils.errorExit("Node configuration not consistent with \"bridge\" topology. Node %s has producers that fall into both halves of the bridged network" % (nodeName))
for _,bridgeNode in bridgeNodes.items():
bridgeNode["peers"]=[]
for prodName in producerNodes:
bridgeNode["peers"].append(prodName)
def connectGroup(group, producerNodes, bridgeNodes) :
groupStr=""
for nodeName in group:
groupStr+=nodeName+", "
prodNode=producerNodes[nodeName]
prodNode["peers"]=[i for i in group if i!=nodeName]
for bridgeName in bridgeNodes:
prodNode["peers"].append(bridgeName)
connectGroup(producerGroup1, producerNodes, bridgeNodes)
connectGroup(producerGroup2, producerNodes, bridgeNodes)
f=open(shapeFile,"w")
f.write(json.dumps(shapeFileObject, indent=4, sort_keys=True))
f.close()
cmdArr.append("--shape")
cmdArr.append(shapeFile)
else:
cmdArr.append("--shape")
cmdArr.append(topo)
Cluster.__LauncherCmdArr = cmdArr.copy()
s=" ".join(cmdArr)
Utils.Print("cmd: %s" % (s))
if 0 != subprocess.call(cmdArr):
Utils.Print("ERROR: Launcher failed to launch. failed cmd: %s" % (s))
return False
startedNodes=totalNodes-unstartedNodes
self.nodes=list(range(startedNodes)) # placeholder for cleanup purposes only
nodes=self.discoverLocalNodes(startedNodes, timeout=Utils.systemWaitTimeout)
if nodes is None or startedNodes != len(nodes):
Utils.Print("ERROR: Unable to validate %s instances, expected: %d, actual: %d" %
(Utils.EosServerName, startedNodes, len(nodes)))
return False
self.nodes=nodes
if unstartedNodes > 0:
self.unstartedNodes=self.discoverUnstartedLocalNodes(unstartedNodes, totalNodes)
biosNode=self.discoverBiosNode(timeout=Utils.systemWaitTimeout)
if not biosNode or not Utils.waitForBool(biosNode.checkPulse, Utils.systemWaitTimeout):
Utils.Print("ERROR: Bios node doesn't appear to be running...")
return False
if onlyBios:
self.nodes=[biosNode]
# ensure cluster node are inter-connected by ensuring everyone has block 1
Utils.Print("Cluster viability smoke test. Validate every cluster node has block 1. ")
if not self.waitOnClusterBlockNumSync(1):
Utils.Print("ERROR: Cluster doesn't seem to be in sync. Some nodes missing block 1")
return False
if PFSetupPolicy.hasPreactivateFeature(pfSetupPolicy):
Utils.Print("Activate Preactivate Feature.")
biosNode.activatePreactivateFeature()
if dontBootstrap:
Utils.Print("Skipping bootstrap.")
self.biosNode=biosNode
return True
Utils.Print("Bootstrap cluster.")
if not loadSystemContract:
useBiosBootFile=False #ensure we use Cluster.bootstrap
if onlyBios or not useBiosBootFile:
self.biosNode=self.bootstrap(biosNode, startedNodes, prodCount + sharedProducers, totalProducers, pfSetupPolicy, onlyBios, onlySetProds, loadSystemContract)
if self.biosNode is None:
Utils.Print("ERROR: Bootstrap failed.")
return False
else:
self.useBiosBootFile=True
self.biosNode=self.bios_bootstrap(biosNode, startedNodes, pfSetupPolicy)
if self.biosNode is None:
Utils.Print("ERROR: Bootstrap failed.")
return False
if self.biosNode is None:
Utils.Print("ERROR: Bootstrap failed.")
return False
# validate iniX accounts can be retrieved
producerKeys=Cluster.parseClusterKeys(totalNodes)
if producerKeys is None:
Utils.Print("ERROR: Unable to parse cluster info")
return False
def initAccountKeys(account, keys):
account.ownerPrivateKey=keys["private"]
account.ownerPublicKey=keys["public"]
account.activePrivateKey=keys["private"]
account.activePublicKey=keys["public"]
for name,_ in producerKeys.items():
account=Account(name)
initAccountKeys(account, producerKeys[name])
self.defProducerAccounts[name] = account
self.eosioAccount=self.defProducerAccounts["eosio"]
self.defproduceraAccount=self.defProducerAccounts["defproducera"]
self.defproducerbAccount=self.defProducerAccounts["defproducerb"]
return True
# Initialize the default nodes (at present just the root node)
def initializeNodes(self, defproduceraPrvtKey=None, defproducerbPrvtKey=None, onlyBios=False):
port=Cluster.__BiosPort if onlyBios else self.port
host=Cluster.__BiosHost if onlyBios else self.host
node=Node(host, port, walletMgr=self.walletMgr, enableMongo=self.enableMongo, mongoHost=self.mongoHost, mongoPort=self.mongoPort, mongoDb=self.mongoDb)
if Utils.Debug: Utils.Print("Node: %s", str(node))
node.checkPulse(exitOnError=True)
self.nodes=[node]
if defproduceraPrvtKey is not None:
self.defproduceraAccount.ownerPrivateKey=defproduceraPrvtKey
self.defproduceraAccount.activePrivateKey=defproduceraPrvtKey
if defproducerbPrvtKey is not None:
self.defproducerbAccount.ownerPrivateKey=defproducerbPrvtKey
self.defproducerbAccount.activePrivateKey=defproducerbPrvtKey
return True
# Initialize nodes from the Json nodes string
def initializeNodesFromJson(self, nodesJsonStr):
nodesObj= json.loads(nodesJsonStr)
if nodesObj is None:
Utils.Print("ERROR: Invalid Json string.")
return False
if "keys" in nodesObj:
keysMap=nodesObj["keys"]
if "defproduceraPrivateKey" in keysMap:
defproduceraPrivateKey=keysMap["defproduceraPrivateKey"]
self.defproduceraAccount.ownerPrivateKey=defproduceraPrivateKey
if "defproducerbPrivateKey" in keysMap:
defproducerbPrivateKey=keysMap["defproducerbPrivateKey"]
self.defproducerbAccount.ownerPrivateKey=defproducerbPrivateKey
nArr=nodesObj["nodes"]
nodes=[]
for n in nArr:
port=n["port"]
host=n["host"]
node=Node(host, port, walletMgr=self.walletMgr)
if Utils.Debug: Utils.Print("Node:", node)
node.checkPulse(exitOnError=True)
nodes.append(node)
self.nodes=nodes
return True
def setNodes(self, nodes):
"""manually set nodes, alternative to explicit launch"""
self.nodes=nodes
def waitOnClusterSync(self, timeout=None, blockType=BlockType.head, blockAdvancing=0):
"""Get head or irrevercible block on node 0, then ensure that block (or that block plus the
blockAdvancing) is present on every cluster node."""
assert(self.nodes)
assert(len(self.nodes) > 0)
node=self.nodes[0]
targetBlockNum=node.getBlockNum(blockType) #retrieve node 0's head or irrevercible block number
targetBlockNum+=blockAdvancing
if Utils.Debug:
Utils.Print("%s block number on root node: %d" % (blockType.type, targetBlockNum))
if targetBlockNum == -1:
return False
return self.waitOnClusterBlockNumSync(targetBlockNum, timeout)
def waitOnClusterBlockNumSync(self, targetBlockNum, timeout=None, blockType=BlockType.head):
"""Wait for all nodes to have targetBlockNum finalized."""
assert(self.nodes)
def doNodesHaveBlockNum(nodes, targetBlockNum, blockType, printCount):
ret=True
for node in nodes:
try:
if (not node.killed) and (not node.isBlockPresent(targetBlockNum, blockType=blockType)):
ret=False
break
except (TypeError) as _:
# This can happen if client connects before server is listening
ret=False
break
printCount+=1
if Utils.Debug and not ret and printCount%5==0:
blockNums=[]
for i in range(0, len(nodes)):
blockNums.append(nodes[i].getBlockNum())
Utils.Print("Cluster still not in sync, head blocks for nodes: [ %s ]" % (", ".join(blockNums)))
return ret
printCount=0
lam = lambda: doNodesHaveBlockNum(self.nodes, targetBlockNum, blockType, printCount)
ret=Utils.waitForBool(lam, timeout)
return ret
@staticmethod
def getClientVersion(verbose=False):
"""Returns client version (string)"""
p = re.compile(r'^Build version:\s(\w+)\n$')
try:
cmd="%s version client" % (Utils.EosClientPath)
if verbose: Utils.Print("cmd: %s" % (cmd))
response=Utils.checkOutput(cmd.split())
assert(response)
assert(isinstance(response, str))
if verbose: Utils.Print("response: <%s>" % (response))
m=p.match(response)
if m is None:
Utils.Print("ERROR: client version regex mismatch")
return None
verStr=m.group(1)
return verStr
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during client version query. %s" % (msg))
raise
@staticmethod
def createAccountKeys(count):
accounts=[]
p = re.compile('Private key: (.+)\nPublic key: (.+)\n', re.MULTILINE)
for _ in range(0, count):
try:
cmd="%s create key --to-console" % (Utils.EosClientPath)
if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
keyStr=Utils.checkOutput(cmd.split())
m=p.search(keyStr)
if m is None:
Utils.Print("ERROR: Owner key creation regex mismatch")
break
ownerPrivate=m.group(1)
ownerPublic=m.group(2)
cmd="%s create key --to-console" % (Utils.EosClientPath)
if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
keyStr=Utils.checkOutput(cmd.split())
m=p.match(keyStr)
if m is None:
Utils.Print("ERROR: Active key creation regex mismatch")
break
activePrivate=m.group(1)
activePublic=m.group(2)
name=''.join(random.choice(string.ascii_lowercase) for _ in range(12))
account=Account(name)
account.ownerPrivateKey=ownerPrivate
account.ownerPublicKey=ownerPublic
account.activePrivateKey=activePrivate
account.activePublicKey=activePublic
accounts.append(account)
if Utils.Debug: Utils.Print("name: %s, key(owner): ['%s', '%s], key(active): ['%s', '%s']" % (name, ownerPublic, ownerPrivate, activePublic, activePrivate))
except subprocess.CalledProcessError as ex:
msg=ex.output.decode("utf-8")
Utils.Print("ERROR: Exception during key creation. %s" % (msg))
break
if count != len(accounts):
Utils.Print("Account keys creation failed. Expected %d, actual: %d" % (count, len(accounts)))
return None
return accounts
# create account keys and import into wallet. Wallet initialization will be user responsibility
# also imports defproducera and defproducerb accounts
def populateWallet(self, accountsCount, wallet):
if self.walletMgr is None:
Utils.Print("ERROR: WalletMgr hasn't been initialized.")
return False
accounts=None
if accountsCount > 0:
Utils.Print ("Create account keys.")
accounts = self.createAccountKeys(accountsCount)
if accounts is None:
Utils.Print("Account keys creation failed.")
return False
Utils.Print("Importing keys for account %s into wallet %s." % (self.defproduceraAccount.name, wallet.name))
if not self.walletMgr.importKey(self.defproduceraAccount, wallet):
Utils.Print("ERROR: Failed to import key for account %s" % (self.defproduceraAccount.name))
return False
Utils.Print("Importing keys for account %s into wallet %s." % (self.defproducerbAccount.name, wallet.name))
if not self.walletMgr.importKey(self.defproducerbAccount, wallet):
Utils.Print("ERROR: Failed to import key for account %s" % (self.defproducerbAccount.name))
return False
for account in accounts:
Utils.Print("Importing keys for account %s into wallet %s." % (account.name, wallet.name))
if not self.walletMgr.importKey(account, wallet):
Utils.Print("ERROR: Failed to import key for account %s" % (account.name))
return False
self.accounts=accounts
return True
def getNode(self, nodeId=0, exitOnError=True):
if exitOnError and nodeId >= len(self.nodes):
Utils.cmdError("cluster never created node %d" % (nodeId))
Utils.errorExit("Failed to retrieve node %d" % (nodeId))
if exitOnError and self.nodes[nodeId] is None:
Utils.cmdError("cluster has None value for node %d" % (nodeId))
Utils.errorExit("Failed to retrieve node %d" % (nodeId))
return self.nodes[nodeId]
def getNodes(self):
return self.nodes
def launchUnstarted(self, numToLaunch=1, cachePopen=False):
assert(isinstance(numToLaunch, int))
assert(numToLaunch>0)
launchList=self.unstartedNodes[:numToLaunch]
del self.unstartedNodes[:numToLaunch]
for node in launchList:
# the node number is indexed off of the started nodes list
node.launchUnstarted(len(self.nodes), cachePopen=cachePopen)
self.nodes.append(node)
# Spread funds across accounts with transactions spread through cluster nodes.
# Validate transactions are synchronized on root node
def spreadFunds(self, source, accounts, amount=1):
assert(source)
assert(isinstance(source, Account))
assert(accounts)
assert(isinstance(accounts, list))
assert(len(accounts) > 0)
Utils.Print("len(accounts): %d" % (len(accounts)))
count=len(accounts)
transferAmount=(count*amount)+amount
transferAmountStr=Node.currencyIntToStr(transferAmount, CORE_SYMBOL)
node=self.nodes[0]
fromm=source
to=accounts[0]
Utils.Print("Transfer %s units from account %s to %s on eos server port %d" % (
transferAmountStr, fromm.name, to.name, node.port))
trans=node.transferFunds(fromm, to, transferAmountStr)
transId=Node.getTransId(trans)
if transId is None:
return False
if Utils.Debug: Utils.Print("Funds transfered on transaction id %s." % (transId))
nextEosIdx=-1
for i in range(0, count):
account=accounts[i]
nextInstanceFound=False
for _ in range(0, count):
#Utils.Print("nextEosIdx: %d, n: %d" % (nextEosIdx, n))
nextEosIdx=(nextEosIdx + 1)%count
if not self.nodes[nextEosIdx].killed:
#Utils.Print("nextEosIdx: %d" % (nextEosIdx))
nextInstanceFound=True
break
if nextInstanceFound is False:
Utils.Print("ERROR: No active nodes found.")
return False
#Utils.Print("nextEosIdx: %d, count: %d" % (nextEosIdx, count))
node=self.nodes[nextEosIdx]
if Utils.Debug: Utils.Print("Wait for transaction id %s on node port %d" % (transId, node.port))
if node.waitForTransInBlock(transId) is False:
Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, node.port))
return False
transferAmount -= amount
transferAmountStr=Node.currencyIntToStr(transferAmount, CORE_SYMBOL)
fromm=account
to=accounts[i+1] if i < (count-1) else source
Utils.Print("Transfer %s units from account %s to %s on eos server port %d." %
(transferAmountStr, fromm.name, to.name, node.port))
trans=node.transferFunds(fromm, to, transferAmountStr)
transId=Node.getTransId(trans)
if transId is None:
return False
if Utils.Debug: Utils.Print("Funds transfered on block num %s." % (transId))
# As an extra step wait for last transaction on the root node
node=self.nodes[0]
if Utils.Debug: Utils.Print("Wait for transaction id %s on node port %d" % (transId, node.port))
if node.waitForTransInBlock(transId) is False:
Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, node.port))
return False
return True
def validateSpreadFunds(self, initialBalances, transferAmount, source, accounts):
"""Given initial Balances, will validate each account has the expected balance based upon transferAmount.
This validation is repeated against every node in the cluster."""
assert(source)
assert(isinstance(source, Account))
assert(accounts)
assert(isinstance(accounts, list))
assert(len(accounts) > 0)
assert(initialBalances)
assert(isinstance(initialBalances, dict))
assert(isinstance(transferAmount, int))
for node in self.nodes:
if node.killed:
continue
if Utils.Debug: Utils.Print("Validate funds on %s server port %d." %
(Utils.EosServerName, node.port))
if node.validateFunds(initialBalances, transferAmount, source, accounts) is False:
Utils.Print("ERROR: Failed to validate funds on eos node port: %d" % (node.port))
return False
return True
def spreadFundsAndValidate(self, transferAmount=1):
"""Sprays 'transferAmount' funds across configured accounts and validates action. The spray is done in a trickle down fashion with account 1
receiving transferAmount*n SYS and forwarding x-transferAmount funds. Transfer actions are spread round-robin across the cluster to vaidate system cohesiveness."""
if Utils.Debug: Utils.Print("Get initial system balances.")
initialBalances=self.nodes[0].getEosBalances([self.defproduceraAccount] + self.accounts)
assert(initialBalances)
assert(isinstance(initialBalances, dict))
if False == self.spreadFunds(self.defproduceraAccount, self.accounts, transferAmount):
Utils.Print("ERROR: Failed to spread funds across nodes.")
return False
Utils.Print("Funds spread across all accounts. Now validate funds")
if False == self.validateSpreadFunds(initialBalances, transferAmount, self.defproduceraAccount, self.accounts):
Utils.Print("ERROR: Failed to validate funds transfer across nodes.")
return False
return True
def validateAccounts(self, accounts, testSysAccounts=True):
assert(len(self.nodes) > 0)
node=self.nodes[0]
myAccounts = []
if testSysAccounts:
myAccounts += [self.eosioAccount, self.defproduceraAccount, self.defproducerbAccount]
if accounts:
assert(isinstance(accounts, list))
myAccounts += accounts
node.validateAccounts(myAccounts)
def createAccountAndVerify(self, account, creator, stakedDeposit=1000, stakeNet=100, stakeCPU=100, buyRAM=10000):
"""create account, verify account and return transaction id"""
assert(len(self.nodes) > 0)
node=self.nodes[0]
trans=node.createInitializeAccount(account, creator, stakedDeposit, stakeNet=stakeNet, stakeCPU=stakeCPU, buyRAM=buyRAM, exitOnError=True)
assert(node.verifyAccount(account))
return trans
# # create account, verify account and return transaction id
# def createAccountAndVerify(self, account, creator, stakedDeposit=1000):
# if len(self.nodes) == 0:
# Utils.Print("ERROR: No nodes initialized.")
# return None
# node=self.nodes[0]
# transId=node.createAccount(account, creator, stakedDeposit)
# if transId is not None and node.verifyAccount(account) is not None:
# return transId
# return None
def createInitializeAccount(self, account, creatorAccount, stakedDeposit=1000, waitForTransBlock=False, stakeNet=100, stakeCPU=100, buyRAM=10000, exitOnError=False):
assert(len(self.nodes) > 0)
node=self.nodes[0]
trans=node.createInitializeAccount(account, creatorAccount, stakedDeposit, waitForTransBlock, stakeNet=stakeNet, stakeCPU=stakeCPU, buyRAM=buyRAM)
return trans
@staticmethod
def nodeNameToId(name):
r"""Convert node name to decimal id. Node name regex is "node_([\d]+)". "node_bios" is a special name which returns -1. Examples: node_00 => 0, node_21 => 21, node_bios => -1. """
if name == "node_bios":
return -1
m=re.search(r"node_([\d]+)", name)
return int(m.group(1))
@staticmethod
def parseProducerKeys(configFile, nodeName):
"""Parse node config file for producer keys. Returns dictionary. (Keys: account name; Values: dictionary objects (Keys: ["name", "node", "private","public"]; Values: account name, node id returned by nodeNameToId(nodeName), private key(string)and public key(string)))."""
configStr=None
with open(configFile, 'r') as f:
configStr=f.read()
pattern=r"^\s*private-key\s*=\W+(\w+)\W+(\w+)\W+$"
m=re.search(pattern, configStr, re.MULTILINE)
regMsg="None" if m is None else "NOT None"
if m is None:
if Utils.Debug: Utils.Print("Failed to find producer keys")
return None
pubKey=m.group(1)
privateKey=m.group(2)
pattern=r"^\s*producer-name\s*=\W*(\w+)\W*$"
matches=re.findall(pattern, configStr, re.MULTILINE)
if matches is None:
if Utils.Debug: Utils.Print("Failed to find producers.")
return None
producerKeys={}
for m in matches:
if Utils.Debug: Utils.Print ("Found producer : %s" % (m))
nodeId=Cluster.nodeNameToId(nodeName)
keys={"name": m, "node": nodeId, "private": privateKey, "public": pubKey}
producerKeys[m]=keys
return producerKeys
@staticmethod
def parseProducers(nodeNum):
"""Parse node config file for producers."""
configFile=Utils.getNodeConfigDir(nodeNum, "config.ini")
if Utils.Debug: Utils.Print("Parsing config file %s" % configFile)
configStr=None
with open(configFile, 'r') as f:
configStr=f.read()
pattern=r"^\s*producer-name\s*=\W*(\w+)\W*$"
producerMatches=re.findall(pattern, configStr, re.MULTILINE)
if producerMatches is None:
if Utils.Debug: Utils.Print("Failed to find producers.")
return None
return producerMatches
@staticmethod
def parseClusterKeys(totalNodes):
"""Parse cluster config file. Updates producer keys data members."""
configFile=Utils.getNodeConfigDir("bios", "config.ini")
if Utils.Debug: Utils.Print("Parsing config file %s" % configFile)
nodeName=Utils.nodeExtensionToName("bios")
producerKeys=Cluster.parseProducerKeys(configFile, nodeName)
if producerKeys is None:
Utils.Print("ERROR: Failed to parse eosio private keys from cluster config files.")
return None
for i in range(0, totalNodes):
configFile=Utils.getNodeConfigDir(i, "config.ini")
if Utils.Debug: Utils.Print("Parsing config file %s" % configFile)
nodeName=Utils.nodeExtensionToName(i)
keys=Cluster.parseProducerKeys(configFile, nodeName)
if keys is not None:
producerKeys.update(keys)
keyMsg="None" if keys is None else len(keys)
return producerKeys
def bios_bootstrap(self, biosNode, totalNodes, pfSetupPolicy, silent=False):
"""Bootstrap cluster using the bios_boot.sh script generated by eosio-launcher."""
Utils.Print("Starting cluster bootstrap.")
assert PFSetupPolicy.isValid(pfSetupPolicy)
cmd="bash bios_boot.sh"
if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
env = {
"BIOS_CONTRACT_PATH": "unittests/contracts/old_versions/v1.6.0-rc3/eosio.bios",
"FEATURE_DIGESTS": ""
}
if PFSetupPolicy.hasPreactivateFeature(pfSetupPolicy):
env["BIOS_CONTRACT_PATH"] = "unittests/contracts/eosio.bios"
if pfSetupPolicy == PFSetupPolicy.FULL:
allBuiltinProtocolFeatureDigests = biosNode.getAllBuiltinFeatureDigestsToPreactivate()
env["FEATURE_DIGESTS"] = " ".join(allBuiltinProtocolFeatureDigests)
Utils.Print("Set FEATURE_DIGESTS to: %s" % env["FEATURE_DIGESTS"])
if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull, env=env):
if not silent: Utils.Print("Launcher failed to shut down eos cluster.")
return None
p = re.compile('error', re.IGNORECASE)
with open(Cluster.__bootlog) as bootFile:
for line in bootFile:
if p.search(line):
Utils.Print("ERROR: bios_boot.sh script resulted in errors. See %s" % (Cluster.__bootlog))
Utils.Print(line)
return None
producerKeys=Cluster.parseClusterKeys(totalNodes)
# should have totalNodes node plus bios node
if producerKeys is None or len(producerKeys) < (totalNodes+1):
Utils.Print("ERROR: Failed to parse private keys from cluster config files.")
return None
self.walletMgr.killall()
self.walletMgr.cleanup()
if not self.walletMgr.launch():
Utils.Print("ERROR: Failed to launch bootstrap wallet.")
return None
ignWallet=self.walletMgr.create("ignition")
if ignWallet is None:
Utils.Print("ERROR: Failed to create ignition wallet.")
return None
eosioName="eosio"
eosioKeys=producerKeys[eosioName]
eosioAccount=Account(eosioName)
eosioAccount.ownerPrivateKey=eosioKeys["private"]
eosioAccount.ownerPublicKey=eosioKeys["public"]
eosioAccount.activePrivateKey=eosioKeys["private"]
eosioAccount.activePublicKey=eosioKeys["public"]
producerKeys.pop(eosioName)