Exemplo n.º 1
0
def peer0DataPath(filename, service_name):
    try:
        f = open(filename)

        for dataNetwork in yaml.load_all(f):
            if dataNetwork['apiVersion'] == 'v1':
                data2 = dataNetwork
                continue
            else:
                data1 = dataNetwork
                volume = dataNetwork['spec']['template']['spec']['containers'][
                    0]['volumeMounts']
                volume.append(
                    dict(mountPath='/var/hyperledger/production',
                         name='peerdata',
                         subPath=service_name))
    except:
        raise BadRequest(msg="{}.yaml datas set error.".format(service_name))

    try:
        data = [data1, data2]
        dataread = [i for i in data]
        with open(filename, 'w') as f:
            yaml.dump_all(dataread, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()
Exemplo n.º 2
0
def dump_crypto_config_yaml_file(filepath, peer_org_dicts, orderer_org_dicts):
    listOrderer = []
    listPeer = []

    try:
        dataNetwork = dict(OrdererOrgs=listOrderer, PeerOrgs=listPeer)

        for each_peer in peer_org_dicts:
            if each_peer['ca']:
                ca = dict(Country=each_peer['ca']['country'],
                          Locality=each_peer['ca']['locality'],
                          Province=each_peer['ca']['province'])
            else:
                ca = {}
            listPeer.append(
                dict(Domain='{}.{}'.format(each_peer['name'],
                                           each_peer['domain']),
                     Name=each_peer['name'][0:1].upper() +
                     each_peer['name'][1:],
                     CA=ca,
                     Template=dict(Count=each_peer['peerNum']),
                     EnableNodeOUs=each_peer['enableNodeOUs']))

        for each_orderer in orderer_org_dicts:
            if each_orderer['ca']:
                ca = dict(Country=each_orderer['ca']['country'],
                          Locality=each_orderer['ca']['locality'],
                          Province=each_orderer['ca']['province'])
            else:
                ca = {}
            specs = []
            for orderhost in each_orderer['ordererHostnames']:
                specs.append(dict(Hostname=orderhost))
            listOrderer.append(
                dict(Domain=each_orderer['domain'],
                     Name=each_orderer['name'][0:1].upper() +
                     each_orderer['name'][1:],
                     CA=ca,
                     Specs=specs))

        filename = '{}/crypto-config.yaml'.format(filepath)
    except:
        raise BadRequest(msg="cryptoconfit.yaml datas set error")

    try:
        f = open(filename, 'w', encoding='utf-8')
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        yaml.dump(dataNetwork, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()
Exemplo n.º 3
0
def creat_secret_key_files():
    # if has exist, just return, if not, create them.
    pri = '{}private.key'.format(CELLO_SECRET_FOR_TOKEN_DIR)
    pub = '{}public.key'.format(CELLO_SECRET_FOR_TOKEN_DIR)
    isExist = os.path.exists(pri) and os.path.exists(pub)
    print('isExist:', isExist)
    if isExist:
        pass
    else:
        try:
            # If the path is not exist, create one. else pass in order to not going to error.
            pathExist = os.path.exists(CELLO_SECRET_FOR_TOKEN_DIR)
            if not pathExist:
                os.system('mkdir {}'.format(CELLO_SECRET_FOR_TOKEN_DIR))
            os.chdir(CELLO_SECRET_FOR_TOKEN_DIR)
            os.system('ssh-keygen -t rsa -b 2048 -f private.key')
            os.system(
                'openssl rsa -in private.key -pubout -outform PEM -out public.key'
            )
        except:
            error_msg = 'private.key or public.key create failed'.format()
            raise BadRequest(msg=error_msg)
    isSuccess = os.path.exists(pri) and os.path.exists(pub)
    print('isSucces:', isSuccess)
    return isSuccess
Exemplo n.º 4
0
def load_yaml_file():
    try:
        f = open('agent/docker/_compose_files/fabric-1.0/crypto-config.yaml')
        dataMap = yaml.load(f)
    except:
        raise BadRequest(msg="load crypto-config.yaml file to data failed!")
    finally:
        f.close()
    return dataMap
Exemplo n.º 5
0
def update_crypto_file_for_addpeers(filepath, peer_org_dict, peers_num):
    filename = '{}/crypto-config.yaml'.format(filepath)

    try:
        f = open(filename)
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        dataNetwork = yaml.load(f)
        listPeer = dataNetwork['PeerOrgs']

        for each_peer in listPeer:
            if each_peer['Domain'] == '{}.{}'.format(peer_org_dict['name'],
                                                     peer_org_dict['domain']):
                peer_specs = each_peer['Specs']
                peers_exist = len(peer_specs)
                for i in range(peers_num):
                    id = peers_exist + i
                    hostname = 'peer{}'.format(id)
                    svc_name = '{}-{}'.format(hostname, peer_org_dict['name'])
                    one_spec = dict(Hostname=hostname, SANS=[svc_name])
                    peer_specs.append(one_spec)
                break

    except:
        raise BadRequest(msg="cryptoconfit.yaml datas set error")

    try:
        f = open(filename, 'w')
        yaml.dump(dataNetwork, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()
Exemplo n.º 6
0
def fabric_ca_config_files(id, fabric_version, CELLO_MASTER_FABRIC_DIR,
                           peer_org_dicts):
    try:
        fabric_version_dir = fabric_version.replace('.', '_')
        for each in peer_org_dicts:
            orgName = each['name']
            orgDomain = each['domain']
            peerPath = '{}{}/crypto-config/peerOrganizations/{}.{}/ca/'.format(
                CELLO_MASTER_FABRIC_DIR, id, orgName, orgDomain)
            os.system(
                'cp /opt/fabric_tools/{}/fabric-ca-server-config.yaml {}'.
                format(fabric_version_dir, peerPath))
    except Exception:
        error_msg = 'cp fabric-ca-server-config.yaml to path {} failed.'.format(
            peerPath)
        raise BadRequest(msg=error_msg)
    return
Exemplo n.º 7
0
def commad_create_path(network_id):

    filepath = '{}{}'.format(CELLO_MASTER_FABRIC_DIR, network_id)

    logger.info("before commad_create_path: {}".format(filepath))
    try:
        os.system('mkdir -p {}'.format(filepath))
    except:
        error_msg = 'Network file create failed, networkid={}'.format(
            network_id)
        raise BadRequest(msg=error_msg)

    isSuccess = os.path.exists(filepath)
    logger.info(" is = {}".format(isSuccess))
    if not isSuccess:
        message = "commad_create_path: {} failed, is = {}".format(
            filepath, isSuccess)
        raise NotFound(msg=message)

    return filepath
Exemplo n.º 8
0
def blockchain_network_create_yarml_for_neworgs(blockchain_network_id):
    request_debug(r, logger)
    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))['blockchain_network']
    else:
        error_msg = "request header content-type is not supported, use application/json"
        raise UnsupportedMediaType(msg=error_msg)

    peer_orgs = body.get('peer_orgs', None)
    if peer_orgs is None:
        raise BadRequest(msg="peer_orgs must be provided in request body")

    network_handler = BlockchainNetworkHandler()
    try:
        network = network_handler.createyamlforneworgs(
            id=blockchain_network_id, peer_orgs=peer_orgs)
        return make_ok_gaea_resp(resource='blockchain_network', result=network)
    except Exception as e:
        msg = "blockchain_network add org failed {}".format(e)
        logger.error(msg)
        raise InternalServerError(msg=msg)
Exemplo n.º 9
0
def organization_update():
    request_debug(r, logger)
    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))
    else:
        body = r.form
    if "id" not in body:
        error_msg = "organization PUT without enough data"
        logger.warning(error_msg)
        raise BadRequest(msg=error_msg)
    else:
        id, d = body["id"], {}
        for k in body:
            if k != "id":
                d[k] = body.get(k)
        result = org_handler().update(id, d)
        if result:
            logger.debug("organization PUT successfully")
            return make_ok_resp()
        else:
            error_msg = "Failed to update organization {}".format(
                result.get("name"))
            logger.warning(error_msg)
            return make_fail_resp(error=error_msg)
