use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project netty by netty.
the class HAProxyIntegrationTest method testBasicCase.
@Test
public void testBasicCase() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<HAProxyMessage> msgHolder = new AtomicReference<HAProxyMessage>();
LocalAddress localAddress = new LocalAddress("HAProxyIntegrationTest");
EventLoopGroup group = new DefaultEventLoopGroup();
ServerBootstrap sb = new ServerBootstrap();
sb.channel(LocalServerChannel.class).group(group).childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new HAProxyMessageDecoder());
ch.pipeline().addLast(new SimpleChannelInboundHandler<HAProxyMessage>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HAProxyMessage msg) throws Exception {
msgHolder.set(msg.retain());
latch.countDown();
}
});
}
});
Channel serverChannel = sb.bind(localAddress).sync().channel();
Bootstrap b = new Bootstrap();
Channel clientChannel = b.channel(LocalChannel.class).handler(HAProxyMessageEncoder.INSTANCE).group(group).connect(localAddress).sync().channel();
try {
HAProxyMessage message = new HAProxyMessage(HAProxyProtocolVersion.V1, HAProxyCommand.PROXY, HAProxyProxiedProtocol.TCP4, "192.168.0.1", "192.168.0.11", 56324, 443);
clientChannel.writeAndFlush(message).sync();
assertTrue(latch.await(5, TimeUnit.SECONDS));
HAProxyMessage readMessage = msgHolder.get();
assertEquals(message.protocolVersion(), readMessage.protocolVersion());
assertEquals(message.command(), readMessage.command());
assertEquals(message.proxiedProtocol(), readMessage.proxiedProtocol());
assertEquals(message.sourceAddress(), readMessage.sourceAddress());
assertEquals(message.destinationAddress(), readMessage.destinationAddress());
assertEquals(message.sourcePort(), readMessage.sourcePort());
assertEquals(message.destinationPort(), readMessage.destinationPort());
readMessage.release();
} finally {
clientChannel.close().sync();
serverChannel.close().sync();
group.shutdownGracefully().sync();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project LogHub by fbacchella.
the class ServerFactory method addChildhandlers.
@Override
public void addChildhandlers(ChannelConsumer<ServerBootstrap, ServerChannel, SA> source) {
ChannelHandler handler = new ChannelInitializer<CC>() {
@Override
public void initChannel(CC ch) throws Exception {
try {
source.addHandlers(ch.pipeline());
} catch (Exception e) {
logger.error("Netty handler failed: {}", e.getMessage());
logger.throwing(Level.DEBUG, e);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
source.exception(ctx, cause);
}
};
bootstrap.childHandler(handler);
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project flink by apache.
the class RestServerEndpoint method start.
/**
* Starts this REST server endpoint.
*
* @throws Exception if we cannot start the RestServerEndpoint
*/
public final void start() throws Exception {
synchronized (lock) {
Preconditions.checkState(state == State.CREATED, "The RestServerEndpoint cannot be restarted.");
log.info("Starting rest endpoint.");
final Router router = new Router();
final CompletableFuture<String> restAddressFuture = new CompletableFuture<>();
handlers = initializeHandlers(restAddressFuture);
/* sort the handlers such that they are ordered the following:
* /jobs
* /jobs/overview
* /jobs/:jobid
* /jobs/:jobid/config
* /:*
*/
Collections.sort(handlers, RestHandlerUrlComparator.INSTANCE);
checkAllEndpointsAndHandlersAreUnique(handlers);
handlers.forEach(handler -> registerHandler(router, handler, log));
ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws ConfigurationException {
RouterHandler handler = new RouterHandler(router, responseHeaders);
// SSL should be the first handler in the pipeline
if (isHttpsEnabled()) {
ch.pipeline().addLast("ssl", new RedirectingSslHandler(restAddress, restAddressFuture, sslHandlerFactory));
}
ch.pipeline().addLast(new HttpServerCodec()).addLast(new FileUploadHandler(uploadDir)).addLast(new FlinkHttpObjectAggregator(maxContentLength, responseHeaders));
for (InboundChannelHandlerFactory factory : inboundChannelHandlerFactories) {
Optional<ChannelHandler> channelHandler = factory.createHandler(configuration, responseHeaders);
if (channelHandler.isPresent()) {
ch.pipeline().addLast(channelHandler.get());
}
}
ch.pipeline().addLast(new ChunkedWriteHandler()).addLast(handler.getName(), handler).addLast(new PipelineErrorHandler(log, responseHeaders));
}
};
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, new ExecutorThreadFactory("flink-rest-server-netty-boss"));
NioEventLoopGroup workerGroup = new NioEventLoopGroup(0, new ExecutorThreadFactory("flink-rest-server-netty-worker"));
bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(initializer);
Iterator<Integer> portsIterator;
try {
portsIterator = NetUtils.getPortRangeFromString(restBindPortRange);
} catch (IllegalConfigurationException e) {
throw e;
} catch (Exception e) {
throw new IllegalArgumentException("Invalid port range definition: " + restBindPortRange);
}
int chosenPort = 0;
while (portsIterator.hasNext()) {
try {
chosenPort = portsIterator.next();
final ChannelFuture channel;
if (restBindAddress == null) {
channel = bootstrap.bind(chosenPort);
} else {
channel = bootstrap.bind(restBindAddress, chosenPort);
}
serverChannel = channel.syncUninterruptibly().channel();
break;
} catch (final Exception e) {
// otherwise
if (!(e instanceof java.net.BindException)) {
throw e;
}
}
}
if (serverChannel == null) {
throw new BindException("Could not start rest endpoint on any port in port range " + restBindPortRange);
}
log.debug("Binding rest endpoint to {}:{}.", restBindAddress, chosenPort);
final InetSocketAddress bindAddress = (InetSocketAddress) serverChannel.localAddress();
final String advertisedAddress;
if (bindAddress.getAddress().isAnyLocalAddress()) {
advertisedAddress = this.restAddress;
} else {
advertisedAddress = bindAddress.getAddress().getHostAddress();
}
port = bindAddress.getPort();
log.info("Rest endpoint listening at {}:{}", advertisedAddress, port);
restBaseUrl = new URL(determineProtocol(), advertisedAddress, port, "").toString();
restAddressFuture.complete(restBaseUrl);
state = State.RUNNING;
startInternal();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project flink by apache.
the class NettyServer method init.
int init(NettyBufferPool nettyBufferPool, Function<SSLHandlerFactory, ServerChannelInitializer> channelInitializer) throws IOException {
checkState(bootstrap == null, "Netty server has already been initialized.");
final long start = System.nanoTime();
bootstrap = new ServerBootstrap();
switch(config.getTransportType()) {
case NIO:
initNioBootstrap();
break;
case EPOLL:
initEpollBootstrap();
break;
case AUTO:
if (Epoll.isAvailable()) {
initEpollBootstrap();
LOG.info("Transport type 'auto': using EPOLL.");
} else {
initNioBootstrap();
LOG.info("Transport type 'auto': using NIO.");
}
}
// --------------------------------------------------------------------
// Configuration
// --------------------------------------------------------------------
// Server bind address
bootstrap.localAddress(config.getServerAddress(), config.getServerPort());
// Pooled allocators for Netty's ByteBuf instances
bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool);
bootstrap.childOption(ChannelOption.ALLOCATOR, nettyBufferPool);
if (config.getServerConnectBacklog() > 0) {
bootstrap.option(ChannelOption.SO_BACKLOG, config.getServerConnectBacklog());
}
// Receive and send buffer size
int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize();
if (receiveAndSendBufferSize > 0) {
bootstrap.childOption(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize);
bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize);
}
// SSL related configuration
final SSLHandlerFactory sslHandlerFactory;
try {
sslHandlerFactory = config.createServerSSLEngineFactory();
} catch (Exception e) {
throw new IOException("Failed to initialize SSL Context for the Netty Server", e);
}
// --------------------------------------------------------------------
// Child channel pipeline for accepted connections
// --------------------------------------------------------------------
bootstrap.childHandler(channelInitializer.apply(sslHandlerFactory));
// --------------------------------------------------------------------
// Start Server
// --------------------------------------------------------------------
bindFuture = bootstrap.bind().syncUninterruptibly();
localAddress = (InetSocketAddress) bindFuture.channel().localAddress();
final long duration = (System.nanoTime() - start) / 1_000_000;
LOG.info("Successful initialization (took {} ms). Listening on SocketAddress {}.", duration, localAddress);
return localAddress.getPort();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer in project zuul by Netflix.
the class ServerTest method getListeningSockets.
@Test
public void getListeningSockets() throws Exception {
ServerStatusManager ssm = mock(ServerStatusManager.class);
Map<NamedSocketAddress, ChannelInitializer<?>> initializers = new HashMap<>();
final List<NioSocketChannel> nioChannels = Collections.synchronizedList(new ArrayList<NioSocketChannel>());
ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() {
@Override
protected void initChannel(final Channel ch) {
LOGGER.info("Channel: " + ch.getClass().getName() + ", isActive=" + ch.isActive() + ", isOpen=" + ch.isOpen());
if (ch instanceof NioSocketChannel) {
nioChannels.add((NioSocketChannel) ch);
}
}
};
initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init);
// The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same
initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init);
ClientConnectionsShutdown ccs = new ClientConnectionsShutdown(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, /* discoveryClient= */
null);
EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry());
EventLoopConfig elc = new EventLoopConfig() {
@Override
public int eventLoopCount() {
return 1;
}
@Override
public int acceptorCount() {
return 1;
}
};
Server s = new Server(new NoopRegistry(), ssm, initializers, ccs, elgm, elc);
s.start();
List<NamedSocketAddress> addrs = s.getListeningAddresses();
assertEquals(2, addrs.size());
for (NamedSocketAddress address : addrs) {
assertTrue(address.unwrap() instanceof InetSocketAddress);
final int port = ((InetSocketAddress) address.unwrap()).getPort();
assertNotEquals(port, 0);
checkConnection(port);
}
await().atMost(1, SECONDS).until(() -> nioChannels.size() == 2);
s.stop();
assertEquals(2, nioChannels.size());
for (NioSocketChannel ch : nioChannels) {
assertTrue("isShutdown", ch.isShutdown());
}
}
Aggregations