github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/bddtests/steps/bdd_grpc_util.py (about)

     1  
     2  # Copyright IBM Corp. 2016 All Rights Reserved.
     3  #
     4  # Licensed under the Apache License, Version 2.0 (the "License");
     5  # you may not use this file except in compliance with the License.
     6  # You may obtain a copy of the License at
     7  #
     8  #      http://www.apache.org/licenses/LICENSE-2.0
     9  #
    10  # Unless required by applicable law or agreed to in writing, software
    11  # distributed under the License is distributed on an "AS IS" BASIS,
    12  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  # See the License for the specific language governing permissions and
    14  # limitations under the License.
    15  #
    16  
    17  import os
    18  import re
    19  import subprocess
    20  import devops_pb2
    21  import fabric_pb2
    22  import chaincode_pb2
    23  
    24  import bdd_test_util
    25  
    26  import grpc
    27  
    28  def getSecretForUserRegistration(userRegistration):
    29      return devops_pb2.Secret(enrollId=userRegistration.secretMsg['enrollId'],enrollSecret=userRegistration.secretMsg['enrollSecret'])
    30  
    31  def getTxResult(context, enrollId):
    32      '''Returns the TransactionResult using the enrollId supplied'''
    33      assert 'users' in context, "users not found in context. Did you register a user?"
    34      assert 'compose_containers' in context, "compose_containers not found in context"
    35  
    36      (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
    37      stub = devops_pb2.beta_create_Devops_stub(channel)
    38  
    39      txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID)
    40      response = stub.GetTransactionResult(txRequest, 2)
    41      assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user "{1}":  {2}'.format(userRegistration.composeService,enrollId, response.msg)
    42      # Now grab the TransactionResult from the Msg bytes
    43      txResult = fabric_pb2.TransactionResult()
    44      txResult.ParseFromString(response.msg)
    45      return txResult
    46  
    47  def getGRPCChannel(ipAddress):
    48      channel = grpc.insecure_channel("{0}:{1}".format(ipAddress, 7051), options = [('grpc.max_message_length', 100*1024*1024)])
    49      print("Returning GRPC for address: {0}".format(ipAddress))
    50      return channel
    51  
    52  def getGRPCChannelAndUser(context, enrollId):
    53      '''Returns a tuple of GRPC channel and UserRegistration instance.  The channel is open to the composeService that the user registered with.'''
    54      userRegistration = bdd_test_util.getUserRegistration(context, enrollId)
    55  
    56      # Get the IP address of the server that the user registered on
    57      ipAddress = bdd_test_util.ipFromContainerNamePart(userRegistration.composeService, context.compose_containers)
    58  
    59      channel = getGRPCChannel(ipAddress)
    60  
    61      return (channel, userRegistration)
    62  
    63  
    64  def getDeployment(context, ccAlias):
    65      '''Return a deployment with chaincode alias from prior deployment, or None if not found'''
    66      deployment = None
    67      if 'deployments' in context:
    68          pass
    69      else:
    70          context.deployments = {}
    71      if ccAlias in context.deployments:
    72          deployment = context.deployments[ccAlias]
    73      # else:
    74      #     raise Exception("Deployment alias not found: '{0}'.  Are you sure you have deployed a chaincode with this alias?".format(ccAlias))
    75      return deployment
    76  
    77  def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor):
    78      '''Deploy a chaincode with the specified alias for the specfied enrollId'''
    79      (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
    80      stub = devops_pb2.beta_create_Devops_stub(channel)
    81  
    82      # Make sure deployment alias does NOT already exist
    83      assert getDeployment(context, ccAlias) == None, "Deployment alias already exists: '{0}'.".format(ccAlias)
    84  
    85      args = getArgsFromContextForUser(context, enrollId)
    86      ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG,
    87          chaincodeID = chaincode_pb2.ChaincodeID(name="",path=chaincodePath),
    88          ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args))
    89      ccSpec.secureContext = userRegistration.getUserName()
    90      if 'metadata' in context:
    91          ccSpec.metadata = context.metadata
    92      try:
    93          ccDeploymentSpec = stub.Deploy(ccSpec, 60)
    94          ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name
    95          context.grpcChaincodeSpec = ccSpec
    96          context.deployments[ccAlias] = ccSpec
    97      except:
    98          del stub
    99          raise
   100  
   101  def invokeChaincode(context, enrollId, ccAlias, functionName):
   102      # Get the deployment for the supplied chaincode alias
   103      deployedCcSpec = getDeployment(context, ccAlias)
   104      assert deployedCcSpec != None, "Deployment NOT found for chaincode alias '{0}'".format(ccAlias)
   105  
   106      # Create a new ChaincodeSpec by copying the deployed one
   107      newChaincodeSpec = chaincode_pb2.ChaincodeSpec()
   108      newChaincodeSpec.CopyFrom(deployedCcSpec)
   109  
   110      # Update hte chaincodeSpec ctorMsg for invoke
   111      args = getArgsFromContextForUser(context, enrollId)
   112  
   113      chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args )
   114      newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput)
   115  
   116      ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec)
   117  
   118      (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
   119  
   120      stub = devops_pb2.beta_create_Devops_stub(channel)
   121      response = stub.Invoke(ccInvocationSpec,2)
   122      return response
   123  
   124  def getArgsFromContextForUser(context, enrollId):
   125      # Update the chaincodeSpec ctorMsg for invoke
   126      args = []
   127      if 'table' in context:
   128          if context.table:
   129              # There are function arguments
   130              userRegistration = bdd_test_util.getUserRegistration(context, enrollId)
   131              # Allow the user to specify expressions referencing tags in the args list
   132              pattern = re.compile('\{(.*)\}$')
   133              for arg in context.table[0].cells:
   134                  m = pattern.match(arg)
   135                  if m:
   136                      # tagName reference found in args list
   137                      tagName = m.groups()[0]
   138                      # make sure the tagName is found in the users tags
   139                      assert tagName in userRegistration.tags, "TagName '{0}' not found for user '{1}'".format(tagName, userRegistration.getUserName())
   140                      args.append(userRegistration.tags[tagName])
   141                  else:
   142                      #No tag referenced, pass the arg
   143                      args.append(arg)
   144      return args
   145  
   146  def toStringArray(items):
   147      itemsAsStr = []
   148      for item in items:
   149          if type(item) == str:
   150              itemsAsStr.append(item)
   151          elif type(item) == unicode:
   152              itemsAsStr.append(str(item))
   153          else:
   154              raise Exception("Error tring to convert to string: unexpected type '{0}'".format(type(item)))
   155      return itemsAsStr
   156  
   157