Example usage for io.netty.util Timer stop

List of usage examples for io.netty.util Timer stop

Introduction

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

Prototype

Set<Timeout> stop();

Source Link

Document

Releases all resources acquired by this Timer and cancels all tasks which were scheduled but not executed yet.

Usage

From source file:com.datastax.driver.core.NettyOptions.java

License:Apache License

/**
 * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
 * <p/>/*from w  w  w  .j  av a 2  s  .c om*/
 * This is guaranteed to be called only after all connections have been individually
 * closed, and their channels closed, and only once per {@link Timer} instance.
 * <p/>
 * This gives the implementor a chance to close the {@link Timer} properly, if required.
 * <p/>
 * The default implementation calls a {@link Timer#stop()} of the passed {@link Timer} instance.
 * <p/>
 * Implementation note: if the {@link Timer} instance is being shared, or used for other purposes than to
 * schedule actions for the current cluster, than it should not be stopped here;
 * subclasses would have to override this method accordingly to take the appropriate action.
 *
 * @param timer the timer used by the cluster being closed
 */
public void onClusterClose(Timer timer) {
    timer.stop();
}

From source file:org.opendaylight.controller.netconf.test.tool.client.stress.StressClient.java

License:Open Source License

public static void main(final String[] args) {

    final Parameters params = parseArgs(args, Parameters.getParser());
    params.validate();/*from w w  w.  j  a  v a  2  s  . c  o  m*/

    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final int threadAmount = params.threadAmount;
    LOG.info("thread amount: " + threadAmount);
    final int requestsPerThread = params.editCount / params.threadAmount;
    LOG.info("requestsPerThread: " + requestsPerThread);
    final int leftoverRequests = params.editCount % params.threadAmount;
    LOG.info("leftoverRequests: " + leftoverRequests);

    LOG.info("Preparing messages");
    // Prepare all msgs up front
    final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
    for (int i = 0; i < threadAmount; i++) {
        if (i != threadAmount - 1) {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
        } else {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
        }
    }

    final String editContentString;
    try {
        editContentString = Files.toString(params.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + params.editContent);
    }

    for (int i = 0; i < threadAmount; i++) {
        final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
        int padding = 0;
        if (i == threadAmount - 1) {
            padding = leftoverRequests;
        }
        for (int j = 0; j < requestsPerThread + padding; j++) {
            LOG.debug("id: " + (i * requestsPerThread + j));
            preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
        }
    }

    final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
    final Timer timer = new HashedWheelTimer();

    final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup,
            timer);

    final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
    for (final List<NetconfMessage> messages : allPreparedMessages) {
        callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting stress test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Boolean>> futures = executorService.invokeAll(callables);
        for (final Future<Boolean> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    // Cleanup
    timer.stop();
    try {
        nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOG.warn("Unable to close executor properly", e);
    }
    //stop the underlying ssh thread that gets spawned if we use ssh
    if (params.ssh) {
        AsyncSshHandler.DEFAULT_CLIENT.stop();
    }
}

From source file:org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicatorTest.java

License:Open Source License

/**
 * Test whether reconnect is scheduled properly
 *///from  w  w  w  . j  ava 2s.c om
@Test
public void testNetconfDeviceReconnectInCommunicator() throws Exception {
    final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(
            RemoteDevice.class);

    final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(
            GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
    final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
        @Override
        public int getConnectTimeout() throws Exception {
            return timedReconnectStrategy.getConnectTimeout();
        }

        @Override
        public Future<Void> scheduleReconnect(final Throwable cause) {
            return timedReconnectStrategy.scheduleReconnect(cause);
        }

        @Override
        public void reconnectSuccessful() {
            timedReconnectStrategy.reconnectSuccessful();
        }
    });

    final EventLoopGroup group = new NioEventLoopGroup();
    final Timer time = new HashedWheelTimer();
    try {
        final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test"),
                device);
        final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder
                .create().withAddress(new InetSocketAddress("localhost", 65000))
                .withReconnectStrategy(reconnectStrategy)
                .withConnectStrategyFactory(new ReconnectStrategyFactory() {
                    @Override
                    public ReconnectStrategy createReconnectStrategy() {
                        return reconnectStrategy;
                    }
                }).withAuthHandler(new LoginPassword("admin", "admin")).withConnectionTimeoutMillis(10000)
                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
                .withSessionListener(listener).build();

        listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);

        verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101))
                .scheduleReconnect(any(Throwable.class));
    } finally {
        time.stop();
        group.shutdownGracefully();
    }
}

