Beispiel #1
0
def cluster_create():
    """Create a cluster on a host

    POST /cluster
    {
    name: xxx,
    host_id: xxx,
    network_type=fabric-0.6,
    consensus_plugin: pbft,
    consensus_mode: batch,
    size: 4,
    }

    :return: response object
    """
    logger.info("/cluster action=" + r.method)
    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 not body["name"] or not body["host_id"] or \
            not body["network_type"]:
        error_msg = "cluster post without enough data"
        logger.warning(error_msg)
        return make_fail_resp(error=error_msg, data=body)

    name, host_id, network_type, size = \
        body['name'], body['host_id'],\
        body['network_type'], int(body['size'])

    if network_type == NETWORK_TYPE_FABRIC_PRE_V1:  # TODO: deprecated soon
        config = FabricPreNetworkConfig(
            consensus_plugin=body['consensus_plugin'],
            consensus_mode=body['consensus_mode'],
            size=size)
    elif network_type == NETWORK_TYPE_FABRIC_V1:
        config = FabricV1NetworkConfig(
            consensus_plugin=body['consensus_plugin'], size=size)
    elif network_type == NETWORK_TYPE_FABRIC_V1_1:
        config = FabricV1NetworkConfig(
            consensus_plugin=body['consensus_plugin'], size=size)
        config.network_type = NETWORK_TYPE_FABRIC_V1_1
    else:
        error_msg = "Unknown network_type={}".format(network_type)
        logger.warning(error_msg)
        return make_fail_resp()

    if not config.validate():
        return make_fail_resp(error="config not validated",
                              data=config.get_data())

    if cluster_handler.create(name=name, host_id=host_id, config=config):
        logger.debug("cluster POST successfully")
        return make_ok_resp(code=CODE_CREATED)
    else:
        logger.debug("cluster creation failed using handlder")
        return make_fail_resp(error="Failed to create cluster {}".format(name))
Beispiel #2
0
def cluster_create():
    """Create a cluster on a host

    POST /cluster
    {
    name: xxx,
    host_id: xxx,
    consensus_plugin: pbft,
    consensus_mode: batch,
    size: 4,
    }

    :return: response object
    """
    logger.info("/cluster action=" + r.method)
    request_debug(r, logger)
    if not r.form["name"] or not r.form["host_id"] \
            or not r.form["fabric_version"] \
            or not r.form["consensus_plugin"] or not r.form["size"]:
        error_msg = "cluster post without enough data"
        logger.warning(error_msg)
        return make_fail_response(error=error_msg, data=r.form)
    else:
        name, host_id, fabric_version, consensus_plugin, \
            consensus_mode, size = r.form['name'], r.form['host_id'], \
            r.form['fabric_version'], r.form['consensus_plugin'], \
            r.form['consensus_mode'] or '', int(r.form["size"])
        if consensus_plugin not in CONSENSUS_PLUGINS:
            logger.debug(
                "Unknown consensus_plugin={}".format(consensus_plugin))
            return make_fail_response()
        if consensus_plugin != CONSENSUS_PLUGINS[0] \
           and consensus_plugin != CONSENSUS_PLUGINS[2] \
           and consensus_mode not in CONSENSUS_MODES:
            logger.debug("Invalid consensus, plugin={}, mode={}".format(
                consensus_plugin, consensus_mode))
            return make_fail_response()

        if size not in CLUSTER_SIZES:
            logger.debug("Unknown cluster size={}".format(size))
            return make_fail_response()
        if cluster_handler.create(name=name,
                                  host_id=host_id,
                                  fabric_version=fabric_version,
                                  consensus_plugin=consensus_plugin,
                                  consensus_mode=consensus_mode,
                                  size=size):
            logger.debug("cluster POST successfully")
            return make_ok_response(code=CODE_CREATED)
        else:
            logger.debug("cluster creation failed")
            return make_fail_response(
                error="Failed to create cluster {}".format(name))
Beispiel #3
0
def cluster_create():
    """Create a cluster on a host

    POST /cluster
    {
    name: xxx,
    host_id: xxx,
    network_type=fabric-0.6,
    consensus_plugin: pbft,
    consensus_mode: batch,
    size: 4,
    }

    :return: response object
    """
    logger.info("/cluster action=" + r.method)
    request_debug(r, logger)
    if not r.form["name"] or not r.form["host_id"] or \
            not r.form["network_type"]:
        error_msg = "cluster post without enough data"
        logger.warning(error_msg)
        return make_fail_resp(error=error_msg, data=r.form)

    name, host_id, network_type = \
        r.form['name'], r.form['host_id'], r.form['network_type']

    if network_type == NETWORK_TYPE_FABRIC_PRE_V1:
        config = FabricPreNetworkConfig(
            consensus_plugin=r.form['consensus_plugin'],
            consensus_mode=r.form['consensus_mode'],
            size=r.form['size'])
    elif network_type == NETWORK_TYPE_FABRIC_V1:
        config = FabricV1NetworkConfig(
            size=r.form['size'])  # TODO: add more variables
    else:
        error_msg = "Unknown network_type={}".format(network_type)
        logger.warning(error_msg)
        return make_fail_resp()

    if not config.validate():
        return make_fail_resp(error="config not validated",
                              data=config.get_data())

    if cluster_handler.create(name=name,
                              host_id=host_id,
                              network_type=network_type,
                              config=config):
        logger.debug("cluster POST successfully")
        return make_ok_resp(code=CODE_CREATED)
    else:
        logger.debug("cluster creation failed using handlder")
        return make_fail_resp(error="Failed to create cluster {}".format(name))
