Search in sources :

Example 6 with WebResponse

use of com.jd.httpservice.utils.web.WebResponse in project jdchain-core by blockchain-jd-com.

the class ManagementController method deActivateParticipant.

/**
 * 代理交易; <br>
 * <p>
 * 此方法假设当前节点是一个待移除的共识节点, 通过此方法接收一笔用于实现管理操作的交易;
 *
 * <p>
 * <p>
 * 此方法接收到交易之后,先把交易提交到已有的共识网络执行,这个已有网络包括本节点; <br>
 *
 * <p>
 * 如果操作中涉及到共识参与方的共识参数变化,将触发将此节点的共识拓扑改变的操作;
 *
 * @param base58LedgerHash   base58格式的账本哈希;
 * @param participantAddress 待移除参与方的地址
 * @return
 */
@RequestMapping(path = "/delegate/deactiveparticipant", method = RequestMethod.POST)
public WebResponse deActivateParticipant(@RequestParam("ledgerHash") String base58LedgerHash, @RequestParam("participantAddress") String participantAddress) {
    try {
        HashDigest ledgerHash = Crypto.resolveAsHashDigest(Base58Utils.decode(base58LedgerHash));
        // 进行一系列安全检查
        if (ledgerQuerys.get(ledgerHash) == null) {
            return WebResponse.createFailureResult(-1, "input ledgerhash not exist!");
        }
        if (!ledgerCurrNodes.get(ledgerHash).getAddress().toBase58().equals(participantAddress)) {
            return WebResponse.createFailureResult(-1, "deactive participant not me!");
        }
        LedgerRepository ledgerRepo = (LedgerRepository) ledgerQuerys.get(ledgerHash);
        LedgerAdminInfo ledgerAdminInfo = ledgerRepo.getAdminInfo();
        String currentProvider = ledgerAdminInfo.getSettings().getConsensusProvider();
        IParticipantManagerService participantService = consensusServiceFactory.getService(currentProvider);
        if (participantService == null || !participantService.supportManagerParticipant()) {
            return WebResponse.createFailureResult(-1, "not support operation");
        }
        // 已经是DEACTIVATED状态
        ParticipantNode node = getCurrentNode(ledgerAdminInfo, participantAddress);
        if (node.getParticipantNodeState() == ParticipantNodeState.DEACTIVATED) {
            return WebResponse.createSuccessResult(null);
        }
        // 已经处于最小节点数环境的共识网络,不能再执行去激活操作
        List<NodeSettings> origConsensusNodes = SearchOrigConsensusNodes(ledgerRepo);
        if (origConsensusNodes.size() <= participantService.minConsensusNodes()) {
            return WebResponse.createFailureResult(-1, "in minimum number of nodes scenario, deactive op is not allowed!");
        }
        ParticipantContext context = ParticipantContext.buildContext(ledgerHash, ledgerRepo, ledgerAdminInfo, currentProvider, participantService, bindingConfigs.get(ledgerHash).getSslSecurity());
        context.setProperty(ParticipantContext.HASH_ALG_PROP, ledgerCryptoSettings.get(ledgerHash).getHashAlgorithm());
        context.setProperty(ParticipantContext.ENDPOINT_SIGNER_PROP, new AsymmetricKeypair(ledgerKeypairs.get(ledgerHash).getPubKey(), ledgerKeypairs.get(ledgerHash).getPrivKey()));
        Properties customProperties = participantService.getCustomProperties(context);
        // 由本节点准备交易
        TransactionRequest txRequest = prepareDeActiveTx(ledgerHash, node, customProperties);
        // 为交易添加本节点的签名信息,防止无法通过安全策略检查
        txRequest = addNodeSigner(txRequest);
        // 连接原有的共识网络,把交易提交到目标账本的原有共识网络进行共识,即在原有共识网络中执行参与方的去激活操作,这个原有网络包括本节点
        TransactionResponse txResponse = participantService.submitNodeStateChangeTx(context, node.getId(), txRequest, origConsensusNodes);
        if (!txResponse.isSuccess()) {
            return WebResponse.createFailureResult(-1, "commit tx to orig consensus, tx execute failed, please retry deactivate participant!");
        }
        // 保证原有共识网络账本状态与共识协议的视图更新信息一致
        WebResponse response = participantService.applyConsensusGroupNodeChange(context, ledgerCurrNodes.get(ledgerHash), null, origConsensusNodes, ParticipantUpdateType.DEACTIVE);
        ledgerPeers.get(ledgerHash).stop();
        LOGGER.info("updateView success!");
        return response;
    } catch (Exception e) {
        return WebResponse.createFailureResult(-1, "deactivate participant failed!" + e);
    } finally {
        ParticipantContext.clear();
    }
}
Also used : WebResponse(com.jd.httpservice.utils.web.WebResponse) IParticipantManagerService(com.jd.blockchain.peer.service.IParticipantManagerService) ParticipantContext(com.jd.blockchain.peer.service.ParticipantContext) BusinessException(utils.BusinessException) BftsmartNodeSettings(com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings)

