Search in sources :

Example 41 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project java by wavefrontHQ.

the class StreamIngester method run.

public void run() {
    activeListeners.inc();
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup parentGroup;
    EventLoopGroup childGroup;
    Class<? extends ServerChannel> socketChannelClass;
    if (Epoll.isAvailable()) {
        logger.fine("Using native socket transport for port " + listeningPort);
        parentGroup = new EpollEventLoopGroup(1);
        childGroup = new EpollEventLoopGroup();
        socketChannelClass = EpollServerSocketChannel.class;
    } else {
        logger.fine("Using NIO socket transport for port " + listeningPort);
        parentGroup = new NioEventLoopGroup(1);
        childGroup = new NioEventLoopGroup();
        socketChannelClass = NioServerSocketChannel.class;
    }
    try {
        b.group(parentGroup, childGroup).channel(socketChannelClass).option(ChannelOption.SO_BACKLOG, 1024).localAddress(listeningPort).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frame decoder", frameDecoderFactory.getDecoder());
                pipeline.addLast("byte array decoder", new ByteArrayDecoder());
                pipeline.addLast(commandHandler);
            }
        });
        if (parentChannelOptions != null) {
            for (Map.Entry<ChannelOption<?>, ?> entry : parentChannelOptions.entrySet()) {
                b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
            }
        }
        if (childChannelOptions != null) {
            for (Map.Entry<ChannelOption<?>, ?> entry : childChannelOptions.entrySet()) {
                b.childOption((ChannelOption<Object>) entry.getKey(), entry.getValue());
            }
        }
        // Start the server.
        ChannelFuture f = b.bind().sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (final InterruptedException e) {
        logger.log(Level.WARNING, "Interrupted");
        parentGroup.shutdownGracefully();
        childGroup.shutdownGracefully();
        logger.info("Listener on port " + String.valueOf(listeningPort) + " shut down");
    } catch (Exception e) {
        // ChannelFuture throws undeclared checked exceptions, so we need to handle it
        if (e instanceof BindException) {
            logger.severe("Unable to start listener - port " + String.valueOf(listeningPort) + " is already in use!");
        } else {
            logger.log(Level.SEVERE, "StreamIngester exception: ", e);
        }
    } finally {
        activeListeners.dec();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ChannelOption(io.netty.channel.ChannelOption) BindException(java.net.BindException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BindException(java.net.BindException) ChannelPipeline(io.netty.channel.ChannelPipeline) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) Map(java.util.Map) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

Example 42 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project scalecube by scalecube.

the class NettyStreamChannelInitializer method initChannel.

@Override
protected void initChannel(Channel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    // contexs contexts contexs
    channel.pipeline().addLast(channelContextHandler);
    // frame codecs
    pipeline.addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
    pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_LENGTH));
    // message acceptor
    pipeline.addLast(messageHandler);
    // at-least-something exception handler
    pipeline.addLast(new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
            // Hint: at this point one can look at throwable, make some exception translation, and via channelContext post
            // ChannelContextError event, and hence give business layer ability to react on low level system error events
            LOGGER.warn("Exception caught for channel {}, {}", ctx.channel(), throwable);
        }
    });
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 43 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project activemq-artemis by apache.

the class NettyConnector method createConnection.

@Override
public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }
    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }
    logger.debug("Remote destination: " + remoteDestination);
    ChannelFuture future;
    // port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }
    future.awaitUninterruptibly();
    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                // handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }
        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                // get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                String scheme = "http";
                if (sslEnabled) {
                    scheme = "https";
                }
                String ipv6Host = IPV6Util.encloseHost(host);
                URI uri = new URI(scheme, null, ipv6Host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
                request.headers().set(HttpHeaderNames.HOST, ipv6Host);
                request.headers().set(HttpHeaderNames.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.UPGRADE);
                final String serverName = ConfigurationHelper.getStringProperty(TransportConstants.ACTIVEMQ_SERVER_NAME, null, configuration);
                if (serverName != null) {
                    request.headers().set(TransportConstants.ACTIVEMQ_SERVER_NAME, serverName);
                }
                final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }
                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);
                logger.debugf("Sending HTTP request %s", request);
                // Send the HTTP request.
                ch.writeAndFlush(request);
                if (!httpUpgradeHandler.awaitHandshake()) {
                    ch.close().awaitUninterruptibly();
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }
        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager);
        return conn;
    } else {
        Throwable t = future.cause();
        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }
        return null;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Inet6Address(java.net.Inet6Address) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) ConnectException(java.net.ConnectException)