Beispiel #4
0
def cluster_create():
    """Create a cluster on a host

    POST /cluster
    {
    name: xxx,
    host_id: xxx,
    network_type=fabric-0.6,
    consensus_plugin: pbft,
    consensus_mode: batch,
    size: 4,
    }

    :return: response object
    """
    logger.info("/cluster action=" + r.method)
    request_debug(r, logger)
    if not r.form["name"] or not r.form["host_id"] or \
            not r.form["network_type"]:
        error_msg = "cluster post without enough data"
        logger.warning(error_msg)
        return make_fail_resp(error=error_msg, data=r.form)

    name, host_id, network_type, size = \
        r.form['name'], r.form['host_id'],\
        r.form['network_type'], int(r.form['size'])

    if network_type == NETWORK_TYPE_FABRIC_PRE_V1:  # TODO: deprecated soon
        config = FabricPreNetworkConfig(
            consensus_plugin=r.form['consensus_plugin'],
            consensus_mode=r.form['consensus_mode'],
            size=size)
    elif network_type == NETWORK_TYPE_FABRIC_V1:
        config = FabricV1NetworkConfig(
            consensus_plugin=r.form['consensus_plugin'],
            size=size)
    else:
        error_msg = "Unknown network_type={}".format(network_type)
        logger.warning(error_msg)
        return make_fail_resp()

    if not config.validate():
        return make_fail_resp(error="config not validated",
                              data=config.get_data())

    if cluster_handler.create(name=name, host_id=host_id, config=config):
        logger.debug("cluster POST successfully")
        return make_ok_resp(code=CODE_CREATED)
    else:
        logger.debug("cluster creation failed using handlder")
        return make_fail_resp(error="Failed to create cluster {}".
                              format(name))
Beispiel #5
0
def cluster_create():
    """Create a cluster on a host

    POST /cluster
    {
    name: xxx,
    host_id: xxx,
    consensus_plugin: pbft,
    consensus_mode: batch,
    size: 4,
    }

    :return: response object
    """
    logger.info("/cluster action=" + r.method)
    request_debug(r, logger)
    if not r.form["name"] or not r.form["host_id"] or not \
            r.form["consensus_plugin"] or not r.form["size"]:
        error_msg = "cluster post without enough data"
        logger.warning(error_msg)
        return make_fail_response(error=error_msg, data=r.form)
    else:
        name, host_id, consensus_plugin, consensus_mode, size = \
            r.form['name'], r.form['host_id'], r.form['consensus_plugin'],\
            r.form['consensus_mode'] or '', int(r.form[
                "size"])
        if consensus_plugin not in CONSENSUS_PLUGINS:
            logger.debug("Unknown consensus_plugin={}".format(
                consensus_plugin))
            return make_fail_response()
        if consensus_plugin != CONSENSUS_PLUGINS[0] and consensus_mode \
                not in CONSENSUS_MODES:
            logger.debug("Invalid consensus, plugin={}, mode={}".format(
                consensus_plugin, consensus_mode))
            return make_fail_response()

        if size not in CLUSTER_SIZES:
            logger.debug("Unknown cluster size={}".format(size))
            return make_fail_response()
        if cluster_handler.create(name=name, host_id=host_id,
                                  consensus_plugin=consensus_plugin,
                                  consensus_mode=consensus_mode,
                                  size=size):
            logger.debug("cluster POST successfully")
            return make_ok_response(code=CODE_CREATED)
        else:
            logger.debug("cluster creation failed")
            return make_fail_response(error="Failed to create cluster {}".
                                      format(name))