Example 7 with WebResponse

use of com.jd.httpservice.utils.web.WebResponse in project jdchain-core by blockchain-jd-com.

the class ManagementController method activateParticipant.

/**
 * 激活参与方; <br>
 * <p>
 * 此方法假设当前节点是一个新建但尚未加入共识网络的共识节点, 通过此方法接收一笔用于实现管理操作的交易;
 *
 * <p>
 * <p>
 * 此方法接收到交易之后,先把交易提交到已有的共识网络执行; <br>
 * <p>
 * 如果交易通过验证并执行成功,则将交易在本地的账本中以本地方式执行; <br>
 * <p>
 * 如果执行之后的新区块一致,则提交本地区块;
 *
 * <p>
 * 如果操作中涉及到共识参与方的共识参数变化,将触发将此节点的共识拓扑改变的操作;
 *
 * @param base58LedgerHash   base58格式的账本哈希;
 * @param consensusHost      激活参与方的共识Ip
 * @param consensusPort      激活参与方的共识Port
 * @param consensusSecure    激活参与方的共识服务是否开启安全连接
 * @param remoteManageHost   提供完备数据库的共识节点管理IP
 * @param remoteManagePort   提供完备数据库的共识节点管理Port
 * @param remoteManageSecure 提供完备数据库的共识节点管理服务是否开启安全连接
 * @return
 */
