Example usage for io.netty.util Timeout cancel

List of usage examples for io.netty.util Timeout cancel

Introduction

In this page you can find the example usage for io.netty.util Timeout cancel.

Prototype

boolean cancel();

Source Link

Document

Attempts to cancel the TimerTask associated with this handle.

Usage

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSession.java

License:Apache License

private void bumpTimeout(final ChannelHandlerContext ctx) {
    final Timeout timeout = timer.newTimeout(heartbeatTimeout(ctx.channel(), future), heartbeatInterval,
            TimeUnit.MILLISECONDS);

    final Timeout old = heartbeatTimeout.getAndSet(timeout);

    if (old != null) {
        old.cancel();
    }/*from ww  w  .j  av  a  2 s  .c o  m*/
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSessionInitializer.java

License:Apache License

@Override
protected void initChannel(final Channel ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override/* w ww .j a  va2  s. c o m*/
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            bumpTimeout(ctx);
            ctx.fireChannelRead(msg);
        }
    });

    // first four bytes are length prefix of message, strip first four bytes.
    pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4));
    pipeline.addLast(new NativeRpcDecoder());
    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
        @Override
        protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            if (msg instanceof NativeRpcError) {
                final NativeRpcError error = (NativeRpcError) msg;

                if (log.isTraceEnabled()) {
                    log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage());
                }

                future.fail(new NativeRpcRemoteException(address, error.getMessage()));
                ctx.channel().close();
                return;
            }

            if (msg instanceof NativeRpcResponse) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] response: cancelling heartbeat", ctx.channel());
                }

                final Timeout old = heartbeatTimeout.getAndSet(null);

                if (old != null) {
                    old.cancel();
                }

                final NativeRpcResponse response = (NativeRpcResponse) msg;
                final R responseBody = mapper.readValue(response.getBody(), expected);
                future.resolve(responseBody);
                return;
            }

            if (msg instanceof NativeRpcHeartBeat) {
                if (log.isTraceEnabled()) {
                    log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval);
                }

                bumpTimeout(ctx);
                return;
            }

            throw new IllegalArgumentException("unable to handle type: " + msg);
        }
    });

    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            future.fail(cause);
        }
    });

    pipeline.addLast(new LengthFieldPrepender(4));
    pipeline.addLast(new NativeRpcEncoder());
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcServerSession.java

License:Apache License

/**
 * Stop any current timeout, if pending.
 *//*from  www  .j a  v  a 2  s.c  o m*/
private void stopCurrentTimeout(final AtomicReference<Timeout> heartbeatTimeout) {
    final Timeout old = heartbeatTimeout.getAndSet(null);

    if (old != null) {
        old.cancel();
    }
}

From source file:com.yahoo.pulsar.client.impl.ConsumerImpl.java

License:Apache License

@Override
public CompletableFuture<Void> closeAsync() {
    if (state.get() == State.Closing || state.get() == State.Closed) {
        batchMessageAckTracker.clear();/*from w  w w  . ja  v a 2  s  .c o  m*/
        unAckedMessageTracker.close();
        return CompletableFuture.completedFuture(null);
    }

    if (!isConnected()) {
        log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription);
        state.set(State.Closed);
        batchMessageAckTracker.clear();
        unAckedMessageTracker.close();
        client.cleanupConsumer(this);
        return CompletableFuture.completedFuture(null);
    }

    Timeout timeout = stats.getStatTimeout();
    if (timeout != null) {
        timeout.cancel();
    }

    state.set(State.Closing);

    long requestId = client.newRequestId();
    ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId);

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
        cnx.removeConsumer(consumerId);
        if (exception == null || !cnx.ctx().channel().isActive()) {
            log.info("[{}] [{}] Closed consumer", topic, subscription);
            state.set(State.Closed);
            batchMessageAckTracker.clear();
            unAckedMessageTracker.close();
            closeFuture.complete(null);
            client.cleanupConsumer(this);
        } else {
            closeFuture.completeExceptionally(exception);
        }
        return null;
    });

    return closeFuture;
}

From source file:com.yahoo.pulsar.client.impl.ProducerImpl.java

