Search in sources :

Example 16 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project alluxio by Alluxio.

the class RPCMessageIntegrationTest method beforeClass.

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();
    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));
    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100), Integer.parseInt(PropertyKey.MASTER_RPC_PORT.getDefaultValue()));
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();
    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BeforeClass(org.junit.BeforeClass)

Example 17 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project pulsar by yahoo.

the class MockBrokerService method startMockBrokerService.

public void startMockBrokerService() throws Exception {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
    final int numThreads = 2;
    final int MaxMessageSize = 5 * 1024 * 1024;
    EventLoopGroup eventLoopGroup;
    try {
        if (SystemUtils.IS_OS_LINUX) {
            try {
                eventLoopGroup = new EpollEventLoopGroup(numThreads, threadFactory);
            } catch (UnsatisfiedLinkError e) {
                eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
            }
        } else {
            eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
        }
        workerGroup = eventLoopGroup;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup, workerGroup);
        if (workerGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                ch.pipeline().addLast("handler", new MockServerCnx());
            }
        });
        // Bind and start to accept incoming connections.
        bootstrap.bind(brokerServicePort).sync();
    } catch (Exception e) {
        throw e;
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 18 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project pulsar by yahoo.

the class PerformanceProducer method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }
    if (arguments.destinations.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }
    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }
        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }
        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }
        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
    }
    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));
    // Read payload data from file if needed
    byte[] payloadData;
    if (arguments.payloadFilename != null) {
        payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
    } else {
        payloadData = new byte[arguments.msgSize];
    }
    // Now processing command line arguments
    String prefixTopicName = arguments.destinations.get(0);
    List<Future<Producer>> futures = Lists.newArrayList();
    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-producer"));
    }
    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setSendTimeout(0, TimeUnit.SECONDS);
    producerConf.setCompressionType(arguments.compression);
    // enable round robin message routing if it is a partitioned topic
    producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS);
        producerConf.setBatchingEnabled(true);
        producerConf.setMaxPendingMessages(arguments.msgRate);
    }
    for (int i = 0; i < arguments.numTopics; i++) {
        String topic = (arguments.numTopics == 1) ? prefixTopicName : String.format("%s-%d", prefixTopicName, i);
        log.info("Adding {} publishers on destination {}", arguments.numProducers, topic);
        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(client.createProducerAsync(topic, producerConf));
        }
    }
    final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer> future : futures) {
        producers.add(future.get());
    }
    log.info("Created {} producers", producers.size());
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    Collections.shuffle(producers);
    AtomicBoolean isDone = new AtomicBoolean();
    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);
            long startTime = System.currentTimeMillis();
            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (Producer producer : producers) {
                    if (arguments.testTime > 0) {
                        if (System.currentTimeMillis() - startTime > arguments.testTime) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    if (arguments.numMessages > 0) {
                        if (totalSent++ >= arguments.numMessages) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();
                    final long sendTime = System.nanoTime();
                    producer.sendAsync(payloadData).thenRun(() -> {
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);
                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                    }).exceptionally(ex -> {
                        log.warn("Write error on message", ex);
                        System.exit(-1);
                        return null;
                    });
                }
            }
        } catch (Throwable t) {
            log.error("Got error", t);
        }
    });
    // Print report stats
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to {}", statsFileName);
    PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
    HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);
    // Some log header bits
    histogramLogWriter.outputLogFormatVersion();
    histogramLogWriter.outputLegend();
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        if (isDone.get()) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", throughputFormat.format(rate), throughputFormat.format(throughput), dec.format(reportHistogram.getMean() / 1000.0), dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0), dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0), dec.format(reportHistogram.getMaxValue() / 1000.0));
        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();
        oldTime = now;
    }
    client.close();
}
Also used : Histogram(org.HdrHistogram.Histogram) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Properties(java.util.Properties) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HistogramLogWriter(org.HdrHistogram.HistogramLogWriter) PrintStream(java.io.PrintStream) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Producer(com.yahoo.pulsar.client.api.Producer) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) FileOutputStream(java.io.FileOutputStream) Future(java.util.concurrent.Future) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration)

Example 19 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project jersey by jersey.

the class NettyHttpContainerProvider method createServer.

/**
     * Create and start Netty server.
     *
     * @param baseUri       base uri.
     * @param configuration Jersey configuration.
     * @param sslContext    Netty SSL context (can be null).
     * @param block         when {@code true}, this method will block until the server is stopped. When {@code false}, the
     *                      execution will
     *                      end immediately after the server is started.
     * @return Netty channel instance.
     * @throws ProcessingException when there is an issue with creating new container.
     */
