Example usage for io.netty.util TimerTask TimerTask

List of usage examples for io.netty.util TimerTask TimerTask

Introduction

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

Prototype

TimerTask

Source Link

Usage

From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

License:Apache License

@Override
public CompletableFuture<Void> snapshot(SnapshotDescription snapshotDesc) {
    HBaseProtos.SnapshotDescription snapshot = ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc);
    try {/*from w  w  w . j  a  v a2  s  . co m*/
        ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
    } catch (IllegalArgumentException e) {
        return failedFuture(e);
    }
    CompletableFuture<Void> future = new CompletableFuture<>();
    final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot).build();
    this.<Long>newMasterCaller()
            .action((controller, stub) -> this.<SnapshotRequest, SnapshotResponse, Long>call(controller, stub,
                    request, (s, c, req, done) -> s.snapshot(c, req, done), resp -> resp.getExpectedTimeout()))
            .call().whenComplete((expectedTimeout, err) -> {
                if (err != null) {
                    future.completeExceptionally(err);
                    return;
                }
                TimerTask pollingTask = new TimerTask() {
                    int tries = 0;
                    long startTime = EnvironmentEdgeManager.currentTime();
                    long endTime = startTime + expectedTimeout;
                    long maxPauseTime = expectedTimeout / maxAttempts;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (EnvironmentEdgeManager.currentTime() < endTime) {
                            isSnapshotFinished(snapshotDesc).whenComplete((done, err) -> {
                                if (err != null) {
                                    future.completeExceptionally(err);
                                } else if (done) {
                                    future.complete(null);
                                } else {
                                    // retry again after pauseTime.
                                    long pauseTime = ConnectionUtils
                                            .getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
                                    pauseTime = Math.min(pauseTime, maxPauseTime);
                                    AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
                                            TimeUnit.MILLISECONDS);
                                }
                            });
                        } else {
                            future.completeExceptionally(new SnapshotCreationException(
                                    "Snapshot '" + snapshot.getName() + "' wasn't completed in expectedTime:"
                                            + expectedTimeout + " ms",
                                    snapshotDesc));
                        }
                    }
                };
                AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
            });
    return future;
}

From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java

License:Apache License

@Override
public CompletableFuture<Void> execProcedure(String signature, String instance, Map<String, String> props) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ProcedureDescription procDesc = ProtobufUtil.buildProcedureDescription(signature, instance, props);
    this.<Long>newMasterCaller()
            .action((controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, Long>call(
                    controller, stub, ExecProcedureRequest.newBuilder().setProcedure(procDesc).build(),
                    (s, c, req, done) -> s.execProcedure(c, req, done), resp -> resp.getExpectedTimeout()))
            .call().whenComplete((expectedTimeout, err) -> {
                if (err != null) {
                    future.completeExceptionally(err);
                    return;
                }//from  w ww  . j  a  v a  2 s.c  o  m
                TimerTask pollingTask = new TimerTask() {
                    int tries = 0;
                    long startTime = EnvironmentEdgeManager.currentTime();
                    long endTime = startTime + expectedTimeout;
                    long maxPauseTime = expectedTimeout / maxAttempts;

                    @Override
                    public void run(Timeout timeout) throws Exception {
                        if (EnvironmentEdgeManager.currentTime() < endTime) {
                            isProcedureFinished(signature, instance, props).whenComplete((done, err) -> {
                                if (err != null) {
                                    future.completeExceptionally(err);
                                    return;
                                }
                                if (done) {
                                    future.complete(null);
                                } else {
                                    // retry again after pauseTime.
                                    long pauseTime = ConnectionUtils
                                            .getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
                                    pauseTime = Math.min(pauseTime, maxPauseTime);
                                    AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
                                            TimeUnit.MICROSECONDS);
                                }
                            });
                        } else {
                            future.completeExceptionally(
                                    new IOException("Procedure '" + signature + " : " + instance
                                            + "' wasn't completed in expectedTime:" + expectedTimeout + " ms"));
                        }
                    }
                };
                // Queue the polling task into RETRY_TIMER to poll procedure state asynchronously.
                AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
            });
    return future;
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannel.java

License:Apache License

/**
 * Get SASL handler/*w  w  w .  ja  v a  2s.  c  om*/
 * @param bootstrap to reconnect to
 * @return new SASL handler
 * @throws java.io.IOException if handler failed to create
 */
