Ejemplo n.º 1
0
def operator_log_create():
    request_debug(r, logger)
    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))['operator_log']
    else:
        error_msg = "request header content-type is not supported, use application/json"
        raise UnsupportedMediaType(msg=error_msg)

    opDate = body.get('opDate', None)
    opName = body.get('opName', '')
    opObject = body.get('opObject', '')
    opResult = body.get('opResult', {})
    operator = body.get('operator', '')
    opDetails = body.get('opDetails', '')

    op_log_handler = OperatorLogHandler()
    # id = uuid4().hex

    try:
        op_log = op_log_handler.create(opDate=opDate,
                                       opName=opName,
                                       opObject=opObject,
                                       opResult=opResult,
                                       operator=operator,
                                       opDetails=opDetails)

        return make_ok_my_resp(resource='operator_log', result=op_log)
    except Exception as e:
        msg = "operator_log create failed, error is  {e}, method is {m}".format(
            e=e, m=opName)
        logger.error(msg)
        raise InternalServerError(msg=msg)
Ejemplo n.º 2
0
def operator_log_list():
    logger.info("/operator_log_list method=" + r.method)
    try:
        request_debug(r, logger)
        op_log_handler = OperatorLogHandler()

        col_filter = dict((key, r.args.get(key)) for key in r.args)
        # rest interface pass time in millsecond, but python datetime
        # use time in second
        start_stamp_in_sec = float(col_filter['start']) / 1000
        end_stamp_in_sec = float(col_filter['end']) / 1000

        if 'start' in col_filter.keys():
            start_time = datetime.utcfromtimestamp(start_stamp_in_sec)
            # start_time = datetime.utcfromtimestamp(1553247740.0)
            col_filter['opDate'] = {'$gte': start_time}
            col_filter.pop('start')
        if 'end' in col_filter.keys():
            end_time = datetime.utcfromtimestamp(end_stamp_in_sec)
            # end_time = datetime.utcfromtimestamp(1553247800.0)
            col_filter['opDate']['$lte'] = end_time
            col_filter.pop('end')

        items = list(op_log_handler.list(filter_data=col_filter))
    except:
        raise NotFound(msg='get operation logs failed')

    return make_ok_my_resp(resource='operator_logs', result=items)
Ejemplo n.º 3
0
def service_endporint_query(blockchain_network_id):
    request_debug(r, logger)
    network_handler = BlockchainNetworkHandler()

    col_filter = blockchain_network_id
    items = list(network_handler.get_endpoints_list(filter_data=col_filter))

    return make_ok_my_resp(resource='service_endpoints',result=items)
Ejemplo n.º 4
0
def blockchain_network_list():
    logger.info("/blockchain_network method=" + r.method)
    request_debug(r, logger)
    col_filter = dict((key, r.args.get(key)) for key in r.args)
    network_handler = BlockchainNetworkHandler()
    items = list(network_handler.list(filter_data=col_filter))

    return make_ok_my_resp(resource='blockchain_networks',result=items)
Ejemplo n.º 5
0
def blockchain_network_query(blockchain_network_id):
    request_debug(r, logger)
    network_handler = BlockchainNetworkHandler()
    result = network_handler.schema(network_handler.get_by_id(blockchain_network_id))
    logger.debug(result)
    if result:
        return make_ok_my_resp(resource='blockchain_network', result=result)
    else:
        error_msg = "blockchain_network not found with id=" + blockchain_network_id
        logger.warning(error_msg)
        raise NotFound(msg=error_msg)
Ejemplo n.º 6
0
def organization_list():
    logger.info("/organization_list method=" + r.method)
    try:
        request_debug(r, logger)

        col_filter = dict((key, r.args.get(key)) for key in r.args)
        items = list(org_handler().list(filter_data=col_filter))
    except:
        raise NotFound(msg='get organizations failed')

    return make_ok_my_resp(resource='organizations', result=items)
Ejemplo n.º 7
0
def net_healthy_query(blockchain_network_id):
    request_debug(r, logger)
    network_handler = BlockchainNetworkHandler()

    col_filter = blockchain_network_id
    infos = network_handler.get_endpoints_list(filter_data=col_filter)
    for info in infos:
        if info["service_type"] == 'peer' and info["peer_port_proto"] == 'cc_listen':
            infos.remove(info)
            continue

    return make_ok_my_resp(resource='healthy',result=infos)
Ejemplo n.º 8
0
def org_healthy_query(organization_id):
    request_debug(r, logger)
    network_handler = BlockchainNetworkHandler()

    serviceEndpoints = modelv2.ServiceEndpoint.objects(org_name=organization_id)
    infos = network_handler.endports_schema(serviceEndpoints, many=True)

    for info in infos:
        if info["service_type"] == 'peer' and info["peer_port_proto"] == 'cc_listen':
            infos.remove(info)
            continue

    return make_ok_my_resp(resource='healthy', result=infos)
