Search in sources :

Example 86 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project herddb by diennea.

the class NettyChannelAcceptor method start.

public void start() throws Exception {
    if (ssl) {
        if (sslCertFile == null) {
            LOGGER.log(Level.INFO, "start SSL with self-signed auto-generated certificate");
            if (sslCiphers != null) {
                LOGGER.log(Level.INFO, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers).build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.INFO, "start SSL with certificate " + sslCertFile.getAbsolutePath() + " chain file " + sslCertChainFile.getAbsolutePath());
            if (sslCiphers != null) {
                LOGGER.log(Level.INFO, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword).ciphers(sslCiphers).build();
        }
    }
    if (callbackThreads == 0) {
        callbackExecutorQueue = new SynchronousQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, callbackExecutorQueue, threadFactory);
    } else {
        callbackExecutorQueue = new LinkedBlockingQueue<Runnable>();
        callbackExecutor = new ThreadPoolExecutor(callbackThreads, callbackThreads, 0L, TimeUnit.MILLISECONDS, callbackExecutorQueue, threadFactory);
    }
    statsLogger.registerGauge("callbacksqueue", new Gauge<Integer>() {

        @Override
        public Integer getDefaultValue() {
            return 0;
        }

        @Override
        public Integer getSample() {
            return callbackExecutorQueue.size();
        }
    });
    InetSocketAddress address = new InetSocketAddress(host, port);
    if (enableRealNetwork) {
        LOGGER.log(Level.INFO, "Starting HerdDB network server at {0}:{1}", new Object[] { host, port + "" });
    }
    if (enableRealNetwork && address.isUnresolved()) {
        throw new IOException("Bind address " + host + ":" + port + " cannot be resolved");
    }
    ChannelInitializer<io.netty.channel.Channel> channelInitialized = new ChannelInitializer<io.netty.channel.Channel>() {

        @Override
        public void initChannel(io.netty.channel.Channel ch) throws Exception {
            NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor);
            if (acceptor != null) {
                acceptor.createConnection(session);
            }
            // Add SSL handler first to encrypt and decrypt everything.
            if (ssl) {
                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
            ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            // 
            ch.pipeline().addLast("messagedecoder", new ProtocolMessageDecoder());
            ch.pipeline().addLast(new ServerInboundMessageHandler(session));
        }
    };
    if (enableRealNetwork) {
        if (NetworkUtils.isEnableEpoolNative()) {
            bossGroup = new EpollEventLoopGroup(workerThreads);
            workerGroup = new EpollEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using netty-native-epoll network type");
        } else {
            bossGroup = new NioEventLoopGroup(workerThreads);
            workerGroup = new NioEventLoopGroup(workerThreads);
            LOGGER.log(Level.FINE, "Using nio network type");
        }
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NetworkUtils.isEnableEpoolNative() ? EpollServerSocketChannel.class : NioServerSocketChannel.class).childHandler(channelInitialized).option(ChannelOption.SO_BACKLOG, 128);
        ChannelFuture f = b.bind(address).sync();
        this.channel = f.channel();
    }
    if (enableJVMNetwork) {
        jvmhostAddress = NetworkUtils.getAddress(address);
        LocalServerRegistry.registerLocalServer(jvmhostAddress, port, localVMChannelAcceptor);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ChannelInitializer(io.netty.channel.ChannelInitializer) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 87 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project reactor-netty by reactor.

the class TransportConnector method connect.

/**
 * Connect a {@link Channel} to the remote peer.
 *
 * @param config the transport configuration
 * @param remoteAddress the {@link SocketAddress} to connect to
 * @param resolverGroup the resolver which will resolve the address of the unresolved named address
 * @param channelInitializer the {@link ChannelInitializer} that will be used for initializing the channel pipeline
 * @param eventLoop the {@link EventLoop} to use for handling the channel.
 * @return a {@link Mono} of {@link Channel}
 */
public static Mono<Channel> connect(TransportConfig config, SocketAddress remoteAddress, AddressResolverGroup<?> resolverGroup, ChannelInitializer<Channel> channelInitializer, EventLoop eventLoop) {
    Objects.requireNonNull(config, "config");
    Objects.requireNonNull(remoteAddress, "remoteAddress");
    Objects.requireNonNull(resolverGroup, "resolverGroup");
    Objects.requireNonNull(channelInitializer, "channelInitializer");
    Objects.requireNonNull(eventLoop, "eventLoop");
    boolean isDomainAddress = remoteAddress instanceof DomainSocketAddress;
    return doInitAndRegister(config, channelInitializer, isDomainAddress, eventLoop).flatMap(channel -> doResolveAndConnect(channel, config, remoteAddress, resolverGroup).onErrorResume(RetryConnectException.class, t -> {
        AtomicInteger index = new AtomicInteger(1);
        return Mono.defer(() -> doInitAndRegister(config, channelInitializer, isDomainAddress, eventLoop).flatMap(ch -> {
            MonoChannelPromise mono = new MonoChannelPromise(ch);
            doConnect(t.addresses, config.bindAddress(), mono, index.get());
            return mono;
        })).retryWhen(Retry.max(t.addresses.size() - 1).filter(RETRY_PREDICATE).doBeforeRetry(sig -> index.incrementAndGet()));
    }));
}
Also used : AttributeKey(io.netty.util.AttributeKey) ChannelOption(io.netty.channel.ChannelOption) Retry(reactor.util.retry.Retry) SocketAddress(java.net.SocketAddress) ReactorNetty.format(reactor.netty.ReactorNetty.format) Nullable(reactor.util.annotation.Nullable) Supplier(java.util.function.Supplier) CoreSubscriber(reactor.core.CoreSubscriber) Loggers(reactor.util.Loggers) ChannelPromise(io.netty.channel.ChannelPromise) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Logger(reactor.util.Logger) Map(java.util.Map) ChannelFactory(io.netty.channel.ChannelFactory) Connection(reactor.netty.Connection) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) AddressResolver(io.netty.resolver.AddressResolver) ChannelInitializer(io.netty.channel.ChannelInitializer) FutureListener(io.netty.util.concurrent.FutureListener) AtomicReferenceFieldUpdater(java.util.concurrent.atomic.AtomicReferenceFieldUpdater) Predicate(java.util.function.Predicate) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Mono(reactor.core.publisher.Mono) EventLoop(io.netty.channel.EventLoop) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) List(java.util.List) Subscription(org.reactivestreams.Subscription) Future(io.netty.util.concurrent.Future) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)86 Channel (io.netty.channel.Channel)59 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)30 ChannelPipeline (io.netty.channel.ChannelPipeline)26 EventLoopGroup (io.netty.channel.EventLoopGroup)26 LocalServerChannel (io.netty.channel.local.LocalServerChannel)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 SocketChannel (io.netty.channel.socket.SocketChannel)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 Map (java.util.Map)12 CountDownLatch (java.util.concurrent.CountDownLatch)12