use of 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()));
}
use of 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;
}
}
use of 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();
}
use of 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);
}
}
use of io.netty.channel.nio.NioEventLoopGroup in project riposte by Nike-Inc.
the class Server method startup.
public void startup() throws CertificateException, IOException, InterruptedException {
if (startedUp) {
throw new IllegalArgumentException("This Server instance has already started. " + "You can only call startup() once");
}
// Figure out what port to bind to.
int port = Integer.parseInt(System.getProperty("endpointsPort", serverConfig.isEndpointsUseSsl() ? String.valueOf(serverConfig.endpointsSslPort()) : String.valueOf(serverConfig.endpointsPort())));
// Configure SSL if desired.
final SslContext sslCtx;
if (serverConfig.isEndpointsUseSsl()) {
sslCtx = serverConfig.createSslContext();
} else {
sslCtx = null;
}
// Configure the server
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
Class<? extends ServerChannel> channelClass;
// NIO event loop group.
if (Epoll.isAvailable()) {
logger.info("The epoll native transport is available. Using epoll instead of NIO. " + "riposte_server_using_native_epoll_transport=true");
bossGroup = (serverConfig.bossThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numBossThreads()) : new EpollEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
workerGroup = (serverConfig.workerThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numWorkerThreads()) : new EpollEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
channelClass = EpollServerSocketChannel.class;
} else {
logger.info("The epoll native transport is NOT available or you are not running on a compatible " + "OS/architecture. Using NIO. riposte_server_using_native_epoll_transport=false");
bossGroup = (serverConfig.bossThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numBossThreads()) : new NioEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
workerGroup = (serverConfig.workerThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numWorkerThreads()) : new NioEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
channelClass = NioServerSocketChannel.class;
}
eventLoopGroups.add(bossGroup);
eventLoopGroups.add(workerGroup);
// Figure out which channel initializer should set up the channel pipelines for new channels.
ChannelInitializer<SocketChannel> channelInitializer = serverConfig.customChannelInitializer();
if (channelInitializer == null) {
// No custom channel initializer, so use the default
channelInitializer = new HttpChannelInitializer(sslCtx, serverConfig.maxRequestSizeInBytes(), serverConfig.appEndpoints(), serverConfig.requestAndResponseFilters(), serverConfig.longRunningTaskExecutor(), serverConfig.riposteErrorHandler(), serverConfig.riposteUnhandledErrorHandler(), serverConfig.requestContentValidationService(), serverConfig.defaultRequestContentDeserializer(), new ResponseSender(serverConfig.defaultResponseContentSerializer(), serverConfig.errorResponseBodySerializer()), serverConfig.metricsListener(), serverConfig.defaultCompletableFutureTimeoutInMillisForNonblockingEndpoints(), serverConfig.accessLogger(), serverConfig.pipelineCreateHooks(), serverConfig.requestSecurityValidator(), serverConfig.workerChannelIdleTimeoutMillis(), serverConfig.proxyRouterConnectTimeoutMillis(), serverConfig.incompleteHttpCallTimeoutMillis(), serverConfig.maxOpenIncomingServerChannels(), serverConfig.isDebugChannelLifecycleLoggingEnabled(), serverConfig.userIdHeaderKeys());
}
// Create the server bootstrap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(channelClass).childHandler(channelInitializer);
// execute pre startup hooks
if (serverConfig.preServerStartupHooks() != null) {
for (PreServerStartupHook hook : serverConfig.preServerStartupHooks()) {
hook.executePreServerStartupHook(b);
}
}
if (serverConfig.isDebugChannelLifecycleLoggingEnabled())
b.handler(new LoggingHandler(SERVER_BOSS_CHANNEL_DEBUG_LOGGER_NAME, LogLevel.DEBUG));
// Bind the server to the desired port and start it up so it is ready to receive requests
Channel ch = b.bind(port).sync().channel();
// execute post startup hooks
if (serverConfig.postServerStartupHooks() != null) {
for (PostServerStartupHook hook : serverConfig.postServerStartupHooks()) {
hook.executePostServerStartupHook(serverConfig, ch);
}
}
channels.add(ch);
logger.info("Server channel open and accepting " + (serverConfig.isEndpointsUseSsl() ? "https" : "http") + " requests on port " + port);
startedUp = true;
// Add a shutdown hook so we can gracefully stop the server when the JVM is going down
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
shutdown();
} catch (Exception e) {
logger.warn("Error shutting down Riposte", e);
}
}
});
}
Aggregations