Example 44 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project activemq-artemis by apache.

the class NettyConnector method start.

@Override
public synchronized void start() {
    if (channelClazz != null) {
        return;
    }
    if (remotingThreads == -1) {
        // Default to number of cores * 3
        remotingThreads = Runtime.getRuntime().availableProcessors() * 3;
    }
    String connectorType;
    if (useEpoll && Epoll.isAvailable()) {
        if (useGlobalWorkerPool) {
            group = SharedEventLoopGroup.getInstance((threadFactory -> new EpollEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            group = new EpollEventLoopGroup(remotingThreads);
        }
        connectorType = EPOLL_CONNECTOR_TYPE;
        channelClazz = EpollSocketChannel.class;
        logger.debug("Connector " + this + " using native epoll");
    } else if (useKQueue && KQueue.isAvailable()) {
        if (useGlobalWorkerPool) {
            group = SharedEventLoopGroup.getInstance((threadFactory -> new KQueueEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            group = new KQueueEventLoopGroup(remotingThreads);
        }
        connectorType = KQUEUE_CONNECTOR_TYPE;
        channelClazz = KQueueSocketChannel.class;
        logger.debug("Connector " + this + " using native kqueue");
    } else {
        if (useGlobalWorkerPool) {
            channelClazz = NioSocketChannel.class;
            group = SharedEventLoopGroup.getInstance((threadFactory -> new NioEventLoopGroup(remotingThreads, threadFactory)));
        } else {
            channelClazz = NioSocketChannel.class;
            group = new NioEventLoopGroup(remotingThreads);
        }
        connectorType = NIO_CONNECTOR_TYPE;
        channelClazz = NioSocketChannel.class;
        logger.debug("Connector + " + this + " using nio");
    }
    // if we are a servlet wrap the socketChannelFactory
    bootstrap = new Bootstrap();
    bootstrap.channel(channelClazz);
    bootstrap.group(group);
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (connectTimeoutMillis != -1) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis);
    }
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    final int writeBufferLowWaterMark = this.writeBufferLowWaterMark != -1 ? this.writeBufferLowWaterMark : WriteBufferWaterMark.DEFAULT.low();
    final int writeBufferHighWaterMark = this.writeBufferHighWaterMark != -1 ? this.writeBufferHighWaterMark : WriteBufferWaterMark.DEFAULT.high();
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(writeBufferLowWaterMark, writeBufferHighWaterMark);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    channelGroup = new DefaultChannelGroup("activemq-connector", GlobalEventExecutor.INSTANCE);
    final String realKeyStorePath;
    final String realKeyStoreProvider;
    final String realKeyStorePassword;
    final String realTrustStorePath;
    final String realTrustStoreProvider;
    final String realTrustStorePassword;
    if (sslEnabled) {
        // HORNETQ-680 - override the server-side config if client-side system properties are set
        realKeyStorePath = Stream.of(System.getProperty(JAVAX_KEYSTORE_PATH_PROP_NAME), System.getProperty(ACTIVEMQ_KEYSTORE_PATH_PROP_NAME), keyStorePath).map(v -> useDefaultSslContext ? keyStorePath : v).filter(Objects::nonNull).findFirst().orElse(null);
        realKeyStorePassword = Stream.of(System.getProperty(JAVAX_KEYSTORE_PASSWORD_PROP_NAME), System.getProperty(ACTIVEMQ_KEYSTORE_PASSWORD_PROP_NAME), keyStorePassword).map(v -> useDefaultSslContext ? keyStorePassword : v).filter(Objects::nonNull).findFirst().orElse(null);
        realKeyStoreProvider = Stream.of(System.getProperty(ACTIVEMQ_KEYSTORE_PROVIDER_PROP_NAME), keyStoreProvider).map(v -> useDefaultSslContext ? keyStoreProvider : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStorePath = Stream.of(System.getProperty(JAVAX_TRUSTSTORE_PATH_PROP_NAME), System.getProperty(ACTIVEMQ_TRUSTSTORE_PATH_PROP_NAME), trustStorePath).map(v -> useDefaultSslContext ? trustStorePath : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStorePassword = Stream.of(System.getProperty(JAVAX_TRUSTSTORE_PASSWORD_PROP_NAME), System.getProperty(ACTIVEMQ_TRUSTSTORE_PASSWORD_PROP_NAME), trustStorePassword).map(v -> useDefaultSslContext ? trustStorePassword : v).filter(Objects::nonNull).findFirst().orElse(null);
        realTrustStoreProvider = Stream.of(System.getProperty(ACTIVEMQ_TRUSTSTORE_PROVIDER_PROP_NAME), trustStoreProvider).map(v -> useDefaultSslContext ? trustStoreProvider : v).filter(Objects::nonNull).findFirst().orElse(null);
    } else {
        realKeyStorePath = null;
        realKeyStoreProvider = null;
        realKeyStorePassword = null;
        realTrustStorePath = null;
        realTrustStoreProvider = null;
        realTrustStorePassword = null;
    }
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled && !useServlet) {
                SSLEngine engine;
                if (sslProvider.equals(TransportConstants.OPENSSL_PROVIDER)) {
                    engine = loadOpenSslEngine(channel.alloc(), realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
                } else {
                    engine = loadJdkSslEngine(useDefaultSslContext, realKeyStoreProvider, realKeyStorePath, realKeyStorePassword, realTrustStoreProvider, realTrustStorePath, realTrustStorePassword);
                }
                engine.setUseClientMode(true);
                engine.setWantClientAuth(true);
                // setting the enabled cipher suites resets the enabled protocols so we need
                // to save the enabled protocols so that after the customer cipher suite is enabled
                // we can reset the enabled protocols if a customer protocol isn't specified
                String[] originalProtocols = engine.getEnabledProtocols();
                if (enabledCipherSuites != null) {
                    try {
                        engine.setEnabledCipherSuites(SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidCipherSuite(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
                        throw e;
                    }
                }
                if (enabledProtocols != null) {
                    try {
                        engine.setEnabledProtocols(SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                    } catch (IllegalArgumentException e) {
                        ActiveMQClientLogger.LOGGER.invalidProtocol(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
                        throw e;
                    }
                } else {
                    engine.setEnabledProtocols(originalProtocols);
                }
                if (verifyHost) {
                    SSLParameters sslParameters = engine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    engine.setSSLParameters(sslParameters);
                }
                SslHandler handler = new SslHandler(engine);
                pipeline.addLast("ssl", handler);
            }
            if (httpEnabled) {
                pipeline.addLast(new HttpRequestEncoder());
                pipeline.addLast(new HttpResponseDecoder());
                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                pipeline.addLast(new HttpHandler());
            }
            if (httpUpgradeEnabled) {
                // prepare to handle a HTTP 101 response to upgrade the protocol.
                final HttpClientCodec httpClientCodec = new HttpClientCodec();
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
            }
            protocolManager.addChannelHandlers(pipeline);
            pipeline.addLast(new ActiveMQClientChannelHandler(channelGroup, handler, new Listener()));
        }
    });
    if (batchDelay > 0) {
        flusher = new BatchFlusher();
        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS);
    }
    ActiveMQClientLogger.LOGGER.startedNettyConnector(connectorType, TransportConstants.NETTY_VERSION, host, port);
}
Also used : AttributeKey(io.netty.util.AttributeKey) SSLContext(javax.net.ssl.SSLContext) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) HttpObject(io.netty.handler.codec.http.HttpObject) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) Base64(io.netty.handler.codec.base64.Base64) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InetAddress(java.net.InetAddress) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ActiveMQClientProtocolManager(org.apache.activemq.artemis.core.protocol.core.impl.ActiveMQClientProtocolManager) ActiveMQComponent(org.apache.activemq.artemis.core.server.ActiveMQComponent) ActiveMQClientLogger(org.apache.activemq.artemis.core.client.ActiveMQClientLogger) ClientProtocolManager(org.apache.activemq.artemis.spi.core.remoting.ClientProtocolManager) Map(java.util.Map) Level(io.netty.util.ResourceLeakDetector.Level) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelPipeline(io.netty.channel.ChannelPipeline) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Cookie(io.netty.handler.codec.http.cookie.Cookie) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) SslHandler(io.netty.handler.ssl.SslHandler) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) ActiveMQClientMessageBundle(org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle) ActiveMQDefaultConfiguration(org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration) ChannelOption(io.netty.channel.ChannelOption) SSLParameters(javax.net.ssl.SSLParameters) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) ConfigurationHelper(org.apache.activemq.artemis.utils.ConfigurationHelper) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ConnectException(java.net.ConnectException) BufferHandler(org.apache.activemq.artemis.spi.core.remoting.BufferHandler) SslContext(io.netty.handler.ssl.SslContext) Executor(java.util.concurrent.Executor) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Future(io.netty.util.concurrent.Future) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ScheduledFuture(java.util.concurrent.ScheduledFuture) SocketAddress(java.net.SocketAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) FutureLatch(org.apache.activemq.artemis.utils.FutureLatch) SSLSupport(org.apache.activemq.artemis.core.remoting.impl.ssl.SSLSupport) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) ChannelPromise(io.netty.channel.ChannelPromise) URI(java.net.URI) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelGroup(io.netty.channel.group.ChannelGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ResourceLeakDetector(io.netty.util.ResourceLeakDetector) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Objects(java.util.Objects) AbstractConnector(org.apache.activemq.artemis.spi.core.remoting.AbstractConnector) List(java.util.List) HttpResponse(io.netty.handler.codec.http.HttpResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) HttpVersion(io.netty.handler.codec.http.HttpVersion) MessageDigest(java.security.MessageDigest) IPV6Util(org.apache.activemq.artemis.utils.IPV6Util) Logger(org.jboss.logging.Logger) HashMap(java.util.HashMap) Base64.encodeBytes(org.apache.activemq.artemis.utils.Base64.encodeBytes) LoginContext(javax.security.auth.login.LoginContext) ConcurrentMap(java.util.concurrent.ConcurrentMap) SSLEngine(javax.net.ssl.SSLEngine) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Connection(org.apache.activemq.artemis.spi.core.remoting.Connection) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) HttpMethod(io.netty.handler.codec.http.HttpMethod) Subject(javax.security.auth.Subject) ChannelFuture(io.netty.channel.ChannelFuture) Epoll(io.netty.channel.epoll.Epoll) TimeUnit(java.util.concurrent.TimeUnit) Inet6Address(java.net.Inet6Address) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) KQueue(io.netty.channel.kqueue.KQueue) Collections(java.util.Collections) ClientCookieDecoder(io.netty.handler.codec.http.cookie.ClientCookieDecoder) BaseConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.BaseConnectionLifeCycleListener) ClientConnectionLifeCycleListener(org.apache.activemq.artemis.spi.core.remoting.ClientConnectionLifeCycleListener) SSLEngine(javax.net.ssl.SSLEngine) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) SSLParameters(javax.net.ssl.SSLParameters) Bootstrap(io.netty.bootstrap.Bootstrap) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) KQueueSocketChannel(io.netty.channel.kqueue.KQueueSocketChannel) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) URISyntaxException(java.net.URISyntaxException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder)

