Cluster.py 61.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
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
14
import errno
15 16 17 18

from core_symbol import CORE_SYMBOL
from testUtils import Utils
from testUtils import Account
19
from Node import BlockType
20 21 22 23 24 25 26 27 28 29 30 31
from Node import Node
from WalletMgr import WalletMgr

# 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
32
    __LauncherCmdArr=[]
33
    __bootlog="eosio-ignition-wd/bootlog.txt"
34 35 36

    # pylint: disable=too-many-arguments
    # walletd [True|False] Is keosd running. If not load the wallet plugin
37
    def __init__(self, walletd=False, localCluster=True, host="localhost", port=8888, walletHost="localhost", walletPort=9899, enableMongo=False
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
                 , 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.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.walletEndpointArgs=""
        if self.walletd:
            self.walletEndpointArgs += " --wallet-url http://%s:%d" % (self.walletHost, self.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
76 77 78 79 80
        self.defProducerAccounts={}
        self.defproduceraAccount=self.defProducerAccounts["defproducera"]= Account("defproducera")
        self.defproducerbAccount=self.defProducerAccounts["defproducerb"]= Account("defproducerb")
        self.eosioAccount=self.defProducerAccounts["eosio"]= Account("eosio")

81 82 83 84 85
        self.defproduceraAccount.ownerPrivateKey=defproduceraPrvtKey
        self.defproduceraAccount.activePrivateKey=defproduceraPrvtKey
        self.defproducerbAccount.ownerPrivateKey=defproducerbPrvtKey
        self.defproducerbAccount.activePrivateKey=defproducerbPrvtKey

86
        self.useBiosBootFile=False
87
        self.filesToCleanup=[]
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102

    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

    # 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
103 104
    def launch(self, pnodes=1, totalNodes=1, prodCount=1, topo="mesh", p2pPlugin="net", delay=1, onlyBios=False, dontBootstrap=False,
               totalProducers=None, extraNodeosArgs=None, useBiosBootFile=True, specificExtraNodeosArgs=None):
105 106 107
        """Launch cluster.
        pnodes: producer nodes count
        totalNodes: producer + non-producer nodes count
108
        prodCount: producers per producer node count
109
        topo: cluster topology (as defined by launcher, and "bridge" shape that is specific to this launch method)
110 111
        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.
112
        onlyBios: When true, only loads the bios contract (and not more full bootstrapping).
113 114
        dontBootstrap: When true, don't do any bootstrapping at all.
        extraNodeosArgs: string of arguments to pass through to each nodoes instance (via --nodeos flag on launcher)
115 116 117
        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.
118 119
        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" }
120
        """
121 122
        assert(isinstance(topo, str))

123 124 125 126 127 128 129
        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.")

130 131
        producerFlag=""
        if totalProducers:
132
            assert(isinstance(totalProducers, (str,int)))
133
            producerFlag="--producers %s" % (totalProducers)
134

135
        tries = 30
136
        while not Utils.arePortsAvailable(set(range(self.port, self.port+totalNodes+1))):
137 138 139 140 141
            Utils.Print("ERROR: Another process is listening on nodeos default port. wait...")
            if tries == 0:
                return False
            tries = tries - 1
            time.sleep(2)
142

143 144
        cmd="%s -p %s -n %s -d %s -i %s -f --p2p-plugin %s %s" % (
            Utils.EosLauncherPath, pnodes, totalNodes, delay, datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3],
145 146 147 148 149
            p2pPlugin, producerFlag)
        cmdArr=cmd.split()
        if self.staging:
            cmdArr.append("--nogen")

150
        nodeosArgs="--max-transaction-time -1 --abi-serializer-max-time-ms 990000 --filter-on * --p2p-max-nodes-per-host %d" % (totalNodes)
151 152 153
        if not self.walletd:
            nodeosArgs += " --plugin eosio::wallet_api_plugin"
        if self.enableMongo:
C
Ciju John 已提交
154
            nodeosArgs += " --plugin eosio::mongo_db_plugin --mongodb-wipe --delete-all-blocks --mongodb-uri %s" % self.mongoUri
155 156 157
        if extraNodeosArgs is not None:
            assert(isinstance(extraNodeosArgs, str))
            nodeosArgs += extraNodeosArgs
158 159
        if Utils.Debug:
            nodeosArgs += " --contracts-console"
160 161 162 163 164

        if nodeosArgs:
            cmdArr.append("--nodeos")
            cmdArr.append(nodeosArgs)

165 166 167 168 169 170 171 172 173 174
        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)

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        genesisFile=open("./genesis.json", "r")
        genesisJsonStr=genesisFile.read()
        genesisFile.close()
        genesisObject=json.loads(genesisJsonStr)
        initialConfiguration=genesisObject["initial_configuration"]
        maxBlockCpuUsage=initialConfiguration.get("max_block_cpu_usage",200000)
        initialConfiguration["max_block_cpu_usage"]=maxBlockCpuUsage*10


        tempGenesisFileName="./tempGenesis.json"
        genesisFile=open(tempGenesisFileName,"w")
        genesisFile.write(json.dumps(genesisObject, indent=2))
        genesisFile.close()
        self.filesToCleanup.append(tempGenesisFileName)
        cmdArr.append("--genesis")
        cmdArr.append(tempGenesisFileName)