public static Channel createServer(final URI baseUri, final ResourceConfig configuration, SslContext sslContext, final boolean block) throws ProcessingException {
    // Configure the server.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new JerseyServerInitializer(baseUri, sslContext, container));
        int port = getPort(baseUri);
        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
        if (block) {
            ch.closeFuture().sync();
            return ch;
        } else {
            return ch;
        }
    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ProcessingException(javax.ws.rs.ProcessingException) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Future(io.netty.util.concurrent.Future) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ProcessingException(javax.ws.rs.ProcessingException)

Example 20 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project intellij-community by JetBrains.

the class BuildMain method main.

public static void main(String[] args) throws Throwable {
    try {
        final long processStart = System.currentTimeMillis();
        final String startMessage = "Build process started. Classpath: " + System.getProperty("java.class.path");
        System.out.println(startMessage);
        LOG.info(startMessage);
        final String host = args[HOST_ARG];
        final int port = Integer.parseInt(args[PORT_ARG]);
        final UUID sessionId = UUID.fromString(args[SESSION_ID_ARG]);
        @SuppressWarnings("ConstantConditions") final File systemDir = new File(FileUtil.toCanonicalPath(args[SYSTEM_DIR_ARG]));
        Utils.setSystemRoot(systemDir);
        final long connectStart = System.currentTimeMillis();
        // IDEA-123132, let's try again
        for (int attempt = 0; attempt < 3; attempt++) {
            try {
                ourEventLoopGroup = new NioEventLoopGroup(1, SharedThreadPool.getInstance());
                break;
            } catch (IllegalStateException e) {
                if (attempt == 2) {
                    printErrorAndExit(host, port, e);
                    return;
                } else {
                    LOG.warn("Cannot create event loop, attempt #" + attempt, e);
                    try {
                        //noinspection BusyWait
                        Thread.sleep(10 * (attempt + 1));
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }
        final Bootstrap bootstrap = new Bootstrap().group(ourEventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

            @Override
            protected void initChannel(Channel channel) throws Exception {
                channel.pipeline().addLast(new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()), new ProtobufVarint32LengthFieldPrepender(), new ProtobufEncoder(), new MyMessageHandler(sessionId));
            }
        }).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true);
        final ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)).awaitUninterruptibly();
        final boolean success = future.isSuccess();
        if (success) {
            LOG.info("Connection to IDE established in " + (System.currentTimeMillis() - connectStart) + " ms");
            final String projectPathToPreload = System.getProperty(PRELOAD_PROJECT_PATH, null);
            final String globalsPathToPreload = System.getProperty(PRELOAD_CONFIG_PATH, null);
            if (projectPathToPreload != null && globalsPathToPreload != null) {
                final PreloadedData data = new PreloadedData();
                ourPreloadedData = data;
                try {
                    // this will pre-load all FS optimizations
                    FileSystemUtil.getAttributes(projectPathToPreload);
                    final BuildRunner runner = new BuildRunner(new JpsModelLoaderImpl(projectPathToPreload, globalsPathToPreload, null));
                    data.setRunner(runner);
                    final File dataStorageRoot = Utils.getDataStorageRoot(projectPathToPreload);
                    final BuildFSState fsState = new BuildFSState(false);
                    final ProjectDescriptor pd = runner.load(new MessageHandler() {

                        @Override
                        public void processMessage(BuildMessage msg) {
                            data.addMessage(msg);
                        }
                    }, dataStorageRoot, fsState);
                    data.setProjectDescriptor(pd);
                    try {
                        final File fsStateFile = new File(dataStorageRoot, BuildSession.FS_STATE_FILE);
                        final DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(fsStateFile)));
                        try {
                            final int version = in.readInt();
                            if (version == BuildFSState.VERSION) {
                                final long savedOrdinal = in.readLong();
                                // must skip "has-work-to-do" flag
                                final boolean hasWorkToDo = in.readBoolean();
                                fsState.load(in, pd.getModel(), pd.getBuildRootIndex());
                                data.setFsEventOrdinal(savedOrdinal);
                                data.setHasHasWorkToDo(hasWorkToDo);
                            }
                        } finally {
                            in.close();
                        }
                    } catch (FileNotFoundException ignored) {
                    } catch (IOException e) {
                        LOG.info("Error pre-loading FS state", e);
                        fsState.clearAll();
                    }
                    // preloading target configurations
                    final BuildTargetsState targetsState = pd.getTargetsState();
                    for (BuildTarget<?> target : pd.getBuildTargetIndex().getAllTargets()) {
                        targetsState.getTargetConfiguration(target);
                    }
                    BuilderRegistry.getInstance();
                    LOG.info("Pre-loaded process ready in " + (System.currentTimeMillis() - processStart) + " ms");
                } catch (Throwable e) {
                    LOG.info("Failed to pre-load project " + projectPathToPreload, e);
                // just failed to preload the project, the situation will be handled later, when real build starts
                }
            } else if (projectPathToPreload != null || globalsPathToPreload != null) {
                LOG.info("Skipping project pre-loading step: both paths to project configuration files and path to global settings must be specified");
            }
            future.channel().writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, CmdlineProtoUtil.createParamRequest()));
        } else {
            printErrorAndExit(host, port, future.cause());
        }
    } catch (Throwable e) {
        LOG.error(e);
        throw e;
    }
}
Also used : MessageHandler(org.jetbrains.jps.incremental.MessageHandler) InetSocketAddress(java.net.InetSocketAddress) ProtobufDecoder(io.netty.handler.codec.protobuf.ProtobufDecoder) ProtobufVarint32LengthFieldPrepender(io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender) BuildTargetsState(org.jetbrains.jps.incremental.storage.BuildTargetsState) BuildFSState(org.jetbrains.jps.incremental.fs.BuildFSState) Bootstrap(io.netty.bootstrap.Bootstrap) UUID(java.util.UUID) ProtobufVarint32FrameDecoder(io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ProtobufEncoder(io.netty.handler.codec.protobuf.ProtobufEncoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) BuildMessage(org.jetbrains.jps.incremental.messages.BuildMessage)

Aggregations

NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)521 EventLoopGroup (io.netty.channel.EventLoopGroup)256 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)226 Bootstrap (io.netty.bootstrap.Bootstrap)184 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)178 SocketChannel (io.netty.channel.socket.SocketChannel)169 ChannelFuture (io.netty.channel.ChannelFuture)157 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)157 Channel (io.netty.channel.Channel)138 InetSocketAddress (java.net.InetSocketAddress)118 LoggingHandler (io.netty.handler.logging.LoggingHandler)87 ChannelPipeline (io.netty.channel.ChannelPipeline)84 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)73 SslContext (io.netty.handler.ssl.SslContext)64 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)49 IOException (java.io.IOException)49 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)47 ByteBuf (io.netty.buffer.ByteBuf)44 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)43 ChannelInitializer (io.netty.channel.ChannelInitializer)41