Example 45 with ChannelPipeline

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelPipeline in project activemq-artemis by apache.

the class NettyAcceptor method start.

@Override
public synchronized void start() throws Exception {
    if (channelClazz != null) {
        // Already started
        return;
    }
    String acceptorType;
    if (useInvm) {
        acceptorType = INVM_ACCEPTOR_TYPE;
        channelClazz = LocalServerChannel.class;
        eventLoopGroup = new DefaultEventLoopGroup();
    } else {
        if (remotingThreads == -1) {
            // Default to number of cores * 3
            remotingThreads = Runtime.getRuntime().availableProcessors() * 3;
        }
        if (useEpoll && Epoll.isAvailable()) {
            channelClazz = EpollServerSocketChannel.class;
            eventLoopGroup = new EpollEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {

                @Override
                public ActiveMQThreadFactory run() {
                    return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
                }
            }));
            acceptorType = EPOLL_ACCEPTOR_TYPE;
            logger.debug("Acceptor using native epoll");
        } else if (useKQueue && KQueue.isAvailable()) {
            channelClazz = KQueueServerSocketChannel.class;
            eventLoopGroup = new KQueueEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {

                @Override
                public ActiveMQThreadFactory run() {
                    return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
                }
            }));
            acceptorType = KQUEUE_ACCEPTOR_TYPE;
            logger.debug("Acceptor using native kqueue");
        } else {
            channelClazz = NioServerSocketChannel.class;
            eventLoopGroup = new NioEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {

                @Override
                public ActiveMQThreadFactory run() {
                    return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
                }
            }));
            acceptorType = NIO_ACCEPTOR_TYPE;
            logger.debug("Acceptor using nio");
        }
    }
    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {

        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
                pipeline.addLast("ssl", getSslHandler(channel.alloc()));
                pipeline.addLast("sslHandshakeExceptionHandler", new SslHandshakeExceptionHandler());
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);
    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    final int writeBufferLowWaterMark = this.writeBufferLowWaterMark != -1 ? this.writeBufferLowWaterMark : WriteBufferWaterMark.DEFAULT.low();
    final int writeBufferHighWaterMark = this.writeBufferHighWaterMark != -1 ? this.writeBufferHighWaterMark : WriteBufferWaterMark.DEFAULT.high();
    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(writeBufferLowWaterMark, writeBufferHighWaterMark);
    bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
    if (backlog != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);
    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);
    if (httpUpgradeEnabled) {
    // the channel will be bound by the Web container and hand over after the HTTP Upgrade
    // handshake is successful
    } else {
        startServerChannels();
        paused = false;
        if (notificationService != null) {
            TypedProperties props = new TypedProperties();
            props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName()));
            props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
            props.putIntProperty(new SimpleString("port"), port);
            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
            notificationService.sendNotification(notification);
        }
        ActiveMQServerLogger.LOGGER.startedAcceptor(acceptorType, host, port, protocolsString);
    }
    if (batchDelay > 0) {
        flusher = new BatchFlusher();
        batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS);
    }
}
Also used : ActiveMQThreadFactory(org.apache.activemq.artemis.utils.ActiveMQThreadFactory) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Notification(org.apache.activemq.artemis.core.server.management.Notification) ClientSessionFactoryImpl(org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl) PrivilegedAction(java.security.PrivilegedAction) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) KQueueServerSocketChannel(io.netty.channel.kqueue.KQueueServerSocketChannel) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) KQueueServerSocketChannel(io.netty.channel.kqueue.KQueueServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) Channel(io.netty.channel.Channel) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) TypedProperties(org.apache.activemq.artemis.utils.collections.TypedProperties) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) KQueueEventLoopGroup(io.netty.channel.kqueue.KQueueEventLoopGroup)

Aggregations

ChannelPipeline (io.netty.channel.ChannelPipeline)370 SocketChannel (io.netty.channel.socket.SocketChannel)107 Channel (io.netty.channel.Channel)90 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)90 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)80 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)78 Bootstrap (io.netty.bootstrap.Bootstrap)77 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)69 ChannelFuture (io.netty.channel.ChannelFuture)68 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)62 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)62 EventLoopGroup (io.netty.channel.EventLoopGroup)54 SslHandler (io.netty.handler.ssl.SslHandler)52 InetSocketAddress (java.net.InetSocketAddress)49 HttpServerCodec (io.netty.handler.codec.http.HttpServerCodec)43 LoggingHandler (io.netty.handler.logging.LoggingHandler)37 IOException (java.io.IOException)37 StringDecoder (io.netty.handler.codec.string.StringDecoder)36 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)36 StringEncoder (io.netty.handler.codec.string.StringEncoder)33