192 193 194
        # 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":
195 196
            shapeFilePrefix="shape_bridge"
            shapeFile=shapeFilePrefix+".json"
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            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"]
215 216 217 218 219 220 221

            numProducers=totalProducers if totalProducers is not None else totalNodes
            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)

222 223 224 225
            # will make a map to node object to make identification easier
            biosNodeObject=None
            bridgeNodes={}
            producerNodes={}
226
            producers=[]
227 228
            for append in range(ord('a'),ord('a')+numProducers):
                name="defproducer" + chr(append) 
229
                producers.append(name)
230 231 232 233 234 235 236 237 238 239 240 241

            # 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))
242

243 244 245 246 247 248 249 250 251 252 253 254
            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)
255 256
                shapeFileNodeProds=shapeFileNode["producers"]
                numNodeProducers=len(shapeFileNodeProds)
257 258 259 260
                if (numNodeProducers==0):
                    bridgeNodes[nodeName]=shapeFileNode
                else:
                    producerNodes[nodeName]=shapeFileNode
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
                    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:
                            errorExit("Node configuration not consistent with \"bridge\" topology. Node %s has producers that fall into both halves of the bridged network" % (nodeName))
285 286 287

            for _,bridgeNode in bridgeNodes.items():
                bridgeNode["peers"]=[]
288 289 290 291 292 293 294 295 296 297 298
                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)
299

300 301
            connectGroup(producerGroup1, producerNodes, bridgeNodes)
            connectGroup(producerGroup2, producerNodes, bridgeNodes)
302 303 304 305 306 307 308 309 310 311 312

            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)

313
        Cluster.__LauncherCmdArr = cmdArr.copy()
314

315 316 317
        s=" ".join(cmdArr)
        if Utils.Debug: Utils.Print("cmd: %s" % (s))
        if 0 != subprocess.call(cmdArr):
318
            Utils.Print("ERROR: Launcher failed to launch. failed cmd: %s" % (s))
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
            return False

        self.nodes=list(range(totalNodes)) # placeholder for cleanup purposes only

        nodes=self.discoverLocalNodes(totalNodes, timeout=Utils.systemWaitTimeout)
        if nodes is None or totalNodes != len(nodes):
            Utils.Print("ERROR: Unable to validate %s instances, expected: %d, actual: %d" %
                          (Utils.EosServerName, totalNodes, len(nodes)))
            return False

        self.nodes=nodes

        if onlyBios:
            biosNode=Node(Cluster.__BiosHost, Cluster.__BiosPort)
            biosNode.setWalletEndpointArgs(self.walletEndpointArgs)
            if not biosNode.checkPulse():
                Utils.Print("ERROR: Bios node doesn't appear to be running...")
                return False

            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 dontBootstrap:
            Utils.Print("Skipping bootstrap.")
            return True

        Utils.Print("Bootstrap cluster.")
351 352
        if self.walletMgr is None:
            self.walletMgr=WalletMgr(True)
353
        if onlyBios or not useBiosBootFile:
354
            self.biosNode=Cluster.bootstrap(totalNodes, prodCount, totalProducers, Cluster.__BiosHost, Cluster.__BiosPort, self.walletMgr, onlyBios)
355 356 357 358
            if self.biosNode is None:
                Utils.Print("ERROR: Bootstrap failed.")
                return False
        else:
359
            self.useBiosBootFile=True
360
            self.biosNode=Cluster.bios_bootstrap(totalNodes, Cluster.__BiosHost, Cluster.__BiosPort, self.walletMgr)
361 362 363
            if self.biosNode is None:
                Utils.Print("ERROR: Bootstrap failed.")
                return False
364

365 366
        self.discoverBiosNodePid()

367 368 369 370 371 372 373 374 375 376 377 378 379
        # 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"]

380
        for name,_ in producerKeys.items():
381 382 383 384 385 386 387
            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"]
388 389 390 391 392 393 394 395 396

        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, enableMongo=self.enableMongo, mongoHost=self.mongoHost, mongoPort=self.mongoPort, mongoDb=self.mongoDb)
        node.setWalletEndpointArgs(self.walletEndpointArgs)
397
        if Utils.Debug: Utils.Print("Node: %s", str(node))
398

399
        node.checkPulse(exitOnError=True)
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
        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)
            node.setWalletEndpointArgs(self.walletEndpointArgs)
            if Utils.Debug: Utils.Print("Node:", node)

439
            node.checkPulse(exitOnError=True)
440 441 442 443 444 445 446 447 448
            nodes.append(node)

        self.nodes=nodes
        return True

    def setNodes(self, nodes):
        """manually set nodes, alternative to explicit launch"""
        self.nodes=nodes