Exemplo n.º 10
0
def organization_create():
    request_debug(r, logger)

    # add operating log
    cur_time = datetime.datetime.utcnow()
    # get current func name
    opName = sys._getframe().f_code.co_name
    opObject = "Organization"
    operator = "admin"
    opResult = {}
    op_log_handler = OperatorLogHandler()

    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))['organization']
        opDetails = body
    else:
        error_msg = "request header content-type is not supported, use application/json"
        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator)

        raise UnsupportedMediaType(error_msg)

    name = body.get('name', None)
    type = body.get('type', None)
    domain = body.get('domain', None)

    if name is None or name == '':
        error_msg = "name is required and not allowed to be ''"

        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator,
                              opDetails=opDetails)

        raise BadRequest(msg=error_msg)
    # if there is '_' in name or ID of genesis.block, orderer couldn't
    # start up, saying "failed: error converting config to map: Illegal characters in key: [Group]"
    if '_' in name:
        # aaa = BadRequest("'_' is not allowed in name or ID")
        # # raise BadRequest("'_' is not allowed in name or ID")
        # raise aaa
        error_msg = '_ is not allowed in name or ID'

        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator,
                              opDetails=opDetails)

        raise BadRequest(msg=error_msg)

    if domain is None or domain == '':
        error_msg = "domain is required and not allowed to be ''"

        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator,
                              opDetails=opDetails)

        raise BadRequest(msg=error_msg)
    if type is None:
        error_msg = "type is required"

        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator,
                              opDetails=opDetails)

        raise BadRequest(msg=error_msg)
    if body['type'] not in ['peer', 'orderer']:
        error_msg = "only peer or orderer type is supported"

        opResult['resDes'] = "ERROR"
        opResult['resCode'] = 400
        opResult['errorMsg'] = error_msg
        op_log_handler.create(opDate=cur_time,
                              opName=opName,
                              opObject=opObject,
                              opResult=opResult,
                              operator=operator,
                              opDetails=opDetails)

        raise BadRequest(msg=error_msg)

    ordererHostnames = body.get('ordererHostnames', None)
    peerNum = body.get('peerNum', None)
    ca = body.get('ca', {})
    id = uuid4().hex
    description = body.get('description', "")

    if body['type'] == 'peer':
        if ordererHostnames is not None:

            error_msg = "peer type organizations don't need ordererHostnames"

            opResult['resDes'] = "ERROR"
            opResult['resCode'] = 400
            opResult['errorMsg'] = error_msg
            op_log_handler.create(opDate=cur_time,
                                  opName=opName,
                                  opObject=opObject,
                                  opResult=opResult,
                                  operator=operator,
                                  opDetails=opDetails)
            raise BadRequest(msg=error_msg)
        if peerNum is None:
            peerNum = 2
        try:
            result = org_handler().create(id=id,
                                          name=name,
                                          description=description,
                                          type=type,
                                          domain=domain,
                                          peerNum=int(peerNum),
                                          ca=ca,
                                          ordererHostnames=[])

            opResult['resDes'] = "OK"
            opResult['resCode'] = 200
            opResult['errorMsg'] = ''
            op_log_handler.create(opDate=cur_time,
                                  opName=opName,
                                  opObject=opObject,
                                  opResult=opResult,
                                  operator=operator,
                                  opDetails=opDetails)

            return make_ok_gaea_resp('organization', result)
        except Exception as e:
            error_msg = "internal server error"
            opResult['resDes'] = "ERROR"
            opResult['resCode'] = 500
            opResult['errorMsg'] = error_msg
            op_log_handler.create(opDate=cur_time,
                                  opName=opName,
                                  opObject=opObject,
                                  opResult=opResult,
                                  operator=operator,
                                  opDetails=opDetails)

            raise InternalServerError()
    else:
        if peerNum is not None:
            error_msg = "orderer type organizations don't need peers"

            opResult['resDes'] = "ERROR"
            opResult['resCode'] = 400
            opResult['errorMsg'] = error_msg
            op_log_handler.create(opDate=cur_time,
                                  opName=opName,
                                  opObject=opObject,
                                  opResult=opResult,
                                  operator=operator,
                                  opDetails=opDetails)

            raise BadRequest(msg=error_msg)
            # userNum = body.get('userNum', None)
        try:
            result = org_handler().create(id=id,
                                          name=name,
                                          description=description,
                                          type=type,
                                          domain=domain,
                                          ca=ca,
                                          peerNum=0,
                                          ordererHostnames=ordererHostnames)

            opResult['resDes'] = "OK"
            opResult['resCode'] = 200
            opResult['errorMsg'] = ''
            op_log_handler.create(opDate=cur_time,
                                  opName=opName,
                                  opObject=opObject,
                                  opResult=opResult,
                                  operator=operator,
                                  opDetails=opDetails)

            return make_ok_gaea_resp('organization', result)
        except Exception as e:
            error_msg = "internal server error"
            op_log_handler.record_operating_log(opDate=cur_time,
                                                opName=opName,
                                                opObject=opObject,
                                                resCode=500,
                                                operator=operator,
                                                errorMsg=error_msg,
                                                opDetails=opDetails)

            raise InternalServerError()
