Search in sources :

Example 21 with TimerTask

use of io.netty.util.TimerTask in project netty-socketio by mrniko.

the class HashedWheelTimeoutScheduler method schedule.

@Override
public void schedule(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) {
    Timeout timeout = executorService.newTimeout(new TimerTask() {

        @Override
        public void run(Timeout timeout) throws Exception {
            try {
                runnable.run();
            } finally {
                scheduledFutures.remove(key);
            }
        }
    }, delay, unit);
    replaceScheduledFuture(key, timeout);
}
Also used : TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout)

Example 22 with TimerTask

use of io.netty.util.TimerTask 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 23 with TimerTask

use of io.netty.util.TimerTask 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 24 with TimerTask

use of io.netty.util.TimerTask in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method queryNodeVersion.

private void queryNodeVersion(ChannelHandlerContext ctx) throws JsonProcessingException {
    final String host = ChannelHandlerContextHelper.getPeerHost(ctx);
    String seq = UUID.randomUUID().toString().replaceAll("-", "");
    Request<?, NodeVersion> request = new Request<>("getClientVersion", Arrays.asList(), null, NodeVersion.class);
    byte[] payload = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(request);
    String content = new String(payload);
    logger.info(" query node version host: {}, seq: {}, content: {}", host, seq, content);
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setType((short) ChannelMessageType.CHANNEL_RPC_REQUEST.getType());
    bcosMessage.setSeq(seq);
    bcosMessage.setResult(0);
    bcosMessage.setData(payload);
    ByteBuf byteBuf = ctx.alloc().buffer();
    bcosMessage.writeHeader(byteBuf);
    bcosMessage.writeExtra(byteBuf);
    BcosResponseCallback callback = new BcosResponseCallback() {

        @Override
        public void onResponse(BcosResponse response) {
            try {
                if (response.getErrorCode() == ChannelMessageError.MESSAGE_TIMEOUT.getError()) {
                    // The fisco node version number is below 2.1.0 when request timeout
                    ChannelHandlerContextHelper.setProtocolVersion(ctx, EnumChannelProtocolVersion.VERSION_1, "below-2.1.0-timeout");
                    logger.info(" query node version timeout, content: {}", response.getContent());
                    sendUpdateTopicMessage(ctx);
                    queryBlockNumber(ctx);
                    return;
                } else if (response.getErrorCode() != 0) {
                    logger.error(" fisco node version response, code: {}, message: {}", response.getErrorCode(), response.getErrorMessage());
                    throw new ChannelPrococolExceiption(" query node version failed, code: " + response.getErrorCode() + ", message: " + response.getErrorMessage());
                }
                Response<NodeVersion.Version> nodeVersion = ObjectMapperFactory.getObjectMapper().readValue(response.getContent(), NodeVersion.class);
                logger.info(" node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                if (EnumNodeVersion.channelProtocolHandleShakeSupport(nodeVersion.getResult().getSupportedVersion())) {
                    // fisco node support channel protocol handshake, start it
                    logger.info(" support channel handshake node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                    queryChannelProtocolVersion(ctx);
                } else {
                    // default channel protocol
                    ChannelHandlerContextHelper.setProtocolVersion(ctx, EnumChannelProtocolVersion.VERSION_1, nodeVersion.getResult().getSupportedVersion());
                    logger.info(" not support channel handshake set default ,node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                    sendUpdateTopicMessage(ctx);
                    queryBlockNumber(ctx);
                // channelService.getEventLogFilterManager().sendFilter();
                }
            } catch (Exception e) {
                logger.error(" query node version failed, message: {}", e.getMessage());
                ctx.writeAndFlush("").addListener(ChannelFutureListener.CLOSE);
            }
        }
    };
    final BcosResponseCallback callbackInner = callback;
    callback.setTimeout(channelService.getTimeoutHandler().newTimeout(new TimerTask() {

        BcosResponseCallback _callback = callbackInner;

        @Override
        public void run(Timeout timeout) throws Exception {
            // handle timer
            _callback.onTimeout();
            logger.error("queryNodeVersion timeout, seq: {}", bcosMessage.getSeq());
        }
    }, queryNodeVersionTimeoutMS, TimeUnit.MILLISECONDS));
    channelService.getSeq2Callback().put(seq, callback);
    ctx.writeAndFlush(byteBuf);
}
Also used : BcosResponseCallback(org.fisco.bcos.channel.client.BcosResponseCallback) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) ChannelPrococolExceiption(org.fisco.bcos.channel.protocol.ChannelPrococolExceiption) Timeout(io.netty.util.Timeout) Request(org.fisco.bcos.web3j.protocol.core.Request) ByteBuf(io.netty.buffer.ByteBuf) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) EnumNodeVersion(org.fisco.bcos.fisco.EnumNodeVersion) NodeVersion(org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) TimerTask(io.netty.util.TimerTask) EnumNodeVersion(org.fisco.bcos.fisco.EnumNodeVersion) EnumChannelProtocolVersion(org.fisco.bcos.channel.protocol.EnumChannelProtocolVersion) NodeVersion(org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion)

Example 25 with TimerTask

use of io.netty.util.TimerTask in project redisson by redisson.

the class CommandAsyncService method async.