License:Apache License

@Override
public CompletableFuture<Void> closeAsync() {
    if (state.get() == State.Closing || state.get() == State.Closed) {
        return CompletableFuture.completedFuture(null);
    }/* w w w.  j  ava  2 s.co  m*/

    if (!isConnected()) {
        log.info("[{}] [{}] Closed Producer (not connected)", topic, producerName);
        synchronized (this) {
            state.set(State.Closed);
            client.cleanupProducer(this);
            pendingMessages.forEach(msg -> {
                msg.cmd.release();
                msg.recycle();
            });
            pendingMessages.clear();
        }

        return CompletableFuture.completedFuture(null);
    }

    state.set(State.Closing);

    Timeout timeout = sendTimeout;
    if (timeout != null) {
        timeout.cancel();
    }
    timeout = stats.getStatTimeout();
    if (timeout != null) {
        timeout.cancel();
    }

    long requestId = client.newRequestId();
    ByteBuf cmd = Commands.newCloseProducer(producerId, requestId);

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
        cnx.removeProducer(producerId);
        if (exception == null || !cnx.ctx().channel().isActive()) {
            // Either we've received the success response for the close producer command from the broker, or the
            // connection did break in the meantime. In any case, the producer is gone.
            synchronized (ProducerImpl.this) {
                log.info("[{}] [{}] Closed Producer", topic, producerName);
                state.set(State.Closed);
                pendingMessages.forEach(msg -> {
                    msg.cmd.release();
                    msg.recycle();
                });
                pendingMessages.clear();
            }

            closeFuture.complete(null);
            client.cleanupProducer(this);
        } else {
            closeFuture.completeExceptionally(exception);
        }

        return null;
    });

    return closeFuture;
}

From source file:io.lettuce.core.PlainChannelInitializer.java

License:Apache License

static void pingBeforeActivate(AsyncCommand<?, ?, ?> cmd, CompletableFuture<Boolean> initializedFuture,
        ChannelHandlerContext ctx, ClientResources clientResources, Duration timeout) throws Exception {

    ctx.fireUserEventTriggered(new PingBeforeActivate(cmd));

    Runnable timeoutGuard = () -> {

        if (cmd.isDone() || initializedFuture.isDone()) {
            return;
        }//from   w ww  .j  ava2 s  .co  m

        initializedFuture.completeExceptionally(ExceptionFactory
                .createTimeoutException("Cannot initialize channel (PING before activate)", timeout));
    };

    Timeout timeoutHandle = clientResources.timer().newTimeout(t -> {

        if (clientResources.eventExecutorGroup().isShuttingDown()) {
            timeoutGuard.run();
            return;
        }

        clientResources.eventExecutorGroup().submit(timeoutGuard);
    }, timeout.toNanos(), TimeUnit.NANOSECONDS);

    cmd.whenComplete((o, throwable) -> {

        timeoutHandle.cancel();

        if (throwable == null) {
            ctx.fireChannelActive();
            initializedFuture.complete(true);
        } else {
            initializedFuture.completeExceptionally(throwable);
        }
    });

}

From source file:io.lettuce.core.protocol.ConnectionWatchdog.java

License:Apache License

void prepareClose() {

    setListenOnChannelInactive(false);//from   ww  w  .ja va2  s  .c  om
    setReconnectSuspended(true);

    Timeout reconnectScheduleTimeout = this.reconnectScheduleTimeout;
    if (reconnectScheduleTimeout != null && !reconnectScheduleTimeout.isCancelled()) {
        reconnectScheduleTimeout.cancel();
    }

    reconnectionHandler.prepareClose();
}

From source file:io.lettuce.core.protocol.ReconnectionHandler.java

License:Apache License