Exemplo n.º 11
0
def blockchain_network_create():
    request_debug(r, logger)

    # add operating log
    # cur_time = datetime.datetime.utcnow()
    cur_time = datetime.datetime.utcnow()
    opName = sys._getframe().f_code.co_name
    opObject = "Network"
    operator = "admin"
    op_log_handler = OperatorLogHandler()

    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))['blockchain_network']
        opDetails = body
    else:
        error_msg = "request header content-type is not supported, use application/json"

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=400,
                                            operator=operator,
                                            errorMsg=error_msg)

        raise UnsupportedMediaType(msg=error_msg)

    name = body.get('name', None)
    orderer_orgs = body.get('orderer_orgs', None)
    peer_orgs = body.get('peer_orgs', None)
    host_id = body.get('host_id', None)
    if name is None or orderer_orgs is None or peer_orgs is None or host_id is None:
        error_msg = "name, orderer(peer)_orgs and host_id must be provided in request body"

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=400,
                                            operator=operator,
                                            errorMsg=error_msg,
                                            opDetails=opDetails)

        raise BadRequest(msg=error_msg)

    description = body.get('description', "")
    fabric_version = body.get('fabric_version', None)
    if fabric_version is None or (fabric_version != 'v1.1'
                                  and fabric_version != 'v1.4'):
        error_msg = "Now only fabric v1.1 and v1.4 is supported"

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=400,
                                            operator=operator,
                                            errorMsg=error_msg,
                                            opDetails=opDetails)

        raise BadRequest(msg=error_msg)
    consensus_type = body.get('consensus_type', None)
    if consensus_type is None:
        consensus_type = 'kafka'
    elif consensus_type not in ['kafka', 'solo']:
        error_msg = 'consensus type {} is not supported'.format(consensus_type)

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=400,
                                            operator=operator,
                                            errorMsg=error_msg,
                                            opDetails=opDetails)

        raise BadRequest(msg=error_msg)

    id = uuid4().hex
    host = host_handler.get_active_host_by_id(host_id)
    if not host:
        error_msg = "Cannot find available host to create new network"
        logger.error(error_msg)

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=500,
                                            operator=operator,
                                            errorMsg=error_msg,
                                            opDetails=opDetails)

        raise InternalServerError(msg=error_msg)

    network_handler = BlockchainNetworkHandler()
    try:
        network = network_handler.create(id=id,
                                         name=name,
                                         description=description,
                                         fabric_version=fabric_version,
                                         orderer_orgs=orderer_orgs,
                                         peer_orgs=peer_orgs,
                                         host=host,
                                         consensus_type=consensus_type,
                                         create_ts=cur_time)

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=200,
                                            operator=operator,
                                            opDetails=opDetails)
        return make_ok_gaea_resp(resource='blockchain_network', result=network)
    except Exception as e:
        error_msg = "blockchain_network create failed {}".format(e)
        logger.error(error_msg)

        op_log_handler.record_operating_log(opDate=cur_time,
                                            opName=opName,
                                            opObject=opObject,
                                            resCode=500,
                                            operator=operator,
                                            errorMsg=error_msg,
                                            opDetails=opDetails)

        raise InternalServerError(msg=error_msg)