@RequestMapping(path = "/delegate/activeparticipant", method = RequestMethod.POST)
public WebResponse activateParticipant(@RequestParam("ledgerHash") String base58LedgerHash, @RequestParam("consensusHost") String consensusHost, @RequestParam("consensusPort") int consensusPort, @RequestParam(name = "consensusSecure", required = false, defaultValue = "false") boolean consensusSecure, @RequestParam("remoteManageHost") String remoteManageHost, @RequestParam("remoteManagePort") int remoteManagePort, @RequestParam(name = "remoteManageSecure", required = false, defaultValue = "false") boolean remoteManageSecure, @RequestParam(name = "shutdown", required = false, defaultValue = "false") boolean shutdown) {
    try {
        HashDigest ledgerHash = Crypto.resolveAsHashDigest(Base58Utils.decode(base58LedgerHash));
        if (ledgerKeypairs.get(ledgerHash) == null) {
            return WebResponse.createFailureResult(-1, "ledger hash not exist!");
        }
        ServiceEndpoint remoteEndpoint = new ServiceEndpoint(new NetworkAddress(remoteManageHost, remoteManagePort, remoteManageSecure));
        remoteEndpoint.setSslSecurity(bindingConfigs.get(ledgerHash).getSslSecurity());
        LedgerRepository ledgerRepo = (LedgerRepository) ledgerQuerys.get(ledgerHash);
        WebResponse webResponse = checkLedgerDiff(ledgerHash, ledgerRepo, ledgerRepo.retrieveLatestBlock(), remoteEndpoint);
        if (!(webResponse.isSuccess())) {
            return webResponse;
        }
        LedgerAdminInfo ledgerAdminInfo = ledgerRepo.getAdminInfo(ledgerRepo.retrieveLatestBlock());
        String currentProvider = ledgerAdminInfo.getSettings().getConsensusProvider();
        IParticipantManagerService participantService = consensusServiceFactory.getService(currentProvider);
        if (participantService == null || !participantService.supportManagerParticipant()) {
            return WebResponse.createFailureResult(-1, "not support operation");
        }
        ParticipantContext context = ParticipantContext.buildContext(ledgerHash, ledgerRepo, ledgerAdminInfo, currentProvider, participantService, bindingConfigs.get(ledgerHash).getSslSecurity());
        context.setProperty(ParticipantContext.HASH_ALG_PROP, ledgerCryptoSettings.get(ledgerHash).getHashAlgorithm());
        context.setProperty(ParticipantContext.ENDPOINT_SIGNER_PROP, new AsymmetricKeypair(ledgerKeypairs.get(ledgerHash).getPubKey(), ledgerKeypairs.get(ledgerHash).getPrivKey()));
        // 检查节点信息
        ParticipantNode addNode = getCurrentNode(ledgerAdminInfo, ledgerCurrNodes.get(ledgerHash).getAddress().toString());
        NodeSettings nodeSettings = getConsensusNodeSettings(ledgerQuerys.values(), consensusHost, consensusPort);
        if (nodeSettings != null) {
            if (!BytesUtils.equals(addNode.getPubKey().toBytes(), nodeSettings.getPubKey().toBytes())) {
                return WebResponse.createFailureResult(-1, String.format("%s:%d already occupied!", consensusHost, consensusPort, addNode.getAddress().toBase58()));
            } else {
                LOGGER.info("participant {}:{} exists and status is CONSENSUS!", consensusHost, consensusPort);
                // 节点存在且状态为激活,返回成功
                return WebResponse.createSuccessResult(null);
            }
        }
        if (addNode.getParticipantNodeState() == ParticipantNodeState.CONSENSUS) {
            LOGGER.info("participant {}:{} already in CONSENSUS state!!", consensusHost, consensusPort);
            return WebResponse.createSuccessResult("participant already in CONSENSUS state!");
        }
        NetworkAddress addConsensusNodeAddress = new NetworkAddress(consensusHost, consensusPort, consensusSecure);
        remoteEndpoint.setSslSecurity(bindingConfigs.get(ledgerHash).getSslSecurity());
        LOGGER.info("active participant {}:{}!", consensusHost, consensusPort);
        return activeParticipant(context, addNode, addConsensusNodeAddress, shutdown, remoteEndpoint);
    } catch (Exception e) {
        LOGGER.error(String.format("activate participant %s:%d failed!", consensusHost, consensusPort), e);
        return WebResponse.createFailureResult(-1, "activate participant failed! " + e.getMessage());
    } finally {
        ParticipantContext.clear();
    }
}
Also used : WebResponse(com.jd.httpservice.utils.web.WebResponse) IParticipantManagerService(com.jd.blockchain.peer.service.IParticipantManagerService) ParticipantContext(com.jd.blockchain.peer.service.ParticipantContext) BusinessException(utils.BusinessException) BftsmartNodeSettings(com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings) NetworkAddress(utils.net.NetworkAddress) ServiceEndpoint(com.jd.httpservice.agent.ServiceEndpoint)

Example 8 with WebResponse

use of com.jd.httpservice.utils.web.WebResponse in project jdchain-core by blockchain-jd-com.

the class GatewayGlobalExceptionHandler method json.

@ExceptionHandler(value = Exception.class)
@ResponseBody
public WebResponse json(HttpServletRequest req, Exception ex) {
    ErrorMessage message = null;
    String reqURL = "[" + req.getMethod() + "] " + req.getRequestURL().toString();
    if (ex instanceof BusinessException) {
        logger.error("BusinessException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " + ex.getMessage(), ex);
        BusinessException businessException = (BusinessException) ex;
        message = new ErrorMessage(businessException.getErrorCode(), businessException.getMessage());
    } else {
        logger.error("Unexpected exception occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "]" + ex.getMessage(), ex);
        message = new ErrorMessage(ErrorCode.UNEXPECTED.getValue(), ErrorCode.UNEXPECTED.getDescription(ex.getMessage()));
    }
    WebResponse response = WebResponse.createFailureResult(message);
    return response;
}
Also used : BusinessException(utils.BusinessException) WebResponse(com.jd.httpservice.utils.web.WebResponse) ErrorMessage(com.jd.httpservice.utils.web.WebResponse.ErrorMessage) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 9 with WebResponse

use of com.jd.httpservice.utils.web.WebResponse in project jdchain-core by blockchain-jd-com.

the class PeerGlobalExceptionHandler method json.

