github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/test/feature/steps/endorser_util.py (about)

     1  # Copyright IBM Corp. 2017 All Rights Reserved.
     2  #
     3  # Licensed under the Apache License, Version 2.0 (the "License");
     4  # you may not use this file except in compliance with the License.
     5  # You may obtain a copy of the License at
     6  #
     7  #      http://www.apache.org/licenses/LICENSE-2.0
     8  #
     9  # Unless required by applicable law or agreed to in writing, software
    10  # distributed under the License is distributed on an "AS IS" BASIS,
    11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  # See the License for the specific language governing permissions and
    13  # limitations under the License.
    14  #
    15  
    16  import os
    17  import sys
    18  import subprocess
    19  import time
    20  
    21  try:
    22      pbFilePath = "../../bddtests"
    23      sys.path.insert(0, pbFilePath)
    24      from peer import chaincode_pb2
    25  except:
    26      print("ERROR! Unable to import the protobuf libraries from the hyperledger/fabric/bddtests directory: {0}".format(sys.exc_info()[0]))
    27      sys.exit(1)
    28  
    29  # The default channel ID
    30  SYS_CHANNEL_ID = "behavesyschan"
    31  TEST_CHANNEL_ID = "behavesystest"
    32  
    33  
    34  def get_chaincode_deploy_spec(projectDir, ccType, path, name, args):
    35      subprocess.call(["peer", "chaincode", "package",
    36                       "-n", name,
    37                       "-c", '{"Args":{0}}'.format(args),
    38                       "-p", path,
    39                       "configs/{0}/test.file".format(projectDir)], shell=True)
    40      ccDeploymentSpec = chaincode_pb2.ChaincodeDeploymentSpec()
    41      with open("test.file", 'rb') as f:
    42          ccDeploymentSpec.ParseFromString(f.read())
    43      return ccDeploymentSpec
    44  
    45  
    46  def install_chaincode(context, chaincode, peers):
    47      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
    48      output = {}
    49      for peer in peers:
    50          peerParts = peer.split('.')
    51          org = '.'.join(peerParts[1:])
    52          command = ["/bin/bash", "-c",
    53                     '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/{1}/users/Admin@{1}/msp'.format(configDir, org),
    54                     'CORE_PEER_LOCALMSPID={0}'.format(org),
    55                     'CORE_PEER_ID={0}'.format(peer),
    56                     'CORE_PEER_ADDRESS={0}:7051'.format(peer),
    57                     "peer", "chaincode", "install",
    58                     #"--lang", chaincode['language'],
    59                     "--name", chaincode['name'],
    60                     "--version", str(chaincode.get('version', 0)),
    61                     #"--channelID", str(chaincode.get('channelID', TEST_CHANNEL_ID)),
    62                     "--path", chaincode['path']]
    63          if "orderers" in chaincode:
    64              command = command + ["--orderer", '{0}:7050'.format(chaincode["orderers"][0])]
    65          if "user" in chaincode:
    66              command = command + ["--username", chaincode["user"]]
    67          if "policy" in chaincode:
    68              command = command + ["--policy", chaincode["policy"]]
    69          command.append('"')
    70          ret = context.composition.docker_exec(command, ['cli'])
    71          output[peer] = ret['cli']
    72  #        assert "Error occurred" not in str(ret['cli']), str(ret['cli'])
    73      print("[{0}]: {1}".format(" ".join(command), output))
    74      return output
    75  
    76  
    77  def instantiate_chaincode(context, chaincode, containers):
    78      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
    79      args = chaincode.get('args', '[]').replace('"', r'\"')
    80      command = ["/bin/bash", "-c",
    81                 '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp'.format(configDir),
    82                 'CORE_PEER_TLS_ROOTCERT_FILE={0}/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt'.format(configDir),
    83                 'CORE_PEER_LOCALMSPID=org1.example.com',
    84                 'CORE_PEER_ID=peer0.org1.example.com',
    85                 'CORE_PEER_ADDRESS=peer0.org1.example.com:7051',
    86                 "peer", "chaincode", "instantiate",
    87                 #"--lang", chaincode['language'],
    88                 "--name", chaincode['name'],
    89                 "--version", str(chaincode.get('version', 0)),
    90                 "--channelID", str(chaincode.get('channelID', TEST_CHANNEL_ID)),
    91                 "--ctor", r"""'{\"Args\": %s}'""" % (args)]
    92      if "orderers" in chaincode:
    93          command = command + ["--orderer", '{0}:7050'.format(chaincode["orderers"][0])]
    94      if "user" in chaincode:
    95          command = command + ["--username", chaincode["user"]]
    96      if "policy" in chaincode:
    97          command = command + ["--policy", chaincode["policy"]]
    98      command.append('"')
    99      ret = context.composition.docker_exec(command, ['peer0.org1.example.com'])
   100  #    assert "Error occurred" not in str(ret['peer0.org1.example.com']), str(ret['peer0.org1.example.com'])
   101      print("[{0}]: {1}".format(" ".join(command), ret))
   102      return ret
   103  
   104  
   105  def create_channel(context, containers, orderers, channelId=TEST_CHANNEL_ID):
   106      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
   107      ret = context.composition.docker_exec(["ls", configDir], containers)
   108  
   109      command = ["/bin/bash", "-c",
   110                 '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp'.format(configDir),
   111                 'CORE_PEER_LOCALMSPID=org1.example.com',
   112                 'CORE_PEER_ID=peer0.org1.example.com',
   113                 'CORE_PEER_ADDRESS=peer0.org1.example.com:7051',
   114                 "peer", "channel", "create",
   115                 "--file", "/var/hyperledger/configs/{0}/{1}.tx".format(context.composition.projectName, channelId),
   116                 "--channelID", channelId,
   117                 "--timeout", "120", # This sets the timeout for the channel creation instead of the default 5 seconds
   118                 "--orderer", '{0}:7050"'.format(orderers[0])]
   119      print("Create command: {0}".format(command))
   120      output = context.composition.docker_exec(command, ['cli'])
   121  
   122  #    for item in output:
   123  #        assert "Error occurred" not in str(output[item]), str(output[item])
   124  
   125      # For now, copy the channel block to the config directory
   126      output = context.composition.docker_exec(["cp",
   127                                                "{0}.block".format(channelId),
   128                                                configDir],
   129                                               ['cli'])
   130      #output = context.composition.docker_exec(["ls", configDir], ['cli'])
   131      #print("Create: {0}".format(output))
   132      print("[{0}]: {1}".format(" ".join(command), output))
   133      return output
   134  
   135  
   136  def fetch_channel(context, peers, orderers, channelId=TEST_CHANNEL_ID):
   137      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
   138      for peer in peers:
   139          peerParts = peer.split('.')
   140          org = '.'.join(peerParts[1:])
   141          command = ["/bin/bash", "-c",
   142                     '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/{1}/users/Admin@{1}/msp'.format(configDir, org),
   143                     "peer", "channel", "fetch", "config",
   144                     "/var/hyperledger/configs/{0}/{1}.block".format(context.composition.projectName, channelId),
   145                     "--file", "/var/hyperledger/configs/{0}/{1}.tx".format(context.composition.projectName, channelId),
   146                     "--channelID", channelId,
   147                     "--orderer", '{0}:7050"'.format(orderers[0])]
   148          output = context.composition.docker_exec(command, [peer])
   149          print("Fetch: {0}".format(str(output)))
   150  #        assert "Error occurred" not in str(output[peer]), str(output[peer])
   151      print("[{0}]: {1}".format(" ".join(command), output))
   152      return output
   153  
   154  
   155  def join_channel(context, peers, orderers, channelId=TEST_CHANNEL_ID):
   156      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
   157  
   158      for peer in peers:
   159          peerParts = peer.split('.')
   160          org = '.'.join(peerParts[1:])
   161          command = ["/bin/bash", "-c",
   162                     '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/{1}/users/Admin@{1}/msp'.format(configDir, org),
   163                     "peer", "channel", "join",
   164                     "--blockpath", '/var/hyperledger/configs/{0}/{1}.block"'.format(context.composition.projectName, channelId)]
   165          count = 0
   166          output = "Error"
   167          while count < 5 and "Error" in output:
   168              output = context.composition.docker_exec(command, [peer])
   169              #print("Join: {0}".format(str(output)))
   170              time.sleep(2)
   171              count = count + 1
   172              output = output[peer]
   173  
   174          # If the LedgerID doesn't already exist check for other errors
   175  #        if "due to LedgerID already exists" not in output:
   176  #            assert "Error occurred" not in str(output), str(output)
   177      print("[{0}]: {1}".format(" ".join(command), output))
   178      return output
   179  
   180  
   181  def invoke_chaincode(context, chaincode, orderers, peer, channelId=TEST_CHANNEL_ID):
   182      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
   183      args = chaincode.get('args', '[]').replace('"', r'\"')
   184      peerParts = peer.split('.')
   185      org = '.'.join(peerParts[1:])
   186      command = ["/bin/bash", "-c",
   187                 '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/{1}/users/Admin@{1}/msp'.format(configDir, org),
   188                 "peer", "chaincode", "invoke",
   189                 "--name", chaincode['name'],
   190                 "--ctor", r"""'{\"Args\": %s}'""" % (args),
   191                 "--channelID", channelId,
   192                 "--orderer", '{0}:7050"'.format(orderers[0])]
   193      output = context.composition.docker_exec(command, [peer])
   194      print("Invoke[{0}]: {1}".format(" ".join(command), str(output)))
   195      #assert "Error occurred" not in output[peer], output[peer]
   196      return output
   197  
   198  
   199  def query_chaincode(context, chaincode, peer, channelId=TEST_CHANNEL_ID):
   200      configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName)
   201      peerParts = peer.split('.')
   202      org = '.'.join(peerParts[1:])
   203      args = chaincode.get('args', '[]').replace('"', r'\"')
   204      command = ["/bin/bash", "-c",
   205                 '"CORE_PEER_MSPCONFIGPATH={0}/peerOrganizations/{1}/users/Admin@{1}/msp'.format(configDir, org),
   206                 'CORE_PEER_TLS_ROOTCERT_FILE={0}/peerOrganizations/{1}/peers/{2}/tls/ca.crt'.format(configDir, org, peer),
   207                 "peer", "chaincode", "query",
   208                 "--name", chaincode['name'],
   209                 "--ctor", r"""'{\"Args\": %s}'""" % (args),
   210                 "--channelID", channelId, '"']
   211      print("Query Exec command: {0}".format(" ".join(command)))
   212      return context.composition.docker_exec(command, [peer])
   213  
   214  
   215  def get_orderers(context):
   216      orderers = []
   217      for container in context.composition.collectServiceNames():
   218          if container.startswith("orderer"):
   219              orderers.append(container)
   220      return orderers
   221  
   222  
   223  def get_peers(context):
   224      peers = []
   225      for container in context.composition.collectServiceNames():
   226          if container.startswith("peer"):
   227              peers.append(container)
   228      return peers
   229  
   230  
   231  def deploy_chaincode(context, chaincode, containers, channelId=TEST_CHANNEL_ID):
   232      for container in containers:
   233          assert container in context.composition.collectServiceNames(), "Unknown component '{0}'".format(container)
   234  
   235      orderers = get_orderers(context)
   236      peers = get_peers(context)
   237      assert orderers != [], "There are no active orderers in this network"
   238  
   239      chaincode.update({"orderers": orderers,
   240                        "channelID": channelId,
   241                        })
   242      create_channel(context, containers, orderers, channelId)
   243      #fetch_channel(context, peers, orderers, channelId)
   244      join_channel(context, peers, orderers, channelId)
   245      install_chaincode(context, chaincode, peers)
   246      instantiate_chaincode(context, chaincode, containers)