449 450 451
    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."""
452 453
        assert(self.nodes)
        assert(len(self.nodes) > 0)
454
        node=self.nodes[0]
455 456
        targetBlockNum=node.getBlockNum(blockType) #retrieve node 0's head or irrevercible block number
        targetBlockNum+=blockAdvancing 
457 458 459
        if Utils.Debug:
            Utils.Print("%s block number on root node: %d" % (blockType.type, targetBlockNum))
        if targetBlockNum == -1:
460 461
            return False

462
        return self.waitOnClusterBlockNumSync(targetBlockNum, timeout)
463

464
    def waitOnClusterBlockNumSync(self, targetBlockNum, timeout=None, blockType=BlockType.head):
465 466 467
        """Wait for all nodes to have targetBlockNum finalized."""
        assert(self.nodes)

468
        def doNodesHaveBlockNum(nodes, targetBlockNum, blockType):
469 470
            for node in nodes:
                try:
471
                    if (not node.killed) and (not node.isBlockPresent(targetBlockNum, blockType=blockType)):
472 473 474 475 476 477 478
                        return False
                except (TypeError) as _:
                    # This can happen if client connects before server is listening
                    return False

            return True

479
        lam = lambda: doNodesHaveBlockNum(self.nodes, targetBlockNum, blockType)
480 481 482
        ret=Utils.waitForBool(lam, timeout)
        return ret

483 484 485
    @staticmethod
    def getClientVersion(verbose=False):
        """Returns client version (string)"""
486
        p = re.compile(r'^Build version:\s(\w+)\n$')
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        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

506 507 508 509 510 511
    @staticmethod
    def createAccountKeys(count):
        accounts=[]
        p = re.compile('Private key: (.+)\nPublic key: (.+)\n', re.MULTILINE)
        for _ in range(0, count):
            try:
512
                cmd="%s create key --to-console" % (Utils.EosClientPath)
513 514 515 516 517 518 519 520 521 522
                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)

523
                cmd="%s create key --to-console" % (Utils.EosClientPath)
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
                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

588 589 590
    def getNode(self, nodeId=0, exitOnError=True):
        if exitOnError and nodeId >= len(self.nodes):
            Utils.cmdError("cluster never created node %d" % (nodeId))
591
            Utils.errorExit("Failed to retrieve node %d" % (nodeId))
592 593
        if exitOnError and self.nodes[nodeId] is None:
            Utils.cmdError("cluster has None value for node %d" % (nodeId))
594
            Utils.errorExit("Failed to retrieve node %d" % (nodeId))
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
        return self.nodes[nodeId]

    def getNodes(self):
        return self.nodes

    # 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:
645
                Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, node.port))
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
                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:
666
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, node.port))
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
            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)

730
    def createAccountAndVerify(self, account, creator, stakedDeposit=1000, stakeNet=100, stakeCPU=100, buyRAM=10000):
731 732 733
        """create account, verify account and return transaction id"""
        assert(len(self.nodes) > 0)
        node=self.nodes[0]
734
        trans=node.createInitializeAccount(account, creator, stakedDeposit, stakeNet=stakeNet, stakeCPU=stakeCPU, buyRAM=buyRAM, exitOnError=True)
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        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

751
    def createInitializeAccount(self, account, creatorAccount, stakedDeposit=1000, waitForTransBlock=False, stakeNet=100, stakeCPU=100, buyRAM=10000, exitOnError=False):
752 753
        assert(len(self.nodes) > 0)
        node=self.nodes[0]
754
        trans=node.createInitializeAccount(account, creatorAccount, stakedDeposit, waitForTransBlock, stakeNet=stakeNet, stakeCPU=stakeCPU, buyRAM=buyRAM)
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
        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)
777
        regMsg="None" if m is None else "NOT None"
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
        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

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    @staticmethod
    def parseProducers(nodeNum):
        """Parse node config file for producers."""

        node="node_%02d" % (nodeNum)
        configFile="etc/eosio/%s/config.ini" % (node)
        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

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    @staticmethod
    def parseClusterKeys(totalNodes):
        """Parse cluster config file. Updates producer keys data members."""

        node="node_bios"
        configFile="etc/eosio/%s/config.ini" % (node)
        if Utils.Debug: Utils.Print("Parsing config file %s" % configFile)
        producerKeys=Cluster.parseProducerKeys(configFile, node)
        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):
            node="node_%02d" % (i)
            configFile="etc/eosio/%s/config.ini" % (node)
            if Utils.Debug: Utils.Print("Parsing config file %s" % configFile)

            keys=Cluster.parseProducerKeys(configFile, node)
            if keys is not None:
                producerKeys.update(keys)
839
            keyMsg="None" if keys is None else len(keys)
840 841 842

        return producerKeys

843
    @staticmethod
844
    def bios_bootstrap(totalNodes, biosHost, biosPort, walletMgr):
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
        """Bootstrap cluster using the bios_boot.sh script generated by eosio-launcher."""

        Utils.Print("Starting cluster bootstrap.")
        biosNode=Node(biosHost, biosPort)
        if not biosNode.checkPulse():
            Utils.Print("ERROR: Bios node doesn't appear to be running...")
            return None

        cmd="bash bios_boot.sh"
        if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
        if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull):
            if not silent: Utils.Print("Launcher failed to shut down eos cluster.")
            return None

        p = re.compile('error', re.IGNORECASE)
860
        with open(Cluster.__bootlog) as bootFile:
861 862
            for line in bootFile:
                if p.search(line):
863
                    Utils.Print("ERROR: bios_boot.sh script resulted in errors. See %s" % (Cluster.__bootlog))
864
                    Utils.Print(line)
865 866 867 868 869 870 871 872 873 874 875 876 877 878
                    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

        walletMgr.killall()
        walletMgr.cleanup()

        if not walletMgr.launch():
            Utils.Print("ERROR: Failed to launch bootstrap wallet.")
            return None
879
        biosNode.setWalletEndpointArgs(walletMgr.getWalletEndpointArgs())
880

881 882 883 884
        ignWallet=walletMgr.create("ignition")
        if ignWallet is None:
            Utils.Print("ERROR: Failed to create ignition wallet.")
            return None
885

886 887 888 889 890 891 892 893 894 895 896 897
        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)

        if not walletMgr.importKey(eosioAccount, ignWallet):
            Utils.Print("ERROR: Failed to import %s account keys into ignition wallet." % (eosioName))
            return None
898

899 900 901 902 903 904 905 906 907 908 909 910 911
        initialFunds="1000000.0000 {0}".format(CORE_SYMBOL)
        Utils.Print("Transfer initial fund %s to individual accounts." % (initialFunds))
        trans=None
        contract="eosio.token"
        action="transfer"
        for name, keys in producerKeys.items():
            data="{\"from\":\"eosio\",\"to\":\"%s\",\"quantity\":\"%s\",\"memo\":\"%s\"}" % (name, initialFunds, "init transfer")
            opts="--permission eosio@active"
            if name != "eosio":
                trans=biosNode.pushMessage(contract, action, data, opts)
                if trans is None or not trans[0]:
                    Utils.Print("ERROR: Failed to transfer funds from eosio.token to %s." % (name))
                    return None
912

913
            Node.validateTransaction(trans[1])
914

915 916 917 918 919
        Utils.Print("Wait for last transfer transaction to become finalized.")
        transId=Node.getTransId(trans[1])
        if not biosNode.waitForTransInBlock(transId):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
            return None
920

921
        Utils.Print("Cluster bootstrap done.")
922 923 924

        return biosNode

925
    @staticmethod
926
    def bootstrap(totalNodes, prodCount, totalProducers, biosHost, biosPort, walletMgr, onlyBios=False):
927 928 929 930
        """Create 'prodCount' init accounts and deposits 10000000000 SYS in each. If prodCount is -1 will initialize all possible producers.
        Ensure nodes are inter-connected prior to this call. One way to validate this will be to check if every node has block 1."""

        Utils.Print("Starting cluster bootstrap.")
931 932 933
        if totalProducers is None:
            totalProducers=totalNodes

934 935 936
        biosNode=Node(biosHost, biosPort)
        if not biosNode.checkPulse():
            Utils.Print("ERROR: Bios node doesn't appear to be running...")
937
            return None
938 939 940

        producerKeys=Cluster.parseClusterKeys(totalNodes)
        # should have totalNodes node plus bios node
B
Brian Johnson 已提交
941 942 943 944 945
        if producerKeys is None:
            Utils.Print("ERROR: Failed to parse any producer keys from config files.")
            return None
        elif len(producerKeys) < (totalProducers+1):
            Utils.Print("ERROR: Failed to parse %d producer keys from cluster config files, only found %d." % (totalProducers+1,len(producerKeys)))
946
            return None
947 948 949 950 951 952

        walletMgr.killall()
        walletMgr.cleanup()

        if not walletMgr.launch():
            Utils.Print("ERROR: Failed to launch bootstrap wallet.")
953
            return None
954
        biosNode.setWalletEndpointArgs(walletMgr.getWalletEndpointArgs())
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
        ignWallet=walletMgr.create("ignition")

        eosioName="eosio"
        eosioKeys=producerKeys[eosioName]
        eosioAccount=Account(eosioName)
        eosioAccount.ownerPrivateKey=eosioKeys["private"]
        eosioAccount.ownerPublicKey=eosioKeys["public"]
        eosioAccount.activePrivateKey=eosioKeys["private"]
        eosioAccount.activePublicKey=eosioKeys["public"]

        if not walletMgr.importKey(eosioAccount, ignWallet):
            Utils.Print("ERROR: Failed to import %s account keys into ignition wallet." % (eosioName))
            return None

        contract="eosio.bios"
        contractDir="contracts/%s" % (contract)
        wasmFile="%s.wasm" % (contract)
        abiFile="%s.abi" % (contract)
        Utils.Print("Publish %s contract" % (contract))
        trans=biosNode.publishContract(eosioAccount.name, contractDir, wasmFile, abiFile, waitForTransBlock=True)
        if trans is None:
            Utils.Print("ERROR: Failed to publish contract %s." % (contract))
            return None

        Node.validateTransaction(trans)
981

982 983 984 985 986 987 988 989 990 991 992
        Utils.Print("Creating accounts: %s " % ", ".join(producerKeys.keys()))
        producerKeys.pop(eosioName)
        accounts=[]
        for name, keys in producerKeys.items():
            initx = None
            initx = Account(name)
            initx.ownerPrivateKey=keys["private"]
            initx.ownerPublicKey=keys["public"]
            initx.activePrivateKey=keys["private"]
            initx.activePublicKey=keys["public"]
            trans=biosNode.createAccount(initx, eosioAccount, 0)
993
            if trans is None:
994
                Utils.Print("ERROR: Failed to create account %s" % (name))
995
                return None
996
            Node.validateTransaction(trans)
997 998 999 1000 1001 1002 1003 1004 1005
            accounts.append(initx)

        transId=Node.getTransId(trans)
        if not biosNode.waitForTransInBlock(transId):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
            return None

        Utils.Print("Validating system accounts within bootstrap")
        biosNode.validateAccounts(accounts)
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        if not onlyBios:
            if prodCount == -1:
                setProdsFile="setprods.json"
                if Utils.Debug: Utils.Print("Reading in setprods file %s." % (setProdsFile))
                with open(setProdsFile, "r") as f:
                    setProdsStr=f.read()

                    Utils.Print("Setting producers.")
                    opts="--permission eosio@active"
                    myTrans=biosNode.pushMessage("eosio", "setprods", setProdsStr, opts)
                    if myTrans is None or not myTrans[0]:
                        Utils.Print("ERROR: Failed to set producers.")
                        return None
            else:
                counts=dict.fromkeys(range(totalNodes), 0) #initialize node prods count to 0
                setProdsStr='{"schedule": ['
                firstTime=True
                prodNames=[]
                for name, keys in producerKeys.items():
                    if counts[keys["node"]] >= prodCount:
                        continue
                    if firstTime:
                        firstTime = False
                    else:
                        setProdsStr += ','

                    setProdsStr += ' { "producer_name": "%s", "block_signing_key": "%s" }' % (keys["name"], keys["public"])
                    prodNames.append(keys["name"])
                    counts[keys["node"]] += 1

                setProdsStr += ' ] }'
                if Utils.Debug: Utils.Print("setprods: %s" % (setProdsStr))
                Utils.Print("Setting producers: %s." % (", ".join(prodNames)))
                opts="--permission eosio@active"
                # pylint: disable=redefined-variable-type
                trans=biosNode.pushMessage("eosio", "setprods", setProdsStr, opts)
                if trans is None or not trans[0]:
                    Utils.Print("ERROR: Failed to set producer %s." % (keys["name"]))
1045
                    return None
1046

1047
            trans=trans[1]
1048
            transId=Node.getTransId(trans)
1049 1050
            if not biosNode.waitForTransInBlock(transId):
                Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
1051
                return None
1052

1053 1054 1055 1056 1057 1058
            # wait for block production handover (essentially a block produced by anyone but eosio).
            lam = lambda: biosNode.getInfo(exitOnError=True)["head_block_producer"] != "eosio"
            ret=Utils.waitForBool(lam)
            if not ret:
                Utils.Print("ERROR: Block production handover failed.")
                return None
1059

1060 1061 1062 1063 1064 1065
        eosioTokenAccount=copy.deepcopy(eosioAccount)
        eosioTokenAccount.name="eosio.token"
        trans=biosNode.createAccount(eosioTokenAccount, eosioAccount, 0)
        if trans is None:
            Utils.Print("ERROR: Failed to create account %s" % (eosioTokenAccount.name))
            return None
1066

1067 1068 1069 1070 1071 1072
        eosioRamAccount=copy.deepcopy(eosioAccount)
        eosioRamAccount.name="eosio.ram"
        trans=biosNode.createAccount(eosioRamAccount, eosioAccount, 0)
        if trans is None:
            Utils.Print("ERROR: Failed to create account %s" % (eosioRamAccount.name))
            return None
1073

1074 1075 1076 1077 1078 1079
        eosioRamfeeAccount=copy.deepcopy(eosioAccount)
        eosioRamfeeAccount.name="eosio.ramfee"
        trans=biosNode.createAccount(eosioRamfeeAccount, eosioAccount, 0)
        if trans is None:
            Utils.Print("ERROR: Failed to create account %s" % (eosioRamfeeAccount.name))
            return None
1080

1081 1082 1083 1084 1085 1086
        eosioStakeAccount=copy.deepcopy(eosioAccount)
        eosioStakeAccount.name="eosio.stake"
        trans=biosNode.createAccount(eosioStakeAccount, eosioAccount, 0)
        if trans is None:
            Utils.Print("ERROR: Failed to create account %s" % (eosioStakeAccount.name))
            return None
1087

1088 1089 1090 1091 1092
        Node.validateTransaction(trans)
        transId=Node.getTransId(trans)
        if not biosNode.waitForTransInBlock(transId):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
            return None
1093

1094 1095 1096 1097 1098 1099 1100 1101 1102
        contract="eosio.token"
        contractDir="contracts/%s" % (contract)
        wasmFile="%s.wasm" % (contract)
        abiFile="%s.abi" % (contract)
        Utils.Print("Publish %s contract" % (contract))
        trans=biosNode.publishContract(eosioTokenAccount.name, contractDir, wasmFile, abiFile, waitForTransBlock=True)
        if trans is None:
            Utils.Print("ERROR: Failed to publish contract %s." % (contract))
            return None
1103

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        # Create currency0000, followed by issue currency0000
        contract=eosioTokenAccount.name
        Utils.Print("push create action to %s contract" % (contract))
        action="create"
        data="{\"issuer\":\"%s\",\"maximum_supply\":\"1000000000.0000 %s\",\"can_freeze\":\"0\",\"can_recall\":\"0\",\"can_whitelist\":\"0\"}" % (eosioTokenAccount.name, CORE_SYMBOL)
        opts="--permission %s@active" % (contract)
        trans=biosNode.pushMessage(contract, action, data, opts)
        if trans is None or not trans[0]:
            Utils.Print("ERROR: Failed to push create action to eosio contract.")
            return None
1114

1115 1116 1117 1118 1119
        Node.validateTransaction(trans[1])
        transId=Node.getTransId(trans[1])
        if not biosNode.waitForTransInBlock(transId):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
            return None
1120

1121 1122 1123 1124 1125 1126 1127 1128 1129
        contract=eosioTokenAccount.name
        Utils.Print("push issue action to %s contract" % (contract))
        action="issue"
        data="{\"to\":\"%s\",\"quantity\":\"1000000000.0000 %s\",\"memo\":\"initial issue\"}" % (eosioAccount.name, CORE_SYMBOL)
        opts="--permission %s@active" % (contract)
        trans=biosNode.pushMessage(contract, action, data, opts)
        if trans is None or not trans[0]:
            Utils.Print("ERROR: Failed to push issue action to eosio contract.")
            return None
1130

1131 1132 1133 1134 1135 1136 1137 1138 1139
        Node.validateTransaction(trans[1])
        Utils.Print("Wait for issue action transaction to become finalized.")
        transId=Node.getTransId(trans[1])
        # biosNode.waitForTransInBlock(transId)
        # guesstimating block finalization timeout. Two production rounds of 12 blocks per node, plus 60 seconds buffer
        timeout = .5 * 12 * 2 * len(producerKeys) + 60
        if not biosNode.waitForTransFinalization(transId, timeout=timeout):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a finalized block on server port %d." % (transId, biosNode.port))
            return None
1140

1141 1142 1143 1144 1145 1146 1147
        expectedAmount="1000000000.0000 {0}".format(CORE_SYMBOL)
        Utils.Print("Verify eosio issue, Expected: %s" % (expectedAmount))
        actualAmount=biosNode.getAccountEosBalanceStr(eosioAccount.name)
        if expectedAmount != actualAmount:
            Utils.Print("ERROR: Issue verification failed. Excepted %s, actual: %s" %
                        (expectedAmount, actualAmount))
            return None
1148

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
        contract="eosio.system"
        contractDir="contracts/%s" % (contract)
        wasmFile="%s.wasm" % (contract)
        abiFile="%s.abi" % (contract)
        Utils.Print("Publish %s contract" % (contract))
        trans=biosNode.publishContract(eosioAccount.name, contractDir, wasmFile, abiFile, waitForTransBlock=True)
        if trans is None:
            Utils.Print("ERROR: Failed to publish contract %s." % (contract))
            return None

        Node.validateTransaction(trans)
1160

1161 1162 1163 1164 1165 1166 1167 1168
        initialFunds="1000000.0000 {0}".format(CORE_SYMBOL)
        Utils.Print("Transfer initial fund %s to individual accounts." % (initialFunds))
        trans=None
        contract=eosioTokenAccount.name
        action="transfer"
        for name, keys in producerKeys.items():
            data="{\"from\":\"%s\",\"to\":\"%s\",\"quantity\":\"%s\",\"memo\":\"%s\"}" % (eosioAccount.name, name, initialFunds, "init transfer")
            opts="--permission %s@active" % (eosioAccount.name)
1169 1170
            trans=biosNode.pushMessage(contract, action, data, opts)
            if trans is None or not trans[0]:
1171
                Utils.Print("ERROR: Failed to transfer funds from %s to %s." % (eosioTokenAccount.name, name))
1172
                return None
1173 1174 1175

            Node.validateTransaction(trans[1])

1176 1177 1178 1179 1180
        Utils.Print("Wait for last transfer transaction to become finalized.")
        transId=Node.getTransId(trans[1])
        if not biosNode.waitForTransInBlock(transId):
            Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, biosNode.port))
            return None
1181

1182
        Utils.Print("Cluster bootstrap done.")
1183

1184
        return biosNode
1185

1186 1187
    @staticmethod
    def pgrepEosServers(timeout=None):
1188
        cmd=Utils.pgrepCmd(Utils.EosServerName)
1189 1190 1191 1192 1193 1194 1195

        def myFunc():
            psOut=None
            try:
                if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
                psOut=Utils.checkOutput(cmd.split())
                return psOut
1196 1197 1198 1199
            except subprocess.CalledProcessError as ex:
                msg=ex.output.decode("utf-8")
                Utils.Print("ERROR: call of \"%s\" failed. %s" % (cmd, msg))
                return None
1200 1201
            return None

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        return Utils.waitForObj(myFunc, timeout)

    @staticmethod
    def pgrepEosServerPattern(nodeInstance):
        if isinstance(nodeInstance, str):
            return r"[\n]?(\d+) (.* --data-dir var/lib/node_%s .*)\n" % nodeInstance
        else:
            nodeInstanceStr="%02d" % nodeInstance
            return Cluster.pgrepEosServerPattern(nodeInstanceStr)

    # Populates list of EosInstanceInfo objects, matched to actual running instances
    def discoverLocalNodes(self, totalNodes, timeout=None):
        nodes=[]

        psOut=Cluster.pgrepEosServers(timeout)
1217 1218 1219 1220
        if psOut is None:
            Utils.Print("ERROR: No nodes discovered.")
            return nodes

1221 1222 1223 1224 1225
        if len(psOut) < 6660:
            psOutDisplay=psOut
        else:
            psOutDisplay=psOut[:6660]+"..."
        if Utils.Debug: Utils.Print("pgrep output: \"%s\"" % psOutDisplay)
1226
        for i in range(0, totalNodes):
1227
            pattern=Cluster.pgrepEosServerPattern(i)
1228 1229 1230 1231 1232 1233 1234 1235 1236
            m=re.search(pattern, psOut, re.MULTILINE)
            if m is None:
                Utils.Print("ERROR: Failed to find %s pid. Pattern %s" % (Utils.EosServerName, pattern))
                break
            instance=Node(self.host, self.port + i, pid=int(m.group(1)), cmd=m.group(2), enableMongo=self.enableMongo, mongoHost=self.mongoHost, mongoPort=self.mongoPort, mongoDb=self.mongoDb)
            instance.setWalletEndpointArgs(self.walletEndpointArgs)
            if Utils.Debug: Utils.Print("Node>", instance)
            nodes.append(instance)

1237
        if Utils.Debug: Utils.Print("Found %d nodes" % (len(nodes)))
1238 1239
        return nodes

1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    def discoverBiosNodePid(self, timeout=None):
        psOut=Cluster.pgrepEosServers(timeout=timeout)
        pattern=Cluster.pgrepEosServerPattern("bios")
        Utils.Print("pattern={\n%s\n}, psOut=\n%s\n" % (pattern,psOut))
        m=re.search(pattern, psOut, re.MULTILINE)
        if m is None:
            Utils.Print("ERROR: Failed to find %s pid. Pattern %s" % (Utils.EosServerName, pattern))
        else:
            self.biosNode.pid=int(m.group(1))

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    # Kills a percentange of Eos instances starting from the tail and update eosInstanceInfos state
    def killSomeEosInstances(self, killCount, killSignalStr=Utils.SigKillTag):
        killSignal=signal.SIGKILL
        if killSignalStr == Utils.SigTermTag:
            killSignal=signal.SIGTERM
        Utils.Print("Kill %d %s instances with signal %s." % (killCount, Utils.EosServerName, killSignal))

        killedCount=0
        for node in reversed(self.nodes):
            if not node.kill(killSignal):
                return False

            killedCount += 1
            if killedCount >= killCount:
                break

        time.sleep(1) # Give processes time to stand down
        return True

    def relaunchEosInstances(self):

        chainArg=self.__chainSyncStrategy.arg

        newChain= False if self.__chainSyncStrategy.name in [Utils.SyncHardReplayTag, Utils.SyncNoneTag] else True
        for i in range(0, len(self.nodes)):
            node=self.nodes[i]
            if node.killed and not node.relaunch(i, chainArg, newChain=newChain):
                return False

        return True

    @staticmethod
    def dumpErrorDetailImpl(fileName):
        Utils.Print("=================================================================")
        Utils.Print("Contents of %s:" % (fileName))
        if os.path.exists(fileName):
            with open(fileName, "r") as f:
                shutil.copyfileobj(f, sys.stdout)
        else:
            Utils.Print("File %s not found." % (fileName))

    def dumpErrorDetails(self):
        fileName="etc/eosio/node_bios/config.ini"
        Cluster.dumpErrorDetailImpl(fileName)
        fileName="var/lib/node_bios/stderr.txt"
        Cluster.dumpErrorDetailImpl(fileName)

        for i in range(0, len(self.nodes)):
            fileName="etc/eosio/node_%02d/config.ini" % (i)
            Cluster.dumpErrorDetailImpl(fileName)
            fileName="var/lib/node_%02d/stderr.txt" % (i)
            Cluster.dumpErrorDetailImpl(fileName)

1303 1304 1305
        if self.useBiosBootFile:
            Cluster.dumpErrorDetailImpl(Cluster.__bootlog)

1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    def killall(self, silent=True, allInstances=False):
        """Kill cluster nodeos instances. allInstances will kill all nodeos instances running on the system."""
        cmd="%s -k 9" % (Utils.EosLauncherPath)
        if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
        if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull):
            if not silent: Utils.Print("Launcher failed to shut down eos cluster.")

        if allInstances:
            # ocassionally the launcher cannot kill the eos server
            cmd="pkill -9 %s" % (Utils.EosServerName)
            if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
            if 0 != subprocess.call(cmd.split(), stdout=Utils.FNull):
                if not silent: Utils.Print("Failed to shut down eos cluster.")

        # another explicit nodes shutdown
        for node in self.nodes:
            try:
                if node.pid is not None:
                    os.kill(node.pid, signal.SIGKILL)
            except OSError as _:
                pass

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    def bounce(self, nodes, silent=True):
        """Bounces nodeos instances as indicated by parameter nodes.
        nodes should take the form of a comma-separated list as accepted by the launcher --bounce command (e.g. '00' or '00,01')"""
        cmdArr = Cluster.__LauncherCmdArr.copy()
        cmdArr.append("--bounce")
        cmdArr.append(nodes)
        cmd=" ".join(cmdArr)
        if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
        if 0 != subprocess.call(cmdArr):
            if not silent: Utils.Print("Launcher failed to bounce nodes: %s." % (nodes))
            return False
        return True

    def down(self, nodes, silent=True):
        """Brings down nodeos instances as indicated by parameter nodes.
        nodes should take the form of a comma-separated list as accepted by the launcher --bounce command (e.g. '00' or '00,01')"""
        cmdArr = Cluster.__LauncherCmdArr.copy()
        cmdArr.append("--down")
        cmdArr.append(nodes)
        cmd=" ".join(cmdArr)
        if Utils.Debug: Utils.Print("cmd: %s" % (cmd))
        if 0 != subprocess.call(cmdArr):
            if not silent: Utils.Print("Launcher failed to take down nodes: %s." % (nodes))
            return False
        return True

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    def isMongodDbRunning(self):
        cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
        subcommand="db.version()"
        if Utils.Debug: Utils.Print("echo %s | %s" % (subcommand, cmd))
        ret,outs,errs=Node.stdinAndCheckOutput(cmd.split(), subcommand)
        if ret is not 0:
            Utils.Print("ERROR: Failed to check database version: %s" % (Node.byteArrToStr(errs)) )
            return False
        if Utils.Debug: Utils.Print("MongoDb response: %s" % (outs))
        return True

    def waitForNextBlock(self, timeout=None):
        if timeout is None:
            timeout=Utils.systemWaitTimeout
        node=self.nodes[0]
        return node.waitForNextBlock(timeout)

    def cleanup(self):
        for f in glob.glob("var/lib/node_*"):
            shutil.rmtree(f)
        for f in glob.glob("etc/eosio/node_*"):
            shutil.rmtree(f)

1377 1378 1379
        for f in self.filesToCleanup:
            os.remove(f)

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        if self.enableMongo:
            cmd="%s %s" % (Utils.MongoPath, self.mongoEndpointArgs)
            subcommand="db.dropDatabase()"
            if Utils.Debug: Utils.Print("echo %s | %s" % (subcommand, cmd))
            ret,_,errs=Node.stdinAndCheckOutput(cmd.split(), subcommand)
            if ret is not 0:
                Utils.Print("ERROR: Failed to drop database: %s" % (Node.byteArrToStr(errs)) )


    # Create accounts and validates that the last transaction is received on root node
    def createAccounts(self, creator, waitForTransBlock=True, stakedDeposit=1000):
        if self.accounts is None:
            return True

        transId=None
        for account in self.accounts:
            if Utils.Debug: Utils.Print("Create account %s." % (account.name))
            trans=self.createAccountAndVerify(account, creator, stakedDeposit)
            if trans is None:
                Utils.Print("ERROR: Failed to create account %s." % (account.name))
                return False
            if Utils.Debug: Utils.Print("Account %s created." % (account.name))
            transId=Node.getTransId(trans)

        if waitForTransBlock and transId is not None:
            node=self.nodes[0]
            if Utils.Debug: Utils.Print("Wait for transaction id %s on server port %d." % ( transId, node.port))
            if node.waitForTransInBlock(transId) is False:
1408
                Utils.Print("ERROR: Failed to validate transaction %s got rolled into a block on server port %d." % (transId, node.port))
1409 1410 1411 1412
                return False

        return True

1413 1414 1415 1416 1417 1418 1419
    def getInfos(self, silentErrors=False, exitOnError=False):
        infos=[]
        for node in self.nodes:
            infos.append(node.getInfo(silentErrors=silentErrors, exitOnError=exitOnError))

        return infos

1420 1421 1422 1423 1424
    def reportStatus(self):
        if hasattr(self, "biosNode") and self.biosNode is not None:
            self.biosNode.reportStatus()
        if hasattr(self, "nodes"): 
            for node in self.nodes:
K
Kevin Heifner 已提交
1425 1426 1427 1428
                try:
                    node.reportStatus()
                except:
                    Utils.Print("No reportStatus")