private SaslClientHandler getSaslHandler(final UserGroupInformation realTicket, final Bootstrap bootstrap)
        throws IOException {
    return new SaslClientHandler(realTicket, authMethod, token, serverPrincipal, client.fallbackAllowed,
            client.conf.get("hbase.rpc.protection",
                    SaslUtil.QualityOfProtection.AUTHENTICATION.name().toLowerCase()),
            new SaslClientHandler.SaslExceptionHandler() {
                @Override
                public void handle(int retryCount, Random random, Throwable cause) {
                    try {
                        // Handle Sasl failure. Try to potentially get new credentials
                        handleSaslConnectionFailure(retryCount, cause, realTicket);

                        // Try to reconnect
                        client.newTimeout(new TimerTask() {
                            @Override
                            public void run(Timeout timeout) throws Exception {
                                connect(bootstrap);
                            }
                        }, random.nextInt(reloginMaxBackoff) + 1, TimeUnit.MILLISECONDS);
                    } catch (IOException | InterruptedException e) {
                        close(e);
                    }
                }
            }, new SaslClientHandler.SaslSuccessfulConnectHandler() {
                @Override
                public void onSuccess(Channel channel) {
                    startHBaseConnection(channel);
                }
            });
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannel.java

License:Apache License

/**
 * Retry to connect or close//from  ww  w .j  a  v a 2  s  . co m
 *
 * @param bootstrap      to connect with
 * @param connectCounter amount of tries
 * @param e              exception of fail
 */
private void retryOrClose(final Bootstrap bootstrap, int connectCounter, Throwable e) {
    if (connectCounter < client.maxRetries) {
        client.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                connect(bootstrap);
            }
        }, client.failureSleep, TimeUnit.MILLISECONDS);
    } else {
        client.failedServers.addToFailedServers(address);
        close(e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannelImpl.java

License:Apache License

/**
 * Retry to connect or close/*from   w ww .j a v  a 2 s . com*/
 * @param bootstrap to connect with
 * @param failureCount failure count
 * @param e exception of fail
 */
private void retryOrClose(final Bootstrap bootstrap, int failureCount, long timeout, Throwable e) {
    if (failureCount < client.maxRetries) {
        client.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                connect(bootstrap);
            }
        }, timeout, TimeUnit.MILLISECONDS);
    } else {
        client.failedServers.addToFailedServers(address);
        close(e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.RpcConnection.java

License:Apache License

protected void scheduleTimeoutTask(final Call call) {
    if (call.timeout > 0) {
        call.timeoutTask = timeoutTimer.newTimeout(new TimerTask() {

            @Override/* w  w  w. j a v a  2  s .c  o  m*/
            public void run(Timeout timeout) throws Exception {
                call.setTimeout(new CallTimeoutException("Call id=" + call.id + ", waitTime="
                        + (EnvironmentEdgeManager.currentTime() - call.getStartTime()) + ", rpcTimeout="
                        + call.timeout));
                callTimeout(call);
            }
        }, call.timeout, TimeUnit.MILLISECONDS);
    }
}

From source file:org.opendaylight.bgpcep.programming.impl.ProgrammingServiceImpl.java

License:Open Source License

@Override
public synchronized ListenableFuture<Instruction> scheduleInstruction(final SubmitInstructionInput input)
        throws SchedulerException {
    final InstructionId id = input.getId();
    if (this.insns.get(id) != null) {
        LOG.info("Instruction ID {} already present", id);
        throw new SchedulerException("Instruction ID currently in use",
                new FailureBuilder().setType(DuplicateInstructionId.class).build());
    }//from   w w w .j  a v a2 s.  c om

    // First things first: check the deadline
    final Nanotime now = NanotimeUtil.currentTime();
    final BigInteger left = input.getDeadline().getValue().subtract(now.getValue());

    if (left.compareTo(BigInteger.ZERO) <= 0) {
        LOG.debug("Instruction {} deadline has already passed by {}ns", id, left);
        throw new SchedulerException("Instruction arrived after specified deadline",
                new FailureBuilder().setType(DeadOnArrival.class).build());
    }

    // Resolve dependencies
    final List<InstructionImpl> dependencies = checkDependencies(input);

    /*
     * All pre-flight checks done are at this point, the following
     * steps can only fail in catastrophic scenarios (OOM and the
     * like).
     */

    // Schedule a timeout for the instruction
    final Timeout t = this.timer.newTimeout(new TimerTask() {
        @Override
        public void run(final Timeout timeout) {
            timeoutInstruction(input.getId());
        }
    }, left.longValue(), TimeUnit.NANOSECONDS);

    // Put it into the instruction list
    final SettableFuture<Instruction> ret = SettableFuture.create();
    final InstructionImpl i = new InstructionImpl(new InstructionPusher(id, input.getDeadline()), ret, id,
            dependencies, t);
    this.insns.put(id, i);

    // Attach it into its dependencies
    for (final InstructionImpl d : dependencies) {
        d.addDependant(i);
    }

    /*
     * All done. The next part is checking whether the instruction can
     * run, which we can figure out after sending out the acknowledgement.
     * This task should be ingress-weighed, so we reinsert it into the
     * same execution service.
     */
    this.executor.submit(new Runnable() {
        @Override
        public void run() {
            tryScheduleInstruction(i);
        }
    });

    return ret;
}

From source file:org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator.java

License:Open Source License

private void start() {
    final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
    LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);

    channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());

    // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
    sendMessage((NetconfHelloMessage) helloMessage);

    replaceHelloMessageOutboundHandler();
    changeState(State.OPEN_WAIT);

    timeout = this.timer.newTimeout(new TimerTask() {
        @Override//from   ww  w  . j  a  v  a 2  s.c  om
        public void run(final Timeout timeout) {
            synchronized (this) {
                if (state != State.ESTABLISHED) {

                    LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);

                    // Do not fail negotiation if promise is done or canceled
                    // It would result in setting result of the promise second time and that throws exception
                    if (isPromiseFinished() == false) {
                        negotiationFailed(
                                new IllegalStateException("Session was not established after " + timeout));
                        changeState(State.FAILED);

                        channel.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                if (future.isSuccess()) {
                                    LOG.debug("Channel {} closed: success", future.channel());
                                } else {
                                    LOG.warn("Channel {} closed: fail", future.channel());
                                }
                            }
                        });
                    }
                } else if (channel.isOpen()) {
                    channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                }
            }
        }

        private boolean isPromiseFinished() {
            return promise.isDone() || promise.isCancelled();
        }

    }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
}