private void reconnect0(CompletableFuture<Channel> result, SocketAddress remoteAddress) {

    ChannelFuture connectFuture = bootstrap.connect(remoteAddress);
    ChannelPromise initFuture = connectFuture.channel().newPromise();

    logger.debug("Reconnecting to Redis at {}", remoteAddress);

    result.whenComplete((c, t) -> {/*from  w w  w .j a va 2  s . c  om*/

        if (t instanceof CancellationException) {
            connectFuture.cancel(true);
            initFuture.cancel(true);
        }
    });

    initFuture.addListener((ChannelFuture it) -> {

        if (it.cause() != null) {

            connectFuture.cancel(true);
            close(it.channel());
            result.completeExceptionally(it.cause());
        } else {
            result.complete(connectFuture.channel());
        }
    });

    connectFuture.addListener((ChannelFuture it) -> {

        if (it.cause() != null) {

            initFuture.tryFailure(it.cause());
            return;
        }

        ChannelPipeline pipeline = it.channel().pipeline();
        RedisChannelInitializer channelInitializer = pipeline.get(RedisChannelInitializer.class);

        if (channelInitializer == null) {

            initFuture.tryFailure(new IllegalStateException(
                    "Reconnection attempt without a RedisChannelInitializer in the channel pipeline"));
            return;
        }

        channelInitializer.channelInitialized().whenComplete((state, throwable) -> {

            if (throwable != null) {

                if (isExecutionException(throwable)) {
                    initFuture.tryFailure(throwable);
                    return;
                }

                if (clientOptions.isCancelCommandsOnReconnectFailure()) {
                    connectionFacade.reset();
                }

                if (clientOptions.isSuspendReconnectOnProtocolFailure()) {

                    logger.error("Disabling autoReconnect due to initialization failure", throwable);
                    setReconnectSuspended(true);
                }

                initFuture.tryFailure(throwable);

                return;
            }

            if (logger.isDebugEnabled()) {
                logger.info("Reconnected to {}, Channel {}", remoteAddress,
                        ChannelLogDescriptor.logDescriptor(it.channel()));
            } else {
                logger.info("Reconnected to {}", remoteAddress);
            }

            initFuture.trySuccess();
        });
    });

    Runnable timeoutAction = () -> {
        initFuture.tryFailure(new TimeoutException(
                String.format("Reconnection attempt exceeded timeout of %d %s ", timeout, timeoutUnit)));
    };

    Timeout timeoutHandle = timer.newTimeout(it -> {

        if (connectFuture.isDone() && initFuture.isDone()) {
            return;
        }

        if (reconnectWorkers.isShutdown()) {
            timeoutAction.run();
            return;
        }

        reconnectWorkers.submit(timeoutAction);

    }, this.timeout, timeoutUnit);

    initFuture.addListener(it -> timeoutHandle.cancel());
}

From source file:io.pravega.controller.timeout.TimerWheelTimeoutService.java

License:Open Source License

@Override
public PingTxnStatus pingTxn(final String scope, final String stream, final UUID txnId, long lease) {

    if (!this.isRunning()) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.DISCONNECTED).build();
    }//from   w  w w.  j  av  a 2s .  com

    final String key = getKey(scope, stream, txnId);
    Preconditions.checkState(map.containsKey(key), "Stream not found in the map");

    final TxnData txnData = map.get(key);

    if (lease > maxLeaseValue || lease > txnData.getScaleGracePeriod()) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.LEASE_TOO_LARGE).build();
    }

    if (lease + System.currentTimeMillis() > txnData.getMaxExecutionTimeExpiry()) {
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.MAX_EXECUTION_TIME_EXCEEDED).build();
    } else {
        Timeout timeout = txnData.getTimeout();
        timeout.cancel();
        Timeout newTimeout = hashedWheelTimer.newTimeout(timeout.task(), lease, TimeUnit.MILLISECONDS);
        txnData.setTimeout(newTimeout);
        return PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.OK).build();
    }

}

From source file:net.qing.sms.simulator.HashedWheelScheduler.java

License:Apache License

public void schedule(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) {
    Timeout timeout = executorService.newTimeout(new TimerTask() {
        @Override//from ww w. j a va  2  s. c om
        public void run(Timeout timeout) throws Exception {
            try {
                runnable.run();
            } finally {
                scheduledFutures.remove(key);
            }
        }
    }, delay, unit);

    if (!timeout.isExpired()) {
        Timeout preTimeout = scheduledFutures.put(key, timeout);
        if (preTimeout != null) {
            preTimeout.cancel();
        }
    }
}