Beispiel #6
0
def cluster_api():
    logger.info("/cluster action=" + r.method)
    request_debug(r, logger)
    if r.method == 'GET':
        if not r.form["id"]:
            logger.warn("cluster get without enough data")
            response_fail["error"] = "cluster GET without enough data"
            response_fail["data"] = r.form
            return jsonify(response_fail), CODE_BAD_REQUEST
        else:
            logger.debug("id=" + r.form['id'])
            result = cluster_handler.get_by_id(r.form['id'])
            if result:
                return jsonify(result), CODE_OK
            else:
                logger.warn("cluster not found with id=" + r.form['id'])
                response_fail["data"] = r.form
                return jsonify(response_fail), CODE_BAD_REQUEST
    elif r.method == 'POST':
        if not r.form["name"] or not r.form["host_id"] or not \
                r.form["consensus_plugin"] or not r.form["size"]:
            logger.warn("cluster post without enough data")
            response_fail["error"] = "cluster POST without enough data"
            response_fail["data"] = r.form
            return jsonify(response_fail), CODE_BAD_REQUEST
        else:
            name, host_id, consensus_plugin, consensus_mode, size = \
                r.form['name'], r.form['host_id'], r.form['consensus_plugin'],\
                r.form['consensus_mode'] or CONSENSUS_MODES[0], int(r.form[
                    "size"])
            if consensus_plugin not in CONSENSUS_PLUGINS:
                logger.debug(
                    "Unknown consensus_plugin={}".format(consensus_plugin))
                return jsonify(response_fail), CODE_BAD_REQUEST
            if consensus_plugin != CONSENSUS_PLUGINS[0] and consensus_mode \
                    not in CONSENSUS_MODES:
                logger.debug("Invalid consensus, plugin={}, mode={}".format(
                    consensus_plugin, consensus_mode))
                return jsonify(response_fail), CODE_BAD_REQUEST

            if size not in CLUSTER_SIZES:
                logger.debug("Unknown cluster size={}".format(size))
                return jsonify(response_fail), CODE_BAD_REQUEST
            if cluster_handler.create(name=name,
                                      host_id=host_id,
                                      consensus_plugin=consensus_plugin,
                                      consensus_mode=consensus_mode,
                                      size=size):
                logger.debug("cluster POST successfully")
                return jsonify(response_ok), CODE_CREATED
            else:
                logger.debug("cluster creation failed")
                response_fail["error"] = "Failed to create cluster {}".format(
                    name)
                return jsonify(response_fail), CODE_BAD_REQUEST
    elif r.method == 'DELETE':
        if not r.form["id"] or not r.form["col_name"]:
            logger.warn("cluster operation post without enough data")
            response_fail["error"] = "cluster delete without enough data"
            response_fail["data"] = r.form
            return jsonify(response_fail), CODE_BAD_REQUEST
        else:
            logger.debug("cluster delete with id={0}, col_name={1}".format(
                r.form["id"], r.form["col_name"]))
            if r.form["col_name"] == "active":
                result = cluster_handler.delete(id=r.form["id"])
            else:
                result = cluster_handler.delete_released(id=r.form["id"])
            if result:
                return jsonify(response_ok), CODE_OK
            else:
                logger.debug("cluster deletion failed")
                response_fail["error"] = "Failed to delete cluster {}".format(
                    r.form["id"])
                return jsonify(response_fail), CODE_BAD_REQUEST
    else:
        response_fail["error"] = "unknown operation method"
        response_fail["data"] = r.form
        return jsonify(response_fail), CODE_BAD_REQUEST
Beispiel #7
0
    def post(self):
        user = utils._get_user()
        user = user.dbUser

        body = cluster_create_parser.parse_args()
        cluster_name = body.get('cluster_name')
        network_type = body.get('network_type')
        consensus_plugin = body.get('consensus_plugin')
        domain = body.get('domain')
        channel = body.get('channel')
        orderer = body.get('orderer')
        peer_orgs = body.get('peer_orgs')
        orderer_org = body.get('orderer_org')

        if not all([cluster_name, network_type, peer_orgs, channel, domain]):
            error_msg = "参数缺失"
            logger.warning(error_msg)
            return make_fail_resp(error=error_msg, data=body)

        host_id = ''
        try:
            hosts = HostModel.objects.all()
            for host in hosts:
                if len(host.clusters) < host.capacity:
                    host_id = host.id
                    break
        except Exception as e:
            logger.error(e)
            return make_fail_resp(error='db error')

        if not host_id:
            return {'stat': 401, 'msg': '服务器已满,请联系客服'}

        if network_type not in NETWORK_TYPES:
            error_msg = "Unknown network_type={}".format(network_type)
            logger.warning(error_msg)
            return make_fail_resp()

        peer_org_list = []

        orderer_org = {
            'name': 'orderer',
            'domain': domain,
            'orderers': ['orderer']
        }

        for peer_org in peer_orgs:
            peer_org = demjson.decode(peer_org)
            if not all([peer_org.get('name'), peer_org.get('peers')]):
                return make_fail_resp(error='参数缺失', data=body)
            peer_org['peers'] = [
                'peer{}'.format(i) for i in range(int(peer_org['peers']))
            ]
            peer_org['domain'] = domain
            peer_org['ca'] = 'ca'
            peer_org_list.append(peer_org)

        cluster = ClusterModel.objects(name=cluster_name)
        if cluster:
            return make_fail_resp(error='链名重复')

        config = FabricNetworkConfig(consensus_plugin=consensus_plugin,
                                     network_type=network_type,
                                     channel=channel,
                                     orderer_org=orderer_org,
                                     peer_orgs=peer_org_list)
        config.domain = domain
        if not config.validate():
            return make_fail_resp(error="config not validated",
                                  data=config.get_data())

        if cluster_handler.create(name=cluster_name,
                                  host_id=host_id,
                                  config=config,
                                  user=user):
            logger.debug("cluster POST successfully")
            return make_ok_resp()
        else:
            logger.debug("cluster creation failed using handlder")
            return make_fail_resp(
                error="Failed to create cluster {}".format(cluster_name))