Search in sources :

Example 1 with ChannelConnections

use of org.fisco.bcos.channel.handler.ChannelConnections in project web3sdk by FISCO-BCOS.

the class Service method asyncSendEthereumMessage.

public void asyncSendEthereumMessage(BcosRequest request, BcosResponseCallback callback) {
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setSeq(request.getMessageID());
    bcosMessage.setResult(0);
    bcosMessage.setType((short) 0x12);
    bcosMessage.setData(request.getContent().getBytes());
    // select node
    try {
        ChannelConnections channelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
        if (channelConnections == null) {
            if (orgID != null) {
                logger.error("not found:{}", orgID);
                throw new TransactionException("not found orgID");
            } else {
                logger.error("not found:{}", agencyName);
                throw new TransactionException("not found agencyName");
            }
        }
        ChannelHandlerContext ctx = channelConnections.randomNetworkConnection(nodeToBlockNumberMap);
        ByteBuf out = ctx.alloc().buffer();
        bcosMessage.writeHeader(out);
        bcosMessage.writeExtra(out);
        seq2Callback.put(request.getMessageID(), callback);
        if (request.getTimeout() > 0) {
            final BcosResponseCallback callbackInner = callback;
            callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                BcosResponseCallback _callback = callbackInner;

                @Override
                public void run(Timeout timeout) throws Exception {
                    logger.error("process bcos message timeout, seq: {}, timeout: {}", bcosMessage.getSeq(), request.getTimeout());
                    // handle timer
                    _callback.onTimeout();
                }
            }, request.getTimeout(), TimeUnit.MILLISECONDS));
        }
        ctx.writeAndFlush(out);
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        InetSocketAddress socketAddress = socketChannel.remoteAddress();
        logger.debug("selected node {}:{} bcos request, seq:{}", socketAddress.getAddress().getHostAddress(), socketAddress.getPort(), bcosMessage.getSeq());
    } catch (Exception e) {
        logger.error(" error message:{}, error: {} ", e.getMessage(), e);
        BcosResponse response = new BcosResponse();
        response.setErrorCode(-1);
        response.setErrorMessage(e.getMessage() + " requset send failed! please check the log file content for reasons.");
        response.setContent("");
        response.setMessageID(request.getMessageID());
        if (callback.getTimeout() != null) {
            callback.getTimeout().cancel();
        }
        callback.onResponse(response);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) SocketChannel(io.netty.channel.socket.SocketChannel) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with ChannelConnections

use of org.fisco.bcos.channel.handler.ChannelConnections in project web3sdk by FISCO-BCOS.

the class Service method asyncSendChannelMessage2.