From source file:org.opendaylight.controller.netconf.util.AbstractNetconfSessionNegotiator.java

License:Open Source License

private void start() {
    final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
    logger.debug("Session negotiation started with hello message {}",
            XmlUtil.toString(helloMessage.getDocument()));

    sendMessage(helloMessage);/*from  w w w.j ava  2s .c o  m*/
    changeState(State.OPEN_WAIT);

    this.timer.newTimeout(new TimerTask() {
        @Override
        public void run(final Timeout timeout) throws Exception {
            synchronized (this) {
                if (state != State.ESTABLISHED) {
                    final IllegalStateException cause = new IllegalStateException(
                            "Session was not established after " + timeout);
                    negotiationFailed(cause);
                    changeState(State.FAILED);
                }
            }
        }
    }, INITIAL_HOLDTIMER, TimeUnit.MINUTES);
}

From source file:org.opendaylight.netconf.nettyutil.AbstractNetconfSessionNegotiator.java

License:Open Source License

private void start() {
    final NetconfHelloMessage helloMessage = this.sessionPreferences.getHelloMessage();
    LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);

    channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());

    sendMessage(helloMessage);//from   w  w  w.  j a v  a2s  . c  o  m

    replaceHelloMessageOutboundHandler();
    changeState(State.OPEN_WAIT);

    timeout = this.timer.newTimeout(new TimerTask() {
        @Override
        public void run(final Timeout timeout) {
            synchronized (this) {
                if (state != State.ESTABLISHED) {

                    LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);

                    // Do not fail negotiation if promise is done or canceled
                    // It would result in setting result of the promise second time and that throws exception
                    if (isPromiseFinished() == false) {
                        LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
                        changeState(State.FAILED);

                        channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                if (future.isSuccess()) {
                                    LOG.debug("Channel {} closed: success", future.channel());
                                } else {
                                    LOG.warn("Channel {} closed: fail", future.channel());
                                }
                            }
                        });
                    }
                } else if (channel.isOpen()) {
                    channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                }
            }
        }

        private boolean isPromiseFinished() {
            return promise.isDone() || promise.isCancelled();
        }

    }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
}