From source file:org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicatorTest.java

License:Open Source License

/**
 * Test whether reconnect is scheduled properly
 *//*from w  w w. ja va 2  s  .  c om*/
@Test
public void testNetconfDeviceReconnectInCommunicator() throws Exception {
    final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(
            RemoteDevice.class);

    final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(
            GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
    final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
        @Override
        public int getConnectTimeout() throws Exception {
            return timedReconnectStrategy.getConnectTimeout();
        }

        @Override
        public Future<Void> scheduleReconnect(final Throwable cause) {
            return timedReconnectStrategy.scheduleReconnect(cause);
        }

        @Override
        public void reconnectSuccessful() {
            timedReconnectStrategy.reconnectSuccessful();
        }
    });

    final EventLoopGroup group = new NioEventLoopGroup();
    final Timer time = new HashedWheelTimer();
    try {
        final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(
                new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
        final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder
                .create().withAddress(new InetSocketAddress("localhost", 65000))
                .withReconnectStrategy(reconnectStrategy)
                .withConnectStrategyFactory(new ReconnectStrategyFactory() {
                    @Override
                    public ReconnectStrategy createReconnectStrategy() {
                        return reconnectStrategy;
                    }
                }).withAuthHandler(new LoginPassword("admin", "admin")).withConnectionTimeoutMillis(10000)
                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
                .withSessionListener(listener).build();

        listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);

        verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101))
                .scheduleReconnect(any(Throwable.class));
    } finally {
        time.stop();
        group.shutdownGracefully();
    }
}

From source file:org.opendaylight.netconf.test.tool.client.stress.StressClient.java

License:Open Source License

public static void main(final String[] args) {

    params = parseArgs(args, Parameters.getParser());
    params.validate();/*  ww  w  .  j ava2s . c  om*/

    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final int threadAmount = params.threadAmount;
    LOG.info("thread amount: " + threadAmount);
    final int requestsPerThread = params.editCount / params.threadAmount;
    LOG.info("requestsPerThread: " + requestsPerThread);
    final int leftoverRequests = params.editCount % params.threadAmount;
    LOG.info("leftoverRequests: " + leftoverRequests);

    LOG.info("Preparing messages");
    // Prepare all msgs up front
    final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
    for (int i = 0; i < threadAmount; i++) {
        if (i != threadAmount - 1) {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
        } else {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
        }
    }

    final String editContentString;
    try {
        editContentString = Files.toString(params.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + params.editContent);
    }

    for (int i = 0; i < threadAmount; i++) {
        final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
        int padding = 0;
        if (i == threadAmount - 1) {
            padding = leftoverRequests;
        }
        for (int j = 0; j < requestsPerThread + padding; j++) {
            LOG.debug("id: " + (i * requestsPerThread + j));
            preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
        }
    }

    final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
    final Timer timer = new HashedWheelTimer();

    final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup,
            timer);

    final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
    for (final List<NetconfMessage> messages : allPreparedMessages) {
        callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting stress test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Boolean>> futures = executorService.invokeAll(callables);
        for (final Future<Boolean> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    // Cleanup
    timer.stop();
    try {
        nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOG.warn("Unable to close executor properly", e);
    }
    //stop the underlying ssh thread that gets spawned if we use ssh
    if (params.ssh) {
        AsyncSshHandler.DEFAULT_CLIENT.stop();
    }
}