Exemplo n.º 12
0
def update_dump_configtx_yaml_file(filepath, peer_org_dicts, orderer_org_dicts,
                                   request_host_ports):

    filename = '{}/configtx.yaml'.format(filepath)
    try:
        f = open(filename)
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        index = 0
        dataNetwork = yaml.load(f)
        DictOrderer = dataNetwork['Orderer']
        ListOrganizations = dataNetwork['Organizations']
        DictProfiles = dataNetwork['Profiles']
        ListPeerOrganizations = []
        ListOrdererOrganizations = []

        if DictOrderer['OrdererType'] == 'etcdraft':
            OrdererAddress = DictOrderer['Addresses']
            ListOrdererType = DictOrderer['EtcdRaft']
            ListConsenters = ListOrdererType['Consenters']
            DictOption = DictOrderer['EtcdRaft']['Options']
            ListOrdererOrganizations_old = DictProfiles[
                'TwoOrgsOrdererGenesis']['Orderer']['Organizations']
            for each in orderer_org_dicts:
                for eachOrder in each['ordererHostnames']:
                    OrdererAddress.append('{}-{}:{}'.format(
                        eachOrder, each['name'], request_host_ports[index]))
                    ListConsenters.append(
                        dict(
                            Host='{}-{}'.format(eachOrder, each['name']),
                            Port='{}'.format(request_host_ports[index]),
                            ClientTLSCert=
                            'crypto-config/ordererOrganizations/{}/orderers/{}.{}/tls/server.crt'
                            .format(each['domain'], eachOrder, each['domain']),
                            ServerTLSCert=
                            'crypto-config/ordererOrganizations/{}/orderers/{}.{}/tls/server.crt'
                            .format(each['domain'], eachOrder,
                                    each['domain'])))
                    index = index + 1
                ListOrdererOrganizations.append(
                    dict(MSPDir='crypto-config/ordererOrganizations/{}/msp'.
                         format(each['domain']),
                         Name='{}Org'.format(each['name'][0:1].upper() +
                                             each['name'][1:]),
                         ID='{}MSP'.format(each['name'][0:1].upper() +
                                           each['name'][1:])))

            DictOrderer['Addresses'] = OrdererAddress
            DictOrderer['EtcdRaft'] = dict(Consenters=ListConsenters,
                                           Options=DictOption)
            dataNetwork['Orderer'] = DictOrderer

            DictProfiles['TwoOrgsOrdererGenesis']['Orderer'][
                'EtcdRaft'] = dict(Consenters=ListConsenters,
                                   Options=DictOption)
            DictProfiles['TwoOrgsOrdererGenesis']['Orderer'][
                'Addresses'] = OrdererAddress
            DictProfiles['TwoOrgsOrdererGenesis']['Orderer'][
                'Organizations'] = ListOrdererOrganizations_old + ListOrdererOrganizations

        for each in peer_org_dicts:
            ListPeerOrganizations.append(
                dict(MSPDir='crypto-config/peerOrganizations/{}.{}/msp'.format(
                    each['name'], each['domain']),
                     AnchorPeers=[{
                         'Port':
                         7051,
                         'Host':
                         'peer0.{}.{}'.format(each['name'], each['domain'])
                     }],
                     Name='{}MSP'.format(each['name'][0:1].upper() +
                                         each['name'][1:]),
                     ID='{}MSP'.format(each['name'][0:1].upper() +
                                       each['name'][1:])))

        ListOrganizations_new = ListOrganizations + ListOrdererOrganizations + ListPeerOrganizations

        DictProfiles['TwoOrgsOrdererGenesis']['Consortiums'][
            'SampleConsortium']['Organizations'] = ListOrganizations_new

        dataNetwork['Profiles'] = DictProfiles
        dataNetwork['Organizations'] = ListOrganizations_new

    except:
        raise BadRequest(msg="configtx.yaml datas set error")

    try:
        f = open(filename, 'w')
        yaml.dump(dataNetwork, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()
    return
Exemplo n.º 13
0
def update_crypto_config_yaml_file(filepath, peer_org_dicts,
                                   orderer_org_dicts):
    filename = '{}/crypto-config.yaml'.format(filepath)

    try:
        f = open(filename)
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        dataNetwork = yaml.load(f)
        listPeer = dataNetwork['PeerOrgs']
        listOrderer = dataNetwork['OrdererOrgs']

        for each_peer in peer_org_dicts:
            if each_peer['ca']:
                ca = dict(Country=each_peer['ca']['country'],
                          Locality=each_peer['ca']['locality'],
                          Province=each_peer['ca']['province'])
            else:
                ca = {}

            peer_specs = []
            for i in range(each_peer['peerNum']):
                hostname = 'peer{}'.format(i)
                svc_name = '{}-{}'.format(hostname, each_peer['name'])
                one_spec = dict(Hostname=hostname, SANS=[svc_name])
                peer_specs.append(one_spec)
            listPeer.append(
                dict(Domain='{}.{}'.format(each_peer['name'], each_peer['domain']), Name=each_peer['name'].title(),
                     CA=ca, \
                     Specs=peer_specs, EnableNodeOUs=each_peer['enableNodeOUs']))

        for each_orderer in orderer_org_dicts:
            if each_orderer['ca']:
                ca = dict(Country=each_orderer['ca']['country'],
                          Locality=each_orderer['ca']['locality'],
                          Province=each_orderer['ca']['province'])
            else:
                ca = {}
            specs = []
            for orderhost in each_orderer['ordererHostnames']:
                svc_name = '{}-{}'.format(orderhost, each_orderer['name'])
                specs.append(dict(Hostname=orderhost, SANS=[svc_name]))
            listOrderer.append(
                dict(Domain=each_orderer['domain'],
                     Name=each_orderer['name'][0:1].upper() +
                     each_orderer['name'][1:],
                     CA=ca,
                     Specs=specs))

    except:
        raise BadRequest(msg="cryptoconfit.yaml datas set error")

    try:
        f = open(filename, 'w')
        yaml.dump(dataNetwork, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()
Exemplo n.º 14
0
def dump_configtx_yaml_file(filepath, consensus_type, peer_org_dicts,
                            orderer_org_dicts, fabric_version,
                            request_host_ports):
    DictApplication = {'Organizations': None}
    ListPeerOrganizations = []
    ListOrdererOrganizations = []
    OrdererAddress = []
    index = 0
    DictOption = []

    try:
        for each in orderer_org_dicts:
            for eachOrder in each['ordererHostnames']:
                OrdererAddress.append('{}-{}:{}'.format(
                    eachOrder, each['name'], request_host_ports[index]))

                index = index + 1
        DictOrderer={'BatchTimeout':'2s','Organizations':None,'Addresses':OrdererAddress,\
                        'OrdererType':consensus_type,'BatchSize':{'AbsoluteMaxBytes':'98 MB','MaxMessageCount':100,'PreferredMaxBytes':'8192 KB'}}

        if consensus_type == 'kafka':
            DictOrderer['Kafka'] = dict(Brokers=[
                'kafka-0.kafka:9092', 'kafka-1.kafka:9092',
                'kafka-2.kafka:9092', 'kafka-3.kafka:9092'
            ])
        elif consensus_type == 'etcdraft':
            ListConsenters = []
            times = "600ms"
            size = "20 MB"
            index = 0
            for each in orderer_org_dicts:
                for eachOrder in each['ordererHostnames']:
                    ListConsenters.append(
                        dict(
                            Host='{}-{}'.format(eachOrder, each['name']),
                            Port='{}'.format(request_host_ports[index]),
                            ClientTLSCert=
                            'crypto-config/ordererOrganizations/{}/orderers/{}.{}/tls/server.crt'
                            .format(each['domain'], eachOrder, each['domain']),
                            ServerTLSCert=
                            'crypto-config/ordererOrganizations/{}/orderers/{}.{}/tls/server.crt'
                            .format(each['domain'], eachOrder,
                                    each['domain'])))

                    index = index + 1
            DictOption = {
                'TickInterval': times,
                'ElectionTick': 10,
                'HeartbeatTick': 1,
                'MaxInflightBlocks': 5,
                'SnapshotIntervalSize': size
            }
            DictOrderer['EtcdRaft'] = dict(Consenters=ListConsenters,
                                           Options=DictOption)

        Va = fabric_version.replace('v', 'V')
        Vb = Va.replace('.', '_')

        # 网络起不来,orderer的capabilities不支持V1_4. orderer目前只支持V1_1. 先写死。
        DictCapabilities = {
            'Global': {
                Vb: True
            },
            'Orderer': {
                'V1_1': True
            },
            'Application': {
                'V1_1': True
            }
        }

        for each in orderer_org_dicts:
            ListOrdererOrganizations.append(
                dict(MSPDir='crypto-config/ordererOrganizations/{}/msp'.format(
                    each['domain']),
                     Name='{}Org'.format(each['name'][0:1].upper() +
                                         each['name'][1:]),
                     ID='{}MSP'.format(each['name'][0:1].upper() +
                                       each['name'][1:])))

        for each in peer_org_dicts:
            ListPeerOrganizations.append(
                dict(MSPDir='crypto-config/peerOrganizations/{}.{}/msp'.format(
                    each['name'], each['domain']),
                     AnchorPeers=[{
                         'Port': 7051,
                         'Host': 'peer0-{}'.format(each['name'])
                     }],
                     Name='{}MSP'.format(each['name'][0:1].upper() +
                                         each['name'][1:]),
                     ID='{}MSP'.format(each['name'][0:1].upper() +
                                       each['name'][1:])))

        ListOrganizations = ListOrdererOrganizations + ListPeerOrganizations

        #'TwoOrgsChannel':{'Application': {'Capabilities':{Vb:True},'Organizations':ListPeerOrganizations},'Consortium':'SampleConsortium'}
        DictProfiles={'TwoOrgsOrdererGenesis':{'Orderer':{'BatchTimeout':'2s','Organizations':ListOrdererOrganizations,'Addresses':DictOrderer['Addresses'],\
                        'OrdererType':consensus_type,'Capabilities':{'V1_1':True},'BatchSize':DictOrderer['BatchSize']}, \
                            'Consortiums':{'SampleConsortium':{'Organizations':ListPeerOrganizations}}}}
        if consensus_type == 'kafka':
            DictProfiles['TwoOrgsOrdererGenesis']['Orderer']['Kafka'] = dict(
                Brokers=[
                    'kafka-0.kafka:9092', 'kafka-1.kafka:9092',
                    'kafka-2.kafka:9092', 'kafka-3.kafka:9092'
                ])
        elif consensus_type == 'etcdraft':
            DictProfiles['TwoOrgsOrdererGenesis']['Orderer'][
                'EtcdRaft'] = dict(Consenters=ListConsenters,
                                   Options=DictOption)

        dataConfig = dict(Application=DictApplication,
                          Orderer=DictOrderer,
                          Capabilities=DictCapabilities,
                          Profiles=DictProfiles,
                          Organizations=ListOrganizations)

        filename = '{}/configtx.yaml'.format(filepath)
    except Exception as e:
        print(e)
        raise BadRequest(msg="configtx.yaml datas set error")

    try:
        f = open(filename, 'w', encoding='utf-8')
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        yaml.dump(dataConfig, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()

    return
Exemplo n.º 15
0
def dump_configtx_yaml_file_k8s(filepath, consensus_type, peer_org_dicts,
                                orderer_org_dicts, fabric_version):
    DictApplication = {'Organizations': None}
    ListPeerOrganizations = []
    ListOrdererOrganizations = []
    OrdererAddress = []
    try:
        for each in orderer_org_dicts:
            for eachOrder in each['ordererHostnames']:
                OrdererAddress.append('{}-{}:7050'.format(
                    eachOrder, each['name']))

        DictOrderer={'BatchTimeout':'2s','Organizations':None,'Addresses':OrdererAddress,\
                        'OrdererType':consensus_type,'BatchSize':{'AbsoluteMaxBytes':'98 MB','MaxMessageCount':10,'PreferredMaxBytes':'512 KB'}}

        if consensus_type == 'kafka':
            DictOrderer['Kafka'] = dict(Brokers=[
                'kafka-0.kafka:9092', 'kafka-1.kafka:9092',
                'kafka-2.kafka:9092', 'kafka-3.kafka:9092'
            ])

        Va = fabric_version.replace('v', 'V')
        Vb = Va.replace('.', '_')

        # 网络起不来,orderer的capabilities不支持V1_4. orderer目前只支持V1_1. 先写死。
        DictCapabilities = {
            'Global': {
                Vb: True
            },
            'Orderer': {
                'V1_1': True
            },
            'Application': {
                'V1_1': True
            }
        }

        for each in orderer_org_dicts:
            ListOrdererOrganizations.append(
                dict(MSPDir='crypto-config/ordererOrganizations/{}/msp'.format(
                    each['domain']),
                     Name='{}Org'.format(each['name'][0:1].upper() +
                                         each['name'][1:]),
                     ID='{}MSP'.format(each['name'][0:1].upper() +
                                       each['name'][1:])))

        for each in peer_org_dicts:
            ListPeerOrganizations.append(
                dict(MSPDir='crypto-config/peerOrganizations/{}.{}/msp'.format(
                    each['name'], each['domain']),
                     AnchorPeers=[{
                         'Port': 7051,
                         'Host': 'peer0-{}'.format(each['name'])
                     }],
                     Name='{}MSP'.format(each['name'][0:1].upper() +
                                         each['name'][1:]),
                     ID='{}MSP'.format(each['name'][0:1].upper() +
                                       each['name'][1:])))

        ListOrganizations = ListOrdererOrganizations + ListPeerOrganizations

        #'TwoOrgsChannel':{'Application': {'Capabilities':{Vb:True},'Organizations':ListPeerOrganizations},'Consortium':'SampleConsortium'}
        DictProfiles={'TwoOrgsOrdererGenesis':{'Orderer':{'BatchTimeout':'2s','Organizations':ListOrdererOrganizations,'Addresses':DictOrderer['Addresses'],\
                        'OrdererType':consensus_type,'Capabilities':{'V1_1':True},'BatchSize':DictOrderer['BatchSize']}, \
                            'Consortiums':{'SampleConsortium':{'Organizations':ListPeerOrganizations}}}}
        if consensus_type == 'kafka':
            DictProfiles['TwoOrgsOrdererGenesis']['Orderer']['Kafka'] = dict(
                Brokers=[
                    'kafka-0.kafka:9092', 'kafka-1.kafka:9092',
                    'kafka-2.kafka:9092', 'kafka-3.kafka:9092'
                ])

        dataConfig = dict(Application=DictApplication,
                          Orderer=DictOrderer,
                          Capabilities=DictCapabilities,
                          Profiles=DictProfiles,
                          Organizations=ListOrganizations)

        filename = '{}/configtx.yaml'.format(filepath)
    except:
        raise BadRequest(msg="configtx.yaml datas set error")

    try:
        f = open(filename, 'w', encoding='utf-8')
    except IOError:
        error_msg = 'File open filed, can not open yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    try:
        yaml.dump(dataConfig, f)
    except:
        error_msg = 'Yaml file dump filed, can not write date to  yaml file: {}.'.format(
            filename)
        raise BadRequest(msg=error_msg)

    f.close()

    return