Ejemplo n.º 9
0
def organization_query(organization_id):
    try:
        request_debug(r, logger)
        result = org_handler().schema(org_handler().get_by_id(organization_id))
        logger.debug(result)
        if result:
            return make_ok_my_resp(resource='organization', result=result)
        else:
            error_msg = "organization not found with id=" + organization_id
            logger.warning(error_msg)
            raise NotFound(msg=error_msg)
    except:
        raise NotFound(msg='get organization failed')
Ejemplo n.º 10
0
def organization_update(organization_id):
    request_debug(r, logger)
    if r.content_type.startswith("application/json"):
        body = dict(r.get_json(force=True, silent=True))
    else:
        body = r.form

    id = organization_id

    peerNum = body["peerNum"]

    result = org_handler().update(id, peerNum)
    if result:
        logger.debug("organization PUT successfully")
        return make_ok_my_resp(resource='organization', result=result)
    else:
        error_msg = "Failed to update organization {}".format(
            result.get("name"))
        logger.warning(error_msg)
        return make_fail_resp(error=error_msg)
Ejemplo n.º 11
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")
    orderer_orgs = body.get('orderer_orgs', None)

    network_handler = BlockchainNetworkHandler()
    try:
        network = network_handler.createyamlforneworgs(id = blockchain_network_id,
                               peer_orgs = peer_orgs,orderer_orgs = orderer_orgs,
                               )
        return make_ok_my_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)
Ejemplo n.º 12
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)
    db_type = body.get('db_type', 'couchdb')
    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 ['etcdraft', '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,
                               db_type = db_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_my_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)
Ejemplo n.º 13
0
def blockchain_network_delete(blockchain_network_id):
    network_handler = BlockchainNetworkHandler()

    # add operating log
    cur_time = datetime.datetime.utcnow()
    opName = sys._getframe().f_code.co_name
    opObject = "Network"
    operator = "admin"
    op_log_handler = OperatorLogHandler()
    opDetails = {}
    opDetails['blockchain_network_id'] = blockchain_network_id

    try:
        network = modelv2.BlockchainNetwork.objects.get(id = blockchain_network_id)
        if network.status == 'error':
            host = network.host
            host.update(pull__clusters = blockchain_network_id)
            # if org has referenced network, remove
            for peer_org in network.peer_orgs:
                org_obj = modelv2.Organization.objects.get(id=peer_org)
                org_obj.update(unset__network=network.id)
            for orderer_org in network.orderer_orgs:
                org_obj = modelv2.Organization.objects.get(id=orderer_org)
                org_obj.update(unset__network=network.id)
            network.delete()
            filepath = '{}{}'.format(CELLO_MASTER_FABRIC_DIR, network.id)
            os.system('rm -rf {}'.format(filepath))

            op_log_handler.record_operating_log(
                opDate=cur_time,
                opName=opName,
                opObject=opObject,
                resCode=200,
                operator=operator,
                opDetails=opDetails
                 )

            return make_ok_my_resp(resource='delete success!',result={})
    except Exception as e:
        error_msg = "blockchain_network {id} delete failed, for {err}".\
                                 format(id = blockchain_network_id, err = e)
        logger.error(error_msg)

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

        raise NotFound(msg=error_msg)
    try:
        network_handler.delete(network)

        op_log_handler.record_operating_log(
            opDate=cur_time,
            opName=opName,
            opObject=opObject,
            resCode=200,
            operator=operator,
            opDetails=opDetails)

        return make_ok_my_resp(resource='delete success!', result={})
    except Exception as e:
        error_msg = "blockchain_network {id} delete failed, for {err}". \
                                 format(id=blockchain_network_id, err=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)
Ejemplo n.º 14
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)

    organizations = list(org_handler().list())
    org_names = []
    for org in organizations:
        org_names.append(org['name'])
    if name in org_names:
        error_msg = "the same org name has exist,please use another name "
        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 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', {})
    host_id = body.get('host_id', None)
    host = host_handler.get_active_host_by_id(host_id)
    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,
                                          host=host,
                                          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_my_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,
                                          host=host,
                                          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_my_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()
Ejemplo n.º 15
0
def organization_delete(organization_id):
    request_debug(r, logger)
    request_data = org_handler().get_by_id(organization_id)

    # add operating log
    cur_time = datetime.datetime.utcnow()
    opName = sys._getframe().f_code.co_name
    opObject = "Organization"
    operator = "admin"
    opResult = {}
    opDetails = {}
    opDetails['organization_id'] = organization_id

    op_log_handler = OperatorLogHandler()

    if request_data is not None and "id" in request_data:
        if request_data.network is not None:
            error_msg = "network has created, organization {} is forbidden to delete.".format(
                organization_id)
            logger.warning(error_msg)

            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)

            raise Forbidden(msg=error_msg)
        else:
            pass
    else:
        error_msg = "organization delete without enough data"
        logger.warning(error_msg)

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

        raise NotFound(msg=error_msg)

    logger.debug("host delete with id={0}".format(organization_id))
    if org_handler().delete(id=organization_id):

        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_my_resp(resource='delete success!', result={})
    else:
        error_msg = "Failed to delete organization {}".format(organization_id)
        logger.warning(error_msg)

        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(msg=error_msg)