public void asyncSendChannelMessage2(ChannelRequest request, ChannelResponseCallback2 callback) {
    try {
        if (request.getContentByteArray().length >= 32 * 1024 * 1024) {
            logger.error("send byte length should not greater than 32M now length:{}", request.getContentByteArray().length);
            throw new AmopException("send byte length should not greater than 32M");
        }
        logger.debug("ChannelRequest:{} ", request.getMessageID());
        callback.setService(this);
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        // channelMessage.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
        if (request.getType() == 0) {
            channelMessage.setType((short) ChannelMessageType.AMOP_REQUEST.getType());
        } else {
            channelMessage.setType(request.getType());
        }
        channelMessage.setData(request.getContentByteArray());
        channelMessage.setTopic(request.getToTopic());
        logger.info("msgid:{} type:{} topic:{}", request.getMessageID(), channelMessage.getType(), request.getToTopic());
        try {
            List<ConnectionInfo> fromConnectionInfos = new ArrayList<ConnectionInfo>();
            // select send node
            ChannelConnections fromChannelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
            if (fromChannelConnections == null) {
                if (orgID != null) {
                    logger.error("not found:{}", orgID);
                    throw new Exception("not found orgID");
                } else {
                    logger.error("not found:{}", agencyName);
                    throw new Exception("not found agencyName");
                }
            }
            fromConnectionInfos.addAll(fromChannelConnections.getConnections());
            logger.debug("FromOrg:{} nodes:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            callback.setFromChannelConnections(fromChannelConnections);
            callback.setFromConnectionInfos(fromConnectionInfos);
            // set request content
            callback.setRequest(channelMessage);
            logger.info("put msgid:{} into callback map", request.getMessageID());
            seq2Callback.put(request.getMessageID(), callback);
            if (request.getTimeout() > 0) {
                logger.info("timeoutms:{}", request.getTimeout());
                final ChannelResponseCallback2 callbackInner = callback;
                callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                    ChannelResponseCallback2 _callback = callbackInner;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        // process timeout logic
                        _callback.onTimeout();
                        logger.error("process channel message timeout, seq: {}, timeout: {}", channelMessage.getSeq(), request.getTimeout());
                    }
                }, request.getTimeout(), TimeUnit.MILLISECONDS));
            }
            callback.retrySendMessage();
        } catch (Exception e) {
            logger.error("send message fail:", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(ChannelMessageError.MESSAGE_SEND_EXCEPTION.getError());
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            callback.onResponse(response);
            return;
        }
    } catch (Exception e) {
        logger.error("system error", e);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) ArrayList(java.util.ArrayList) ConnectionInfo(org.fisco.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 3 with ChannelConnections

use of org.fisco.bcos.channel.handler.ChannelConnections in project web3sdk by FISCO-BCOS.

the class Service method run.

public void run() throws Exception {
    logger.debug("init ChannelService");
    if (setJavaOpt) {
        initJavaOpt();
    }
    parseFromTopic2KeyInfo();
    int flag = 0;
    for (ChannelConnections channelConnections : allChannelConnections.getAllChannelConnections()) {
        if (channelConnections.getGroupId() == groupId) {
            flag = 1;
            try {
                ConnectionCallback connectionCallback = new ConnectionCallback(topics);
                connectionCallback.setChannelService(this);
                channelConnections.setCallback(connectionCallback);
                channelConnections.setCaCert(allChannelConnections.getCaCert());
                channelConnections.setSslCert(allChannelConnections.getSslCert());
                channelConnections.setSslKey(allChannelConnections.getSslKey());
                channelConnections.setGmCaCert(allChannelConnections.getGmCaCert());
                channelConnections.setGmEnSslCert(allChannelConnections.getGmEnSslCert());
                channelConnections.setGmEnSslKey(allChannelConnections.getGmEnSslKey());
                channelConnections.setGmSslCert(allChannelConnections.getGmSslCert());
                channelConnections.setGmSslKey(allChannelConnections.getGmSslKey());
                channelConnections.init();
                channelConnections.setThreadPool(threadPool);
                channelConnections.startConnect();
                int sleepTime = 0;
                boolean running = false;
                while (true) {
                    Map<String, ChannelHandlerContext> networkConnection = channelConnections.getNetworkConnections();
                    for (ChannelHandlerContext ctx : networkConnection.values()) {
                        if (Objects.nonNull(ctx) && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
                            running = true;
                            break;
                        }
                    }
                    if (running || sleepTime > connectSeconds * 1000) {
                        break;
                    } else {
                        Thread.sleep(connectSleepPerMillis);
                        sleepTime += connectSleepPerMillis;
                    }
                }
                String baseMessage = " nodes: " + channelConnections.getConnectionsStr() + " ,groupId: " + String.valueOf(groupId) + " ,caCert: " + channelConnections.getCaCert() + " ,sslKey: " + channelConnections.getSslKey() + " ,sslCert: " + channelConnections.getSslCert() + " ,java version: " + System.getProperty("java.version") + " ,java vendor: " + System.getProperty("java.vm.vendor");
                if (!running) {
                    String errorMessage = " Failed to connect to " + baseMessage;
                    logger.error(errorMessage);
                    throw new Exception(errorMessage);
                }
                logger.info(" Connect to " + baseMessage);
                channelConnections.startPeriodTask();
                eventLogFilterManager.start();
            } catch (InterruptedException e) {
                logger.warn(" thread interrupted exception: ", e);
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                logger.error(" service init failed, error message: {}, error: ", e.getMessage(), e);
                throw e;
            }
        }
    }
    if (flag == 0) {
        throw new Exception("Please set the right groupId ");
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ConnectionCallback(org.fisco.bcos.channel.handler.ConnectionCallback) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 4 with ChannelConnections

use of org.fisco.bcos.channel.handler.ChannelConnections in project web3sdk by FISCO-BCOS.

the class Service method asyncMulticastChannelMessage2.

public void asyncMulticastChannelMessage2(ChannelRequest request) {
    try {
        logger.debug("ChannelRequest:{} ", request.getMessageID());
        ChannelMessage2 channelMessage = new ChannelMessage2();
        channelMessage.setSeq(request.getMessageID());
        channelMessage.setResult(0);
        channelMessage.setType((short) ChannelMessageType.AMOP_MULBROADCAST.getType());
        channelMessage.setData(request.getContentByteArray());
        channelMessage.setTopic(request.getToTopic());
        try {
            // set request content
            ChannelConnections fromChannelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
            if (fromChannelConnections == null) {
                if (orgID != null) {
                    logger.error("not found:{}", orgID);
                    throw new Exception("not found orgID");
                } else {
                    logger.error("not found:{}", agencyName);
                    throw new Exception("not found agencyName");
                }
            }
            logger.debug("FromOrg:{} nodes:{}", request.getFromOrg(), fromChannelConnections.getConnections().size());
            for (ConnectionInfo connectionInfo : fromChannelConnections.getConnections()) {
                ChannelHandlerContext ctx = fromChannelConnections.getNetworkConnectionByHost(connectionInfo.getHost(), connectionInfo.getPort());
                if (ctx != null && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
                    ByteBuf out = ctx.alloc().buffer();
                    channelMessage.writeHeader(out);
                    channelMessage.writeExtra(out);
                    ctx.writeAndFlush(out);
                    logger.debug("send message to{}:{} success ", connectionInfo.getHost(), connectionInfo.getPort());
                } else {
                    logger.error("sending node unavailable, {}:{}", connectionInfo.getHost(), connectionInfo.getPort());
                }
            }
        } catch (Exception e) {
            logger.error("send message fail:{}", e);
            ChannelResponse response = new ChannelResponse();
            response.setErrorCode(ChannelMessageError.MESSAGE_SEND_EXCEPTION.getError());
            response.setMessageID(request.getMessageID());
            response.setErrorMessage(e.getMessage());
            response.setContent("");
            return;
        }
    } catch (Exception e) {
        logger.error("system error:{}", e);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ConnectionInfo(org.fisco.bcos.channel.handler.ConnectionInfo) ChannelResponse(org.fisco.bcos.channel.dto.ChannelResponse) ByteBuf(io.netty.buffer.ByteBuf) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 5 with ChannelConnections

use of org.fisco.bcos.channel.handler.ChannelConnections in project web3sdk by FISCO-BCOS.

the class Service method updateTopicsToNode.

public void updateTopicsToNode() {
    logger.info(" updateTopicToNode, groupId: {}, topics: {}", groupId, getTopics());
    // select send node
    ChannelConnections channelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
    if (Objects.isNull(channelConnections)) {
        throw new IllegalArgumentException(" No group configuration was found, groupId: " + groupId);
    }
    ConnectionCallback callback = (ConnectionCallback) channelConnections.getCallback();
    if (Objects.isNull(callback)) {
        throw new IllegalArgumentException(" No callback was found for ChannelConnections, service is not initialized");
    }
    callback.setTopics(getTopics());
    /**
     * send update topic message to all connected nodes
     */
    Map<String, ChannelHandlerContext> networkConnections = channelConnections.getNetworkConnections();
    for (ChannelHandlerContext ctx : networkConnections.values()) {
        if (Objects.nonNull(ctx) && ChannelHandlerContextHelper.isChannelAvailable(ctx)) {
            try {
                callback.sendUpdateTopicMessage(ctx);
            } catch (Exception e) {
                logger.debug(" e: ", e);
            }
        }
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) ConnectionCallback(org.fisco.bcos.channel.handler.ConnectionCallback) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 IOException (java.io.IOException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 NoSuchProviderException (java.security.NoSuchProviderException)5 CertificateException (java.security.cert.CertificateException)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)5 ChannelConnections (org.fisco.bcos.channel.handler.ChannelConnections)5 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)4 ByteBuf (io.netty.buffer.ByteBuf)2 Timeout (io.netty.util.Timeout)2 TimerTask (io.netty.util.TimerTask)2 ChannelMessage2 (org.fisco.bcos.channel.dto.ChannelMessage2)2 ChannelResponse (org.fisco.bcos.channel.dto.ChannelResponse)2 ConnectionCallback (org.fisco.bcos.channel.handler.ConnectionCallback)2 ConnectionInfo (org.fisco.bcos.channel.handler.ConnectionInfo)2 SocketChannel (io.netty.channel.socket.SocketChannel)1 InetSocketAddress (java.net.InetSocketAddress)1