protected <V, R> void async(final boolean readOnlyMode, final NodeSource source, final Codec codec, final RedisCommand<V> command, final Object[] params, final RPromise<R> mainPromise, final int attempt) {
    if (mainPromise.isCancelled()) {
        return;
    }
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown"));
        return;
    }
    final AsyncDetails<V, R> details = AsyncDetails.acquire();
    if (isRedissonReferenceSupportEnabled()) {
        try {
            for (int i = 0; i < params.length; i++) {
                RedissonReference reference = redisson != null ? RedissonObjectFactory.toReference(redisson, params[i]) : RedissonObjectFactory.toReference(redissonReactive, params[i]);
                params[i] = reference == null ? params[i] : reference;
            }
        } catch (Exception e) {
            connectionManager.getShutdownLatch().release();
            mainPromise.tryFailure(e);
            return;
        }
    }
    final RFuture<RedisConnection> connectionFuture;
    if (readOnlyMode) {
        connectionFuture = connectionManager.connectionReadOp(source, command);
    } else {
        connectionFuture = connectionManager.connectionWriteOp(source, command);
    }
    final RPromise<R> attemptPromise = connectionManager.newPromise();
    details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise, attempt);
    final TimerTask retryTimerTask = new TimerTask() {

        @Override
        public void run(Timeout t) throws Exception {
            if (details.getAttemptPromise().isDone()) {
                return;
            }
            if (details.getConnectionFuture().cancel(false)) {
                connectionManager.getShutdownLatch().release();
            } else {
                if (details.getConnectionFuture().isSuccess()) {
                    ChannelFuture writeFuture = details.getWriteFuture();
                    if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
                        return;
                    }
                }
            }
            if (details.getMainPromise().isCancelled()) {
                if (details.getAttemptPromise().cancel(false)) {
                    AsyncDetails.release(details);
                }
                return;
            }
            if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Command execution timeout for command: " + command + " with params: " + LogHelper.toString(details.getParams())));
                }
                details.getAttemptPromise().tryFailure(details.getException());
                return;
            }
            if (!details.getAttemptPromise().cancel(false)) {
                return;
            }
            int count = details.getAttempt() + 1;
            if (log.isDebugEnabled()) {
                log.debug("attempt {} for command {} and params {}", count, details.getCommand(), Arrays.toString(details.getParams()));
            }
            async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(), count);
            AsyncDetails.release(details);
        }
    };
    Timeout timeout = connectionManager.newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);
    connectionFuture.addListener(new FutureListener<RedisConnection>() {

        @Override
        public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
            if (connFuture.isCancelled()) {
                return;
            }
            if (!connFuture.isSuccess()) {
                connectionManager.getShutdownLatch().release();
                details.setException(convertException(connectionFuture));
                return;
            }
            if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) {
                releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
                return;
            }
            final RedisConnection connection = connFuture.getNow();
            if (details.getSource().getRedirect() == Redirect.ASK) {
                List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(2);
                RPromise<Void> promise = connectionManager.newPromise();
                list.add(new CommandData<Void, Void>(promise, details.getCodec(), RedisCommands.ASKING, new Object[] {}));
                list.add(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
                RPromise<Void> main = connectionManager.newPromise();
                ChannelFuture future = connection.send(new CommandsData(main, list));
                details.setWriteFuture(future);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("aquired connection for command {} and params {} from slot {} using node {}", details.getCommand(), Arrays.toString(details.getParams()), details.getSource(), connection.getRedisClient().getAddr());
                }
                ChannelFuture future = connection.send(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams()));
                details.setWriteFuture(future);
            }
            details.getWriteFuture().addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    checkWriteFuture(details, connection);
                }
            });
            releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details);
        }
    });
    attemptPromise.addListener(new FutureListener<R>() {

        @Override
        public void operationComplete(Future<R> future) throws Exception {
            checkAttemptFuture(source, details, future);
        }
    });
}
Also used : RPromise(org.redisson.misc.RPromise) TimerTask(io.netty.util.TimerTask) List(java.util.List) ArrayList(java.util.ArrayList) CommandsData(org.redisson.client.protocol.CommandsData) ChannelFuture(io.netty.channel.ChannelFuture) RedissonReference(org.redisson.RedissonReference) Timeout(io.netty.util.Timeout) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RedisAskException(org.redisson.client.RedisAskException) RedisLoadingException(org.redisson.client.RedisLoadingException) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedisException(org.redisson.client.RedisException) RedisMovedException(org.redisson.client.RedisMovedException) WriteRedisConnectionException(org.redisson.client.WriteRedisConnectionException) RedisTryAgainException(org.redisson.client.RedisTryAgainException) RedissonShutdownException(org.redisson.RedissonShutdownException) RedisTimeoutException(org.redisson.client.RedisTimeoutException) RedissonShutdownException(org.redisson.RedissonShutdownException) CommandData(org.redisson.client.protocol.CommandData) RedisConnection(org.redisson.client.RedisConnection)

Aggregations

Timeout (io.netty.util.Timeout)38 TimerTask (io.netty.util.TimerTask)38 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 AtomicLong (java.util.concurrent.atomic.AtomicLong)8 RFuture (org.redisson.api.RFuture)8 RedisTimeoutException (org.redisson.client.RedisTimeoutException)7 FutureListener (io.netty.util.concurrent.FutureListener)6 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelFuture (io.netty.channel.ChannelFuture)5 Future (io.netty.util.concurrent.Future)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 ArrayList (java.util.ArrayList)5 RedisException (org.redisson.client.RedisException)5 WriteRedisConnectionException (org.redisson.client.WriteRedisConnectionException)5 CompletableFutureWrapper (org.redisson.misc.CompletableFutureWrapper)5 RedisConnection (org.redisson.client.RedisConnection)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ChannelFutureListener (io.netty.channel.ChannelFutureListener)3 IOException (java.io.IOException)3