@ExceptionHandler(value = Exception.class)
@ResponseBody
public WebResponse json(HttpServletRequest req, Exception ex) {
    String reqURL = req.getRequestURL().insert(0, "[" + req.getMethod() + "] ").toString();
    ErrorMessage message = null;
    if (ex instanceof BusinessException) {
        logger.error("BusinessException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " + ex.getMessage(), ex);
        BusinessException businessException = (BusinessException) ex;
        message = new ErrorMessage(businessException.getErrorCode(), businessException.getMessage());
    } else if (ex instanceof JSONException) {
        logger.error("JSONException occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "] " + ex.getMessage(), ex);
        message = new ErrorMessage(ErrorCode.REQUEST_PARAM_FORMAT_ILLEGAL.getValue(), ErrorCode.REQUEST_PARAM_FORMAT_ILLEGAL.getDescription());
    } else {
        logger.error("Unexpected exception occurred! --[RequestURL=" + reqURL + "][" + ex.getClass().toString() + "]" + ex.getMessage(), ex);
        message = new ErrorMessage(ErrorCode.UNEXPECTED.getValue(), ErrorCode.UNEXPECTED.getDescription(ex.getMessage()));
    }
    WebResponse responseResult = WebResponse.createFailureResult(message);
    return responseResult;
}
Also used : BusinessException(utils.BusinessException) WebResponse(com.jd.httpservice.utils.web.WebResponse) JSONException(com.alibaba.fastjson.JSONException) ErrorMessage(com.jd.httpservice.utils.web.WebResponse.ErrorMessage) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 10 with WebResponse

use of com.jd.httpservice.utils.web.WebResponse in project jdchain-core by blockchain-jd-com.

the class ParticipantInactive method active.

public WebResponse active() throws Exception {
    String url = (secure ? "https://" : "http://") + host + ":" + port + "/management/delegate/activeparticipant";
    HttpPost httpPost = new HttpPost(url);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("ledgerHash", ledger));
    params.add(new BasicNameValuePair("consensusHost", host));
    params.add(new BasicNameValuePair("consensusPort", consensusPort + ""));
    params.add(new BasicNameValuePair("consensusStorage", consensusStorage));
    params.add(new BasicNameValuePair("consensusSecure", consensusSecure + ""));
    params.add(new BasicNameValuePair("remoteManageHost", synHost));
    params.add(new BasicNameValuePair("remoteManagePort", synPort + ""));
    params.add(new BasicNameValuePair("remoteManageSecure", synSecure + ""));
    params.add(new BasicNameValuePair("shutdown", shutdown + ""));
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    ServiceEndpoint endpoint = new ServiceEndpoint(host, port, secure);
    if (secure) {
        GmSSLProvider.enableGMSupport(participant.getSSLSecurity().getProtocol());
        endpoint.setSslSecurity(participant.getSSLSecurity());
    } else {
        endpoint.setSslSecurity(new SSLSecurity());
    }
    HttpResponse response = ServiceConnectionManager.buildHttpClient(endpoint).execute(httpPost);
    return (WebResponse) new JsonResponseConverter(WebResponse.class).getResponse(null, response.getEntity().getContent(), null);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) WebResponse(com.jd.httpservice.utils.web.WebResponse) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JsonResponseConverter(com.jd.httpservice.converters.JsonResponseConverter) ServiceEndpoint(com.jd.httpservice.agent.ServiceEndpoint) SSLSecurity(utils.net.SSLSecurity)

Aggregations

WebResponse (com.jd.httpservice.utils.web.WebResponse)10 BusinessException (utils.BusinessException)7 BftsmartNodeSettings (com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings)4 IParticipantManagerService (com.jd.blockchain.peer.service.IParticipantManagerService)4 ServiceEndpoint (com.jd.httpservice.agent.ServiceEndpoint)4 SSLSecurity (utils.net.SSLSecurity)3 ParticipantContext (com.jd.blockchain.peer.service.ParticipantContext)2 JsonResponseConverter (com.jd.httpservice.converters.JsonResponseConverter)2 ErrorMessage (com.jd.httpservice.utils.web.WebResponse.ErrorMessage)2 ArrayList (java.util.ArrayList)2 HttpResponse (org.apache.http.HttpResponse)2 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)2 HttpPost (org.apache.http.client.methods.HttpPost)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 NetworkAddress (utils.net.NetworkAddress)2 JSONException (com.alibaba.fastjson.JSONException)1 BlockchainIdentity (com.jd.blockchain.ledger.BlockchainIdentity)1 ContractInfo (com.jd.blockchain.ledger.ContractInfo)1